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   setOperationAction(ISD::ADDC,      MVT::i32, Custom);
824   setOperationAction(ISD::ADDE,      MVT::i32, Custom);
825   setOperationAction(ISD::SUBC,      MVT::i32, Custom);
826   setOperationAction(ISD::SUBE,      MVT::i32, Custom);
827 
828   if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops())
829     setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
830 
831   // ARM does not have ROTL.
832   setOperationAction(ISD::ROTL, MVT::i32, Expand);
833   for (MVT VT : MVT::vector_valuetypes()) {
834     setOperationAction(ISD::ROTL, VT, Expand);
835     setOperationAction(ISD::ROTR, VT, Expand);
836   }
837   setOperationAction(ISD::CTTZ,  MVT::i32, Custom);
838   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
839   if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
840     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
841 
842   // @llvm.readcyclecounter requires the Performance Monitors extension.
843   // Default to the 0 expansion on unsupported platforms.
844   // FIXME: Technically there are older ARM CPUs that have
845   // implementation-specific ways of obtaining this information.
846   if (Subtarget->hasPerfMon())
847     setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
848 
849   // Only ARMv6 has BSWAP.
850   if (!Subtarget->hasV6Ops())
851     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
852 
853   bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode()
854                                         : Subtarget->hasDivideInARMMode();
855   if (!hasDivide) {
856     // These are expanded into libcalls if the cpu doesn't have HW divider.
857     setOperationAction(ISD::SDIV,  MVT::i32, LibCall);
858     setOperationAction(ISD::UDIV,  MVT::i32, LibCall);
859   }
860 
861   if (Subtarget->isTargetWindows() && !Subtarget->hasDivideInThumbMode()) {
862     setOperationAction(ISD::SDIV, MVT::i32, Custom);
863     setOperationAction(ISD::UDIV, MVT::i32, Custom);
864 
865     setOperationAction(ISD::SDIV, MVT::i64, Custom);
866     setOperationAction(ISD::UDIV, MVT::i64, Custom);
867   }
868 
869   setOperationAction(ISD::SREM,  MVT::i32, Expand);
870   setOperationAction(ISD::UREM,  MVT::i32, Expand);
871 
872   // Register based DivRem for AEABI (RTABI 4.2)
873   if (Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() ||
874       Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() ||
875       Subtarget->isTargetWindows()) {
876     setOperationAction(ISD::SREM, MVT::i64, Custom);
877     setOperationAction(ISD::UREM, MVT::i64, Custom);
878     HasStandaloneRem = false;
879 
880     if (Subtarget->isTargetWindows()) {
881       const struct {
882         const RTLIB::Libcall Op;
883         const char * const Name;
884         const CallingConv::ID CC;
885       } LibraryCalls[] = {
886         { RTLIB::SDIVREM_I8, "__rt_sdiv", CallingConv::ARM_AAPCS },
887         { RTLIB::SDIVREM_I16, "__rt_sdiv", CallingConv::ARM_AAPCS },
888         { RTLIB::SDIVREM_I32, "__rt_sdiv", CallingConv::ARM_AAPCS },
889         { RTLIB::SDIVREM_I64, "__rt_sdiv64", CallingConv::ARM_AAPCS },
890 
891         { RTLIB::UDIVREM_I8, "__rt_udiv", CallingConv::ARM_AAPCS },
892         { RTLIB::UDIVREM_I16, "__rt_udiv", CallingConv::ARM_AAPCS },
893         { RTLIB::UDIVREM_I32, "__rt_udiv", CallingConv::ARM_AAPCS },
894         { RTLIB::UDIVREM_I64, "__rt_udiv64", CallingConv::ARM_AAPCS },
895       };
896 
897       for (const auto &LC : LibraryCalls) {
898         setLibcallName(LC.Op, LC.Name);
899         setLibcallCallingConv(LC.Op, LC.CC);
900       }
901     } else {
902       const struct {
903         const RTLIB::Libcall Op;
904         const char * const Name;
905         const CallingConv::ID CC;
906       } LibraryCalls[] = {
907         { RTLIB::SDIVREM_I8, "__aeabi_idivmod", CallingConv::ARM_AAPCS },
908         { RTLIB::SDIVREM_I16, "__aeabi_idivmod", CallingConv::ARM_AAPCS },
909         { RTLIB::SDIVREM_I32, "__aeabi_idivmod", CallingConv::ARM_AAPCS },
910         { RTLIB::SDIVREM_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS },
911 
912         { RTLIB::UDIVREM_I8, "__aeabi_uidivmod", CallingConv::ARM_AAPCS },
913         { RTLIB::UDIVREM_I16, "__aeabi_uidivmod", CallingConv::ARM_AAPCS },
914         { RTLIB::UDIVREM_I32, "__aeabi_uidivmod", CallingConv::ARM_AAPCS },
915         { RTLIB::UDIVREM_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS },
916       };
917 
918       for (const auto &LC : LibraryCalls) {
919         setLibcallName(LC.Op, LC.Name);
920         setLibcallCallingConv(LC.Op, LC.CC);
921       }
922     }
923 
924     setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
925     setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
926     setOperationAction(ISD::SDIVREM, MVT::i64, Custom);
927     setOperationAction(ISD::UDIVREM, MVT::i64, Custom);
928   } else {
929     setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
930     setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
931   }
932 
933   if (Subtarget->isTargetWindows() && Subtarget->getTargetTriple().isOSMSVCRT())
934     for (auto &VT : {MVT::f32, MVT::f64})
935       setOperationAction(ISD::FPOWI, VT, Custom);
936 
937   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
938   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
939   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
940   setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
941 
942   setOperationAction(ISD::TRAP, MVT::Other, Legal);
943 
944   // Use the default implementation.
945   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
946   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
947   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
948   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
949   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
950   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
951 
952   if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
953     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
954   else
955     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
956 
957   // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
958   // the default expansion.
959   InsertFencesForAtomic = false;
960   if (Subtarget->hasAnyDataBarrier() &&
961       (!Subtarget->isThumb() || Subtarget->hasV8MBaselineOps())) {
962     // ATOMIC_FENCE needs custom lowering; the others should have been expanded
963     // to ldrex/strex loops already.
964     setOperationAction(ISD::ATOMIC_FENCE,     MVT::Other, Custom);
965     if (!Subtarget->isThumb() || !Subtarget->isMClass())
966       setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i64, Custom);
967 
968     // On v8, we have particularly efficient implementations of atomic fences
969     // if they can be combined with nearby atomic loads and stores.
970     if (!Subtarget->hasV8Ops() || getTargetMachine().getOptLevel() == 0) {
971       // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc.
972       InsertFencesForAtomic = true;
973     }
974   } else {
975     // If there's anything we can use as a barrier, go through custom lowering
976     // for ATOMIC_FENCE.
977     // If target has DMB in thumb, Fences can be inserted.
978     if (Subtarget->hasDataBarrier())
979       InsertFencesForAtomic = true;
980 
981     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other,
982                        Subtarget->hasAnyDataBarrier() ? Custom : Expand);
983 
984     // Set them all for expansion, which will force libcalls.
985     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Expand);
986     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Expand);
987     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Expand);
988     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Expand);
989     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Expand);
990     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Expand);
991     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Expand);
992     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
993     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
994     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
995     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
996     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
997     // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
998     // Unordered/Monotonic case.
999     if (!InsertFencesForAtomic) {
1000       setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
1001       setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
1002     }
1003   }
1004 
1005   setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
1006 
1007   // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
1008   if (!Subtarget->hasV6Ops()) {
1009     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
1010     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
1011   }
1012   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
1013 
1014   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
1015       !Subtarget->isThumb1Only()) {
1016     // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
1017     // iff target supports vfp2.
1018     setOperationAction(ISD::BITCAST, MVT::i64, Custom);
1019     setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
1020   }
1021 
1022   // We want to custom lower some of our intrinsics.
1023   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1024   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
1025   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
1026   setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom);
1027   if (Subtarget->useSjLjEH())
1028     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
1029 
1030   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
1031   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
1032   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
1033   setOperationAction(ISD::SELECT,    MVT::i32, Custom);
1034   setOperationAction(ISD::SELECT,    MVT::f32, Custom);
1035   setOperationAction(ISD::SELECT,    MVT::f64, Custom);
1036   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
1037   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
1038   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
1039 
1040   // Thumb-1 cannot currently select ARMISD::SUBE.
1041   if (!Subtarget->isThumb1Only())
1042     setOperationAction(ISD::SETCCE, MVT::i32, Custom);
1043 
1044   setOperationAction(ISD::BRCOND,    MVT::Other, Custom);
1045   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
1046   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
1047   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
1048   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
1049 
1050   // We don't support sin/cos/fmod/copysign/pow
1051   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
1052   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
1053   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
1054   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
1055   setOperationAction(ISD::FSINCOS,   MVT::f64, Expand);
1056   setOperationAction(ISD::FSINCOS,   MVT::f32, Expand);
1057   setOperationAction(ISD::FREM,      MVT::f64, Expand);
1058   setOperationAction(ISD::FREM,      MVT::f32, Expand);
1059   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
1060       !Subtarget->isThumb1Only()) {
1061     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
1062     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
1063   }
1064   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
1065   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
1066 
1067   if (!Subtarget->hasVFP4()) {
1068     setOperationAction(ISD::FMA, MVT::f64, Expand);
1069     setOperationAction(ISD::FMA, MVT::f32, Expand);
1070   }
1071 
1072   // Various VFP goodness
1073   if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) {
1074     // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded.
1075     if (!Subtarget->hasFPARMv8() || Subtarget->isFPOnlySP()) {
1076       setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
1077       setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
1078     }
1079 
1080     // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
1081     if (!Subtarget->hasFP16()) {
1082       setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
1083       setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
1084     }
1085   }
1086 
1087   // Use __sincos_stret if available.
1088   if (getLibcallName(RTLIB::SINCOS_STRET_F32) != nullptr &&
1089       getLibcallName(RTLIB::SINCOS_STRET_F64) != nullptr) {
1090     setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1091     setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1092   }
1093 
1094   // FP-ARMv8 implements a lot of rounding-like FP operations.
1095   if (Subtarget->hasFPARMv8()) {
1096     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
1097     setOperationAction(ISD::FCEIL, MVT::f32, Legal);
1098     setOperationAction(ISD::FROUND, MVT::f32, Legal);
1099     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
1100     setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
1101     setOperationAction(ISD::FRINT, MVT::f32, Legal);
1102     setOperationAction(ISD::FMINNUM, MVT::f32, Legal);
1103     setOperationAction(ISD::FMAXNUM, MVT::f32, Legal);
1104     setOperationAction(ISD::FMINNUM, MVT::v2f32, Legal);
1105     setOperationAction(ISD::FMAXNUM, MVT::v2f32, Legal);
1106     setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
1107     setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
1108 
1109     if (!Subtarget->isFPOnlySP()) {
1110       setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
1111       setOperationAction(ISD::FCEIL, MVT::f64, Legal);
1112       setOperationAction(ISD::FROUND, MVT::f64, Legal);
1113       setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
1114       setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
1115       setOperationAction(ISD::FRINT, MVT::f64, Legal);
1116       setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
1117       setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
1118     }
1119   }
1120 
1121   if (Subtarget->hasNEON()) {
1122     // vmin and vmax aren't available in a scalar form, so we use
1123     // a NEON instruction with an undef lane instead.
1124     setOperationAction(ISD::FMINNAN, MVT::f32, Legal);
1125     setOperationAction(ISD::FMAXNAN, MVT::f32, Legal);
1126     setOperationAction(ISD::FMINNAN, MVT::v2f32, Legal);
1127     setOperationAction(ISD::FMAXNAN, MVT::v2f32, Legal);
1128     setOperationAction(ISD::FMINNAN, MVT::v4f32, Legal);
1129     setOperationAction(ISD::FMAXNAN, MVT::v4f32, Legal);
1130   }
1131 
1132   // We have target-specific dag combine patterns for the following nodes:
1133   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
1134   setTargetDAGCombine(ISD::ADD);
1135   setTargetDAGCombine(ISD::SUB);
1136   setTargetDAGCombine(ISD::MUL);
1137   setTargetDAGCombine(ISD::AND);
1138   setTargetDAGCombine(ISD::OR);
1139   setTargetDAGCombine(ISD::XOR);
1140 
1141   if (Subtarget->hasV6Ops())
1142     setTargetDAGCombine(ISD::SRL);
1143 
1144   setStackPointerRegisterToSaveRestore(ARM::SP);
1145 
1146   if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() ||
1147       !Subtarget->hasVFP2())
1148     setSchedulingPreference(Sched::RegPressure);
1149   else
1150     setSchedulingPreference(Sched::Hybrid);
1151 
1152   //// temporary - rewrite interface to use type
1153   MaxStoresPerMemset = 8;
1154   MaxStoresPerMemsetOptSize = 4;
1155   MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
1156   MaxStoresPerMemcpyOptSize = 2;
1157   MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
1158   MaxStoresPerMemmoveOptSize = 2;
1159 
1160   // On ARM arguments smaller than 4 bytes are extended, so all arguments
1161   // are at least 4 bytes aligned.
1162   setMinStackArgumentAlignment(4);
1163 
1164   // Prefer likely predicted branches to selects on out-of-order cores.
1165   PredictableSelectIsExpensive = Subtarget->getSchedModel().isOutOfOrder();
1166 
1167   setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
1168 }
1169 
1170 bool ARMTargetLowering::useSoftFloat() const {
1171   return Subtarget->useSoftFloat();
1172 }
1173 
1174 // FIXME: It might make sense to define the representative register class as the
1175 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
1176 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
1177 // SPR's representative would be DPR_VFP2. This should work well if register
1178 // pressure tracking were modified such that a register use would increment the
1179 // pressure of the register class's representative and all of it's super
1180 // classes' representatives transitively. We have not implemented this because
1181 // of the difficulty prior to coalescing of modeling operand register classes
1182 // due to the common occurrence of cross class copies and subregister insertions
1183 // and extractions.
1184 std::pair<const TargetRegisterClass *, uint8_t>
1185 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1186                                            MVT VT) const {
1187   const TargetRegisterClass *RRC = nullptr;
1188   uint8_t Cost = 1;
1189   switch (VT.SimpleTy) {
1190   default:
1191     return TargetLowering::findRepresentativeClass(TRI, VT);
1192   // Use DPR as representative register class for all floating point
1193   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
1194   // the cost is 1 for both f32 and f64.
1195   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
1196   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
1197     RRC = &ARM::DPRRegClass;
1198     // When NEON is used for SP, only half of the register file is available
1199     // because operations that define both SP and DP results will be constrained
1200     // to the VFP2 class (D0-D15). We currently model this constraint prior to
1201     // coalescing by double-counting the SP regs. See the FIXME above.
1202     if (Subtarget->useNEONForSinglePrecisionFP())
1203       Cost = 2;
1204     break;
1205   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1206   case MVT::v4f32: case MVT::v2f64:
1207     RRC = &ARM::DPRRegClass;
1208     Cost = 2;
1209     break;
1210   case MVT::v4i64:
1211     RRC = &ARM::DPRRegClass;
1212     Cost = 4;
1213     break;
1214   case MVT::v8i64:
1215     RRC = &ARM::DPRRegClass;
1216     Cost = 8;
1217     break;
1218   }
1219   return std::make_pair(RRC, Cost);
1220 }
1221 
1222 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1223   switch ((ARMISD::NodeType)Opcode) {
1224   case ARMISD::FIRST_NUMBER:  break;
1225   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
1226   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
1227   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
1228   case ARMISD::COPY_STRUCT_BYVAL: return "ARMISD::COPY_STRUCT_BYVAL";
1229   case ARMISD::CALL:          return "ARMISD::CALL";
1230   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
1231   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
1232   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
1233   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
1234   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
1235   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
1236   case ARMISD::INTRET_FLAG:   return "ARMISD::INTRET_FLAG";
1237   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
1238   case ARMISD::CMP:           return "ARMISD::CMP";
1239   case ARMISD::CMN:           return "ARMISD::CMN";
1240   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
1241   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
1242   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
1243   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
1244   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
1245 
1246   case ARMISD::CMOV:          return "ARMISD::CMOV";
1247 
1248   case ARMISD::SSAT:          return "ARMISD::SSAT";
1249   case ARMISD::USAT:          return "ARMISD::USAT";
1250 
1251   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
1252   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
1253   case ARMISD::RRX:           return "ARMISD::RRX";
1254 
1255   case ARMISD::ADDC:          return "ARMISD::ADDC";
1256   case ARMISD::ADDE:          return "ARMISD::ADDE";
1257   case ARMISD::SUBC:          return "ARMISD::SUBC";
1258   case ARMISD::SUBE:          return "ARMISD::SUBE";
1259 
1260   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
1261   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
1262 
1263   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1264   case ARMISD::EH_SJLJ_LONGJMP: return "ARMISD::EH_SJLJ_LONGJMP";
1265   case ARMISD::EH_SJLJ_SETUP_DISPATCH: return "ARMISD::EH_SJLJ_SETUP_DISPATCH";
1266 
1267   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
1268 
1269   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1270 
1271   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
1272 
1273   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1274 
1275   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
1276 
1277   case ARMISD::WIN__CHKSTK:   return "ARMISD::WIN__CHKSTK";
1278   case ARMISD::WIN__DBZCHK:   return "ARMISD::WIN__DBZCHK";
1279 
1280   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
1281   case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
1282   case ARMISD::VCGE:          return "ARMISD::VCGE";
1283   case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
1284   case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
1285   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
1286   case ARMISD::VCGT:          return "ARMISD::VCGT";
1287   case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
1288   case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
1289   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
1290   case ARMISD::VTST:          return "ARMISD::VTST";
1291 
1292   case ARMISD::VSHL:          return "ARMISD::VSHL";
1293   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
1294   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
1295   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
1296   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
1297   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
1298   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
1299   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
1300   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
1301   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
1302   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
1303   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
1304   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
1305   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
1306   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
1307   case ARMISD::VSLI:          return "ARMISD::VSLI";
1308   case ARMISD::VSRI:          return "ARMISD::VSRI";
1309   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
1310   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
1311   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
1312   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
1313   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
1314   case ARMISD::VDUP:          return "ARMISD::VDUP";
1315   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
1316   case ARMISD::VEXT:          return "ARMISD::VEXT";
1317   case ARMISD::VREV64:        return "ARMISD::VREV64";
1318   case ARMISD::VREV32:        return "ARMISD::VREV32";
1319   case ARMISD::VREV16:        return "ARMISD::VREV16";
1320   case ARMISD::VZIP:          return "ARMISD::VZIP";
1321   case ARMISD::VUZP:          return "ARMISD::VUZP";
1322   case ARMISD::VTRN:          return "ARMISD::VTRN";
1323   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
1324   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
1325   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
1326   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
1327   case ARMISD::UMAAL:         return "ARMISD::UMAAL";
1328   case ARMISD::UMLAL:         return "ARMISD::UMLAL";
1329   case ARMISD::SMLAL:         return "ARMISD::SMLAL";
1330   case ARMISD::SMLALBB:       return "ARMISD::SMLALBB";
1331   case ARMISD::SMLALBT:       return "ARMISD::SMLALBT";
1332   case ARMISD::SMLALTB:       return "ARMISD::SMLALTB";
1333   case ARMISD::SMLALTT:       return "ARMISD::SMLALTT";
1334   case ARMISD::SMULWB:        return "ARMISD::SMULWB";
1335   case ARMISD::SMULWT:        return "ARMISD::SMULWT";
1336   case ARMISD::SMLALD:        return "ARMISD::SMLALD";
1337   case ARMISD::SMLALDX:       return "ARMISD::SMLALDX";
1338   case ARMISD::SMLSLD:        return "ARMISD::SMLSLD";
1339   case ARMISD::SMLSLDX:       return "ARMISD::SMLSLDX";
1340   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
1341   case ARMISD::BFI:           return "ARMISD::BFI";
1342   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
1343   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
1344   case ARMISD::VBSL:          return "ARMISD::VBSL";
1345   case ARMISD::MEMCPY:        return "ARMISD::MEMCPY";
1346   case ARMISD::VLD1DUP:       return "ARMISD::VLD1DUP";
1347   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
1348   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
1349   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
1350   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
1351   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
1352   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
1353   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
1354   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
1355   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
1356   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
1357   case ARMISD::VLD1DUP_UPD:   return "ARMISD::VLD1DUP_UPD";
1358   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
1359   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
1360   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
1361   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
1362   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
1363   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
1364   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
1365   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
1366   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
1367   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
1368   }
1369   return nullptr;
1370 }
1371 
1372 EVT ARMTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1373                                           EVT VT) const {
1374   if (!VT.isVector())
1375     return getPointerTy(DL);
1376   return VT.changeVectorElementTypeToInteger();
1377 }
1378 
1379 /// getRegClassFor - Return the register class that should be used for the
1380 /// specified value type.
1381 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1382   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1383   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1384   // load / store 4 to 8 consecutive D registers.
1385   if (Subtarget->hasNEON()) {
1386     if (VT == MVT::v4i64)
1387       return &ARM::QQPRRegClass;
1388     if (VT == MVT::v8i64)
1389       return &ARM::QQQQPRRegClass;
1390   }
1391   return TargetLowering::getRegClassFor(VT);
1392 }
1393 
1394 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the
1395 // source/dest is aligned and the copy size is large enough. We therefore want
1396 // to align such objects passed to memory intrinsics.
1397 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize,
1398                                                unsigned &PrefAlign) const {
1399   if (!isa<MemIntrinsic>(CI))
1400     return false;
1401   MinSize = 8;
1402   // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1
1403   // cycle faster than 4-byte aligned LDM.
1404   PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4);
1405   return true;
1406 }
1407 
1408 // Create a fast isel object.
1409 FastISel *
1410 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1411                                   const TargetLibraryInfo *libInfo) const {
1412   return ARM::createFastISel(funcInfo, libInfo);
1413 }
1414 
1415 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1416   unsigned NumVals = N->getNumValues();
1417   if (!NumVals)
1418     return Sched::RegPressure;
1419 
1420   for (unsigned i = 0; i != NumVals; ++i) {
1421     EVT VT = N->getValueType(i);
1422     if (VT == MVT::Glue || VT == MVT::Other)
1423       continue;
1424     if (VT.isFloatingPoint() || VT.isVector())
1425       return Sched::ILP;
1426   }
1427 
1428   if (!N->isMachineOpcode())
1429     return Sched::RegPressure;
1430 
1431   // Load are scheduled for latency even if there instruction itinerary
1432   // is not available.
1433   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1434   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1435 
1436   if (MCID.getNumDefs() == 0)
1437     return Sched::RegPressure;
1438   if (!Itins->isEmpty() &&
1439       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1440     return Sched::ILP;
1441 
1442   return Sched::RegPressure;
1443 }
1444 
1445 //===----------------------------------------------------------------------===//
1446 // Lowering Code
1447 //===----------------------------------------------------------------------===//
1448 
1449 static bool isSRL16(const SDValue &Op) {
1450   if (Op.getOpcode() != ISD::SRL)
1451     return false;
1452   if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1453     return Const->getZExtValue() == 16;
1454   return false;
1455 }
1456 
1457 static bool isSRA16(const SDValue &Op) {
1458   if (Op.getOpcode() != ISD::SRA)
1459     return false;
1460   if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1461     return Const->getZExtValue() == 16;
1462   return false;
1463 }
1464 
1465 static bool isSHL16(const SDValue &Op) {
1466   if (Op.getOpcode() != ISD::SHL)
1467     return false;
1468   if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1469     return Const->getZExtValue() == 16;
1470   return false;
1471 }
1472 
1473 // Check for a signed 16-bit value. We special case SRA because it makes it
1474 // more simple when also looking for SRAs that aren't sign extending a
1475 // smaller value. Without the check, we'd need to take extra care with
1476 // checking order for some operations.
1477 static bool isS16(const SDValue &Op, SelectionDAG &DAG) {
1478   if (isSRA16(Op))
1479     return isSHL16(Op.getOperand(0));
1480   return DAG.ComputeNumSignBits(Op) == 17;
1481 }
1482 
1483 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1484 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1485   switch (CC) {
1486   default: llvm_unreachable("Unknown condition code!");
1487   case ISD::SETNE:  return ARMCC::NE;
1488   case ISD::SETEQ:  return ARMCC::EQ;
1489   case ISD::SETGT:  return ARMCC::GT;
1490   case ISD::SETGE:  return ARMCC::GE;
1491   case ISD::SETLT:  return ARMCC::LT;
1492   case ISD::SETLE:  return ARMCC::LE;
1493   case ISD::SETUGT: return ARMCC::HI;
1494   case ISD::SETUGE: return ARMCC::HS;
1495   case ISD::SETULT: return ARMCC::LO;
1496   case ISD::SETULE: return ARMCC::LS;
1497   }
1498 }
1499 
1500 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1501 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1502                         ARMCC::CondCodes &CondCode2, bool &InvalidOnQNaN) {
1503   CondCode2 = ARMCC::AL;
1504   InvalidOnQNaN = true;
1505   switch (CC) {
1506   default: llvm_unreachable("Unknown FP condition!");
1507   case ISD::SETEQ:
1508   case ISD::SETOEQ:
1509     CondCode = ARMCC::EQ;
1510     InvalidOnQNaN = false;
1511     break;
1512   case ISD::SETGT:
1513   case ISD::SETOGT: CondCode = ARMCC::GT; break;
1514   case ISD::SETGE:
1515   case ISD::SETOGE: CondCode = ARMCC::GE; break;
1516   case ISD::SETOLT: CondCode = ARMCC::MI; break;
1517   case ISD::SETOLE: CondCode = ARMCC::LS; break;
1518   case ISD::SETONE:
1519     CondCode = ARMCC::MI;
1520     CondCode2 = ARMCC::GT;
1521     InvalidOnQNaN = false;
1522     break;
1523   case ISD::SETO:   CondCode = ARMCC::VC; break;
1524   case ISD::SETUO:  CondCode = ARMCC::VS; break;
1525   case ISD::SETUEQ:
1526     CondCode = ARMCC::EQ;
1527     CondCode2 = ARMCC::VS;
1528     InvalidOnQNaN = false;
1529     break;
1530   case ISD::SETUGT: CondCode = ARMCC::HI; break;
1531   case ISD::SETUGE: CondCode = ARMCC::PL; break;
1532   case ISD::SETLT:
1533   case ISD::SETULT: CondCode = ARMCC::LT; break;
1534   case ISD::SETLE:
1535   case ISD::SETULE: CondCode = ARMCC::LE; break;
1536   case ISD::SETNE:
1537   case ISD::SETUNE:
1538     CondCode = ARMCC::NE;
1539     InvalidOnQNaN = false;
1540     break;
1541   }
1542 }
1543 
1544 //===----------------------------------------------------------------------===//
1545 //                      Calling Convention Implementation
1546 //===----------------------------------------------------------------------===//
1547 
1548 #include "ARMGenCallingConv.inc"
1549 
1550 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1551 /// account presence of floating point hardware and calling convention
1552 /// limitations, such as support for variadic functions.
1553 CallingConv::ID
1554 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1555                                            bool isVarArg) const {
1556   switch (CC) {
1557   default:
1558     report_fatal_error("Unsupported calling convention");
1559   case CallingConv::ARM_AAPCS:
1560   case CallingConv::ARM_APCS:
1561   case CallingConv::GHC:
1562     return CC;
1563   case CallingConv::PreserveMost:
1564     return CallingConv::PreserveMost;
1565   case CallingConv::ARM_AAPCS_VFP:
1566   case CallingConv::Swift:
1567     return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1568   case CallingConv::C:
1569     if (!Subtarget->isAAPCS_ABI())
1570       return CallingConv::ARM_APCS;
1571     else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() &&
1572              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1573              !isVarArg)
1574       return CallingConv::ARM_AAPCS_VFP;
1575     else
1576       return CallingConv::ARM_AAPCS;
1577   case CallingConv::Fast:
1578   case CallingConv::CXX_FAST_TLS:
1579     if (!Subtarget->isAAPCS_ABI()) {
1580       if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1581         return CallingConv::Fast;
1582       return CallingConv::ARM_APCS;
1583     } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1584       return CallingConv::ARM_AAPCS_VFP;
1585     else
1586       return CallingConv::ARM_AAPCS;
1587   }
1588 }
1589 
1590 CCAssignFn *ARMTargetLowering::CCAssignFnForCall(CallingConv::ID CC,
1591                                                  bool isVarArg) const {
1592   return CCAssignFnForNode(CC, false, isVarArg);
1593 }
1594 
1595 CCAssignFn *ARMTargetLowering::CCAssignFnForReturn(CallingConv::ID CC,
1596                                                    bool isVarArg) const {
1597   return CCAssignFnForNode(CC, true, isVarArg);
1598 }
1599 
1600 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1601 /// CallingConvention.
1602 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1603                                                  bool Return,
1604                                                  bool isVarArg) const {
1605   switch (getEffectiveCallingConv(CC, isVarArg)) {
1606   default:
1607     report_fatal_error("Unsupported calling convention");
1608   case CallingConv::ARM_APCS:
1609     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1610   case CallingConv::ARM_AAPCS:
1611     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1612   case CallingConv::ARM_AAPCS_VFP:
1613     return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1614   case CallingConv::Fast:
1615     return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1616   case CallingConv::GHC:
1617     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1618   case CallingConv::PreserveMost:
1619     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1620   }
1621 }
1622 
1623 /// LowerCallResult - Lower the result values of a call into the
1624 /// appropriate copies out of appropriate physical registers.
1625 SDValue ARMTargetLowering::LowerCallResult(
1626     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
1627     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
1628     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
1629     SDValue ThisVal) const {
1630   // Assign locations to each value returned by this call.
1631   SmallVector<CCValAssign, 16> RVLocs;
1632   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1633                  *DAG.getContext());
1634   CCInfo.AnalyzeCallResult(Ins, CCAssignFnForReturn(CallConv, isVarArg));
1635 
1636   // Copy all of the result registers out of their specified physreg.
1637   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1638     CCValAssign VA = RVLocs[i];
1639 
1640     // Pass 'this' value directly from the argument to return value, to avoid
1641     // reg unit interference
1642     if (i == 0 && isThisReturn) {
1643       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1644              "unexpected return calling convention register assignment");
1645       InVals.push_back(ThisVal);
1646       continue;
1647     }
1648 
1649     SDValue Val;
1650     if (VA.needsCustom()) {
1651       // Handle f64 or half of a v2f64.
1652       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1653                                       InFlag);
1654       Chain = Lo.getValue(1);
1655       InFlag = Lo.getValue(2);
1656       VA = RVLocs[++i]; // skip ahead to next loc
1657       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1658                                       InFlag);
1659       Chain = Hi.getValue(1);
1660       InFlag = Hi.getValue(2);
1661       if (!Subtarget->isLittle())
1662         std::swap (Lo, Hi);
1663       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1664 
1665       if (VA.getLocVT() == MVT::v2f64) {
1666         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1667         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1668                           DAG.getConstant(0, dl, MVT::i32));
1669 
1670         VA = RVLocs[++i]; // skip ahead to next loc
1671         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1672         Chain = Lo.getValue(1);
1673         InFlag = Lo.getValue(2);
1674         VA = RVLocs[++i]; // skip ahead to next loc
1675         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1676         Chain = Hi.getValue(1);
1677         InFlag = Hi.getValue(2);
1678         if (!Subtarget->isLittle())
1679           std::swap (Lo, Hi);
1680         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1681         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1682                           DAG.getConstant(1, dl, MVT::i32));
1683       }
1684     } else {
1685       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1686                                InFlag);
1687       Chain = Val.getValue(1);
1688       InFlag = Val.getValue(2);
1689     }
1690 
1691     switch (VA.getLocInfo()) {
1692     default: llvm_unreachable("Unknown loc info!");
1693     case CCValAssign::Full: break;
1694     case CCValAssign::BCvt:
1695       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1696       break;
1697     }
1698 
1699     InVals.push_back(Val);
1700   }
1701 
1702   return Chain;
1703 }
1704 
1705 /// LowerMemOpCallTo - Store the argument to the stack.
1706 SDValue ARMTargetLowering::LowerMemOpCallTo(SDValue Chain, SDValue StackPtr,
1707                                             SDValue Arg, const SDLoc &dl,
1708                                             SelectionDAG &DAG,
1709                                             const CCValAssign &VA,
1710                                             ISD::ArgFlagsTy Flags) const {
1711   unsigned LocMemOffset = VA.getLocMemOffset();
1712   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1713   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
1714                        StackPtr, PtrOff);
1715   return DAG.getStore(
1716       Chain, dl, Arg, PtrOff,
1717       MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset));
1718 }
1719 
1720 void ARMTargetLowering::PassF64ArgInRegs(const SDLoc &dl, SelectionDAG &DAG,
1721                                          SDValue Chain, SDValue &Arg,
1722                                          RegsToPassVector &RegsToPass,
1723                                          CCValAssign &VA, CCValAssign &NextVA,
1724                                          SDValue &StackPtr,
1725                                          SmallVectorImpl<SDValue> &MemOpChains,
1726                                          ISD::ArgFlagsTy Flags) const {
1727   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1728                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
1729   unsigned id = Subtarget->isLittle() ? 0 : 1;
1730   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1731 
1732   if (NextVA.isRegLoc())
1733     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1734   else {
1735     assert(NextVA.isMemLoc());
1736     if (!StackPtr.getNode())
1737       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP,
1738                                     getPointerTy(DAG.getDataLayout()));
1739 
1740     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
1741                                            dl, DAG, NextVA,
1742                                            Flags));
1743   }
1744 }
1745 
1746 /// LowerCall - Lowering a call into a callseq_start <-
1747 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1748 /// nodes.
1749 SDValue
1750 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1751                              SmallVectorImpl<SDValue> &InVals) const {
1752   SelectionDAG &DAG                     = CLI.DAG;
1753   SDLoc &dl                             = CLI.DL;
1754   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1755   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
1756   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
1757   SDValue Chain                         = CLI.Chain;
1758   SDValue Callee                        = CLI.Callee;
1759   bool &isTailCall                      = CLI.IsTailCall;
1760   CallingConv::ID CallConv              = CLI.CallConv;
1761   bool doesNotRet                       = CLI.DoesNotReturn;
1762   bool isVarArg                         = CLI.IsVarArg;
1763 
1764   MachineFunction &MF = DAG.getMachineFunction();
1765   bool isStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1766   bool isThisReturn   = false;
1767   bool isSibCall      = false;
1768   auto Attr = MF.getFunction().getFnAttribute("disable-tail-calls");
1769 
1770   // Disable tail calls if they're not supported.
1771   if (!Subtarget->supportsTailCall() || Attr.getValueAsString() == "true")
1772     isTailCall = false;
1773 
1774   if (isTailCall) {
1775     // Check if it's really possible to do a tail call.
1776     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1777                     isVarArg, isStructRet, MF.getFunction().hasStructRetAttr(),
1778                                                    Outs, OutVals, Ins, DAG);
1779     if (!isTailCall && CLI.CS && CLI.CS.isMustTailCall())
1780       report_fatal_error("failed to perform tail call elimination on a call "
1781                          "site marked musttail");
1782     // We don't support GuaranteedTailCallOpt for ARM, only automatically
1783     // detected sibcalls.
1784     if (isTailCall) {
1785       ++NumTailCalls;
1786       isSibCall = true;
1787     }
1788   }
1789 
1790   // Analyze operands of the call, assigning locations to each operand.
1791   SmallVector<CCValAssign, 16> ArgLocs;
1792   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1793                  *DAG.getContext());
1794   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CallConv, isVarArg));
1795 
1796   // Get a count of how many bytes are to be pushed on the stack.
1797   unsigned NumBytes = CCInfo.getNextStackOffset();
1798 
1799   // For tail calls, memory operands are available in our caller's stack.
1800   if (isSibCall)
1801     NumBytes = 0;
1802 
1803   // Adjust the stack pointer for the new arguments...
1804   // These operations are automatically eliminated by the prolog/epilog pass
1805   if (!isSibCall)
1806     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
1807 
1808   SDValue StackPtr =
1809       DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout()));
1810 
1811   RegsToPassVector RegsToPass;
1812   SmallVector<SDValue, 8> MemOpChains;
1813 
1814   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1815   // of tail call optimization, arguments are handled later.
1816   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1817        i != e;
1818        ++i, ++realArgIdx) {
1819     CCValAssign &VA = ArgLocs[i];
1820     SDValue Arg = OutVals[realArgIdx];
1821     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1822     bool isByVal = Flags.isByVal();
1823 
1824     // Promote the value if needed.
1825     switch (VA.getLocInfo()) {
1826     default: llvm_unreachable("Unknown loc info!");
1827     case CCValAssign::Full: break;
1828     case CCValAssign::SExt:
1829       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1830       break;
1831     case CCValAssign::ZExt:
1832       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1833       break;
1834     case CCValAssign::AExt:
1835       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1836       break;
1837     case CCValAssign::BCvt:
1838       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1839       break;
1840     }
1841 
1842     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1843     if (VA.needsCustom()) {
1844       if (VA.getLocVT() == MVT::v2f64) {
1845         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1846                                   DAG.getConstant(0, dl, MVT::i32));
1847         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1848                                   DAG.getConstant(1, dl, MVT::i32));
1849 
1850         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1851                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1852 
1853         VA = ArgLocs[++i]; // skip ahead to next loc
1854         if (VA.isRegLoc()) {
1855           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1856                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1857         } else {
1858           assert(VA.isMemLoc());
1859 
1860           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1861                                                  dl, DAG, VA, Flags));
1862         }
1863       } else {
1864         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1865                          StackPtr, MemOpChains, Flags);
1866       }
1867     } else if (VA.isRegLoc()) {
1868       if (realArgIdx == 0 && Flags.isReturned() && !Flags.isSwiftSelf() &&
1869           Outs[0].VT == MVT::i32) {
1870         assert(VA.getLocVT() == MVT::i32 &&
1871                "unexpected calling convention register assignment");
1872         assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1873                "unexpected use of 'returned'");
1874         isThisReturn = true;
1875       }
1876       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1877     } else if (isByVal) {
1878       assert(VA.isMemLoc());
1879       unsigned offset = 0;
1880 
1881       // True if this byval aggregate will be split between registers
1882       // and memory.
1883       unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1884       unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed();
1885 
1886       if (CurByValIdx < ByValArgsCount) {
1887 
1888         unsigned RegBegin, RegEnd;
1889         CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1890 
1891         EVT PtrVT =
1892             DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
1893         unsigned int i, j;
1894         for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1895           SDValue Const = DAG.getConstant(4*i, dl, MVT::i32);
1896           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1897           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1898                                      MachinePointerInfo(),
1899                                      DAG.InferPtrAlignment(AddArg));
1900           MemOpChains.push_back(Load.getValue(1));
1901           RegsToPass.push_back(std::make_pair(j, Load));
1902         }
1903 
1904         // If parameter size outsides register area, "offset" value
1905         // helps us to calculate stack slot for remained part properly.
1906         offset = RegEnd - RegBegin;
1907 
1908         CCInfo.nextInRegsParam();
1909       }
1910 
1911       if (Flags.getByValSize() > 4*offset) {
1912         auto PtrVT = getPointerTy(DAG.getDataLayout());
1913         unsigned LocMemOffset = VA.getLocMemOffset();
1914         SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1915         SDValue Dst = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, StkPtrOff);
1916         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl);
1917         SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, SrcOffset);
1918         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl,
1919                                            MVT::i32);
1920         SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), dl,
1921                                             MVT::i32);
1922 
1923         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1924         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1925         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1926                                           Ops));
1927       }
1928     } else if (!isSibCall) {
1929       assert(VA.isMemLoc());
1930 
1931       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1932                                              dl, DAG, VA, Flags));
1933     }
1934   }
1935 
1936   if (!MemOpChains.empty())
1937     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1938 
1939   // Build a sequence of copy-to-reg nodes chained together with token chain
1940   // and flag operands which copy the outgoing args into the appropriate regs.
1941   SDValue InFlag;
1942   // Tail call byval lowering might overwrite argument registers so in case of
1943   // tail call optimization the copies to registers are lowered later.
1944   if (!isTailCall)
1945     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1946       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1947                                RegsToPass[i].second, InFlag);
1948       InFlag = Chain.getValue(1);
1949     }
1950 
1951   // For tail calls lower the arguments to the 'real' stack slot.
1952   if (isTailCall) {
1953     // Force all the incoming stack arguments to be loaded from the stack
1954     // before any new outgoing arguments are stored to the stack, because the
1955     // outgoing stack slots may alias the incoming argument stack slots, and
1956     // the alias isn't otherwise explicit. This is slightly more conservative
1957     // than necessary, because it means that each store effectively depends
1958     // on every argument instead of just those arguments it would clobber.
1959 
1960     // Do not flag preceding copytoreg stuff together with the following stuff.
1961     InFlag = SDValue();
1962     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1963       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1964                                RegsToPass[i].second, InFlag);
1965       InFlag = Chain.getValue(1);
1966     }
1967     InFlag = SDValue();
1968   }
1969 
1970   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1971   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1972   // node so that legalize doesn't hack it.
1973   bool isDirect = false;
1974 
1975   const TargetMachine &TM = getTargetMachine();
1976   const Module *Mod = MF.getFunction().getParent();
1977   const GlobalValue *GV = nullptr;
1978   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
1979     GV = G->getGlobal();
1980   bool isStub =
1981       !TM.shouldAssumeDSOLocal(*Mod, GV) && Subtarget->isTargetMachO();
1982 
1983   bool isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1984   bool isLocalARMFunc = false;
1985   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1986   auto PtrVt = getPointerTy(DAG.getDataLayout());
1987 
1988   if (Subtarget->genLongCalls()) {
1989     assert((!isPositionIndependent() || Subtarget->isTargetWindows()) &&
1990            "long-calls codegen is not position independent!");
1991     // Handle a global address or an external symbol. If it's not one of
1992     // those, the target's already in a register, so we don't need to do
1993     // anything extra.
1994     if (isa<GlobalAddressSDNode>(Callee)) {
1995       // Create a constant pool entry for the callee address
1996       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1997       ARMConstantPoolValue *CPV =
1998         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1999 
2000       // Get the address of the callee into a register
2001       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
2002       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2003       Callee = DAG.getLoad(
2004           PtrVt, dl, DAG.getEntryNode(), CPAddr,
2005           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2006     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
2007       const char *Sym = S->getSymbol();
2008 
2009       // Create a constant pool entry for the callee address
2010       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2011       ARMConstantPoolValue *CPV =
2012         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
2013                                       ARMPCLabelIndex, 0);
2014       // Get the address of the callee into a register
2015       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
2016       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2017       Callee = DAG.getLoad(
2018           PtrVt, dl, DAG.getEntryNode(), CPAddr,
2019           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2020     }
2021   } else if (isa<GlobalAddressSDNode>(Callee)) {
2022     // If we're optimizing for minimum size and the function is called three or
2023     // more times in this block, we can improve codesize by calling indirectly
2024     // as BLXr has a 16-bit encoding.
2025     auto *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal();
2026     auto *BB = CLI.CS.getParent();
2027     bool PreferIndirect =
2028         Subtarget->isThumb() && MF.getFunction().optForMinSize() &&
2029         count_if(GV->users(), [&BB](const User *U) {
2030           return isa<Instruction>(U) && cast<Instruction>(U)->getParent() == BB;
2031         }) > 2;
2032 
2033     if (!PreferIndirect) {
2034       isDirect = true;
2035       bool isDef = GV->isStrongDefinitionForLinker();
2036 
2037       // ARM call to a local ARM function is predicable.
2038       isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking);
2039       // tBX takes a register source operand.
2040       if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
2041         assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
2042         Callee = DAG.getNode(
2043             ARMISD::WrapperPIC, dl, PtrVt,
2044             DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, ARMII::MO_NONLAZY));
2045         Callee = DAG.getLoad(
2046             PtrVt, dl, DAG.getEntryNode(), Callee,
2047             MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2048             /* Alignment = */ 0, MachineMemOperand::MODereferenceable |
2049                                      MachineMemOperand::MOInvariant);
2050       } else if (Subtarget->isTargetCOFF()) {
2051         assert(Subtarget->isTargetWindows() &&
2052                "Windows is the only supported COFF target");
2053         unsigned TargetFlags = GV->hasDLLImportStorageClass()
2054                                    ? ARMII::MO_DLLIMPORT
2055                                    : ARMII::MO_NO_FLAG;
2056         Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, /*Offset=*/0,
2057                                             TargetFlags);
2058         if (GV->hasDLLImportStorageClass())
2059           Callee =
2060               DAG.getLoad(PtrVt, dl, DAG.getEntryNode(),
2061                           DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee),
2062                           MachinePointerInfo::getGOT(DAG.getMachineFunction()));
2063       } else {
2064         Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, 0);
2065       }
2066     }
2067   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2068     isDirect = true;
2069     // tBX takes a register source operand.
2070     const char *Sym = S->getSymbol();
2071     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
2072       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2073       ARMConstantPoolValue *CPV =
2074         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
2075                                       ARMPCLabelIndex, 4);
2076       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
2077       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2078       Callee = DAG.getLoad(
2079           PtrVt, dl, DAG.getEntryNode(), CPAddr,
2080           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2081       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2082       Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel);
2083     } else {
2084       Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, 0);
2085     }
2086   }
2087 
2088   // FIXME: handle tail calls differently.
2089   unsigned CallOpc;
2090   if (Subtarget->isThumb()) {
2091     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
2092       CallOpc = ARMISD::CALL_NOLINK;
2093     else
2094       CallOpc = ARMISD::CALL;
2095   } else {
2096     if (!isDirect && !Subtarget->hasV5TOps())
2097       CallOpc = ARMISD::CALL_NOLINK;
2098     else if (doesNotRet && isDirect && Subtarget->hasRetAddrStack() &&
2099              // Emit regular call when code size is the priority
2100              !MF.getFunction().optForMinSize())
2101       // "mov lr, pc; b _foo" to avoid confusing the RSP
2102       CallOpc = ARMISD::CALL_NOLINK;
2103     else
2104       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
2105   }
2106 
2107   std::vector<SDValue> Ops;
2108   Ops.push_back(Chain);
2109   Ops.push_back(Callee);
2110 
2111   // Add argument registers to the end of the list so that they are known live
2112   // into the call.
2113   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2114     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2115                                   RegsToPass[i].second.getValueType()));
2116 
2117   // Add a register mask operand representing the call-preserved registers.
2118   if (!isTailCall) {
2119     const uint32_t *Mask;
2120     const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
2121     if (isThisReturn) {
2122       // For 'this' returns, use the R0-preserving mask if applicable
2123       Mask = ARI->getThisReturnPreservedMask(MF, CallConv);
2124       if (!Mask) {
2125         // Set isThisReturn to false if the calling convention is not one that
2126         // allows 'returned' to be modeled in this way, so LowerCallResult does
2127         // not try to pass 'this' straight through
2128         isThisReturn = false;
2129         Mask = ARI->getCallPreservedMask(MF, CallConv);
2130       }
2131     } else
2132       Mask = ARI->getCallPreservedMask(MF, CallConv);
2133 
2134     assert(Mask && "Missing call preserved mask for calling convention");
2135     Ops.push_back(DAG.getRegisterMask(Mask));
2136   }
2137 
2138   if (InFlag.getNode())
2139     Ops.push_back(InFlag);
2140 
2141   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2142   if (isTailCall) {
2143     MF.getFrameInfo().setHasTailCall();
2144     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
2145   }
2146 
2147   // Returns a chain and a flag for retval copy to use.
2148   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
2149   InFlag = Chain.getValue(1);
2150 
2151   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
2152                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
2153   if (!Ins.empty())
2154     InFlag = Chain.getValue(1);
2155 
2156   // Handle result values, copying them out of physregs into vregs that we
2157   // return.
2158   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
2159                          InVals, isThisReturn,
2160                          isThisReturn ? OutVals[0] : SDValue());
2161 }
2162 
2163 /// HandleByVal - Every parameter *after* a byval parameter is passed
2164 /// on the stack.  Remember the next parameter register to allocate,
2165 /// and then confiscate the rest of the parameter registers to insure
2166 /// this.
2167 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size,
2168                                     unsigned Align) const {
2169   // Byval (as with any stack) slots are always at least 4 byte aligned.
2170   Align = std::max(Align, 4U);
2171 
2172   unsigned Reg = State->AllocateReg(GPRArgRegs);
2173   if (!Reg)
2174     return;
2175 
2176   unsigned AlignInRegs = Align / 4;
2177   unsigned Waste = (ARM::R4 - Reg) % AlignInRegs;
2178   for (unsigned i = 0; i < Waste; ++i)
2179     Reg = State->AllocateReg(GPRArgRegs);
2180 
2181   if (!Reg)
2182     return;
2183 
2184   unsigned Excess = 4 * (ARM::R4 - Reg);
2185 
2186   // Special case when NSAA != SP and parameter size greater than size of
2187   // all remained GPR regs. In that case we can't split parameter, we must
2188   // send it to stack. We also must set NCRN to R4, so waste all
2189   // remained registers.
2190   const unsigned NSAAOffset = State->getNextStackOffset();
2191   if (NSAAOffset != 0 && Size > Excess) {
2192     while (State->AllocateReg(GPRArgRegs))
2193       ;
2194     return;
2195   }
2196 
2197   // First register for byval parameter is the first register that wasn't
2198   // allocated before this method call, so it would be "reg".
2199   // If parameter is small enough to be saved in range [reg, r4), then
2200   // the end (first after last) register would be reg + param-size-in-regs,
2201   // else parameter would be splitted between registers and stack,
2202   // end register would be r4 in this case.
2203   unsigned ByValRegBegin = Reg;
2204   unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4);
2205   State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
2206   // Note, first register is allocated in the beginning of function already,
2207   // allocate remained amount of registers we need.
2208   for (unsigned i = Reg + 1; i != ByValRegEnd; ++i)
2209     State->AllocateReg(GPRArgRegs);
2210   // A byval parameter that is split between registers and memory needs its
2211   // size truncated here.
2212   // In the case where the entire structure fits in registers, we set the
2213   // size in memory to zero.
2214   Size = std::max<int>(Size - Excess, 0);
2215 }
2216 
2217 /// MatchingStackOffset - Return true if the given stack call argument is
2218 /// already available in the same position (relatively) of the caller's
2219 /// incoming argument stack.
2220 static
2221 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2222                          MachineFrameInfo &MFI, const MachineRegisterInfo *MRI,
2223                          const TargetInstrInfo *TII) {
2224   unsigned Bytes = Arg.getValueSizeInBits() / 8;
2225   int FI = std::numeric_limits<int>::max();
2226   if (Arg.getOpcode() == ISD::CopyFromReg) {
2227     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2228     if (!TargetRegisterInfo::isVirtualRegister(VR))
2229       return false;
2230     MachineInstr *Def = MRI->getVRegDef(VR);
2231     if (!Def)
2232       return false;
2233     if (!Flags.isByVal()) {
2234       if (!TII->isLoadFromStackSlot(*Def, FI))
2235         return false;
2236     } else {
2237       return false;
2238     }
2239   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2240     if (Flags.isByVal())
2241       // ByVal argument is passed in as a pointer but it's now being
2242       // dereferenced. e.g.
2243       // define @foo(%struct.X* %A) {
2244       //   tail call @bar(%struct.X* byval %A)
2245       // }
2246       return false;
2247     SDValue Ptr = Ld->getBasePtr();
2248     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2249     if (!FINode)
2250       return false;
2251     FI = FINode->getIndex();
2252   } else
2253     return false;
2254 
2255   assert(FI != std::numeric_limits<int>::max());
2256   if (!MFI.isFixedObjectIndex(FI))
2257     return false;
2258   return Offset == MFI.getObjectOffset(FI) && Bytes == MFI.getObjectSize(FI);
2259 }
2260 
2261 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2262 /// for tail call optimization. Targets which want to do tail call
2263 /// optimization should implement this function.
2264 bool
2265 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2266                                                      CallingConv::ID CalleeCC,
2267                                                      bool isVarArg,
2268                                                      bool isCalleeStructRet,
2269                                                      bool isCallerStructRet,
2270                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2271                                     const SmallVectorImpl<SDValue> &OutVals,
2272                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2273                                                      SelectionDAG& DAG) const {
2274   MachineFunction &MF = DAG.getMachineFunction();
2275   const Function &CallerF = MF.getFunction();
2276   CallingConv::ID CallerCC = CallerF.getCallingConv();
2277 
2278   assert(Subtarget->supportsTailCall());
2279 
2280   // Tail calls to function pointers cannot be optimized for Thumb1 if the args
2281   // to the call take up r0-r3. The reason is that there are no legal registers
2282   // left to hold the pointer to the function to be called.
2283   if (Subtarget->isThumb1Only() && Outs.size() >= 4 &&
2284       !isa<GlobalAddressSDNode>(Callee.getNode()))
2285       return false;
2286 
2287   // Look for obvious safe cases to perform tail call optimization that do not
2288   // require ABI changes. This is what gcc calls sibcall.
2289 
2290   // Exception-handling functions need a special set of instructions to indicate
2291   // a return to the hardware. Tail-calling another function would probably
2292   // break this.
2293   if (CallerF.hasFnAttribute("interrupt"))
2294     return false;
2295 
2296   // Also avoid sibcall optimization if either caller or callee uses struct
2297   // return semantics.
2298   if (isCalleeStructRet || isCallerStructRet)
2299     return false;
2300 
2301   // Externally-defined functions with weak linkage should not be
2302   // tail-called on ARM when the OS does not support dynamic
2303   // pre-emption of symbols, as the AAELF spec requires normal calls
2304   // to undefined weak functions to be replaced with a NOP or jump to the
2305   // next instruction. The behaviour of branch instructions in this
2306   // situation (as used for tail calls) is implementation-defined, so we
2307   // cannot rely on the linker replacing the tail call with a return.
2308   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2309     const GlobalValue *GV = G->getGlobal();
2310     const Triple &TT = getTargetMachine().getTargetTriple();
2311     if (GV->hasExternalWeakLinkage() &&
2312         (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2313       return false;
2314   }
2315 
2316   // Check that the call results are passed in the same way.
2317   LLVMContext &C = *DAG.getContext();
2318   if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins,
2319                                   CCAssignFnForReturn(CalleeCC, isVarArg),
2320                                   CCAssignFnForReturn(CallerCC, isVarArg)))
2321     return false;
2322   // The callee has to preserve all registers the caller needs to preserve.
2323   const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
2324   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
2325   if (CalleeCC != CallerCC) {
2326     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
2327     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
2328       return false;
2329   }
2330 
2331   // If Caller's vararg or byval argument has been split between registers and
2332   // stack, do not perform tail call, since part of the argument is in caller's
2333   // local frame.
2334   const ARMFunctionInfo *AFI_Caller = MF.getInfo<ARMFunctionInfo>();
2335   if (AFI_Caller->getArgRegsSaveSize())
2336     return false;
2337 
2338   // If the callee takes no arguments then go on to check the results of the
2339   // call.
2340   if (!Outs.empty()) {
2341     // Check if stack adjustment is needed. For now, do not do this if any
2342     // argument is passed on the stack.
2343     SmallVector<CCValAssign, 16> ArgLocs;
2344     CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
2345     CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
2346     if (CCInfo.getNextStackOffset()) {
2347       // Check if the arguments are already laid out in the right way as
2348       // the caller's fixed stack objects.
2349       MachineFrameInfo &MFI = MF.getFrameInfo();
2350       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2351       const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2352       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2353            i != e;
2354            ++i, ++realArgIdx) {
2355         CCValAssign &VA = ArgLocs[i];
2356         EVT RegVT = VA.getLocVT();
2357         SDValue Arg = OutVals[realArgIdx];
2358         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2359         if (VA.getLocInfo() == CCValAssign::Indirect)
2360           return false;
2361         if (VA.needsCustom()) {
2362           // f64 and vector types are split into multiple registers or
2363           // register/stack-slot combinations.  The types will not match
2364           // the registers; give up on memory f64 refs until we figure
2365           // out what to do about this.
2366           if (!VA.isRegLoc())
2367             return false;
2368           if (!ArgLocs[++i].isRegLoc())
2369             return false;
2370           if (RegVT == MVT::v2f64) {
2371             if (!ArgLocs[++i].isRegLoc())
2372               return false;
2373             if (!ArgLocs[++i].isRegLoc())
2374               return false;
2375           }
2376         } else if (!VA.isRegLoc()) {
2377           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2378                                    MFI, MRI, TII))
2379             return false;
2380         }
2381       }
2382     }
2383 
2384     const MachineRegisterInfo &MRI = MF.getRegInfo();
2385     if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
2386       return false;
2387   }
2388 
2389   return true;
2390 }
2391 
2392 bool
2393 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2394                                   MachineFunction &MF, bool isVarArg,
2395                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
2396                                   LLVMContext &Context) const {
2397   SmallVector<CCValAssign, 16> RVLocs;
2398   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2399   return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2400 }
2401 
2402 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2403                                     const SDLoc &DL, SelectionDAG &DAG) {
2404   const MachineFunction &MF = DAG.getMachineFunction();
2405   const Function &F = MF.getFunction();
2406 
2407   StringRef IntKind = F.getFnAttribute("interrupt").getValueAsString();
2408 
2409   // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2410   // version of the "preferred return address". These offsets affect the return
2411   // instruction if this is a return from PL1 without hypervisor extensions.
2412   //    IRQ/FIQ: +4     "subs pc, lr, #4"
2413   //    SWI:     0      "subs pc, lr, #0"
2414   //    ABORT:   +4     "subs pc, lr, #4"
2415   //    UNDEF:   +4/+2  "subs pc, lr, #0"
2416   // UNDEF varies depending on where the exception came from ARM or Thumb
2417   // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2418 
2419   int64_t LROffset;
2420   if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2421       IntKind == "ABORT")
2422     LROffset = 4;
2423   else if (IntKind == "SWI" || IntKind == "UNDEF")
2424     LROffset = 0;
2425   else
2426     report_fatal_error("Unsupported interrupt attribute. If present, value "
2427                        "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2428 
2429   RetOps.insert(RetOps.begin() + 1,
2430                 DAG.getConstant(LROffset, DL, MVT::i32, false));
2431 
2432   return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2433 }
2434 
2435 SDValue
2436 ARMTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2437                                bool isVarArg,
2438                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2439                                const SmallVectorImpl<SDValue> &OutVals,
2440                                const SDLoc &dl, SelectionDAG &DAG) const {
2441   // CCValAssign - represent the assignment of the return value to a location.
2442   SmallVector<CCValAssign, 16> RVLocs;
2443 
2444   // CCState - Info about the registers and stack slots.
2445   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2446                  *DAG.getContext());
2447 
2448   // Analyze outgoing return values.
2449   CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2450 
2451   SDValue Flag;
2452   SmallVector<SDValue, 4> RetOps;
2453   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2454   bool isLittleEndian = Subtarget->isLittle();
2455 
2456   MachineFunction &MF = DAG.getMachineFunction();
2457   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2458   AFI->setReturnRegsCount(RVLocs.size());
2459 
2460   // Copy the result values into the output registers.
2461   for (unsigned i = 0, realRVLocIdx = 0;
2462        i != RVLocs.size();
2463        ++i, ++realRVLocIdx) {
2464     CCValAssign &VA = RVLocs[i];
2465     assert(VA.isRegLoc() && "Can only return in registers!");
2466 
2467     SDValue Arg = OutVals[realRVLocIdx];
2468 
2469     switch (VA.getLocInfo()) {
2470     default: llvm_unreachable("Unknown loc info!");
2471     case CCValAssign::Full: break;
2472     case CCValAssign::BCvt:
2473       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2474       break;
2475     }
2476 
2477     if (VA.needsCustom()) {
2478       if (VA.getLocVT() == MVT::v2f64) {
2479         // Extract the first half and return it in two registers.
2480         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2481                                    DAG.getConstant(0, dl, MVT::i32));
2482         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2483                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
2484 
2485         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2486                                  HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2487                                  Flag);
2488         Flag = Chain.getValue(1);
2489         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2490         VA = RVLocs[++i]; // skip ahead to next loc
2491         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2492                                  HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2493                                  Flag);
2494         Flag = Chain.getValue(1);
2495         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2496         VA = RVLocs[++i]; // skip ahead to next loc
2497 
2498         // Extract the 2nd half and fall through to handle it as an f64 value.
2499         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2500                           DAG.getConstant(1, dl, MVT::i32));
2501       }
2502       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
2503       // available.
2504       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2505                                   DAG.getVTList(MVT::i32, MVT::i32), Arg);
2506       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2507                                fmrrd.getValue(isLittleEndian ? 0 : 1),
2508                                Flag);
2509       Flag = Chain.getValue(1);
2510       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2511       VA = RVLocs[++i]; // skip ahead to next loc
2512       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2513                                fmrrd.getValue(isLittleEndian ? 1 : 0),
2514                                Flag);
2515     } else
2516       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2517 
2518     // Guarantee that all emitted copies are
2519     // stuck together, avoiding something bad.
2520     Flag = Chain.getValue(1);
2521     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2522   }
2523   const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
2524   const MCPhysReg *I =
2525       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2526   if (I) {
2527     for (; *I; ++I) {
2528       if (ARM::GPRRegClass.contains(*I))
2529         RetOps.push_back(DAG.getRegister(*I, MVT::i32));
2530       else if (ARM::DPRRegClass.contains(*I))
2531         RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
2532       else
2533         llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2534     }
2535   }
2536 
2537   // Update chain and glue.
2538   RetOps[0] = Chain;
2539   if (Flag.getNode())
2540     RetOps.push_back(Flag);
2541 
2542   // CPUs which aren't M-class use a special sequence to return from
2543   // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2544   // though we use "subs pc, lr, #N").
2545   //
2546   // M-class CPUs actually use a normal return sequence with a special
2547   // (hardware-provided) value in LR, so the normal code path works.
2548   if (DAG.getMachineFunction().getFunction().hasFnAttribute("interrupt") &&
2549       !Subtarget->isMClass()) {
2550     if (Subtarget->isThumb1Only())
2551       report_fatal_error("interrupt attribute is not supported in Thumb1");
2552     return LowerInterruptReturn(RetOps, dl, DAG);
2553   }
2554 
2555   return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2556 }
2557 
2558 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2559   if (N->getNumValues() != 1)
2560     return false;
2561   if (!N->hasNUsesOfValue(1, 0))
2562     return false;
2563 
2564   SDValue TCChain = Chain;
2565   SDNode *Copy = *N->use_begin();
2566   if (Copy->getOpcode() == ISD::CopyToReg) {
2567     // If the copy has a glue operand, we conservatively assume it isn't safe to
2568     // perform a tail call.
2569     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2570       return false;
2571     TCChain = Copy->getOperand(0);
2572   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2573     SDNode *VMov = Copy;
2574     // f64 returned in a pair of GPRs.
2575     SmallPtrSet<SDNode*, 2> Copies;
2576     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2577          UI != UE; ++UI) {
2578       if (UI->getOpcode() != ISD::CopyToReg)
2579         return false;
2580       Copies.insert(*UI);
2581     }
2582     if (Copies.size() > 2)
2583       return false;
2584 
2585     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2586          UI != UE; ++UI) {
2587       SDValue UseChain = UI->getOperand(0);
2588       if (Copies.count(UseChain.getNode()))
2589         // Second CopyToReg
2590         Copy = *UI;
2591       else {
2592         // We are at the top of this chain.
2593         // If the copy has a glue operand, we conservatively assume it
2594         // isn't safe to perform a tail call.
2595         if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue)
2596           return false;
2597         // First CopyToReg
2598         TCChain = UseChain;
2599       }
2600     }
2601   } else if (Copy->getOpcode() == ISD::BITCAST) {
2602     // f32 returned in a single GPR.
2603     if (!Copy->hasOneUse())
2604       return false;
2605     Copy = *Copy->use_begin();
2606     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2607       return false;
2608     // If the copy has a glue operand, we conservatively assume it isn't safe to
2609     // perform a tail call.
2610     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2611       return false;
2612     TCChain = Copy->getOperand(0);
2613   } else {
2614     return false;
2615   }
2616 
2617   bool HasRet = false;
2618   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2619        UI != UE; ++UI) {
2620     if (UI->getOpcode() != ARMISD::RET_FLAG &&
2621         UI->getOpcode() != ARMISD::INTRET_FLAG)
2622       return false;
2623     HasRet = true;
2624   }
2625 
2626   if (!HasRet)
2627     return false;
2628 
2629   Chain = TCChain;
2630   return true;
2631 }
2632 
2633 bool ARMTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
2634   if (!Subtarget->supportsTailCall())
2635     return false;
2636 
2637   auto Attr =
2638       CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2639   if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2640     return false;
2641 
2642   return true;
2643 }
2644 
2645 // Trying to write a 64 bit value so need to split into two 32 bit values first,
2646 // and pass the lower and high parts through.
2647 static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) {
2648   SDLoc DL(Op);
2649   SDValue WriteValue = Op->getOperand(2);
2650 
2651   // This function is only supposed to be called for i64 type argument.
2652   assert(WriteValue.getValueType() == MVT::i64
2653           && "LowerWRITE_REGISTER called for non-i64 type argument.");
2654 
2655   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2656                            DAG.getConstant(0, DL, MVT::i32));
2657   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2658                            DAG.getConstant(1, DL, MVT::i32));
2659   SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi };
2660   return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops);
2661 }
2662 
2663 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2664 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2665 // one of the above mentioned nodes. It has to be wrapped because otherwise
2666 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2667 // be used to form addressing mode. These wrapped nodes will be selected
2668 // into MOVi.
2669 SDValue ARMTargetLowering::LowerConstantPool(SDValue Op,
2670                                              SelectionDAG &DAG) const {
2671   EVT PtrVT = Op.getValueType();
2672   // FIXME there is no actual debug info here
2673   SDLoc dl(Op);
2674   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2675   SDValue Res;
2676 
2677   // When generating execute-only code Constant Pools must be promoted to the
2678   // global data section. It's a bit ugly that we can't share them across basic
2679   // blocks, but this way we guarantee that execute-only behaves correct with
2680   // position-independent addressing modes.
2681   if (Subtarget->genExecuteOnly()) {
2682     auto AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
2683     auto T = const_cast<Type*>(CP->getType());
2684     auto C = const_cast<Constant*>(CP->getConstVal());
2685     auto M = const_cast<Module*>(DAG.getMachineFunction().
2686                                  getFunction().getParent());
2687     auto GV = new GlobalVariable(
2688                     *M, T, /*isConst=*/true, GlobalVariable::InternalLinkage, C,
2689                     Twine(DAG.getDataLayout().getPrivateGlobalPrefix()) + "CP" +
2690                     Twine(DAG.getMachineFunction().getFunctionNumber()) + "_" +
2691                     Twine(AFI->createPICLabelUId())
2692                   );
2693     SDValue GA = DAG.getTargetGlobalAddress(dyn_cast<GlobalValue>(GV),
2694                                             dl, PtrVT);
2695     return LowerGlobalAddress(GA, DAG);
2696   }
2697 
2698   if (CP->isMachineConstantPoolEntry())
2699     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2700                                     CP->getAlignment());
2701   else
2702     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2703                                     CP->getAlignment());
2704   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2705 }
2706 
2707 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2708   return MachineJumpTableInfo::EK_Inline;
2709 }
2710 
2711 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2712                                              SelectionDAG &DAG) const {
2713   MachineFunction &MF = DAG.getMachineFunction();
2714   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2715   unsigned ARMPCLabelIndex = 0;
2716   SDLoc DL(Op);
2717   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2718   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2719   SDValue CPAddr;
2720   bool IsPositionIndependent = isPositionIndependent() || Subtarget->isROPI();
2721   if (!IsPositionIndependent) {
2722     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2723   } else {
2724     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2725     ARMPCLabelIndex = AFI->createPICLabelUId();
2726     ARMConstantPoolValue *CPV =
2727       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2728                                       ARMCP::CPBlockAddress, PCAdj);
2729     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2730   }
2731   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2732   SDValue Result = DAG.getLoad(
2733       PtrVT, DL, DAG.getEntryNode(), CPAddr,
2734       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2735   if (!IsPositionIndependent)
2736     return Result;
2737   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32);
2738   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2739 }
2740 
2741 /// \brief Convert a TLS address reference into the correct sequence of loads
2742 /// and calls to compute the variable's address for Darwin, and return an
2743 /// SDValue containing the final node.
2744 
2745 /// Darwin only has one TLS scheme which must be capable of dealing with the
2746 /// fully general situation, in the worst case. This means:
2747 ///     + "extern __thread" declaration.
2748 ///     + Defined in a possibly unknown dynamic library.
2749 ///
2750 /// The general system is that each __thread variable has a [3 x i32] descriptor
2751 /// which contains information used by the runtime to calculate the address. The
2752 /// only part of this the compiler needs to know about is the first word, which
2753 /// contains a function pointer that must be called with the address of the
2754 /// entire descriptor in "r0".
2755 ///
2756 /// Since this descriptor may be in a different unit, in general access must
2757 /// proceed along the usual ARM rules. A common sequence to produce is:
2758 ///
2759 ///     movw rT1, :lower16:_var$non_lazy_ptr
2760 ///     movt rT1, :upper16:_var$non_lazy_ptr
2761 ///     ldr r0, [rT1]
2762 ///     ldr rT2, [r0]
2763 ///     blx rT2
2764 ///     [...address now in r0...]
2765 SDValue
2766 ARMTargetLowering::LowerGlobalTLSAddressDarwin(SDValue Op,
2767                                                SelectionDAG &DAG) const {
2768   assert(Subtarget->isTargetDarwin() &&
2769          "This function expects a Darwin target");
2770   SDLoc DL(Op);
2771 
2772   // First step is to get the address of the actua global symbol. This is where
2773   // the TLS descriptor lives.
2774   SDValue DescAddr = LowerGlobalAddressDarwin(Op, DAG);
2775 
2776   // The first entry in the descriptor is a function pointer that we must call
2777   // to obtain the address of the variable.
2778   SDValue Chain = DAG.getEntryNode();
2779   SDValue FuncTLVGet = DAG.getLoad(
2780       MVT::i32, DL, Chain, DescAddr,
2781       MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2782       /* Alignment = */ 4,
2783       MachineMemOperand::MONonTemporal | MachineMemOperand::MODereferenceable |
2784           MachineMemOperand::MOInvariant);
2785   Chain = FuncTLVGet.getValue(1);
2786 
2787   MachineFunction &F = DAG.getMachineFunction();
2788   MachineFrameInfo &MFI = F.getFrameInfo();
2789   MFI.setAdjustsStack(true);
2790 
2791   // TLS calls preserve all registers except those that absolutely must be
2792   // trashed: R0 (it takes an argument), LR (it's a call) and CPSR (let's not be
2793   // silly).
2794   auto TRI =
2795       getTargetMachine().getSubtargetImpl(F.getFunction())->getRegisterInfo();
2796   auto ARI = static_cast<const ARMRegisterInfo *>(TRI);
2797   const uint32_t *Mask = ARI->getTLSCallPreservedMask(DAG.getMachineFunction());
2798 
2799   // Finally, we can make the call. This is just a degenerate version of a
2800   // normal AArch64 call node: r0 takes the address of the descriptor, and
2801   // returns the address of the variable in this thread.
2802   Chain = DAG.getCopyToReg(Chain, DL, ARM::R0, DescAddr, SDValue());
2803   Chain =
2804       DAG.getNode(ARMISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
2805                   Chain, FuncTLVGet, DAG.getRegister(ARM::R0, MVT::i32),
2806                   DAG.getRegisterMask(Mask), Chain.getValue(1));
2807   return DAG.getCopyFromReg(Chain, DL, ARM::R0, MVT::i32, Chain.getValue(1));
2808 }
2809 
2810 SDValue
2811 ARMTargetLowering::LowerGlobalTLSAddressWindows(SDValue Op,
2812                                                 SelectionDAG &DAG) const {
2813   assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering");
2814 
2815   SDValue Chain = DAG.getEntryNode();
2816   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2817   SDLoc DL(Op);
2818 
2819   // Load the current TEB (thread environment block)
2820   SDValue Ops[] = {Chain,
2821                    DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32),
2822                    DAG.getConstant(15, DL, MVT::i32),
2823                    DAG.getConstant(0, DL, MVT::i32),
2824                    DAG.getConstant(13, DL, MVT::i32),
2825                    DAG.getConstant(0, DL, MVT::i32),
2826                    DAG.getConstant(2, DL, MVT::i32)};
2827   SDValue CurrentTEB = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
2828                                    DAG.getVTList(MVT::i32, MVT::Other), Ops);
2829 
2830   SDValue TEB = CurrentTEB.getValue(0);
2831   Chain = CurrentTEB.getValue(1);
2832 
2833   // Load the ThreadLocalStoragePointer from the TEB
2834   // A pointer to the TLS array is located at offset 0x2c from the TEB.
2835   SDValue TLSArray =
2836       DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x2c, DL));
2837   TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo());
2838 
2839   // The pointer to the thread's TLS data area is at the TLS Index scaled by 4
2840   // offset into the TLSArray.
2841 
2842   // Load the TLS index from the C runtime
2843   SDValue TLSIndex =
2844       DAG.getTargetExternalSymbol("_tls_index", PtrVT, ARMII::MO_NO_FLAG);
2845   TLSIndex = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, TLSIndex);
2846   TLSIndex = DAG.getLoad(PtrVT, DL, Chain, TLSIndex, MachinePointerInfo());
2847 
2848   SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex,
2849                               DAG.getConstant(2, DL, MVT::i32));
2850   SDValue TLS = DAG.getLoad(PtrVT, DL, Chain,
2851                             DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot),
2852                             MachinePointerInfo());
2853 
2854   // Get the offset of the start of the .tls section (section base)
2855   const auto *GA = cast<GlobalAddressSDNode>(Op);
2856   auto *CPV = ARMConstantPoolConstant::Create(GA->getGlobal(), ARMCP::SECREL);
2857   SDValue Offset = DAG.getLoad(
2858       PtrVT, DL, Chain, DAG.getNode(ARMISD::Wrapper, DL, MVT::i32,
2859                                     DAG.getTargetConstantPool(CPV, PtrVT, 4)),
2860       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2861 
2862   return DAG.getNode(ISD::ADD, DL, PtrVT, TLS, Offset);
2863 }
2864 
2865 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2866 SDValue
2867 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2868                                                  SelectionDAG &DAG) const {
2869   SDLoc dl(GA);
2870   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2871   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2872   MachineFunction &MF = DAG.getMachineFunction();
2873   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2874   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2875   ARMConstantPoolValue *CPV =
2876     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2877                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2878   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2879   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2880   Argument = DAG.getLoad(
2881       PtrVT, dl, DAG.getEntryNode(), Argument,
2882       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2883   SDValue Chain = Argument.getValue(1);
2884 
2885   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2886   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2887 
2888   // call __tls_get_addr.
2889   ArgListTy Args;
2890   ArgListEntry Entry;
2891   Entry.Node = Argument;
2892   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2893   Args.push_back(Entry);
2894 
2895   // FIXME: is there useful debug info available here?
2896   TargetLowering::CallLoweringInfo CLI(DAG);
2897   CLI.setDebugLoc(dl).setChain(Chain).setLibCallee(
2898       CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
2899       DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args));
2900 
2901   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2902   return CallResult.first;
2903 }
2904 
2905 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2906 // "local exec" model.
2907 SDValue
2908 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2909                                         SelectionDAG &DAG,
2910                                         TLSModel::Model model) const {
2911   const GlobalValue *GV = GA->getGlobal();
2912   SDLoc dl(GA);
2913   SDValue Offset;
2914   SDValue Chain = DAG.getEntryNode();
2915   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2916   // Get the Thread Pointer
2917   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2918 
2919   if (model == TLSModel::InitialExec) {
2920     MachineFunction &MF = DAG.getMachineFunction();
2921     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2922     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2923     // Initial exec model.
2924     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2925     ARMConstantPoolValue *CPV =
2926       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2927                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2928                                       true);
2929     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2930     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2931     Offset = DAG.getLoad(
2932         PtrVT, dl, Chain, Offset,
2933         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2934     Chain = Offset.getValue(1);
2935 
2936     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2937     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2938 
2939     Offset = DAG.getLoad(
2940         PtrVT, dl, Chain, Offset,
2941         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2942   } else {
2943     // local exec model
2944     assert(model == TLSModel::LocalExec);
2945     ARMConstantPoolValue *CPV =
2946       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2947     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2948     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2949     Offset = DAG.getLoad(
2950         PtrVT, dl, Chain, Offset,
2951         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2952   }
2953 
2954   // The address of the thread local variable is the add of the thread
2955   // pointer with the offset of the variable.
2956   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2957 }
2958 
2959 SDValue
2960 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2961   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2962   if (DAG.getTarget().Options.EmulatedTLS)
2963     return LowerToTLSEmulatedModel(GA, DAG);
2964 
2965   if (Subtarget->isTargetDarwin())
2966     return LowerGlobalTLSAddressDarwin(Op, DAG);
2967 
2968   if (Subtarget->isTargetWindows())
2969     return LowerGlobalTLSAddressWindows(Op, DAG);
2970 
2971   // TODO: implement the "local dynamic" model
2972   assert(Subtarget->isTargetELF() && "Only ELF implemented here");
2973   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2974 
2975   switch (model) {
2976     case TLSModel::GeneralDynamic:
2977     case TLSModel::LocalDynamic:
2978       return LowerToTLSGeneralDynamicModel(GA, DAG);
2979     case TLSModel::InitialExec:
2980     case TLSModel::LocalExec:
2981       return LowerToTLSExecModels(GA, DAG, model);
2982   }
2983   llvm_unreachable("bogus TLS model");
2984 }
2985 
2986 /// Return true if all users of V are within function F, looking through
2987 /// ConstantExprs.
2988 static bool allUsersAreInFunction(const Value *V, const Function *F) {
2989   SmallVector<const User*,4> Worklist;
2990   for (auto *U : V->users())
2991     Worklist.push_back(U);
2992   while (!Worklist.empty()) {
2993     auto *U = Worklist.pop_back_val();
2994     if (isa<ConstantExpr>(U)) {
2995       for (auto *UU : U->users())
2996         Worklist.push_back(UU);
2997       continue;
2998     }
2999 
3000     auto *I = dyn_cast<Instruction>(U);
3001     if (!I || I->getParent()->getParent() != F)
3002       return false;
3003   }
3004   return true;
3005 }
3006 
3007 /// Return true if all users of V are within some (any) function, looking through
3008 /// ConstantExprs. In other words, are there any global constant users?
3009 static bool allUsersAreInFunctions(const Value *V) {
3010   SmallVector<const User*,4> Worklist;
3011   for (auto *U : V->users())
3012     Worklist.push_back(U);
3013   while (!Worklist.empty()) {
3014     auto *U = Worklist.pop_back_val();
3015     if (isa<ConstantExpr>(U)) {
3016       for (auto *UU : U->users())
3017         Worklist.push_back(UU);
3018       continue;
3019     }
3020 
3021     if (!isa<Instruction>(U))
3022       return false;
3023   }
3024   return true;
3025 }
3026 
3027 // Return true if T is an integer, float or an array/vector of either.
3028 static bool isSimpleType(Type *T) {
3029   if (T->isIntegerTy() || T->isFloatingPointTy())
3030     return true;
3031   Type *SubT = nullptr;
3032   if (T->isArrayTy())
3033     SubT = T->getArrayElementType();
3034   else if (T->isVectorTy())
3035     SubT = T->getVectorElementType();
3036   else
3037     return false;
3038   return SubT->isIntegerTy() || SubT->isFloatingPointTy();
3039 }
3040 
3041 static SDValue promoteToConstantPool(const GlobalValue *GV, SelectionDAG &DAG,
3042                                      EVT PtrVT, const SDLoc &dl) {
3043   // If we're creating a pool entry for a constant global with unnamed address,
3044   // and the global is small enough, we can emit it inline into the constant pool
3045   // to save ourselves an indirection.
3046   //
3047   // This is a win if the constant is only used in one function (so it doesn't
3048   // need to be duplicated) or duplicating the constant wouldn't increase code
3049   // size (implying the constant is no larger than 4 bytes).
3050   const Function &F = DAG.getMachineFunction().getFunction();
3051 
3052   // We rely on this decision to inline being idemopotent and unrelated to the
3053   // use-site. We know that if we inline a variable at one use site, we'll
3054   // inline it elsewhere too (and reuse the constant pool entry). Fast-isel
3055   // doesn't know about this optimization, so bail out if it's enabled else
3056   // we could decide to inline here (and thus never emit the GV) but require
3057   // the GV from fast-isel generated code.
3058   if (!EnableConstpoolPromotion ||
3059       DAG.getMachineFunction().getTarget().Options.EnableFastISel)
3060       return SDValue();
3061 
3062   auto *GVar = dyn_cast<GlobalVariable>(GV);
3063   if (!GVar || !GVar->hasInitializer() ||
3064       !GVar->isConstant() || !GVar->hasGlobalUnnamedAddr() ||
3065       !GVar->hasLocalLinkage())
3066     return SDValue();
3067 
3068   // Ensure that we don't try and inline any type that contains pointers. If
3069   // we inline a value that contains relocations, we move the relocations from
3070   // .data to .text which is not ideal.
3071   auto *Init = GVar->getInitializer();
3072   if (!isSimpleType(Init->getType()))
3073     return SDValue();
3074 
3075   // The constant islands pass can only really deal with alignment requests
3076   // <= 4 bytes and cannot pad constants itself. Therefore we cannot promote
3077   // any type wanting greater alignment requirements than 4 bytes. We also
3078   // can only promote constants that are multiples of 4 bytes in size or
3079   // are paddable to a multiple of 4. Currently we only try and pad constants
3080   // that are strings for simplicity.
3081   auto *CDAInit = dyn_cast<ConstantDataArray>(Init);
3082   unsigned Size = DAG.getDataLayout().getTypeAllocSize(Init->getType());
3083   unsigned Align = GVar->getAlignment();
3084   unsigned RequiredPadding = 4 - (Size % 4);
3085   bool PaddingPossible =
3086     RequiredPadding == 4 || (CDAInit && CDAInit->isString());
3087   if (!PaddingPossible || Align > 4 || Size > ConstpoolPromotionMaxSize ||
3088       Size == 0)
3089     return SDValue();
3090 
3091   unsigned PaddedSize = Size + ((RequiredPadding == 4) ? 0 : RequiredPadding);
3092   MachineFunction &MF = DAG.getMachineFunction();
3093   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3094 
3095   // We can't bloat the constant pool too much, else the ConstantIslands pass
3096   // may fail to converge. If we haven't promoted this global yet (it may have
3097   // multiple uses), and promoting it would increase the constant pool size (Sz
3098   // > 4), ensure we have space to do so up to MaxTotal.
3099   if (!AFI->getGlobalsPromotedToConstantPool().count(GVar) && Size > 4)
3100     if (AFI->getPromotedConstpoolIncrease() + PaddedSize - 4 >=
3101         ConstpoolPromotionMaxTotal)
3102       return SDValue();
3103 
3104   // This is only valid if all users are in a single function OR it has users
3105   // in multiple functions but it no larger than a pointer. We also check if
3106   // GVar has constant (non-ConstantExpr) users. If so, it essentially has its
3107   // address taken.
3108   if (!allUsersAreInFunction(GVar, &F) &&
3109       !(Size <= 4 && allUsersAreInFunctions(GVar)))
3110     return SDValue();
3111 
3112   // We're going to inline this global. Pad it out if needed.
3113   if (RequiredPadding != 4) {
3114     StringRef S = CDAInit->getAsString();
3115 
3116     SmallVector<uint8_t,16> V(S.size());
3117     std::copy(S.bytes_begin(), S.bytes_end(), V.begin());
3118     while (RequiredPadding--)
3119       V.push_back(0);
3120     Init = ConstantDataArray::get(*DAG.getContext(), V);
3121   }
3122 
3123   auto CPVal = ARMConstantPoolConstant::Create(GVar, Init);
3124   SDValue CPAddr =
3125     DAG.getTargetConstantPool(CPVal, PtrVT, /*Align=*/4);
3126   if (!AFI->getGlobalsPromotedToConstantPool().count(GVar)) {
3127     AFI->markGlobalAsPromotedToConstantPool(GVar);
3128     AFI->setPromotedConstpoolIncrease(AFI->getPromotedConstpoolIncrease() +
3129                                       PaddedSize - 4);
3130   }
3131   ++NumConstpoolPromoted;
3132   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3133 }
3134 
3135 bool ARMTargetLowering::isReadOnly(const GlobalValue *GV) const {
3136   if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
3137     GV = GA->getBaseObject();
3138   return (isa<GlobalVariable>(GV) && cast<GlobalVariable>(GV)->isConstant()) ||
3139          isa<Function>(GV);
3140 }
3141 
3142 SDValue ARMTargetLowering::LowerGlobalAddress(SDValue Op,
3143                                               SelectionDAG &DAG) const {
3144   switch (Subtarget->getTargetTriple().getObjectFormat()) {
3145   default: llvm_unreachable("unknown object format");
3146   case Triple::COFF:
3147     return LowerGlobalAddressWindows(Op, DAG);
3148   case Triple::ELF:
3149     return LowerGlobalAddressELF(Op, DAG);
3150   case Triple::MachO:
3151     return LowerGlobalAddressDarwin(Op, DAG);
3152   }
3153 }
3154 
3155 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
3156                                                  SelectionDAG &DAG) const {
3157   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3158   SDLoc dl(Op);
3159   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3160   const TargetMachine &TM = getTargetMachine();
3161   bool IsRO = isReadOnly(GV);
3162 
3163   // promoteToConstantPool only if not generating XO text section
3164   if (TM.shouldAssumeDSOLocal(*GV->getParent(), GV) && !Subtarget->genExecuteOnly())
3165     if (SDValue V = promoteToConstantPool(GV, DAG, PtrVT, dl))
3166       return V;
3167 
3168   if (isPositionIndependent()) {
3169     bool UseGOT_PREL = !TM.shouldAssumeDSOLocal(*GV->getParent(), GV);
3170     SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3171                                            UseGOT_PREL ? ARMII::MO_GOT : 0);
3172     SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G);
3173     if (UseGOT_PREL)
3174       Result =
3175           DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
3176                       MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3177     return Result;
3178   } else if (Subtarget->isROPI() && IsRO) {
3179     // PC-relative.
3180     SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT);
3181     SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G);
3182     return Result;
3183   } else if (Subtarget->isRWPI() && !IsRO) {
3184     // SB-relative.
3185     SDValue RelAddr;
3186     if (Subtarget->useMovt(DAG.getMachineFunction())) {
3187       ++NumMovwMovt;
3188       SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_SBREL);
3189       RelAddr = DAG.getNode(ARMISD::Wrapper, dl, PtrVT, G);
3190     } else { // use literal pool for address constant
3191       ARMConstantPoolValue *CPV =
3192         ARMConstantPoolConstant::Create(GV, ARMCP::SBREL);
3193       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3194       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3195       RelAddr = DAG.getLoad(
3196           PtrVT, dl, DAG.getEntryNode(), CPAddr,
3197           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3198     }
3199     SDValue SB = DAG.getCopyFromReg(DAG.getEntryNode(), dl, ARM::R9, PtrVT);
3200     SDValue Result = DAG.getNode(ISD::ADD, dl, PtrVT, SB, RelAddr);
3201     return Result;
3202   }
3203 
3204   // If we have T2 ops, we can materialize the address directly via movt/movw
3205   // pair. This is always cheaper.
3206   if (Subtarget->useMovt(DAG.getMachineFunction())) {
3207     ++NumMovwMovt;
3208     // FIXME: Once remat is capable of dealing with instructions with register
3209     // operands, expand this into two nodes.
3210     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
3211                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
3212   } else {
3213     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
3214     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3215     return DAG.getLoad(
3216         PtrVT, dl, DAG.getEntryNode(), CPAddr,
3217         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3218   }
3219 }
3220 
3221 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
3222                                                     SelectionDAG &DAG) const {
3223   assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
3224          "ROPI/RWPI not currently supported for Darwin");
3225   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3226   SDLoc dl(Op);
3227   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3228 
3229   if (Subtarget->useMovt(DAG.getMachineFunction()))
3230     ++NumMovwMovt;
3231 
3232   // FIXME: Once remat is capable of dealing with instructions with register
3233   // operands, expand this into multiple nodes
3234   unsigned Wrapper =
3235       isPositionIndependent() ? ARMISD::WrapperPIC : ARMISD::Wrapper;
3236 
3237   SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
3238   SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
3239 
3240   if (Subtarget->isGVIndirectSymbol(GV))
3241     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
3242                          MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3243   return Result;
3244 }
3245 
3246 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
3247                                                      SelectionDAG &DAG) const {
3248   assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
3249   assert(Subtarget->useMovt(DAG.getMachineFunction()) &&
3250          "Windows on ARM expects to use movw/movt");
3251   assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
3252          "ROPI/RWPI not currently supported for Windows");
3253 
3254   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3255   const ARMII::TOF TargetFlags =
3256     (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG);
3257   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3258   SDValue Result;
3259   SDLoc DL(Op);
3260 
3261   ++NumMovwMovt;
3262 
3263   // FIXME: Once remat is capable of dealing with instructions with register
3264   // operands, expand this into two nodes.
3265   Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
3266                        DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0,
3267                                                   TargetFlags));
3268   if (GV->hasDLLImportStorageClass())
3269     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
3270                          MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3271   return Result;
3272 }
3273 
3274 SDValue
3275 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
3276   SDLoc dl(Op);
3277   SDValue Val = DAG.getConstant(0, dl, MVT::i32);
3278   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
3279                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
3280                      Op.getOperand(1), Val);
3281 }
3282 
3283 SDValue
3284 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
3285   SDLoc dl(Op);
3286   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
3287                      Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32));
3288 }
3289 
3290 SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op,
3291                                                       SelectionDAG &DAG) const {
3292   SDLoc dl(Op);
3293   return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other,
3294                      Op.getOperand(0));
3295 }
3296 
3297 SDValue
3298 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
3299                                           const ARMSubtarget *Subtarget) const {
3300   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3301   SDLoc dl(Op);
3302   switch (IntNo) {
3303   default: return SDValue();    // Don't custom lower most intrinsics.
3304   case Intrinsic::thread_pointer: {
3305     EVT PtrVT = getPointerTy(DAG.getDataLayout());
3306     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
3307   }
3308   case Intrinsic::eh_sjlj_lsda: {
3309     MachineFunction &MF = DAG.getMachineFunction();
3310     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3311     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
3312     EVT PtrVT = getPointerTy(DAG.getDataLayout());
3313     SDValue CPAddr;
3314     bool IsPositionIndependent = isPositionIndependent();
3315     unsigned PCAdj = IsPositionIndependent ? (Subtarget->isThumb() ? 4 : 8) : 0;
3316     ARMConstantPoolValue *CPV =
3317       ARMConstantPoolConstant::Create(&MF.getFunction(), ARMPCLabelIndex,
3318                                       ARMCP::CPLSDA, PCAdj);
3319     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3320     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3321     SDValue Result = DAG.getLoad(
3322         PtrVT, dl, DAG.getEntryNode(), CPAddr,
3323         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3324 
3325     if (IsPositionIndependent) {
3326       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
3327       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
3328     }
3329     return Result;
3330   }
3331   case Intrinsic::arm_neon_vabs:
3332     return DAG.getNode(ISD::ABS, SDLoc(Op), Op.getValueType(),
3333                         Op.getOperand(1));
3334   case Intrinsic::arm_neon_vmulls:
3335   case Intrinsic::arm_neon_vmullu: {
3336     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
3337       ? ARMISD::VMULLs : ARMISD::VMULLu;
3338     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3339                        Op.getOperand(1), Op.getOperand(2));
3340   }
3341   case Intrinsic::arm_neon_vminnm:
3342   case Intrinsic::arm_neon_vmaxnm: {
3343     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminnm)
3344       ? ISD::FMINNUM : ISD::FMAXNUM;
3345     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3346                        Op.getOperand(1), Op.getOperand(2));
3347   }
3348   case Intrinsic::arm_neon_vminu:
3349   case Intrinsic::arm_neon_vmaxu: {
3350     if (Op.getValueType().isFloatingPoint())
3351       return SDValue();
3352     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminu)
3353       ? ISD::UMIN : ISD::UMAX;
3354     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3355                          Op.getOperand(1), Op.getOperand(2));
3356   }
3357   case Intrinsic::arm_neon_vmins:
3358   case Intrinsic::arm_neon_vmaxs: {
3359     // v{min,max}s is overloaded between signed integers and floats.
3360     if (!Op.getValueType().isFloatingPoint()) {
3361       unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
3362         ? ISD::SMIN : ISD::SMAX;
3363       return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3364                          Op.getOperand(1), Op.getOperand(2));
3365     }
3366     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
3367       ? ISD::FMINNAN : ISD::FMAXNAN;
3368     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3369                        Op.getOperand(1), Op.getOperand(2));
3370   }
3371   case Intrinsic::arm_neon_vtbl1:
3372     return DAG.getNode(ARMISD::VTBL1, SDLoc(Op), Op.getValueType(),
3373                        Op.getOperand(1), Op.getOperand(2));
3374   case Intrinsic::arm_neon_vtbl2:
3375     return DAG.getNode(ARMISD::VTBL2, SDLoc(Op), Op.getValueType(),
3376                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
3377   }
3378 }
3379 
3380 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
3381                                  const ARMSubtarget *Subtarget) {
3382   SDLoc dl(Op);
3383   ConstantSDNode *SSIDNode = cast<ConstantSDNode>(Op.getOperand(2));
3384   auto SSID = static_cast<SyncScope::ID>(SSIDNode->getZExtValue());
3385   if (SSID == SyncScope::SingleThread)
3386     return Op;
3387 
3388   if (!Subtarget->hasDataBarrier()) {
3389     // Some ARMv6 cpus can support data barriers with an mcr instruction.
3390     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
3391     // here.
3392     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
3393            "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
3394     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
3395                        DAG.getConstant(0, dl, MVT::i32));
3396   }
3397 
3398   ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
3399   AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
3400   ARM_MB::MemBOpt Domain = ARM_MB::ISH;
3401   if (Subtarget->isMClass()) {
3402     // Only a full system barrier exists in the M-class architectures.
3403     Domain = ARM_MB::SY;
3404   } else if (Subtarget->preferISHSTBarriers() &&
3405              Ord == AtomicOrdering::Release) {
3406     // Swift happens to implement ISHST barriers in a way that's compatible with
3407     // Release semantics but weaker than ISH so we'd be fools not to use
3408     // it. Beware: other processors probably don't!
3409     Domain = ARM_MB::ISHST;
3410   }
3411 
3412   return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
3413                      DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32),
3414                      DAG.getConstant(Domain, dl, MVT::i32));
3415 }
3416 
3417 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
3418                              const ARMSubtarget *Subtarget) {
3419   // ARM pre v5TE and Thumb1 does not have preload instructions.
3420   if (!(Subtarget->isThumb2() ||
3421         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
3422     // Just preserve the chain.
3423     return Op.getOperand(0);
3424 
3425   SDLoc dl(Op);
3426   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
3427   if (!isRead &&
3428       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
3429     // ARMv7 with MP extension has PLDW.
3430     return Op.getOperand(0);
3431 
3432   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
3433   if (Subtarget->isThumb()) {
3434     // Invert the bits.
3435     isRead = ~isRead & 1;
3436     isData = ~isData & 1;
3437   }
3438 
3439   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
3440                      Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32),
3441                      DAG.getConstant(isData, dl, MVT::i32));
3442 }
3443 
3444 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
3445   MachineFunction &MF = DAG.getMachineFunction();
3446   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
3447 
3448   // vastart just stores the address of the VarArgsFrameIndex slot into the
3449   // memory location argument.
3450   SDLoc dl(Op);
3451   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
3452   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3453   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3454   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
3455                       MachinePointerInfo(SV));
3456 }
3457 
3458 SDValue ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA,
3459                                                 CCValAssign &NextVA,
3460                                                 SDValue &Root,
3461                                                 SelectionDAG &DAG,
3462                                                 const SDLoc &dl) const {
3463   MachineFunction &MF = DAG.getMachineFunction();
3464   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3465 
3466   const TargetRegisterClass *RC;
3467   if (AFI->isThumb1OnlyFunction())
3468     RC = &ARM::tGPRRegClass;
3469   else
3470     RC = &ARM::GPRRegClass;
3471 
3472   // Transform the arguments stored in physical registers into virtual ones.
3473   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3474   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
3475 
3476   SDValue ArgValue2;
3477   if (NextVA.isMemLoc()) {
3478     MachineFrameInfo &MFI = MF.getFrameInfo();
3479     int FI = MFI.CreateFixedObject(4, NextVA.getLocMemOffset(), true);
3480 
3481     // Create load node to retrieve arguments from the stack.
3482     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3483     ArgValue2 = DAG.getLoad(
3484         MVT::i32, dl, Root, FIN,
3485         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI));
3486   } else {
3487     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
3488     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
3489   }
3490   if (!Subtarget->isLittle())
3491     std::swap (ArgValue, ArgValue2);
3492   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
3493 }
3494 
3495 // The remaining GPRs hold either the beginning of variable-argument
3496 // data, or the beginning of an aggregate passed by value (usually
3497 // byval).  Either way, we allocate stack slots adjacent to the data
3498 // provided by our caller, and store the unallocated registers there.
3499 // If this is a variadic function, the va_list pointer will begin with
3500 // these values; otherwise, this reassembles a (byval) structure that
3501 // was split between registers and memory.
3502 // Return: The frame index registers were stored into.
3503 int ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
3504                                       const SDLoc &dl, SDValue &Chain,
3505                                       const Value *OrigArg,
3506                                       unsigned InRegsParamRecordIdx,
3507                                       int ArgOffset, unsigned ArgSize) const {
3508   // Currently, two use-cases possible:
3509   // Case #1. Non-var-args function, and we meet first byval parameter.
3510   //          Setup first unallocated register as first byval register;
3511   //          eat all remained registers
3512   //          (these two actions are performed by HandleByVal method).
3513   //          Then, here, we initialize stack frame with
3514   //          "store-reg" instructions.
3515   // Case #2. Var-args function, that doesn't contain byval parameters.
3516   //          The same: eat all remained unallocated registers,
3517   //          initialize stack frame.
3518 
3519   MachineFunction &MF = DAG.getMachineFunction();
3520   MachineFrameInfo &MFI = MF.getFrameInfo();
3521   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3522   unsigned RBegin, REnd;
3523   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
3524     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
3525   } else {
3526     unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3527     RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx];
3528     REnd = ARM::R4;
3529   }
3530 
3531   if (REnd != RBegin)
3532     ArgOffset = -4 * (ARM::R4 - RBegin);
3533 
3534   auto PtrVT = getPointerTy(DAG.getDataLayout());
3535   int FrameIndex = MFI.CreateFixedObject(ArgSize, ArgOffset, false);
3536   SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT);
3537 
3538   SmallVector<SDValue, 4> MemOps;
3539   const TargetRegisterClass *RC =
3540       AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
3541 
3542   for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) {
3543     unsigned VReg = MF.addLiveIn(Reg, RC);
3544     SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
3545     SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3546                                  MachinePointerInfo(OrigArg, 4 * i));
3547     MemOps.push_back(Store);
3548     FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT));
3549   }
3550 
3551   if (!MemOps.empty())
3552     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3553   return FrameIndex;
3554 }
3555 
3556 // Setup stack frame, the va_list pointer will start from.
3557 void ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
3558                                              const SDLoc &dl, SDValue &Chain,
3559                                              unsigned ArgOffset,
3560                                              unsigned TotalArgRegsSaveSize,
3561                                              bool ForceMutable) const {
3562   MachineFunction &MF = DAG.getMachineFunction();
3563   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3564 
3565   // Try to store any remaining integer argument regs
3566   // to their spots on the stack so that they may be loaded by dereferencing
3567   // the result of va_next.
3568   // If there is no regs to be stored, just point address after last
3569   // argument passed via stack.
3570   int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
3571                                   CCInfo.getInRegsParamsCount(),
3572                                   CCInfo.getNextStackOffset(), 4);
3573   AFI->setVarArgsFrameIndex(FrameIndex);
3574 }
3575 
3576 SDValue ARMTargetLowering::LowerFormalArguments(
3577     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3578     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3579     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3580   MachineFunction &MF = DAG.getMachineFunction();
3581   MachineFrameInfo &MFI = MF.getFrameInfo();
3582 
3583   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3584 
3585   // Assign locations to all of the incoming arguments.
3586   SmallVector<CCValAssign, 16> ArgLocs;
3587   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3588                  *DAG.getContext());
3589   CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForCall(CallConv, isVarArg));
3590 
3591   SmallVector<SDValue, 16> ArgValues;
3592   SDValue ArgValue;
3593   Function::const_arg_iterator CurOrigArg = MF.getFunction().arg_begin();
3594   unsigned CurArgIdx = 0;
3595 
3596   // Initially ArgRegsSaveSize is zero.
3597   // Then we increase this value each time we meet byval parameter.
3598   // We also increase this value in case of varargs function.
3599   AFI->setArgRegsSaveSize(0);
3600 
3601   // Calculate the amount of stack space that we need to allocate to store
3602   // byval and variadic arguments that are passed in registers.
3603   // We need to know this before we allocate the first byval or variadic
3604   // argument, as they will be allocated a stack slot below the CFA (Canonical
3605   // Frame Address, the stack pointer at entry to the function).
3606   unsigned ArgRegBegin = ARM::R4;
3607   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3608     if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount())
3609       break;
3610 
3611     CCValAssign &VA = ArgLocs[i];
3612     unsigned Index = VA.getValNo();
3613     ISD::ArgFlagsTy Flags = Ins[Index].Flags;
3614     if (!Flags.isByVal())
3615       continue;
3616 
3617     assert(VA.isMemLoc() && "unexpected byval pointer in reg");
3618     unsigned RBegin, REnd;
3619     CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd);
3620     ArgRegBegin = std::min(ArgRegBegin, RBegin);
3621 
3622     CCInfo.nextInRegsParam();
3623   }
3624   CCInfo.rewindByValRegsInfo();
3625 
3626   int lastInsIndex = -1;
3627   if (isVarArg && MFI.hasVAStart()) {
3628     unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3629     if (RegIdx != array_lengthof(GPRArgRegs))
3630       ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]);
3631   }
3632 
3633   unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin);
3634   AFI->setArgRegsSaveSize(TotalArgRegsSaveSize);
3635   auto PtrVT = getPointerTy(DAG.getDataLayout());
3636 
3637   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3638     CCValAssign &VA = ArgLocs[i];
3639     if (Ins[VA.getValNo()].isOrigArg()) {
3640       std::advance(CurOrigArg,
3641                    Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx);
3642       CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex();
3643     }
3644     // Arguments stored in registers.
3645     if (VA.isRegLoc()) {
3646       EVT RegVT = VA.getLocVT();
3647 
3648       if (VA.needsCustom()) {
3649         // f64 and vector types are split up into multiple registers or
3650         // combinations of registers and stack slots.
3651         if (VA.getLocVT() == MVT::v2f64) {
3652           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
3653                                                    Chain, DAG, dl);
3654           VA = ArgLocs[++i]; // skip ahead to next loc
3655           SDValue ArgValue2;
3656           if (VA.isMemLoc()) {
3657             int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), true);
3658             SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3659             ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
3660                                     MachinePointerInfo::getFixedStack(
3661                                         DAG.getMachineFunction(), FI));
3662           } else {
3663             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3664                                              Chain, DAG, dl);
3665           }
3666           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3667           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3668                                  ArgValue, ArgValue1,
3669                                  DAG.getIntPtrConstant(0, dl));
3670           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3671                                  ArgValue, ArgValue2,
3672                                  DAG.getIntPtrConstant(1, dl));
3673         } else
3674           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3675       } else {
3676         const TargetRegisterClass *RC;
3677 
3678         if (RegVT == MVT::f32)
3679           RC = &ARM::SPRRegClass;
3680         else if (RegVT == MVT::f64)
3681           RC = &ARM::DPRRegClass;
3682         else if (RegVT == MVT::v2f64)
3683           RC = &ARM::QPRRegClass;
3684         else if (RegVT == MVT::i32)
3685           RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass
3686                                            : &ARM::GPRRegClass;
3687         else
3688           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3689 
3690         // Transform the arguments in physical registers into virtual ones.
3691         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3692         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3693       }
3694 
3695       // If this is an 8 or 16-bit value, it is really passed promoted
3696       // to 32 bits.  Insert an assert[sz]ext to capture this, then
3697       // truncate to the right size.
3698       switch (VA.getLocInfo()) {
3699       default: llvm_unreachable("Unknown loc info!");
3700       case CCValAssign::Full: break;
3701       case CCValAssign::BCvt:
3702         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3703         break;
3704       case CCValAssign::SExt:
3705         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3706                                DAG.getValueType(VA.getValVT()));
3707         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3708         break;
3709       case CCValAssign::ZExt:
3710         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3711                                DAG.getValueType(VA.getValVT()));
3712         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3713         break;
3714       }
3715 
3716       InVals.push_back(ArgValue);
3717     } else { // VA.isRegLoc()
3718       // sanity check
3719       assert(VA.isMemLoc());
3720       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3721 
3722       int index = VA.getValNo();
3723 
3724       // Some Ins[] entries become multiple ArgLoc[] entries.
3725       // Process them only once.
3726       if (index != lastInsIndex)
3727         {
3728           ISD::ArgFlagsTy Flags = Ins[index].Flags;
3729           // FIXME: For now, all byval parameter objects are marked mutable.
3730           // This can be changed with more analysis.
3731           // In case of tail call optimization mark all arguments mutable.
3732           // Since they could be overwritten by lowering of arguments in case of
3733           // a tail call.
3734           if (Flags.isByVal()) {
3735             assert(Ins[index].isOrigArg() &&
3736                    "Byval arguments cannot be implicit");
3737             unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed();
3738 
3739             int FrameIndex = StoreByValRegs(
3740                 CCInfo, DAG, dl, Chain, &*CurOrigArg, CurByValIndex,
3741                 VA.getLocMemOffset(), Flags.getByValSize());
3742             InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT));
3743             CCInfo.nextInRegsParam();
3744           } else {
3745             unsigned FIOffset = VA.getLocMemOffset();
3746             int FI = MFI.CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3747                                            FIOffset, true);
3748 
3749             // Create load nodes to retrieve arguments from the stack.
3750             SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3751             InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3752                                          MachinePointerInfo::getFixedStack(
3753                                              DAG.getMachineFunction(), FI)));
3754           }
3755           lastInsIndex = index;
3756         }
3757     }
3758   }
3759 
3760   // varargs
3761   if (isVarArg && MFI.hasVAStart())
3762     VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3763                          CCInfo.getNextStackOffset(),
3764                          TotalArgRegsSaveSize);
3765 
3766   AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3767 
3768   return Chain;
3769 }
3770 
3771 /// isFloatingPointZero - Return true if this is +0.0.
3772 static bool isFloatingPointZero(SDValue Op) {
3773   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3774     return CFP->getValueAPF().isPosZero();
3775   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3776     // Maybe this has already been legalized into the constant pool?
3777     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3778       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3779       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3780         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3781           return CFP->getValueAPF().isPosZero();
3782     }
3783   } else if (Op->getOpcode() == ISD::BITCAST &&
3784              Op->getValueType(0) == MVT::f64) {
3785     // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64)
3786     // created by LowerConstantFP().
3787     SDValue BitcastOp = Op->getOperand(0);
3788     if (BitcastOp->getOpcode() == ARMISD::VMOVIMM &&
3789         isNullConstant(BitcastOp->getOperand(0)))
3790       return true;
3791   }
3792   return false;
3793 }
3794 
3795 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3796 /// the given operands.
3797 SDValue ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3798                                      SDValue &ARMcc, SelectionDAG &DAG,
3799                                      const SDLoc &dl) const {
3800   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3801     unsigned C = RHSC->getZExtValue();
3802     if (!isLegalICmpImmediate(C)) {
3803       // Constant does not fit, try adjusting it by one?
3804       switch (CC) {
3805       default: break;
3806       case ISD::SETLT:
3807       case ISD::SETGE:
3808         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3809           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3810           RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3811         }
3812         break;
3813       case ISD::SETULT:
3814       case ISD::SETUGE:
3815         if (C != 0 && isLegalICmpImmediate(C-1)) {
3816           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3817           RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3818         }
3819         break;
3820       case ISD::SETLE:
3821       case ISD::SETGT:
3822         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3823           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3824           RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3825         }
3826         break;
3827       case ISD::SETULE:
3828       case ISD::SETUGT:
3829         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3830           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3831           RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3832         }
3833         break;
3834       }
3835     }
3836   } else if ((ARM_AM::getShiftOpcForNode(LHS.getOpcode()) != ARM_AM::no_shift) &&
3837              (ARM_AM::getShiftOpcForNode(RHS.getOpcode()) == ARM_AM::no_shift)) {
3838     // In ARM and Thumb-2, the compare instructions can shift their second
3839     // operand.
3840     CC = ISD::getSetCCSwappedOperands(CC);
3841     std::swap(LHS, RHS);
3842   }
3843 
3844   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3845   ARMISD::NodeType CompareType;
3846   switch (CondCode) {
3847   default:
3848     CompareType = ARMISD::CMP;
3849     break;
3850   case ARMCC::EQ:
3851   case ARMCC::NE:
3852     // Uses only Z Flag
3853     CompareType = ARMISD::CMPZ;
3854     break;
3855   }
3856   ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3857   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3858 }
3859 
3860 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3861 SDValue ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS,
3862                                      SelectionDAG &DAG, const SDLoc &dl,
3863                                      bool InvalidOnQNaN) const {
3864   assert(!Subtarget->isFPOnlySP() || RHS.getValueType() != MVT::f64);
3865   SDValue Cmp;
3866   SDValue C = DAG.getConstant(InvalidOnQNaN, dl, MVT::i32);
3867   if (!isFloatingPointZero(RHS))
3868     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS, C);
3869   else
3870     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS, C);
3871   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3872 }
3873 
3874 /// duplicateCmp - Glue values can have only one use, so this function
3875 /// duplicates a comparison node.
3876 SDValue
3877 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3878   unsigned Opc = Cmp.getOpcode();
3879   SDLoc DL(Cmp);
3880   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3881     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3882 
3883   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3884   Cmp = Cmp.getOperand(0);
3885   Opc = Cmp.getOpcode();
3886   if (Opc == ARMISD::CMPFP)
3887     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),
3888                       Cmp.getOperand(1), Cmp.getOperand(2));
3889   else {
3890     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3891     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),
3892                       Cmp.getOperand(1));
3893   }
3894   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3895 }
3896 
3897 // This function returns three things: the arithmetic computation itself
3898 // (Value), a comparison (OverflowCmp), and a condition code (ARMcc).  The
3899 // comparison and the condition code define the case in which the arithmetic
3900 // computation *does not* overflow.
3901 std::pair<SDValue, SDValue>
3902 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
3903                                  SDValue &ARMcc) const {
3904   assert(Op.getValueType() == MVT::i32 &&  "Unsupported value type");
3905 
3906   SDValue Value, OverflowCmp;
3907   SDValue LHS = Op.getOperand(0);
3908   SDValue RHS = Op.getOperand(1);
3909   SDLoc dl(Op);
3910 
3911   // FIXME: We are currently always generating CMPs because we don't support
3912   // generating CMN through the backend. This is not as good as the natural
3913   // CMP case because it causes a register dependency and cannot be folded
3914   // later.
3915 
3916   switch (Op.getOpcode()) {
3917   default:
3918     llvm_unreachable("Unknown overflow instruction!");
3919   case ISD::SADDO:
3920     ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3921     Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3922     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3923     break;
3924   case ISD::UADDO:
3925     ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3926     // We use ADDC here to correspond to its use in LowerUnsignedALUO.
3927     // We do not use it in the USUBO case as Value may not be used.
3928     Value = DAG.getNode(ARMISD::ADDC, dl,
3929                         DAG.getVTList(Op.getValueType(), MVT::i32), LHS, RHS)
3930                 .getValue(0);
3931     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3932     break;
3933   case ISD::SSUBO:
3934     ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3935     Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3936     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3937     break;
3938   case ISD::USUBO:
3939     ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3940     Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3941     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3942     break;
3943   } // switch (...)
3944 
3945   return std::make_pair(Value, OverflowCmp);
3946 }
3947 
3948 SDValue
3949 ARMTargetLowering::LowerSignedALUO(SDValue Op, SelectionDAG &DAG) const {
3950   // Let legalize expand this if it isn't a legal type yet.
3951   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
3952     return SDValue();
3953 
3954   SDValue Value, OverflowCmp;
3955   SDValue ARMcc;
3956   std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
3957   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3958   SDLoc dl(Op);
3959   // We use 0 and 1 as false and true values.
3960   SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
3961   SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
3962   EVT VT = Op.getValueType();
3963 
3964   SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal,
3965                                  ARMcc, CCR, OverflowCmp);
3966 
3967   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
3968   return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
3969 }
3970 
3971 static SDValue ConvertBooleanCarryToCarryFlag(SDValue BoolCarry,
3972                                               SelectionDAG &DAG) {
3973   SDLoc DL(BoolCarry);
3974   EVT CarryVT = BoolCarry.getValueType();
3975 
3976   APInt NegOne = APInt::getAllOnesValue(CarryVT.getScalarSizeInBits());
3977   // This converts the boolean value carry into the carry flag by doing
3978   // ARMISD::ADDC Carry, ~0
3979   return DAG.getNode(ARMISD::ADDC, DL, DAG.getVTList(CarryVT, MVT::i32),
3980                      BoolCarry, DAG.getConstant(NegOne, DL, CarryVT));
3981 }
3982 
3983 static SDValue ConvertCarryFlagToBooleanCarry(SDValue Flags, EVT VT,
3984                                               SelectionDAG &DAG) {
3985   SDLoc DL(Flags);
3986 
3987   // Now convert the carry flag into a boolean carry. We do this
3988   // using ARMISD:ADDE 0, 0, Carry
3989   return DAG.getNode(ARMISD::ADDE, DL, DAG.getVTList(VT, MVT::i32),
3990                      DAG.getConstant(0, DL, MVT::i32),
3991                      DAG.getConstant(0, DL, MVT::i32), Flags);
3992 }
3993 
3994 SDValue ARMTargetLowering::LowerUnsignedALUO(SDValue Op,
3995                                              SelectionDAG &DAG) const {
3996   // Let legalize expand this if it isn't a legal type yet.
3997   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
3998     return SDValue();
3999 
4000   SDValue LHS = Op.getOperand(0);
4001   SDValue RHS = Op.getOperand(1);
4002   SDLoc dl(Op);
4003 
4004   EVT VT = Op.getValueType();
4005   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
4006   SDValue Value;
4007   SDValue Overflow;
4008   switch (Op.getOpcode()) {
4009   default:
4010     llvm_unreachable("Unknown overflow instruction!");
4011   case ISD::UADDO:
4012     Value = DAG.getNode(ARMISD::ADDC, dl, VTs, LHS, RHS);
4013     // Convert the carry flag into a boolean value.
4014     Overflow = ConvertCarryFlagToBooleanCarry(Value.getValue(1), VT, DAG);
4015     break;
4016   case ISD::USUBO: {
4017     Value = DAG.getNode(ARMISD::SUBC, dl, VTs, LHS, RHS);
4018     // Convert the carry flag into a boolean value.
4019     Overflow = ConvertCarryFlagToBooleanCarry(Value.getValue(1), VT, DAG);
4020     // ARMISD::SUBC returns 0 when we have to borrow, so make it an overflow
4021     // value. So compute 1 - C.
4022     Overflow = DAG.getNode(ISD::SUB, dl, MVT::i32,
4023                            DAG.getConstant(1, dl, MVT::i32), Overflow);
4024     break;
4025   }
4026   }
4027 
4028   return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
4029 }
4030 
4031 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
4032   SDValue Cond = Op.getOperand(0);
4033   SDValue SelectTrue = Op.getOperand(1);
4034   SDValue SelectFalse = Op.getOperand(2);
4035   SDLoc dl(Op);
4036   unsigned Opc = Cond.getOpcode();
4037 
4038   if (Cond.getResNo() == 1 &&
4039       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
4040        Opc == ISD::USUBO)) {
4041     if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
4042       return SDValue();
4043 
4044     SDValue Value, OverflowCmp;
4045     SDValue ARMcc;
4046     std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
4047     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4048     EVT VT = Op.getValueType();
4049 
4050     return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR,
4051                    OverflowCmp, DAG);
4052   }
4053 
4054   // Convert:
4055   //
4056   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
4057   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
4058   //
4059   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
4060     const ConstantSDNode *CMOVTrue =
4061       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
4062     const ConstantSDNode *CMOVFalse =
4063       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
4064 
4065     if (CMOVTrue && CMOVFalse) {
4066       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
4067       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
4068 
4069       SDValue True;
4070       SDValue False;
4071       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
4072         True = SelectTrue;
4073         False = SelectFalse;
4074       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
4075         True = SelectFalse;
4076         False = SelectTrue;
4077       }
4078 
4079       if (True.getNode() && False.getNode()) {
4080         EVT VT = Op.getValueType();
4081         SDValue ARMcc = Cond.getOperand(2);
4082         SDValue CCR = Cond.getOperand(3);
4083         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
4084         assert(True.getValueType() == VT);
4085         return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG);
4086       }
4087     }
4088   }
4089 
4090   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
4091   // undefined bits before doing a full-word comparison with zero.
4092   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
4093                      DAG.getConstant(1, dl, Cond.getValueType()));
4094 
4095   return DAG.getSelectCC(dl, Cond,
4096                          DAG.getConstant(0, dl, Cond.getValueType()),
4097                          SelectTrue, SelectFalse, ISD::SETNE);
4098 }
4099 
4100 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
4101                                  bool &swpCmpOps, bool &swpVselOps) {
4102   // Start by selecting the GE condition code for opcodes that return true for
4103   // 'equality'
4104   if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
4105       CC == ISD::SETULE)
4106     CondCode = ARMCC::GE;
4107 
4108   // and GT for opcodes that return false for 'equality'.
4109   else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
4110            CC == ISD::SETULT)
4111     CondCode = ARMCC::GT;
4112 
4113   // Since we are constrained to GE/GT, if the opcode contains 'less', we need
4114   // to swap the compare operands.
4115   if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
4116       CC == ISD::SETULT)
4117     swpCmpOps = true;
4118 
4119   // Both GT and GE are ordered comparisons, and return false for 'unordered'.
4120   // If we have an unordered opcode, we need to swap the operands to the VSEL
4121   // instruction (effectively negating the condition).
4122   //
4123   // This also has the effect of swapping which one of 'less' or 'greater'
4124   // returns true, so we also swap the compare operands. It also switches
4125   // whether we return true for 'equality', so we compensate by picking the
4126   // opposite condition code to our original choice.
4127   if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
4128       CC == ISD::SETUGT) {
4129     swpCmpOps = !swpCmpOps;
4130     swpVselOps = !swpVselOps;
4131     CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
4132   }
4133 
4134   // 'ordered' is 'anything but unordered', so use the VS condition code and
4135   // swap the VSEL operands.
4136   if (CC == ISD::SETO) {
4137     CondCode = ARMCC::VS;
4138     swpVselOps = true;
4139   }
4140 
4141   // 'unordered or not equal' is 'anything but equal', so use the EQ condition
4142   // code and swap the VSEL operands.
4143   if (CC == ISD::SETUNE) {
4144     CondCode = ARMCC::EQ;
4145     swpVselOps = true;
4146   }
4147 }
4148 
4149 SDValue ARMTargetLowering::getCMOV(const SDLoc &dl, EVT VT, SDValue FalseVal,
4150                                    SDValue TrueVal, SDValue ARMcc, SDValue CCR,
4151                                    SDValue Cmp, SelectionDAG &DAG) const {
4152   if (Subtarget->isFPOnlySP() && VT == MVT::f64) {
4153     FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl,
4154                            DAG.getVTList(MVT::i32, MVT::i32), FalseVal);
4155     TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl,
4156                           DAG.getVTList(MVT::i32, MVT::i32), TrueVal);
4157 
4158     SDValue TrueLow = TrueVal.getValue(0);
4159     SDValue TrueHigh = TrueVal.getValue(1);
4160     SDValue FalseLow = FalseVal.getValue(0);
4161     SDValue FalseHigh = FalseVal.getValue(1);
4162 
4163     SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow,
4164                               ARMcc, CCR, Cmp);
4165     SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh,
4166                                ARMcc, CCR, duplicateCmp(Cmp, DAG));
4167 
4168     return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High);
4169   } else {
4170     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
4171                        Cmp);
4172   }
4173 }
4174 
4175 static bool isGTorGE(ISD::CondCode CC) {
4176   return CC == ISD::SETGT || CC == ISD::SETGE;
4177 }
4178 
4179 static bool isLTorLE(ISD::CondCode CC) {
4180   return CC == ISD::SETLT || CC == ISD::SETLE;
4181 }
4182 
4183 // See if a conditional (LHS CC RHS ? TrueVal : FalseVal) is lower-saturating.
4184 // All of these conditions (and their <= and >= counterparts) will do:
4185 //          x < k ? k : x
4186 //          x > k ? x : k
4187 //          k < x ? x : k
4188 //          k > x ? k : x
4189 static bool isLowerSaturate(const SDValue LHS, const SDValue RHS,
4190                             const SDValue TrueVal, const SDValue FalseVal,
4191                             const ISD::CondCode CC, const SDValue K) {
4192   return (isGTorGE(CC) &&
4193           ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal))) ||
4194          (isLTorLE(CC) &&
4195           ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal)));
4196 }
4197 
4198 // Similar to isLowerSaturate(), but checks for upper-saturating conditions.
4199 static bool isUpperSaturate(const SDValue LHS, const SDValue RHS,
4200                             const SDValue TrueVal, const SDValue FalseVal,
4201                             const ISD::CondCode CC, const SDValue K) {
4202   return (isGTorGE(CC) &&
4203           ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal))) ||
4204          (isLTorLE(CC) &&
4205           ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal)));
4206 }
4207 
4208 // Check if two chained conditionals could be converted into SSAT or USAT.
4209 //
4210 // SSAT can replace a set of two conditional selectors that bound a number to an
4211 // interval of type [k, ~k] when k + 1 is a power of 2. Here are some examples:
4212 //
4213 //     x < -k ? -k : (x > k ? k : x)
4214 //     x < -k ? -k : (x < k ? x : k)
4215 //     x > -k ? (x > k ? k : x) : -k
4216 //     x < k ? (x < -k ? -k : x) : k
4217 //     etc.
4218 //
4219 // USAT works similarily to SSAT but bounds on the interval [0, k] where k + 1 is
4220 // a power of 2.
4221 //
4222 // It returns true if the conversion can be done, false otherwise.
4223 // Additionally, the variable is returned in parameter V, the constant in K and
4224 // usat is set to true if the conditional represents an unsigned saturation
4225 static bool isSaturatingConditional(const SDValue &Op, SDValue &V,
4226                                     uint64_t &K, bool &usat) {
4227   SDValue LHS1 = Op.getOperand(0);
4228   SDValue RHS1 = Op.getOperand(1);
4229   SDValue TrueVal1 = Op.getOperand(2);
4230   SDValue FalseVal1 = Op.getOperand(3);
4231   ISD::CondCode CC1 = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4232 
4233   const SDValue Op2 = isa<ConstantSDNode>(TrueVal1) ? FalseVal1 : TrueVal1;
4234   if (Op2.getOpcode() != ISD::SELECT_CC)
4235     return false;
4236 
4237   SDValue LHS2 = Op2.getOperand(0);
4238   SDValue RHS2 = Op2.getOperand(1);
4239   SDValue TrueVal2 = Op2.getOperand(2);
4240   SDValue FalseVal2 = Op2.getOperand(3);
4241   ISD::CondCode CC2 = cast<CondCodeSDNode>(Op2.getOperand(4))->get();
4242 
4243   // Find out which are the constants and which are the variables
4244   // in each conditional
4245   SDValue *K1 = isa<ConstantSDNode>(LHS1) ? &LHS1 : isa<ConstantSDNode>(RHS1)
4246                                                         ? &RHS1
4247                                                         : nullptr;
4248   SDValue *K2 = isa<ConstantSDNode>(LHS2) ? &LHS2 : isa<ConstantSDNode>(RHS2)
4249                                                         ? &RHS2
4250                                                         : nullptr;
4251   SDValue K2Tmp = isa<ConstantSDNode>(TrueVal2) ? TrueVal2 : FalseVal2;
4252   SDValue V1Tmp = (K1 && *K1 == LHS1) ? RHS1 : LHS1;
4253   SDValue V2Tmp = (K2 && *K2 == LHS2) ? RHS2 : LHS2;
4254   SDValue V2 = (K2Tmp == TrueVal2) ? FalseVal2 : TrueVal2;
4255 
4256   // We must detect cases where the original operations worked with 16- or
4257   // 8-bit values. In such case, V2Tmp != V2 because the comparison operations
4258   // must work with sign-extended values but the select operations return
4259   // the original non-extended value.
4260   SDValue V2TmpReg = V2Tmp;
4261   if (V2Tmp->getOpcode() == ISD::SIGN_EXTEND_INREG)
4262     V2TmpReg = V2Tmp->getOperand(0);
4263 
4264   // Check that the registers and the constants have the correct values
4265   // in both conditionals
4266   if (!K1 || !K2 || *K1 == Op2 || *K2 != K2Tmp || V1Tmp != V2Tmp ||
4267       V2TmpReg != V2)
4268     return false;
4269 
4270   // Figure out which conditional is saturating the lower/upper bound.
4271   const SDValue *LowerCheckOp =
4272       isLowerSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1)
4273           ? &Op
4274           : isLowerSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2)
4275                 ? &Op2
4276                 : nullptr;
4277   const SDValue *UpperCheckOp =
4278       isUpperSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1)
4279           ? &Op
4280           : isUpperSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2)
4281                 ? &Op2
4282                 : nullptr;
4283 
4284   if (!UpperCheckOp || !LowerCheckOp || LowerCheckOp == UpperCheckOp)
4285     return false;
4286 
4287   // Check that the constant in the lower-bound check is
4288   // the opposite of the constant in the upper-bound check
4289   // in 1's complement.
4290   int64_t Val1 = cast<ConstantSDNode>(*K1)->getSExtValue();
4291   int64_t Val2 = cast<ConstantSDNode>(*K2)->getSExtValue();
4292   int64_t PosVal = std::max(Val1, Val2);
4293   int64_t NegVal = std::min(Val1, Val2);
4294 
4295   if (((Val1 > Val2 && UpperCheckOp == &Op) ||
4296        (Val1 < Val2 && UpperCheckOp == &Op2)) &&
4297       isPowerOf2_64(PosVal + 1)) {
4298 
4299     // Handle the difference between USAT (unsigned) and SSAT (signed) saturation
4300     if (Val1 == ~Val2)
4301       usat = false;
4302     else if (NegVal == 0)
4303       usat = true;
4304     else
4305       return false;
4306 
4307     V = V2;
4308     K = (uint64_t)PosVal; // At this point, PosVal is guaranteed to be positive
4309 
4310     return true;
4311   }
4312 
4313   return false;
4314 }
4315 
4316 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
4317   EVT VT = Op.getValueType();
4318   SDLoc dl(Op);
4319 
4320   // Try to convert two saturating conditional selects into a single SSAT
4321   SDValue SatValue;
4322   uint64_t SatConstant;
4323   bool SatUSat;
4324   if (((!Subtarget->isThumb() && Subtarget->hasV6Ops()) || Subtarget->isThumb2()) &&
4325       isSaturatingConditional(Op, SatValue, SatConstant, SatUSat)) {
4326     if (SatUSat)
4327       return DAG.getNode(ARMISD::USAT, dl, VT, SatValue,
4328                          DAG.getConstant(countTrailingOnes(SatConstant), dl, VT));
4329     else
4330       return DAG.getNode(ARMISD::SSAT, dl, VT, SatValue,
4331                          DAG.getConstant(countTrailingOnes(SatConstant), dl, VT));
4332   }
4333 
4334   SDValue LHS = Op.getOperand(0);
4335   SDValue RHS = Op.getOperand(1);
4336   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4337   SDValue TrueVal = Op.getOperand(2);
4338   SDValue FalseVal = Op.getOperand(3);
4339 
4340   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
4341     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
4342                                                     dl);
4343 
4344     // If softenSetCCOperands only returned one value, we should compare it to
4345     // zero.
4346     if (!RHS.getNode()) {
4347       RHS = DAG.getConstant(0, dl, LHS.getValueType());
4348       CC = ISD::SETNE;
4349     }
4350   }
4351 
4352   if (LHS.getValueType() == MVT::i32) {
4353     // Try to generate VSEL on ARMv8.
4354     // The VSEL instruction can't use all the usual ARM condition
4355     // codes: it only has two bits to select the condition code, so it's
4356     // constrained to use only GE, GT, VS and EQ.
4357     //
4358     // To implement all the various ISD::SETXXX opcodes, we sometimes need to
4359     // swap the operands of the previous compare instruction (effectively
4360     // inverting the compare condition, swapping 'less' and 'greater') and
4361     // sometimes need to swap the operands to the VSEL (which inverts the
4362     // condition in the sense of firing whenever the previous condition didn't)
4363     if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
4364                                     TrueVal.getValueType() == MVT::f64)) {
4365       ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
4366       if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
4367           CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
4368         CC = ISD::getSetCCInverse(CC, true);
4369         std::swap(TrueVal, FalseVal);
4370       }
4371     }
4372 
4373     SDValue ARMcc;
4374     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4375     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
4376     return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
4377   }
4378 
4379   ARMCC::CondCodes CondCode, CondCode2;
4380   bool InvalidOnQNaN;
4381   FPCCToARMCC(CC, CondCode, CondCode2, InvalidOnQNaN);
4382 
4383   // Try to generate VMAXNM/VMINNM on ARMv8.
4384   if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
4385                                   TrueVal.getValueType() == MVT::f64)) {
4386     bool swpCmpOps = false;
4387     bool swpVselOps = false;
4388     checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
4389 
4390     if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
4391         CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
4392       if (swpCmpOps)
4393         std::swap(LHS, RHS);
4394       if (swpVselOps)
4395         std::swap(TrueVal, FalseVal);
4396     }
4397   }
4398 
4399   SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
4400   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN);
4401   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4402   SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
4403   if (CondCode2 != ARMCC::AL) {
4404     SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32);
4405     // FIXME: Needs another CMP because flag can have but one use.
4406     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN);
4407     Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG);
4408   }
4409   return Result;
4410 }
4411 
4412 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
4413 /// to morph to an integer compare sequence.
4414 static bool canChangeToInt(SDValue Op, bool &SeenZero,
4415                            const ARMSubtarget *Subtarget) {
4416   SDNode *N = Op.getNode();
4417   if (!N->hasOneUse())
4418     // Otherwise it requires moving the value from fp to integer registers.
4419     return false;
4420   if (!N->getNumValues())
4421     return false;
4422   EVT VT = Op.getValueType();
4423   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
4424     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
4425     // vmrs are very slow, e.g. cortex-a8.
4426     return false;
4427 
4428   if (isFloatingPointZero(Op)) {
4429     SeenZero = true;
4430     return true;
4431   }
4432   return ISD::isNormalLoad(N);
4433 }
4434 
4435 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
4436   if (isFloatingPointZero(Op))
4437     return DAG.getConstant(0, SDLoc(Op), MVT::i32);
4438 
4439   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
4440     return DAG.getLoad(MVT::i32, SDLoc(Op), Ld->getChain(), Ld->getBasePtr(),
4441                        Ld->getPointerInfo(), Ld->getAlignment(),
4442                        Ld->getMemOperand()->getFlags());
4443 
4444   llvm_unreachable("Unknown VFP cmp argument!");
4445 }
4446 
4447 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
4448                            SDValue &RetVal1, SDValue &RetVal2) {
4449   SDLoc dl(Op);
4450 
4451   if (isFloatingPointZero(Op)) {
4452     RetVal1 = DAG.getConstant(0, dl, MVT::i32);
4453     RetVal2 = DAG.getConstant(0, dl, MVT::i32);
4454     return;
4455   }
4456 
4457   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
4458     SDValue Ptr = Ld->getBasePtr();
4459     RetVal1 =
4460         DAG.getLoad(MVT::i32, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
4461                     Ld->getAlignment(), Ld->getMemOperand()->getFlags());
4462 
4463     EVT PtrType = Ptr.getValueType();
4464     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
4465     SDValue NewPtr = DAG.getNode(ISD::ADD, dl,
4466                                  PtrType, Ptr, DAG.getConstant(4, dl, PtrType));
4467     RetVal2 = DAG.getLoad(MVT::i32, dl, Ld->getChain(), NewPtr,
4468                           Ld->getPointerInfo().getWithOffset(4), NewAlign,
4469                           Ld->getMemOperand()->getFlags());
4470     return;
4471   }
4472 
4473   llvm_unreachable("Unknown VFP cmp argument!");
4474 }
4475 
4476 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
4477 /// f32 and even f64 comparisons to integer ones.
4478 SDValue
4479 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
4480   SDValue Chain = Op.getOperand(0);
4481   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
4482   SDValue LHS = Op.getOperand(2);
4483   SDValue RHS = Op.getOperand(3);
4484   SDValue Dest = Op.getOperand(4);
4485   SDLoc dl(Op);
4486 
4487   bool LHSSeenZero = false;
4488   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
4489   bool RHSSeenZero = false;
4490   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
4491   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
4492     // If unsafe fp math optimization is enabled and there are no other uses of
4493     // the CMP operands, and the condition code is EQ or NE, we can optimize it
4494     // to an integer comparison.
4495     if (CC == ISD::SETOEQ)
4496       CC = ISD::SETEQ;
4497     else if (CC == ISD::SETUNE)
4498       CC = ISD::SETNE;
4499 
4500     SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32);
4501     SDValue ARMcc;
4502     if (LHS.getValueType() == MVT::f32) {
4503       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
4504                         bitcastf32Toi32(LHS, DAG), Mask);
4505       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
4506                         bitcastf32Toi32(RHS, DAG), Mask);
4507       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
4508       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4509       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
4510                          Chain, Dest, ARMcc, CCR, Cmp);
4511     }
4512 
4513     SDValue LHS1, LHS2;
4514     SDValue RHS1, RHS2;
4515     expandf64Toi32(LHS, DAG, LHS1, LHS2);
4516     expandf64Toi32(RHS, DAG, RHS1, RHS2);
4517     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
4518     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
4519     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
4520     ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
4521     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
4522     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
4523     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
4524   }
4525 
4526   return SDValue();
4527 }
4528 
4529 SDValue ARMTargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
4530   SDValue Chain = Op.getOperand(0);
4531   SDValue Cond = Op.getOperand(1);
4532   SDValue Dest = Op.getOperand(2);
4533   SDLoc dl(Op);
4534 
4535   // Optimize {s|u}{add|sub}.with.overflow feeding into a branch instruction.
4536   unsigned Opc = Cond.getOpcode();
4537   if (Cond.getResNo() == 1 && (Opc == ISD::SADDO || Opc == ISD::UADDO ||
4538                                Opc == ISD::SSUBO || Opc == ISD::USUBO)) {
4539     // Only lower legal XALUO ops.
4540     if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
4541       return SDValue();
4542 
4543     // The actual operation with overflow check.
4544     SDValue Value, OverflowCmp;
4545     SDValue ARMcc;
4546     std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
4547 
4548     // Reverse the condition code.
4549     ARMCC::CondCodes CondCode =
4550         (ARMCC::CondCodes)cast<const ConstantSDNode>(ARMcc)->getZExtValue();
4551     CondCode = ARMCC::getOppositeCondition(CondCode);
4552     ARMcc = DAG.getConstant(CondCode, SDLoc(ARMcc), MVT::i32);
4553     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4554 
4555     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc, CCR,
4556                        OverflowCmp);
4557   }
4558 
4559   return SDValue();
4560 }
4561 
4562 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
4563   SDValue Chain = Op.getOperand(0);
4564   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
4565   SDValue LHS = Op.getOperand(2);
4566   SDValue RHS = Op.getOperand(3);
4567   SDValue Dest = Op.getOperand(4);
4568   SDLoc dl(Op);
4569 
4570   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
4571     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
4572                                                     dl);
4573 
4574     // If softenSetCCOperands only returned one value, we should compare it to
4575     // zero.
4576     if (!RHS.getNode()) {
4577       RHS = DAG.getConstant(0, dl, LHS.getValueType());
4578       CC = ISD::SETNE;
4579     }
4580   }
4581 
4582   // Optimize {s|u}{add|sub}.with.overflow feeding into a branch instruction.
4583   unsigned Opc = LHS.getOpcode();
4584   if (LHS.getResNo() == 1 && (isOneConstant(RHS) || isNullConstant(RHS)) &&
4585       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
4586        Opc == ISD::USUBO) && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
4587     // Only lower legal XALUO ops.
4588     if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
4589       return SDValue();
4590 
4591     // The actual operation with overflow check.
4592     SDValue Value, OverflowCmp;
4593     SDValue ARMcc;
4594     std::tie(Value, OverflowCmp) = getARMXALUOOp(LHS.getValue(0), DAG, ARMcc);
4595 
4596     if ((CC == ISD::SETNE) != isOneConstant(RHS)) {
4597       // Reverse the condition code.
4598       ARMCC::CondCodes CondCode =
4599           (ARMCC::CondCodes)cast<const ConstantSDNode>(ARMcc)->getZExtValue();
4600       CondCode = ARMCC::getOppositeCondition(CondCode);
4601       ARMcc = DAG.getConstant(CondCode, SDLoc(ARMcc), MVT::i32);
4602     }
4603     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4604 
4605     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc, CCR,
4606                        OverflowCmp);
4607   }
4608 
4609   if (LHS.getValueType() == MVT::i32) {
4610     SDValue ARMcc;
4611     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
4612     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4613     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
4614                        Chain, Dest, ARMcc, CCR, Cmp);
4615   }
4616 
4617   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
4618 
4619   if (getTargetMachine().Options.UnsafeFPMath &&
4620       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
4621        CC == ISD::SETNE || CC == ISD::SETUNE)) {
4622     if (SDValue Result = OptimizeVFPBrcond(Op, DAG))
4623       return Result;
4624   }
4625 
4626   ARMCC::CondCodes CondCode, CondCode2;
4627   bool InvalidOnQNaN;
4628   FPCCToARMCC(CC, CondCode, CondCode2, InvalidOnQNaN);
4629 
4630   SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
4631   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN);
4632   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4633   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
4634   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
4635   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
4636   if (CondCode2 != ARMCC::AL) {
4637     ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32);
4638     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
4639     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
4640   }
4641   return Res;
4642 }
4643 
4644 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
4645   SDValue Chain = Op.getOperand(0);
4646   SDValue Table = Op.getOperand(1);
4647   SDValue Index = Op.getOperand(2);
4648   SDLoc dl(Op);
4649 
4650   EVT PTy = getPointerTy(DAG.getDataLayout());
4651   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
4652   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
4653   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI);
4654   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy));
4655   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Table, Index);
4656   if (Subtarget->isThumb2() || (Subtarget->hasV8MBaselineOps() && Subtarget->isThumb())) {
4657     // Thumb2 and ARMv8-M use a two-level jump. That is, it jumps into the jump table
4658     // which does another jump to the destination. This also makes it easier
4659     // to translate it to TBB / TBH later (Thumb2 only).
4660     // FIXME: This might not work if the function is extremely large.
4661     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
4662                        Addr, Op.getOperand(2), JTI);
4663   }
4664   if (isPositionIndependent() || Subtarget->isROPI()) {
4665     Addr =
4666         DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
4667                     MachinePointerInfo::getJumpTable(DAG.getMachineFunction()));
4668     Chain = Addr.getValue(1);
4669     Addr = DAG.getNode(ISD::ADD, dl, PTy, Table, Addr);
4670     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
4671   } else {
4672     Addr =
4673         DAG.getLoad(PTy, dl, Chain, Addr,
4674                     MachinePointerInfo::getJumpTable(DAG.getMachineFunction()));
4675     Chain = Addr.getValue(1);
4676     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
4677   }
4678 }
4679 
4680 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
4681   EVT VT = Op.getValueType();
4682   SDLoc dl(Op);
4683 
4684   if (Op.getValueType().getVectorElementType() == MVT::i32) {
4685     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
4686       return Op;
4687     return DAG.UnrollVectorOp(Op.getNode());
4688   }
4689 
4690   assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
4691          "Invalid type for custom lowering!");
4692   if (VT != MVT::v4i16)
4693     return DAG.UnrollVectorOp(Op.getNode());
4694 
4695   Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
4696   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
4697 }
4698 
4699 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
4700   EVT VT = Op.getValueType();
4701   if (VT.isVector())
4702     return LowerVectorFP_TO_INT(Op, DAG);
4703   if (Subtarget->isFPOnlySP() && Op.getOperand(0).getValueType() == MVT::f64) {
4704     RTLIB::Libcall LC;
4705     if (Op.getOpcode() == ISD::FP_TO_SINT)
4706       LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(),
4707                               Op.getValueType());
4708     else
4709       LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(),
4710                               Op.getValueType());
4711     return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0),
4712                        /*isSigned*/ false, SDLoc(Op)).first;
4713   }
4714 
4715   return Op;
4716 }
4717 
4718 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
4719   EVT VT = Op.getValueType();
4720   SDLoc dl(Op);
4721 
4722   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
4723     if (VT.getVectorElementType() == MVT::f32)
4724       return Op;
4725     return DAG.UnrollVectorOp(Op.getNode());
4726   }
4727 
4728   assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
4729          "Invalid type for custom lowering!");
4730   if (VT != MVT::v4f32)
4731     return DAG.UnrollVectorOp(Op.getNode());
4732 
4733   unsigned CastOpc;
4734   unsigned Opc;
4735   switch (Op.getOpcode()) {
4736   default: llvm_unreachable("Invalid opcode!");
4737   case ISD::SINT_TO_FP:
4738     CastOpc = ISD::SIGN_EXTEND;
4739     Opc = ISD::SINT_TO_FP;
4740     break;
4741   case ISD::UINT_TO_FP:
4742     CastOpc = ISD::ZERO_EXTEND;
4743     Opc = ISD::UINT_TO_FP;
4744     break;
4745   }
4746 
4747   Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
4748   return DAG.getNode(Opc, dl, VT, Op);
4749 }
4750 
4751 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
4752   EVT VT = Op.getValueType();
4753   if (VT.isVector())
4754     return LowerVectorINT_TO_FP(Op, DAG);
4755   if (Subtarget->isFPOnlySP() && Op.getValueType() == MVT::f64) {
4756     RTLIB::Libcall LC;
4757     if (Op.getOpcode() == ISD::SINT_TO_FP)
4758       LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(),
4759                               Op.getValueType());
4760     else
4761       LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(),
4762                               Op.getValueType());
4763     return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0),
4764                        /*isSigned*/ false, SDLoc(Op)).first;
4765   }
4766 
4767   return Op;
4768 }
4769 
4770 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
4771   // Implement fcopysign with a fabs and a conditional fneg.
4772   SDValue Tmp0 = Op.getOperand(0);
4773   SDValue Tmp1 = Op.getOperand(1);
4774   SDLoc dl(Op);
4775   EVT VT = Op.getValueType();
4776   EVT SrcVT = Tmp1.getValueType();
4777   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
4778     Tmp0.getOpcode() == ARMISD::VMOVDRR;
4779   bool UseNEON = !InGPR && Subtarget->hasNEON();
4780 
4781   if (UseNEON) {
4782     // Use VBSL to copy the sign bit.
4783     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
4784     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
4785                                DAG.getTargetConstant(EncodedVal, dl, MVT::i32));
4786     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
4787     if (VT == MVT::f64)
4788       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4789                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
4790                          DAG.getConstant(32, dl, MVT::i32));
4791     else /*if (VT == MVT::f32)*/
4792       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
4793     if (SrcVT == MVT::f32) {
4794       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
4795       if (VT == MVT::f64)
4796         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4797                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
4798                            DAG.getConstant(32, dl, MVT::i32));
4799     } else if (VT == MVT::f32)
4800       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
4801                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
4802                          DAG.getConstant(32, dl, MVT::i32));
4803     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
4804     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
4805 
4806     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
4807                                             dl, MVT::i32);
4808     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
4809     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
4810                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
4811 
4812     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
4813                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
4814                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
4815     if (VT == MVT::f32) {
4816       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
4817       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
4818                         DAG.getConstant(0, dl, MVT::i32));
4819     } else {
4820       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
4821     }
4822 
4823     return Res;
4824   }
4825 
4826   // Bitcast operand 1 to i32.
4827   if (SrcVT == MVT::f64)
4828     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4829                        Tmp1).getValue(1);
4830   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
4831 
4832   // Or in the signbit with integer operations.
4833   SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32);
4834   SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32);
4835   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
4836   if (VT == MVT::f32) {
4837     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
4838                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
4839     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4840                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
4841   }
4842 
4843   // f64: Or the high part with signbit and then combine two parts.
4844   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4845                      Tmp0);
4846   SDValue Lo = Tmp0.getValue(0);
4847   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
4848   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
4849   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
4850 }
4851 
4852 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
4853   MachineFunction &MF = DAG.getMachineFunction();
4854   MachineFrameInfo &MFI = MF.getFrameInfo();
4855   MFI.setReturnAddressIsTaken(true);
4856 
4857   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
4858     return SDValue();
4859 
4860   EVT VT = Op.getValueType();
4861   SDLoc dl(Op);
4862   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4863   if (Depth) {
4864     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
4865     SDValue Offset = DAG.getConstant(4, dl, MVT::i32);
4866     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
4867                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
4868                        MachinePointerInfo());
4869   }
4870 
4871   // Return LR, which contains the return address. Mark it an implicit live-in.
4872   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
4873   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
4874 }
4875 
4876 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
4877   const ARMBaseRegisterInfo &ARI =
4878     *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
4879   MachineFunction &MF = DAG.getMachineFunction();
4880   MachineFrameInfo &MFI = MF.getFrameInfo();
4881   MFI.setFrameAddressIsTaken(true);
4882 
4883   EVT VT = Op.getValueType();
4884   SDLoc dl(Op);  // FIXME probably not meaningful
4885   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4886   unsigned FrameReg = ARI.getFrameRegister(MF);
4887   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
4888   while (Depth--)
4889     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
4890                             MachinePointerInfo());
4891   return FrameAddr;
4892 }
4893 
4894 // FIXME? Maybe this could be a TableGen attribute on some registers and
4895 // this table could be generated automatically from RegInfo.
4896 unsigned ARMTargetLowering::getRegisterByName(const char* RegName, EVT VT,
4897                                               SelectionDAG &DAG) const {
4898   unsigned Reg = StringSwitch<unsigned>(RegName)
4899                        .Case("sp", ARM::SP)
4900                        .Default(0);
4901   if (Reg)
4902     return Reg;
4903   report_fatal_error(Twine("Invalid register name \""
4904                               + StringRef(RegName)  + "\"."));
4905 }
4906 
4907 // Result is 64 bit value so split into two 32 bit values and return as a
4908 // pair of values.
4909 static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results,
4910                                 SelectionDAG &DAG) {
4911   SDLoc DL(N);
4912 
4913   // This function is only supposed to be called for i64 type destination.
4914   assert(N->getValueType(0) == MVT::i64
4915           && "ExpandREAD_REGISTER called for non-i64 type result.");
4916 
4917   SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL,
4918                              DAG.getVTList(MVT::i32, MVT::i32, MVT::Other),
4919                              N->getOperand(0),
4920                              N->getOperand(1));
4921 
4922   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0),
4923                     Read.getValue(1)));
4924   Results.push_back(Read.getOperand(0));
4925 }
4926 
4927 /// \p BC is a bitcast that is about to be turned into a VMOVDRR.
4928 /// When \p DstVT, the destination type of \p BC, is on the vector
4929 /// register bank and the source of bitcast, \p Op, operates on the same bank,
4930 /// it might be possible to combine them, such that everything stays on the
4931 /// vector register bank.
4932 /// \p return The node that would replace \p BT, if the combine
4933 /// is possible.
4934 static SDValue CombineVMOVDRRCandidateWithVecOp(const SDNode *BC,
4935                                                 SelectionDAG &DAG) {
4936   SDValue Op = BC->getOperand(0);
4937   EVT DstVT = BC->getValueType(0);
4938 
4939   // The only vector instruction that can produce a scalar (remember,
4940   // since the bitcast was about to be turned into VMOVDRR, the source
4941   // type is i64) from a vector is EXTRACT_VECTOR_ELT.
4942   // Moreover, we can do this combine only if there is one use.
4943   // Finally, if the destination type is not a vector, there is not
4944   // much point on forcing everything on the vector bank.
4945   if (!DstVT.isVector() || Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4946       !Op.hasOneUse())
4947     return SDValue();
4948 
4949   // If the index is not constant, we will introduce an additional
4950   // multiply that will stick.
4951   // Give up in that case.
4952   ConstantSDNode *Index = dyn_cast<ConstantSDNode>(Op.getOperand(1));
4953   if (!Index)
4954     return SDValue();
4955   unsigned DstNumElt = DstVT.getVectorNumElements();
4956 
4957   // Compute the new index.
4958   const APInt &APIntIndex = Index->getAPIntValue();
4959   APInt NewIndex(APIntIndex.getBitWidth(), DstNumElt);
4960   NewIndex *= APIntIndex;
4961   // Check if the new constant index fits into i32.
4962   if (NewIndex.getBitWidth() > 32)
4963     return SDValue();
4964 
4965   // vMTy bitcast(i64 extractelt vNi64 src, i32 index) ->
4966   // vMTy extractsubvector vNxMTy (bitcast vNi64 src), i32 index*M)
4967   SDLoc dl(Op);
4968   SDValue ExtractSrc = Op.getOperand(0);
4969   EVT VecVT = EVT::getVectorVT(
4970       *DAG.getContext(), DstVT.getScalarType(),
4971       ExtractSrc.getValueType().getVectorNumElements() * DstNumElt);
4972   SDValue BitCast = DAG.getNode(ISD::BITCAST, dl, VecVT, ExtractSrc);
4973   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DstVT, BitCast,
4974                      DAG.getConstant(NewIndex.getZExtValue(), dl, MVT::i32));
4975 }
4976 
4977 /// ExpandBITCAST - If the target supports VFP, this function is called to
4978 /// expand a bit convert where either the source or destination type is i64 to
4979 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
4980 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
4981 /// vectors), since the legalizer won't know what to do with that.
4982 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
4983   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4984   SDLoc dl(N);
4985   SDValue Op = N->getOperand(0);
4986 
4987   // This function is only supposed to be called for i64 types, either as the
4988   // source or destination of the bit convert.
4989   EVT SrcVT = Op.getValueType();
4990   EVT DstVT = N->getValueType(0);
4991   assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
4992          "ExpandBITCAST called for non-i64 type");
4993 
4994   // Turn i64->f64 into VMOVDRR.
4995   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
4996     // Do not force values to GPRs (this is what VMOVDRR does for the inputs)
4997     // if we can combine the bitcast with its source.
4998     if (SDValue Val = CombineVMOVDRRCandidateWithVecOp(N, DAG))
4999       return Val;
5000 
5001     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
5002                              DAG.getConstant(0, dl, MVT::i32));
5003     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
5004                              DAG.getConstant(1, dl, MVT::i32));
5005     return DAG.getNode(ISD::BITCAST, dl, DstVT,
5006                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
5007   }
5008 
5009   // Turn f64->i64 into VMOVRRD.
5010   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
5011     SDValue Cvt;
5012     if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() &&
5013         SrcVT.getVectorNumElements() > 1)
5014       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
5015                         DAG.getVTList(MVT::i32, MVT::i32),
5016                         DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
5017     else
5018       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
5019                         DAG.getVTList(MVT::i32, MVT::i32), Op);
5020     // Merge the pieces into a single i64 value.
5021     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
5022   }
5023 
5024   return SDValue();
5025 }
5026 
5027 /// getZeroVector - Returns a vector of specified type with all zero elements.
5028 /// Zero vectors are used to represent vector negation and in those cases
5029 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
5030 /// not support i64 elements, so sometimes the zero vectors will need to be
5031 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
5032 /// zero vector.
5033 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, const SDLoc &dl) {
5034   assert(VT.isVector() && "Expected a vector type");
5035   // The canonical modified immediate encoding of a zero vector is....0!
5036   SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32);
5037   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
5038   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
5039   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5040 }
5041 
5042 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
5043 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
5044 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
5045                                                 SelectionDAG &DAG) const {
5046   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5047   EVT VT = Op.getValueType();
5048   unsigned VTBits = VT.getSizeInBits();
5049   SDLoc dl(Op);
5050   SDValue ShOpLo = Op.getOperand(0);
5051   SDValue ShOpHi = Op.getOperand(1);
5052   SDValue ShAmt  = Op.getOperand(2);
5053   SDValue ARMcc;
5054   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5055   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
5056 
5057   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
5058 
5059   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
5060                                  DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
5061   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
5062   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
5063                                    DAG.getConstant(VTBits, dl, MVT::i32));
5064   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
5065   SDValue LoSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
5066   SDValue LoBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
5067   SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
5068                             ISD::SETGE, ARMcc, DAG, dl);
5069   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift, LoBigShift,
5070                            ARMcc, CCR, CmpLo);
5071 
5072   SDValue HiSmallShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
5073   SDValue HiBigShift = Opc == ISD::SRA
5074                            ? DAG.getNode(Opc, dl, VT, ShOpHi,
5075                                          DAG.getConstant(VTBits - 1, dl, VT))
5076                            : DAG.getConstant(0, dl, VT);
5077   SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
5078                             ISD::SETGE, ARMcc, DAG, dl);
5079   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift,
5080                            ARMcc, CCR, CmpHi);
5081 
5082   SDValue Ops[2] = { Lo, Hi };
5083   return DAG.getMergeValues(Ops, dl);
5084 }
5085 
5086 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
5087 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
5088 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
5089                                                SelectionDAG &DAG) const {
5090   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5091   EVT VT = Op.getValueType();
5092   unsigned VTBits = VT.getSizeInBits();
5093   SDLoc dl(Op);
5094   SDValue ShOpLo = Op.getOperand(0);
5095   SDValue ShOpHi = Op.getOperand(1);
5096   SDValue ShAmt  = Op.getOperand(2);
5097   SDValue ARMcc;
5098   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5099 
5100   assert(Op.getOpcode() == ISD::SHL_PARTS);
5101   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
5102                                  DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
5103   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
5104   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
5105   SDValue HiSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
5106 
5107   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
5108                                    DAG.getConstant(VTBits, dl, MVT::i32));
5109   SDValue HiBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
5110   SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
5111                             ISD::SETGE, ARMcc, DAG, dl);
5112   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift,
5113                            ARMcc, CCR, CmpHi);
5114 
5115   SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
5116                           ISD::SETGE, ARMcc, DAG, dl);
5117   SDValue LoSmallShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
5118   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift,
5119                            DAG.getConstant(0, dl, VT), ARMcc, CCR, CmpLo);
5120 
5121   SDValue Ops[2] = { Lo, Hi };
5122   return DAG.getMergeValues(Ops, dl);
5123 }
5124 
5125 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
5126                                             SelectionDAG &DAG) const {
5127   // The rounding mode is in bits 23:22 of the FPSCR.
5128   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
5129   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
5130   // so that the shift + and get folded into a bitfield extract.
5131   SDLoc dl(Op);
5132   SDValue Ops[] = { DAG.getEntryNode(),
5133                     DAG.getConstant(Intrinsic::arm_get_fpscr, dl, MVT::i32) };
5134 
5135   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_W_CHAIN, dl, MVT::i32, Ops);
5136   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
5137                                   DAG.getConstant(1U << 22, dl, MVT::i32));
5138   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
5139                               DAG.getConstant(22, dl, MVT::i32));
5140   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
5141                      DAG.getConstant(3, dl, MVT::i32));
5142 }
5143 
5144 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
5145                          const ARMSubtarget *ST) {
5146   SDLoc dl(N);
5147   EVT VT = N->getValueType(0);
5148   if (VT.isVector()) {
5149     assert(ST->hasNEON());
5150 
5151     // Compute the least significant set bit: LSB = X & -X
5152     SDValue X = N->getOperand(0);
5153     SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X);
5154     SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX);
5155 
5156     EVT ElemTy = VT.getVectorElementType();
5157 
5158     if (ElemTy == MVT::i8) {
5159       // Compute with: cttz(x) = ctpop(lsb - 1)
5160       SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
5161                                 DAG.getTargetConstant(1, dl, ElemTy));
5162       SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
5163       return DAG.getNode(ISD::CTPOP, dl, VT, Bits);
5164     }
5165 
5166     if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) &&
5167         (N->getOpcode() == ISD::CTTZ_ZERO_UNDEF)) {
5168       // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0
5169       unsigned NumBits = ElemTy.getSizeInBits();
5170       SDValue WidthMinus1 =
5171           DAG.getNode(ARMISD::VMOVIMM, dl, VT,
5172                       DAG.getTargetConstant(NumBits - 1, dl, ElemTy));
5173       SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB);
5174       return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ);
5175     }
5176 
5177     // Compute with: cttz(x) = ctpop(lsb - 1)
5178 
5179     // Since we can only compute the number of bits in a byte with vcnt.8, we
5180     // have to gather the result with pairwise addition (vpaddl) for i16, i32,
5181     // and i64.
5182 
5183     // Compute LSB - 1.
5184     SDValue Bits;
5185     if (ElemTy == MVT::i64) {
5186       // Load constant 0xffff'ffff'ffff'ffff to register.
5187       SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
5188                                DAG.getTargetConstant(0x1eff, dl, MVT::i32));
5189       Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF);
5190     } else {
5191       SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
5192                                 DAG.getTargetConstant(1, dl, ElemTy));
5193       Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
5194     }
5195 
5196     // Count #bits with vcnt.8.
5197     EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
5198     SDValue BitsVT8 = DAG.getNode(ISD::BITCAST, dl, VT8Bit, Bits);
5199     SDValue Cnt8 = DAG.getNode(ISD::CTPOP, dl, VT8Bit, BitsVT8);
5200 
5201     // Gather the #bits with vpaddl (pairwise add.)
5202     EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
5203     SDValue Cnt16 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT16Bit,
5204         DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
5205         Cnt8);
5206     if (ElemTy == MVT::i16)
5207       return Cnt16;
5208 
5209     EVT VT32Bit = VT.is64BitVector() ? MVT::v2i32 : MVT::v4i32;
5210     SDValue Cnt32 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT32Bit,
5211         DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
5212         Cnt16);
5213     if (ElemTy == MVT::i32)
5214       return Cnt32;
5215 
5216     assert(ElemTy == MVT::i64);
5217     SDValue Cnt64 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
5218         DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
5219         Cnt32);
5220     return Cnt64;
5221   }
5222 
5223   if (!ST->hasV6T2Ops())
5224     return SDValue();
5225 
5226   SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, VT, N->getOperand(0));
5227   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
5228 }
5229 
5230 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
5231 /// for each 16-bit element from operand, repeated.  The basic idea is to
5232 /// leverage vcnt to get the 8-bit counts, gather and add the results.
5233 ///
5234 /// Trace for v4i16:
5235 /// input    = [v0    v1    v2    v3   ] (vi 16-bit element)
5236 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
5237 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
5238 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
5239 ///            [b0 b1 b2 b3 b4 b5 b6 b7]
5240 ///           +[b1 b0 b3 b2 b5 b4 b7 b6]
5241 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
5242 /// vuzp:    = [k0 k1 k2 k3 k0 k1 k2 k3]  each ki is 8-bits)
5243 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
5244   EVT VT = N->getValueType(0);
5245   SDLoc DL(N);
5246 
5247   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
5248   SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
5249   SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
5250   SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
5251   SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
5252   return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
5253 }
5254 
5255 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
5256 /// bit-count for each 16-bit element from the operand.  We need slightly
5257 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
5258 /// 64/128-bit registers.
5259 ///
5260 /// Trace for v4i16:
5261 /// input           = [v0    v1    v2    v3    ] (vi 16-bit element)
5262 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
5263 /// v8i16:Extended  = [k0    k1    k2    k3    k0    k1    k2    k3    ]
5264 /// v4i16:Extracted = [k0    k1    k2    k3    ]
5265 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
5266   EVT VT = N->getValueType(0);
5267   SDLoc DL(N);
5268 
5269   SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
5270   if (VT.is64BitVector()) {
5271     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
5272     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
5273                        DAG.getIntPtrConstant(0, DL));
5274   } else {
5275     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
5276                                     BitCounts, DAG.getIntPtrConstant(0, DL));
5277     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
5278   }
5279 }
5280 
5281 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
5282 /// bit-count for each 32-bit element from the operand.  The idea here is
5283 /// to split the vector into 16-bit elements, leverage the 16-bit count
5284 /// routine, and then combine the results.
5285 ///
5286 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
5287 /// input    = [v0    v1    ] (vi: 32-bit elements)
5288 /// Bitcast  = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
5289 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
5290 /// vrev: N0 = [k1 k0 k3 k2 ]
5291 ///            [k0 k1 k2 k3 ]
5292 ///       N1 =+[k1 k0 k3 k2 ]
5293 ///            [k0 k2 k1 k3 ]
5294 ///       N2 =+[k1 k3 k0 k2 ]
5295 ///            [k0    k2    k1    k3    ]
5296 /// Extended =+[k1    k3    k0    k2    ]
5297 ///            [k0    k2    ]
5298 /// Extracted=+[k1    k3    ]
5299 ///
5300 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
5301   EVT VT = N->getValueType(0);
5302   SDLoc DL(N);
5303 
5304   EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
5305 
5306   SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
5307   SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
5308   SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
5309   SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
5310   SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
5311 
5312   if (VT.is64BitVector()) {
5313     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
5314     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
5315                        DAG.getIntPtrConstant(0, DL));
5316   } else {
5317     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
5318                                     DAG.getIntPtrConstant(0, DL));
5319     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
5320   }
5321 }
5322 
5323 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
5324                           const ARMSubtarget *ST) {
5325   EVT VT = N->getValueType(0);
5326 
5327   assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
5328   assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
5329           VT == MVT::v4i16 || VT == MVT::v8i16) &&
5330          "Unexpected type for custom ctpop lowering");
5331 
5332   if (VT.getVectorElementType() == MVT::i32)
5333     return lowerCTPOP32BitElements(N, DAG);
5334   else
5335     return lowerCTPOP16BitElements(N, DAG);
5336 }
5337 
5338 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
5339                           const ARMSubtarget *ST) {
5340   EVT VT = N->getValueType(0);
5341   SDLoc dl(N);
5342 
5343   if (!VT.isVector())
5344     return SDValue();
5345 
5346   // Lower vector shifts on NEON to use VSHL.
5347   assert(ST->hasNEON() && "unexpected vector shift");
5348 
5349   // Left shifts translate directly to the vshiftu intrinsic.
5350   if (N->getOpcode() == ISD::SHL)
5351     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
5352                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, dl,
5353                                        MVT::i32),
5354                        N->getOperand(0), N->getOperand(1));
5355 
5356   assert((N->getOpcode() == ISD::SRA ||
5357           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
5358 
5359   // NEON uses the same intrinsics for both left and right shifts.  For
5360   // right shifts, the shift amounts are negative, so negate the vector of
5361   // shift amounts.
5362   EVT ShiftVT = N->getOperand(1).getValueType();
5363   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
5364                                      getZeroVector(ShiftVT, DAG, dl),
5365                                      N->getOperand(1));
5366   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
5367                              Intrinsic::arm_neon_vshifts :
5368                              Intrinsic::arm_neon_vshiftu);
5369   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
5370                      DAG.getConstant(vshiftInt, dl, MVT::i32),
5371                      N->getOperand(0), NegatedCount);
5372 }
5373 
5374 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
5375                                 const ARMSubtarget *ST) {
5376   EVT VT = N->getValueType(0);
5377   SDLoc dl(N);
5378 
5379   // We can get here for a node like i32 = ISD::SHL i32, i64
5380   if (VT != MVT::i64)
5381     return SDValue();
5382 
5383   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
5384          "Unknown shift to lower!");
5385 
5386   // We only lower SRA, SRL of 1 here, all others use generic lowering.
5387   if (!isOneConstant(N->getOperand(1)))
5388     return SDValue();
5389 
5390   // If we are in thumb mode, we don't have RRX.
5391   if (ST->isThumb1Only()) return SDValue();
5392 
5393   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
5394   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
5395                            DAG.getConstant(0, dl, MVT::i32));
5396   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
5397                            DAG.getConstant(1, dl, MVT::i32));
5398 
5399   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
5400   // captures the result into a carry flag.
5401   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
5402   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
5403 
5404   // The low part is an ARMISD::RRX operand, which shifts the carry in.
5405   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
5406 
5407   // Merge the pieces into a single i64 value.
5408  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
5409 }
5410 
5411 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
5412   SDValue TmpOp0, TmpOp1;
5413   bool Invert = false;
5414   bool Swap = false;
5415   unsigned Opc = 0;
5416 
5417   SDValue Op0 = Op.getOperand(0);
5418   SDValue Op1 = Op.getOperand(1);
5419   SDValue CC = Op.getOperand(2);
5420   EVT CmpVT = Op0.getValueType().changeVectorElementTypeToInteger();
5421   EVT VT = Op.getValueType();
5422   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
5423   SDLoc dl(Op);
5424 
5425   if (Op0.getValueType().getVectorElementType() == MVT::i64 &&
5426       (SetCCOpcode == ISD::SETEQ || SetCCOpcode == ISD::SETNE)) {
5427     // Special-case integer 64-bit equality comparisons. They aren't legal,
5428     // but they can be lowered with a few vector instructions.
5429     unsigned CmpElements = CmpVT.getVectorNumElements() * 2;
5430     EVT SplitVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, CmpElements);
5431     SDValue CastOp0 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op0);
5432     SDValue CastOp1 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op1);
5433     SDValue Cmp = DAG.getNode(ISD::SETCC, dl, SplitVT, CastOp0, CastOp1,
5434                               DAG.getCondCode(ISD::SETEQ));
5435     SDValue Reversed = DAG.getNode(ARMISD::VREV64, dl, SplitVT, Cmp);
5436     SDValue Merged = DAG.getNode(ISD::AND, dl, SplitVT, Cmp, Reversed);
5437     Merged = DAG.getNode(ISD::BITCAST, dl, CmpVT, Merged);
5438     if (SetCCOpcode == ISD::SETNE)
5439       Merged = DAG.getNOT(dl, Merged, CmpVT);
5440     Merged = DAG.getSExtOrTrunc(Merged, dl, VT);
5441     return Merged;
5442   }
5443 
5444   if (CmpVT.getVectorElementType() == MVT::i64)
5445     // 64-bit comparisons are not legal in general.
5446     return SDValue();
5447 
5448   if (Op1.getValueType().isFloatingPoint()) {
5449     switch (SetCCOpcode) {
5450     default: llvm_unreachable("Illegal FP comparison");
5451     case ISD::SETUNE:
5452     case ISD::SETNE:  Invert = true; LLVM_FALLTHROUGH;
5453     case ISD::SETOEQ:
5454     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
5455     case ISD::SETOLT:
5456     case ISD::SETLT: Swap = true; LLVM_FALLTHROUGH;
5457     case ISD::SETOGT:
5458     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
5459     case ISD::SETOLE:
5460     case ISD::SETLE:  Swap = true; LLVM_FALLTHROUGH;
5461     case ISD::SETOGE:
5462     case ISD::SETGE: Opc = ARMISD::VCGE; break;
5463     case ISD::SETUGE: Swap = true; LLVM_FALLTHROUGH;
5464     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
5465     case ISD::SETUGT: Swap = true; LLVM_FALLTHROUGH;
5466     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
5467     case ISD::SETUEQ: Invert = true; LLVM_FALLTHROUGH;
5468     case ISD::SETONE:
5469       // Expand this to (OLT | OGT).
5470       TmpOp0 = Op0;
5471       TmpOp1 = Op1;
5472       Opc = ISD::OR;
5473       Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
5474       Op1 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp0, TmpOp1);
5475       break;
5476     case ISD::SETUO:
5477       Invert = true;
5478       LLVM_FALLTHROUGH;
5479     case ISD::SETO:
5480       // Expand this to (OLT | OGE).
5481       TmpOp0 = Op0;
5482       TmpOp1 = Op1;
5483       Opc = ISD::OR;
5484       Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
5485       Op1 = DAG.getNode(ARMISD::VCGE, dl, CmpVT, TmpOp0, TmpOp1);
5486       break;
5487     }
5488   } else {
5489     // Integer comparisons.
5490     switch (SetCCOpcode) {
5491     default: llvm_unreachable("Illegal integer comparison");
5492     case ISD::SETNE:  Invert = true; LLVM_FALLTHROUGH;
5493     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
5494     case ISD::SETLT:  Swap = true; LLVM_FALLTHROUGH;
5495     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
5496     case ISD::SETLE:  Swap = true; LLVM_FALLTHROUGH;
5497     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
5498     case ISD::SETULT: Swap = true; LLVM_FALLTHROUGH;
5499     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
5500     case ISD::SETULE: Swap = true; LLVM_FALLTHROUGH;
5501     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
5502     }
5503 
5504     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
5505     if (Opc == ARMISD::VCEQ) {
5506       SDValue AndOp;
5507       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
5508         AndOp = Op0;
5509       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
5510         AndOp = Op1;
5511 
5512       // Ignore bitconvert.
5513       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
5514         AndOp = AndOp.getOperand(0);
5515 
5516       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
5517         Opc = ARMISD::VTST;
5518         Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0));
5519         Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1));
5520         Invert = !Invert;
5521       }
5522     }
5523   }
5524 
5525   if (Swap)
5526     std::swap(Op0, Op1);
5527 
5528   // If one of the operands is a constant vector zero, attempt to fold the
5529   // comparison to a specialized compare-against-zero form.
5530   SDValue SingleOp;
5531   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
5532     SingleOp = Op0;
5533   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
5534     if (Opc == ARMISD::VCGE)
5535       Opc = ARMISD::VCLEZ;
5536     else if (Opc == ARMISD::VCGT)
5537       Opc = ARMISD::VCLTZ;
5538     SingleOp = Op1;
5539   }
5540 
5541   SDValue Result;
5542   if (SingleOp.getNode()) {
5543     switch (Opc) {
5544     case ARMISD::VCEQ:
5545       Result = DAG.getNode(ARMISD::VCEQZ, dl, CmpVT, SingleOp); break;
5546     case ARMISD::VCGE:
5547       Result = DAG.getNode(ARMISD::VCGEZ, dl, CmpVT, SingleOp); break;
5548     case ARMISD::VCLEZ:
5549       Result = DAG.getNode(ARMISD::VCLEZ, dl, CmpVT, SingleOp); break;
5550     case ARMISD::VCGT:
5551       Result = DAG.getNode(ARMISD::VCGTZ, dl, CmpVT, SingleOp); break;
5552     case ARMISD::VCLTZ:
5553       Result = DAG.getNode(ARMISD::VCLTZ, dl, CmpVT, SingleOp); break;
5554     default:
5555       Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
5556     }
5557   } else {
5558      Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
5559   }
5560 
5561   Result = DAG.getSExtOrTrunc(Result, dl, VT);
5562 
5563   if (Invert)
5564     Result = DAG.getNOT(dl, Result, VT);
5565 
5566   return Result;
5567 }
5568 
5569 static SDValue LowerSETCCE(SDValue Op, SelectionDAG &DAG) {
5570   SDValue LHS = Op.getOperand(0);
5571   SDValue RHS = Op.getOperand(1);
5572   SDValue Carry = Op.getOperand(2);
5573   SDValue Cond = Op.getOperand(3);
5574   SDLoc DL(Op);
5575 
5576   assert(LHS.getSimpleValueType().isInteger() && "SETCCE is integer only.");
5577 
5578   assert(Carry.getOpcode() != ISD::CARRY_FALSE);
5579   SDVTList VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
5580   SDValue Cmp = DAG.getNode(ARMISD::SUBE, DL, VTs, LHS, RHS, Carry);
5581 
5582   SDValue FVal = DAG.getConstant(0, DL, MVT::i32);
5583   SDValue TVal = DAG.getConstant(1, DL, MVT::i32);
5584   SDValue ARMcc = DAG.getConstant(
5585       IntCCToARMCC(cast<CondCodeSDNode>(Cond)->get()), DL, MVT::i32);
5586   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5587   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), DL, ARM::CPSR,
5588                                    Cmp.getValue(1), SDValue());
5589   return DAG.getNode(ARMISD::CMOV, DL, Op.getValueType(), FVal, TVal, ARMcc,
5590                      CCR, Chain.getValue(1));
5591 }
5592 
5593 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
5594 /// valid vector constant for a NEON instruction with a "modified immediate"
5595 /// operand (e.g., VMOV).  If so, return the encoded value.
5596 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
5597                                  unsigned SplatBitSize, SelectionDAG &DAG,
5598                                  const SDLoc &dl, EVT &VT, bool is128Bits,
5599                                  NEONModImmType type) {
5600   unsigned OpCmode, Imm;
5601 
5602   // SplatBitSize is set to the smallest size that splats the vector, so a
5603   // zero vector will always have SplatBitSize == 8.  However, NEON modified
5604   // immediate instructions others than VMOV do not support the 8-bit encoding
5605   // of a zero vector, and the default encoding of zero is supposed to be the
5606   // 32-bit version.
5607   if (SplatBits == 0)
5608     SplatBitSize = 32;
5609 
5610   switch (SplatBitSize) {
5611   case 8:
5612     if (type != VMOVModImm)
5613       return SDValue();
5614     // Any 1-byte value is OK.  Op=0, Cmode=1110.
5615     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
5616     OpCmode = 0xe;
5617     Imm = SplatBits;
5618     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
5619     break;
5620 
5621   case 16:
5622     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
5623     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
5624     if ((SplatBits & ~0xff) == 0) {
5625       // Value = 0x00nn: Op=x, Cmode=100x.
5626       OpCmode = 0x8;
5627       Imm = SplatBits;
5628       break;
5629     }
5630     if ((SplatBits & ~0xff00) == 0) {
5631       // Value = 0xnn00: Op=x, Cmode=101x.
5632       OpCmode = 0xa;
5633       Imm = SplatBits >> 8;
5634       break;
5635     }
5636     return SDValue();
5637 
5638   case 32:
5639     // NEON's 32-bit VMOV supports splat values where:
5640     // * only one byte is nonzero, or
5641     // * the least significant byte is 0xff and the second byte is nonzero, or
5642     // * the least significant 2 bytes are 0xff and the third is nonzero.
5643     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
5644     if ((SplatBits & ~0xff) == 0) {
5645       // Value = 0x000000nn: Op=x, Cmode=000x.
5646       OpCmode = 0;
5647       Imm = SplatBits;
5648       break;
5649     }
5650     if ((SplatBits & ~0xff00) == 0) {
5651       // Value = 0x0000nn00: Op=x, Cmode=001x.
5652       OpCmode = 0x2;
5653       Imm = SplatBits >> 8;
5654       break;
5655     }
5656     if ((SplatBits & ~0xff0000) == 0) {
5657       // Value = 0x00nn0000: Op=x, Cmode=010x.
5658       OpCmode = 0x4;
5659       Imm = SplatBits >> 16;
5660       break;
5661     }
5662     if ((SplatBits & ~0xff000000) == 0) {
5663       // Value = 0xnn000000: Op=x, Cmode=011x.
5664       OpCmode = 0x6;
5665       Imm = SplatBits >> 24;
5666       break;
5667     }
5668 
5669     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
5670     if (type == OtherModImm) return SDValue();
5671 
5672     if ((SplatBits & ~0xffff) == 0 &&
5673         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
5674       // Value = 0x0000nnff: Op=x, Cmode=1100.
5675       OpCmode = 0xc;
5676       Imm = SplatBits >> 8;
5677       break;
5678     }
5679 
5680     if ((SplatBits & ~0xffffff) == 0 &&
5681         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
5682       // Value = 0x00nnffff: Op=x, Cmode=1101.
5683       OpCmode = 0xd;
5684       Imm = SplatBits >> 16;
5685       break;
5686     }
5687 
5688     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
5689     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
5690     // VMOV.I32.  A (very) minor optimization would be to replicate the value
5691     // and fall through here to test for a valid 64-bit splat.  But, then the
5692     // caller would also need to check and handle the change in size.
5693     return SDValue();
5694 
5695   case 64: {
5696     if (type != VMOVModImm)
5697       return SDValue();
5698     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
5699     uint64_t BitMask = 0xff;
5700     uint64_t Val = 0;
5701     unsigned ImmMask = 1;
5702     Imm = 0;
5703     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
5704       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
5705         Val |= BitMask;
5706         Imm |= ImmMask;
5707       } else if ((SplatBits & BitMask) != 0) {
5708         return SDValue();
5709       }
5710       BitMask <<= 8;
5711       ImmMask <<= 1;
5712     }
5713 
5714     if (DAG.getDataLayout().isBigEndian())
5715       // swap higher and lower 32 bit word
5716       Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4);
5717 
5718     // Op=1, Cmode=1110.
5719     OpCmode = 0x1e;
5720     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
5721     break;
5722   }
5723 
5724   default:
5725     llvm_unreachable("unexpected size for isNEONModifiedImm");
5726   }
5727 
5728   unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
5729   return DAG.getTargetConstant(EncodedVal, dl, MVT::i32);
5730 }
5731 
5732 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
5733                                            const ARMSubtarget *ST) const {
5734   bool IsDouble = Op.getValueType() == MVT::f64;
5735   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
5736   const APFloat &FPVal = CFP->getValueAPF();
5737 
5738   // Prevent floating-point constants from using literal loads
5739   // when execute-only is enabled.
5740   if (ST->genExecuteOnly()) {
5741     APInt INTVal = FPVal.bitcastToAPInt();
5742     SDLoc DL(CFP);
5743     if (IsDouble) {
5744       SDValue Lo = DAG.getConstant(INTVal.trunc(32), DL, MVT::i32);
5745       SDValue Hi = DAG.getConstant(INTVal.lshr(32).trunc(32), DL, MVT::i32);
5746       if (!ST->isLittle())
5747         std::swap(Lo, Hi);
5748       return DAG.getNode(ARMISD::VMOVDRR, DL, MVT::f64, Lo, Hi);
5749     } else {
5750       return DAG.getConstant(INTVal, DL, MVT::i32);
5751     }
5752   }
5753 
5754   if (!ST->hasVFP3())
5755     return SDValue();
5756 
5757   // Use the default (constant pool) lowering for double constants when we have
5758   // an SP-only FPU
5759   if (IsDouble && Subtarget->isFPOnlySP())
5760     return SDValue();
5761 
5762   // Try splatting with a VMOV.f32...
5763   int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
5764 
5765   if (ImmVal != -1) {
5766     if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
5767       // We have code in place to select a valid ConstantFP already, no need to
5768       // do any mangling.
5769       return Op;
5770     }
5771 
5772     // It's a float and we are trying to use NEON operations where
5773     // possible. Lower it to a splat followed by an extract.
5774     SDLoc DL(Op);
5775     SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32);
5776     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
5777                                       NewVal);
5778     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
5779                        DAG.getConstant(0, DL, MVT::i32));
5780   }
5781 
5782   // The rest of our options are NEON only, make sure that's allowed before
5783   // proceeding..
5784   if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
5785     return SDValue();
5786 
5787   EVT VMovVT;
5788   uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
5789 
5790   // It wouldn't really be worth bothering for doubles except for one very
5791   // important value, which does happen to match: 0.0. So make sure we don't do
5792   // anything stupid.
5793   if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
5794     return SDValue();
5795 
5796   // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
5797   SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op),
5798                                      VMovVT, false, VMOVModImm);
5799   if (NewVal != SDValue()) {
5800     SDLoc DL(Op);
5801     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
5802                                       NewVal);
5803     if (IsDouble)
5804       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
5805 
5806     // It's a float: cast and extract a vector element.
5807     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
5808                                        VecConstant);
5809     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
5810                        DAG.getConstant(0, DL, MVT::i32));
5811   }
5812 
5813   // Finally, try a VMVN.i32
5814   NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT,
5815                              false, VMVNModImm);
5816   if (NewVal != SDValue()) {
5817     SDLoc DL(Op);
5818     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
5819 
5820     if (IsDouble)
5821       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
5822 
5823     // It's a float: cast and extract a vector element.
5824     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
5825                                        VecConstant);
5826     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
5827                        DAG.getConstant(0, DL, MVT::i32));
5828   }
5829 
5830   return SDValue();
5831 }
5832 
5833 // check if an VEXT instruction can handle the shuffle mask when the
5834 // vector sources of the shuffle are the same.
5835 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
5836   unsigned NumElts = VT.getVectorNumElements();
5837 
5838   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
5839   if (M[0] < 0)
5840     return false;
5841 
5842   Imm = M[0];
5843 
5844   // If this is a VEXT shuffle, the immediate value is the index of the first
5845   // element.  The other shuffle indices must be the successive elements after
5846   // the first one.
5847   unsigned ExpectedElt = Imm;
5848   for (unsigned i = 1; i < NumElts; ++i) {
5849     // Increment the expected index.  If it wraps around, just follow it
5850     // back to index zero and keep going.
5851     ++ExpectedElt;
5852     if (ExpectedElt == NumElts)
5853       ExpectedElt = 0;
5854 
5855     if (M[i] < 0) continue; // ignore UNDEF indices
5856     if (ExpectedElt != static_cast<unsigned>(M[i]))
5857       return false;
5858   }
5859 
5860   return true;
5861 }
5862 
5863 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
5864                        bool &ReverseVEXT, unsigned &Imm) {
5865   unsigned NumElts = VT.getVectorNumElements();
5866   ReverseVEXT = false;
5867 
5868   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
5869   if (M[0] < 0)
5870     return false;
5871 
5872   Imm = M[0];
5873 
5874   // If this is a VEXT shuffle, the immediate value is the index of the first
5875   // element.  The other shuffle indices must be the successive elements after
5876   // the first one.
5877   unsigned ExpectedElt = Imm;
5878   for (unsigned i = 1; i < NumElts; ++i) {
5879     // Increment the expected index.  If it wraps around, it may still be
5880     // a VEXT but the source vectors must be swapped.
5881     ExpectedElt += 1;
5882     if (ExpectedElt == NumElts * 2) {
5883       ExpectedElt = 0;
5884       ReverseVEXT = true;
5885     }
5886 
5887     if (M[i] < 0) continue; // ignore UNDEF indices
5888     if (ExpectedElt != static_cast<unsigned>(M[i]))
5889       return false;
5890   }
5891 
5892   // Adjust the index value if the source operands will be swapped.
5893   if (ReverseVEXT)
5894     Imm -= NumElts;
5895 
5896   return true;
5897 }
5898 
5899 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
5900 /// instruction with the specified blocksize.  (The order of the elements
5901 /// within each block of the vector is reversed.)
5902 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
5903   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
5904          "Only possible block sizes for VREV are: 16, 32, 64");
5905 
5906   unsigned EltSz = VT.getScalarSizeInBits();
5907   if (EltSz == 64)
5908     return false;
5909 
5910   unsigned NumElts = VT.getVectorNumElements();
5911   unsigned BlockElts = M[0] + 1;
5912   // If the first shuffle index is UNDEF, be optimistic.
5913   if (M[0] < 0)
5914     BlockElts = BlockSize / EltSz;
5915 
5916   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
5917     return false;
5918 
5919   for (unsigned i = 0; i < NumElts; ++i) {
5920     if (M[i] < 0) continue; // ignore UNDEF indices
5921     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
5922       return false;
5923   }
5924 
5925   return true;
5926 }
5927 
5928 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
5929   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
5930   // range, then 0 is placed into the resulting vector. So pretty much any mask
5931   // of 8 elements can work here.
5932   return VT == MVT::v8i8 && M.size() == 8;
5933 }
5934 
5935 static unsigned SelectPairHalf(unsigned Elements, ArrayRef<int> Mask,
5936                                unsigned Index) {
5937   if (Mask.size() == Elements * 2)
5938     return Index / Elements;
5939   return Mask[Index] == 0 ? 0 : 1;
5940 }
5941 
5942 // Checks whether the shuffle mask represents a vector transpose (VTRN) by
5943 // checking that pairs of elements in the shuffle mask represent the same index
5944 // in each vector, incrementing the expected index by 2 at each step.
5945 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 2, 6]
5946 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,c,g}
5947 //  v2={e,f,g,h}
5948 // WhichResult gives the offset for each element in the mask based on which
5949 // of the two results it belongs to.
5950 //
5951 // The transpose can be represented either as:
5952 // result1 = shufflevector v1, v2, result1_shuffle_mask
5953 // result2 = shufflevector v1, v2, result2_shuffle_mask
5954 // where v1/v2 and the shuffle masks have the same number of elements
5955 // (here WhichResult (see below) indicates which result is being checked)
5956 //
5957 // or as:
5958 // results = shufflevector v1, v2, shuffle_mask
5959 // where both results are returned in one vector and the shuffle mask has twice
5960 // as many elements as v1/v2 (here WhichResult will always be 0 if true) here we
5961 // want to check the low half and high half of the shuffle mask as if it were
5962 // the other case
5963 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5964   unsigned EltSz = VT.getScalarSizeInBits();
5965   if (EltSz == 64)
5966     return false;
5967 
5968   unsigned NumElts = VT.getVectorNumElements();
5969   if (M.size() != NumElts && M.size() != NumElts*2)
5970     return false;
5971 
5972   // If the mask is twice as long as the input vector then we need to check the
5973   // upper and lower parts of the mask with a matching value for WhichResult
5974   // FIXME: A mask with only even values will be rejected in case the first
5975   // element is undefined, e.g. [-1, 4, 2, 6] will be rejected, because only
5976   // M[0] is used to determine WhichResult
5977   for (unsigned i = 0; i < M.size(); i += NumElts) {
5978     WhichResult = SelectPairHalf(NumElts, M, i);
5979     for (unsigned j = 0; j < NumElts; j += 2) {
5980       if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
5981           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + NumElts + WhichResult))
5982         return false;
5983     }
5984   }
5985 
5986   if (M.size() == NumElts*2)
5987     WhichResult = 0;
5988 
5989   return true;
5990 }
5991 
5992 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
5993 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5994 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
5995 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5996   unsigned EltSz = VT.getScalarSizeInBits();
5997   if (EltSz == 64)
5998     return false;
5999 
6000   unsigned NumElts = VT.getVectorNumElements();
6001   if (M.size() != NumElts && M.size() != NumElts*2)
6002     return false;
6003 
6004   for (unsigned i = 0; i < M.size(); i += NumElts) {
6005     WhichResult = SelectPairHalf(NumElts, M, i);
6006     for (unsigned j = 0; j < NumElts; j += 2) {
6007       if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
6008           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + WhichResult))
6009         return false;
6010     }
6011   }
6012 
6013   if (M.size() == NumElts*2)
6014     WhichResult = 0;
6015 
6016   return true;
6017 }
6018 
6019 // Checks whether the shuffle mask represents a vector unzip (VUZP) by checking
6020 // that the mask elements are either all even and in steps of size 2 or all odd
6021 // and in steps of size 2.
6022 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 2, 4, 6]
6023 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,c,e,g}
6024 //  v2={e,f,g,h}
6025 // Requires similar checks to that of isVTRNMask with
6026 // respect the how results are returned.
6027 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6028   unsigned EltSz = VT.getScalarSizeInBits();
6029   if (EltSz == 64)
6030     return false;
6031 
6032   unsigned NumElts = VT.getVectorNumElements();
6033   if (M.size() != NumElts && M.size() != NumElts*2)
6034     return false;
6035 
6036   for (unsigned i = 0; i < M.size(); i += NumElts) {
6037     WhichResult = SelectPairHalf(NumElts, M, i);
6038     for (unsigned j = 0; j < NumElts; ++j) {
6039       if (M[i+j] >= 0 && (unsigned) M[i+j] != 2 * j + WhichResult)
6040         return false;
6041     }
6042   }
6043 
6044   if (M.size() == NumElts*2)
6045     WhichResult = 0;
6046 
6047   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
6048   if (VT.is64BitVector() && EltSz == 32)
6049     return false;
6050 
6051   return true;
6052 }
6053 
6054 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
6055 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6056 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
6057 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
6058   unsigned EltSz = VT.getScalarSizeInBits();
6059   if (EltSz == 64)
6060     return false;
6061 
6062   unsigned NumElts = VT.getVectorNumElements();
6063   if (M.size() != NumElts && M.size() != NumElts*2)
6064     return false;
6065 
6066   unsigned Half = NumElts / 2;
6067   for (unsigned i = 0; i < M.size(); i += NumElts) {
6068     WhichResult = SelectPairHalf(NumElts, M, i);
6069     for (unsigned j = 0; j < NumElts; j += Half) {
6070       unsigned Idx = WhichResult;
6071       for (unsigned k = 0; k < Half; ++k) {
6072         int MIdx = M[i + j + k];
6073         if (MIdx >= 0 && (unsigned) MIdx != Idx)
6074           return false;
6075         Idx += 2;
6076       }
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 // Checks whether the shuffle mask represents a vector zip (VZIP) by checking
6091 // that pairs of elements of the shufflemask represent the same index in each
6092 // vector incrementing sequentially through the vectors.
6093 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 1, 5]
6094 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,b,f}
6095 //  v2={e,f,g,h}
6096 // Requires similar checks to that of isVTRNMask with respect the how results
6097 // are returned.
6098 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6099   unsigned EltSz = VT.getScalarSizeInBits();
6100   if (EltSz == 64)
6101     return false;
6102 
6103   unsigned NumElts = VT.getVectorNumElements();
6104   if (M.size() != NumElts && M.size() != NumElts*2)
6105     return false;
6106 
6107   for (unsigned i = 0; i < M.size(); i += NumElts) {
6108     WhichResult = SelectPairHalf(NumElts, M, i);
6109     unsigned Idx = WhichResult * NumElts / 2;
6110     for (unsigned j = 0; j < NumElts; j += 2) {
6111       if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
6112           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx + NumElts))
6113         return false;
6114       Idx += 1;
6115     }
6116   }
6117 
6118   if (M.size() == NumElts*2)
6119     WhichResult = 0;
6120 
6121   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
6122   if (VT.is64BitVector() && EltSz == 32)
6123     return false;
6124 
6125   return true;
6126 }
6127 
6128 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
6129 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6130 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
6131 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
6132   unsigned EltSz = VT.getScalarSizeInBits();
6133   if (EltSz == 64)
6134     return false;
6135 
6136   unsigned NumElts = VT.getVectorNumElements();
6137   if (M.size() != NumElts && M.size() != NumElts*2)
6138     return false;
6139 
6140   for (unsigned i = 0; i < M.size(); i += NumElts) {
6141     WhichResult = SelectPairHalf(NumElts, M, i);
6142     unsigned Idx = WhichResult * NumElts / 2;
6143     for (unsigned j = 0; j < NumElts; j += 2) {
6144       if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
6145           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx))
6146         return false;
6147       Idx += 1;
6148     }
6149   }
6150 
6151   if (M.size() == NumElts*2)
6152     WhichResult = 0;
6153 
6154   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
6155   if (VT.is64BitVector() && EltSz == 32)
6156     return false;
6157 
6158   return true;
6159 }
6160 
6161 /// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN),
6162 /// and return the corresponding ARMISD opcode if it is, or 0 if it isn't.
6163 static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT,
6164                                            unsigned &WhichResult,
6165                                            bool &isV_UNDEF) {
6166   isV_UNDEF = false;
6167   if (isVTRNMask(ShuffleMask, VT, WhichResult))
6168     return ARMISD::VTRN;
6169   if (isVUZPMask(ShuffleMask, VT, WhichResult))
6170     return ARMISD::VUZP;
6171   if (isVZIPMask(ShuffleMask, VT, WhichResult))
6172     return ARMISD::VZIP;
6173 
6174   isV_UNDEF = true;
6175   if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
6176     return ARMISD::VTRN;
6177   if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
6178     return ARMISD::VUZP;
6179   if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
6180     return ARMISD::VZIP;
6181 
6182   return 0;
6183 }
6184 
6185 /// \return true if this is a reverse operation on an vector.
6186 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
6187   unsigned NumElts = VT.getVectorNumElements();
6188   // Make sure the mask has the right size.
6189   if (NumElts != M.size())
6190       return false;
6191 
6192   // Look for <15, ..., 3, -1, 1, 0>.
6193   for (unsigned i = 0; i != NumElts; ++i)
6194     if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
6195       return false;
6196 
6197   return true;
6198 }
6199 
6200 // If N is an integer constant that can be moved into a register in one
6201 // instruction, return an SDValue of such a constant (will become a MOV
6202 // instruction).  Otherwise return null.
6203 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
6204                                      const ARMSubtarget *ST, const SDLoc &dl) {
6205   uint64_t Val;
6206   if (!isa<ConstantSDNode>(N))
6207     return SDValue();
6208   Val = cast<ConstantSDNode>(N)->getZExtValue();
6209 
6210   if (ST->isThumb1Only()) {
6211     if (Val <= 255 || ~Val <= 255)
6212       return DAG.getConstant(Val, dl, MVT::i32);
6213   } else {
6214     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
6215       return DAG.getConstant(Val, dl, MVT::i32);
6216   }
6217   return SDValue();
6218 }
6219 
6220 // If this is a case we can't handle, return null and let the default
6221 // expansion code take care of it.
6222 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
6223                                              const ARMSubtarget *ST) const {
6224   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
6225   SDLoc dl(Op);
6226   EVT VT = Op.getValueType();
6227 
6228   APInt SplatBits, SplatUndef;
6229   unsigned SplatBitSize;
6230   bool HasAnyUndefs;
6231   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
6232     if (SplatUndef.isAllOnesValue())
6233       return DAG.getUNDEF(VT);
6234 
6235     if (SplatBitSize <= 64) {
6236       // Check if an immediate VMOV works.
6237       EVT VmovVT;
6238       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
6239                                       SplatUndef.getZExtValue(), SplatBitSize,
6240                                       DAG, dl, VmovVT, VT.is128BitVector(),
6241                                       VMOVModImm);
6242       if (Val.getNode()) {
6243         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
6244         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
6245       }
6246 
6247       // Try an immediate VMVN.
6248       uint64_t NegatedImm = (~SplatBits).getZExtValue();
6249       Val = isNEONModifiedImm(NegatedImm,
6250                                       SplatUndef.getZExtValue(), SplatBitSize,
6251                                       DAG, dl, VmovVT, VT.is128BitVector(),
6252                                       VMVNModImm);
6253       if (Val.getNode()) {
6254         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
6255         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
6256       }
6257 
6258       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
6259       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
6260         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
6261         if (ImmVal != -1) {
6262           SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32);
6263           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
6264         }
6265       }
6266     }
6267   }
6268 
6269   // Scan through the operands to see if only one value is used.
6270   //
6271   // As an optimisation, even if more than one value is used it may be more
6272   // profitable to splat with one value then change some lanes.
6273   //
6274   // Heuristically we decide to do this if the vector has a "dominant" value,
6275   // defined as splatted to more than half of the lanes.
6276   unsigned NumElts = VT.getVectorNumElements();
6277   bool isOnlyLowElement = true;
6278   bool usesOnlyOneValue = true;
6279   bool hasDominantValue = false;
6280   bool isConstant = true;
6281 
6282   // Map of the number of times a particular SDValue appears in the
6283   // element list.
6284   DenseMap<SDValue, unsigned> ValueCounts;
6285   SDValue Value;
6286   for (unsigned i = 0; i < NumElts; ++i) {
6287     SDValue V = Op.getOperand(i);
6288     if (V.isUndef())
6289       continue;
6290     if (i > 0)
6291       isOnlyLowElement = false;
6292     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
6293       isConstant = false;
6294 
6295     ValueCounts.insert(std::make_pair(V, 0));
6296     unsigned &Count = ValueCounts[V];
6297 
6298     // Is this value dominant? (takes up more than half of the lanes)
6299     if (++Count > (NumElts / 2)) {
6300       hasDominantValue = true;
6301       Value = V;
6302     }
6303   }
6304   if (ValueCounts.size() != 1)
6305     usesOnlyOneValue = false;
6306   if (!Value.getNode() && !ValueCounts.empty())
6307     Value = ValueCounts.begin()->first;
6308 
6309   if (ValueCounts.empty())
6310     return DAG.getUNDEF(VT);
6311 
6312   // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
6313   // Keep going if we are hitting this case.
6314   if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
6315     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
6316 
6317   unsigned EltSize = VT.getScalarSizeInBits();
6318 
6319   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
6320   // i32 and try again.
6321   if (hasDominantValue && EltSize <= 32) {
6322     if (!isConstant) {
6323       SDValue N;
6324 
6325       // If we are VDUPing a value that comes directly from a vector, that will
6326       // cause an unnecessary move to and from a GPR, where instead we could
6327       // just use VDUPLANE. We can only do this if the lane being extracted
6328       // is at a constant index, as the VDUP from lane instructions only have
6329       // constant-index forms.
6330       ConstantSDNode *constIndex;
6331       if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6332           (constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1)))) {
6333         // We need to create a new undef vector to use for the VDUPLANE if the
6334         // size of the vector from which we get the value is different than the
6335         // size of the vector that we need to create. We will insert the element
6336         // such that the register coalescer will remove unnecessary copies.
6337         if (VT != Value->getOperand(0).getValueType()) {
6338           unsigned index = constIndex->getAPIntValue().getLimitedValue() %
6339                              VT.getVectorNumElements();
6340           N =  DAG.getNode(ARMISD::VDUPLANE, dl, VT,
6341                  DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
6342                         Value, DAG.getConstant(index, dl, MVT::i32)),
6343                            DAG.getConstant(index, dl, MVT::i32));
6344         } else
6345           N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
6346                         Value->getOperand(0), Value->getOperand(1));
6347       } else
6348         N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
6349 
6350       if (!usesOnlyOneValue) {
6351         // The dominant value was splatted as 'N', but we now have to insert
6352         // all differing elements.
6353         for (unsigned I = 0; I < NumElts; ++I) {
6354           if (Op.getOperand(I) == Value)
6355             continue;
6356           SmallVector<SDValue, 3> Ops;
6357           Ops.push_back(N);
6358           Ops.push_back(Op.getOperand(I));
6359           Ops.push_back(DAG.getConstant(I, dl, MVT::i32));
6360           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
6361         }
6362       }
6363       return N;
6364     }
6365     if (VT.getVectorElementType().isFloatingPoint()) {
6366       SmallVector<SDValue, 8> Ops;
6367       for (unsigned i = 0; i < NumElts; ++i)
6368         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
6369                                   Op.getOperand(i)));
6370       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
6371       SDValue Val = DAG.getBuildVector(VecVT, dl, Ops);
6372       Val = LowerBUILD_VECTOR(Val, DAG, ST);
6373       if (Val.getNode())
6374         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6375     }
6376     if (usesOnlyOneValue) {
6377       SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
6378       if (isConstant && Val.getNode())
6379         return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
6380     }
6381   }
6382 
6383   // If all elements are constants and the case above didn't get hit, fall back
6384   // to the default expansion, which will generate a load from the constant
6385   // pool.
6386   if (isConstant)
6387     return SDValue();
6388 
6389   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
6390   if (NumElts >= 4) {
6391     SDValue shuffle = ReconstructShuffle(Op, DAG);
6392     if (shuffle != SDValue())
6393       return shuffle;
6394   }
6395 
6396   if (VT.is128BitVector() && VT != MVT::v2f64 && VT != MVT::v4f32) {
6397     // If we haven't found an efficient lowering, try splitting a 128-bit vector
6398     // into two 64-bit vectors; we might discover a better way to lower it.
6399     SmallVector<SDValue, 64> Ops(Op->op_begin(), Op->op_begin() + NumElts);
6400     EVT ExtVT = VT.getVectorElementType();
6401     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElts / 2);
6402     SDValue Lower =
6403         DAG.getBuildVector(HVT, dl, makeArrayRef(&Ops[0], NumElts / 2));
6404     if (Lower.getOpcode() == ISD::BUILD_VECTOR)
6405       Lower = LowerBUILD_VECTOR(Lower, DAG, ST);
6406     SDValue Upper = DAG.getBuildVector(
6407         HVT, dl, makeArrayRef(&Ops[NumElts / 2], NumElts / 2));
6408     if (Upper.getOpcode() == ISD::BUILD_VECTOR)
6409       Upper = LowerBUILD_VECTOR(Upper, DAG, ST);
6410     if (Lower && Upper)
6411       return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lower, Upper);
6412   }
6413 
6414   // Vectors with 32- or 64-bit elements can be built by directly assigning
6415   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
6416   // will be legalized.
6417   if (EltSize >= 32) {
6418     // Do the expansion with floating-point types, since that is what the VFP
6419     // registers are defined to use, and since i64 is not legal.
6420     EVT EltVT = EVT::getFloatingPointVT(EltSize);
6421     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
6422     SmallVector<SDValue, 8> Ops;
6423     for (unsigned i = 0; i < NumElts; ++i)
6424       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
6425     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
6426     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6427   }
6428 
6429   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
6430   // know the default expansion would otherwise fall back on something even
6431   // worse. For a vector with one or two non-undef values, that's
6432   // scalar_to_vector for the elements followed by a shuffle (provided the
6433   // shuffle is valid for the target) and materialization element by element
6434   // on the stack followed by a load for everything else.
6435   if (!isConstant && !usesOnlyOneValue) {
6436     SDValue Vec = DAG.getUNDEF(VT);
6437     for (unsigned i = 0 ; i < NumElts; ++i) {
6438       SDValue V = Op.getOperand(i);
6439       if (V.isUndef())
6440         continue;
6441       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32);
6442       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
6443     }
6444     return Vec;
6445   }
6446 
6447   return SDValue();
6448 }
6449 
6450 // Gather data to see if the operation can be modelled as a
6451 // shuffle in combination with VEXTs.
6452 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
6453                                               SelectionDAG &DAG) const {
6454   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
6455   SDLoc dl(Op);
6456   EVT VT = Op.getValueType();
6457   unsigned NumElts = VT.getVectorNumElements();
6458 
6459   struct ShuffleSourceInfo {
6460     SDValue Vec;
6461     unsigned MinElt = std::numeric_limits<unsigned>::max();
6462     unsigned MaxElt = 0;
6463 
6464     // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
6465     // be compatible with the shuffle we intend to construct. As a result
6466     // ShuffleVec will be some sliding window into the original Vec.
6467     SDValue ShuffleVec;
6468 
6469     // Code should guarantee that element i in Vec starts at element "WindowBase
6470     // + i * WindowScale in ShuffleVec".
6471     int WindowBase = 0;
6472     int WindowScale = 1;
6473 
6474     ShuffleSourceInfo(SDValue Vec) : Vec(Vec), ShuffleVec(Vec) {}
6475 
6476     bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
6477   };
6478 
6479   // First gather all vectors used as an immediate source for this BUILD_VECTOR
6480   // node.
6481   SmallVector<ShuffleSourceInfo, 2> Sources;
6482   for (unsigned i = 0; i < NumElts; ++i) {
6483     SDValue V = Op.getOperand(i);
6484     if (V.isUndef())
6485       continue;
6486     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
6487       // A shuffle can only come from building a vector from various
6488       // elements of other vectors.
6489       return SDValue();
6490     } else if (!isa<ConstantSDNode>(V.getOperand(1))) {
6491       // Furthermore, shuffles require a constant mask, whereas extractelts
6492       // accept variable indices.
6493       return SDValue();
6494     }
6495 
6496     // Add this element source to the list if it's not already there.
6497     SDValue SourceVec = V.getOperand(0);
6498     auto Source = llvm::find(Sources, SourceVec);
6499     if (Source == Sources.end())
6500       Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
6501 
6502     // Update the minimum and maximum lane number seen.
6503     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
6504     Source->MinElt = std::min(Source->MinElt, EltNo);
6505     Source->MaxElt = std::max(Source->MaxElt, EltNo);
6506   }
6507 
6508   // Currently only do something sane when at most two source vectors
6509   // are involved.
6510   if (Sources.size() > 2)
6511     return SDValue();
6512 
6513   // Find out the smallest element size among result and two sources, and use
6514   // it as element size to build the shuffle_vector.
6515   EVT SmallestEltTy = VT.getVectorElementType();
6516   for (auto &Source : Sources) {
6517     EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
6518     if (SrcEltTy.bitsLT(SmallestEltTy))
6519       SmallestEltTy = SrcEltTy;
6520   }
6521   unsigned ResMultiplier =
6522       VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits();
6523   NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
6524   EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
6525 
6526   // If the source vector is too wide or too narrow, we may nevertheless be able
6527   // to construct a compatible shuffle either by concatenating it with UNDEF or
6528   // extracting a suitable range of elements.
6529   for (auto &Src : Sources) {
6530     EVT SrcVT = Src.ShuffleVec.getValueType();
6531 
6532     if (SrcVT.getSizeInBits() == VT.getSizeInBits())
6533       continue;
6534 
6535     // This stage of the search produces a source with the same element type as
6536     // the original, but with a total width matching the BUILD_VECTOR output.
6537     EVT EltVT = SrcVT.getVectorElementType();
6538     unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
6539     EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
6540 
6541     if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
6542       if (2 * SrcVT.getSizeInBits() != VT.getSizeInBits())
6543         return SDValue();
6544       // We can pad out the smaller vector for free, so if it's part of a
6545       // shuffle...
6546       Src.ShuffleVec =
6547           DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
6548                       DAG.getUNDEF(Src.ShuffleVec.getValueType()));
6549       continue;
6550     }
6551 
6552     if (SrcVT.getSizeInBits() != 2 * VT.getSizeInBits())
6553       return SDValue();
6554 
6555     if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
6556       // Span too large for a VEXT to cope
6557       return SDValue();
6558     }
6559 
6560     if (Src.MinElt >= NumSrcElts) {
6561       // The extraction can just take the second half
6562       Src.ShuffleVec =
6563           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6564                       DAG.getConstant(NumSrcElts, dl, MVT::i32));
6565       Src.WindowBase = -NumSrcElts;
6566     } else if (Src.MaxElt < NumSrcElts) {
6567       // The extraction can just take the first half
6568       Src.ShuffleVec =
6569           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6570                       DAG.getConstant(0, dl, MVT::i32));
6571     } else {
6572       // An actual VEXT is needed
6573       SDValue VEXTSrc1 =
6574           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6575                       DAG.getConstant(0, dl, MVT::i32));
6576       SDValue VEXTSrc2 =
6577           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6578                       DAG.getConstant(NumSrcElts, dl, MVT::i32));
6579 
6580       Src.ShuffleVec = DAG.getNode(ARMISD::VEXT, dl, DestVT, VEXTSrc1,
6581                                    VEXTSrc2,
6582                                    DAG.getConstant(Src.MinElt, dl, MVT::i32));
6583       Src.WindowBase = -Src.MinElt;
6584     }
6585   }
6586 
6587   // Another possible incompatibility occurs from the vector element types. We
6588   // can fix this by bitcasting the source vectors to the same type we intend
6589   // for the shuffle.
6590   for (auto &Src : Sources) {
6591     EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
6592     if (SrcEltTy == SmallestEltTy)
6593       continue;
6594     assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
6595     Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
6596     Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
6597     Src.WindowBase *= Src.WindowScale;
6598   }
6599 
6600   // Final sanity check before we try to actually produce a shuffle.
6601   DEBUG(
6602     for (auto Src : Sources)
6603       assert(Src.ShuffleVec.getValueType() == ShuffleVT);
6604   );
6605 
6606   // The stars all align, our next step is to produce the mask for the shuffle.
6607   SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
6608   int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits();
6609   for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
6610     SDValue Entry = Op.getOperand(i);
6611     if (Entry.isUndef())
6612       continue;
6613 
6614     auto Src = llvm::find(Sources, Entry.getOperand(0));
6615     int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
6616 
6617     // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
6618     // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
6619     // segment.
6620     EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
6621     int BitsDefined = std::min(OrigEltTy.getSizeInBits(),
6622                                VT.getScalarSizeInBits());
6623     int LanesDefined = BitsDefined / BitsPerShuffleLane;
6624 
6625     // This source is expected to fill ResMultiplier lanes of the final shuffle,
6626     // starting at the appropriate offset.
6627     int *LaneMask = &Mask[i * ResMultiplier];
6628 
6629     int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
6630     ExtractBase += NumElts * (Src - Sources.begin());
6631     for (int j = 0; j < LanesDefined; ++j)
6632       LaneMask[j] = ExtractBase + j;
6633   }
6634 
6635   // Final check before we try to produce nonsense...
6636   if (!isShuffleMaskLegal(Mask, ShuffleVT))
6637     return SDValue();
6638 
6639   // We can't handle more than two sources. This should have already
6640   // been checked before this point.
6641   assert(Sources.size() <= 2 && "Too many sources!");
6642 
6643   SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
6644   for (unsigned i = 0; i < Sources.size(); ++i)
6645     ShuffleOps[i] = Sources[i].ShuffleVec;
6646 
6647   SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
6648                                          ShuffleOps[1], Mask);
6649   return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
6650 }
6651 
6652 /// isShuffleMaskLegal - Targets can use this to indicate that they only
6653 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
6654 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
6655 /// are assumed to be legal.
6656 bool ARMTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
6657   if (VT.getVectorNumElements() == 4 &&
6658       (VT.is128BitVector() || VT.is64BitVector())) {
6659     unsigned PFIndexes[4];
6660     for (unsigned i = 0; i != 4; ++i) {
6661       if (M[i] < 0)
6662         PFIndexes[i] = 8;
6663       else
6664         PFIndexes[i] = M[i];
6665     }
6666 
6667     // Compute the index in the perfect shuffle table.
6668     unsigned PFTableIndex =
6669       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
6670     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6671     unsigned Cost = (PFEntry >> 30);
6672 
6673     if (Cost <= 4)
6674       return true;
6675   }
6676 
6677   bool ReverseVEXT, isV_UNDEF;
6678   unsigned Imm, WhichResult;
6679 
6680   unsigned EltSize = VT.getScalarSizeInBits();
6681   return (EltSize >= 32 ||
6682           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
6683           isVREVMask(M, VT, 64) ||
6684           isVREVMask(M, VT, 32) ||
6685           isVREVMask(M, VT, 16) ||
6686           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
6687           isVTBLMask(M, VT) ||
6688           isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF) ||
6689           ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
6690 }
6691 
6692 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
6693 /// the specified operations to build the shuffle.
6694 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
6695                                       SDValue RHS, SelectionDAG &DAG,
6696                                       const SDLoc &dl) {
6697   unsigned OpNum = (PFEntry >> 26) & 0x0F;
6698   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
6699   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
6700 
6701   enum {
6702     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
6703     OP_VREV,
6704     OP_VDUP0,
6705     OP_VDUP1,
6706     OP_VDUP2,
6707     OP_VDUP3,
6708     OP_VEXT1,
6709     OP_VEXT2,
6710     OP_VEXT3,
6711     OP_VUZPL, // VUZP, left result
6712     OP_VUZPR, // VUZP, right result
6713     OP_VZIPL, // VZIP, left result
6714     OP_VZIPR, // VZIP, right result
6715     OP_VTRNL, // VTRN, left result
6716     OP_VTRNR  // VTRN, right result
6717   };
6718 
6719   if (OpNum == OP_COPY) {
6720     if (LHSID == (1*9+2)*9+3) return LHS;
6721     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
6722     return RHS;
6723   }
6724 
6725   SDValue OpLHS, OpRHS;
6726   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
6727   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
6728   EVT VT = OpLHS.getValueType();
6729 
6730   switch (OpNum) {
6731   default: llvm_unreachable("Unknown shuffle opcode!");
6732   case OP_VREV:
6733     // VREV divides the vector in half and swaps within the half.
6734     if (VT.getVectorElementType() == MVT::i32 ||
6735         VT.getVectorElementType() == MVT::f32)
6736       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
6737     // vrev <4 x i16> -> VREV32
6738     if (VT.getVectorElementType() == MVT::i16)
6739       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
6740     // vrev <4 x i8> -> VREV16
6741     assert(VT.getVectorElementType() == MVT::i8);
6742     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
6743   case OP_VDUP0:
6744   case OP_VDUP1:
6745   case OP_VDUP2:
6746   case OP_VDUP3:
6747     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
6748                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32));
6749   case OP_VEXT1:
6750   case OP_VEXT2:
6751   case OP_VEXT3:
6752     return DAG.getNode(ARMISD::VEXT, dl, VT,
6753                        OpLHS, OpRHS,
6754                        DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32));
6755   case OP_VUZPL:
6756   case OP_VUZPR:
6757     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
6758                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
6759   case OP_VZIPL:
6760   case OP_VZIPR:
6761     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
6762                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
6763   case OP_VTRNL:
6764   case OP_VTRNR:
6765     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
6766                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
6767   }
6768 }
6769 
6770 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
6771                                        ArrayRef<int> ShuffleMask,
6772                                        SelectionDAG &DAG) {
6773   // Check to see if we can use the VTBL instruction.
6774   SDValue V1 = Op.getOperand(0);
6775   SDValue V2 = Op.getOperand(1);
6776   SDLoc DL(Op);
6777 
6778   SmallVector<SDValue, 8> VTBLMask;
6779   for (ArrayRef<int>::iterator
6780          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
6781     VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32));
6782 
6783   if (V2.getNode()->isUndef())
6784     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
6785                        DAG.getBuildVector(MVT::v8i8, DL, VTBLMask));
6786 
6787   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
6788                      DAG.getBuildVector(MVT::v8i8, DL, VTBLMask));
6789 }
6790 
6791 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
6792                                                       SelectionDAG &DAG) {
6793   SDLoc DL(Op);
6794   SDValue OpLHS = Op.getOperand(0);
6795   EVT VT = OpLHS.getValueType();
6796 
6797   assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
6798          "Expect an v8i16/v16i8 type");
6799   OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
6800   // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
6801   // extract the first 8 bytes into the top double word and the last 8 bytes
6802   // into the bottom double word. The v8i16 case is similar.
6803   unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
6804   return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
6805                      DAG.getConstant(ExtractNum, DL, MVT::i32));
6806 }
6807 
6808 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
6809   SDValue V1 = Op.getOperand(0);
6810   SDValue V2 = Op.getOperand(1);
6811   SDLoc dl(Op);
6812   EVT VT = Op.getValueType();
6813   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
6814 
6815   // Convert shuffles that are directly supported on NEON to target-specific
6816   // DAG nodes, instead of keeping them as shuffles and matching them again
6817   // during code selection.  This is more efficient and avoids the possibility
6818   // of inconsistencies between legalization and selection.
6819   // FIXME: floating-point vectors should be canonicalized to integer vectors
6820   // of the same time so that they get CSEd properly.
6821   ArrayRef<int> ShuffleMask = SVN->getMask();
6822 
6823   unsigned EltSize = VT.getScalarSizeInBits();
6824   if (EltSize <= 32) {
6825     if (SVN->isSplat()) {
6826       int Lane = SVN->getSplatIndex();
6827       // If this is undef splat, generate it via "just" vdup, if possible.
6828       if (Lane == -1) Lane = 0;
6829 
6830       // Test if V1 is a SCALAR_TO_VECTOR.
6831       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
6832         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
6833       }
6834       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
6835       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
6836       // reaches it).
6837       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
6838           !isa<ConstantSDNode>(V1.getOperand(0))) {
6839         bool IsScalarToVector = true;
6840         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
6841           if (!V1.getOperand(i).isUndef()) {
6842             IsScalarToVector = false;
6843             break;
6844           }
6845         if (IsScalarToVector)
6846           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
6847       }
6848       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
6849                          DAG.getConstant(Lane, dl, MVT::i32));
6850     }
6851 
6852     bool ReverseVEXT;
6853     unsigned Imm;
6854     if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
6855       if (ReverseVEXT)
6856         std::swap(V1, V2);
6857       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
6858                          DAG.getConstant(Imm, dl, MVT::i32));
6859     }
6860 
6861     if (isVREVMask(ShuffleMask, VT, 64))
6862       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
6863     if (isVREVMask(ShuffleMask, VT, 32))
6864       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
6865     if (isVREVMask(ShuffleMask, VT, 16))
6866       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
6867 
6868     if (V2->isUndef() && isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
6869       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
6870                          DAG.getConstant(Imm, dl, MVT::i32));
6871     }
6872 
6873     // Check for Neon shuffles that modify both input vectors in place.
6874     // If both results are used, i.e., if there are two shuffles with the same
6875     // source operands and with masks corresponding to both results of one of
6876     // these operations, DAG memoization will ensure that a single node is
6877     // used for both shuffles.
6878     unsigned WhichResult;
6879     bool isV_UNDEF;
6880     if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
6881             ShuffleMask, VT, WhichResult, isV_UNDEF)) {
6882       if (isV_UNDEF)
6883         V2 = V1;
6884       return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2)
6885           .getValue(WhichResult);
6886     }
6887 
6888     // Also check for these shuffles through CONCAT_VECTORS: we canonicalize
6889     // shuffles that produce a result larger than their operands with:
6890     //   shuffle(concat(v1, undef), concat(v2, undef))
6891     // ->
6892     //   shuffle(concat(v1, v2), undef)
6893     // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine).
6894     //
6895     // This is useful in the general case, but there are special cases where
6896     // native shuffles produce larger results: the two-result ops.
6897     //
6898     // Look through the concat when lowering them:
6899     //   shuffle(concat(v1, v2), undef)
6900     // ->
6901     //   concat(VZIP(v1, v2):0, :1)
6902     //
6903     if (V1->getOpcode() == ISD::CONCAT_VECTORS && V2->isUndef()) {
6904       SDValue SubV1 = V1->getOperand(0);
6905       SDValue SubV2 = V1->getOperand(1);
6906       EVT SubVT = SubV1.getValueType();
6907 
6908       // We expect these to have been canonicalized to -1.
6909       assert(llvm::all_of(ShuffleMask, [&](int i) {
6910         return i < (int)VT.getVectorNumElements();
6911       }) && "Unexpected shuffle index into UNDEF operand!");
6912 
6913       if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
6914               ShuffleMask, SubVT, WhichResult, isV_UNDEF)) {
6915         if (isV_UNDEF)
6916           SubV2 = SubV1;
6917         assert((WhichResult == 0) &&
6918                "In-place shuffle of concat can only have one result!");
6919         SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT),
6920                                   SubV1, SubV2);
6921         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0),
6922                            Res.getValue(1));
6923       }
6924     }
6925   }
6926 
6927   // If the shuffle is not directly supported and it has 4 elements, use
6928   // the PerfectShuffle-generated table to synthesize it from other shuffles.
6929   unsigned NumElts = VT.getVectorNumElements();
6930   if (NumElts == 4) {
6931     unsigned PFIndexes[4];
6932     for (unsigned i = 0; i != 4; ++i) {
6933       if (ShuffleMask[i] < 0)
6934         PFIndexes[i] = 8;
6935       else
6936         PFIndexes[i] = ShuffleMask[i];
6937     }
6938 
6939     // Compute the index in the perfect shuffle table.
6940     unsigned PFTableIndex =
6941       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
6942     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6943     unsigned Cost = (PFEntry >> 30);
6944 
6945     if (Cost <= 4)
6946       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
6947   }
6948 
6949   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
6950   if (EltSize >= 32) {
6951     // Do the expansion with floating-point types, since that is what the VFP
6952     // registers are defined to use, and since i64 is not legal.
6953     EVT EltVT = EVT::getFloatingPointVT(EltSize);
6954     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
6955     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
6956     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
6957     SmallVector<SDValue, 8> Ops;
6958     for (unsigned i = 0; i < NumElts; ++i) {
6959       if (ShuffleMask[i] < 0)
6960         Ops.push_back(DAG.getUNDEF(EltVT));
6961       else
6962         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6963                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
6964                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
6965                                                   dl, MVT::i32)));
6966     }
6967     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
6968     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6969   }
6970 
6971   if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
6972     return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
6973 
6974   if (VT == MVT::v8i8)
6975     if (SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG))
6976       return NewOp;
6977 
6978   return SDValue();
6979 }
6980 
6981 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
6982   // INSERT_VECTOR_ELT is legal only for immediate indexes.
6983   SDValue Lane = Op.getOperand(2);
6984   if (!isa<ConstantSDNode>(Lane))
6985     return SDValue();
6986 
6987   return Op;
6988 }
6989 
6990 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
6991   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
6992   SDValue Lane = Op.getOperand(1);
6993   if (!isa<ConstantSDNode>(Lane))
6994     return SDValue();
6995 
6996   SDValue Vec = Op.getOperand(0);
6997   if (Op.getValueType() == MVT::i32 && Vec.getScalarValueSizeInBits() < 32) {
6998     SDLoc dl(Op);
6999     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
7000   }
7001 
7002   return Op;
7003 }
7004 
7005 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
7006   // The only time a CONCAT_VECTORS operation can have legal types is when
7007   // two 64-bit vectors are concatenated to a 128-bit vector.
7008   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
7009          "unexpected CONCAT_VECTORS");
7010   SDLoc dl(Op);
7011   SDValue Val = DAG.getUNDEF(MVT::v2f64);
7012   SDValue Op0 = Op.getOperand(0);
7013   SDValue Op1 = Op.getOperand(1);
7014   if (!Op0.isUndef())
7015     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
7016                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
7017                       DAG.getIntPtrConstant(0, dl));
7018   if (!Op1.isUndef())
7019     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
7020                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
7021                       DAG.getIntPtrConstant(1, dl));
7022   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
7023 }
7024 
7025 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
7026 /// element has been zero/sign-extended, depending on the isSigned parameter,
7027 /// from an integer type half its size.
7028 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
7029                                    bool isSigned) {
7030   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
7031   EVT VT = N->getValueType(0);
7032   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
7033     SDNode *BVN = N->getOperand(0).getNode();
7034     if (BVN->getValueType(0) != MVT::v4i32 ||
7035         BVN->getOpcode() != ISD::BUILD_VECTOR)
7036       return false;
7037     unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
7038     unsigned HiElt = 1 - LoElt;
7039     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
7040     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
7041     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
7042     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
7043     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
7044       return false;
7045     if (isSigned) {
7046       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
7047           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
7048         return true;
7049     } else {
7050       if (Hi0->isNullValue() && Hi1->isNullValue())
7051         return true;
7052     }
7053     return false;
7054   }
7055 
7056   if (N->getOpcode() != ISD::BUILD_VECTOR)
7057     return false;
7058 
7059   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
7060     SDNode *Elt = N->getOperand(i).getNode();
7061     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
7062       unsigned EltSize = VT.getScalarSizeInBits();
7063       unsigned HalfSize = EltSize / 2;
7064       if (isSigned) {
7065         if (!isIntN(HalfSize, C->getSExtValue()))
7066           return false;
7067       } else {
7068         if (!isUIntN(HalfSize, C->getZExtValue()))
7069           return false;
7070       }
7071       continue;
7072     }
7073     return false;
7074   }
7075 
7076   return true;
7077 }
7078 
7079 /// isSignExtended - Check if a node is a vector value that is sign-extended
7080 /// or a constant BUILD_VECTOR with sign-extended elements.
7081 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
7082   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
7083     return true;
7084   if (isExtendedBUILD_VECTOR(N, DAG, true))
7085     return true;
7086   return false;
7087 }
7088 
7089 /// isZeroExtended - Check if a node is a vector value that is zero-extended
7090 /// or a constant BUILD_VECTOR with zero-extended elements.
7091 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
7092   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
7093     return true;
7094   if (isExtendedBUILD_VECTOR(N, DAG, false))
7095     return true;
7096   return false;
7097 }
7098 
7099 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
7100   if (OrigVT.getSizeInBits() >= 64)
7101     return OrigVT;
7102 
7103   assert(OrigVT.isSimple() && "Expecting a simple value type");
7104 
7105   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
7106   switch (OrigSimpleTy) {
7107   default: llvm_unreachable("Unexpected Vector Type");
7108   case MVT::v2i8:
7109   case MVT::v2i16:
7110      return MVT::v2i32;
7111   case MVT::v4i8:
7112     return  MVT::v4i16;
7113   }
7114 }
7115 
7116 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
7117 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
7118 /// We insert the required extension here to get the vector to fill a D register.
7119 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
7120                                             const EVT &OrigTy,
7121                                             const EVT &ExtTy,
7122                                             unsigned ExtOpcode) {
7123   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
7124   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
7125   // 64-bits we need to insert a new extension so that it will be 64-bits.
7126   assert(ExtTy.is128BitVector() && "Unexpected extension size");
7127   if (OrigTy.getSizeInBits() >= 64)
7128     return N;
7129 
7130   // Must extend size to at least 64 bits to be used as an operand for VMULL.
7131   EVT NewVT = getExtensionTo64Bits(OrigTy);
7132 
7133   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
7134 }
7135 
7136 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
7137 /// does not do any sign/zero extension. If the original vector is less
7138 /// than 64 bits, an appropriate extension will be added after the load to
7139 /// reach a total size of 64 bits. We have to add the extension separately
7140 /// because ARM does not have a sign/zero extending load for vectors.
7141 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
7142   EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
7143 
7144   // The load already has the right type.
7145   if (ExtendedTy == LD->getMemoryVT())
7146     return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
7147                        LD->getBasePtr(), LD->getPointerInfo(),
7148                        LD->getAlignment(), LD->getMemOperand()->getFlags());
7149 
7150   // We need to create a zextload/sextload. We cannot just create a load
7151   // followed by a zext/zext node because LowerMUL is also run during normal
7152   // operation legalization where we can't create illegal types.
7153   return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
7154                         LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
7155                         LD->getMemoryVT(), LD->getAlignment(),
7156                         LD->getMemOperand()->getFlags());
7157 }
7158 
7159 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
7160 /// extending load, or BUILD_VECTOR with extended elements, return the
7161 /// unextended value. The unextended vector should be 64 bits so that it can
7162 /// be used as an operand to a VMULL instruction. If the original vector size
7163 /// before extension is less than 64 bits we add a an extension to resize
7164 /// the vector to 64 bits.
7165 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
7166   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
7167     return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
7168                                         N->getOperand(0)->getValueType(0),
7169                                         N->getValueType(0),
7170                                         N->getOpcode());
7171 
7172   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7173     assert((ISD::isSEXTLoad(LD) || ISD::isZEXTLoad(LD)) &&
7174            "Expected extending load");
7175 
7176     SDValue newLoad = SkipLoadExtensionForVMULL(LD, DAG);
7177     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), newLoad.getValue(1));
7178     unsigned Opcode = ISD::isSEXTLoad(LD) ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
7179     SDValue extLoad =
7180         DAG.getNode(Opcode, SDLoc(newLoad), LD->getValueType(0), newLoad);
7181     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 0), extLoad);
7182 
7183     return newLoad;
7184   }
7185 
7186   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
7187   // have been legalized as a BITCAST from v4i32.
7188   if (N->getOpcode() == ISD::BITCAST) {
7189     SDNode *BVN = N->getOperand(0).getNode();
7190     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
7191            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
7192     unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
7193     return DAG.getBuildVector(
7194         MVT::v2i32, SDLoc(N),
7195         {BVN->getOperand(LowElt), BVN->getOperand(LowElt + 2)});
7196   }
7197   // Construct a new BUILD_VECTOR with elements truncated to half the size.
7198   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
7199   EVT VT = N->getValueType(0);
7200   unsigned EltSize = VT.getScalarSizeInBits() / 2;
7201   unsigned NumElts = VT.getVectorNumElements();
7202   MVT TruncVT = MVT::getIntegerVT(EltSize);
7203   SmallVector<SDValue, 8> Ops;
7204   SDLoc dl(N);
7205   for (unsigned i = 0; i != NumElts; ++i) {
7206     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
7207     const APInt &CInt = C->getAPIntValue();
7208     // Element types smaller than 32 bits are not legal, so use i32 elements.
7209     // The values are implicitly truncated so sext vs. zext doesn't matter.
7210     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
7211   }
7212   return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops);
7213 }
7214 
7215 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
7216   unsigned Opcode = N->getOpcode();
7217   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
7218     SDNode *N0 = N->getOperand(0).getNode();
7219     SDNode *N1 = N->getOperand(1).getNode();
7220     return N0->hasOneUse() && N1->hasOneUse() &&
7221       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
7222   }
7223   return false;
7224 }
7225 
7226 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
7227   unsigned Opcode = N->getOpcode();
7228   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
7229     SDNode *N0 = N->getOperand(0).getNode();
7230     SDNode *N1 = N->getOperand(1).getNode();
7231     return N0->hasOneUse() && N1->hasOneUse() &&
7232       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
7233   }
7234   return false;
7235 }
7236 
7237 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
7238   // Multiplications are only custom-lowered for 128-bit vectors so that
7239   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
7240   EVT VT = Op.getValueType();
7241   assert(VT.is128BitVector() && VT.isInteger() &&
7242          "unexpected type for custom-lowering ISD::MUL");
7243   SDNode *N0 = Op.getOperand(0).getNode();
7244   SDNode *N1 = Op.getOperand(1).getNode();
7245   unsigned NewOpc = 0;
7246   bool isMLA = false;
7247   bool isN0SExt = isSignExtended(N0, DAG);
7248   bool isN1SExt = isSignExtended(N1, DAG);
7249   if (isN0SExt && isN1SExt)
7250     NewOpc = ARMISD::VMULLs;
7251   else {
7252     bool isN0ZExt = isZeroExtended(N0, DAG);
7253     bool isN1ZExt = isZeroExtended(N1, DAG);
7254     if (isN0ZExt && isN1ZExt)
7255       NewOpc = ARMISD::VMULLu;
7256     else if (isN1SExt || isN1ZExt) {
7257       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
7258       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
7259       if (isN1SExt && isAddSubSExt(N0, DAG)) {
7260         NewOpc = ARMISD::VMULLs;
7261         isMLA = true;
7262       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
7263         NewOpc = ARMISD::VMULLu;
7264         isMLA = true;
7265       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
7266         std::swap(N0, N1);
7267         NewOpc = ARMISD::VMULLu;
7268         isMLA = true;
7269       }
7270     }
7271 
7272     if (!NewOpc) {
7273       if (VT == MVT::v2i64)
7274         // Fall through to expand this.  It is not legal.
7275         return SDValue();
7276       else
7277         // Other vector multiplications are legal.
7278         return Op;
7279     }
7280   }
7281 
7282   // Legalize to a VMULL instruction.
7283   SDLoc DL(Op);
7284   SDValue Op0;
7285   SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
7286   if (!isMLA) {
7287     Op0 = SkipExtensionForVMULL(N0, DAG);
7288     assert(Op0.getValueType().is64BitVector() &&
7289            Op1.getValueType().is64BitVector() &&
7290            "unexpected types for extended operands to VMULL");
7291     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
7292   }
7293 
7294   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
7295   // isel lowering to take advantage of no-stall back to back vmul + vmla.
7296   //   vmull q0, d4, d6
7297   //   vmlal q0, d5, d6
7298   // is faster than
7299   //   vaddl q0, d4, d5
7300   //   vmovl q1, d6
7301   //   vmul  q0, q0, q1
7302   SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
7303   SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
7304   EVT Op1VT = Op1.getValueType();
7305   return DAG.getNode(N0->getOpcode(), DL, VT,
7306                      DAG.getNode(NewOpc, DL, VT,
7307                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
7308                      DAG.getNode(NewOpc, DL, VT,
7309                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
7310 }
7311 
7312 static SDValue LowerSDIV_v4i8(SDValue X, SDValue Y, const SDLoc &dl,
7313                               SelectionDAG &DAG) {
7314   // TODO: Should this propagate fast-math-flags?
7315 
7316   // Convert to float
7317   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
7318   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
7319   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
7320   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
7321   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
7322   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
7323   // Get reciprocal estimate.
7324   // float4 recip = vrecpeq_f32(yf);
7325   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7326                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
7327                    Y);
7328   // Because char has a smaller range than uchar, we can actually get away
7329   // without any newton steps.  This requires that we use a weird bias
7330   // of 0xb000, however (again, this has been exhaustively tested).
7331   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
7332   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
7333   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
7334   Y = DAG.getConstant(0xb000, dl, MVT::v4i32);
7335   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
7336   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
7337   // Convert back to short.
7338   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
7339   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
7340   return X;
7341 }
7342 
7343 static SDValue LowerSDIV_v4i16(SDValue N0, SDValue N1, const SDLoc &dl,
7344                                SelectionDAG &DAG) {
7345   // TODO: Should this propagate fast-math-flags?
7346 
7347   SDValue N2;
7348   // Convert to float.
7349   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
7350   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
7351   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
7352   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
7353   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
7354   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
7355 
7356   // Use reciprocal estimate and one refinement step.
7357   // float4 recip = vrecpeq_f32(yf);
7358   // recip *= vrecpsq_f32(yf, recip);
7359   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7360                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
7361                    N1);
7362   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7363                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
7364                    N1, N2);
7365   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
7366   // Because short has a smaller range than ushort, we can actually get away
7367   // with only a single newton step.  This requires that we use a weird bias
7368   // of 89, however (again, this has been exhaustively tested).
7369   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
7370   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
7371   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
7372   N1 = DAG.getConstant(0x89, dl, MVT::v4i32);
7373   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
7374   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
7375   // Convert back to integer and return.
7376   // return vmovn_s32(vcvt_s32_f32(result));
7377   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
7378   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
7379   return N0;
7380 }
7381 
7382 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
7383   EVT VT = Op.getValueType();
7384   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
7385          "unexpected type for custom-lowering ISD::SDIV");
7386 
7387   SDLoc dl(Op);
7388   SDValue N0 = Op.getOperand(0);
7389   SDValue N1 = Op.getOperand(1);
7390   SDValue N2, N3;
7391 
7392   if (VT == MVT::v8i8) {
7393     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
7394     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
7395 
7396     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
7397                      DAG.getIntPtrConstant(4, dl));
7398     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
7399                      DAG.getIntPtrConstant(4, dl));
7400     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
7401                      DAG.getIntPtrConstant(0, dl));
7402     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
7403                      DAG.getIntPtrConstant(0, dl));
7404 
7405     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
7406     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
7407 
7408     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
7409     N0 = LowerCONCAT_VECTORS(N0, DAG);
7410 
7411     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
7412     return N0;
7413   }
7414   return LowerSDIV_v4i16(N0, N1, dl, DAG);
7415 }
7416 
7417 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
7418   // TODO: Should this propagate fast-math-flags?
7419   EVT VT = Op.getValueType();
7420   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
7421          "unexpected type for custom-lowering ISD::UDIV");
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::ZERO_EXTEND, dl, MVT::v8i16, N0);
7430     N1 = DAG.getNode(ISD::ZERO_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_v4i16(N0, N1, dl, DAG); // v4i16
7442     N2 = LowerSDIV_v4i16(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::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
7448                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl,
7449                                      MVT::i32),
7450                      N0);
7451     return N0;
7452   }
7453 
7454   // v4i16 sdiv ... Convert to float.
7455   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
7456   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
7457   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
7458   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
7459   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
7460   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
7461 
7462   // Use reciprocal estimate and two refinement steps.
7463   // float4 recip = vrecpeq_f32(yf);
7464   // recip *= vrecpsq_f32(yf, recip);
7465   // recip *= vrecpsq_f32(yf, recip);
7466   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7467                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
7468                    BN1);
7469   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7470                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
7471                    BN1, N2);
7472   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
7473   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7474                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
7475                    BN1, N2);
7476   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
7477   // Simply multiplying by the reciprocal estimate can leave us a few ulps
7478   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
7479   // and that it will never cause us to return an answer too large).
7480   // float4 result = as_float4(as_int4(xf*recip) + 2);
7481   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
7482   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
7483   N1 = DAG.getConstant(2, dl, MVT::v4i32);
7484   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
7485   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
7486   // Convert back to integer and return.
7487   // return vmovn_u32(vcvt_s32_f32(result));
7488   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
7489   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
7490   return N0;
7491 }
7492 
7493 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
7494   EVT VT = Op.getNode()->getValueType(0);
7495   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
7496 
7497   unsigned Opc;
7498   bool ExtraOp = false;
7499   switch (Op.getOpcode()) {
7500   default: llvm_unreachable("Invalid code");
7501   case ISD::ADDC: Opc = ARMISD::ADDC; break;
7502   case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
7503   case ISD::SUBC: Opc = ARMISD::SUBC; break;
7504   case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
7505   }
7506 
7507   if (!ExtraOp)
7508     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
7509                        Op.getOperand(1));
7510   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
7511                      Op.getOperand(1), Op.getOperand(2));
7512 }
7513 
7514 static SDValue LowerADDSUBCARRY(SDValue Op, SelectionDAG &DAG) {
7515   SDNode *N = Op.getNode();
7516   EVT VT = N->getValueType(0);
7517   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
7518 
7519   SDValue Carry = Op.getOperand(2);
7520   EVT CarryVT = Carry.getValueType();
7521 
7522   SDLoc DL(Op);
7523 
7524   APInt NegOne = APInt::getAllOnesValue(CarryVT.getScalarSizeInBits());
7525 
7526   SDValue Result;
7527   if (Op.getOpcode() == ISD::ADDCARRY) {
7528     // This converts the boolean value carry into the carry flag.
7529     Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG);
7530 
7531     // Do the addition proper using the carry flag we wanted.
7532     Result = DAG.getNode(ARMISD::ADDE, DL, VTs, Op.getOperand(0),
7533                          Op.getOperand(1), Carry.getValue(1));
7534 
7535     // Now convert the carry flag into a boolean value.
7536     Carry = ConvertCarryFlagToBooleanCarry(Result.getValue(1), VT, DAG);
7537   } else {
7538     // ARMISD::SUBE expects a carry not a borrow like ISD::SUBCARRY so we
7539     // have to invert the carry first.
7540     Carry = DAG.getNode(ISD::SUB, DL, MVT::i32,
7541                         DAG.getConstant(1, DL, MVT::i32), Carry);
7542     // This converts the boolean value carry into the carry flag.
7543     Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG);
7544 
7545     // Do the subtraction proper using the carry flag we wanted.
7546     Result = DAG.getNode(ARMISD::SUBE, DL, VTs, Op.getOperand(0),
7547                          Op.getOperand(1), Carry.getValue(1));
7548 
7549     // Now convert the carry flag into a boolean value.
7550     Carry = ConvertCarryFlagToBooleanCarry(Result.getValue(1), VT, DAG);
7551     // But the carry returned by ARMISD::SUBE is not a borrow as expected
7552     // by ISD::SUBCARRY, so compute 1 - C.
7553     Carry = DAG.getNode(ISD::SUB, DL, MVT::i32,
7554                         DAG.getConstant(1, DL, MVT::i32), Carry);
7555   }
7556 
7557   // Return both values.
7558   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Result, Carry);
7559 }
7560 
7561 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
7562   assert(Subtarget->isTargetDarwin());
7563 
7564   // For iOS, we want to call an alternative entry point: __sincos_stret,
7565   // return values are passed via sret.
7566   SDLoc dl(Op);
7567   SDValue Arg = Op.getOperand(0);
7568   EVT ArgVT = Arg.getValueType();
7569   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
7570   auto PtrVT = getPointerTy(DAG.getDataLayout());
7571 
7572   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
7573   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7574 
7575   // Pair of floats / doubles used to pass the result.
7576   Type *RetTy = StructType::get(ArgTy, ArgTy);
7577   auto &DL = DAG.getDataLayout();
7578 
7579   ArgListTy Args;
7580   bool ShouldUseSRet = Subtarget->isAPCS_ABI();
7581   SDValue SRet;
7582   if (ShouldUseSRet) {
7583     // Create stack object for sret.
7584     const uint64_t ByteSize = DL.getTypeAllocSize(RetTy);
7585     const unsigned StackAlign = DL.getPrefTypeAlignment(RetTy);
7586     int FrameIdx = MFI.CreateStackObject(ByteSize, StackAlign, false);
7587     SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy(DL));
7588 
7589     ArgListEntry Entry;
7590     Entry.Node = SRet;
7591     Entry.Ty = RetTy->getPointerTo();
7592     Entry.IsSExt = false;
7593     Entry.IsZExt = false;
7594     Entry.IsSRet = true;
7595     Args.push_back(Entry);
7596     RetTy = Type::getVoidTy(*DAG.getContext());
7597   }
7598 
7599   ArgListEntry Entry;
7600   Entry.Node = Arg;
7601   Entry.Ty = ArgTy;
7602   Entry.IsSExt = false;
7603   Entry.IsZExt = false;
7604   Args.push_back(Entry);
7605 
7606   RTLIB::Libcall LC =
7607       (ArgVT == MVT::f64) ? RTLIB::SINCOS_STRET_F64 : RTLIB::SINCOS_STRET_F32;
7608   const char *LibcallName = getLibcallName(LC);
7609   CallingConv::ID CC = getLibcallCallingConv(LC);
7610   SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DL));
7611 
7612   TargetLowering::CallLoweringInfo CLI(DAG);
7613   CLI.setDebugLoc(dl)
7614       .setChain(DAG.getEntryNode())
7615       .setCallee(CC, RetTy, Callee, std::move(Args))
7616       .setDiscardResult(ShouldUseSRet);
7617   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
7618 
7619   if (!ShouldUseSRet)
7620     return CallResult.first;
7621 
7622   SDValue LoadSin =
7623       DAG.getLoad(ArgVT, dl, CallResult.second, SRet, MachinePointerInfo());
7624 
7625   // Address of cos field.
7626   SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, SRet,
7627                             DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl));
7628   SDValue LoadCos =
7629       DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add, MachinePointerInfo());
7630 
7631   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
7632   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
7633                      LoadSin.getValue(0), LoadCos.getValue(0));
7634 }
7635 
7636 SDValue ARMTargetLowering::LowerWindowsDIVLibCall(SDValue Op, SelectionDAG &DAG,
7637                                                   bool Signed,
7638                                                   SDValue &Chain) const {
7639   EVT VT = Op.getValueType();
7640   assert((VT == MVT::i32 || VT == MVT::i64) &&
7641          "unexpected type for custom lowering DIV");
7642   SDLoc dl(Op);
7643 
7644   const auto &DL = DAG.getDataLayout();
7645   const auto &TLI = DAG.getTargetLoweringInfo();
7646 
7647   const char *Name = nullptr;
7648   if (Signed)
7649     Name = (VT == MVT::i32) ? "__rt_sdiv" : "__rt_sdiv64";
7650   else
7651     Name = (VT == MVT::i32) ? "__rt_udiv" : "__rt_udiv64";
7652 
7653   SDValue ES = DAG.getExternalSymbol(Name, TLI.getPointerTy(DL));
7654 
7655   ARMTargetLowering::ArgListTy Args;
7656 
7657   for (auto AI : {1, 0}) {
7658     ArgListEntry Arg;
7659     Arg.Node = Op.getOperand(AI);
7660     Arg.Ty = Arg.Node.getValueType().getTypeForEVT(*DAG.getContext());
7661     Args.push_back(Arg);
7662   }
7663 
7664   CallLoweringInfo CLI(DAG);
7665   CLI.setDebugLoc(dl)
7666     .setChain(Chain)
7667     .setCallee(CallingConv::ARM_AAPCS_VFP, VT.getTypeForEVT(*DAG.getContext()),
7668                ES, std::move(Args));
7669 
7670   return LowerCallTo(CLI).first;
7671 }
7672 
7673 SDValue ARMTargetLowering::LowerDIV_Windows(SDValue Op, SelectionDAG &DAG,
7674                                             bool Signed) const {
7675   assert(Op.getValueType() == MVT::i32 &&
7676          "unexpected type for custom lowering DIV");
7677   SDLoc dl(Op);
7678 
7679   SDValue DBZCHK = DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other,
7680                                DAG.getEntryNode(), Op.getOperand(1));
7681 
7682   return LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
7683 }
7684 
7685 static SDValue WinDBZCheckDenominator(SelectionDAG &DAG, SDNode *N, SDValue InChain) {
7686   SDLoc DL(N);
7687   SDValue Op = N->getOperand(1);
7688   if (N->getValueType(0) == MVT::i32)
7689     return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain, Op);
7690   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op,
7691                            DAG.getConstant(0, DL, MVT::i32));
7692   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op,
7693                            DAG.getConstant(1, DL, MVT::i32));
7694   return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain,
7695                      DAG.getNode(ISD::OR, DL, MVT::i32, Lo, Hi));
7696 }
7697 
7698 void ARMTargetLowering::ExpandDIV_Windows(
7699     SDValue Op, SelectionDAG &DAG, bool Signed,
7700     SmallVectorImpl<SDValue> &Results) const {
7701   const auto &DL = DAG.getDataLayout();
7702   const auto &TLI = DAG.getTargetLoweringInfo();
7703 
7704   assert(Op.getValueType() == MVT::i64 &&
7705          "unexpected type for custom lowering DIV");
7706   SDLoc dl(Op);
7707 
7708   SDValue DBZCHK = WinDBZCheckDenominator(DAG, Op.getNode(), DAG.getEntryNode());
7709 
7710   SDValue Result = LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
7711 
7712   SDValue Lower = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Result);
7713   SDValue Upper = DAG.getNode(ISD::SRL, dl, MVT::i64, Result,
7714                               DAG.getConstant(32, dl, TLI.getPointerTy(DL)));
7715   Upper = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Upper);
7716 
7717   Results.push_back(Lower);
7718   Results.push_back(Upper);
7719 }
7720 
7721 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
7722   if (isStrongerThanMonotonic(cast<AtomicSDNode>(Op)->getOrdering()))
7723     // Acquire/Release load/store is not legal for targets without a dmb or
7724     // equivalent available.
7725     return SDValue();
7726 
7727   // Monotonic load/store is legal for all targets.
7728   return Op;
7729 }
7730 
7731 static void ReplaceREADCYCLECOUNTER(SDNode *N,
7732                                     SmallVectorImpl<SDValue> &Results,
7733                                     SelectionDAG &DAG,
7734                                     const ARMSubtarget *Subtarget) {
7735   SDLoc DL(N);
7736   // Under Power Management extensions, the cycle-count is:
7737   //    mrc p15, #0, <Rt>, c9, c13, #0
7738   SDValue Ops[] = { N->getOperand(0), // Chain
7739                     DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32),
7740                     DAG.getConstant(15, DL, MVT::i32),
7741                     DAG.getConstant(0, DL, MVT::i32),
7742                     DAG.getConstant(9, DL, MVT::i32),
7743                     DAG.getConstant(13, DL, MVT::i32),
7744                     DAG.getConstant(0, DL, MVT::i32)
7745   };
7746 
7747   SDValue Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
7748                                  DAG.getVTList(MVT::i32, MVT::Other), Ops);
7749   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Cycles32,
7750                                 DAG.getConstant(0, DL, MVT::i32)));
7751   Results.push_back(Cycles32.getValue(1));
7752 }
7753 
7754 static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) {
7755   SDLoc dl(V.getNode());
7756   SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i32);
7757   SDValue VHi = DAG.getAnyExtOrTrunc(
7758       DAG.getNode(ISD::SRL, dl, MVT::i64, V, DAG.getConstant(32, dl, MVT::i32)),
7759       dl, MVT::i32);
7760   bool isBigEndian = DAG.getDataLayout().isBigEndian();
7761   if (isBigEndian)
7762     std::swap (VLo, VHi);
7763   SDValue RegClass =
7764       DAG.getTargetConstant(ARM::GPRPairRegClassID, dl, MVT::i32);
7765   SDValue SubReg0 = DAG.getTargetConstant(ARM::gsub_0, dl, MVT::i32);
7766   SDValue SubReg1 = DAG.getTargetConstant(ARM::gsub_1, dl, MVT::i32);
7767   const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 };
7768   return SDValue(
7769       DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0);
7770 }
7771 
7772 static void ReplaceCMP_SWAP_64Results(SDNode *N,
7773                                        SmallVectorImpl<SDValue> & Results,
7774                                        SelectionDAG &DAG) {
7775   assert(N->getValueType(0) == MVT::i64 &&
7776          "AtomicCmpSwap on types less than 64 should be legal");
7777   SDValue Ops[] = {N->getOperand(1),
7778                    createGPRPairNode(DAG, N->getOperand(2)),
7779                    createGPRPairNode(DAG, N->getOperand(3)),
7780                    N->getOperand(0)};
7781   SDNode *CmpSwap = DAG.getMachineNode(
7782       ARM::CMP_SWAP_64, SDLoc(N),
7783       DAG.getVTList(MVT::Untyped, MVT::i32, MVT::Other), Ops);
7784 
7785   MachineFunction &MF = DAG.getMachineFunction();
7786   MachineSDNode::mmo_iterator MemOp = MF.allocateMemRefsArray(1);
7787   MemOp[0] = cast<MemSDNode>(N)->getMemOperand();
7788   cast<MachineSDNode>(CmpSwap)->setMemRefs(MemOp, MemOp + 1);
7789 
7790   bool isBigEndian = DAG.getDataLayout().isBigEndian();
7791 
7792   Results.push_back(
7793       DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_1 : ARM::gsub_0,
7794                                  SDLoc(N), MVT::i32, SDValue(CmpSwap, 0)));
7795   Results.push_back(
7796       DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_0 : ARM::gsub_1,
7797                                  SDLoc(N), MVT::i32, SDValue(CmpSwap, 0)));
7798   Results.push_back(SDValue(CmpSwap, 2));
7799 }
7800 
7801 static SDValue LowerFPOWI(SDValue Op, const ARMSubtarget &Subtarget,
7802                           SelectionDAG &DAG) {
7803   const auto &TLI = DAG.getTargetLoweringInfo();
7804 
7805   assert(Subtarget.getTargetTriple().isOSMSVCRT() &&
7806          "Custom lowering is MSVCRT specific!");
7807 
7808   SDLoc dl(Op);
7809   SDValue Val = Op.getOperand(0);
7810   MVT Ty = Val->getSimpleValueType(0);
7811   SDValue Exponent = DAG.getNode(ISD::SINT_TO_FP, dl, Ty, Op.getOperand(1));
7812   SDValue Callee = DAG.getExternalSymbol(Ty == MVT::f32 ? "powf" : "pow",
7813                                          TLI.getPointerTy(DAG.getDataLayout()));
7814 
7815   TargetLowering::ArgListTy Args;
7816   TargetLowering::ArgListEntry Entry;
7817 
7818   Entry.Node = Val;
7819   Entry.Ty = Val.getValueType().getTypeForEVT(*DAG.getContext());
7820   Entry.IsZExt = true;
7821   Args.push_back(Entry);
7822 
7823   Entry.Node = Exponent;
7824   Entry.Ty = Exponent.getValueType().getTypeForEVT(*DAG.getContext());
7825   Entry.IsZExt = true;
7826   Args.push_back(Entry);
7827 
7828   Type *LCRTy = Val.getValueType().getTypeForEVT(*DAG.getContext());
7829 
7830   // In the in-chain to the call is the entry node  If we are emitting a
7831   // tailcall, the chain will be mutated if the node has a non-entry input
7832   // chain.
7833   SDValue InChain = DAG.getEntryNode();
7834   SDValue TCChain = InChain;
7835 
7836   const Function &F = DAG.getMachineFunction().getFunction();
7837   bool IsTC = TLI.isInTailCallPosition(DAG, Op.getNode(), TCChain) &&
7838               F.getReturnType() == LCRTy;
7839   if (IsTC)
7840     InChain = TCChain;
7841 
7842   TargetLowering::CallLoweringInfo CLI(DAG);
7843   CLI.setDebugLoc(dl)
7844       .setChain(InChain)
7845       .setCallee(CallingConv::ARM_AAPCS_VFP, LCRTy, Callee, std::move(Args))
7846       .setTailCall(IsTC);
7847   std::pair<SDValue, SDValue> CI = TLI.LowerCallTo(CLI);
7848 
7849   // Return the chain (the DAG root) if it is a tail call
7850   return !CI.second.getNode() ? DAG.getRoot() : CI.first;
7851 }
7852 
7853 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
7854   DEBUG(dbgs() << "Lowering node: "; Op.dump());
7855   switch (Op.getOpcode()) {
7856   default: llvm_unreachable("Don't know how to custom lower this!");
7857   case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG);
7858   case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
7859   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
7860   case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
7861   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
7862   case ISD::SELECT:        return LowerSELECT(Op, DAG);
7863   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
7864   case ISD::BRCOND:        return LowerBRCOND(Op, DAG);
7865   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
7866   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
7867   case ISD::VASTART:       return LowerVASTART(Op, DAG);
7868   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
7869   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
7870   case ISD::SINT_TO_FP:
7871   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
7872   case ISD::FP_TO_SINT:
7873   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
7874   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
7875   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
7876   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
7877   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
7878   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
7879   case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG);
7880   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
7881                                                                Subtarget);
7882   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG);
7883   case ISD::SHL:
7884   case ISD::SRL:
7885   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
7886   case ISD::SREM:          return LowerREM(Op.getNode(), DAG);
7887   case ISD::UREM:          return LowerREM(Op.getNode(), DAG);
7888   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
7889   case ISD::SRL_PARTS:
7890   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
7891   case ISD::CTTZ:
7892   case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
7893   case ISD::CTPOP:         return LowerCTPOP(Op.getNode(), DAG, Subtarget);
7894   case ISD::SETCC:         return LowerVSETCC(Op, DAG);
7895   case ISD::SETCCE:        return LowerSETCCE(Op, DAG);
7896   case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
7897   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
7898   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
7899   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
7900   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
7901   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
7902   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
7903   case ISD::MUL:           return LowerMUL(Op, DAG);
7904   case ISD::SDIV:
7905     if (Subtarget->isTargetWindows() && !Op.getValueType().isVector())
7906       return LowerDIV_Windows(Op, DAG, /* Signed */ true);
7907     return LowerSDIV(Op, DAG);
7908   case ISD::UDIV:
7909     if (Subtarget->isTargetWindows() && !Op.getValueType().isVector())
7910       return LowerDIV_Windows(Op, DAG, /* Signed */ false);
7911     return LowerUDIV(Op, DAG);
7912   case ISD::ADDC:
7913   case ISD::ADDE:
7914   case ISD::SUBC:
7915   case ISD::SUBE:          return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
7916   case ISD::ADDCARRY:
7917   case ISD::SUBCARRY:      return LowerADDSUBCARRY(Op, DAG);
7918   case ISD::SADDO:
7919   case ISD::SSUBO:
7920     return LowerSignedALUO(Op, DAG);
7921   case ISD::UADDO:
7922   case ISD::USUBO:
7923     return LowerUnsignedALUO(Op, DAG);
7924   case ISD::ATOMIC_LOAD:
7925   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
7926   case ISD::FSINCOS:       return LowerFSINCOS(Op, DAG);
7927   case ISD::SDIVREM:
7928   case ISD::UDIVREM:       return LowerDivRem(Op, DAG);
7929   case ISD::DYNAMIC_STACKALLOC:
7930     if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
7931       return LowerDYNAMIC_STACKALLOC(Op, DAG);
7932     llvm_unreachable("Don't know how to custom lower this!");
7933   case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
7934   case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
7935   case ISD::FPOWI: return LowerFPOWI(Op, *Subtarget, DAG);
7936   case ARMISD::WIN__DBZCHK: return SDValue();
7937   }
7938 }
7939 
7940 static void ReplaceLongIntrinsic(SDNode *N, SmallVectorImpl<SDValue> &Results,
7941                                  SelectionDAG &DAG) {
7942   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
7943   unsigned Opc = 0;
7944   if (IntNo == Intrinsic::arm_smlald)
7945     Opc = ARMISD::SMLALD;
7946   else if (IntNo == Intrinsic::arm_smlaldx)
7947     Opc = ARMISD::SMLALDX;
7948   else if (IntNo == Intrinsic::arm_smlsld)
7949     Opc = ARMISD::SMLSLD;
7950   else if (IntNo == Intrinsic::arm_smlsldx)
7951     Opc = ARMISD::SMLSLDX;
7952   else
7953     return;
7954 
7955   SDLoc dl(N);
7956   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7957                            N->getOperand(3),
7958                            DAG.getConstant(0, dl, MVT::i32));
7959   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7960                            N->getOperand(3),
7961                            DAG.getConstant(1, dl, MVT::i32));
7962 
7963   SDValue LongMul = DAG.getNode(Opc, dl,
7964                                 DAG.getVTList(MVT::i32, MVT::i32),
7965                                 N->getOperand(1), N->getOperand(2),
7966                                 Lo, Hi);
7967   Results.push_back(LongMul.getValue(0));
7968   Results.push_back(LongMul.getValue(1));
7969 }
7970 
7971 /// ReplaceNodeResults - Replace the results of node with an illegal result
7972 /// type with new values built out of custom code.
7973 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
7974                                            SmallVectorImpl<SDValue> &Results,
7975                                            SelectionDAG &DAG) const {
7976   SDValue Res;
7977   switch (N->getOpcode()) {
7978   default:
7979     llvm_unreachable("Don't know how to custom expand this!");
7980   case ISD::READ_REGISTER:
7981     ExpandREAD_REGISTER(N, Results, DAG);
7982     break;
7983   case ISD::BITCAST:
7984     Res = ExpandBITCAST(N, DAG);
7985     break;
7986   case ISD::SRL:
7987   case ISD::SRA:
7988     Res = Expand64BitShift(N, DAG, Subtarget);
7989     break;
7990   case ISD::SREM:
7991   case ISD::UREM:
7992     Res = LowerREM(N, DAG);
7993     break;
7994   case ISD::SDIVREM:
7995   case ISD::UDIVREM:
7996     Res = LowerDivRem(SDValue(N, 0), DAG);
7997     assert(Res.getNumOperands() == 2 && "DivRem needs two values");
7998     Results.push_back(Res.getValue(0));
7999     Results.push_back(Res.getValue(1));
8000     return;
8001   case ISD::READCYCLECOUNTER:
8002     ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
8003     return;
8004   case ISD::UDIV:
8005   case ISD::SDIV:
8006     assert(Subtarget->isTargetWindows() && "can only expand DIV on Windows");
8007     return ExpandDIV_Windows(SDValue(N, 0), DAG, N->getOpcode() == ISD::SDIV,
8008                              Results);
8009   case ISD::ATOMIC_CMP_SWAP:
8010     ReplaceCMP_SWAP_64Results(N, Results, DAG);
8011     return;
8012   case ISD::INTRINSIC_WO_CHAIN:
8013     return ReplaceLongIntrinsic(N, Results, DAG);
8014   }
8015   if (Res.getNode())
8016     Results.push_back(Res);
8017 }
8018 
8019 //===----------------------------------------------------------------------===//
8020 //                           ARM Scheduler Hooks
8021 //===----------------------------------------------------------------------===//
8022 
8023 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
8024 /// registers the function context.
8025 void ARMTargetLowering::SetupEntryBlockForSjLj(MachineInstr &MI,
8026                                                MachineBasicBlock *MBB,
8027                                                MachineBasicBlock *DispatchBB,
8028                                                int FI) const {
8029   assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
8030          "ROPI/RWPI not currently supported with SjLj");
8031   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
8032   DebugLoc dl = MI.getDebugLoc();
8033   MachineFunction *MF = MBB->getParent();
8034   MachineRegisterInfo *MRI = &MF->getRegInfo();
8035   MachineConstantPool *MCP = MF->getConstantPool();
8036   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
8037   const Function &F = MF->getFunction();
8038 
8039   bool isThumb = Subtarget->isThumb();
8040   bool isThumb2 = Subtarget->isThumb2();
8041 
8042   unsigned PCLabelId = AFI->createPICLabelUId();
8043   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
8044   ARMConstantPoolValue *CPV =
8045     ARMConstantPoolMBB::Create(F.getContext(), DispatchBB, PCLabelId, PCAdj);
8046   unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
8047 
8048   const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass
8049                                            : &ARM::GPRRegClass;
8050 
8051   // Grab constant pool and fixed stack memory operands.
8052   MachineMemOperand *CPMMO =
8053       MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF),
8054                                MachineMemOperand::MOLoad, 4, 4);
8055 
8056   MachineMemOperand *FIMMOSt =
8057       MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI),
8058                                MachineMemOperand::MOStore, 4, 4);
8059 
8060   // Load the address of the dispatch MBB into the jump buffer.
8061   if (isThumb2) {
8062     // Incoming value: jbuf
8063     //   ldr.n  r5, LCPI1_1
8064     //   orr    r5, r5, #1
8065     //   add    r5, pc
8066     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
8067     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
8068     BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
8069         .addConstantPoolIndex(CPI)
8070         .addMemOperand(CPMMO)
8071         .add(predOps(ARMCC::AL));
8072     // Set the low bit because of thumb mode.
8073     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
8074     BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
8075         .addReg(NewVReg1, RegState::Kill)
8076         .addImm(0x01)
8077         .add(predOps(ARMCC::AL))
8078         .add(condCodeOp());
8079     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
8080     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
8081       .addReg(NewVReg2, RegState::Kill)
8082       .addImm(PCLabelId);
8083     BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
8084         .addReg(NewVReg3, RegState::Kill)
8085         .addFrameIndex(FI)
8086         .addImm(36) // &jbuf[1] :: pc
8087         .addMemOperand(FIMMOSt)
8088         .add(predOps(ARMCC::AL));
8089   } else if (isThumb) {
8090     // Incoming value: jbuf
8091     //   ldr.n  r1, LCPI1_4
8092     //   add    r1, pc
8093     //   mov    r2, #1
8094     //   orrs   r1, r2
8095     //   add    r2, $jbuf, #+4 ; &jbuf[1]
8096     //   str    r1, [r2]
8097     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
8098     BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
8099         .addConstantPoolIndex(CPI)
8100         .addMemOperand(CPMMO)
8101         .add(predOps(ARMCC::AL));
8102     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
8103     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
8104       .addReg(NewVReg1, RegState::Kill)
8105       .addImm(PCLabelId);
8106     // Set the low bit because of thumb mode.
8107     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
8108     BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
8109         .addReg(ARM::CPSR, RegState::Define)
8110         .addImm(1)
8111         .add(predOps(ARMCC::AL));
8112     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
8113     BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
8114         .addReg(ARM::CPSR, RegState::Define)
8115         .addReg(NewVReg2, RegState::Kill)
8116         .addReg(NewVReg3, RegState::Kill)
8117         .add(predOps(ARMCC::AL));
8118     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
8119     BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5)
8120             .addFrameIndex(FI)
8121             .addImm(36); // &jbuf[1] :: pc
8122     BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
8123         .addReg(NewVReg4, RegState::Kill)
8124         .addReg(NewVReg5, RegState::Kill)
8125         .addImm(0)
8126         .addMemOperand(FIMMOSt)
8127         .add(predOps(ARMCC::AL));
8128   } else {
8129     // Incoming value: jbuf
8130     //   ldr  r1, LCPI1_1
8131     //   add  r1, pc, r1
8132     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
8133     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
8134     BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1)
8135         .addConstantPoolIndex(CPI)
8136         .addImm(0)
8137         .addMemOperand(CPMMO)
8138         .add(predOps(ARMCC::AL));
8139     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
8140     BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
8141         .addReg(NewVReg1, RegState::Kill)
8142         .addImm(PCLabelId)
8143         .add(predOps(ARMCC::AL));
8144     BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
8145         .addReg(NewVReg2, RegState::Kill)
8146         .addFrameIndex(FI)
8147         .addImm(36) // &jbuf[1] :: pc
8148         .addMemOperand(FIMMOSt)
8149         .add(predOps(ARMCC::AL));
8150   }
8151 }
8152 
8153 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr &MI,
8154                                               MachineBasicBlock *MBB) const {
8155   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
8156   DebugLoc dl = MI.getDebugLoc();
8157   MachineFunction *MF = MBB->getParent();
8158   MachineRegisterInfo *MRI = &MF->getRegInfo();
8159   MachineFrameInfo &MFI = MF->getFrameInfo();
8160   int FI = MFI.getFunctionContextIndex();
8161 
8162   const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass
8163                                                         : &ARM::GPRnopcRegClass;
8164 
8165   // Get a mapping of the call site numbers to all of the landing pads they're
8166   // associated with.
8167   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2>> CallSiteNumToLPad;
8168   unsigned MaxCSNum = 0;
8169   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
8170        ++BB) {
8171     if (!BB->isEHPad()) continue;
8172 
8173     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
8174     // pad.
8175     for (MachineBasicBlock::iterator
8176            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
8177       if (!II->isEHLabel()) continue;
8178 
8179       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
8180       if (!MF->hasCallSiteLandingPad(Sym)) continue;
8181 
8182       SmallVectorImpl<unsigned> &CallSiteIdxs = MF->getCallSiteLandingPad(Sym);
8183       for (SmallVectorImpl<unsigned>::iterator
8184              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
8185            CSI != CSE; ++CSI) {
8186         CallSiteNumToLPad[*CSI].push_back(&*BB);
8187         MaxCSNum = std::max(MaxCSNum, *CSI);
8188       }
8189       break;
8190     }
8191   }
8192 
8193   // Get an ordered list of the machine basic blocks for the jump table.
8194   std::vector<MachineBasicBlock*> LPadList;
8195   SmallPtrSet<MachineBasicBlock*, 32> InvokeBBs;
8196   LPadList.reserve(CallSiteNumToLPad.size());
8197   for (unsigned I = 1; I <= MaxCSNum; ++I) {
8198     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
8199     for (SmallVectorImpl<MachineBasicBlock*>::iterator
8200            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
8201       LPadList.push_back(*II);
8202       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
8203     }
8204   }
8205 
8206   assert(!LPadList.empty() &&
8207          "No landing pad destinations for the dispatch jump table!");
8208 
8209   // Create the jump table and associated information.
8210   MachineJumpTableInfo *JTI =
8211     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
8212   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
8213 
8214   // Create the MBBs for the dispatch code.
8215 
8216   // Shove the dispatch's address into the return slot in the function context.
8217   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
8218   DispatchBB->setIsEHPad();
8219 
8220   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
8221   unsigned trap_opcode;
8222   if (Subtarget->isThumb())
8223     trap_opcode = ARM::tTRAP;
8224   else
8225     trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
8226 
8227   BuildMI(TrapBB, dl, TII->get(trap_opcode));
8228   DispatchBB->addSuccessor(TrapBB);
8229 
8230   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
8231   DispatchBB->addSuccessor(DispContBB);
8232 
8233   // Insert and MBBs.
8234   MF->insert(MF->end(), DispatchBB);
8235   MF->insert(MF->end(), DispContBB);
8236   MF->insert(MF->end(), TrapBB);
8237 
8238   // Insert code into the entry block that creates and registers the function
8239   // context.
8240   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
8241 
8242   MachineMemOperand *FIMMOLd = MF->getMachineMemOperand(
8243       MachinePointerInfo::getFixedStack(*MF, FI),
8244       MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile, 4, 4);
8245 
8246   MachineInstrBuilder MIB;
8247   MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
8248 
8249   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
8250   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
8251 
8252   // Add a register mask with no preserved registers.  This results in all
8253   // registers being marked as clobbered. This can't work if the dispatch block
8254   // is in a Thumb1 function and is linked with ARM code which uses the FP
8255   // registers, as there is no way to preserve the FP registers in Thumb1 mode.
8256   MIB.addRegMask(RI.getSjLjDispatchPreservedMask(*MF));
8257 
8258   bool IsPositionIndependent = isPositionIndependent();
8259   unsigned NumLPads = LPadList.size();
8260   if (Subtarget->isThumb2()) {
8261     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
8262     BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
8263         .addFrameIndex(FI)
8264         .addImm(4)
8265         .addMemOperand(FIMMOLd)
8266         .add(predOps(ARMCC::AL));
8267 
8268     if (NumLPads < 256) {
8269       BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
8270           .addReg(NewVReg1)
8271           .addImm(LPadList.size())
8272           .add(predOps(ARMCC::AL));
8273     } else {
8274       unsigned VReg1 = MRI->createVirtualRegister(TRC);
8275       BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
8276           .addImm(NumLPads & 0xFFFF)
8277           .add(predOps(ARMCC::AL));
8278 
8279       unsigned VReg2 = VReg1;
8280       if ((NumLPads & 0xFFFF0000) != 0) {
8281         VReg2 = MRI->createVirtualRegister(TRC);
8282         BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
8283             .addReg(VReg1)
8284             .addImm(NumLPads >> 16)
8285             .add(predOps(ARMCC::AL));
8286       }
8287 
8288       BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
8289           .addReg(NewVReg1)
8290           .addReg(VReg2)
8291           .add(predOps(ARMCC::AL));
8292     }
8293 
8294     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
8295       .addMBB(TrapBB)
8296       .addImm(ARMCC::HI)
8297       .addReg(ARM::CPSR);
8298 
8299     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
8300     BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT), NewVReg3)
8301         .addJumpTableIndex(MJTI)
8302         .add(predOps(ARMCC::AL));
8303 
8304     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
8305     BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
8306         .addReg(NewVReg3, RegState::Kill)
8307         .addReg(NewVReg1)
8308         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))
8309         .add(predOps(ARMCC::AL))
8310         .add(condCodeOp());
8311 
8312     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
8313       .addReg(NewVReg4, RegState::Kill)
8314       .addReg(NewVReg1)
8315       .addJumpTableIndex(MJTI);
8316   } else if (Subtarget->isThumb()) {
8317     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
8318     BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
8319         .addFrameIndex(FI)
8320         .addImm(1)
8321         .addMemOperand(FIMMOLd)
8322         .add(predOps(ARMCC::AL));
8323 
8324     if (NumLPads < 256) {
8325       BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
8326           .addReg(NewVReg1)
8327           .addImm(NumLPads)
8328           .add(predOps(ARMCC::AL));
8329     } else {
8330       MachineConstantPool *ConstantPool = MF->getConstantPool();
8331       Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext());
8332       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
8333 
8334       // MachineConstantPool wants an explicit alignment.
8335       unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
8336       if (Align == 0)
8337         Align = MF->getDataLayout().getTypeAllocSize(C->getType());
8338       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
8339 
8340       unsigned VReg1 = MRI->createVirtualRegister(TRC);
8341       BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
8342           .addReg(VReg1, RegState::Define)
8343           .addConstantPoolIndex(Idx)
8344           .add(predOps(ARMCC::AL));
8345       BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
8346           .addReg(NewVReg1)
8347           .addReg(VReg1)
8348           .add(predOps(ARMCC::AL));
8349     }
8350 
8351     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
8352       .addMBB(TrapBB)
8353       .addImm(ARMCC::HI)
8354       .addReg(ARM::CPSR);
8355 
8356     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
8357     BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
8358         .addReg(ARM::CPSR, RegState::Define)
8359         .addReg(NewVReg1)
8360         .addImm(2)
8361         .add(predOps(ARMCC::AL));
8362 
8363     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
8364     BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
8365         .addJumpTableIndex(MJTI)
8366         .add(predOps(ARMCC::AL));
8367 
8368     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
8369     BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
8370         .addReg(ARM::CPSR, RegState::Define)
8371         .addReg(NewVReg2, RegState::Kill)
8372         .addReg(NewVReg3)
8373         .add(predOps(ARMCC::AL));
8374 
8375     MachineMemOperand *JTMMOLd = MF->getMachineMemOperand(
8376         MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4);
8377 
8378     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
8379     BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
8380         .addReg(NewVReg4, RegState::Kill)
8381         .addImm(0)
8382         .addMemOperand(JTMMOLd)
8383         .add(predOps(ARMCC::AL));
8384 
8385     unsigned NewVReg6 = NewVReg5;
8386     if (IsPositionIndependent) {
8387       NewVReg6 = MRI->createVirtualRegister(TRC);
8388       BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
8389           .addReg(ARM::CPSR, RegState::Define)
8390           .addReg(NewVReg5, RegState::Kill)
8391           .addReg(NewVReg3)
8392           .add(predOps(ARMCC::AL));
8393     }
8394 
8395     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
8396       .addReg(NewVReg6, RegState::Kill)
8397       .addJumpTableIndex(MJTI);
8398   } else {
8399     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
8400     BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
8401         .addFrameIndex(FI)
8402         .addImm(4)
8403         .addMemOperand(FIMMOLd)
8404         .add(predOps(ARMCC::AL));
8405 
8406     if (NumLPads < 256) {
8407       BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
8408           .addReg(NewVReg1)
8409           .addImm(NumLPads)
8410           .add(predOps(ARMCC::AL));
8411     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
8412       unsigned VReg1 = MRI->createVirtualRegister(TRC);
8413       BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
8414           .addImm(NumLPads & 0xFFFF)
8415           .add(predOps(ARMCC::AL));
8416 
8417       unsigned VReg2 = VReg1;
8418       if ((NumLPads & 0xFFFF0000) != 0) {
8419         VReg2 = MRI->createVirtualRegister(TRC);
8420         BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
8421             .addReg(VReg1)
8422             .addImm(NumLPads >> 16)
8423             .add(predOps(ARMCC::AL));
8424       }
8425 
8426       BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
8427           .addReg(NewVReg1)
8428           .addReg(VReg2)
8429           .add(predOps(ARMCC::AL));
8430     } else {
8431       MachineConstantPool *ConstantPool = MF->getConstantPool();
8432       Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext());
8433       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
8434 
8435       // MachineConstantPool wants an explicit alignment.
8436       unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
8437       if (Align == 0)
8438         Align = MF->getDataLayout().getTypeAllocSize(C->getType());
8439       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
8440 
8441       unsigned VReg1 = MRI->createVirtualRegister(TRC);
8442       BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
8443           .addReg(VReg1, RegState::Define)
8444           .addConstantPoolIndex(Idx)
8445           .addImm(0)
8446           .add(predOps(ARMCC::AL));
8447       BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
8448           .addReg(NewVReg1)
8449           .addReg(VReg1, RegState::Kill)
8450           .add(predOps(ARMCC::AL));
8451     }
8452 
8453     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
8454       .addMBB(TrapBB)
8455       .addImm(ARMCC::HI)
8456       .addReg(ARM::CPSR);
8457 
8458     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
8459     BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
8460         .addReg(NewVReg1)
8461         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))
8462         .add(predOps(ARMCC::AL))
8463         .add(condCodeOp());
8464     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
8465     BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
8466         .addJumpTableIndex(MJTI)
8467         .add(predOps(ARMCC::AL));
8468 
8469     MachineMemOperand *JTMMOLd = MF->getMachineMemOperand(
8470         MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4);
8471     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
8472     BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
8473         .addReg(NewVReg3, RegState::Kill)
8474         .addReg(NewVReg4)
8475         .addImm(0)
8476         .addMemOperand(JTMMOLd)
8477         .add(predOps(ARMCC::AL));
8478 
8479     if (IsPositionIndependent) {
8480       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
8481         .addReg(NewVReg5, RegState::Kill)
8482         .addReg(NewVReg4)
8483         .addJumpTableIndex(MJTI);
8484     } else {
8485       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
8486         .addReg(NewVReg5, RegState::Kill)
8487         .addJumpTableIndex(MJTI);
8488     }
8489   }
8490 
8491   // Add the jump table entries as successors to the MBB.
8492   SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
8493   for (std::vector<MachineBasicBlock*>::iterator
8494          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
8495     MachineBasicBlock *CurMBB = *I;
8496     if (SeenMBBs.insert(CurMBB).second)
8497       DispContBB->addSuccessor(CurMBB);
8498   }
8499 
8500   // N.B. the order the invoke BBs are processed in doesn't matter here.
8501   const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
8502   SmallVector<MachineBasicBlock*, 64> MBBLPads;
8503   for (MachineBasicBlock *BB : InvokeBBs) {
8504 
8505     // Remove the landing pad successor from the invoke block and replace it
8506     // with the new dispatch block.
8507     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
8508                                                   BB->succ_end());
8509     while (!Successors.empty()) {
8510       MachineBasicBlock *SMBB = Successors.pop_back_val();
8511       if (SMBB->isEHPad()) {
8512         BB->removeSuccessor(SMBB);
8513         MBBLPads.push_back(SMBB);
8514       }
8515     }
8516 
8517     BB->addSuccessor(DispatchBB, BranchProbability::getZero());
8518     BB->normalizeSuccProbs();
8519 
8520     // Find the invoke call and mark all of the callee-saved registers as
8521     // 'implicit defined' so that they're spilled. This prevents code from
8522     // moving instructions to before the EH block, where they will never be
8523     // executed.
8524     for (MachineBasicBlock::reverse_iterator
8525            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
8526       if (!II->isCall()) continue;
8527 
8528       DenseMap<unsigned, bool> DefRegs;
8529       for (MachineInstr::mop_iterator
8530              OI = II->operands_begin(), OE = II->operands_end();
8531            OI != OE; ++OI) {
8532         if (!OI->isReg()) continue;
8533         DefRegs[OI->getReg()] = true;
8534       }
8535 
8536       MachineInstrBuilder MIB(*MF, &*II);
8537 
8538       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
8539         unsigned Reg = SavedRegs[i];
8540         if (Subtarget->isThumb2() &&
8541             !ARM::tGPRRegClass.contains(Reg) &&
8542             !ARM::hGPRRegClass.contains(Reg))
8543           continue;
8544         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
8545           continue;
8546         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
8547           continue;
8548         if (!DefRegs[Reg])
8549           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
8550       }
8551 
8552       break;
8553     }
8554   }
8555 
8556   // Mark all former landing pads as non-landing pads. The dispatch is the only
8557   // landing pad now.
8558   for (SmallVectorImpl<MachineBasicBlock*>::iterator
8559          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
8560     (*I)->setIsEHPad(false);
8561 
8562   // The instruction is gone now.
8563   MI.eraseFromParent();
8564 }
8565 
8566 static
8567 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
8568   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
8569        E = MBB->succ_end(); I != E; ++I)
8570     if (*I != Succ)
8571       return *I;
8572   llvm_unreachable("Expecting a BB with two successors!");
8573 }
8574 
8575 /// Return the load opcode for a given load size. If load size >= 8,
8576 /// neon opcode will be returned.
8577 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
8578   if (LdSize >= 8)
8579     return LdSize == 16 ? ARM::VLD1q32wb_fixed
8580                         : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
8581   if (IsThumb1)
8582     return LdSize == 4 ? ARM::tLDRi
8583                        : LdSize == 2 ? ARM::tLDRHi
8584                                      : LdSize == 1 ? ARM::tLDRBi : 0;
8585   if (IsThumb2)
8586     return LdSize == 4 ? ARM::t2LDR_POST
8587                        : LdSize == 2 ? ARM::t2LDRH_POST
8588                                      : LdSize == 1 ? ARM::t2LDRB_POST : 0;
8589   return LdSize == 4 ? ARM::LDR_POST_IMM
8590                      : LdSize == 2 ? ARM::LDRH_POST
8591                                    : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
8592 }
8593 
8594 /// Return the store opcode for a given store size. If store size >= 8,
8595 /// neon opcode will be returned.
8596 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
8597   if (StSize >= 8)
8598     return StSize == 16 ? ARM::VST1q32wb_fixed
8599                         : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
8600   if (IsThumb1)
8601     return StSize == 4 ? ARM::tSTRi
8602                        : StSize == 2 ? ARM::tSTRHi
8603                                      : StSize == 1 ? ARM::tSTRBi : 0;
8604   if (IsThumb2)
8605     return StSize == 4 ? ARM::t2STR_POST
8606                        : StSize == 2 ? ARM::t2STRH_POST
8607                                      : StSize == 1 ? ARM::t2STRB_POST : 0;
8608   return StSize == 4 ? ARM::STR_POST_IMM
8609                      : StSize == 2 ? ARM::STRH_POST
8610                                    : StSize == 1 ? ARM::STRB_POST_IMM : 0;
8611 }
8612 
8613 /// Emit a post-increment load operation with given size. The instructions
8614 /// will be added to BB at Pos.
8615 static void emitPostLd(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos,
8616                        const TargetInstrInfo *TII, const DebugLoc &dl,
8617                        unsigned LdSize, unsigned Data, unsigned AddrIn,
8618                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
8619   unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
8620   assert(LdOpc != 0 && "Should have a load opcode");
8621   if (LdSize >= 8) {
8622     BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
8623         .addReg(AddrOut, RegState::Define)
8624         .addReg(AddrIn)
8625         .addImm(0)
8626         .add(predOps(ARMCC::AL));
8627   } else if (IsThumb1) {
8628     // load + update AddrIn
8629     BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
8630         .addReg(AddrIn)
8631         .addImm(0)
8632         .add(predOps(ARMCC::AL));
8633     BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut)
8634         .add(t1CondCodeOp())
8635         .addReg(AddrIn)
8636         .addImm(LdSize)
8637         .add(predOps(ARMCC::AL));
8638   } else if (IsThumb2) {
8639     BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
8640         .addReg(AddrOut, RegState::Define)
8641         .addReg(AddrIn)
8642         .addImm(LdSize)
8643         .add(predOps(ARMCC::AL));
8644   } else { // arm
8645     BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
8646         .addReg(AddrOut, RegState::Define)
8647         .addReg(AddrIn)
8648         .addReg(0)
8649         .addImm(LdSize)
8650         .add(predOps(ARMCC::AL));
8651   }
8652 }
8653 
8654 /// Emit a post-increment store operation with given size. The instructions
8655 /// will be added to BB at Pos.
8656 static void emitPostSt(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos,
8657                        const TargetInstrInfo *TII, const DebugLoc &dl,
8658                        unsigned StSize, unsigned Data, unsigned AddrIn,
8659                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
8660   unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
8661   assert(StOpc != 0 && "Should have a store opcode");
8662   if (StSize >= 8) {
8663     BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
8664         .addReg(AddrIn)
8665         .addImm(0)
8666         .addReg(Data)
8667         .add(predOps(ARMCC::AL));
8668   } else if (IsThumb1) {
8669     // store + update AddrIn
8670     BuildMI(*BB, Pos, dl, TII->get(StOpc))
8671         .addReg(Data)
8672         .addReg(AddrIn)
8673         .addImm(0)
8674         .add(predOps(ARMCC::AL));
8675     BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut)
8676         .add(t1CondCodeOp())
8677         .addReg(AddrIn)
8678         .addImm(StSize)
8679         .add(predOps(ARMCC::AL));
8680   } else if (IsThumb2) {
8681     BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
8682         .addReg(Data)
8683         .addReg(AddrIn)
8684         .addImm(StSize)
8685         .add(predOps(ARMCC::AL));
8686   } else { // arm
8687     BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
8688         .addReg(Data)
8689         .addReg(AddrIn)
8690         .addReg(0)
8691         .addImm(StSize)
8692         .add(predOps(ARMCC::AL));
8693   }
8694 }
8695 
8696 MachineBasicBlock *
8697 ARMTargetLowering::EmitStructByval(MachineInstr &MI,
8698                                    MachineBasicBlock *BB) const {
8699   // This pseudo instruction has 3 operands: dst, src, size
8700   // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
8701   // Otherwise, we will generate unrolled scalar copies.
8702   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
8703   const BasicBlock *LLVM_BB = BB->getBasicBlock();
8704   MachineFunction::iterator It = ++BB->getIterator();
8705 
8706   unsigned dest = MI.getOperand(0).getReg();
8707   unsigned src = MI.getOperand(1).getReg();
8708   unsigned SizeVal = MI.getOperand(2).getImm();
8709   unsigned Align = MI.getOperand(3).getImm();
8710   DebugLoc dl = MI.getDebugLoc();
8711 
8712   MachineFunction *MF = BB->getParent();
8713   MachineRegisterInfo &MRI = MF->getRegInfo();
8714   unsigned UnitSize = 0;
8715   const TargetRegisterClass *TRC = nullptr;
8716   const TargetRegisterClass *VecTRC = nullptr;
8717 
8718   bool IsThumb1 = Subtarget->isThumb1Only();
8719   bool IsThumb2 = Subtarget->isThumb2();
8720   bool IsThumb = Subtarget->isThumb();
8721 
8722   if (Align & 1) {
8723     UnitSize = 1;
8724   } else if (Align & 2) {
8725     UnitSize = 2;
8726   } else {
8727     // Check whether we can use NEON instructions.
8728     if (!MF->getFunction().hasFnAttribute(Attribute::NoImplicitFloat) &&
8729         Subtarget->hasNEON()) {
8730       if ((Align % 16 == 0) && SizeVal >= 16)
8731         UnitSize = 16;
8732       else if ((Align % 8 == 0) && SizeVal >= 8)
8733         UnitSize = 8;
8734     }
8735     // Can't use NEON instructions.
8736     if (UnitSize == 0)
8737       UnitSize = 4;
8738   }
8739 
8740   // Select the correct opcode and register class for unit size load/store
8741   bool IsNeon = UnitSize >= 8;
8742   TRC = IsThumb ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
8743   if (IsNeon)
8744     VecTRC = UnitSize == 16 ? &ARM::DPairRegClass
8745                             : UnitSize == 8 ? &ARM::DPRRegClass
8746                                             : nullptr;
8747 
8748   unsigned BytesLeft = SizeVal % UnitSize;
8749   unsigned LoopSize = SizeVal - BytesLeft;
8750 
8751   if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
8752     // Use LDR and STR to copy.
8753     // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
8754     // [destOut] = STR_POST(scratch, destIn, UnitSize)
8755     unsigned srcIn = src;
8756     unsigned destIn = dest;
8757     for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
8758       unsigned srcOut = MRI.createVirtualRegister(TRC);
8759       unsigned destOut = MRI.createVirtualRegister(TRC);
8760       unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
8761       emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
8762                  IsThumb1, IsThumb2);
8763       emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
8764                  IsThumb1, IsThumb2);
8765       srcIn = srcOut;
8766       destIn = destOut;
8767     }
8768 
8769     // Handle the leftover bytes with LDRB and STRB.
8770     // [scratch, srcOut] = LDRB_POST(srcIn, 1)
8771     // [destOut] = STRB_POST(scratch, destIn, 1)
8772     for (unsigned i = 0; i < BytesLeft; i++) {
8773       unsigned srcOut = MRI.createVirtualRegister(TRC);
8774       unsigned destOut = MRI.createVirtualRegister(TRC);
8775       unsigned scratch = MRI.createVirtualRegister(TRC);
8776       emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
8777                  IsThumb1, IsThumb2);
8778       emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
8779                  IsThumb1, IsThumb2);
8780       srcIn = srcOut;
8781       destIn = destOut;
8782     }
8783     MI.eraseFromParent(); // The instruction is gone now.
8784     return BB;
8785   }
8786 
8787   // Expand the pseudo op to a loop.
8788   // thisMBB:
8789   //   ...
8790   //   movw varEnd, # --> with thumb2
8791   //   movt varEnd, #
8792   //   ldrcp varEnd, idx --> without thumb2
8793   //   fallthrough --> loopMBB
8794   // loopMBB:
8795   //   PHI varPhi, varEnd, varLoop
8796   //   PHI srcPhi, src, srcLoop
8797   //   PHI destPhi, dst, destLoop
8798   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
8799   //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
8800   //   subs varLoop, varPhi, #UnitSize
8801   //   bne loopMBB
8802   //   fallthrough --> exitMBB
8803   // exitMBB:
8804   //   epilogue to handle left-over bytes
8805   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
8806   //   [destOut] = STRB_POST(scratch, destLoop, 1)
8807   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
8808   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
8809   MF->insert(It, loopMBB);
8810   MF->insert(It, exitMBB);
8811 
8812   // Transfer the remainder of BB and its successor edges to exitMBB.
8813   exitMBB->splice(exitMBB->begin(), BB,
8814                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
8815   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
8816 
8817   // Load an immediate to varEnd.
8818   unsigned varEnd = MRI.createVirtualRegister(TRC);
8819   if (Subtarget->useMovt(*MF)) {
8820     unsigned Vtmp = varEnd;
8821     if ((LoopSize & 0xFFFF0000) != 0)
8822       Vtmp = MRI.createVirtualRegister(TRC);
8823     BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVi16 : ARM::MOVi16), Vtmp)
8824         .addImm(LoopSize & 0xFFFF)
8825         .add(predOps(ARMCC::AL));
8826 
8827     if ((LoopSize & 0xFFFF0000) != 0)
8828       BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVTi16 : ARM::MOVTi16), varEnd)
8829           .addReg(Vtmp)
8830           .addImm(LoopSize >> 16)
8831           .add(predOps(ARMCC::AL));
8832   } else {
8833     MachineConstantPool *ConstantPool = MF->getConstantPool();
8834     Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext());
8835     const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
8836 
8837     // MachineConstantPool wants an explicit alignment.
8838     unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
8839     if (Align == 0)
8840       Align = MF->getDataLayout().getTypeAllocSize(C->getType());
8841     unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
8842 
8843     if (IsThumb)
8844       BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci))
8845           .addReg(varEnd, RegState::Define)
8846           .addConstantPoolIndex(Idx)
8847           .add(predOps(ARMCC::AL));
8848     else
8849       BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp))
8850           .addReg(varEnd, RegState::Define)
8851           .addConstantPoolIndex(Idx)
8852           .addImm(0)
8853           .add(predOps(ARMCC::AL));
8854   }
8855   BB->addSuccessor(loopMBB);
8856 
8857   // Generate the loop body:
8858   //   varPhi = PHI(varLoop, varEnd)
8859   //   srcPhi = PHI(srcLoop, src)
8860   //   destPhi = PHI(destLoop, dst)
8861   MachineBasicBlock *entryBB = BB;
8862   BB = loopMBB;
8863   unsigned varLoop = MRI.createVirtualRegister(TRC);
8864   unsigned varPhi = MRI.createVirtualRegister(TRC);
8865   unsigned srcLoop = MRI.createVirtualRegister(TRC);
8866   unsigned srcPhi = MRI.createVirtualRegister(TRC);
8867   unsigned destLoop = MRI.createVirtualRegister(TRC);
8868   unsigned destPhi = MRI.createVirtualRegister(TRC);
8869 
8870   BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
8871     .addReg(varLoop).addMBB(loopMBB)
8872     .addReg(varEnd).addMBB(entryBB);
8873   BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
8874     .addReg(srcLoop).addMBB(loopMBB)
8875     .addReg(src).addMBB(entryBB);
8876   BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
8877     .addReg(destLoop).addMBB(loopMBB)
8878     .addReg(dest).addMBB(entryBB);
8879 
8880   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
8881   //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
8882   unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
8883   emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
8884              IsThumb1, IsThumb2);
8885   emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
8886              IsThumb1, IsThumb2);
8887 
8888   // Decrement loop variable by UnitSize.
8889   if (IsThumb1) {
8890     BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop)
8891         .add(t1CondCodeOp())
8892         .addReg(varPhi)
8893         .addImm(UnitSize)
8894         .add(predOps(ARMCC::AL));
8895   } else {
8896     MachineInstrBuilder MIB =
8897         BuildMI(*BB, BB->end(), dl,
8898                 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
8899     MIB.addReg(varPhi)
8900         .addImm(UnitSize)
8901         .add(predOps(ARMCC::AL))
8902         .add(condCodeOp());
8903     MIB->getOperand(5).setReg(ARM::CPSR);
8904     MIB->getOperand(5).setIsDef(true);
8905   }
8906   BuildMI(*BB, BB->end(), dl,
8907           TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
8908       .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
8909 
8910   // loopMBB can loop back to loopMBB or fall through to exitMBB.
8911   BB->addSuccessor(loopMBB);
8912   BB->addSuccessor(exitMBB);
8913 
8914   // Add epilogue to handle BytesLeft.
8915   BB = exitMBB;
8916   auto StartOfExit = exitMBB->begin();
8917 
8918   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
8919   //   [destOut] = STRB_POST(scratch, destLoop, 1)
8920   unsigned srcIn = srcLoop;
8921   unsigned destIn = destLoop;
8922   for (unsigned i = 0; i < BytesLeft; i++) {
8923     unsigned srcOut = MRI.createVirtualRegister(TRC);
8924     unsigned destOut = MRI.createVirtualRegister(TRC);
8925     unsigned scratch = MRI.createVirtualRegister(TRC);
8926     emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
8927                IsThumb1, IsThumb2);
8928     emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
8929                IsThumb1, IsThumb2);
8930     srcIn = srcOut;
8931     destIn = destOut;
8932   }
8933 
8934   MI.eraseFromParent(); // The instruction is gone now.
8935   return BB;
8936 }
8937 
8938 MachineBasicBlock *
8939 ARMTargetLowering::EmitLowered__chkstk(MachineInstr &MI,
8940                                        MachineBasicBlock *MBB) const {
8941   const TargetMachine &TM = getTargetMachine();
8942   const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
8943   DebugLoc DL = MI.getDebugLoc();
8944 
8945   assert(Subtarget->isTargetWindows() &&
8946          "__chkstk is only supported on Windows");
8947   assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
8948 
8949   // __chkstk takes the number of words to allocate on the stack in R4, and
8950   // returns the stack adjustment in number of bytes in R4.  This will not
8951   // clober any other registers (other than the obvious lr).
8952   //
8953   // Although, technically, IP should be considered a register which may be
8954   // clobbered, the call itself will not touch it.  Windows on ARM is a pure
8955   // thumb-2 environment, so there is no interworking required.  As a result, we
8956   // do not expect a veneer to be emitted by the linker, clobbering IP.
8957   //
8958   // Each module receives its own copy of __chkstk, so no import thunk is
8959   // required, again, ensuring that IP is not clobbered.
8960   //
8961   // Finally, although some linkers may theoretically provide a trampoline for
8962   // out of range calls (which is quite common due to a 32M range limitation of
8963   // branches for Thumb), we can generate the long-call version via
8964   // -mcmodel=large, alleviating the need for the trampoline which may clobber
8965   // IP.
8966 
8967   switch (TM.getCodeModel()) {
8968   case CodeModel::Small:
8969   case CodeModel::Medium:
8970   case CodeModel::Kernel:
8971     BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
8972         .add(predOps(ARMCC::AL))
8973         .addExternalSymbol("__chkstk")
8974         .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
8975         .addReg(ARM::R4, RegState::Implicit | RegState::Define)
8976         .addReg(ARM::R12,
8977                 RegState::Implicit | RegState::Define | RegState::Dead)
8978         .addReg(ARM::CPSR,
8979                 RegState::Implicit | RegState::Define | RegState::Dead);
8980     break;
8981   case CodeModel::Large: {
8982     MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
8983     unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
8984 
8985     BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
8986       .addExternalSymbol("__chkstk");
8987     BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
8988         .add(predOps(ARMCC::AL))
8989         .addReg(Reg, RegState::Kill)
8990         .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
8991         .addReg(ARM::R4, RegState::Implicit | RegState::Define)
8992         .addReg(ARM::R12,
8993                 RegState::Implicit | RegState::Define | RegState::Dead)
8994         .addReg(ARM::CPSR,
8995                 RegState::Implicit | RegState::Define | RegState::Dead);
8996     break;
8997   }
8998   }
8999 
9000   BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr), ARM::SP)
9001       .addReg(ARM::SP, RegState::Kill)
9002       .addReg(ARM::R4, RegState::Kill)
9003       .setMIFlags(MachineInstr::FrameSetup)
9004       .add(predOps(ARMCC::AL))
9005       .add(condCodeOp());
9006 
9007   MI.eraseFromParent();
9008   return MBB;
9009 }
9010 
9011 MachineBasicBlock *
9012 ARMTargetLowering::EmitLowered__dbzchk(MachineInstr &MI,
9013                                        MachineBasicBlock *MBB) const {
9014   DebugLoc DL = MI.getDebugLoc();
9015   MachineFunction *MF = MBB->getParent();
9016   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
9017 
9018   MachineBasicBlock *ContBB = MF->CreateMachineBasicBlock();
9019   MF->insert(++MBB->getIterator(), ContBB);
9020   ContBB->splice(ContBB->begin(), MBB,
9021                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
9022   ContBB->transferSuccessorsAndUpdatePHIs(MBB);
9023   MBB->addSuccessor(ContBB);
9024 
9025   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
9026   BuildMI(TrapBB, DL, TII->get(ARM::t__brkdiv0));
9027   MF->push_back(TrapBB);
9028   MBB->addSuccessor(TrapBB);
9029 
9030   BuildMI(*MBB, MI, DL, TII->get(ARM::tCMPi8))
9031       .addReg(MI.getOperand(0).getReg())
9032       .addImm(0)
9033       .add(predOps(ARMCC::AL));
9034   BuildMI(*MBB, MI, DL, TII->get(ARM::t2Bcc))
9035       .addMBB(TrapBB)
9036       .addImm(ARMCC::EQ)
9037       .addReg(ARM::CPSR);
9038 
9039   MI.eraseFromParent();
9040   return ContBB;
9041 }
9042 
9043 MachineBasicBlock *
9044 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
9045                                                MachineBasicBlock *BB) const {
9046   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
9047   DebugLoc dl = MI.getDebugLoc();
9048   bool isThumb2 = Subtarget->isThumb2();
9049   switch (MI.getOpcode()) {
9050   default: {
9051     MI.print(errs());
9052     llvm_unreachable("Unexpected instr type to insert");
9053   }
9054 
9055   // Thumb1 post-indexed loads are really just single-register LDMs.
9056   case ARM::tLDR_postidx: {
9057     MachineOperand Def(MI.getOperand(1));
9058     if (TargetRegisterInfo::isPhysicalRegister(Def.getReg()))
9059       Def.setIsRenamable(false);
9060     BuildMI(*BB, MI, dl, TII->get(ARM::tLDMIA_UPD))
9061         .add(Def)  // Rn_wb
9062         .add(MI.getOperand(2))  // Rn
9063         .add(MI.getOperand(3))  // PredImm
9064         .add(MI.getOperand(4))  // PredReg
9065         .add(MI.getOperand(0)); // Rt
9066     MI.eraseFromParent();
9067     return BB;
9068   }
9069 
9070   // The Thumb2 pre-indexed stores have the same MI operands, they just
9071   // define them differently in the .td files from the isel patterns, so
9072   // they need pseudos.
9073   case ARM::t2STR_preidx:
9074     MI.setDesc(TII->get(ARM::t2STR_PRE));
9075     return BB;
9076   case ARM::t2STRB_preidx:
9077     MI.setDesc(TII->get(ARM::t2STRB_PRE));
9078     return BB;
9079   case ARM::t2STRH_preidx:
9080     MI.setDesc(TII->get(ARM::t2STRH_PRE));
9081     return BB;
9082 
9083   case ARM::STRi_preidx:
9084   case ARM::STRBi_preidx: {
9085     unsigned NewOpc = MI.getOpcode() == ARM::STRi_preidx ? ARM::STR_PRE_IMM
9086                                                          : ARM::STRB_PRE_IMM;
9087     // Decode the offset.
9088     unsigned Offset = MI.getOperand(4).getImm();
9089     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
9090     Offset = ARM_AM::getAM2Offset(Offset);
9091     if (isSub)
9092       Offset = -Offset;
9093 
9094     MachineMemOperand *MMO = *MI.memoperands_begin();
9095     BuildMI(*BB, MI, dl, TII->get(NewOpc))
9096         .add(MI.getOperand(0)) // Rn_wb
9097         .add(MI.getOperand(1)) // Rt
9098         .add(MI.getOperand(2)) // Rn
9099         .addImm(Offset)        // offset (skip GPR==zero_reg)
9100         .add(MI.getOperand(5)) // pred
9101         .add(MI.getOperand(6))
9102         .addMemOperand(MMO);
9103     MI.eraseFromParent();
9104     return BB;
9105   }
9106   case ARM::STRr_preidx:
9107   case ARM::STRBr_preidx:
9108   case ARM::STRH_preidx: {
9109     unsigned NewOpc;
9110     switch (MI.getOpcode()) {
9111     default: llvm_unreachable("unexpected opcode!");
9112     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
9113     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
9114     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
9115     }
9116     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
9117     for (unsigned i = 0; i < MI.getNumOperands(); ++i)
9118       MIB.add(MI.getOperand(i));
9119     MI.eraseFromParent();
9120     return BB;
9121   }
9122 
9123   case ARM::tMOVCCr_pseudo: {
9124     // To "insert" a SELECT_CC instruction, we actually have to insert the
9125     // diamond control-flow pattern.  The incoming instruction knows the
9126     // destination vreg to set, the condition code register to branch on, the
9127     // true/false values to select between, and a branch opcode to use.
9128     const BasicBlock *LLVM_BB = BB->getBasicBlock();
9129     MachineFunction::iterator It = ++BB->getIterator();
9130 
9131     //  thisMBB:
9132     //  ...
9133     //   TrueVal = ...
9134     //   cmpTY ccX, r1, r2
9135     //   bCC copy1MBB
9136     //   fallthrough --> copy0MBB
9137     MachineBasicBlock *thisMBB  = BB;
9138     MachineFunction *F = BB->getParent();
9139     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
9140     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
9141     F->insert(It, copy0MBB);
9142     F->insert(It, sinkMBB);
9143 
9144     // Transfer the remainder of BB and its successor edges to sinkMBB.
9145     sinkMBB->splice(sinkMBB->begin(), BB,
9146                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
9147     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
9148 
9149     BB->addSuccessor(copy0MBB);
9150     BB->addSuccessor(sinkMBB);
9151 
9152     BuildMI(BB, dl, TII->get(ARM::tBcc))
9153         .addMBB(sinkMBB)
9154         .addImm(MI.getOperand(3).getImm())
9155         .addReg(MI.getOperand(4).getReg());
9156 
9157     //  copy0MBB:
9158     //   %FalseValue = ...
9159     //   # fallthrough to sinkMBB
9160     BB = copy0MBB;
9161 
9162     // Update machine-CFG edges
9163     BB->addSuccessor(sinkMBB);
9164 
9165     //  sinkMBB:
9166     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
9167     //  ...
9168     BB = sinkMBB;
9169     BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), MI.getOperand(0).getReg())
9170         .addReg(MI.getOperand(1).getReg())
9171         .addMBB(copy0MBB)
9172         .addReg(MI.getOperand(2).getReg())
9173         .addMBB(thisMBB);
9174 
9175     MI.eraseFromParent(); // The pseudo instruction is gone now.
9176     return BB;
9177   }
9178 
9179   case ARM::BCCi64:
9180   case ARM::BCCZi64: {
9181     // If there is an unconditional branch to the other successor, remove it.
9182     BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
9183 
9184     // Compare both parts that make up the double comparison separately for
9185     // equality.
9186     bool RHSisZero = MI.getOpcode() == ARM::BCCZi64;
9187 
9188     unsigned LHS1 = MI.getOperand(1).getReg();
9189     unsigned LHS2 = MI.getOperand(2).getReg();
9190     if (RHSisZero) {
9191       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
9192           .addReg(LHS1)
9193           .addImm(0)
9194           .add(predOps(ARMCC::AL));
9195       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
9196         .addReg(LHS2).addImm(0)
9197         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
9198     } else {
9199       unsigned RHS1 = MI.getOperand(3).getReg();
9200       unsigned RHS2 = MI.getOperand(4).getReg();
9201       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
9202           .addReg(LHS1)
9203           .addReg(RHS1)
9204           .add(predOps(ARMCC::AL));
9205       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
9206         .addReg(LHS2).addReg(RHS2)
9207         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
9208     }
9209 
9210     MachineBasicBlock *destMBB = MI.getOperand(RHSisZero ? 3 : 5).getMBB();
9211     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
9212     if (MI.getOperand(0).getImm() == ARMCC::NE)
9213       std::swap(destMBB, exitMBB);
9214 
9215     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
9216       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
9217     if (isThumb2)
9218       BuildMI(BB, dl, TII->get(ARM::t2B))
9219           .addMBB(exitMBB)
9220           .add(predOps(ARMCC::AL));
9221     else
9222       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
9223 
9224     MI.eraseFromParent(); // The pseudo instruction is gone now.
9225     return BB;
9226   }
9227 
9228   case ARM::Int_eh_sjlj_setjmp:
9229   case ARM::Int_eh_sjlj_setjmp_nofp:
9230   case ARM::tInt_eh_sjlj_setjmp:
9231   case ARM::t2Int_eh_sjlj_setjmp:
9232   case ARM::t2Int_eh_sjlj_setjmp_nofp:
9233     return BB;
9234 
9235   case ARM::Int_eh_sjlj_setup_dispatch:
9236     EmitSjLjDispatchBlock(MI, BB);
9237     return BB;
9238 
9239   case ARM::ABS:
9240   case ARM::t2ABS: {
9241     // To insert an ABS instruction, we have to insert the
9242     // diamond control-flow pattern.  The incoming instruction knows the
9243     // source vreg to test against 0, the destination vreg to set,
9244     // the condition code register to branch on, the
9245     // true/false values to select between, and a branch opcode to use.
9246     // It transforms
9247     //     V1 = ABS V0
9248     // into
9249     //     V2 = MOVS V0
9250     //     BCC                      (branch to SinkBB if V0 >= 0)
9251     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
9252     //     SinkBB: V1 = PHI(V2, V3)
9253     const BasicBlock *LLVM_BB = BB->getBasicBlock();
9254     MachineFunction::iterator BBI = ++BB->getIterator();
9255     MachineFunction *Fn = BB->getParent();
9256     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
9257     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
9258     Fn->insert(BBI, RSBBB);
9259     Fn->insert(BBI, SinkBB);
9260 
9261     unsigned int ABSSrcReg = MI.getOperand(1).getReg();
9262     unsigned int ABSDstReg = MI.getOperand(0).getReg();
9263     bool ABSSrcKIll = MI.getOperand(1).isKill();
9264     bool isThumb2 = Subtarget->isThumb2();
9265     MachineRegisterInfo &MRI = Fn->getRegInfo();
9266     // In Thumb mode S must not be specified if source register is the SP or
9267     // PC and if destination register is the SP, so restrict register class
9268     unsigned NewRsbDstReg =
9269       MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass);
9270 
9271     // Transfer the remainder of BB and its successor edges to sinkMBB.
9272     SinkBB->splice(SinkBB->begin(), BB,
9273                    std::next(MachineBasicBlock::iterator(MI)), BB->end());
9274     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
9275 
9276     BB->addSuccessor(RSBBB);
9277     BB->addSuccessor(SinkBB);
9278 
9279     // fall through to SinkMBB
9280     RSBBB->addSuccessor(SinkBB);
9281 
9282     // insert a cmp at the end of BB
9283     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
9284         .addReg(ABSSrcReg)
9285         .addImm(0)
9286         .add(predOps(ARMCC::AL));
9287 
9288     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
9289     BuildMI(BB, dl,
9290       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
9291       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
9292 
9293     // insert rsbri in RSBBB
9294     // Note: BCC and rsbri will be converted into predicated rsbmi
9295     // by if-conversion pass
9296     BuildMI(*RSBBB, RSBBB->begin(), dl,
9297             TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
9298         .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0)
9299         .addImm(0)
9300         .add(predOps(ARMCC::AL))
9301         .add(condCodeOp());
9302 
9303     // insert PHI in SinkBB,
9304     // reuse ABSDstReg to not change uses of ABS instruction
9305     BuildMI(*SinkBB, SinkBB->begin(), dl,
9306       TII->get(ARM::PHI), ABSDstReg)
9307       .addReg(NewRsbDstReg).addMBB(RSBBB)
9308       .addReg(ABSSrcReg).addMBB(BB);
9309 
9310     // remove ABS instruction
9311     MI.eraseFromParent();
9312 
9313     // return last added BB
9314     return SinkBB;
9315   }
9316   case ARM::COPY_STRUCT_BYVAL_I32:
9317     ++NumLoopByVals;
9318     return EmitStructByval(MI, BB);
9319   case ARM::WIN__CHKSTK:
9320     return EmitLowered__chkstk(MI, BB);
9321   case ARM::WIN__DBZCHK:
9322     return EmitLowered__dbzchk(MI, BB);
9323   }
9324 }
9325 
9326 /// \brief Attaches vregs to MEMCPY that it will use as scratch registers
9327 /// when it is expanded into LDM/STM. This is done as a post-isel lowering
9328 /// instead of as a custom inserter because we need the use list from the SDNode.
9329 static void attachMEMCPYScratchRegs(const ARMSubtarget *Subtarget,
9330                                     MachineInstr &MI, const SDNode *Node) {
9331   bool isThumb1 = Subtarget->isThumb1Only();
9332 
9333   DebugLoc DL = MI.getDebugLoc();
9334   MachineFunction *MF = MI.getParent()->getParent();
9335   MachineRegisterInfo &MRI = MF->getRegInfo();
9336   MachineInstrBuilder MIB(*MF, MI);
9337 
9338   // If the new dst/src is unused mark it as dead.
9339   if (!Node->hasAnyUseOfValue(0)) {
9340     MI.getOperand(0).setIsDead(true);
9341   }
9342   if (!Node->hasAnyUseOfValue(1)) {
9343     MI.getOperand(1).setIsDead(true);
9344   }
9345 
9346   // The MEMCPY both defines and kills the scratch registers.
9347   for (unsigned I = 0; I != MI.getOperand(4).getImm(); ++I) {
9348     unsigned TmpReg = MRI.createVirtualRegister(isThumb1 ? &ARM::tGPRRegClass
9349                                                          : &ARM::GPRRegClass);
9350     MIB.addReg(TmpReg, RegState::Define|RegState::Dead);
9351   }
9352 }
9353 
9354 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
9355                                                       SDNode *Node) const {
9356   if (MI.getOpcode() == ARM::MEMCPY) {
9357     attachMEMCPYScratchRegs(Subtarget, MI, Node);
9358     return;
9359   }
9360 
9361   const MCInstrDesc *MCID = &MI.getDesc();
9362   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
9363   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
9364   // operand is still set to noreg. If needed, set the optional operand's
9365   // register to CPSR, and remove the redundant implicit def.
9366   //
9367   // e.g. ADCS (..., implicit-def CPSR) -> ADC (... opt:def CPSR).
9368 
9369   // Rename pseudo opcodes.
9370   unsigned NewOpc = convertAddSubFlagsOpcode(MI.getOpcode());
9371   unsigned ccOutIdx;
9372   if (NewOpc) {
9373     const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo();
9374     MCID = &TII->get(NewOpc);
9375 
9376     assert(MCID->getNumOperands() ==
9377            MI.getDesc().getNumOperands() + 5 - MI.getDesc().getSize()
9378         && "converted opcode should be the same except for cc_out"
9379            " (and, on Thumb1, pred)");
9380 
9381     MI.setDesc(*MCID);
9382 
9383     // Add the optional cc_out operand
9384     MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
9385 
9386     // On Thumb1, move all input operands to the end, then add the predicate
9387     if (Subtarget->isThumb1Only()) {
9388       for (unsigned c = MCID->getNumOperands() - 4; c--;) {
9389         MI.addOperand(MI.getOperand(1));
9390         MI.RemoveOperand(1);
9391       }
9392 
9393       // Restore the ties
9394       for (unsigned i = MI.getNumOperands(); i--;) {
9395         const MachineOperand& op = MI.getOperand(i);
9396         if (op.isReg() && op.isUse()) {
9397           int DefIdx = MCID->getOperandConstraint(i, MCOI::TIED_TO);
9398           if (DefIdx != -1)
9399             MI.tieOperands(DefIdx, i);
9400         }
9401       }
9402 
9403       MI.addOperand(MachineOperand::CreateImm(ARMCC::AL));
9404       MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/false));
9405       ccOutIdx = 1;
9406     } else
9407       ccOutIdx = MCID->getNumOperands() - 1;
9408   } else
9409     ccOutIdx = MCID->getNumOperands() - 1;
9410 
9411   // Any ARM instruction that sets the 's' bit should specify an optional
9412   // "cc_out" operand in the last operand position.
9413   if (!MI.hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
9414     assert(!NewOpc && "Optional cc_out operand required");
9415     return;
9416   }
9417   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
9418   // since we already have an optional CPSR def.
9419   bool definesCPSR = false;
9420   bool deadCPSR = false;
9421   for (unsigned i = MCID->getNumOperands(), e = MI.getNumOperands(); i != e;
9422        ++i) {
9423     const MachineOperand &MO = MI.getOperand(i);
9424     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
9425       definesCPSR = true;
9426       if (MO.isDead())
9427         deadCPSR = true;
9428       MI.RemoveOperand(i);
9429       break;
9430     }
9431   }
9432   if (!definesCPSR) {
9433     assert(!NewOpc && "Optional cc_out operand required");
9434     return;
9435   }
9436   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
9437   if (deadCPSR) {
9438     assert(!MI.getOperand(ccOutIdx).getReg() &&
9439            "expect uninitialized optional cc_out operand");
9440     // Thumb1 instructions must have the S bit even if the CPSR is dead.
9441     if (!Subtarget->isThumb1Only())
9442       return;
9443   }
9444 
9445   // If this instruction was defined with an optional CPSR def and its dag node
9446   // had a live implicit CPSR def, then activate the optional CPSR def.
9447   MachineOperand &MO = MI.getOperand(ccOutIdx);
9448   MO.setReg(ARM::CPSR);
9449   MO.setIsDef(true);
9450 }
9451 
9452 //===----------------------------------------------------------------------===//
9453 //                           ARM Optimization Hooks
9454 //===----------------------------------------------------------------------===//
9455 
9456 // Helper function that checks if N is a null or all ones constant.
9457 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
9458   return AllOnes ? isAllOnesConstant(N) : isNullConstant(N);
9459 }
9460 
9461 // Return true if N is conditionally 0 or all ones.
9462 // Detects these expressions where cc is an i1 value:
9463 //
9464 //   (select cc 0, y)   [AllOnes=0]
9465 //   (select cc y, 0)   [AllOnes=0]
9466 //   (zext cc)          [AllOnes=0]
9467 //   (sext cc)          [AllOnes=0/1]
9468 //   (select cc -1, y)  [AllOnes=1]
9469 //   (select cc y, -1)  [AllOnes=1]
9470 //
9471 // Invert is set when N is the null/all ones constant when CC is false.
9472 // OtherOp is set to the alternative value of N.
9473 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
9474                                        SDValue &CC, bool &Invert,
9475                                        SDValue &OtherOp,
9476                                        SelectionDAG &DAG) {
9477   switch (N->getOpcode()) {
9478   default: return false;
9479   case ISD::SELECT: {
9480     CC = N->getOperand(0);
9481     SDValue N1 = N->getOperand(1);
9482     SDValue N2 = N->getOperand(2);
9483     if (isZeroOrAllOnes(N1, AllOnes)) {
9484       Invert = false;
9485       OtherOp = N2;
9486       return true;
9487     }
9488     if (isZeroOrAllOnes(N2, AllOnes)) {
9489       Invert = true;
9490       OtherOp = N1;
9491       return true;
9492     }
9493     return false;
9494   }
9495   case ISD::ZERO_EXTEND:
9496     // (zext cc) can never be the all ones value.
9497     if (AllOnes)
9498       return false;
9499     LLVM_FALLTHROUGH;
9500   case ISD::SIGN_EXTEND: {
9501     SDLoc dl(N);
9502     EVT VT = N->getValueType(0);
9503     CC = N->getOperand(0);
9504     if (CC.getValueType() != MVT::i1 || CC.getOpcode() != ISD::SETCC)
9505       return false;
9506     Invert = !AllOnes;
9507     if (AllOnes)
9508       // When looking for an AllOnes constant, N is an sext, and the 'other'
9509       // value is 0.
9510       OtherOp = DAG.getConstant(0, dl, VT);
9511     else if (N->getOpcode() == ISD::ZERO_EXTEND)
9512       // When looking for a 0 constant, N can be zext or sext.
9513       OtherOp = DAG.getConstant(1, dl, VT);
9514     else
9515       OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl,
9516                                 VT);
9517     return true;
9518   }
9519   }
9520 }
9521 
9522 // Combine a constant select operand into its use:
9523 //
9524 //   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
9525 //   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
9526 //   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
9527 //   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
9528 //   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
9529 //
9530 // The transform is rejected if the select doesn't have a constant operand that
9531 // is null, or all ones when AllOnes is set.
9532 //
9533 // Also recognize sext/zext from i1:
9534 //
9535 //   (add (zext cc), x) -> (select cc (add x, 1), x)
9536 //   (add (sext cc), x) -> (select cc (add x, -1), x)
9537 //
9538 // These transformations eventually create predicated instructions.
9539 //
9540 // @param N       The node to transform.
9541 // @param Slct    The N operand that is a select.
9542 // @param OtherOp The other N operand (x above).
9543 // @param DCI     Context.
9544 // @param AllOnes Require the select constant to be all ones instead of null.
9545 // @returns The new node, or SDValue() on failure.
9546 static
9547 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
9548                             TargetLowering::DAGCombinerInfo &DCI,
9549                             bool AllOnes = false) {
9550   SelectionDAG &DAG = DCI.DAG;
9551   EVT VT = N->getValueType(0);
9552   SDValue NonConstantVal;
9553   SDValue CCOp;
9554   bool SwapSelectOps;
9555   if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
9556                                   NonConstantVal, DAG))
9557     return SDValue();
9558 
9559   // Slct is now know to be the desired identity constant when CC is true.
9560   SDValue TrueVal = OtherOp;
9561   SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
9562                                  OtherOp, NonConstantVal);
9563   // Unless SwapSelectOps says CC should be false.
9564   if (SwapSelectOps)
9565     std::swap(TrueVal, FalseVal);
9566 
9567   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
9568                      CCOp, TrueVal, FalseVal);
9569 }
9570 
9571 // Attempt combineSelectAndUse on each operand of a commutative operator N.
9572 static
9573 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
9574                                        TargetLowering::DAGCombinerInfo &DCI) {
9575   SDValue N0 = N->getOperand(0);
9576   SDValue N1 = N->getOperand(1);
9577   if (N0.getNode()->hasOneUse())
9578     if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes))
9579       return Result;
9580   if (N1.getNode()->hasOneUse())
9581     if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes))
9582       return Result;
9583   return SDValue();
9584 }
9585 
9586 static bool IsVUZPShuffleNode(SDNode *N) {
9587   // VUZP shuffle node.
9588   if (N->getOpcode() == ARMISD::VUZP)
9589     return true;
9590 
9591   // "VUZP" on i32 is an alias for VTRN.
9592   if (N->getOpcode() == ARMISD::VTRN && N->getValueType(0) == MVT::v2i32)
9593     return true;
9594 
9595   return false;
9596 }
9597 
9598 static SDValue AddCombineToVPADD(SDNode *N, SDValue N0, SDValue N1,
9599                                  TargetLowering::DAGCombinerInfo &DCI,
9600                                  const ARMSubtarget *Subtarget) {
9601   // Look for ADD(VUZP.0, VUZP.1).
9602   if (!IsVUZPShuffleNode(N0.getNode()) || N0.getNode() != N1.getNode() ||
9603       N0 == N1)
9604    return SDValue();
9605 
9606   // Make sure the ADD is a 64-bit add; there is no 128-bit VPADD.
9607   if (!N->getValueType(0).is64BitVector())
9608     return SDValue();
9609 
9610   // Generate vpadd.
9611   SelectionDAG &DAG = DCI.DAG;
9612   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9613   SDLoc dl(N);
9614   SDNode *Unzip = N0.getNode();
9615   EVT VT = N->getValueType(0);
9616 
9617   SmallVector<SDValue, 8> Ops;
9618   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpadd, dl,
9619                                 TLI.getPointerTy(DAG.getDataLayout())));
9620   Ops.push_back(Unzip->getOperand(0));
9621   Ops.push_back(Unzip->getOperand(1));
9622 
9623   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops);
9624 }
9625 
9626 static SDValue AddCombineVUZPToVPADDL(SDNode *N, SDValue N0, SDValue N1,
9627                                       TargetLowering::DAGCombinerInfo &DCI,
9628                                       const ARMSubtarget *Subtarget) {
9629   // Check for two extended operands.
9630   if (!(N0.getOpcode() == ISD::SIGN_EXTEND &&
9631         N1.getOpcode() == ISD::SIGN_EXTEND) &&
9632       !(N0.getOpcode() == ISD::ZERO_EXTEND &&
9633         N1.getOpcode() == ISD::ZERO_EXTEND))
9634     return SDValue();
9635 
9636   SDValue N00 = N0.getOperand(0);
9637   SDValue N10 = N1.getOperand(0);
9638 
9639   // Look for ADD(SEXT(VUZP.0), SEXT(VUZP.1))
9640   if (!IsVUZPShuffleNode(N00.getNode()) || N00.getNode() != N10.getNode() ||
9641       N00 == N10)
9642     return SDValue();
9643 
9644   // We only recognize Q register paddl here; this can't be reached until
9645   // after type legalization.
9646   if (!N00.getValueType().is64BitVector() ||
9647       !N0.getValueType().is128BitVector())
9648     return SDValue();
9649 
9650   // Generate vpaddl.
9651   SelectionDAG &DAG = DCI.DAG;
9652   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9653   SDLoc dl(N);
9654   EVT VT = N->getValueType(0);
9655 
9656   SmallVector<SDValue, 8> Ops;
9657   // Form vpaddl.sN or vpaddl.uN depending on the kind of extension.
9658   unsigned Opcode;
9659   if (N0.getOpcode() == ISD::SIGN_EXTEND)
9660     Opcode = Intrinsic::arm_neon_vpaddls;
9661   else
9662     Opcode = Intrinsic::arm_neon_vpaddlu;
9663   Ops.push_back(DAG.getConstant(Opcode, dl,
9664                                 TLI.getPointerTy(DAG.getDataLayout())));
9665   EVT ElemTy = N00.getValueType().getVectorElementType();
9666   unsigned NumElts = VT.getVectorNumElements();
9667   EVT ConcatVT = EVT::getVectorVT(*DAG.getContext(), ElemTy, NumElts * 2);
9668   SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), ConcatVT,
9669                                N00.getOperand(0), N00.getOperand(1));
9670   Ops.push_back(Concat);
9671 
9672   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops);
9673 }
9674 
9675 // FIXME: This function shouldn't be necessary; if we lower BUILD_VECTOR in
9676 // an appropriate manner, we end up with ADD(VUZP(ZEXT(N))), which is
9677 // much easier to match.
9678 static SDValue
9679 AddCombineBUILD_VECTORToVPADDL(SDNode *N, SDValue N0, SDValue N1,
9680                                TargetLowering::DAGCombinerInfo &DCI,
9681                                const ARMSubtarget *Subtarget) {
9682   // Only perform optimization if after legalize, and if NEON is available. We
9683   // also expected both operands to be BUILD_VECTORs.
9684   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
9685       || N0.getOpcode() != ISD::BUILD_VECTOR
9686       || N1.getOpcode() != ISD::BUILD_VECTOR)
9687     return SDValue();
9688 
9689   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
9690   EVT VT = N->getValueType(0);
9691   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
9692     return SDValue();
9693 
9694   // Check that the vector operands are of the right form.
9695   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
9696   // operands, where N is the size of the formed vector.
9697   // Each EXTRACT_VECTOR should have the same input vector and odd or even
9698   // index such that we have a pair wise add pattern.
9699 
9700   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
9701   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9702     return SDValue();
9703   SDValue Vec = N0->getOperand(0)->getOperand(0);
9704   SDNode *V = Vec.getNode();
9705   unsigned nextIndex = 0;
9706 
9707   // For each operands to the ADD which are BUILD_VECTORs,
9708   // check to see if each of their operands are an EXTRACT_VECTOR with
9709   // the same vector and appropriate index.
9710   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
9711     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
9712         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9713 
9714       SDValue ExtVec0 = N0->getOperand(i);
9715       SDValue ExtVec1 = N1->getOperand(i);
9716 
9717       // First operand is the vector, verify its the same.
9718       if (V != ExtVec0->getOperand(0).getNode() ||
9719           V != ExtVec1->getOperand(0).getNode())
9720         return SDValue();
9721 
9722       // Second is the constant, verify its correct.
9723       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
9724       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
9725 
9726       // For the constant, we want to see all the even or all the odd.
9727       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
9728           || C1->getZExtValue() != nextIndex+1)
9729         return SDValue();
9730 
9731       // Increment index.
9732       nextIndex+=2;
9733     } else
9734       return SDValue();
9735   }
9736 
9737   // Don't generate vpaddl+vmovn; we'll match it to vpadd later. Also make sure
9738   // we're using the entire input vector, otherwise there's a size/legality
9739   // mismatch somewhere.
9740   if (nextIndex != Vec.getValueType().getVectorNumElements() ||
9741       Vec.getValueType().getVectorElementType() == VT.getVectorElementType())
9742     return SDValue();
9743 
9744   // Create VPADDL node.
9745   SelectionDAG &DAG = DCI.DAG;
9746   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9747 
9748   SDLoc dl(N);
9749 
9750   // Build operand list.
9751   SmallVector<SDValue, 8> Ops;
9752   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl,
9753                                 TLI.getPointerTy(DAG.getDataLayout())));
9754 
9755   // Input is the vector.
9756   Ops.push_back(Vec);
9757 
9758   // Get widened type and narrowed type.
9759   MVT widenType;
9760   unsigned numElem = VT.getVectorNumElements();
9761 
9762   EVT inputLaneType = Vec.getValueType().getVectorElementType();
9763   switch (inputLaneType.getSimpleVT().SimpleTy) {
9764     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
9765     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
9766     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
9767     default:
9768       llvm_unreachable("Invalid vector element type for padd optimization.");
9769   }
9770 
9771   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops);
9772   unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
9773   return DAG.getNode(ExtOp, dl, VT, tmp);
9774 }
9775 
9776 static SDValue findMUL_LOHI(SDValue V) {
9777   if (V->getOpcode() == ISD::UMUL_LOHI ||
9778       V->getOpcode() == ISD::SMUL_LOHI)
9779     return V;
9780   return SDValue();
9781 }
9782 
9783 static SDValue AddCombineTo64BitSMLAL16(SDNode *AddcNode, SDNode *AddeNode,
9784                                         TargetLowering::DAGCombinerInfo &DCI,
9785                                         const ARMSubtarget *Subtarget) {
9786   if (Subtarget->isThumb()) {
9787     if (!Subtarget->hasDSP())
9788       return SDValue();
9789   } else if (!Subtarget->hasV5TEOps())
9790     return SDValue();
9791 
9792   // SMLALBB, SMLALBT, SMLALTB, SMLALTT multiply two 16-bit values and
9793   // accumulates the product into a 64-bit value. The 16-bit values will
9794   // be sign extended somehow or SRA'd into 32-bit values
9795   // (addc (adde (mul 16bit, 16bit), lo), hi)
9796   SDValue Mul = AddcNode->getOperand(0);
9797   SDValue Lo = AddcNode->getOperand(1);
9798   if (Mul.getOpcode() != ISD::MUL) {
9799     Lo = AddcNode->getOperand(0);
9800     Mul = AddcNode->getOperand(1);
9801     if (Mul.getOpcode() != ISD::MUL)
9802       return SDValue();
9803   }
9804 
9805   SDValue SRA = AddeNode->getOperand(0);
9806   SDValue Hi = AddeNode->getOperand(1);
9807   if (SRA.getOpcode() != ISD::SRA) {
9808     SRA = AddeNode->getOperand(1);
9809     Hi = AddeNode->getOperand(0);
9810     if (SRA.getOpcode() != ISD::SRA)
9811       return SDValue();
9812   }
9813   if (auto Const = dyn_cast<ConstantSDNode>(SRA.getOperand(1))) {
9814     if (Const->getZExtValue() != 31)
9815       return SDValue();
9816   } else
9817     return SDValue();
9818 
9819   if (SRA.getOperand(0) != Mul)
9820     return SDValue();
9821 
9822   SelectionDAG &DAG = DCI.DAG;
9823   SDLoc dl(AddcNode);
9824   unsigned Opcode = 0;
9825   SDValue Op0;
9826   SDValue Op1;
9827 
9828   if (isS16(Mul.getOperand(0), DAG) && isS16(Mul.getOperand(1), DAG)) {
9829     Opcode = ARMISD::SMLALBB;
9830     Op0 = Mul.getOperand(0);
9831     Op1 = Mul.getOperand(1);
9832   } else if (isS16(Mul.getOperand(0), DAG) && isSRA16(Mul.getOperand(1))) {
9833     Opcode = ARMISD::SMLALBT;
9834     Op0 = Mul.getOperand(0);
9835     Op1 = Mul.getOperand(1).getOperand(0);
9836   } else if (isSRA16(Mul.getOperand(0)) && isS16(Mul.getOperand(1), DAG)) {
9837     Opcode = ARMISD::SMLALTB;
9838     Op0 = Mul.getOperand(0).getOperand(0);
9839     Op1 = Mul.getOperand(1);
9840   } else if (isSRA16(Mul.getOperand(0)) && isSRA16(Mul.getOperand(1))) {
9841     Opcode = ARMISD::SMLALTT;
9842     Op0 = Mul->getOperand(0).getOperand(0);
9843     Op1 = Mul->getOperand(1).getOperand(0);
9844   }
9845 
9846   if (!Op0 || !Op1)
9847     return SDValue();
9848 
9849   SDValue SMLAL = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
9850                               Op0, Op1, Lo, Hi);
9851   // Replace the ADDs' nodes uses by the MLA node's values.
9852   SDValue HiMLALResult(SMLAL.getNode(), 1);
9853   SDValue LoMLALResult(SMLAL.getNode(), 0);
9854 
9855   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
9856   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
9857 
9858   // Return original node to notify the driver to stop replacing.
9859   SDValue resNode(AddcNode, 0);
9860   return resNode;
9861 }
9862 
9863 static SDValue AddCombineTo64bitMLAL(SDNode *AddeNode,
9864                                      TargetLowering::DAGCombinerInfo &DCI,
9865                                      const ARMSubtarget *Subtarget) {
9866   // Look for multiply add opportunities.
9867   // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
9868   // each add nodes consumes a value from ISD::UMUL_LOHI and there is
9869   // a glue link from the first add to the second add.
9870   // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
9871   // a S/UMLAL instruction.
9872   //                  UMUL_LOHI
9873   //                 / :lo    \ :hi
9874   //                V          \          [no multiline comment]
9875   //    loAdd ->  ADDC         |
9876   //                 \ :carry /
9877   //                  V      V
9878   //                    ADDE   <- hiAdd
9879   //
9880   assert(AddeNode->getOpcode() == ARMISD::ADDE && "Expect an ADDE");
9881 
9882   assert(AddeNode->getNumOperands() == 3 &&
9883          AddeNode->getOperand(2).getValueType() == MVT::i32 &&
9884          "ADDE node has the wrong inputs");
9885 
9886   // Check that we are chained to the right ADDC node.
9887   SDNode* AddcNode = AddeNode->getOperand(2).getNode();
9888   if (AddcNode->getOpcode() != ARMISD::ADDC)
9889     return SDValue();
9890 
9891   SDValue AddcOp0 = AddcNode->getOperand(0);
9892   SDValue AddcOp1 = AddcNode->getOperand(1);
9893 
9894   // Check if the two operands are from the same mul_lohi node.
9895   if (AddcOp0.getNode() == AddcOp1.getNode())
9896     return SDValue();
9897 
9898   assert(AddcNode->getNumValues() == 2 &&
9899          AddcNode->getValueType(0) == MVT::i32 &&
9900          "Expect ADDC with two result values. First: i32");
9901 
9902   // Check that the ADDC adds the low result of the S/UMUL_LOHI. If not, it
9903   // maybe a SMLAL which multiplies two 16-bit values.
9904   if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
9905       AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
9906       AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
9907       AddcOp1->getOpcode() != ISD::SMUL_LOHI)
9908     return AddCombineTo64BitSMLAL16(AddcNode, AddeNode, DCI, Subtarget);
9909 
9910   // Check for the triangle shape.
9911   SDValue AddeOp0 = AddeNode->getOperand(0);
9912   SDValue AddeOp1 = AddeNode->getOperand(1);
9913 
9914   // Make sure that the ADDE operands are not coming from the same node.
9915   if (AddeOp0.getNode() == AddeOp1.getNode())
9916     return SDValue();
9917 
9918   // Find the MUL_LOHI node walking up ADDE's operands.
9919   bool IsLeftOperandMUL = false;
9920   SDValue MULOp = findMUL_LOHI(AddeOp0);
9921   if (MULOp == SDValue())
9922    MULOp = findMUL_LOHI(AddeOp1);
9923   else
9924     IsLeftOperandMUL = true;
9925   if (MULOp == SDValue())
9926     return SDValue();
9927 
9928   // Figure out the right opcode.
9929   unsigned Opc = MULOp->getOpcode();
9930   unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
9931 
9932   // Figure out the high and low input values to the MLAL node.
9933   SDValue* HiAdd = nullptr;
9934   SDValue* LoMul = nullptr;
9935   SDValue* LowAdd = nullptr;
9936 
9937   // Ensure that ADDE is from high result of ISD::xMUL_LOHI.
9938   if ((AddeOp0 != MULOp.getValue(1)) && (AddeOp1 != MULOp.getValue(1)))
9939     return SDValue();
9940 
9941   if (IsLeftOperandMUL)
9942     HiAdd = &AddeOp1;
9943   else
9944     HiAdd = &AddeOp0;
9945 
9946 
9947   // Ensure that LoMul and LowAdd are taken from correct ISD::SMUL_LOHI node
9948   // whose low result is fed to the ADDC we are checking.
9949 
9950   if (AddcOp0 == MULOp.getValue(0)) {
9951     LoMul = &AddcOp0;
9952     LowAdd = &AddcOp1;
9953   }
9954   if (AddcOp1 == MULOp.getValue(0)) {
9955     LoMul = &AddcOp1;
9956     LowAdd = &AddcOp0;
9957   }
9958 
9959   if (!LoMul)
9960     return SDValue();
9961 
9962   // If HiAdd is the same node as ADDC or is a predecessor of ADDC the
9963   // replacement below will create a cycle.
9964   if (AddcNode == HiAdd->getNode() ||
9965       AddcNode->isPredecessorOf(HiAdd->getNode()))
9966     return SDValue();
9967 
9968   // Create the merged node.
9969   SelectionDAG &DAG = DCI.DAG;
9970 
9971   // Build operand list.
9972   SmallVector<SDValue, 8> Ops;
9973   Ops.push_back(LoMul->getOperand(0));
9974   Ops.push_back(LoMul->getOperand(1));
9975   Ops.push_back(*LowAdd);
9976   Ops.push_back(*HiAdd);
9977 
9978   SDValue MLALNode =  DAG.getNode(FinalOpc, SDLoc(AddcNode),
9979                                  DAG.getVTList(MVT::i32, MVT::i32), Ops);
9980 
9981   // Replace the ADDs' nodes uses by the MLA node's values.
9982   SDValue HiMLALResult(MLALNode.getNode(), 1);
9983   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
9984 
9985   SDValue LoMLALResult(MLALNode.getNode(), 0);
9986   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
9987 
9988   // Return original node to notify the driver to stop replacing.
9989   return SDValue(AddeNode, 0);
9990 }
9991 
9992 static SDValue AddCombineTo64bitUMAAL(SDNode *AddeNode,
9993                                       TargetLowering::DAGCombinerInfo &DCI,
9994                                       const ARMSubtarget *Subtarget) {
9995   // UMAAL is similar to UMLAL except that it adds two unsigned values.
9996   // While trying to combine for the other MLAL nodes, first search for the
9997   // chance to use UMAAL. Check if Addc uses a node which has already
9998   // been combined into a UMLAL. The other pattern is UMLAL using Addc/Adde
9999   // as the addend, and it's handled in PerformUMLALCombine.
10000 
10001   if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP())
10002     return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget);
10003 
10004   // Check that we have a glued ADDC node.
10005   SDNode* AddcNode = AddeNode->getOperand(2).getNode();
10006   if (AddcNode->getOpcode() != ARMISD::ADDC)
10007     return SDValue();
10008 
10009   // Find the converted UMAAL or quit if it doesn't exist.
10010   SDNode *UmlalNode = nullptr;
10011   SDValue AddHi;
10012   if (AddcNode->getOperand(0).getOpcode() == ARMISD::UMLAL) {
10013     UmlalNode = AddcNode->getOperand(0).getNode();
10014     AddHi = AddcNode->getOperand(1);
10015   } else if (AddcNode->getOperand(1).getOpcode() == ARMISD::UMLAL) {
10016     UmlalNode = AddcNode->getOperand(1).getNode();
10017     AddHi = AddcNode->getOperand(0);
10018   } else {
10019     return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget);
10020   }
10021 
10022   // The ADDC should be glued to an ADDE node, which uses the same UMLAL as
10023   // the ADDC as well as Zero.
10024   if (!isNullConstant(UmlalNode->getOperand(3)))
10025     return SDValue();
10026 
10027   if ((isNullConstant(AddeNode->getOperand(0)) &&
10028        AddeNode->getOperand(1).getNode() == UmlalNode) ||
10029       (AddeNode->getOperand(0).getNode() == UmlalNode &&
10030        isNullConstant(AddeNode->getOperand(1)))) {
10031     SelectionDAG &DAG = DCI.DAG;
10032     SDValue Ops[] = { UmlalNode->getOperand(0), UmlalNode->getOperand(1),
10033                       UmlalNode->getOperand(2), AddHi };
10034     SDValue UMAAL =  DAG.getNode(ARMISD::UMAAL, SDLoc(AddcNode),
10035                                  DAG.getVTList(MVT::i32, MVT::i32), Ops);
10036 
10037     // Replace the ADDs' nodes uses by the UMAAL node's values.
10038     DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), SDValue(UMAAL.getNode(), 1));
10039     DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), SDValue(UMAAL.getNode(), 0));
10040 
10041     // Return original node to notify the driver to stop replacing.
10042     return SDValue(AddeNode, 0);
10043   }
10044   return SDValue();
10045 }
10046 
10047 static SDValue PerformUMLALCombine(SDNode *N, SelectionDAG &DAG,
10048                                    const ARMSubtarget *Subtarget) {
10049   if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP())
10050     return SDValue();
10051 
10052   // Check that we have a pair of ADDC and ADDE as operands.
10053   // Both addends of the ADDE must be zero.
10054   SDNode* AddcNode = N->getOperand(2).getNode();
10055   SDNode* AddeNode = N->getOperand(3).getNode();
10056   if ((AddcNode->getOpcode() == ARMISD::ADDC) &&
10057       (AddeNode->getOpcode() == ARMISD::ADDE) &&
10058       isNullConstant(AddeNode->getOperand(0)) &&
10059       isNullConstant(AddeNode->getOperand(1)) &&
10060       (AddeNode->getOperand(2).getNode() == AddcNode))
10061     return DAG.getNode(ARMISD::UMAAL, SDLoc(N),
10062                        DAG.getVTList(MVT::i32, MVT::i32),
10063                        {N->getOperand(0), N->getOperand(1),
10064                         AddcNode->getOperand(0), AddcNode->getOperand(1)});
10065   else
10066     return SDValue();
10067 }
10068 
10069 static SDValue PerformAddcSubcCombine(SDNode *N,
10070                                       TargetLowering::DAGCombinerInfo &DCI,
10071                                       const ARMSubtarget *Subtarget) {
10072   SelectionDAG &DAG(DCI.DAG);
10073 
10074   if (N->getOpcode() == ARMISD::ADDC) {
10075     // (ADDC (ADDE 0, 0, C), -1) -> C
10076     SDValue LHS = N->getOperand(0);
10077     SDValue RHS = N->getOperand(1);
10078     if (LHS->getOpcode() == ARMISD::ADDE &&
10079         isNullConstant(LHS->getOperand(0)) &&
10080         isNullConstant(LHS->getOperand(1)) && isAllOnesConstant(RHS)) {
10081       return DCI.CombineTo(N, SDValue(N, 0), LHS->getOperand(2));
10082     }
10083   }
10084 
10085   if (Subtarget->isThumb1Only()) {
10086     SDValue RHS = N->getOperand(1);
10087     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) {
10088       int32_t imm = C->getSExtValue();
10089       if (imm < 0 && imm > std::numeric_limits<int>::min()) {
10090         SDLoc DL(N);
10091         RHS = DAG.getConstant(-imm, DL, MVT::i32);
10092         unsigned Opcode = (N->getOpcode() == ARMISD::ADDC) ? ARMISD::SUBC
10093                                                            : ARMISD::ADDC;
10094         return DAG.getNode(Opcode, DL, N->getVTList(), N->getOperand(0), RHS);
10095       }
10096     }
10097   }
10098   return SDValue();
10099 }
10100 
10101 static SDValue PerformAddeSubeCombine(SDNode *N, SelectionDAG &DAG,
10102                                       const ARMSubtarget *Subtarget) {
10103   if (Subtarget->isThumb1Only()) {
10104     SDValue RHS = N->getOperand(1);
10105     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) {
10106       int64_t imm = C->getSExtValue();
10107       if (imm < 0) {
10108         SDLoc DL(N);
10109 
10110         // The with-carry-in form matches bitwise not instead of the negation.
10111         // Effectively, the inverse interpretation of the carry flag already
10112         // accounts for part of the negation.
10113         RHS = DAG.getConstant(~imm, DL, MVT::i32);
10114 
10115         unsigned Opcode = (N->getOpcode() == ARMISD::ADDE) ? ARMISD::SUBE
10116                                                            : ARMISD::ADDE;
10117         return DAG.getNode(Opcode, DL, N->getVTList(),
10118                            N->getOperand(0), RHS, N->getOperand(2));
10119       }
10120     }
10121   }
10122   return SDValue();
10123 }
10124 
10125 /// PerformADDECombine - Target-specific dag combine transform from
10126 /// ARMISD::ADDC, ARMISD::ADDE, and ISD::MUL_LOHI to MLAL or
10127 /// ARMISD::ADDC, ARMISD::ADDE and ARMISD::UMLAL to ARMISD::UMAAL
10128 static SDValue PerformADDECombine(SDNode *N,
10129                                   TargetLowering::DAGCombinerInfo &DCI,
10130                                   const ARMSubtarget *Subtarget) {
10131   // Only ARM and Thumb2 support UMLAL/SMLAL.
10132   if (Subtarget->isThumb1Only())
10133     return PerformAddeSubeCombine(N, DCI.DAG, Subtarget);
10134 
10135   // Only perform the checks after legalize when the pattern is available.
10136   if (DCI.isBeforeLegalize()) return SDValue();
10137 
10138   return AddCombineTo64bitUMAAL(N, DCI, Subtarget);
10139 }
10140 
10141 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
10142 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
10143 /// called with the default operands, and if that fails, with commuted
10144 /// operands.
10145 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
10146                                           TargetLowering::DAGCombinerInfo &DCI,
10147                                           const ARMSubtarget *Subtarget){
10148   // Attempt to create vpadd for this add.
10149   if (SDValue Result = AddCombineToVPADD(N, N0, N1, DCI, Subtarget))
10150     return Result;
10151 
10152   // Attempt to create vpaddl for this add.
10153   if (SDValue Result = AddCombineVUZPToVPADDL(N, N0, N1, DCI, Subtarget))
10154     return Result;
10155   if (SDValue Result = AddCombineBUILD_VECTORToVPADDL(N, N0, N1, DCI,
10156                                                       Subtarget))
10157     return Result;
10158 
10159   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
10160   if (N0.getNode()->hasOneUse())
10161     if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI))
10162       return Result;
10163   return SDValue();
10164 }
10165 
10166 static SDValue PerformSHLSimplify(SDNode *N,
10167                                 TargetLowering::DAGCombinerInfo &DCI,
10168                                 const ARMSubtarget *ST) {
10169   // Allow the generic combiner to identify potential bswaps.
10170   if (DCI.isBeforeLegalize())
10171     return SDValue();
10172 
10173   // DAG combiner will fold:
10174   // (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
10175   // (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2
10176   // Other code patterns that can be also be modified have the following form:
10177   // b + ((a << 1) | 510)
10178   // b + ((a << 1) & 510)
10179   // b + ((a << 1) ^ 510)
10180   // b + ((a << 1) + 510)
10181 
10182   // Many instructions can  perform the shift for free, but it requires both
10183   // the operands to be registers. If c1 << c2 is too large, a mov immediate
10184   // instruction will needed. So, unfold back to the original pattern if:
10185   // - if c1 and c2 are small enough that they don't require mov imms.
10186   // - the user(s) of the node can perform an shl
10187 
10188   // No shifted operands for 16-bit instructions.
10189   if (ST->isThumb() && ST->isThumb1Only())
10190     return SDValue();
10191 
10192   // Check that all the users could perform the shl themselves.
10193   for (auto U : N->uses()) {
10194     switch(U->getOpcode()) {
10195     default:
10196       return SDValue();
10197     case ISD::SUB:
10198     case ISD::ADD:
10199     case ISD::AND:
10200     case ISD::OR:
10201     case ISD::XOR:
10202     case ISD::SETCC:
10203     case ARMISD::CMP:
10204       // Check that the user isn't already using a constant because there
10205       // aren't any instructions that support an immediate operand and a
10206       // shifted operand.
10207       if (isa<ConstantSDNode>(U->getOperand(0)) ||
10208           isa<ConstantSDNode>(U->getOperand(1)))
10209         return SDValue();
10210 
10211       // Check that it's not already using a shift.
10212       if (U->getOperand(0).getOpcode() == ISD::SHL ||
10213           U->getOperand(1).getOpcode() == ISD::SHL)
10214         return SDValue();
10215       break;
10216     }
10217   }
10218 
10219   if (N->getOpcode() != ISD::ADD && N->getOpcode() != ISD::OR &&
10220       N->getOpcode() != ISD::XOR && N->getOpcode() != ISD::AND)
10221     return SDValue();
10222 
10223   if (N->getOperand(0).getOpcode() != ISD::SHL)
10224     return SDValue();
10225 
10226   SDValue SHL = N->getOperand(0);
10227 
10228   auto *C1ShlC2 = dyn_cast<ConstantSDNode>(N->getOperand(1));
10229   auto *C2 = dyn_cast<ConstantSDNode>(SHL.getOperand(1));
10230   if (!C1ShlC2 || !C2)
10231     return SDValue();
10232 
10233   APInt C2Int = C2->getAPIntValue();
10234   APInt C1Int = C1ShlC2->getAPIntValue();
10235 
10236   // Check that performing a lshr will not lose any information.
10237   APInt Mask = APInt::getHighBitsSet(C2Int.getBitWidth(),
10238                                      C2Int.getBitWidth() - C2->getZExtValue());
10239   if ((C1Int & Mask) != C1Int)
10240     return SDValue();
10241 
10242   // Shift the first constant.
10243   C1Int.lshrInPlace(C2Int);
10244 
10245   // The immediates are encoded as an 8-bit value that can be rotated.
10246   auto LargeImm = [](const APInt &Imm) {
10247     unsigned Zeros = Imm.countLeadingZeros() + Imm.countTrailingZeros();
10248     return Imm.getBitWidth() - Zeros > 8;
10249   };
10250 
10251   if (LargeImm(C1Int) || LargeImm(C2Int))
10252     return SDValue();
10253 
10254   SelectionDAG &DAG = DCI.DAG;
10255   SDLoc dl(N);
10256   SDValue X = SHL.getOperand(0);
10257   SDValue BinOp = DAG.getNode(N->getOpcode(), dl, MVT::i32, X,
10258                               DAG.getConstant(C1Int, dl, MVT::i32));
10259   // Shift left to compensate for the lshr of C1Int.
10260   SDValue Res = DAG.getNode(ISD::SHL, dl, MVT::i32, BinOp, SHL.getOperand(1));
10261 
10262   DEBUG(dbgs() << "Simplify shl use:\n"; SHL.getOperand(0).dump(); SHL.dump();
10263         N->dump());
10264   DEBUG(dbgs() << "Into:\n"; X.dump(); BinOp.dump(); Res.dump());
10265 
10266   DAG.ReplaceAllUsesWith(SDValue(N, 0), Res);
10267   return SDValue(N, 0);
10268 }
10269 
10270 
10271 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
10272 ///
10273 static SDValue PerformADDCombine(SDNode *N,
10274                                  TargetLowering::DAGCombinerInfo &DCI,
10275                                  const ARMSubtarget *Subtarget) {
10276   SDValue N0 = N->getOperand(0);
10277   SDValue N1 = N->getOperand(1);
10278 
10279   // Only works one way, because it needs an immediate operand.
10280   if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
10281     return Result;
10282 
10283   // First try with the default operand order.
10284   if (SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget))
10285     return Result;
10286 
10287   // If that didn't work, try again with the operands commuted.
10288   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
10289 }
10290 
10291 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
10292 ///
10293 static SDValue PerformSUBCombine(SDNode *N,
10294                                  TargetLowering::DAGCombinerInfo &DCI) {
10295   SDValue N0 = N->getOperand(0);
10296   SDValue N1 = N->getOperand(1);
10297 
10298   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
10299   if (N1.getNode()->hasOneUse())
10300     if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI))
10301       return Result;
10302 
10303   return SDValue();
10304 }
10305 
10306 /// PerformVMULCombine
10307 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
10308 /// special multiplier accumulator forwarding.
10309 ///   vmul d3, d0, d2
10310 ///   vmla d3, d1, d2
10311 /// is faster than
10312 ///   vadd d3, d0, d1
10313 ///   vmul d3, d3, d2
10314 //  However, for (A + B) * (A + B),
10315 //    vadd d2, d0, d1
10316 //    vmul d3, d0, d2
10317 //    vmla d3, d1, d2
10318 //  is slower than
10319 //    vadd d2, d0, d1
10320 //    vmul d3, d2, d2
10321 static SDValue PerformVMULCombine(SDNode *N,
10322                                   TargetLowering::DAGCombinerInfo &DCI,
10323                                   const ARMSubtarget *Subtarget) {
10324   if (!Subtarget->hasVMLxForwarding())
10325     return SDValue();
10326 
10327   SelectionDAG &DAG = DCI.DAG;
10328   SDValue N0 = N->getOperand(0);
10329   SDValue N1 = N->getOperand(1);
10330   unsigned Opcode = N0.getOpcode();
10331   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
10332       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
10333     Opcode = N1.getOpcode();
10334     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
10335         Opcode != ISD::FADD && Opcode != ISD::FSUB)
10336       return SDValue();
10337     std::swap(N0, N1);
10338   }
10339 
10340   if (N0 == N1)
10341     return SDValue();
10342 
10343   EVT VT = N->getValueType(0);
10344   SDLoc DL(N);
10345   SDValue N00 = N0->getOperand(0);
10346   SDValue N01 = N0->getOperand(1);
10347   return DAG.getNode(Opcode, DL, VT,
10348                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
10349                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
10350 }
10351 
10352 static SDValue PerformMULCombine(SDNode *N,
10353                                  TargetLowering::DAGCombinerInfo &DCI,
10354                                  const ARMSubtarget *Subtarget) {
10355   SelectionDAG &DAG = DCI.DAG;
10356 
10357   if (Subtarget->isThumb1Only())
10358     return SDValue();
10359 
10360   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
10361     return SDValue();
10362 
10363   EVT VT = N->getValueType(0);
10364   if (VT.is64BitVector() || VT.is128BitVector())
10365     return PerformVMULCombine(N, DCI, Subtarget);
10366   if (VT != MVT::i32)
10367     return SDValue();
10368 
10369   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
10370   if (!C)
10371     return SDValue();
10372 
10373   int64_t MulAmt = C->getSExtValue();
10374   unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
10375 
10376   ShiftAmt = ShiftAmt & (32 - 1);
10377   SDValue V = N->getOperand(0);
10378   SDLoc DL(N);
10379 
10380   SDValue Res;
10381   MulAmt >>= ShiftAmt;
10382 
10383   if (MulAmt >= 0) {
10384     if (isPowerOf2_32(MulAmt - 1)) {
10385       // (mul x, 2^N + 1) => (add (shl x, N), x)
10386       Res = DAG.getNode(ISD::ADD, DL, VT,
10387                         V,
10388                         DAG.getNode(ISD::SHL, DL, VT,
10389                                     V,
10390                                     DAG.getConstant(Log2_32(MulAmt - 1), DL,
10391                                                     MVT::i32)));
10392     } else if (isPowerOf2_32(MulAmt + 1)) {
10393       // (mul x, 2^N - 1) => (sub (shl x, N), x)
10394       Res = DAG.getNode(ISD::SUB, DL, VT,
10395                         DAG.getNode(ISD::SHL, DL, VT,
10396                                     V,
10397                                     DAG.getConstant(Log2_32(MulAmt + 1), DL,
10398                                                     MVT::i32)),
10399                         V);
10400     } else
10401       return SDValue();
10402   } else {
10403     uint64_t MulAmtAbs = -MulAmt;
10404     if (isPowerOf2_32(MulAmtAbs + 1)) {
10405       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
10406       Res = DAG.getNode(ISD::SUB, DL, VT,
10407                         V,
10408                         DAG.getNode(ISD::SHL, DL, VT,
10409                                     V,
10410                                     DAG.getConstant(Log2_32(MulAmtAbs + 1), DL,
10411                                                     MVT::i32)));
10412     } else if (isPowerOf2_32(MulAmtAbs - 1)) {
10413       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
10414       Res = DAG.getNode(ISD::ADD, DL, VT,
10415                         V,
10416                         DAG.getNode(ISD::SHL, DL, VT,
10417                                     V,
10418                                     DAG.getConstant(Log2_32(MulAmtAbs - 1), DL,
10419                                                     MVT::i32)));
10420       Res = DAG.getNode(ISD::SUB, DL, VT,
10421                         DAG.getConstant(0, DL, MVT::i32), Res);
10422     } else
10423       return SDValue();
10424   }
10425 
10426   if (ShiftAmt != 0)
10427     Res = DAG.getNode(ISD::SHL, DL, VT,
10428                       Res, DAG.getConstant(ShiftAmt, DL, MVT::i32));
10429 
10430   // Do not add new nodes to DAG combiner worklist.
10431   DCI.CombineTo(N, Res, false);
10432   return SDValue();
10433 }
10434 
10435 static SDValue PerformANDCombine(SDNode *N,
10436                                  TargetLowering::DAGCombinerInfo &DCI,
10437                                  const ARMSubtarget *Subtarget) {
10438   // Attempt to use immediate-form VBIC
10439   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
10440   SDLoc dl(N);
10441   EVT VT = N->getValueType(0);
10442   SelectionDAG &DAG = DCI.DAG;
10443 
10444   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
10445     return SDValue();
10446 
10447   APInt SplatBits, SplatUndef;
10448   unsigned SplatBitSize;
10449   bool HasAnyUndefs;
10450   if (BVN &&
10451       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
10452     if (SplatBitSize <= 64) {
10453       EVT VbicVT;
10454       SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
10455                                       SplatUndef.getZExtValue(), SplatBitSize,
10456                                       DAG, dl, VbicVT, VT.is128BitVector(),
10457                                       OtherModImm);
10458       if (Val.getNode()) {
10459         SDValue Input =
10460           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
10461         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
10462         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
10463       }
10464     }
10465   }
10466 
10467   if (!Subtarget->isThumb1Only()) {
10468     // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
10469     if (SDValue Result = combineSelectAndUseCommutative(N, true, DCI))
10470       return Result;
10471 
10472     if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
10473       return Result;
10474   }
10475 
10476   return SDValue();
10477 }
10478 
10479 // Try combining OR nodes to SMULWB, SMULWT.
10480 static SDValue PerformORCombineToSMULWBT(SDNode *OR,
10481                                          TargetLowering::DAGCombinerInfo &DCI,
10482                                          const ARMSubtarget *Subtarget) {
10483   if (!Subtarget->hasV6Ops() ||
10484       (Subtarget->isThumb() &&
10485        (!Subtarget->hasThumb2() || !Subtarget->hasDSP())))
10486     return SDValue();
10487 
10488   SDValue SRL = OR->getOperand(0);
10489   SDValue SHL = OR->getOperand(1);
10490 
10491   if (SRL.getOpcode() != ISD::SRL || SHL.getOpcode() != ISD::SHL) {
10492     SRL = OR->getOperand(1);
10493     SHL = OR->getOperand(0);
10494   }
10495   if (!isSRL16(SRL) || !isSHL16(SHL))
10496     return SDValue();
10497 
10498   // The first operands to the shifts need to be the two results from the
10499   // same smul_lohi node.
10500   if ((SRL.getOperand(0).getNode() != SHL.getOperand(0).getNode()) ||
10501        SRL.getOperand(0).getOpcode() != ISD::SMUL_LOHI)
10502     return SDValue();
10503 
10504   SDNode *SMULLOHI = SRL.getOperand(0).getNode();
10505   if (SRL.getOperand(0) != SDValue(SMULLOHI, 0) ||
10506       SHL.getOperand(0) != SDValue(SMULLOHI, 1))
10507     return SDValue();
10508 
10509   // Now we have:
10510   // (or (srl (smul_lohi ?, ?), 16), (shl (smul_lohi ?, ?), 16)))
10511   // For SMUL[B|T] smul_lohi will take a 32-bit and a 16-bit arguments.
10512   // For SMUWB the 16-bit value will signed extended somehow.
10513   // For SMULWT only the SRA is required.
10514   // Check both sides of SMUL_LOHI
10515   SDValue OpS16 = SMULLOHI->getOperand(0);
10516   SDValue OpS32 = SMULLOHI->getOperand(1);
10517 
10518   SelectionDAG &DAG = DCI.DAG;
10519   if (!isS16(OpS16, DAG) && !isSRA16(OpS16)) {
10520     OpS16 = OpS32;
10521     OpS32 = SMULLOHI->getOperand(0);
10522   }
10523 
10524   SDLoc dl(OR);
10525   unsigned Opcode = 0;
10526   if (isS16(OpS16, DAG))
10527     Opcode = ARMISD::SMULWB;
10528   else if (isSRA16(OpS16)) {
10529     Opcode = ARMISD::SMULWT;
10530     OpS16 = OpS16->getOperand(0);
10531   }
10532   else
10533     return SDValue();
10534 
10535   SDValue Res = DAG.getNode(Opcode, dl, MVT::i32, OpS32, OpS16);
10536   DAG.ReplaceAllUsesOfValueWith(SDValue(OR, 0), Res);
10537   return SDValue(OR, 0);
10538 }
10539 
10540 static SDValue PerformORCombineToBFI(SDNode *N,
10541                                      TargetLowering::DAGCombinerInfo &DCI,
10542                                      const ARMSubtarget *Subtarget) {
10543   // BFI is only available on V6T2+
10544   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
10545     return SDValue();
10546 
10547   EVT VT = N->getValueType(0);
10548   SDValue N0 = N->getOperand(0);
10549   SDValue N1 = N->getOperand(1);
10550   SelectionDAG &DAG = DCI.DAG;
10551   SDLoc DL(N);
10552   // 1) or (and A, mask), val => ARMbfi A, val, mask
10553   //      iff (val & mask) == val
10554   //
10555   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
10556   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
10557   //          && mask == ~mask2
10558   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
10559   //          && ~mask == mask2
10560   //  (i.e., copy a bitfield value into another bitfield of the same width)
10561 
10562   if (VT != MVT::i32)
10563     return SDValue();
10564 
10565   SDValue N00 = N0.getOperand(0);
10566 
10567   // The value and the mask need to be constants so we can verify this is
10568   // actually a bitfield set. If the mask is 0xffff, we can do better
10569   // via a movt instruction, so don't use BFI in that case.
10570   SDValue MaskOp = N0.getOperand(1);
10571   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
10572   if (!MaskC)
10573     return SDValue();
10574   unsigned Mask = MaskC->getZExtValue();
10575   if (Mask == 0xffff)
10576     return SDValue();
10577   SDValue Res;
10578   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
10579   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
10580   if (N1C) {
10581     unsigned Val = N1C->getZExtValue();
10582     if ((Val & ~Mask) != Val)
10583       return SDValue();
10584 
10585     if (ARM::isBitFieldInvertedMask(Mask)) {
10586       Val >>= countTrailingZeros(~Mask);
10587 
10588       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
10589                         DAG.getConstant(Val, DL, MVT::i32),
10590                         DAG.getConstant(Mask, DL, MVT::i32));
10591 
10592       DCI.CombineTo(N, Res, false);
10593       // Return value from the original node to inform the combiner than N is
10594       // now dead.
10595       return SDValue(N, 0);
10596     }
10597   } else if (N1.getOpcode() == ISD::AND) {
10598     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
10599     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
10600     if (!N11C)
10601       return SDValue();
10602     unsigned Mask2 = N11C->getZExtValue();
10603 
10604     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
10605     // as is to match.
10606     if (ARM::isBitFieldInvertedMask(Mask) &&
10607         (Mask == ~Mask2)) {
10608       // The pack halfword instruction works better for masks that fit it,
10609       // so use that when it's available.
10610       if (Subtarget->hasDSP() &&
10611           (Mask == 0xffff || Mask == 0xffff0000))
10612         return SDValue();
10613       // 2a
10614       unsigned amt = countTrailingZeros(Mask2);
10615       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
10616                         DAG.getConstant(amt, DL, MVT::i32));
10617       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
10618                         DAG.getConstant(Mask, DL, MVT::i32));
10619       DCI.CombineTo(N, Res, false);
10620       // Return value from the original node to inform the combiner than N is
10621       // now dead.
10622       return SDValue(N, 0);
10623     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
10624                (~Mask == Mask2)) {
10625       // The pack halfword instruction works better for masks that fit it,
10626       // so use that when it's available.
10627       if (Subtarget->hasDSP() &&
10628           (Mask2 == 0xffff || Mask2 == 0xffff0000))
10629         return SDValue();
10630       // 2b
10631       unsigned lsb = countTrailingZeros(Mask);
10632       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
10633                         DAG.getConstant(lsb, DL, MVT::i32));
10634       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
10635                         DAG.getConstant(Mask2, DL, MVT::i32));
10636       DCI.CombineTo(N, Res, false);
10637       // Return value from the original node to inform the combiner than N is
10638       // now dead.
10639       return SDValue(N, 0);
10640     }
10641   }
10642 
10643   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
10644       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
10645       ARM::isBitFieldInvertedMask(~Mask)) {
10646     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
10647     // where lsb(mask) == #shamt and masked bits of B are known zero.
10648     SDValue ShAmt = N00.getOperand(1);
10649     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
10650     unsigned LSB = countTrailingZeros(Mask);
10651     if (ShAmtC != LSB)
10652       return SDValue();
10653 
10654     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
10655                       DAG.getConstant(~Mask, DL, MVT::i32));
10656 
10657     DCI.CombineTo(N, Res, false);
10658     // Return value from the original node to inform the combiner than N is
10659     // now dead.
10660     return SDValue(N, 0);
10661   }
10662 
10663   return SDValue();
10664 }
10665 
10666 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
10667 static SDValue PerformORCombine(SDNode *N,
10668                                 TargetLowering::DAGCombinerInfo &DCI,
10669                                 const ARMSubtarget *Subtarget) {
10670   // Attempt to use immediate-form VORR
10671   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
10672   SDLoc dl(N);
10673   EVT VT = N->getValueType(0);
10674   SelectionDAG &DAG = DCI.DAG;
10675 
10676   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
10677     return SDValue();
10678 
10679   APInt SplatBits, SplatUndef;
10680   unsigned SplatBitSize;
10681   bool HasAnyUndefs;
10682   if (BVN && Subtarget->hasNEON() &&
10683       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
10684     if (SplatBitSize <= 64) {
10685       EVT VorrVT;
10686       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
10687                                       SplatUndef.getZExtValue(), SplatBitSize,
10688                                       DAG, dl, VorrVT, VT.is128BitVector(),
10689                                       OtherModImm);
10690       if (Val.getNode()) {
10691         SDValue Input =
10692           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
10693         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
10694         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
10695       }
10696     }
10697   }
10698 
10699   if (!Subtarget->isThumb1Only()) {
10700     // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
10701     if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI))
10702       return Result;
10703     if (SDValue Result = PerformORCombineToSMULWBT(N, DCI, Subtarget))
10704       return Result;
10705   }
10706 
10707   SDValue N0 = N->getOperand(0);
10708   SDValue N1 = N->getOperand(1);
10709 
10710   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
10711   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
10712       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
10713 
10714     // The code below optimizes (or (and X, Y), Z).
10715     // The AND operand needs to have a single user to make these optimizations
10716     // profitable.
10717     if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
10718       return SDValue();
10719 
10720     APInt SplatUndef;
10721     unsigned SplatBitSize;
10722     bool HasAnyUndefs;
10723 
10724     APInt SplatBits0, SplatBits1;
10725     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
10726     BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
10727     // Ensure that the second operand of both ands are constants
10728     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
10729                                       HasAnyUndefs) && !HasAnyUndefs) {
10730         if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
10731                                           HasAnyUndefs) && !HasAnyUndefs) {
10732             // Ensure that the bit width of the constants are the same and that
10733             // the splat arguments are logical inverses as per the pattern we
10734             // are trying to simplify.
10735             if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
10736                 SplatBits0 == ~SplatBits1) {
10737                 // Canonicalize the vector type to make instruction selection
10738                 // simpler.
10739                 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
10740                 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
10741                                              N0->getOperand(1),
10742                                              N0->getOperand(0),
10743                                              N1->getOperand(0));
10744                 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10745             }
10746         }
10747     }
10748   }
10749 
10750   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
10751   // reasonable.
10752   if (N0.getOpcode() == ISD::AND && N0.hasOneUse()) {
10753     if (SDValue Res = PerformORCombineToBFI(N, DCI, Subtarget))
10754       return Res;
10755   }
10756 
10757   if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
10758     return Result;
10759 
10760   return SDValue();
10761 }
10762 
10763 static SDValue PerformXORCombine(SDNode *N,
10764                                  TargetLowering::DAGCombinerInfo &DCI,
10765                                  const ARMSubtarget *Subtarget) {
10766   EVT VT = N->getValueType(0);
10767   SelectionDAG &DAG = DCI.DAG;
10768 
10769   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
10770     return SDValue();
10771 
10772   if (!Subtarget->isThumb1Only()) {
10773     // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
10774     if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI))
10775       return Result;
10776 
10777     if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
10778       return Result;
10779   }
10780 
10781   return SDValue();
10782 }
10783 
10784 // ParseBFI - given a BFI instruction in N, extract the "from" value (Rn) and return it,
10785 // and fill in FromMask and ToMask with (consecutive) bits in "from" to be extracted and
10786 // their position in "to" (Rd).
10787 static SDValue ParseBFI(SDNode *N, APInt &ToMask, APInt &FromMask) {
10788   assert(N->getOpcode() == ARMISD::BFI);
10789 
10790   SDValue From = N->getOperand(1);
10791   ToMask = ~cast<ConstantSDNode>(N->getOperand(2))->getAPIntValue();
10792   FromMask = APInt::getLowBitsSet(ToMask.getBitWidth(), ToMask.countPopulation());
10793 
10794   // If the Base came from a SHR #C, we can deduce that it is really testing bit
10795   // #C in the base of the SHR.
10796   if (From->getOpcode() == ISD::SRL &&
10797       isa<ConstantSDNode>(From->getOperand(1))) {
10798     APInt Shift = cast<ConstantSDNode>(From->getOperand(1))->getAPIntValue();
10799     assert(Shift.getLimitedValue() < 32 && "Shift too large!");
10800     FromMask <<= Shift.getLimitedValue(31);
10801     From = From->getOperand(0);
10802   }
10803 
10804   return From;
10805 }
10806 
10807 // If A and B contain one contiguous set of bits, does A | B == A . B?
10808 //
10809 // Neither A nor B must be zero.
10810 static bool BitsProperlyConcatenate(const APInt &A, const APInt &B) {
10811   unsigned LastActiveBitInA =  A.countTrailingZeros();
10812   unsigned FirstActiveBitInB = B.getBitWidth() - B.countLeadingZeros() - 1;
10813   return LastActiveBitInA - 1 == FirstActiveBitInB;
10814 }
10815 
10816 static SDValue FindBFIToCombineWith(SDNode *N) {
10817   // We have a BFI in N. Follow a possible chain of BFIs and find a BFI it can combine with,
10818   // if one exists.
10819   APInt ToMask, FromMask;
10820   SDValue From = ParseBFI(N, ToMask, FromMask);
10821   SDValue To = N->getOperand(0);
10822 
10823   // Now check for a compatible BFI to merge with. We can pass through BFIs that
10824   // aren't compatible, but not if they set the same bit in their destination as
10825   // we do (or that of any BFI we're going to combine with).
10826   SDValue V = To;
10827   APInt CombinedToMask = ToMask;
10828   while (V.getOpcode() == ARMISD::BFI) {
10829     APInt NewToMask, NewFromMask;
10830     SDValue NewFrom = ParseBFI(V.getNode(), NewToMask, NewFromMask);
10831     if (NewFrom != From) {
10832       // This BFI has a different base. Keep going.
10833       CombinedToMask |= NewToMask;
10834       V = V.getOperand(0);
10835       continue;
10836     }
10837 
10838     // Do the written bits conflict with any we've seen so far?
10839     if ((NewToMask & CombinedToMask).getBoolValue())
10840       // Conflicting bits - bail out because going further is unsafe.
10841       return SDValue();
10842 
10843     // Are the new bits contiguous when combined with the old bits?
10844     if (BitsProperlyConcatenate(ToMask, NewToMask) &&
10845         BitsProperlyConcatenate(FromMask, NewFromMask))
10846       return V;
10847     if (BitsProperlyConcatenate(NewToMask, ToMask) &&
10848         BitsProperlyConcatenate(NewFromMask, FromMask))
10849       return V;
10850 
10851     // We've seen a write to some bits, so track it.
10852     CombinedToMask |= NewToMask;
10853     // Keep going...
10854     V = V.getOperand(0);
10855   }
10856 
10857   return SDValue();
10858 }
10859 
10860 static SDValue PerformBFICombine(SDNode *N,
10861                                  TargetLowering::DAGCombinerInfo &DCI) {
10862   SDValue N1 = N->getOperand(1);
10863   if (N1.getOpcode() == ISD::AND) {
10864     // (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
10865     // the bits being cleared by the AND are not demanded by the BFI.
10866     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
10867     if (!N11C)
10868       return SDValue();
10869     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
10870     unsigned LSB = countTrailingZeros(~InvMask);
10871     unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
10872     assert(Width <
10873                static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
10874            "undefined behavior");
10875     unsigned Mask = (1u << Width) - 1;
10876     unsigned Mask2 = N11C->getZExtValue();
10877     if ((Mask & (~Mask2)) == 0)
10878       return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
10879                              N->getOperand(0), N1.getOperand(0),
10880                              N->getOperand(2));
10881   } else if (N->getOperand(0).getOpcode() == ARMISD::BFI) {
10882     // We have a BFI of a BFI. Walk up the BFI chain to see how long it goes.
10883     // Keep track of any consecutive bits set that all come from the same base
10884     // value. We can combine these together into a single BFI.
10885     SDValue CombineBFI = FindBFIToCombineWith(N);
10886     if (CombineBFI == SDValue())
10887       return SDValue();
10888 
10889     // We've found a BFI.
10890     APInt ToMask1, FromMask1;
10891     SDValue From1 = ParseBFI(N, ToMask1, FromMask1);
10892 
10893     APInt ToMask2, FromMask2;
10894     SDValue From2 = ParseBFI(CombineBFI.getNode(), ToMask2, FromMask2);
10895     assert(From1 == From2);
10896     (void)From2;
10897 
10898     // First, unlink CombineBFI.
10899     DCI.DAG.ReplaceAllUsesWith(CombineBFI, CombineBFI.getOperand(0));
10900     // Then create a new BFI, combining the two together.
10901     APInt NewFromMask = FromMask1 | FromMask2;
10902     APInt NewToMask = ToMask1 | ToMask2;
10903 
10904     EVT VT = N->getValueType(0);
10905     SDLoc dl(N);
10906 
10907     if (NewFromMask[0] == 0)
10908       From1 = DCI.DAG.getNode(
10909         ISD::SRL, dl, VT, From1,
10910         DCI.DAG.getConstant(NewFromMask.countTrailingZeros(), dl, VT));
10911     return DCI.DAG.getNode(ARMISD::BFI, dl, VT, N->getOperand(0), From1,
10912                            DCI.DAG.getConstant(~NewToMask, dl, VT));
10913   }
10914   return SDValue();
10915 }
10916 
10917 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
10918 /// ARMISD::VMOVRRD.
10919 static SDValue PerformVMOVRRDCombine(SDNode *N,
10920                                      TargetLowering::DAGCombinerInfo &DCI,
10921                                      const ARMSubtarget *Subtarget) {
10922   // vmovrrd(vmovdrr x, y) -> x,y
10923   SDValue InDouble = N->getOperand(0);
10924   if (InDouble.getOpcode() == ARMISD::VMOVDRR && !Subtarget->isFPOnlySP())
10925     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
10926 
10927   // vmovrrd(load f64) -> (load i32), (load i32)
10928   SDNode *InNode = InDouble.getNode();
10929   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
10930       InNode->getValueType(0) == MVT::f64 &&
10931       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
10932       !cast<LoadSDNode>(InNode)->isVolatile()) {
10933     // TODO: Should this be done for non-FrameIndex operands?
10934     LoadSDNode *LD = cast<LoadSDNode>(InNode);
10935 
10936     SelectionDAG &DAG = DCI.DAG;
10937     SDLoc DL(LD);
10938     SDValue BasePtr = LD->getBasePtr();
10939     SDValue NewLD1 =
10940         DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr, LD->getPointerInfo(),
10941                     LD->getAlignment(), LD->getMemOperand()->getFlags());
10942 
10943     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
10944                                     DAG.getConstant(4, DL, MVT::i32));
10945     SDValue NewLD2 = DAG.getLoad(
10946         MVT::i32, DL, NewLD1.getValue(1), OffsetPtr, LD->getPointerInfo(),
10947         std::min(4U, LD->getAlignment() / 2), LD->getMemOperand()->getFlags());
10948 
10949     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
10950     if (DCI.DAG.getDataLayout().isBigEndian())
10951       std::swap (NewLD1, NewLD2);
10952     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
10953     return Result;
10954   }
10955 
10956   return SDValue();
10957 }
10958 
10959 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
10960 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
10961 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
10962   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
10963   SDValue Op0 = N->getOperand(0);
10964   SDValue Op1 = N->getOperand(1);
10965   if (Op0.getOpcode() == ISD::BITCAST)
10966     Op0 = Op0.getOperand(0);
10967   if (Op1.getOpcode() == ISD::BITCAST)
10968     Op1 = Op1.getOperand(0);
10969   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
10970       Op0.getNode() == Op1.getNode() &&
10971       Op0.getResNo() == 0 && Op1.getResNo() == 1)
10972     return DAG.getNode(ISD::BITCAST, SDLoc(N),
10973                        N->getValueType(0), Op0.getOperand(0));
10974   return SDValue();
10975 }
10976 
10977 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
10978 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
10979 /// i64 vector to have f64 elements, since the value can then be loaded
10980 /// directly into a VFP register.
10981 static bool hasNormalLoadOperand(SDNode *N) {
10982   unsigned NumElts = N->getValueType(0).getVectorNumElements();
10983   for (unsigned i = 0; i < NumElts; ++i) {
10984     SDNode *Elt = N->getOperand(i).getNode();
10985     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
10986       return true;
10987   }
10988   return false;
10989 }
10990 
10991 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
10992 /// ISD::BUILD_VECTOR.
10993 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
10994                                           TargetLowering::DAGCombinerInfo &DCI,
10995                                           const ARMSubtarget *Subtarget) {
10996   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
10997   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
10998   // into a pair of GPRs, which is fine when the value is used as a scalar,
10999   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
11000   SelectionDAG &DAG = DCI.DAG;
11001   if (N->getNumOperands() == 2)
11002     if (SDValue RV = PerformVMOVDRRCombine(N, DAG))
11003       return RV;
11004 
11005   // Load i64 elements as f64 values so that type legalization does not split
11006   // them up into i32 values.
11007   EVT VT = N->getValueType(0);
11008   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
11009     return SDValue();
11010   SDLoc dl(N);
11011   SmallVector<SDValue, 8> Ops;
11012   unsigned NumElts = VT.getVectorNumElements();
11013   for (unsigned i = 0; i < NumElts; ++i) {
11014     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
11015     Ops.push_back(V);
11016     // Make the DAGCombiner fold the bitcast.
11017     DCI.AddToWorklist(V.getNode());
11018   }
11019   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
11020   SDValue BV = DAG.getBuildVector(FloatVT, dl, Ops);
11021   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
11022 }
11023 
11024 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
11025 static SDValue
11026 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
11027   // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
11028   // At that time, we may have inserted bitcasts from integer to float.
11029   // If these bitcasts have survived DAGCombine, change the lowering of this
11030   // BUILD_VECTOR in something more vector friendly, i.e., that does not
11031   // force to use floating point types.
11032 
11033   // Make sure we can change the type of the vector.
11034   // This is possible iff:
11035   // 1. The vector is only used in a bitcast to a integer type. I.e.,
11036   //    1.1. Vector is used only once.
11037   //    1.2. Use is a bit convert to an integer type.
11038   // 2. The size of its operands are 32-bits (64-bits are not legal).
11039   EVT VT = N->getValueType(0);
11040   EVT EltVT = VT.getVectorElementType();
11041 
11042   // Check 1.1. and 2.
11043   if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
11044     return SDValue();
11045 
11046   // By construction, the input type must be float.
11047   assert(EltVT == MVT::f32 && "Unexpected type!");
11048 
11049   // Check 1.2.
11050   SDNode *Use = *N->use_begin();
11051   if (Use->getOpcode() != ISD::BITCAST ||
11052       Use->getValueType(0).isFloatingPoint())
11053     return SDValue();
11054 
11055   // Check profitability.
11056   // Model is, if more than half of the relevant operands are bitcast from
11057   // i32, turn the build_vector into a sequence of insert_vector_elt.
11058   // Relevant operands are everything that is not statically
11059   // (i.e., at compile time) bitcasted.
11060   unsigned NumOfBitCastedElts = 0;
11061   unsigned NumElts = VT.getVectorNumElements();
11062   unsigned NumOfRelevantElts = NumElts;
11063   for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
11064     SDValue Elt = N->getOperand(Idx);
11065     if (Elt->getOpcode() == ISD::BITCAST) {
11066       // Assume only bit cast to i32 will go away.
11067       if (Elt->getOperand(0).getValueType() == MVT::i32)
11068         ++NumOfBitCastedElts;
11069     } else if (Elt.isUndef() || isa<ConstantSDNode>(Elt))
11070       // Constants are statically casted, thus do not count them as
11071       // relevant operands.
11072       --NumOfRelevantElts;
11073   }
11074 
11075   // Check if more than half of the elements require a non-free bitcast.
11076   if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
11077     return SDValue();
11078 
11079   SelectionDAG &DAG = DCI.DAG;
11080   // Create the new vector type.
11081   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
11082   // Check if the type is legal.
11083   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11084   if (!TLI.isTypeLegal(VecVT))
11085     return SDValue();
11086 
11087   // Combine:
11088   // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
11089   // => BITCAST INSERT_VECTOR_ELT
11090   //                      (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
11091   //                      (BITCAST EN), N.
11092   SDValue Vec = DAG.getUNDEF(VecVT);
11093   SDLoc dl(N);
11094   for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
11095     SDValue V = N->getOperand(Idx);
11096     if (V.isUndef())
11097       continue;
11098     if (V.getOpcode() == ISD::BITCAST &&
11099         V->getOperand(0).getValueType() == MVT::i32)
11100       // Fold obvious case.
11101       V = V.getOperand(0);
11102     else {
11103       V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
11104       // Make the DAGCombiner fold the bitcasts.
11105       DCI.AddToWorklist(V.getNode());
11106     }
11107     SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32);
11108     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
11109   }
11110   Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
11111   // Make the DAGCombiner fold the bitcasts.
11112   DCI.AddToWorklist(Vec.getNode());
11113   return Vec;
11114 }
11115 
11116 /// PerformInsertEltCombine - Target-specific dag combine xforms for
11117 /// ISD::INSERT_VECTOR_ELT.
11118 static SDValue PerformInsertEltCombine(SDNode *N,
11119                                        TargetLowering::DAGCombinerInfo &DCI) {
11120   // Bitcast an i64 load inserted into a vector to f64.
11121   // Otherwise, the i64 value will be legalized to a pair of i32 values.
11122   EVT VT = N->getValueType(0);
11123   SDNode *Elt = N->getOperand(1).getNode();
11124   if (VT.getVectorElementType() != MVT::i64 ||
11125       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
11126     return SDValue();
11127 
11128   SelectionDAG &DAG = DCI.DAG;
11129   SDLoc dl(N);
11130   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
11131                                  VT.getVectorNumElements());
11132   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
11133   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
11134   // Make the DAGCombiner fold the bitcasts.
11135   DCI.AddToWorklist(Vec.getNode());
11136   DCI.AddToWorklist(V.getNode());
11137   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
11138                                Vec, V, N->getOperand(2));
11139   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
11140 }
11141 
11142 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
11143 /// ISD::VECTOR_SHUFFLE.
11144 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
11145   // The LLVM shufflevector instruction does not require the shuffle mask
11146   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
11147   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
11148   // operands do not match the mask length, they are extended by concatenating
11149   // them with undef vectors.  That is probably the right thing for other
11150   // targets, but for NEON it is better to concatenate two double-register
11151   // size vector operands into a single quad-register size vector.  Do that
11152   // transformation here:
11153   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
11154   //   shuffle(concat(v1, v2), undef)
11155   SDValue Op0 = N->getOperand(0);
11156   SDValue Op1 = N->getOperand(1);
11157   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
11158       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
11159       Op0.getNumOperands() != 2 ||
11160       Op1.getNumOperands() != 2)
11161     return SDValue();
11162   SDValue Concat0Op1 = Op0.getOperand(1);
11163   SDValue Concat1Op1 = Op1.getOperand(1);
11164   if (!Concat0Op1.isUndef() || !Concat1Op1.isUndef())
11165     return SDValue();
11166   // Skip the transformation if any of the types are illegal.
11167   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11168   EVT VT = N->getValueType(0);
11169   if (!TLI.isTypeLegal(VT) ||
11170       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
11171       !TLI.isTypeLegal(Concat1Op1.getValueType()))
11172     return SDValue();
11173 
11174   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
11175                                   Op0.getOperand(0), Op1.getOperand(0));
11176   // Translate the shuffle mask.
11177   SmallVector<int, 16> NewMask;
11178   unsigned NumElts = VT.getVectorNumElements();
11179   unsigned HalfElts = NumElts/2;
11180   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
11181   for (unsigned n = 0; n < NumElts; ++n) {
11182     int MaskElt = SVN->getMaskElt(n);
11183     int NewElt = -1;
11184     if (MaskElt < (int)HalfElts)
11185       NewElt = MaskElt;
11186     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
11187       NewElt = HalfElts + MaskElt - NumElts;
11188     NewMask.push_back(NewElt);
11189   }
11190   return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
11191                               DAG.getUNDEF(VT), NewMask);
11192 }
11193 
11194 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP,
11195 /// NEON load/store intrinsics, and generic vector load/stores, to merge
11196 /// base address updates.
11197 /// For generic load/stores, the memory type is assumed to be a vector.
11198 /// The caller is assumed to have checked legality.
11199 static SDValue CombineBaseUpdate(SDNode *N,
11200                                  TargetLowering::DAGCombinerInfo &DCI) {
11201   SelectionDAG &DAG = DCI.DAG;
11202   const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
11203                             N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
11204   const bool isStore = N->getOpcode() == ISD::STORE;
11205   const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1);
11206   SDValue Addr = N->getOperand(AddrOpIdx);
11207   MemSDNode *MemN = cast<MemSDNode>(N);
11208   SDLoc dl(N);
11209 
11210   // Search for a use of the address operand that is an increment.
11211   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
11212          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
11213     SDNode *User = *UI;
11214     if (User->getOpcode() != ISD::ADD ||
11215         UI.getUse().getResNo() != Addr.getResNo())
11216       continue;
11217 
11218     // Check that the add is independent of the load/store.  Otherwise, folding
11219     // it would create a cycle.
11220     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
11221       continue;
11222 
11223     // Find the new opcode for the updating load/store.
11224     bool isLoadOp = true;
11225     bool isLaneOp = false;
11226     unsigned NewOpc = 0;
11227     unsigned NumVecs = 0;
11228     if (isIntrinsic) {
11229       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
11230       switch (IntNo) {
11231       default: llvm_unreachable("unexpected intrinsic for Neon base update");
11232       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
11233         NumVecs = 1; break;
11234       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
11235         NumVecs = 2; break;
11236       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
11237         NumVecs = 3; break;
11238       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
11239         NumVecs = 4; break;
11240       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
11241         NumVecs = 2; isLaneOp = true; break;
11242       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
11243         NumVecs = 3; isLaneOp = true; break;
11244       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
11245         NumVecs = 4; isLaneOp = true; break;
11246       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
11247         NumVecs = 1; isLoadOp = false; break;
11248       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
11249         NumVecs = 2; isLoadOp = false; break;
11250       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
11251         NumVecs = 3; isLoadOp = false; break;
11252       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
11253         NumVecs = 4; isLoadOp = false; break;
11254       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
11255         NumVecs = 2; isLoadOp = false; isLaneOp = true; break;
11256       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
11257         NumVecs = 3; isLoadOp = false; isLaneOp = true; break;
11258       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
11259         NumVecs = 4; isLoadOp = false; isLaneOp = true; break;
11260       }
11261     } else {
11262       isLaneOp = true;
11263       switch (N->getOpcode()) {
11264       default: llvm_unreachable("unexpected opcode for Neon base update");
11265       case ARMISD::VLD1DUP: NewOpc = ARMISD::VLD1DUP_UPD; NumVecs = 1; break;
11266       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
11267       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
11268       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
11269       case ISD::LOAD:       NewOpc = ARMISD::VLD1_UPD;
11270         NumVecs = 1; isLaneOp = false; break;
11271       case ISD::STORE:      NewOpc = ARMISD::VST1_UPD;
11272         NumVecs = 1; isLaneOp = false; isLoadOp = false; break;
11273       }
11274     }
11275 
11276     // Find the size of memory referenced by the load/store.
11277     EVT VecTy;
11278     if (isLoadOp) {
11279       VecTy = N->getValueType(0);
11280     } else if (isIntrinsic) {
11281       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
11282     } else {
11283       assert(isStore && "Node has to be a load, a store, or an intrinsic!");
11284       VecTy = N->getOperand(1).getValueType();
11285     }
11286 
11287     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
11288     if (isLaneOp)
11289       NumBytes /= VecTy.getVectorNumElements();
11290 
11291     // If the increment is a constant, it must match the memory ref size.
11292     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
11293     ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode());
11294     if (NumBytes >= 3 * 16 && (!CInc || CInc->getZExtValue() != NumBytes)) {
11295       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
11296       // separate instructions that make it harder to use a non-constant update.
11297       continue;
11298     }
11299 
11300     // OK, we found an ADD we can fold into the base update.
11301     // Now, create a _UPD node, taking care of not breaking alignment.
11302 
11303     EVT AlignedVecTy = VecTy;
11304     unsigned Alignment = MemN->getAlignment();
11305 
11306     // If this is a less-than-standard-aligned load/store, change the type to
11307     // match the standard alignment.
11308     // The alignment is overlooked when selecting _UPD variants; and it's
11309     // easier to introduce bitcasts here than fix that.
11310     // There are 3 ways to get to this base-update combine:
11311     // - intrinsics: they are assumed to be properly aligned (to the standard
11312     //   alignment of the memory type), so we don't need to do anything.
11313     // - ARMISD::VLDx nodes: they are only generated from the aforementioned
11314     //   intrinsics, so, likewise, there's nothing to do.
11315     // - generic load/store instructions: the alignment is specified as an
11316     //   explicit operand, rather than implicitly as the standard alignment
11317     //   of the memory type (like the intrisics).  We need to change the
11318     //   memory type to match the explicit alignment.  That way, we don't
11319     //   generate non-standard-aligned ARMISD::VLDx nodes.
11320     if (isa<LSBaseSDNode>(N)) {
11321       if (Alignment == 0)
11322         Alignment = 1;
11323       if (Alignment < VecTy.getScalarSizeInBits() / 8) {
11324         MVT EltTy = MVT::getIntegerVT(Alignment * 8);
11325         assert(NumVecs == 1 && "Unexpected multi-element generic load/store.");
11326         assert(!isLaneOp && "Unexpected generic load/store lane.");
11327         unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8);
11328         AlignedVecTy = MVT::getVectorVT(EltTy, NumElts);
11329       }
11330       // Don't set an explicit alignment on regular load/stores that we want
11331       // to transform to VLD/VST 1_UPD nodes.
11332       // This matches the behavior of regular load/stores, which only get an
11333       // explicit alignment if the MMO alignment is larger than the standard
11334       // alignment of the memory type.
11335       // Intrinsics, however, always get an explicit alignment, set to the
11336       // alignment of the MMO.
11337       Alignment = 1;
11338     }
11339 
11340     // Create the new updating load/store node.
11341     // First, create an SDVTList for the new updating node's results.
11342     EVT Tys[6];
11343     unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
11344     unsigned n;
11345     for (n = 0; n < NumResultVecs; ++n)
11346       Tys[n] = AlignedVecTy;
11347     Tys[n++] = MVT::i32;
11348     Tys[n] = MVT::Other;
11349     SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2));
11350 
11351     // Then, gather the new node's operands.
11352     SmallVector<SDValue, 8> Ops;
11353     Ops.push_back(N->getOperand(0)); // incoming chain
11354     Ops.push_back(N->getOperand(AddrOpIdx));
11355     Ops.push_back(Inc);
11356 
11357     if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) {
11358       // Try to match the intrinsic's signature
11359       Ops.push_back(StN->getValue());
11360     } else {
11361       // Loads (and of course intrinsics) match the intrinsics' signature,
11362       // so just add all but the alignment operand.
11363       for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i)
11364         Ops.push_back(N->getOperand(i));
11365     }
11366 
11367     // For all node types, the alignment operand is always the last one.
11368     Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32));
11369 
11370     // If this is a non-standard-aligned STORE, the penultimate operand is the
11371     // stored value.  Bitcast it to the aligned type.
11372     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) {
11373       SDValue &StVal = Ops[Ops.size()-2];
11374       StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal);
11375     }
11376 
11377     EVT LoadVT = isLaneOp ? VecTy.getVectorElementType() : AlignedVecTy;
11378     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys, Ops, LoadVT,
11379                                            MemN->getMemOperand());
11380 
11381     // Update the uses.
11382     SmallVector<SDValue, 5> NewResults;
11383     for (unsigned i = 0; i < NumResultVecs; ++i)
11384       NewResults.push_back(SDValue(UpdN.getNode(), i));
11385 
11386     // If this is an non-standard-aligned LOAD, the first result is the loaded
11387     // value.  Bitcast it to the expected result type.
11388     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) {
11389       SDValue &LdVal = NewResults[0];
11390       LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal);
11391     }
11392 
11393     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
11394     DCI.CombineTo(N, NewResults);
11395     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
11396 
11397     break;
11398   }
11399   return SDValue();
11400 }
11401 
11402 static SDValue PerformVLDCombine(SDNode *N,
11403                                  TargetLowering::DAGCombinerInfo &DCI) {
11404   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
11405     return SDValue();
11406 
11407   return CombineBaseUpdate(N, DCI);
11408 }
11409 
11410 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
11411 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
11412 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
11413 /// return true.
11414 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
11415   SelectionDAG &DAG = DCI.DAG;
11416   EVT VT = N->getValueType(0);
11417   // vldN-dup instructions only support 64-bit vectors for N > 1.
11418   if (!VT.is64BitVector())
11419     return false;
11420 
11421   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
11422   SDNode *VLD = N->getOperand(0).getNode();
11423   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
11424     return false;
11425   unsigned NumVecs = 0;
11426   unsigned NewOpc = 0;
11427   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
11428   if (IntNo == Intrinsic::arm_neon_vld2lane) {
11429     NumVecs = 2;
11430     NewOpc = ARMISD::VLD2DUP;
11431   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
11432     NumVecs = 3;
11433     NewOpc = ARMISD::VLD3DUP;
11434   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
11435     NumVecs = 4;
11436     NewOpc = ARMISD::VLD4DUP;
11437   } else {
11438     return false;
11439   }
11440 
11441   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
11442   // numbers match the load.
11443   unsigned VLDLaneNo =
11444     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
11445   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
11446        UI != UE; ++UI) {
11447     // Ignore uses of the chain result.
11448     if (UI.getUse().getResNo() == NumVecs)
11449       continue;
11450     SDNode *User = *UI;
11451     if (User->getOpcode() != ARMISD::VDUPLANE ||
11452         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
11453       return false;
11454   }
11455 
11456   // Create the vldN-dup node.
11457   EVT Tys[5];
11458   unsigned n;
11459   for (n = 0; n < NumVecs; ++n)
11460     Tys[n] = VT;
11461   Tys[n] = MVT::Other;
11462   SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1));
11463   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
11464   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
11465   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
11466                                            Ops, VLDMemInt->getMemoryVT(),
11467                                            VLDMemInt->getMemOperand());
11468 
11469   // Update the uses.
11470   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
11471        UI != UE; ++UI) {
11472     unsigned ResNo = UI.getUse().getResNo();
11473     // Ignore uses of the chain result.
11474     if (ResNo == NumVecs)
11475       continue;
11476     SDNode *User = *UI;
11477     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
11478   }
11479 
11480   // Now the vldN-lane intrinsic is dead except for its chain result.
11481   // Update uses of the chain.
11482   std::vector<SDValue> VLDDupResults;
11483   for (unsigned n = 0; n < NumVecs; ++n)
11484     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
11485   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
11486   DCI.CombineTo(VLD, VLDDupResults);
11487 
11488   return true;
11489 }
11490 
11491 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
11492 /// ARMISD::VDUPLANE.
11493 static SDValue PerformVDUPLANECombine(SDNode *N,
11494                                       TargetLowering::DAGCombinerInfo &DCI) {
11495   SDValue Op = N->getOperand(0);
11496 
11497   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
11498   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
11499   if (CombineVLDDUP(N, DCI))
11500     return SDValue(N, 0);
11501 
11502   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
11503   // redundant.  Ignore bit_converts for now; element sizes are checked below.
11504   while (Op.getOpcode() == ISD::BITCAST)
11505     Op = Op.getOperand(0);
11506   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
11507     return SDValue();
11508 
11509   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
11510   unsigned EltSize = Op.getScalarValueSizeInBits();
11511   // The canonical VMOV for a zero vector uses a 32-bit element size.
11512   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11513   unsigned EltBits;
11514   if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
11515     EltSize = 8;
11516   EVT VT = N->getValueType(0);
11517   if (EltSize > VT.getScalarSizeInBits())
11518     return SDValue();
11519 
11520   return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
11521 }
11522 
11523 /// PerformVDUPCombine - Target-specific dag combine xforms for ARMISD::VDUP.
11524 static SDValue PerformVDUPCombine(SDNode *N,
11525                                   TargetLowering::DAGCombinerInfo &DCI) {
11526   SelectionDAG &DAG = DCI.DAG;
11527   SDValue Op = N->getOperand(0);
11528 
11529   // Match VDUP(LOAD) -> VLD1DUP.
11530   // We match this pattern here rather than waiting for isel because the
11531   // transform is only legal for unindexed loads.
11532   LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode());
11533   if (LD && Op.hasOneUse() && LD->isUnindexed() &&
11534       LD->getMemoryVT() == N->getValueType(0).getVectorElementType()) {
11535     SDValue Ops[] = { LD->getOperand(0), LD->getOperand(1),
11536                       DAG.getConstant(LD->getAlignment(), SDLoc(N), MVT::i32) };
11537     SDVTList SDTys = DAG.getVTList(N->getValueType(0), MVT::Other);
11538     SDValue VLDDup = DAG.getMemIntrinsicNode(ARMISD::VLD1DUP, SDLoc(N), SDTys,
11539                                              Ops, LD->getMemoryVT(),
11540                                              LD->getMemOperand());
11541     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), VLDDup.getValue(1));
11542     return VLDDup;
11543   }
11544 
11545   return SDValue();
11546 }
11547 
11548 static SDValue PerformLOADCombine(SDNode *N,
11549                                   TargetLowering::DAGCombinerInfo &DCI) {
11550   EVT VT = N->getValueType(0);
11551 
11552   // If this is a legal vector load, try to combine it into a VLD1_UPD.
11553   if (ISD::isNormalLoad(N) && VT.isVector() &&
11554       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
11555     return CombineBaseUpdate(N, DCI);
11556 
11557   return SDValue();
11558 }
11559 
11560 /// PerformSTORECombine - Target-specific dag combine xforms for
11561 /// ISD::STORE.
11562 static SDValue PerformSTORECombine(SDNode *N,
11563                                    TargetLowering::DAGCombinerInfo &DCI) {
11564   StoreSDNode *St = cast<StoreSDNode>(N);
11565   if (St->isVolatile())
11566     return SDValue();
11567 
11568   // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
11569   // pack all of the elements in one place.  Next, store to memory in fewer
11570   // chunks.
11571   SDValue StVal = St->getValue();
11572   EVT VT = StVal.getValueType();
11573   if (St->isTruncatingStore() && VT.isVector()) {
11574     SelectionDAG &DAG = DCI.DAG;
11575     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11576     EVT StVT = St->getMemoryVT();
11577     unsigned NumElems = VT.getVectorNumElements();
11578     assert(StVT != VT && "Cannot truncate to the same type");
11579     unsigned FromEltSz = VT.getScalarSizeInBits();
11580     unsigned ToEltSz = StVT.getScalarSizeInBits();
11581 
11582     // From, To sizes and ElemCount must be pow of two
11583     if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
11584 
11585     // We are going to use the original vector elt for storing.
11586     // Accumulated smaller vector elements must be a multiple of the store size.
11587     if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
11588 
11589     unsigned SizeRatio  = FromEltSz / ToEltSz;
11590     assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
11591 
11592     // Create a type on which we perform the shuffle.
11593     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
11594                                      NumElems*SizeRatio);
11595     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
11596 
11597     SDLoc DL(St);
11598     SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
11599     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
11600     for (unsigned i = 0; i < NumElems; ++i)
11601       ShuffleVec[i] = DAG.getDataLayout().isBigEndian()
11602                           ? (i + 1) * SizeRatio - 1
11603                           : i * SizeRatio;
11604 
11605     // Can't shuffle using an illegal type.
11606     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
11607 
11608     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
11609                                 DAG.getUNDEF(WideVec.getValueType()),
11610                                 ShuffleVec);
11611     // At this point all of the data is stored at the bottom of the
11612     // register. We now need to save it to mem.
11613 
11614     // Find the largest store unit
11615     MVT StoreType = MVT::i8;
11616     for (MVT Tp : MVT::integer_valuetypes()) {
11617       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
11618         StoreType = Tp;
11619     }
11620     // Didn't find a legal store type.
11621     if (!TLI.isTypeLegal(StoreType))
11622       return SDValue();
11623 
11624     // Bitcast the original vector into a vector of store-size units
11625     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
11626             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
11627     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
11628     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
11629     SmallVector<SDValue, 8> Chains;
11630     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL,
11631                                         TLI.getPointerTy(DAG.getDataLayout()));
11632     SDValue BasePtr = St->getBasePtr();
11633 
11634     // Perform one or more big stores into memory.
11635     unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
11636     for (unsigned I = 0; I < E; I++) {
11637       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
11638                                    StoreType, ShuffWide,
11639                                    DAG.getIntPtrConstant(I, DL));
11640       SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
11641                                 St->getPointerInfo(), St->getAlignment(),
11642                                 St->getMemOperand()->getFlags());
11643       BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
11644                             Increment);
11645       Chains.push_back(Ch);
11646     }
11647     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
11648   }
11649 
11650   if (!ISD::isNormalStore(St))
11651     return SDValue();
11652 
11653   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
11654   // ARM stores of arguments in the same cache line.
11655   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
11656       StVal.getNode()->hasOneUse()) {
11657     SelectionDAG  &DAG = DCI.DAG;
11658     bool isBigEndian = DAG.getDataLayout().isBigEndian();
11659     SDLoc DL(St);
11660     SDValue BasePtr = St->getBasePtr();
11661     SDValue NewST1 = DAG.getStore(
11662         St->getChain(), DL, StVal.getNode()->getOperand(isBigEndian ? 1 : 0),
11663         BasePtr, St->getPointerInfo(), St->getAlignment(),
11664         St->getMemOperand()->getFlags());
11665 
11666     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
11667                                     DAG.getConstant(4, DL, MVT::i32));
11668     return DAG.getStore(NewST1.getValue(0), DL,
11669                         StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
11670                         OffsetPtr, St->getPointerInfo(),
11671                         std::min(4U, St->getAlignment() / 2),
11672                         St->getMemOperand()->getFlags());
11673   }
11674 
11675   if (StVal.getValueType() == MVT::i64 &&
11676       StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
11677 
11678     // Bitcast an i64 store extracted from a vector to f64.
11679     // Otherwise, the i64 value will be legalized to a pair of i32 values.
11680     SelectionDAG &DAG = DCI.DAG;
11681     SDLoc dl(StVal);
11682     SDValue IntVec = StVal.getOperand(0);
11683     EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
11684                                    IntVec.getValueType().getVectorNumElements());
11685     SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
11686     SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11687                                  Vec, StVal.getOperand(1));
11688     dl = SDLoc(N);
11689     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
11690     // Make the DAGCombiner fold the bitcasts.
11691     DCI.AddToWorklist(Vec.getNode());
11692     DCI.AddToWorklist(ExtElt.getNode());
11693     DCI.AddToWorklist(V.getNode());
11694     return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
11695                         St->getPointerInfo(), St->getAlignment(),
11696                         St->getMemOperand()->getFlags(), St->getAAInfo());
11697   }
11698 
11699   // If this is a legal vector store, try to combine it into a VST1_UPD.
11700   if (ISD::isNormalStore(N) && VT.isVector() &&
11701       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
11702     return CombineBaseUpdate(N, DCI);
11703 
11704   return SDValue();
11705 }
11706 
11707 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
11708 /// can replace combinations of VMUL and VCVT (floating-point to integer)
11709 /// when the VMUL has a constant operand that is a power of 2.
11710 ///
11711 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
11712 ///  vmul.f32        d16, d17, d16
11713 ///  vcvt.s32.f32    d16, d16
11714 /// becomes:
11715 ///  vcvt.s32.f32    d16, d16, #3
11716 static SDValue PerformVCVTCombine(SDNode *N, SelectionDAG &DAG,
11717                                   const ARMSubtarget *Subtarget) {
11718   if (!Subtarget->hasNEON())
11719     return SDValue();
11720 
11721   SDValue Op = N->getOperand(0);
11722   if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
11723       Op.getOpcode() != ISD::FMUL)
11724     return SDValue();
11725 
11726   SDValue ConstVec = Op->getOperand(1);
11727   if (!isa<BuildVectorSDNode>(ConstVec))
11728     return SDValue();
11729 
11730   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
11731   uint32_t FloatBits = FloatTy.getSizeInBits();
11732   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
11733   uint32_t IntBits = IntTy.getSizeInBits();
11734   unsigned NumLanes = Op.getValueType().getVectorNumElements();
11735   if (FloatBits != 32 || IntBits > 32 || NumLanes > 4) {
11736     // These instructions only exist converting from f32 to i32. We can handle
11737     // smaller integers by generating an extra truncate, but larger ones would
11738     // be lossy. We also can't handle more then 4 lanes, since these intructions
11739     // only support v2i32/v4i32 types.
11740     return SDValue();
11741   }
11742 
11743   BitVector UndefElements;
11744   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
11745   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33);
11746   if (C == -1 || C == 0 || C > 32)
11747     return SDValue();
11748 
11749   SDLoc dl(N);
11750   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
11751   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
11752     Intrinsic::arm_neon_vcvtfp2fxu;
11753   SDValue FixConv = DAG.getNode(
11754       ISD::INTRINSIC_WO_CHAIN, dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
11755       DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), Op->getOperand(0),
11756       DAG.getConstant(C, dl, MVT::i32));
11757 
11758   if (IntBits < FloatBits)
11759     FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv);
11760 
11761   return FixConv;
11762 }
11763 
11764 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
11765 /// can replace combinations of VCVT (integer to floating-point) and VDIV
11766 /// when the VDIV has a constant operand that is a power of 2.
11767 ///
11768 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
11769 ///  vcvt.f32.s32    d16, d16
11770 ///  vdiv.f32        d16, d17, d16
11771 /// becomes:
11772 ///  vcvt.f32.s32    d16, d16, #3
11773 static SDValue PerformVDIVCombine(SDNode *N, SelectionDAG &DAG,
11774                                   const ARMSubtarget *Subtarget) {
11775   if (!Subtarget->hasNEON())
11776     return SDValue();
11777 
11778   SDValue Op = N->getOperand(0);
11779   unsigned OpOpcode = Op.getNode()->getOpcode();
11780   if (!N->getValueType(0).isVector() || !N->getValueType(0).isSimple() ||
11781       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
11782     return SDValue();
11783 
11784   SDValue ConstVec = N->getOperand(1);
11785   if (!isa<BuildVectorSDNode>(ConstVec))
11786     return SDValue();
11787 
11788   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
11789   uint32_t FloatBits = FloatTy.getSizeInBits();
11790   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
11791   uint32_t IntBits = IntTy.getSizeInBits();
11792   unsigned NumLanes = Op.getValueType().getVectorNumElements();
11793   if (FloatBits != 32 || IntBits > 32 || NumLanes > 4) {
11794     // These instructions only exist converting from i32 to f32. We can handle
11795     // smaller integers by generating an extra extend, but larger ones would
11796     // be lossy. We also can't handle more then 4 lanes, since these intructions
11797     // only support v2i32/v4i32 types.
11798     return SDValue();
11799   }
11800 
11801   BitVector UndefElements;
11802   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
11803   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33);
11804   if (C == -1 || C == 0 || C > 32)
11805     return SDValue();
11806 
11807   SDLoc dl(N);
11808   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
11809   SDValue ConvInput = Op.getOperand(0);
11810   if (IntBits < FloatBits)
11811     ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
11812                             dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
11813                             ConvInput);
11814 
11815   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
11816     Intrinsic::arm_neon_vcvtfxu2fp;
11817   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
11818                      Op.getValueType(),
11819                      DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
11820                      ConvInput, DAG.getConstant(C, dl, MVT::i32));
11821 }
11822 
11823 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
11824 /// operand of a vector shift operation, where all the elements of the
11825 /// build_vector must have the same constant integer value.
11826 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
11827   // Ignore bit_converts.
11828   while (Op.getOpcode() == ISD::BITCAST)
11829     Op = Op.getOperand(0);
11830   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
11831   APInt SplatBits, SplatUndef;
11832   unsigned SplatBitSize;
11833   bool HasAnyUndefs;
11834   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
11835                                       HasAnyUndefs, ElementBits) ||
11836       SplatBitSize > ElementBits)
11837     return false;
11838   Cnt = SplatBits.getSExtValue();
11839   return true;
11840 }
11841 
11842 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
11843 /// operand of a vector shift left operation.  That value must be in the range:
11844 ///   0 <= Value < ElementBits for a left shift; or
11845 ///   0 <= Value <= ElementBits for a long left shift.
11846 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
11847   assert(VT.isVector() && "vector shift count is not a vector type");
11848   int64_t ElementBits = VT.getScalarSizeInBits();
11849   if (! getVShiftImm(Op, ElementBits, Cnt))
11850     return false;
11851   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
11852 }
11853 
11854 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
11855 /// operand of a vector shift right operation.  For a shift opcode, the value
11856 /// is positive, but for an intrinsic the value count must be negative. The
11857 /// absolute value must be in the range:
11858 ///   1 <= |Value| <= ElementBits for a right shift; or
11859 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
11860 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
11861                          int64_t &Cnt) {
11862   assert(VT.isVector() && "vector shift count is not a vector type");
11863   int64_t ElementBits = VT.getScalarSizeInBits();
11864   if (! getVShiftImm(Op, ElementBits, Cnt))
11865     return false;
11866   if (!isIntrinsic)
11867     return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
11868   if (Cnt >= -(isNarrow ? ElementBits/2 : ElementBits) && Cnt <= -1) {
11869     Cnt = -Cnt;
11870     return true;
11871   }
11872   return false;
11873 }
11874 
11875 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
11876 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
11877   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
11878   switch (IntNo) {
11879   default:
11880     // Don't do anything for most intrinsics.
11881     break;
11882 
11883   // Vector shifts: check for immediate versions and lower them.
11884   // Note: This is done during DAG combining instead of DAG legalizing because
11885   // the build_vectors for 64-bit vector element shift counts are generally
11886   // not legal, and it is hard to see their values after they get legalized to
11887   // loads from a constant pool.
11888   case Intrinsic::arm_neon_vshifts:
11889   case Intrinsic::arm_neon_vshiftu:
11890   case Intrinsic::arm_neon_vrshifts:
11891   case Intrinsic::arm_neon_vrshiftu:
11892   case Intrinsic::arm_neon_vrshiftn:
11893   case Intrinsic::arm_neon_vqshifts:
11894   case Intrinsic::arm_neon_vqshiftu:
11895   case Intrinsic::arm_neon_vqshiftsu:
11896   case Intrinsic::arm_neon_vqshiftns:
11897   case Intrinsic::arm_neon_vqshiftnu:
11898   case Intrinsic::arm_neon_vqshiftnsu:
11899   case Intrinsic::arm_neon_vqrshiftns:
11900   case Intrinsic::arm_neon_vqrshiftnu:
11901   case Intrinsic::arm_neon_vqrshiftnsu: {
11902     EVT VT = N->getOperand(1).getValueType();
11903     int64_t Cnt;
11904     unsigned VShiftOpc = 0;
11905 
11906     switch (IntNo) {
11907     case Intrinsic::arm_neon_vshifts:
11908     case Intrinsic::arm_neon_vshiftu:
11909       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
11910         VShiftOpc = ARMISD::VSHL;
11911         break;
11912       }
11913       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
11914         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
11915                      ARMISD::VSHRs : ARMISD::VSHRu);
11916         break;
11917       }
11918       return SDValue();
11919 
11920     case Intrinsic::arm_neon_vrshifts:
11921     case Intrinsic::arm_neon_vrshiftu:
11922       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
11923         break;
11924       return SDValue();
11925 
11926     case Intrinsic::arm_neon_vqshifts:
11927     case Intrinsic::arm_neon_vqshiftu:
11928       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
11929         break;
11930       return SDValue();
11931 
11932     case Intrinsic::arm_neon_vqshiftsu:
11933       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
11934         break;
11935       llvm_unreachable("invalid shift count for vqshlu intrinsic");
11936 
11937     case Intrinsic::arm_neon_vrshiftn:
11938     case Intrinsic::arm_neon_vqshiftns:
11939     case Intrinsic::arm_neon_vqshiftnu:
11940     case Intrinsic::arm_neon_vqshiftnsu:
11941     case Intrinsic::arm_neon_vqrshiftns:
11942     case Intrinsic::arm_neon_vqrshiftnu:
11943     case Intrinsic::arm_neon_vqrshiftnsu:
11944       // Narrowing shifts require an immediate right shift.
11945       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
11946         break;
11947       llvm_unreachable("invalid shift count for narrowing vector shift "
11948                        "intrinsic");
11949 
11950     default:
11951       llvm_unreachable("unhandled vector shift");
11952     }
11953 
11954     switch (IntNo) {
11955     case Intrinsic::arm_neon_vshifts:
11956     case Intrinsic::arm_neon_vshiftu:
11957       // Opcode already set above.
11958       break;
11959     case Intrinsic::arm_neon_vrshifts:
11960       VShiftOpc = ARMISD::VRSHRs; break;
11961     case Intrinsic::arm_neon_vrshiftu:
11962       VShiftOpc = ARMISD::VRSHRu; break;
11963     case Intrinsic::arm_neon_vrshiftn:
11964       VShiftOpc = ARMISD::VRSHRN; break;
11965     case Intrinsic::arm_neon_vqshifts:
11966       VShiftOpc = ARMISD::VQSHLs; break;
11967     case Intrinsic::arm_neon_vqshiftu:
11968       VShiftOpc = ARMISD::VQSHLu; break;
11969     case Intrinsic::arm_neon_vqshiftsu:
11970       VShiftOpc = ARMISD::VQSHLsu; break;
11971     case Intrinsic::arm_neon_vqshiftns:
11972       VShiftOpc = ARMISD::VQSHRNs; break;
11973     case Intrinsic::arm_neon_vqshiftnu:
11974       VShiftOpc = ARMISD::VQSHRNu; break;
11975     case Intrinsic::arm_neon_vqshiftnsu:
11976       VShiftOpc = ARMISD::VQSHRNsu; break;
11977     case Intrinsic::arm_neon_vqrshiftns:
11978       VShiftOpc = ARMISD::VQRSHRNs; break;
11979     case Intrinsic::arm_neon_vqrshiftnu:
11980       VShiftOpc = ARMISD::VQRSHRNu; break;
11981     case Intrinsic::arm_neon_vqrshiftnsu:
11982       VShiftOpc = ARMISD::VQRSHRNsu; break;
11983     }
11984 
11985     SDLoc dl(N);
11986     return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
11987                        N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32));
11988   }
11989 
11990   case Intrinsic::arm_neon_vshiftins: {
11991     EVT VT = N->getOperand(1).getValueType();
11992     int64_t Cnt;
11993     unsigned VShiftOpc = 0;
11994 
11995     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
11996       VShiftOpc = ARMISD::VSLI;
11997     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
11998       VShiftOpc = ARMISD::VSRI;
11999     else {
12000       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
12001     }
12002 
12003     SDLoc dl(N);
12004     return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
12005                        N->getOperand(1), N->getOperand(2),
12006                        DAG.getConstant(Cnt, dl, MVT::i32));
12007   }
12008 
12009   case Intrinsic::arm_neon_vqrshifts:
12010   case Intrinsic::arm_neon_vqrshiftu:
12011     // No immediate versions of these to check for.
12012     break;
12013   }
12014 
12015   return SDValue();
12016 }
12017 
12018 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
12019 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
12020 /// combining instead of DAG legalizing because the build_vectors for 64-bit
12021 /// vector element shift counts are generally not legal, and it is hard to see
12022 /// their values after they get legalized to loads from a constant pool.
12023 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
12024                                    const ARMSubtarget *ST) {
12025   EVT VT = N->getValueType(0);
12026   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
12027     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
12028     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
12029     SDValue N1 = N->getOperand(1);
12030     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
12031       SDValue N0 = N->getOperand(0);
12032       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
12033           DAG.MaskedValueIsZero(N0.getOperand(0),
12034                                 APInt::getHighBitsSet(32, 16)))
12035         return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
12036     }
12037   }
12038 
12039   // Nothing to be done for scalar shifts.
12040   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12041   if (!VT.isVector() || !TLI.isTypeLegal(VT))
12042     return SDValue();
12043 
12044   assert(ST->hasNEON() && "unexpected vector shift");
12045   int64_t Cnt;
12046 
12047   switch (N->getOpcode()) {
12048   default: llvm_unreachable("unexpected shift opcode");
12049 
12050   case ISD::SHL:
12051     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) {
12052       SDLoc dl(N);
12053       return DAG.getNode(ARMISD::VSHL, dl, VT, N->getOperand(0),
12054                          DAG.getConstant(Cnt, dl, MVT::i32));
12055     }
12056     break;
12057 
12058   case ISD::SRA:
12059   case ISD::SRL:
12060     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
12061       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
12062                             ARMISD::VSHRs : ARMISD::VSHRu);
12063       SDLoc dl(N);
12064       return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0),
12065                          DAG.getConstant(Cnt, dl, MVT::i32));
12066     }
12067   }
12068   return SDValue();
12069 }
12070 
12071 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
12072 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
12073 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
12074                                     const ARMSubtarget *ST) {
12075   SDValue N0 = N->getOperand(0);
12076 
12077   // Check for sign- and zero-extensions of vector extract operations of 8-
12078   // and 16-bit vector elements.  NEON supports these directly.  They are
12079   // handled during DAG combining because type legalization will promote them
12080   // to 32-bit types and it is messy to recognize the operations after that.
12081   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
12082     SDValue Vec = N0.getOperand(0);
12083     SDValue Lane = N0.getOperand(1);
12084     EVT VT = N->getValueType(0);
12085     EVT EltVT = N0.getValueType();
12086     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12087 
12088     if (VT == MVT::i32 &&
12089         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
12090         TLI.isTypeLegal(Vec.getValueType()) &&
12091         isa<ConstantSDNode>(Lane)) {
12092 
12093       unsigned Opc = 0;
12094       switch (N->getOpcode()) {
12095       default: llvm_unreachable("unexpected opcode");
12096       case ISD::SIGN_EXTEND:
12097         Opc = ARMISD::VGETLANEs;
12098         break;
12099       case ISD::ZERO_EXTEND:
12100       case ISD::ANY_EXTEND:
12101         Opc = ARMISD::VGETLANEu;
12102         break;
12103       }
12104       return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
12105     }
12106   }
12107 
12108   return SDValue();
12109 }
12110 
12111 static const APInt *isPowerOf2Constant(SDValue V) {
12112   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
12113   if (!C)
12114     return nullptr;
12115   const APInt *CV = &C->getAPIntValue();
12116   return CV->isPowerOf2() ? CV : nullptr;
12117 }
12118 
12119 SDValue ARMTargetLowering::PerformCMOVToBFICombine(SDNode *CMOV, SelectionDAG &DAG) const {
12120   // If we have a CMOV, OR and AND combination such as:
12121   //   if (x & CN)
12122   //     y |= CM;
12123   //
12124   // And:
12125   //   * CN is a single bit;
12126   //   * All bits covered by CM are known zero in y
12127   //
12128   // Then we can convert this into a sequence of BFI instructions. This will
12129   // always be a win if CM is a single bit, will always be no worse than the
12130   // TST&OR sequence if CM is two bits, and for thumb will be no worse if CM is
12131   // three bits (due to the extra IT instruction).
12132 
12133   SDValue Op0 = CMOV->getOperand(0);
12134   SDValue Op1 = CMOV->getOperand(1);
12135   auto CCNode = cast<ConstantSDNode>(CMOV->getOperand(2));
12136   auto CC = CCNode->getAPIntValue().getLimitedValue();
12137   SDValue CmpZ = CMOV->getOperand(4);
12138 
12139   // The compare must be against zero.
12140   if (!isNullConstant(CmpZ->getOperand(1)))
12141     return SDValue();
12142 
12143   assert(CmpZ->getOpcode() == ARMISD::CMPZ);
12144   SDValue And = CmpZ->getOperand(0);
12145   if (And->getOpcode() != ISD::AND)
12146     return SDValue();
12147   const APInt *AndC = isPowerOf2Constant(And->getOperand(1));
12148   if (!AndC)
12149     return SDValue();
12150   SDValue X = And->getOperand(0);
12151 
12152   if (CC == ARMCC::EQ) {
12153     // We're performing an "equal to zero" compare. Swap the operands so we
12154     // canonicalize on a "not equal to zero" compare.
12155     std::swap(Op0, Op1);
12156   } else {
12157     assert(CC == ARMCC::NE && "How can a CMPZ node not be EQ or NE?");
12158   }
12159 
12160   if (Op1->getOpcode() != ISD::OR)
12161     return SDValue();
12162 
12163   ConstantSDNode *OrC = dyn_cast<ConstantSDNode>(Op1->getOperand(1));
12164   if (!OrC)
12165     return SDValue();
12166   SDValue Y = Op1->getOperand(0);
12167 
12168   if (Op0 != Y)
12169     return SDValue();
12170 
12171   // Now, is it profitable to continue?
12172   APInt OrCI = OrC->getAPIntValue();
12173   unsigned Heuristic = Subtarget->isThumb() ? 3 : 2;
12174   if (OrCI.countPopulation() > Heuristic)
12175     return SDValue();
12176 
12177   // Lastly, can we determine that the bits defined by OrCI
12178   // are zero in Y?
12179   KnownBits Known;
12180   DAG.computeKnownBits(Y, Known);
12181   if ((OrCI & Known.Zero) != OrCI)
12182     return SDValue();
12183 
12184   // OK, we can do the combine.
12185   SDValue V = Y;
12186   SDLoc dl(X);
12187   EVT VT = X.getValueType();
12188   unsigned BitInX = AndC->logBase2();
12189 
12190   if (BitInX != 0) {
12191     // We must shift X first.
12192     X = DAG.getNode(ISD::SRL, dl, VT, X,
12193                     DAG.getConstant(BitInX, dl, VT));
12194   }
12195 
12196   for (unsigned BitInY = 0, NumActiveBits = OrCI.getActiveBits();
12197        BitInY < NumActiveBits; ++BitInY) {
12198     if (OrCI[BitInY] == 0)
12199       continue;
12200     APInt Mask(VT.getSizeInBits(), 0);
12201     Mask.setBit(BitInY);
12202     V = DAG.getNode(ARMISD::BFI, dl, VT, V, X,
12203                     // Confusingly, the operand is an *inverted* mask.
12204                     DAG.getConstant(~Mask, dl, VT));
12205   }
12206 
12207   return V;
12208 }
12209 
12210 /// PerformBRCONDCombine - Target-specific DAG combining for ARMISD::BRCOND.
12211 SDValue
12212 ARMTargetLowering::PerformBRCONDCombine(SDNode *N, SelectionDAG &DAG) const {
12213   SDValue Cmp = N->getOperand(4);
12214   if (Cmp.getOpcode() != ARMISD::CMPZ)
12215     // Only looking at NE cases.
12216     return SDValue();
12217 
12218   EVT VT = N->getValueType(0);
12219   SDLoc dl(N);
12220   SDValue LHS = Cmp.getOperand(0);
12221   SDValue RHS = Cmp.getOperand(1);
12222   SDValue Chain = N->getOperand(0);
12223   SDValue BB = N->getOperand(1);
12224   SDValue ARMcc = N->getOperand(2);
12225   ARMCC::CondCodes CC =
12226     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
12227 
12228   // (brcond Chain BB ne CPSR (cmpz (and (cmov 0 1 CC CPSR Cmp) 1) 0))
12229   // -> (brcond Chain BB CC CPSR Cmp)
12230   if (CC == ARMCC::NE && LHS.getOpcode() == ISD::AND && LHS->hasOneUse() &&
12231       LHS->getOperand(0)->getOpcode() == ARMISD::CMOV &&
12232       LHS->getOperand(0)->hasOneUse()) {
12233     auto *LHS00C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(0));
12234     auto *LHS01C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(1));
12235     auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
12236     auto *RHSC = dyn_cast<ConstantSDNode>(RHS);
12237     if ((LHS00C && LHS00C->getZExtValue() == 0) &&
12238         (LHS01C && LHS01C->getZExtValue() == 1) &&
12239         (LHS1C && LHS1C->getZExtValue() == 1) &&
12240         (RHSC && RHSC->getZExtValue() == 0)) {
12241       return DAG.getNode(
12242           ARMISD::BRCOND, dl, VT, Chain, BB, LHS->getOperand(0)->getOperand(2),
12243           LHS->getOperand(0)->getOperand(3), LHS->getOperand(0)->getOperand(4));
12244     }
12245   }
12246 
12247   return SDValue();
12248 }
12249 
12250 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
12251 SDValue
12252 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
12253   SDValue Cmp = N->getOperand(4);
12254   if (Cmp.getOpcode() != ARMISD::CMPZ)
12255     // Only looking at EQ and NE cases.
12256     return SDValue();
12257 
12258   EVT VT = N->getValueType(0);
12259   SDLoc dl(N);
12260   SDValue LHS = Cmp.getOperand(0);
12261   SDValue RHS = Cmp.getOperand(1);
12262   SDValue FalseVal = N->getOperand(0);
12263   SDValue TrueVal = N->getOperand(1);
12264   SDValue ARMcc = N->getOperand(2);
12265   ARMCC::CondCodes CC =
12266     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
12267 
12268   // BFI is only available on V6T2+.
12269   if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) {
12270     SDValue R = PerformCMOVToBFICombine(N, DAG);
12271     if (R)
12272       return R;
12273   }
12274 
12275   // Simplify
12276   //   mov     r1, r0
12277   //   cmp     r1, x
12278   //   mov     r0, y
12279   //   moveq   r0, x
12280   // to
12281   //   cmp     r0, x
12282   //   movne   r0, y
12283   //
12284   //   mov     r1, r0
12285   //   cmp     r1, x
12286   //   mov     r0, x
12287   //   movne   r0, y
12288   // to
12289   //   cmp     r0, x
12290   //   movne   r0, y
12291   /// FIXME: Turn this into a target neutral optimization?
12292   SDValue Res;
12293   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
12294     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
12295                       N->getOperand(3), Cmp);
12296   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
12297     SDValue ARMcc;
12298     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
12299     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
12300                       N->getOperand(3), NewCmp);
12301   }
12302 
12303   // (cmov F T ne CPSR (cmpz (cmov 0 1 CC CPSR Cmp) 0))
12304   // -> (cmov F T CC CPSR Cmp)
12305   if (CC == ARMCC::NE && LHS.getOpcode() == ARMISD::CMOV && LHS->hasOneUse()) {
12306     auto *LHS0C = dyn_cast<ConstantSDNode>(LHS->getOperand(0));
12307     auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
12308     auto *RHSC = dyn_cast<ConstantSDNode>(RHS);
12309     if ((LHS0C && LHS0C->getZExtValue() == 0) &&
12310         (LHS1C && LHS1C->getZExtValue() == 1) &&
12311         (RHSC && RHSC->getZExtValue() == 0)) {
12312       return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
12313                          LHS->getOperand(2), LHS->getOperand(3),
12314                          LHS->getOperand(4));
12315     }
12316   }
12317 
12318   if (Res.getNode()) {
12319     KnownBits Known;
12320     DAG.computeKnownBits(SDValue(N,0), Known);
12321     // Capture demanded bits information that would be otherwise lost.
12322     if (Known.Zero == 0xfffffffe)
12323       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
12324                         DAG.getValueType(MVT::i1));
12325     else if (Known.Zero == 0xffffff00)
12326       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
12327                         DAG.getValueType(MVT::i8));
12328     else if (Known.Zero == 0xffff0000)
12329       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
12330                         DAG.getValueType(MVT::i16));
12331   }
12332 
12333   return Res;
12334 }
12335 
12336 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
12337                                              DAGCombinerInfo &DCI) const {
12338   switch (N->getOpcode()) {
12339   default: break;
12340   case ARMISD::ADDE:    return PerformADDECombine(N, DCI, Subtarget);
12341   case ARMISD::UMLAL:   return PerformUMLALCombine(N, DCI.DAG, Subtarget);
12342   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
12343   case ISD::SUB:        return PerformSUBCombine(N, DCI);
12344   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
12345   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
12346   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
12347   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
12348   case ARMISD::ADDC:
12349   case ARMISD::SUBC:    return PerformAddcSubcCombine(N, DCI, Subtarget);
12350   case ARMISD::SUBE:    return PerformAddeSubeCombine(N, DCI.DAG, Subtarget);
12351   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
12352   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget);
12353   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
12354   case ISD::STORE:      return PerformSTORECombine(N, DCI);
12355   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget);
12356   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
12357   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
12358   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
12359   case ARMISD::VDUP: return PerformVDUPCombine(N, DCI);
12360   case ISD::FP_TO_SINT:
12361   case ISD::FP_TO_UINT:
12362     return PerformVCVTCombine(N, DCI.DAG, Subtarget);
12363   case ISD::FDIV:
12364     return PerformVDIVCombine(N, DCI.DAG, Subtarget);
12365   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
12366   case ISD::SHL:
12367   case ISD::SRA:
12368   case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
12369   case ISD::SIGN_EXTEND:
12370   case ISD::ZERO_EXTEND:
12371   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
12372   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
12373   case ARMISD::BRCOND: return PerformBRCONDCombine(N, DCI.DAG);
12374   case ISD::LOAD:       return PerformLOADCombine(N, DCI);
12375   case ARMISD::VLD1DUP:
12376   case ARMISD::VLD2DUP:
12377   case ARMISD::VLD3DUP:
12378   case ARMISD::VLD4DUP:
12379     return PerformVLDCombine(N, DCI);
12380   case ARMISD::BUILD_VECTOR:
12381     return PerformARMBUILD_VECTORCombine(N, DCI);
12382   case ARMISD::SMULWB: {
12383     unsigned BitWidth = N->getValueType(0).getSizeInBits();
12384     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16);
12385     if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))
12386       return SDValue();
12387     break;
12388   }
12389   case ARMISD::SMULWT: {
12390     unsigned BitWidth = N->getValueType(0).getSizeInBits();
12391     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16);
12392     if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))
12393       return SDValue();
12394     break;
12395   }
12396   case ARMISD::SMLALBB: {
12397     unsigned BitWidth = N->getValueType(0).getSizeInBits();
12398     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16);
12399     if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) ||
12400         (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)))
12401       return SDValue();
12402     break;
12403   }
12404   case ARMISD::SMLALBT: {
12405     unsigned LowWidth = N->getOperand(0).getValueType().getSizeInBits();
12406     APInt LowMask = APInt::getLowBitsSet(LowWidth, 16);
12407     unsigned HighWidth = N->getOperand(1).getValueType().getSizeInBits();
12408     APInt HighMask = APInt::getHighBitsSet(HighWidth, 16);
12409     if ((SimplifyDemandedBits(N->getOperand(0), LowMask, DCI)) ||
12410         (SimplifyDemandedBits(N->getOperand(1), HighMask, DCI)))
12411       return SDValue();
12412     break;
12413   }
12414   case ARMISD::SMLALTB: {
12415     unsigned HighWidth = N->getOperand(0).getValueType().getSizeInBits();
12416     APInt HighMask = APInt::getHighBitsSet(HighWidth, 16);
12417     unsigned LowWidth = N->getOperand(1).getValueType().getSizeInBits();
12418     APInt LowMask = APInt::getLowBitsSet(LowWidth, 16);
12419     if ((SimplifyDemandedBits(N->getOperand(0), HighMask, DCI)) ||
12420         (SimplifyDemandedBits(N->getOperand(1), LowMask, DCI)))
12421       return SDValue();
12422     break;
12423   }
12424   case ARMISD::SMLALTT: {
12425     unsigned BitWidth = N->getValueType(0).getSizeInBits();
12426     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16);
12427     if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) ||
12428         (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)))
12429       return SDValue();
12430     break;
12431   }
12432   case ISD::INTRINSIC_VOID:
12433   case ISD::INTRINSIC_W_CHAIN:
12434     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
12435     case Intrinsic::arm_neon_vld1:
12436     case Intrinsic::arm_neon_vld2:
12437     case Intrinsic::arm_neon_vld3:
12438     case Intrinsic::arm_neon_vld4:
12439     case Intrinsic::arm_neon_vld2lane:
12440     case Intrinsic::arm_neon_vld3lane:
12441     case Intrinsic::arm_neon_vld4lane:
12442     case Intrinsic::arm_neon_vst1:
12443     case Intrinsic::arm_neon_vst2:
12444     case Intrinsic::arm_neon_vst3:
12445     case Intrinsic::arm_neon_vst4:
12446     case Intrinsic::arm_neon_vst2lane:
12447     case Intrinsic::arm_neon_vst3lane:
12448     case Intrinsic::arm_neon_vst4lane:
12449       return PerformVLDCombine(N, DCI);
12450     default: break;
12451     }
12452     break;
12453   }
12454   return SDValue();
12455 }
12456 
12457 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
12458                                                           EVT VT) const {
12459   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
12460 }
12461 
12462 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
12463                                                        unsigned,
12464                                                        unsigned,
12465                                                        bool *Fast) const {
12466   // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
12467   bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
12468 
12469   switch (VT.getSimpleVT().SimpleTy) {
12470   default:
12471     return false;
12472   case MVT::i8:
12473   case MVT::i16:
12474   case MVT::i32: {
12475     // Unaligned access can use (for example) LRDB, LRDH, LDR
12476     if (AllowsUnaligned) {
12477       if (Fast)
12478         *Fast = Subtarget->hasV7Ops();
12479       return true;
12480     }
12481     return false;
12482   }
12483   case MVT::f64:
12484   case MVT::v2f64: {
12485     // For any little-endian targets with neon, we can support unaligned ld/st
12486     // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
12487     // A big-endian target may also explicitly support unaligned accesses
12488     if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) {
12489       if (Fast)
12490         *Fast = true;
12491       return true;
12492     }
12493     return false;
12494   }
12495   }
12496 }
12497 
12498 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
12499                        unsigned AlignCheck) {
12500   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
12501           (DstAlign == 0 || DstAlign % AlignCheck == 0));
12502 }
12503 
12504 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
12505                                            unsigned DstAlign, unsigned SrcAlign,
12506                                            bool IsMemset, bool ZeroMemset,
12507                                            bool MemcpyStrSrc,
12508                                            MachineFunction &MF) const {
12509   const Function &F = MF.getFunction();
12510 
12511   // See if we can use NEON instructions for this...
12512   if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() &&
12513       !F.hasFnAttribute(Attribute::NoImplicitFloat)) {
12514     bool Fast;
12515     if (Size >= 16 &&
12516         (memOpAlign(SrcAlign, DstAlign, 16) ||
12517          (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) {
12518       return MVT::v2f64;
12519     } else if (Size >= 8 &&
12520                (memOpAlign(SrcAlign, DstAlign, 8) ||
12521                 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) &&
12522                  Fast))) {
12523       return MVT::f64;
12524     }
12525   }
12526 
12527   // Let the target-independent logic figure it out.
12528   return MVT::Other;
12529 }
12530 
12531 // 64-bit integers are split into their high and low parts and held in two
12532 // different registers, so the trunc is free since the low register can just
12533 // be used.
12534 bool ARMTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const {
12535   if (!SrcTy->isIntegerTy() || !DstTy->isIntegerTy())
12536     return false;
12537   unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
12538   unsigned DestBits = DstTy->getPrimitiveSizeInBits();
12539   return (SrcBits == 64 && DestBits == 32);
12540 }
12541 
12542 bool ARMTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const {
12543   if (SrcVT.isVector() || DstVT.isVector() || !SrcVT.isInteger() ||
12544       !DstVT.isInteger())
12545     return false;
12546   unsigned SrcBits = SrcVT.getSizeInBits();
12547   unsigned DestBits = DstVT.getSizeInBits();
12548   return (SrcBits == 64 && DestBits == 32);
12549 }
12550 
12551 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
12552   if (Val.getOpcode() != ISD::LOAD)
12553     return false;
12554 
12555   EVT VT1 = Val.getValueType();
12556   if (!VT1.isSimple() || !VT1.isInteger() ||
12557       !VT2.isSimple() || !VT2.isInteger())
12558     return false;
12559 
12560   switch (VT1.getSimpleVT().SimpleTy) {
12561   default: break;
12562   case MVT::i1:
12563   case MVT::i8:
12564   case MVT::i16:
12565     // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
12566     return true;
12567   }
12568 
12569   return false;
12570 }
12571 
12572 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
12573   EVT VT = ExtVal.getValueType();
12574 
12575   if (!isTypeLegal(VT))
12576     return false;
12577 
12578   // Don't create a loadext if we can fold the extension into a wide/long
12579   // instruction.
12580   // If there's more than one user instruction, the loadext is desirable no
12581   // matter what.  There can be two uses by the same instruction.
12582   if (ExtVal->use_empty() ||
12583       !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode()))
12584     return true;
12585 
12586   SDNode *U = *ExtVal->use_begin();
12587   if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB ||
12588        U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHL))
12589     return false;
12590 
12591   return true;
12592 }
12593 
12594 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
12595   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
12596     return false;
12597 
12598   if (!isTypeLegal(EVT::getEVT(Ty1)))
12599     return false;
12600 
12601   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
12602 
12603   // Assuming the caller doesn't have a zeroext or signext return parameter,
12604   // truncation all the way down to i1 is valid.
12605   return true;
12606 }
12607 
12608 int ARMTargetLowering::getScalingFactorCost(const DataLayout &DL,
12609                                                 const AddrMode &AM, Type *Ty,
12610                                                 unsigned AS) const {
12611   if (isLegalAddressingMode(DL, AM, Ty, AS)) {
12612     if (Subtarget->hasFPAO())
12613       return AM.Scale < 0 ? 1 : 0; // positive offsets execute faster
12614     return 0;
12615   }
12616   return -1;
12617 }
12618 
12619 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
12620   if (V < 0)
12621     return false;
12622 
12623   unsigned Scale = 1;
12624   switch (VT.getSimpleVT().SimpleTy) {
12625   default: return false;
12626   case MVT::i1:
12627   case MVT::i8:
12628     // Scale == 1;
12629     break;
12630   case MVT::i16:
12631     // Scale == 2;
12632     Scale = 2;
12633     break;
12634   case MVT::i32:
12635     // Scale == 4;
12636     Scale = 4;
12637     break;
12638   }
12639 
12640   if ((V & (Scale - 1)) != 0)
12641     return false;
12642   V /= Scale;
12643   return V == (V & ((1LL << 5) - 1));
12644 }
12645 
12646 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
12647                                       const ARMSubtarget *Subtarget) {
12648   bool isNeg = false;
12649   if (V < 0) {
12650     isNeg = true;
12651     V = - V;
12652   }
12653 
12654   switch (VT.getSimpleVT().SimpleTy) {
12655   default: return false;
12656   case MVT::i1:
12657   case MVT::i8:
12658   case MVT::i16:
12659   case MVT::i32:
12660     // + imm12 or - imm8
12661     if (isNeg)
12662       return V == (V & ((1LL << 8) - 1));
12663     return V == (V & ((1LL << 12) - 1));
12664   case MVT::f32:
12665   case MVT::f64:
12666     // Same as ARM mode. FIXME: NEON?
12667     if (!Subtarget->hasVFP2())
12668       return false;
12669     if ((V & 3) != 0)
12670       return false;
12671     V >>= 2;
12672     return V == (V & ((1LL << 8) - 1));
12673   }
12674 }
12675 
12676 /// isLegalAddressImmediate - Return true if the integer value can be used
12677 /// as the offset of the target addressing mode for load / store of the
12678 /// given type.
12679 static bool isLegalAddressImmediate(int64_t V, EVT VT,
12680                                     const ARMSubtarget *Subtarget) {
12681   if (V == 0)
12682     return true;
12683 
12684   if (!VT.isSimple())
12685     return false;
12686 
12687   if (Subtarget->isThumb1Only())
12688     return isLegalT1AddressImmediate(V, VT);
12689   else if (Subtarget->isThumb2())
12690     return isLegalT2AddressImmediate(V, VT, Subtarget);
12691 
12692   // ARM mode.
12693   if (V < 0)
12694     V = - V;
12695   switch (VT.getSimpleVT().SimpleTy) {
12696   default: return false;
12697   case MVT::i1:
12698   case MVT::i8:
12699   case MVT::i32:
12700     // +- imm12
12701     return V == (V & ((1LL << 12) - 1));
12702   case MVT::i16:
12703     // +- imm8
12704     return V == (V & ((1LL << 8) - 1));
12705   case MVT::f32:
12706   case MVT::f64:
12707     if (!Subtarget->hasVFP2()) // FIXME: NEON?
12708       return false;
12709     if ((V & 3) != 0)
12710       return false;
12711     V >>= 2;
12712     return V == (V & ((1LL << 8) - 1));
12713   }
12714 }
12715 
12716 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
12717                                                       EVT VT) const {
12718   int Scale = AM.Scale;
12719   if (Scale < 0)
12720     return false;
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     if (Scale == 1)
12729       return true;
12730     // r + r << imm
12731     Scale = Scale & ~1;
12732     return Scale == 2 || Scale == 4 || Scale == 8;
12733   case MVT::i64:
12734     // FIXME: What are we trying to model here? ldrd doesn't have an r + r
12735     // version in Thumb mode.
12736     // r + r
12737     if (Scale == 1)
12738       return true;
12739     // r * 2 (this can be lowered to r + r).
12740     if (!AM.HasBaseReg && Scale == 2)
12741       return true;
12742     return false;
12743   case MVT::isVoid:
12744     // Note, we allow "void" uses (basically, uses that aren't loads or
12745     // stores), because arm allows folding a scale into many arithmetic
12746     // operations.  This should be made more precise and revisited later.
12747 
12748     // Allow r << imm, but the imm has to be a multiple of two.
12749     if (Scale & 1) return false;
12750     return isPowerOf2_32(Scale);
12751   }
12752 }
12753 
12754 bool ARMTargetLowering::isLegalT1ScaledAddressingMode(const AddrMode &AM,
12755                                                       EVT VT) const {
12756   const int Scale = AM.Scale;
12757 
12758   // Negative scales are not supported in Thumb1.
12759   if (Scale < 0)
12760     return false;
12761 
12762   // Thumb1 addressing modes do not support register scaling excepting the
12763   // following cases:
12764   // 1. Scale == 1 means no scaling.
12765   // 2. Scale == 2 this can be lowered to r + r if there is no base register.
12766   return (Scale == 1) || (!AM.HasBaseReg && Scale == 2);
12767 }
12768 
12769 /// isLegalAddressingMode - Return true if the addressing mode represented
12770 /// by AM is legal for this target, for a load/store of the specified type.
12771 bool ARMTargetLowering::isLegalAddressingMode(const DataLayout &DL,
12772                                               const AddrMode &AM, Type *Ty,
12773                                               unsigned AS, Instruction *I) const {
12774   EVT VT = getValueType(DL, Ty, true);
12775   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
12776     return false;
12777 
12778   // Can never fold addr of global into load/store.
12779   if (AM.BaseGV)
12780     return false;
12781 
12782   switch (AM.Scale) {
12783   case 0:  // no scale reg, must be "r+i" or "r", or "i".
12784     break;
12785   default:
12786     // ARM doesn't support any R+R*scale+imm addr modes.
12787     if (AM.BaseOffs)
12788       return false;
12789 
12790     if (!VT.isSimple())
12791       return false;
12792 
12793     if (Subtarget->isThumb1Only())
12794       return isLegalT1ScaledAddressingMode(AM, VT);
12795 
12796     if (Subtarget->isThumb2())
12797       return isLegalT2ScaledAddressingMode(AM, VT);
12798 
12799     int Scale = AM.Scale;
12800     switch (VT.getSimpleVT().SimpleTy) {
12801     default: return false;
12802     case MVT::i1:
12803     case MVT::i8:
12804     case MVT::i32:
12805       if (Scale < 0) Scale = -Scale;
12806       if (Scale == 1)
12807         return true;
12808       // r + r << imm
12809       return isPowerOf2_32(Scale & ~1);
12810     case MVT::i16:
12811     case MVT::i64:
12812       // r +/- r
12813       if (Scale == 1 || (AM.HasBaseReg && Scale == -1))
12814         return true;
12815       // r * 2 (this can be lowered to r + r).
12816       if (!AM.HasBaseReg && Scale == 2)
12817         return true;
12818       return false;
12819 
12820     case MVT::isVoid:
12821       // Note, we allow "void" uses (basically, uses that aren't loads or
12822       // stores), because arm allows folding a scale into many arithmetic
12823       // operations.  This should be made more precise and revisited later.
12824 
12825       // Allow r << imm, but the imm has to be a multiple of two.
12826       if (Scale & 1) return false;
12827       return isPowerOf2_32(Scale);
12828     }
12829   }
12830   return true;
12831 }
12832 
12833 /// isLegalICmpImmediate - Return true if the specified immediate is legal
12834 /// icmp immediate, that is the target has icmp instructions which can compare
12835 /// a register against the immediate without having to materialize the
12836 /// immediate into a register.
12837 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
12838   // Thumb2 and ARM modes can use cmn for negative immediates.
12839   if (!Subtarget->isThumb())
12840     return ARM_AM::getSOImmVal(std::abs(Imm)) != -1;
12841   if (Subtarget->isThumb2())
12842     return ARM_AM::getT2SOImmVal(std::abs(Imm)) != -1;
12843   // Thumb1 doesn't have cmn, and only 8-bit immediates.
12844   return Imm >= 0 && Imm <= 255;
12845 }
12846 
12847 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
12848 /// *or sub* immediate, that is the target has add or sub instructions which can
12849 /// add a register with the immediate without having to materialize the
12850 /// immediate into a register.
12851 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
12852   // Same encoding for add/sub, just flip the sign.
12853   int64_t AbsImm = std::abs(Imm);
12854   if (!Subtarget->isThumb())
12855     return ARM_AM::getSOImmVal(AbsImm) != -1;
12856   if (Subtarget->isThumb2())
12857     return ARM_AM::getT2SOImmVal(AbsImm) != -1;
12858   // Thumb1 only has 8-bit unsigned immediate.
12859   return AbsImm >= 0 && AbsImm <= 255;
12860 }
12861 
12862 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
12863                                       bool isSEXTLoad, SDValue &Base,
12864                                       SDValue &Offset, bool &isInc,
12865                                       SelectionDAG &DAG) {
12866   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
12867     return false;
12868 
12869   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
12870     // AddressingMode 3
12871     Base = Ptr->getOperand(0);
12872     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
12873       int RHSC = (int)RHS->getZExtValue();
12874       if (RHSC < 0 && RHSC > -256) {
12875         assert(Ptr->getOpcode() == ISD::ADD);
12876         isInc = false;
12877         Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
12878         return true;
12879       }
12880     }
12881     isInc = (Ptr->getOpcode() == ISD::ADD);
12882     Offset = Ptr->getOperand(1);
12883     return true;
12884   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
12885     // AddressingMode 2
12886     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
12887       int RHSC = (int)RHS->getZExtValue();
12888       if (RHSC < 0 && RHSC > -0x1000) {
12889         assert(Ptr->getOpcode() == ISD::ADD);
12890         isInc = false;
12891         Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
12892         Base = Ptr->getOperand(0);
12893         return true;
12894       }
12895     }
12896 
12897     if (Ptr->getOpcode() == ISD::ADD) {
12898       isInc = true;
12899       ARM_AM::ShiftOpc ShOpcVal=
12900         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
12901       if (ShOpcVal != ARM_AM::no_shift) {
12902         Base = Ptr->getOperand(1);
12903         Offset = Ptr->getOperand(0);
12904       } else {
12905         Base = Ptr->getOperand(0);
12906         Offset = Ptr->getOperand(1);
12907       }
12908       return true;
12909     }
12910 
12911     isInc = (Ptr->getOpcode() == ISD::ADD);
12912     Base = Ptr->getOperand(0);
12913     Offset = Ptr->getOperand(1);
12914     return true;
12915   }
12916 
12917   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
12918   return false;
12919 }
12920 
12921 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
12922                                      bool isSEXTLoad, SDValue &Base,
12923                                      SDValue &Offset, bool &isInc,
12924                                      SelectionDAG &DAG) {
12925   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
12926     return false;
12927 
12928   Base = Ptr->getOperand(0);
12929   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
12930     int RHSC = (int)RHS->getZExtValue();
12931     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
12932       assert(Ptr->getOpcode() == ISD::ADD);
12933       isInc = false;
12934       Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
12935       return true;
12936     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
12937       isInc = Ptr->getOpcode() == ISD::ADD;
12938       Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0));
12939       return true;
12940     }
12941   }
12942 
12943   return false;
12944 }
12945 
12946 /// getPreIndexedAddressParts - returns true by value, base pointer and
12947 /// offset pointer and addressing mode by reference if the node's address
12948 /// can be legally represented as pre-indexed load / store address.
12949 bool
12950 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
12951                                              SDValue &Offset,
12952                                              ISD::MemIndexedMode &AM,
12953                                              SelectionDAG &DAG) const {
12954   if (Subtarget->isThumb1Only())
12955     return false;
12956 
12957   EVT VT;
12958   SDValue Ptr;
12959   bool isSEXTLoad = false;
12960   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
12961     Ptr = LD->getBasePtr();
12962     VT  = LD->getMemoryVT();
12963     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
12964   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
12965     Ptr = ST->getBasePtr();
12966     VT  = ST->getMemoryVT();
12967   } else
12968     return false;
12969 
12970   bool isInc;
12971   bool isLegal = false;
12972   if (Subtarget->isThumb2())
12973     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
12974                                        Offset, isInc, DAG);
12975   else
12976     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
12977                                         Offset, isInc, DAG);
12978   if (!isLegal)
12979     return false;
12980 
12981   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
12982   return true;
12983 }
12984 
12985 /// getPostIndexedAddressParts - returns true by value, base pointer and
12986 /// offset pointer and addressing mode by reference if this node can be
12987 /// combined with a load / store to form a post-indexed load / store.
12988 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
12989                                                    SDValue &Base,
12990                                                    SDValue &Offset,
12991                                                    ISD::MemIndexedMode &AM,
12992                                                    SelectionDAG &DAG) const {
12993   EVT VT;
12994   SDValue Ptr;
12995   bool isSEXTLoad = false, isNonExt;
12996   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
12997     VT  = LD->getMemoryVT();
12998     Ptr = LD->getBasePtr();
12999     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
13000     isNonExt = LD->getExtensionType() == ISD::NON_EXTLOAD;
13001   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
13002     VT  = ST->getMemoryVT();
13003     Ptr = ST->getBasePtr();
13004     isNonExt = !ST->isTruncatingStore();
13005   } else
13006     return false;
13007 
13008   if (Subtarget->isThumb1Only()) {
13009     // Thumb-1 can do a limited post-inc load or store as an updating LDM. It
13010     // must be non-extending/truncating, i32, with an offset of 4.
13011     assert(Op->getValueType(0) == MVT::i32 && "Non-i32 post-inc op?!");
13012     if (Op->getOpcode() != ISD::ADD || !isNonExt)
13013       return false;
13014     auto *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1));
13015     if (!RHS || RHS->getZExtValue() != 4)
13016       return false;
13017 
13018     Offset = Op->getOperand(1);
13019     Base = Op->getOperand(0);
13020     AM = ISD::POST_INC;
13021     return true;
13022   }
13023 
13024   bool isInc;
13025   bool isLegal = false;
13026   if (Subtarget->isThumb2())
13027     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
13028                                        isInc, DAG);
13029   else
13030     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
13031                                         isInc, DAG);
13032   if (!isLegal)
13033     return false;
13034 
13035   if (Ptr != Base) {
13036     // Swap base ptr and offset to catch more post-index load / store when
13037     // it's legal. In Thumb2 mode, offset must be an immediate.
13038     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
13039         !Subtarget->isThumb2())
13040       std::swap(Base, Offset);
13041 
13042     // Post-indexed load / store update the base pointer.
13043     if (Ptr != Base)
13044       return false;
13045   }
13046 
13047   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
13048   return true;
13049 }
13050 
13051 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
13052                                                       KnownBits &Known,
13053                                                       const APInt &DemandedElts,
13054                                                       const SelectionDAG &DAG,
13055                                                       unsigned Depth) const {
13056   unsigned BitWidth = Known.getBitWidth();
13057   Known.resetAll();
13058   switch (Op.getOpcode()) {
13059   default: break;
13060   case ARMISD::ADDC:
13061   case ARMISD::ADDE:
13062   case ARMISD::SUBC:
13063   case ARMISD::SUBE:
13064     // Special cases when we convert a carry to a boolean.
13065     if (Op.getResNo() == 0) {
13066       SDValue LHS = Op.getOperand(0);
13067       SDValue RHS = Op.getOperand(1);
13068       // (ADDE 0, 0, C) will give us a single bit.
13069       if (Op->getOpcode() == ARMISD::ADDE && isNullConstant(LHS) &&
13070           isNullConstant(RHS)) {
13071         Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
13072         return;
13073       }
13074     }
13075     break;
13076   case ARMISD::CMOV: {
13077     // Bits are known zero/one if known on the LHS and RHS.
13078     DAG.computeKnownBits(Op.getOperand(0), Known, Depth+1);
13079     if (Known.isUnknown())
13080       return;
13081 
13082     KnownBits KnownRHS;
13083     DAG.computeKnownBits(Op.getOperand(1), KnownRHS, Depth+1);
13084     Known.Zero &= KnownRHS.Zero;
13085     Known.One  &= KnownRHS.One;
13086     return;
13087   }
13088   case ISD::INTRINSIC_W_CHAIN: {
13089     ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
13090     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
13091     switch (IntID) {
13092     default: return;
13093     case Intrinsic::arm_ldaex:
13094     case Intrinsic::arm_ldrex: {
13095       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
13096       unsigned MemBits = VT.getScalarSizeInBits();
13097       Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
13098       return;
13099     }
13100     }
13101   }
13102   case ARMISD::BFI: {
13103     // Conservatively, we can recurse down the first operand
13104     // and just mask out all affected bits.
13105     DAG.computeKnownBits(Op.getOperand(0), Known, Depth + 1);
13106 
13107     // The operand to BFI is already a mask suitable for removing the bits it
13108     // sets.
13109     ConstantSDNode *CI = cast<ConstantSDNode>(Op.getOperand(2));
13110     const APInt &Mask = CI->getAPIntValue();
13111     Known.Zero &= Mask;
13112     Known.One &= Mask;
13113     return;
13114   }
13115   }
13116 }
13117 
13118 //===----------------------------------------------------------------------===//
13119 //                           ARM Inline Assembly Support
13120 //===----------------------------------------------------------------------===//
13121 
13122 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
13123   // Looking for "rev" which is V6+.
13124   if (!Subtarget->hasV6Ops())
13125     return false;
13126 
13127   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
13128   std::string AsmStr = IA->getAsmString();
13129   SmallVector<StringRef, 4> AsmPieces;
13130   SplitString(AsmStr, AsmPieces, ";\n");
13131 
13132   switch (AsmPieces.size()) {
13133   default: return false;
13134   case 1:
13135     AsmStr = AsmPieces[0];
13136     AsmPieces.clear();
13137     SplitString(AsmStr, AsmPieces, " \t,");
13138 
13139     // rev $0, $1
13140     if (AsmPieces.size() == 3 &&
13141         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
13142         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
13143       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
13144       if (Ty && Ty->getBitWidth() == 32)
13145         return IntrinsicLowering::LowerToByteSwap(CI);
13146     }
13147     break;
13148   }
13149 
13150   return false;
13151 }
13152 
13153 const char *ARMTargetLowering::LowerXConstraint(EVT ConstraintVT) const {
13154   // At this point, we have to lower this constraint to something else, so we
13155   // lower it to an "r" or "w". However, by doing this we will force the result
13156   // to be in register, while the X constraint is much more permissive.
13157   //
13158   // Although we are correct (we are free to emit anything, without
13159   // constraints), we might break use cases that would expect us to be more
13160   // efficient and emit something else.
13161   if (!Subtarget->hasVFP2())
13162     return "r";
13163   if (ConstraintVT.isFloatingPoint())
13164     return "w";
13165   if (ConstraintVT.isVector() && Subtarget->hasNEON() &&
13166      (ConstraintVT.getSizeInBits() == 64 ||
13167       ConstraintVT.getSizeInBits() == 128))
13168     return "w";
13169 
13170   return "r";
13171 }
13172 
13173 /// getConstraintType - Given a constraint letter, return the type of
13174 /// constraint it is for this target.
13175 ARMTargetLowering::ConstraintType
13176 ARMTargetLowering::getConstraintType(StringRef Constraint) const {
13177   if (Constraint.size() == 1) {
13178     switch (Constraint[0]) {
13179     default:  break;
13180     case 'l': return C_RegisterClass;
13181     case 'w': return C_RegisterClass;
13182     case 'h': return C_RegisterClass;
13183     case 'x': return C_RegisterClass;
13184     case 't': return C_RegisterClass;
13185     case 'j': return C_Other; // Constant for movw.
13186       // An address with a single base register. Due to the way we
13187       // currently handle addresses it is the same as an 'r' memory constraint.
13188     case 'Q': return C_Memory;
13189     }
13190   } else if (Constraint.size() == 2) {
13191     switch (Constraint[0]) {
13192     default: break;
13193     // All 'U+' constraints are addresses.
13194     case 'U': return C_Memory;
13195     }
13196   }
13197   return TargetLowering::getConstraintType(Constraint);
13198 }
13199 
13200 /// Examine constraint type and operand type and determine a weight value.
13201 /// This object must already have been set up with the operand type
13202 /// and the current alternative constraint selected.
13203 TargetLowering::ConstraintWeight
13204 ARMTargetLowering::getSingleConstraintMatchWeight(
13205     AsmOperandInfo &info, const char *constraint) const {
13206   ConstraintWeight weight = CW_Invalid;
13207   Value *CallOperandVal = info.CallOperandVal;
13208     // If we don't have a value, we can't do a match,
13209     // but allow it at the lowest weight.
13210   if (!CallOperandVal)
13211     return CW_Default;
13212   Type *type = CallOperandVal->getType();
13213   // Look at the constraint type.
13214   switch (*constraint) {
13215   default:
13216     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
13217     break;
13218   case 'l':
13219     if (type->isIntegerTy()) {
13220       if (Subtarget->isThumb())
13221         weight = CW_SpecificReg;
13222       else
13223         weight = CW_Register;
13224     }
13225     break;
13226   case 'w':
13227     if (type->isFloatingPointTy())
13228       weight = CW_Register;
13229     break;
13230   }
13231   return weight;
13232 }
13233 
13234 using RCPair = std::pair<unsigned, const TargetRegisterClass *>;
13235 
13236 RCPair ARMTargetLowering::getRegForInlineAsmConstraint(
13237     const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
13238   if (Constraint.size() == 1) {
13239     // GCC ARM Constraint Letters
13240     switch (Constraint[0]) {
13241     case 'l': // Low regs or general regs.
13242       if (Subtarget->isThumb())
13243         return RCPair(0U, &ARM::tGPRRegClass);
13244       return RCPair(0U, &ARM::GPRRegClass);
13245     case 'h': // High regs or no regs.
13246       if (Subtarget->isThumb())
13247         return RCPair(0U, &ARM::hGPRRegClass);
13248       break;
13249     case 'r':
13250       if (Subtarget->isThumb1Only())
13251         return RCPair(0U, &ARM::tGPRRegClass);
13252       return RCPair(0U, &ARM::GPRRegClass);
13253     case 'w':
13254       if (VT == MVT::Other)
13255         break;
13256       if (VT == MVT::f32)
13257         return RCPair(0U, &ARM::SPRRegClass);
13258       if (VT.getSizeInBits() == 64)
13259         return RCPair(0U, &ARM::DPRRegClass);
13260       if (VT.getSizeInBits() == 128)
13261         return RCPair(0U, &ARM::QPRRegClass);
13262       break;
13263     case 'x':
13264       if (VT == MVT::Other)
13265         break;
13266       if (VT == MVT::f32)
13267         return RCPair(0U, &ARM::SPR_8RegClass);
13268       if (VT.getSizeInBits() == 64)
13269         return RCPair(0U, &ARM::DPR_8RegClass);
13270       if (VT.getSizeInBits() == 128)
13271         return RCPair(0U, &ARM::QPR_8RegClass);
13272       break;
13273     case 't':
13274       if (VT == MVT::f32 || VT == MVT::i32)
13275         return RCPair(0U, &ARM::SPRRegClass);
13276       break;
13277     }
13278   }
13279   if (StringRef("{cc}").equals_lower(Constraint))
13280     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
13281 
13282   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
13283 }
13284 
13285 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
13286 /// vector.  If it is invalid, don't add anything to Ops.
13287 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
13288                                                      std::string &Constraint,
13289                                                      std::vector<SDValue>&Ops,
13290                                                      SelectionDAG &DAG) const {
13291   SDValue Result;
13292 
13293   // Currently only support length 1 constraints.
13294   if (Constraint.length() != 1) return;
13295 
13296   char ConstraintLetter = Constraint[0];
13297   switch (ConstraintLetter) {
13298   default: break;
13299   case 'j':
13300   case 'I': case 'J': case 'K': case 'L':
13301   case 'M': case 'N': case 'O':
13302     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
13303     if (!C)
13304       return;
13305 
13306     int64_t CVal64 = C->getSExtValue();
13307     int CVal = (int) CVal64;
13308     // None of these constraints allow values larger than 32 bits.  Check
13309     // that the value fits in an int.
13310     if (CVal != CVal64)
13311       return;
13312 
13313     switch (ConstraintLetter) {
13314       case 'j':
13315         // Constant suitable for movw, must be between 0 and
13316         // 65535.
13317         if (Subtarget->hasV6T2Ops())
13318           if (CVal >= 0 && CVal <= 65535)
13319             break;
13320         return;
13321       case 'I':
13322         if (Subtarget->isThumb1Only()) {
13323           // This must be a constant between 0 and 255, for ADD
13324           // immediates.
13325           if (CVal >= 0 && CVal <= 255)
13326             break;
13327         } else if (Subtarget->isThumb2()) {
13328           // A constant that can be used as an immediate value in a
13329           // data-processing instruction.
13330           if (ARM_AM::getT2SOImmVal(CVal) != -1)
13331             break;
13332         } else {
13333           // A constant that can be used as an immediate value in a
13334           // data-processing instruction.
13335           if (ARM_AM::getSOImmVal(CVal) != -1)
13336             break;
13337         }
13338         return;
13339 
13340       case 'J':
13341         if (Subtarget->isThumb1Only()) {
13342           // This must be a constant between -255 and -1, for negated ADD
13343           // immediates. This can be used in GCC with an "n" modifier that
13344           // prints the negated value, for use with SUB instructions. It is
13345           // not useful otherwise but is implemented for compatibility.
13346           if (CVal >= -255 && CVal <= -1)
13347             break;
13348         } else {
13349           // This must be a constant between -4095 and 4095. It is not clear
13350           // what this constraint is intended for. Implemented for
13351           // compatibility with GCC.
13352           if (CVal >= -4095 && CVal <= 4095)
13353             break;
13354         }
13355         return;
13356 
13357       case 'K':
13358         if (Subtarget->isThumb1Only()) {
13359           // A 32-bit value where only one byte has a nonzero value. Exclude
13360           // zero to match GCC. This constraint is used by GCC internally for
13361           // constants that can be loaded with a move/shift combination.
13362           // It is not useful otherwise but is implemented for compatibility.
13363           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
13364             break;
13365         } else if (Subtarget->isThumb2()) {
13366           // A constant whose bitwise inverse can be used as an immediate
13367           // value in a data-processing instruction. This can be used in GCC
13368           // with a "B" modifier that prints the inverted value, for use with
13369           // BIC and MVN instructions. It is not useful otherwise but is
13370           // implemented for compatibility.
13371           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
13372             break;
13373         } else {
13374           // A constant whose bitwise inverse can be used as an immediate
13375           // value in a data-processing instruction. This can be used in GCC
13376           // with a "B" modifier that prints the inverted value, for use with
13377           // BIC and MVN instructions. It is not useful otherwise but is
13378           // implemented for compatibility.
13379           if (ARM_AM::getSOImmVal(~CVal) != -1)
13380             break;
13381         }
13382         return;
13383 
13384       case 'L':
13385         if (Subtarget->isThumb1Only()) {
13386           // This must be a constant between -7 and 7,
13387           // for 3-operand ADD/SUB immediate instructions.
13388           if (CVal >= -7 && CVal < 7)
13389             break;
13390         } else if (Subtarget->isThumb2()) {
13391           // A constant whose negation can be used as an immediate value in a
13392           // data-processing instruction. This can be used in GCC with an "n"
13393           // modifier that prints the negated value, for use with SUB
13394           // instructions. It is not useful otherwise but is implemented for
13395           // compatibility.
13396           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
13397             break;
13398         } else {
13399           // A constant whose negation can be used as an immediate value in a
13400           // data-processing instruction. This can be used in GCC with an "n"
13401           // modifier that prints the negated value, for use with SUB
13402           // instructions. It is not useful otherwise but is implemented for
13403           // compatibility.
13404           if (ARM_AM::getSOImmVal(-CVal) != -1)
13405             break;
13406         }
13407         return;
13408 
13409       case 'M':
13410         if (Subtarget->isThumb1Only()) {
13411           // This must be a multiple of 4 between 0 and 1020, for
13412           // ADD sp + immediate.
13413           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
13414             break;
13415         } else {
13416           // A power of two or a constant between 0 and 32.  This is used in
13417           // GCC for the shift amount on shifted register operands, but it is
13418           // useful in general for any shift amounts.
13419           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
13420             break;
13421         }
13422         return;
13423 
13424       case 'N':
13425         if (Subtarget->isThumb()) {  // FIXME thumb2
13426           // This must be a constant between 0 and 31, for shift amounts.
13427           if (CVal >= 0 && CVal <= 31)
13428             break;
13429         }
13430         return;
13431 
13432       case 'O':
13433         if (Subtarget->isThumb()) {  // FIXME thumb2
13434           // This must be a multiple of 4 between -508 and 508, for
13435           // ADD/SUB sp = sp + immediate.
13436           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
13437             break;
13438         }
13439         return;
13440     }
13441     Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType());
13442     break;
13443   }
13444 
13445   if (Result.getNode()) {
13446     Ops.push_back(Result);
13447     return;
13448   }
13449   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
13450 }
13451 
13452 static RTLIB::Libcall getDivRemLibcall(
13453     const SDNode *N, MVT::SimpleValueType SVT) {
13454   assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
13455           N->getOpcode() == ISD::SREM    || N->getOpcode() == ISD::UREM) &&
13456          "Unhandled Opcode in getDivRemLibcall");
13457   bool isSigned = N->getOpcode() == ISD::SDIVREM ||
13458                   N->getOpcode() == ISD::SREM;
13459   RTLIB::Libcall LC;
13460   switch (SVT) {
13461   default: llvm_unreachable("Unexpected request for libcall!");
13462   case MVT::i8:  LC = isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
13463   case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
13464   case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
13465   case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
13466   }
13467   return LC;
13468 }
13469 
13470 static TargetLowering::ArgListTy getDivRemArgList(
13471     const SDNode *N, LLVMContext *Context, const ARMSubtarget *Subtarget) {
13472   assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
13473           N->getOpcode() == ISD::SREM    || N->getOpcode() == ISD::UREM) &&
13474          "Unhandled Opcode in getDivRemArgList");
13475   bool isSigned = N->getOpcode() == ISD::SDIVREM ||
13476                   N->getOpcode() == ISD::SREM;
13477   TargetLowering::ArgListTy Args;
13478   TargetLowering::ArgListEntry Entry;
13479   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
13480     EVT ArgVT = N->getOperand(i).getValueType();
13481     Type *ArgTy = ArgVT.getTypeForEVT(*Context);
13482     Entry.Node = N->getOperand(i);
13483     Entry.Ty = ArgTy;
13484     Entry.IsSExt = isSigned;
13485     Entry.IsZExt = !isSigned;
13486     Args.push_back(Entry);
13487   }
13488   if (Subtarget->isTargetWindows() && Args.size() >= 2)
13489     std::swap(Args[0], Args[1]);
13490   return Args;
13491 }
13492 
13493 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
13494   assert((Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() ||
13495           Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() ||
13496           Subtarget->isTargetWindows()) &&
13497          "Register-based DivRem lowering only");
13498   unsigned Opcode = Op->getOpcode();
13499   assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
13500          "Invalid opcode for Div/Rem lowering");
13501   bool isSigned = (Opcode == ISD::SDIVREM);
13502   EVT VT = Op->getValueType(0);
13503   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
13504   SDLoc dl(Op);
13505 
13506   // If the target has hardware divide, use divide + multiply + subtract:
13507   //     div = a / b
13508   //     rem = a - b * div
13509   //     return {div, rem}
13510   // This should be lowered into UDIV/SDIV + MLS later on.
13511   bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode()
13512                                         : Subtarget->hasDivideInARMMode();
13513   if (hasDivide && Op->getValueType(0).isSimple() &&
13514       Op->getSimpleValueType(0) == MVT::i32) {
13515     unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
13516     const SDValue Dividend = Op->getOperand(0);
13517     const SDValue Divisor = Op->getOperand(1);
13518     SDValue Div = DAG.getNode(DivOpcode, dl, VT, Dividend, Divisor);
13519     SDValue Mul = DAG.getNode(ISD::MUL, dl, VT, Div, Divisor);
13520     SDValue Rem = DAG.getNode(ISD::SUB, dl, VT, Dividend, Mul);
13521 
13522     SDValue Values[2] = {Div, Rem};
13523     return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VT, VT), Values);
13524   }
13525 
13526   RTLIB::Libcall LC = getDivRemLibcall(Op.getNode(),
13527                                        VT.getSimpleVT().SimpleTy);
13528   SDValue InChain = DAG.getEntryNode();
13529 
13530   TargetLowering::ArgListTy Args = getDivRemArgList(Op.getNode(),
13531                                                     DAG.getContext(),
13532                                                     Subtarget);
13533 
13534   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
13535                                          getPointerTy(DAG.getDataLayout()));
13536 
13537   Type *RetTy = StructType::get(Ty, Ty);
13538 
13539   if (Subtarget->isTargetWindows())
13540     InChain = WinDBZCheckDenominator(DAG, Op.getNode(), InChain);
13541 
13542   TargetLowering::CallLoweringInfo CLI(DAG);
13543   CLI.setDebugLoc(dl).setChain(InChain)
13544     .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args))
13545     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
13546 
13547   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
13548   return CallInfo.first;
13549 }
13550 
13551 // Lowers REM using divmod helpers
13552 // see RTABI section 4.2/4.3
13553 SDValue ARMTargetLowering::LowerREM(SDNode *N, SelectionDAG &DAG) const {
13554   // Build return types (div and rem)
13555   std::vector<Type*> RetTyParams;
13556   Type *RetTyElement;
13557 
13558   switch (N->getValueType(0).getSimpleVT().SimpleTy) {
13559   default: llvm_unreachable("Unexpected request for libcall!");
13560   case MVT::i8:   RetTyElement = Type::getInt8Ty(*DAG.getContext());  break;
13561   case MVT::i16:  RetTyElement = Type::getInt16Ty(*DAG.getContext()); break;
13562   case MVT::i32:  RetTyElement = Type::getInt32Ty(*DAG.getContext()); break;
13563   case MVT::i64:  RetTyElement = Type::getInt64Ty(*DAG.getContext()); break;
13564   }
13565 
13566   RetTyParams.push_back(RetTyElement);
13567   RetTyParams.push_back(RetTyElement);
13568   ArrayRef<Type*> ret = ArrayRef<Type*>(RetTyParams);
13569   Type *RetTy = StructType::get(*DAG.getContext(), ret);
13570 
13571   RTLIB::Libcall LC = getDivRemLibcall(N, N->getValueType(0).getSimpleVT().
13572                                                              SimpleTy);
13573   SDValue InChain = DAG.getEntryNode();
13574   TargetLowering::ArgListTy Args = getDivRemArgList(N, DAG.getContext(),
13575                                                     Subtarget);
13576   bool isSigned = N->getOpcode() == ISD::SREM;
13577   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
13578                                          getPointerTy(DAG.getDataLayout()));
13579 
13580   if (Subtarget->isTargetWindows())
13581     InChain = WinDBZCheckDenominator(DAG, N, InChain);
13582 
13583   // Lower call
13584   CallLoweringInfo CLI(DAG);
13585   CLI.setChain(InChain)
13586      .setCallee(CallingConv::ARM_AAPCS, RetTy, Callee, std::move(Args))
13587      .setSExtResult(isSigned).setZExtResult(!isSigned).setDebugLoc(SDLoc(N));
13588   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
13589 
13590   // Return second (rem) result operand (first contains div)
13591   SDNode *ResNode = CallResult.first.getNode();
13592   assert(ResNode->getNumOperands() == 2 && "divmod should return two operands");
13593   return ResNode->getOperand(1);
13594 }
13595 
13596 SDValue
13597 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
13598   assert(Subtarget->isTargetWindows() && "unsupported target platform");
13599   SDLoc DL(Op);
13600 
13601   // Get the inputs.
13602   SDValue Chain = Op.getOperand(0);
13603   SDValue Size  = Op.getOperand(1);
13604 
13605   SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
13606                               DAG.getConstant(2, DL, MVT::i32));
13607 
13608   SDValue Flag;
13609   Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
13610   Flag = Chain.getValue(1);
13611 
13612   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
13613   Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
13614 
13615   SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
13616   Chain = NewSP.getValue(1);
13617 
13618   SDValue Ops[2] = { NewSP, Chain };
13619   return DAG.getMergeValues(Ops, DL);
13620 }
13621 
13622 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
13623   assert(Op.getValueType() == MVT::f64 && Subtarget->isFPOnlySP() &&
13624          "Unexpected type for custom-lowering FP_EXTEND");
13625 
13626   RTLIB::Libcall LC;
13627   LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
13628 
13629   SDValue SrcVal = Op.getOperand(0);
13630   return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
13631                      SDLoc(Op)).first;
13632 }
13633 
13634 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
13635   assert(Op.getOperand(0).getValueType() == MVT::f64 &&
13636          Subtarget->isFPOnlySP() &&
13637          "Unexpected type for custom-lowering FP_ROUND");
13638 
13639   RTLIB::Libcall LC;
13640   LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
13641 
13642   SDValue SrcVal = Op.getOperand(0);
13643   return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
13644                      SDLoc(Op)).first;
13645 }
13646 
13647 bool
13648 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
13649   // The ARM target isn't yet aware of offsets.
13650   return false;
13651 }
13652 
13653 bool ARM::isBitFieldInvertedMask(unsigned v) {
13654   if (v == 0xffffffff)
13655     return false;
13656 
13657   // there can be 1's on either or both "outsides", all the "inside"
13658   // bits must be 0's
13659   return isShiftedMask_32(~v);
13660 }
13661 
13662 /// isFPImmLegal - Returns true if the target can instruction select the
13663 /// specified FP immediate natively. If false, the legalizer will
13664 /// materialize the FP immediate as a load from a constant pool.
13665 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
13666   if (!Subtarget->hasVFP3())
13667     return false;
13668   if (VT == MVT::f32)
13669     return ARM_AM::getFP32Imm(Imm) != -1;
13670   if (VT == MVT::f64 && !Subtarget->isFPOnlySP())
13671     return ARM_AM::getFP64Imm(Imm) != -1;
13672   return false;
13673 }
13674 
13675 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
13676 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
13677 /// specified in the intrinsic calls.
13678 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
13679                                            const CallInst &I,
13680                                            MachineFunction &MF,
13681                                            unsigned Intrinsic) const {
13682   switch (Intrinsic) {
13683   case Intrinsic::arm_neon_vld1:
13684   case Intrinsic::arm_neon_vld2:
13685   case Intrinsic::arm_neon_vld3:
13686   case Intrinsic::arm_neon_vld4:
13687   case Intrinsic::arm_neon_vld2lane:
13688   case Intrinsic::arm_neon_vld3lane:
13689   case Intrinsic::arm_neon_vld4lane: {
13690     Info.opc = ISD::INTRINSIC_W_CHAIN;
13691     // Conservatively set memVT to the entire set of vectors loaded.
13692     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
13693     uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
13694     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
13695     Info.ptrVal = I.getArgOperand(0);
13696     Info.offset = 0;
13697     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
13698     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
13699     // volatile loads with NEON intrinsics not supported
13700     Info.flags = MachineMemOperand::MOLoad;
13701     return true;
13702   }
13703   case Intrinsic::arm_neon_vst1:
13704   case Intrinsic::arm_neon_vst2:
13705   case Intrinsic::arm_neon_vst3:
13706   case Intrinsic::arm_neon_vst4:
13707   case Intrinsic::arm_neon_vst2lane:
13708   case Intrinsic::arm_neon_vst3lane:
13709   case Intrinsic::arm_neon_vst4lane: {
13710     Info.opc = ISD::INTRINSIC_VOID;
13711     // Conservatively set memVT to the entire set of vectors stored.
13712     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
13713     unsigned NumElts = 0;
13714     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
13715       Type *ArgTy = I.getArgOperand(ArgI)->getType();
13716       if (!ArgTy->isVectorTy())
13717         break;
13718       NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
13719     }
13720     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
13721     Info.ptrVal = I.getArgOperand(0);
13722     Info.offset = 0;
13723     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
13724     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
13725     // volatile stores with NEON intrinsics not supported
13726     Info.flags = MachineMemOperand::MOStore;
13727     return true;
13728   }
13729   case Intrinsic::arm_ldaex:
13730   case Intrinsic::arm_ldrex: {
13731     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
13732     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
13733     Info.opc = ISD::INTRINSIC_W_CHAIN;
13734     Info.memVT = MVT::getVT(PtrTy->getElementType());
13735     Info.ptrVal = I.getArgOperand(0);
13736     Info.offset = 0;
13737     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
13738     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
13739     return true;
13740   }
13741   case Intrinsic::arm_stlex:
13742   case Intrinsic::arm_strex: {
13743     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
13744     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
13745     Info.opc = ISD::INTRINSIC_W_CHAIN;
13746     Info.memVT = MVT::getVT(PtrTy->getElementType());
13747     Info.ptrVal = I.getArgOperand(1);
13748     Info.offset = 0;
13749     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
13750     Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
13751     return true;
13752   }
13753   case Intrinsic::arm_stlexd:
13754   case Intrinsic::arm_strexd:
13755     Info.opc = ISD::INTRINSIC_W_CHAIN;
13756     Info.memVT = MVT::i64;
13757     Info.ptrVal = I.getArgOperand(2);
13758     Info.offset = 0;
13759     Info.align = 8;
13760     Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
13761     return true;
13762 
13763   case Intrinsic::arm_ldaexd:
13764   case Intrinsic::arm_ldrexd:
13765     Info.opc = ISD::INTRINSIC_W_CHAIN;
13766     Info.memVT = MVT::i64;
13767     Info.ptrVal = I.getArgOperand(0);
13768     Info.offset = 0;
13769     Info.align = 8;
13770     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
13771     return true;
13772 
13773   default:
13774     break;
13775   }
13776 
13777   return false;
13778 }
13779 
13780 /// \brief Returns true if it is beneficial to convert a load of a constant
13781 /// to just the constant itself.
13782 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
13783                                                           Type *Ty) const {
13784   assert(Ty->isIntegerTy());
13785 
13786   unsigned Bits = Ty->getPrimitiveSizeInBits();
13787   if (Bits == 0 || Bits > 32)
13788     return false;
13789   return true;
13790 }
13791 
13792 bool ARMTargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT,
13793                                                 unsigned Index) const {
13794   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
13795     return false;
13796 
13797   return (Index == 0 || Index == ResVT.getVectorNumElements());
13798 }
13799 
13800 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder,
13801                                         ARM_MB::MemBOpt Domain) const {
13802   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
13803 
13804   // First, if the target has no DMB, see what fallback we can use.
13805   if (!Subtarget->hasDataBarrier()) {
13806     // Some ARMv6 cpus can support data barriers with an mcr instruction.
13807     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
13808     // here.
13809     if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) {
13810       Function *MCR = Intrinsic::getDeclaration(M, Intrinsic::arm_mcr);
13811       Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0),
13812                         Builder.getInt32(0), Builder.getInt32(7),
13813                         Builder.getInt32(10), Builder.getInt32(5)};
13814       return Builder.CreateCall(MCR, args);
13815     } else {
13816       // Instead of using barriers, atomic accesses on these subtargets use
13817       // libcalls.
13818       llvm_unreachable("makeDMB on a target so old that it has no barriers");
13819     }
13820   } else {
13821     Function *DMB = Intrinsic::getDeclaration(M, Intrinsic::arm_dmb);
13822     // Only a full system barrier exists in the M-class architectures.
13823     Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain;
13824     Constant *CDomain = Builder.getInt32(Domain);
13825     return Builder.CreateCall(DMB, CDomain);
13826   }
13827 }
13828 
13829 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
13830 Instruction *ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
13831                                                  Instruction *Inst,
13832                                                  AtomicOrdering Ord) const {
13833   switch (Ord) {
13834   case AtomicOrdering::NotAtomic:
13835   case AtomicOrdering::Unordered:
13836     llvm_unreachable("Invalid fence: unordered/non-atomic");
13837   case AtomicOrdering::Monotonic:
13838   case AtomicOrdering::Acquire:
13839     return nullptr; // Nothing to do
13840   case AtomicOrdering::SequentiallyConsistent:
13841     if (!Inst->hasAtomicStore())
13842       return nullptr; // Nothing to do
13843     LLVM_FALLTHROUGH;
13844   case AtomicOrdering::Release:
13845   case AtomicOrdering::AcquireRelease:
13846     if (Subtarget->preferISHSTBarriers())
13847       return makeDMB(Builder, ARM_MB::ISHST);
13848     // FIXME: add a comment with a link to documentation justifying this.
13849     else
13850       return makeDMB(Builder, ARM_MB::ISH);
13851   }
13852   llvm_unreachable("Unknown fence ordering in emitLeadingFence");
13853 }
13854 
13855 Instruction *ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
13856                                                   Instruction *Inst,
13857                                                   AtomicOrdering Ord) const {
13858   switch (Ord) {
13859   case AtomicOrdering::NotAtomic:
13860   case AtomicOrdering::Unordered:
13861     llvm_unreachable("Invalid fence: unordered/not-atomic");
13862   case AtomicOrdering::Monotonic:
13863   case AtomicOrdering::Release:
13864     return nullptr; // Nothing to do
13865   case AtomicOrdering::Acquire:
13866   case AtomicOrdering::AcquireRelease:
13867   case AtomicOrdering::SequentiallyConsistent:
13868     return makeDMB(Builder, ARM_MB::ISH);
13869   }
13870   llvm_unreachable("Unknown fence ordering in emitTrailingFence");
13871 }
13872 
13873 // Loads and stores less than 64-bits are already atomic; ones above that
13874 // are doomed anyway, so defer to the default libcall and blame the OS when
13875 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
13876 // anything for those.
13877 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
13878   unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
13879   return (Size == 64) && !Subtarget->isMClass();
13880 }
13881 
13882 // Loads and stores less than 64-bits are already atomic; ones above that
13883 // are doomed anyway, so defer to the default libcall and blame the OS when
13884 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
13885 // anything for those.
13886 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that
13887 // guarantee, see DDI0406C ARM architecture reference manual,
13888 // sections A8.8.72-74 LDRD)
13889 TargetLowering::AtomicExpansionKind
13890 ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
13891   unsigned Size = LI->getType()->getPrimitiveSizeInBits();
13892   return ((Size == 64) && !Subtarget->isMClass()) ? AtomicExpansionKind::LLOnly
13893                                                   : AtomicExpansionKind::None;
13894 }
13895 
13896 // For the real atomic operations, we have ldrex/strex up to 32 bits,
13897 // and up to 64 bits on the non-M profiles
13898 TargetLowering::AtomicExpansionKind
13899 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
13900   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
13901   bool hasAtomicRMW = !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps();
13902   return (Size <= (Subtarget->isMClass() ? 32U : 64U) && hasAtomicRMW)
13903              ? AtomicExpansionKind::LLSC
13904              : AtomicExpansionKind::None;
13905 }
13906 
13907 bool ARMTargetLowering::shouldExpandAtomicCmpXchgInIR(
13908     AtomicCmpXchgInst *AI) const {
13909   // At -O0, fast-regalloc cannot cope with the live vregs necessary to
13910   // implement cmpxchg without spilling. If the address being exchanged is also
13911   // on the stack and close enough to the spill slot, this can lead to a
13912   // situation where the monitor always gets cleared and the atomic operation
13913   // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead.
13914   bool hasAtomicCmpXchg =
13915       !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps();
13916   return getTargetMachine().getOptLevel() != 0 && hasAtomicCmpXchg;
13917 }
13918 
13919 bool ARMTargetLowering::shouldInsertFencesForAtomic(
13920     const Instruction *I) const {
13921   return InsertFencesForAtomic;
13922 }
13923 
13924 // This has so far only been implemented for MachO.
13925 bool ARMTargetLowering::useLoadStackGuardNode() const {
13926   return Subtarget->isTargetMachO();
13927 }
13928 
13929 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
13930                                                   unsigned &Cost) const {
13931   // If we do not have NEON, vector types are not natively supported.
13932   if (!Subtarget->hasNEON())
13933     return false;
13934 
13935   // Floating point values and vector values map to the same register file.
13936   // Therefore, although we could do a store extract of a vector type, this is
13937   // better to leave at float as we have more freedom in the addressing mode for
13938   // those.
13939   if (VectorTy->isFPOrFPVectorTy())
13940     return false;
13941 
13942   // If the index is unknown at compile time, this is very expensive to lower
13943   // and it is not possible to combine the store with the extract.
13944   if (!isa<ConstantInt>(Idx))
13945     return false;
13946 
13947   assert(VectorTy->isVectorTy() && "VectorTy is not a vector type");
13948   unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth();
13949   // We can do a store + vector extract on any vector that fits perfectly in a D
13950   // or Q register.
13951   if (BitWidth == 64 || BitWidth == 128) {
13952     Cost = 0;
13953     return true;
13954   }
13955   return false;
13956 }
13957 
13958 bool ARMTargetLowering::isCheapToSpeculateCttz() const {
13959   return Subtarget->hasV6T2Ops();
13960 }
13961 
13962 bool ARMTargetLowering::isCheapToSpeculateCtlz() const {
13963   return Subtarget->hasV6T2Ops();
13964 }
13965 
13966 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
13967                                          AtomicOrdering Ord) const {
13968   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
13969   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
13970   bool IsAcquire = isAcquireOrStronger(Ord);
13971 
13972   // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
13973   // intrinsic must return {i32, i32} and we have to recombine them into a
13974   // single i64 here.
13975   if (ValTy->getPrimitiveSizeInBits() == 64) {
13976     Intrinsic::ID Int =
13977         IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
13978     Function *Ldrex = Intrinsic::getDeclaration(M, Int);
13979 
13980     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
13981     Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
13982 
13983     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
13984     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
13985     if (!Subtarget->isLittle())
13986       std::swap (Lo, Hi);
13987     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
13988     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
13989     return Builder.CreateOr(
13990         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
13991   }
13992 
13993   Type *Tys[] = { Addr->getType() };
13994   Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
13995   Function *Ldrex = Intrinsic::getDeclaration(M, Int, Tys);
13996 
13997   return Builder.CreateTruncOrBitCast(
13998       Builder.CreateCall(Ldrex, Addr),
13999       cast<PointerType>(Addr->getType())->getElementType());
14000 }
14001 
14002 void ARMTargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
14003     IRBuilder<> &Builder) const {
14004   if (!Subtarget->hasV7Ops())
14005     return;
14006   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
14007   Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::arm_clrex));
14008 }
14009 
14010 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
14011                                                Value *Addr,
14012                                                AtomicOrdering Ord) const {
14013   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
14014   bool IsRelease = isReleaseOrStronger(Ord);
14015 
14016   // Since the intrinsics must have legal type, the i64 intrinsics take two
14017   // parameters: "i32, i32". We must marshal Val into the appropriate form
14018   // before the call.
14019   if (Val->getType()->getPrimitiveSizeInBits() == 64) {
14020     Intrinsic::ID Int =
14021         IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
14022     Function *Strex = Intrinsic::getDeclaration(M, Int);
14023     Type *Int32Ty = Type::getInt32Ty(M->getContext());
14024 
14025     Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
14026     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
14027     if (!Subtarget->isLittle())
14028       std::swap(Lo, Hi);
14029     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
14030     return Builder.CreateCall(Strex, {Lo, Hi, Addr});
14031   }
14032 
14033   Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
14034   Type *Tys[] = { Addr->getType() };
14035   Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
14036 
14037   return Builder.CreateCall(
14038       Strex, {Builder.CreateZExtOrBitCast(
14039                   Val, Strex->getFunctionType()->getParamType(0)),
14040               Addr});
14041 }
14042 
14043 /// A helper function for determining the number of interleaved accesses we
14044 /// will generate when lowering accesses of the given type.
14045 unsigned
14046 ARMTargetLowering::getNumInterleavedAccesses(VectorType *VecTy,
14047                                              const DataLayout &DL) const {
14048   return (DL.getTypeSizeInBits(VecTy) + 127) / 128;
14049 }
14050 
14051 bool ARMTargetLowering::isLegalInterleavedAccessType(
14052     VectorType *VecTy, const DataLayout &DL) const {
14053 
14054   unsigned VecSize = DL.getTypeSizeInBits(VecTy);
14055   unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType());
14056 
14057   // Ensure the vector doesn't have f16 elements. Even though we could do an
14058   // i16 vldN, we can't hold the f16 vectors and will end up converting via
14059   // f32.
14060   if (VecTy->getElementType()->isHalfTy())
14061     return false;
14062 
14063   // Ensure the number of vector elements is greater than 1.
14064   if (VecTy->getNumElements() < 2)
14065     return false;
14066 
14067   // Ensure the element type is legal.
14068   if (ElSize != 8 && ElSize != 16 && ElSize != 32)
14069     return false;
14070 
14071   // Ensure the total vector size is 64 or a multiple of 128. Types larger than
14072   // 128 will be split into multiple interleaved accesses.
14073   return VecSize == 64 || VecSize % 128 == 0;
14074 }
14075 
14076 /// \brief Lower an interleaved load into a vldN intrinsic.
14077 ///
14078 /// E.g. Lower an interleaved load (Factor = 2):
14079 ///        %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4
14080 ///        %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6>  ; Extract even elements
14081 ///        %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7>  ; Extract odd elements
14082 ///
14083 ///      Into:
14084 ///        %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4)
14085 ///        %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0
14086 ///        %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1
14087 bool ARMTargetLowering::lowerInterleavedLoad(
14088     LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
14089     ArrayRef<unsigned> Indices, unsigned Factor) const {
14090   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
14091          "Invalid interleave factor");
14092   assert(!Shuffles.empty() && "Empty shufflevector input");
14093   assert(Shuffles.size() == Indices.size() &&
14094          "Unmatched number of shufflevectors and indices");
14095 
14096   VectorType *VecTy = Shuffles[0]->getType();
14097   Type *EltTy = VecTy->getVectorElementType();
14098 
14099   const DataLayout &DL = LI->getModule()->getDataLayout();
14100 
14101   // Skip if we do not have NEON and skip illegal vector types. We can
14102   // "legalize" wide vector types into multiple interleaved accesses as long as
14103   // the vector types are divisible by 128.
14104   if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(VecTy, DL))
14105     return false;
14106 
14107   unsigned NumLoads = getNumInterleavedAccesses(VecTy, DL);
14108 
14109   // A pointer vector can not be the return type of the ldN intrinsics. Need to
14110   // load integer vectors first and then convert to pointer vectors.
14111   if (EltTy->isPointerTy())
14112     VecTy =
14113         VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
14114 
14115   IRBuilder<> Builder(LI);
14116 
14117   // The base address of the load.
14118   Value *BaseAddr = LI->getPointerOperand();
14119 
14120   if (NumLoads > 1) {
14121     // If we're going to generate more than one load, reset the sub-vector type
14122     // to something legal.
14123     VecTy = VectorType::get(VecTy->getVectorElementType(),
14124                             VecTy->getVectorNumElements() / NumLoads);
14125 
14126     // We will compute the pointer operand of each load from the original base
14127     // address using GEPs. Cast the base address to a pointer to the scalar
14128     // element type.
14129     BaseAddr = Builder.CreateBitCast(
14130         BaseAddr, VecTy->getVectorElementType()->getPointerTo(
14131                       LI->getPointerAddressSpace()));
14132   }
14133 
14134   assert(isTypeLegal(EVT::getEVT(VecTy)) && "Illegal vldN vector type!");
14135 
14136   Type *Int8Ptr = Builder.getInt8PtrTy(LI->getPointerAddressSpace());
14137   Type *Tys[] = {VecTy, Int8Ptr};
14138   static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2,
14139                                             Intrinsic::arm_neon_vld3,
14140                                             Intrinsic::arm_neon_vld4};
14141   Function *VldnFunc =
14142       Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
14143 
14144   // Holds sub-vectors extracted from the load intrinsic return values. The
14145   // sub-vectors are associated with the shufflevector instructions they will
14146   // replace.
14147   DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs;
14148 
14149   for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) {
14150     // If we're generating more than one load, compute the base address of
14151     // subsequent loads as an offset from the previous.
14152     if (LoadCount > 0)
14153       BaseAddr = Builder.CreateConstGEP1_32(
14154           BaseAddr, VecTy->getVectorNumElements() * Factor);
14155 
14156     SmallVector<Value *, 2> Ops;
14157     Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr));
14158     Ops.push_back(Builder.getInt32(LI->getAlignment()));
14159 
14160     CallInst *VldN = Builder.CreateCall(VldnFunc, Ops, "vldN");
14161 
14162     // Replace uses of each shufflevector with the corresponding vector loaded
14163     // by ldN.
14164     for (unsigned i = 0; i < Shuffles.size(); i++) {
14165       ShuffleVectorInst *SV = Shuffles[i];
14166       unsigned Index = Indices[i];
14167 
14168       Value *SubVec = Builder.CreateExtractValue(VldN, Index);
14169 
14170       // Convert the integer vector to pointer vector if the element is pointer.
14171       if (EltTy->isPointerTy())
14172         SubVec = Builder.CreateIntToPtr(
14173             SubVec, VectorType::get(SV->getType()->getVectorElementType(),
14174                                     VecTy->getVectorNumElements()));
14175 
14176       SubVecs[SV].push_back(SubVec);
14177     }
14178   }
14179 
14180   // Replace uses of the shufflevector instructions with the sub-vectors
14181   // returned by the load intrinsic. If a shufflevector instruction is
14182   // associated with more than one sub-vector, those sub-vectors will be
14183   // concatenated into a single wide vector.
14184   for (ShuffleVectorInst *SVI : Shuffles) {
14185     auto &SubVec = SubVecs[SVI];
14186     auto *WideVec =
14187         SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0];
14188     SVI->replaceAllUsesWith(WideVec);
14189   }
14190 
14191   return true;
14192 }
14193 
14194 /// \brief Lower an interleaved store into a vstN intrinsic.
14195 ///
14196 /// E.g. Lower an interleaved store (Factor = 3):
14197 ///        %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
14198 ///                                  <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
14199 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4
14200 ///
14201 ///      Into:
14202 ///        %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
14203 ///        %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
14204 ///        %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
14205 ///        call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
14206 ///
14207 /// Note that the new shufflevectors will be removed and we'll only generate one
14208 /// vst3 instruction in CodeGen.
14209 ///
14210 /// Example for a more general valid mask (Factor 3). Lower:
14211 ///        %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1,
14212 ///                 <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19>
14213 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr
14214 ///
14215 ///      Into:
14216 ///        %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7>
14217 ///        %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35>
14218 ///        %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19>
14219 ///        call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
14220 bool ARMTargetLowering::lowerInterleavedStore(StoreInst *SI,
14221                                               ShuffleVectorInst *SVI,
14222                                               unsigned Factor) const {
14223   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
14224          "Invalid interleave factor");
14225 
14226   VectorType *VecTy = SVI->getType();
14227   assert(VecTy->getVectorNumElements() % Factor == 0 &&
14228          "Invalid interleaved store");
14229 
14230   unsigned LaneLen = VecTy->getVectorNumElements() / Factor;
14231   Type *EltTy = VecTy->getVectorElementType();
14232   VectorType *SubVecTy = VectorType::get(EltTy, LaneLen);
14233 
14234   const DataLayout &DL = SI->getModule()->getDataLayout();
14235 
14236   // Skip if we do not have NEON and skip illegal vector types. We can
14237   // "legalize" wide vector types into multiple interleaved accesses as long as
14238   // the vector types are divisible by 128.
14239   if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(SubVecTy, DL))
14240     return false;
14241 
14242   unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL);
14243 
14244   Value *Op0 = SVI->getOperand(0);
14245   Value *Op1 = SVI->getOperand(1);
14246   IRBuilder<> Builder(SI);
14247 
14248   // StN intrinsics don't support pointer vectors as arguments. Convert pointer
14249   // vectors to integer vectors.
14250   if (EltTy->isPointerTy()) {
14251     Type *IntTy = DL.getIntPtrType(EltTy);
14252 
14253     // Convert to the corresponding integer vector.
14254     Type *IntVecTy =
14255         VectorType::get(IntTy, Op0->getType()->getVectorNumElements());
14256     Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
14257     Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
14258 
14259     SubVecTy = VectorType::get(IntTy, LaneLen);
14260   }
14261 
14262   // The base address of the store.
14263   Value *BaseAddr = SI->getPointerOperand();
14264 
14265   if (NumStores > 1) {
14266     // If we're going to generate more than one store, reset the lane length
14267     // and sub-vector type to something legal.
14268     LaneLen /= NumStores;
14269     SubVecTy = VectorType::get(SubVecTy->getVectorElementType(), LaneLen);
14270 
14271     // We will compute the pointer operand of each store from the original base
14272     // address using GEPs. Cast the base address to a pointer to the scalar
14273     // element type.
14274     BaseAddr = Builder.CreateBitCast(
14275         BaseAddr, SubVecTy->getVectorElementType()->getPointerTo(
14276                       SI->getPointerAddressSpace()));
14277   }
14278 
14279   assert(isTypeLegal(EVT::getEVT(SubVecTy)) && "Illegal vstN vector type!");
14280 
14281   auto Mask = SVI->getShuffleMask();
14282 
14283   Type *Int8Ptr = Builder.getInt8PtrTy(SI->getPointerAddressSpace());
14284   Type *Tys[] = {Int8Ptr, SubVecTy};
14285   static const Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2,
14286                                              Intrinsic::arm_neon_vst3,
14287                                              Intrinsic::arm_neon_vst4};
14288 
14289   for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) {
14290     // If we generating more than one store, we compute the base address of
14291     // subsequent stores as an offset from the previous.
14292     if (StoreCount > 0)
14293       BaseAddr = Builder.CreateConstGEP1_32(BaseAddr, LaneLen * Factor);
14294 
14295     SmallVector<Value *, 6> Ops;
14296     Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr));
14297 
14298     Function *VstNFunc =
14299         Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys);
14300 
14301     // Split the shufflevector operands into sub vectors for the new vstN call.
14302     for (unsigned i = 0; i < Factor; i++) {
14303       unsigned IdxI = StoreCount * LaneLen * Factor + i;
14304       if (Mask[IdxI] >= 0) {
14305         Ops.push_back(Builder.CreateShuffleVector(
14306             Op0, Op1, createSequentialMask(Builder, Mask[IdxI], LaneLen, 0)));
14307       } else {
14308         unsigned StartMask = 0;
14309         for (unsigned j = 1; j < LaneLen; j++) {
14310           unsigned IdxJ = StoreCount * LaneLen * Factor + j;
14311           if (Mask[IdxJ * Factor + IdxI] >= 0) {
14312             StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ;
14313             break;
14314           }
14315         }
14316         // Note: If all elements in a chunk are undefs, StartMask=0!
14317         // Note: Filling undef gaps with random elements is ok, since
14318         // those elements were being written anyway (with undefs).
14319         // In the case of all undefs we're defaulting to using elems from 0
14320         // Note: StartMask cannot be negative, it's checked in
14321         // isReInterleaveMask
14322         Ops.push_back(Builder.CreateShuffleVector(
14323             Op0, Op1, createSequentialMask(Builder, StartMask, LaneLen, 0)));
14324       }
14325     }
14326 
14327     Ops.push_back(Builder.getInt32(SI->getAlignment()));
14328     Builder.CreateCall(VstNFunc, Ops);
14329   }
14330   return true;
14331 }
14332 
14333 enum HABaseType {
14334   HA_UNKNOWN = 0,
14335   HA_FLOAT,
14336   HA_DOUBLE,
14337   HA_VECT64,
14338   HA_VECT128
14339 };
14340 
14341 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
14342                                    uint64_t &Members) {
14343   if (auto *ST = dyn_cast<StructType>(Ty)) {
14344     for (unsigned i = 0; i < ST->getNumElements(); ++i) {
14345       uint64_t SubMembers = 0;
14346       if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
14347         return false;
14348       Members += SubMembers;
14349     }
14350   } else if (auto *AT = dyn_cast<ArrayType>(Ty)) {
14351     uint64_t SubMembers = 0;
14352     if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
14353       return false;
14354     Members += SubMembers * AT->getNumElements();
14355   } else if (Ty->isFloatTy()) {
14356     if (Base != HA_UNKNOWN && Base != HA_FLOAT)
14357       return false;
14358     Members = 1;
14359     Base = HA_FLOAT;
14360   } else if (Ty->isDoubleTy()) {
14361     if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
14362       return false;
14363     Members = 1;
14364     Base = HA_DOUBLE;
14365   } else if (auto *VT = dyn_cast<VectorType>(Ty)) {
14366     Members = 1;
14367     switch (Base) {
14368     case HA_FLOAT:
14369     case HA_DOUBLE:
14370       return false;
14371     case HA_VECT64:
14372       return VT->getBitWidth() == 64;
14373     case HA_VECT128:
14374       return VT->getBitWidth() == 128;
14375     case HA_UNKNOWN:
14376       switch (VT->getBitWidth()) {
14377       case 64:
14378         Base = HA_VECT64;
14379         return true;
14380       case 128:
14381         Base = HA_VECT128;
14382         return true;
14383       default:
14384         return false;
14385       }
14386     }
14387   }
14388 
14389   return (Members > 0 && Members <= 4);
14390 }
14391 
14392 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate or one of
14393 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when
14394 /// passing according to AAPCS rules.
14395 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
14396     Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
14397   if (getEffectiveCallingConv(CallConv, isVarArg) !=
14398       CallingConv::ARM_AAPCS_VFP)
14399     return false;
14400 
14401   HABaseType Base = HA_UNKNOWN;
14402   uint64_t Members = 0;
14403   bool IsHA = isHomogeneousAggregate(Ty, Base, Members);
14404   DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump());
14405 
14406   bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy();
14407   return IsHA || IsIntArray;
14408 }
14409 
14410 unsigned ARMTargetLowering::getExceptionPointerRegister(
14411     const Constant *PersonalityFn) const {
14412   // Platforms which do not use SjLj EH may return values in these registers
14413   // via the personality function.
14414   return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R0;
14415 }
14416 
14417 unsigned ARMTargetLowering::getExceptionSelectorRegister(
14418     const Constant *PersonalityFn) const {
14419   // Platforms which do not use SjLj EH may return values in these registers
14420   // via the personality function.
14421   return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R1;
14422 }
14423 
14424 void ARMTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
14425   // Update IsSplitCSR in ARMFunctionInfo.
14426   ARMFunctionInfo *AFI = Entry->getParent()->getInfo<ARMFunctionInfo>();
14427   AFI->setIsSplitCSR(true);
14428 }
14429 
14430 void ARMTargetLowering::insertCopiesSplitCSR(
14431     MachineBasicBlock *Entry,
14432     const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
14433   const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
14434   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
14435   if (!IStart)
14436     return;
14437 
14438   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
14439   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
14440   MachineBasicBlock::iterator MBBI = Entry->begin();
14441   for (const MCPhysReg *I = IStart; *I; ++I) {
14442     const TargetRegisterClass *RC = nullptr;
14443     if (ARM::GPRRegClass.contains(*I))
14444       RC = &ARM::GPRRegClass;
14445     else if (ARM::DPRRegClass.contains(*I))
14446       RC = &ARM::DPRRegClass;
14447     else
14448       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
14449 
14450     unsigned NewVR = MRI->createVirtualRegister(RC);
14451     // Create copy from CSR to a virtual register.
14452     // FIXME: this currently does not emit CFI pseudo-instructions, it works
14453     // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
14454     // nounwind. If we want to generalize this later, we may need to emit
14455     // CFI pseudo-instructions.
14456     assert(Entry->getParent()->getFunction().hasFnAttribute(
14457                Attribute::NoUnwind) &&
14458            "Function should be nounwind in insertCopiesSplitCSR!");
14459     Entry->addLiveIn(*I);
14460     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
14461         .addReg(*I);
14462 
14463     // Insert the copy-back instructions right before the terminator.
14464     for (auto *Exit : Exits)
14465       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
14466               TII->get(TargetOpcode::COPY), *I)
14467           .addReg(NewVR);
14468   }
14469 }
14470 
14471 void ARMTargetLowering::finalizeLowering(MachineFunction &MF) const {
14472   MF.getFrameInfo().computeMaxCallFrameSize(MF);
14473   TargetLoweringBase::finalizeLowering(MF);
14474 }
14475