xref: /freebsd/contrib/llvm-project/llvm/lib/Target/ARM/ARMISelLowering.cpp (revision e64bea71c21eb42e97aa615188ba91f6cce0d36d)
1 //===- ARMISelLowering.cpp - ARM DAG Lowering Implementation --------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file defines the interfaces that ARM uses to lower LLVM code into a
10 // selection DAG.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "ARMISelLowering.h"
15 #include "ARMBaseInstrInfo.h"
16 #include "ARMBaseRegisterInfo.h"
17 #include "ARMCallingConv.h"
18 #include "ARMConstantPoolValue.h"
19 #include "ARMMachineFunctionInfo.h"
20 #include "ARMPerfectShuffle.h"
21 #include "ARMRegisterInfo.h"
22 #include "ARMSelectionDAGInfo.h"
23 #include "ARMSubtarget.h"
24 #include "ARMTargetTransformInfo.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/Twine.h"
41 #include "llvm/Analysis/VectorUtils.h"
42 #include "llvm/CodeGen/CallingConvLower.h"
43 #include "llvm/CodeGen/ComplexDeinterleavingPass.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/RuntimeLibcallUtil.h"
57 #include "llvm/CodeGen/SelectionDAG.h"
58 #include "llvm/CodeGen/SelectionDAGAddressAnalysis.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/CodeGenTypes/MachineValueType.h"
67 #include "llvm/IR/Attributes.h"
68 #include "llvm/IR/CallingConv.h"
69 #include "llvm/IR/Constant.h"
70 #include "llvm/IR/Constants.h"
71 #include "llvm/IR/DataLayout.h"
72 #include "llvm/IR/DebugLoc.h"
73 #include "llvm/IR/DerivedTypes.h"
74 #include "llvm/IR/Function.h"
75 #include "llvm/IR/GlobalAlias.h"
76 #include "llvm/IR/GlobalValue.h"
77 #include "llvm/IR/GlobalVariable.h"
78 #include "llvm/IR/IRBuilder.h"
79 #include "llvm/IR/InlineAsm.h"
80 #include "llvm/IR/Instruction.h"
81 #include "llvm/IR/Instructions.h"
82 #include "llvm/IR/IntrinsicInst.h"
83 #include "llvm/IR/Intrinsics.h"
84 #include "llvm/IR/IntrinsicsARM.h"
85 #include "llvm/IR/Module.h"
86 #include "llvm/IR/Type.h"
87 #include "llvm/IR/User.h"
88 #include "llvm/IR/Value.h"
89 #include "llvm/MC/MCInstrDesc.h"
90 #include "llvm/MC/MCInstrItineraries.h"
91 #include "llvm/MC/MCSchedule.h"
92 #include "llvm/Support/AtomicOrdering.h"
93 #include "llvm/Support/BranchProbability.h"
94 #include "llvm/Support/Casting.h"
95 #include "llvm/Support/CodeGen.h"
96 #include "llvm/Support/CommandLine.h"
97 #include "llvm/Support/Compiler.h"
98 #include "llvm/Support/Debug.h"
99 #include "llvm/Support/ErrorHandling.h"
100 #include "llvm/Support/KnownBits.h"
101 #include "llvm/Support/MathExtras.h"
102 #include "llvm/Support/raw_ostream.h"
103 #include "llvm/Target/TargetMachine.h"
104 #include "llvm/Target/TargetOptions.h"
105 #include "llvm/TargetParser/Triple.h"
106 #include <algorithm>
107 #include <cassert>
108 #include <cstdint>
109 #include <cstdlib>
110 #include <iterator>
111 #include <limits>
112 #include <optional>
113 #include <tuple>
114 #include <utility>
115 #include <vector>
116 
117 using namespace llvm;
118 
119 #define DEBUG_TYPE "arm-isel"
120 
121 STATISTIC(NumTailCalls, "Number of tail calls");
122 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt");
123 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments");
124 STATISTIC(NumConstpoolPromoted,
125   "Number of constants with their storage promoted into constant pools");
126 
127 static cl::opt<bool>
128 ARMInterworking("arm-interworking", cl::Hidden,
129   cl::desc("Enable / disable ARM interworking (for debugging only)"),
130   cl::init(true));
131 
132 static cl::opt<bool> EnableConstpoolPromotion(
133     "arm-promote-constant", cl::Hidden,
134     cl::desc("Enable / disable promotion of unnamed_addr constants into "
135              "constant pools"),
136     cl::init(false)); // FIXME: set to true by default once PR32780 is fixed
137 static cl::opt<unsigned> ConstpoolPromotionMaxSize(
138     "arm-promote-constant-max-size", cl::Hidden,
139     cl::desc("Maximum size of constant to promote into a constant pool"),
140     cl::init(64));
141 static cl::opt<unsigned> ConstpoolPromotionMaxTotal(
142     "arm-promote-constant-max-total", cl::Hidden,
143     cl::desc("Maximum size of ALL constants to promote into a constant pool"),
144     cl::init(128));
145 
146 cl::opt<unsigned>
147 MVEMaxSupportedInterleaveFactor("mve-max-interleave-factor", cl::Hidden,
148   cl::desc("Maximum interleave factor for MVE VLDn to generate."),
149   cl::init(2));
150 
151 cl::opt<unsigned> ArmMaxBaseUpdatesToCheck(
152     "arm-max-base-updates-to-check", cl::Hidden,
153     cl::desc("Maximum number of base-updates to check generating postindex."),
154     cl::init(64));
155 
156 /// Value type used for "flags" operands / results (either CPSR or FPSCR_NZCV).
157 constexpr MVT FlagsVT = MVT::i32;
158 
159 // The APCS parameter registers.
160 static const MCPhysReg GPRArgRegs[] = {
161   ARM::R0, ARM::R1, ARM::R2, ARM::R3
162 };
163 
handleCMSEValue(const SDValue & Value,const ISD::InputArg & Arg,SelectionDAG & DAG,const SDLoc & DL)164 static SDValue handleCMSEValue(const SDValue &Value, const ISD::InputArg &Arg,
165                                SelectionDAG &DAG, const SDLoc &DL) {
166   assert(Arg.ArgVT.isScalarInteger());
167   assert(Arg.ArgVT.bitsLT(MVT::i32));
168   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, Arg.ArgVT, Value);
169   SDValue Ext =
170       DAG.getNode(Arg.Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, DL,
171                   MVT::i32, Trunc);
172   return Ext;
173 }
174 
addTypeForNEON(MVT VT,MVT PromotedLdStVT)175 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT) {
176   if (VT != PromotedLdStVT) {
177     setOperationAction(ISD::LOAD, VT, Promote);
178     AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT);
179 
180     setOperationAction(ISD::STORE, VT, Promote);
181     AddPromotedToType (ISD::STORE, VT, PromotedLdStVT);
182   }
183 
184   MVT ElemTy = VT.getVectorElementType();
185   if (ElemTy != MVT::f64)
186     setOperationAction(ISD::SETCC, VT, Custom);
187   setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
188   setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
189   if (ElemTy == MVT::i32) {
190     setOperationAction(ISD::SINT_TO_FP, VT, Custom);
191     setOperationAction(ISD::UINT_TO_FP, VT, Custom);
192     setOperationAction(ISD::FP_TO_SINT, VT, Custom);
193     setOperationAction(ISD::FP_TO_UINT, VT, Custom);
194   } else {
195     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
196     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
197     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
198     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
199   }
200   setOperationAction(ISD::BUILD_VECTOR,      VT, Custom);
201   setOperationAction(ISD::VECTOR_SHUFFLE,    VT, Custom);
202   setOperationAction(ISD::CONCAT_VECTORS,    VT, Legal);
203   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
204   setOperationAction(ISD::SELECT,            VT, Expand);
205   setOperationAction(ISD::SELECT_CC,         VT, Expand);
206   setOperationAction(ISD::VSELECT,           VT, Expand);
207   setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
208   if (VT.isInteger()) {
209     setOperationAction(ISD::SHL, VT, Custom);
210     setOperationAction(ISD::SRA, VT, Custom);
211     setOperationAction(ISD::SRL, VT, Custom);
212   }
213 
214   // Neon does not support vector divide/remainder operations.
215   setOperationAction(ISD::SDIV, VT, Expand);
216   setOperationAction(ISD::UDIV, VT, Expand);
217   setOperationAction(ISD::FDIV, VT, Expand);
218   setOperationAction(ISD::SREM, VT, Expand);
219   setOperationAction(ISD::UREM, VT, Expand);
220   setOperationAction(ISD::FREM, VT, Expand);
221   setOperationAction(ISD::SDIVREM, VT, Expand);
222   setOperationAction(ISD::UDIVREM, VT, Expand);
223 
224   if (!VT.isFloatingPoint() && VT != MVT::v2i64 && VT != MVT::v1i64)
225     for (auto Opcode : {ISD::ABS, ISD::ABDS, ISD::ABDU, ISD::SMIN, ISD::SMAX,
226                         ISD::UMIN, ISD::UMAX})
227       setOperationAction(Opcode, VT, Legal);
228   if (!VT.isFloatingPoint())
229     for (auto Opcode : {ISD::SADDSAT, ISD::UADDSAT, ISD::SSUBSAT, ISD::USUBSAT})
230       setOperationAction(Opcode, VT, Legal);
231 }
232 
addDRTypeForNEON(MVT VT)233 void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
234   addRegisterClass(VT, &ARM::DPRRegClass);
235   addTypeForNEON(VT, MVT::f64);
236 }
237 
addQRTypeForNEON(MVT VT)238 void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
239   addRegisterClass(VT, &ARM::DPairRegClass);
240   addTypeForNEON(VT, MVT::v2f64);
241 }
242 
setAllExpand(MVT VT)243 void ARMTargetLowering::setAllExpand(MVT VT) {
244   for (unsigned Opc = 0; Opc < ISD::BUILTIN_OP_END; ++Opc)
245     setOperationAction(Opc, VT, Expand);
246 
247   // We support these really simple operations even on types where all
248   // the actual arithmetic has to be broken down into simpler
249   // operations or turned into library calls.
250   setOperationAction(ISD::BITCAST, VT, Legal);
251   setOperationAction(ISD::LOAD, VT, Legal);
252   setOperationAction(ISD::STORE, VT, Legal);
253   setOperationAction(ISD::UNDEF, VT, Legal);
254 }
255 
addAllExtLoads(const MVT From,const MVT To,LegalizeAction Action)256 void ARMTargetLowering::addAllExtLoads(const MVT From, const MVT To,
257                                        LegalizeAction Action) {
258   setLoadExtAction(ISD::EXTLOAD,  From, To, Action);
259   setLoadExtAction(ISD::ZEXTLOAD, From, To, Action);
260   setLoadExtAction(ISD::SEXTLOAD, From, To, Action);
261 }
262 
addMVEVectorTypes(bool HasMVEFP)263 void ARMTargetLowering::addMVEVectorTypes(bool HasMVEFP) {
264   const MVT IntTypes[] = { MVT::v16i8, MVT::v8i16, MVT::v4i32 };
265 
266   for (auto VT : IntTypes) {
267     addRegisterClass(VT, &ARM::MQPRRegClass);
268     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
269     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
270     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
271     setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
272     setOperationAction(ISD::SHL, VT, Custom);
273     setOperationAction(ISD::SRA, VT, Custom);
274     setOperationAction(ISD::SRL, VT, Custom);
275     setOperationAction(ISD::SMIN, VT, Legal);
276     setOperationAction(ISD::SMAX, VT, Legal);
277     setOperationAction(ISD::UMIN, VT, Legal);
278     setOperationAction(ISD::UMAX, VT, Legal);
279     setOperationAction(ISD::ABS, VT, Legal);
280     setOperationAction(ISD::SETCC, VT, Custom);
281     setOperationAction(ISD::MLOAD, VT, Custom);
282     setOperationAction(ISD::MSTORE, VT, Legal);
283     setOperationAction(ISD::CTLZ, VT, Legal);
284     setOperationAction(ISD::CTTZ, VT, Custom);
285     setOperationAction(ISD::BITREVERSE, VT, Legal);
286     setOperationAction(ISD::BSWAP, VT, Legal);
287     setOperationAction(ISD::SADDSAT, VT, Legal);
288     setOperationAction(ISD::UADDSAT, VT, Legal);
289     setOperationAction(ISD::SSUBSAT, VT, Legal);
290     setOperationAction(ISD::USUBSAT, VT, Legal);
291     setOperationAction(ISD::ABDS, VT, Legal);
292     setOperationAction(ISD::ABDU, VT, Legal);
293     setOperationAction(ISD::AVGFLOORS, VT, Legal);
294     setOperationAction(ISD::AVGFLOORU, VT, Legal);
295     setOperationAction(ISD::AVGCEILS, VT, Legal);
296     setOperationAction(ISD::AVGCEILU, VT, Legal);
297 
298     // No native support for these.
299     setOperationAction(ISD::UDIV, VT, Expand);
300     setOperationAction(ISD::SDIV, VT, Expand);
301     setOperationAction(ISD::UREM, VT, Expand);
302     setOperationAction(ISD::SREM, VT, Expand);
303     setOperationAction(ISD::UDIVREM, VT, Expand);
304     setOperationAction(ISD::SDIVREM, VT, Expand);
305     setOperationAction(ISD::CTPOP, VT, Expand);
306     setOperationAction(ISD::SELECT, VT, Expand);
307     setOperationAction(ISD::SELECT_CC, VT, Expand);
308 
309     // Vector reductions
310     setOperationAction(ISD::VECREDUCE_ADD, VT, Legal);
311     setOperationAction(ISD::VECREDUCE_SMAX, VT, Legal);
312     setOperationAction(ISD::VECREDUCE_UMAX, VT, Legal);
313     setOperationAction(ISD::VECREDUCE_SMIN, VT, Legal);
314     setOperationAction(ISD::VECREDUCE_UMIN, VT, Legal);
315     setOperationAction(ISD::VECREDUCE_MUL, VT, Custom);
316     setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
317     setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
318     setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
319 
320     if (!HasMVEFP) {
321       setOperationAction(ISD::SINT_TO_FP, VT, Expand);
322       setOperationAction(ISD::UINT_TO_FP, VT, Expand);
323       setOperationAction(ISD::FP_TO_SINT, VT, Expand);
324       setOperationAction(ISD::FP_TO_UINT, VT, Expand);
325     } else {
326       setOperationAction(ISD::FP_TO_SINT_SAT, VT, Custom);
327       setOperationAction(ISD::FP_TO_UINT_SAT, VT, Custom);
328     }
329 
330     // Pre and Post inc are supported on loads and stores
331     for (unsigned im = (unsigned)ISD::PRE_INC;
332          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
333       setIndexedLoadAction(im, VT, Legal);
334       setIndexedStoreAction(im, VT, Legal);
335       setIndexedMaskedLoadAction(im, VT, Legal);
336       setIndexedMaskedStoreAction(im, VT, Legal);
337     }
338   }
339 
340   const MVT FloatTypes[] = { MVT::v8f16, MVT::v4f32 };
341   for (auto VT : FloatTypes) {
342     addRegisterClass(VT, &ARM::MQPRRegClass);
343     if (!HasMVEFP)
344       setAllExpand(VT);
345 
346     // These are legal or custom whether we have MVE.fp or not
347     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
348     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
349     setOperationAction(ISD::INSERT_VECTOR_ELT, VT.getVectorElementType(), Custom);
350     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
351     setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
352     setOperationAction(ISD::BUILD_VECTOR, VT.getVectorElementType(), Custom);
353     setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Legal);
354     setOperationAction(ISD::SETCC, VT, Custom);
355     setOperationAction(ISD::MLOAD, VT, Custom);
356     setOperationAction(ISD::MSTORE, VT, Legal);
357     setOperationAction(ISD::SELECT, VT, Expand);
358     setOperationAction(ISD::SELECT_CC, VT, Expand);
359 
360     // Pre and Post inc are supported on loads and stores
361     for (unsigned im = (unsigned)ISD::PRE_INC;
362          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
363       setIndexedLoadAction(im, VT, Legal);
364       setIndexedStoreAction(im, VT, Legal);
365       setIndexedMaskedLoadAction(im, VT, Legal);
366       setIndexedMaskedStoreAction(im, VT, Legal);
367     }
368 
369     if (HasMVEFP) {
370       setOperationAction(ISD::FMINNUM, VT, Legal);
371       setOperationAction(ISD::FMAXNUM, VT, Legal);
372       setOperationAction(ISD::FROUND, VT, Legal);
373       setOperationAction(ISD::FROUNDEVEN, VT, Legal);
374       setOperationAction(ISD::FRINT, VT, Legal);
375       setOperationAction(ISD::FTRUNC, VT, Legal);
376       setOperationAction(ISD::FFLOOR, VT, Legal);
377       setOperationAction(ISD::FCEIL, VT, Legal);
378       setOperationAction(ISD::VECREDUCE_FADD, VT, Custom);
379       setOperationAction(ISD::VECREDUCE_FMUL, VT, Custom);
380       setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
381       setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
382 
383       // No native support for these.
384       setOperationAction(ISD::FDIV, VT, Expand);
385       setOperationAction(ISD::FREM, VT, Expand);
386       setOperationAction(ISD::FSQRT, VT, Expand);
387       setOperationAction(ISD::FSIN, VT, Expand);
388       setOperationAction(ISD::FCOS, VT, Expand);
389       setOperationAction(ISD::FTAN, VT, Expand);
390       setOperationAction(ISD::FPOW, VT, Expand);
391       setOperationAction(ISD::FLOG, VT, Expand);
392       setOperationAction(ISD::FLOG2, VT, Expand);
393       setOperationAction(ISD::FLOG10, VT, Expand);
394       setOperationAction(ISD::FEXP, VT, Expand);
395       setOperationAction(ISD::FEXP2, VT, Expand);
396       setOperationAction(ISD::FEXP10, VT, Expand);
397       setOperationAction(ISD::FNEARBYINT, VT, Expand);
398     }
399   }
400 
401   // Custom Expand smaller than legal vector reductions to prevent false zero
402   // items being added.
403   setOperationAction(ISD::VECREDUCE_FADD, MVT::v4f16, Custom);
404   setOperationAction(ISD::VECREDUCE_FMUL, MVT::v4f16, Custom);
405   setOperationAction(ISD::VECREDUCE_FMIN, MVT::v4f16, Custom);
406   setOperationAction(ISD::VECREDUCE_FMAX, MVT::v4f16, Custom);
407   setOperationAction(ISD::VECREDUCE_FADD, MVT::v2f16, Custom);
408   setOperationAction(ISD::VECREDUCE_FMUL, MVT::v2f16, Custom);
409   setOperationAction(ISD::VECREDUCE_FMIN, MVT::v2f16, Custom);
410   setOperationAction(ISD::VECREDUCE_FMAX, MVT::v2f16, Custom);
411 
412   // We 'support' these types up to bitcast/load/store level, regardless of
413   // MVE integer-only / float support. Only doing FP data processing on the FP
414   // vector types is inhibited at integer-only level.
415   const MVT LongTypes[] = { MVT::v2i64, MVT::v2f64 };
416   for (auto VT : LongTypes) {
417     addRegisterClass(VT, &ARM::MQPRRegClass);
418     setAllExpand(VT);
419     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
420     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
421     setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
422     setOperationAction(ISD::VSELECT, VT, Legal);
423     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
424   }
425   setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal);
426 
427   // We can do bitwise operations on v2i64 vectors
428   setOperationAction(ISD::AND, MVT::v2i64, Legal);
429   setOperationAction(ISD::OR, MVT::v2i64, Legal);
430   setOperationAction(ISD::XOR, MVT::v2i64, Legal);
431 
432   // It is legal to extload from v4i8 to v4i16 or v4i32.
433   addAllExtLoads(MVT::v8i16, MVT::v8i8, Legal);
434   addAllExtLoads(MVT::v4i32, MVT::v4i16, Legal);
435   addAllExtLoads(MVT::v4i32, MVT::v4i8, Legal);
436 
437   // It is legal to sign extend from v4i8/v4i16 to v4i32 or v8i8 to v8i16.
438   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8,  Legal);
439   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Legal);
440   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i32, Legal);
441   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v8i8,  Legal);
442   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v8i16, Legal);
443 
444   // Some truncating stores are legal too.
445   setTruncStoreAction(MVT::v4i32, MVT::v4i16, Legal);
446   setTruncStoreAction(MVT::v4i32, MVT::v4i8,  Legal);
447   setTruncStoreAction(MVT::v8i16, MVT::v8i8,  Legal);
448 
449   // Pre and Post inc on these are legal, given the correct extends
450   for (unsigned im = (unsigned)ISD::PRE_INC;
451        im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
452     for (auto VT : {MVT::v8i8, MVT::v4i8, MVT::v4i16}) {
453       setIndexedLoadAction(im, VT, Legal);
454       setIndexedStoreAction(im, VT, Legal);
455       setIndexedMaskedLoadAction(im, VT, Legal);
456       setIndexedMaskedStoreAction(im, VT, Legal);
457     }
458   }
459 
460   // Predicate types
461   const MVT pTypes[] = {MVT::v16i1, MVT::v8i1, MVT::v4i1, MVT::v2i1};
462   for (auto VT : pTypes) {
463     addRegisterClass(VT, &ARM::VCCRRegClass);
464     setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
465     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
466     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
467     setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
468     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
469     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
470     setOperationAction(ISD::SETCC, VT, Custom);
471     setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
472     setOperationAction(ISD::LOAD, VT, Custom);
473     setOperationAction(ISD::STORE, VT, Custom);
474     setOperationAction(ISD::TRUNCATE, VT, Custom);
475     setOperationAction(ISD::VSELECT, VT, Expand);
476     setOperationAction(ISD::SELECT, VT, Expand);
477     setOperationAction(ISD::SELECT_CC, VT, Expand);
478 
479     if (!HasMVEFP) {
480       setOperationAction(ISD::SINT_TO_FP, VT, Expand);
481       setOperationAction(ISD::UINT_TO_FP, VT, Expand);
482       setOperationAction(ISD::FP_TO_SINT, VT, Expand);
483       setOperationAction(ISD::FP_TO_UINT, VT, Expand);
484     }
485   }
486   setOperationAction(ISD::SETCC, MVT::v2i1, Expand);
487   setOperationAction(ISD::TRUNCATE, MVT::v2i1, Expand);
488   setOperationAction(ISD::AND, MVT::v2i1, Expand);
489   setOperationAction(ISD::OR, MVT::v2i1, Expand);
490   setOperationAction(ISD::XOR, MVT::v2i1, Expand);
491   setOperationAction(ISD::SINT_TO_FP, MVT::v2i1, Expand);
492   setOperationAction(ISD::UINT_TO_FP, MVT::v2i1, Expand);
493   setOperationAction(ISD::FP_TO_SINT, MVT::v2i1, Expand);
494   setOperationAction(ISD::FP_TO_UINT, MVT::v2i1, Expand);
495 
496   setOperationAction(ISD::SIGN_EXTEND, MVT::v8i32, Custom);
497   setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
498   setOperationAction(ISD::SIGN_EXTEND, MVT::v16i32, Custom);
499   setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32, Custom);
500   setOperationAction(ISD::ZERO_EXTEND, MVT::v16i16, Custom);
501   setOperationAction(ISD::ZERO_EXTEND, MVT::v16i32, Custom);
502   setOperationAction(ISD::TRUNCATE, MVT::v8i32, Custom);
503   setOperationAction(ISD::TRUNCATE, MVT::v16i16, Custom);
504 }
505 
getTM() const506 const ARMBaseTargetMachine &ARMTargetLowering::getTM() const {
507   return static_cast<const ARMBaseTargetMachine &>(getTargetMachine());
508 }
509 
ARMTargetLowering(const TargetMachine & TM_,const ARMSubtarget & STI)510 ARMTargetLowering::ARMTargetLowering(const TargetMachine &TM_,
511                                      const ARMSubtarget &STI)
512     : TargetLowering(TM_), Subtarget(&STI),
513       RegInfo(Subtarget->getRegisterInfo()),
514       Itins(Subtarget->getInstrItineraryData()) {
515   const auto &TM = static_cast<const ARMBaseTargetMachine &>(TM_);
516 
517   setBooleanContents(ZeroOrOneBooleanContent);
518   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
519 
520   const Triple &TT = TM.getTargetTriple();
521 
522   if (TT.isOSBinFormatMachO()) {
523     // Uses VFP for Thumb libfuncs if available.
524     if (Subtarget->isThumb() && Subtarget->hasVFP2Base() &&
525         Subtarget->hasARMOps() && !Subtarget->useSoftFloat()) {
526       // clang-format off
527       static const struct {
528         const RTLIB::Libcall Op;
529         const RTLIB::LibcallImpl Impl;
530       } LibraryCalls[] = {
531         // Single-precision floating-point arithmetic.
532         { RTLIB::ADD_F32, RTLIB::__addsf3vfp },
533         { RTLIB::SUB_F32, RTLIB::__subsf3vfp },
534         { RTLIB::MUL_F32, RTLIB::__mulsf3vfp },
535         { RTLIB::DIV_F32, RTLIB::__divsf3vfp },
536 
537         // Double-precision floating-point arithmetic.
538         { RTLIB::ADD_F64, RTLIB::__adddf3vfp },
539         { RTLIB::SUB_F64, RTLIB::__subdf3vfp },
540         { RTLIB::MUL_F64, RTLIB::__muldf3vfp },
541         { RTLIB::DIV_F64, RTLIB::__divdf3vfp },
542 
543         // Single-precision comparisons.
544         { RTLIB::OEQ_F32, RTLIB::__eqsf2vfp },
545         { RTLIB::UNE_F32, RTLIB::__nesf2vfp },
546         { RTLIB::OLT_F32, RTLIB::__ltsf2vfp },
547         { RTLIB::OLE_F32, RTLIB::__lesf2vfp },
548         { RTLIB::OGE_F32, RTLIB::__gesf2vfp },
549         { RTLIB::OGT_F32, RTLIB::__gtsf2vfp },
550         { RTLIB::UO_F32,  RTLIB::__unordsf2vfp },
551 
552         // Double-precision comparisons.
553         { RTLIB::OEQ_F64, RTLIB::__eqdf2vfp },
554         { RTLIB::UNE_F64, RTLIB::__nedf2vfp },
555         { RTLIB::OLT_F64, RTLIB::__ltdf2vfp },
556         { RTLIB::OLE_F64, RTLIB::__ledf2vfp },
557         { RTLIB::OGE_F64, RTLIB::__gedf2vfp },
558         { RTLIB::OGT_F64, RTLIB::__gtdf2vfp },
559         { RTLIB::UO_F64,  RTLIB::__unorddf2vfp },
560 
561         // Floating-point to integer conversions.
562         // i64 conversions are done via library routines even when generating VFP
563         // instructions, so use the same ones.
564         { RTLIB::FPTOSINT_F64_I32, RTLIB::__fixdfsivfp },
565         { RTLIB::FPTOUINT_F64_I32, RTLIB::__fixunsdfsivfp },
566         { RTLIB::FPTOSINT_F32_I32, RTLIB::__fixsfsivfp },
567         { RTLIB::FPTOUINT_F32_I32, RTLIB::__fixunssfsivfp },
568 
569         // Conversions between floating types.
570         { RTLIB::FPROUND_F64_F32, RTLIB::__truncdfsf2vfp },
571         { RTLIB::FPEXT_F32_F64,   RTLIB::__extendsfdf2vfp },
572 
573         // Integer to floating-point conversions.
574         // i64 conversions are done via library routines even when generating VFP
575         // instructions, so use the same ones.
576         // FIXME: There appears to be some naming inconsistency in ARM libgcc:
577         // e.g., __floatunsidf vs. __floatunssidfvfp.
578         { RTLIB::SINTTOFP_I32_F64, RTLIB::__floatsidfvfp },
579         { RTLIB::UINTTOFP_I32_F64, RTLIB::__floatunssidfvfp },
580         { RTLIB::SINTTOFP_I32_F32, RTLIB::__floatsisfvfp },
581         { RTLIB::UINTTOFP_I32_F32, RTLIB::__floatunssisfvfp },
582       };
583       // clang-format on
584 
585       for (const auto &LC : LibraryCalls)
586         setLibcallImpl(LC.Op, LC.Impl);
587     }
588   }
589 
590   // RTLIB
591   if (TM.isAAPCS_ABI() && (TT.isTargetAEABI() || TT.isTargetGNUAEABI() ||
592                            TT.isTargetMuslAEABI() || TT.isAndroid())) {
593     // FIXME: This does not depend on the subtarget and should go directly into
594     // RuntimeLibcalls. This is only here because of missing support for setting
595     // the calling convention of an implementation.
596     // clang-format off
597     static const struct {
598       const RTLIB::Libcall Op;
599       const RTLIB::LibcallImpl Impl;
600     } LibraryCalls[] = {
601       // Double-precision floating-point arithmetic helper functions
602       // RTABI chapter 4.1.2, Table 2
603       { RTLIB::ADD_F64, RTLIB::__aeabi_dadd },
604       { RTLIB::DIV_F64, RTLIB::__aeabi_ddiv },
605       { RTLIB::MUL_F64, RTLIB::__aeabi_dmul },
606       { RTLIB::SUB_F64, RTLIB::__aeabi_dsub },
607 
608       // Double-precision floating-point comparison helper functions
609       // RTABI chapter 4.1.2, Table 3
610       { RTLIB::OEQ_F64, RTLIB::__aeabi_dcmpeq__oeq },
611       { RTLIB::UNE_F64, RTLIB::__aeabi_dcmpeq__une },
612       { RTLIB::OLT_F64, RTLIB::__aeabi_dcmplt },
613       { RTLIB::OLE_F64, RTLIB::__aeabi_dcmple },
614       { RTLIB::OGE_F64, RTLIB::__aeabi_dcmpge },
615       { RTLIB::OGT_F64, RTLIB::__aeabi_dcmpgt },
616       { RTLIB::UO_F64,  RTLIB::__aeabi_dcmpun },
617 
618       // Single-precision floating-point arithmetic helper functions
619       // RTABI chapter 4.1.2, Table 4
620       { RTLIB::ADD_F32, RTLIB::__aeabi_fadd },
621       { RTLIB::DIV_F32, RTLIB::__aeabi_fdiv },
622       { RTLIB::MUL_F32, RTLIB::__aeabi_fmul },
623       { RTLIB::SUB_F32, RTLIB::__aeabi_fsub },
624 
625       // Single-precision floating-point comparison helper functions
626       // RTABI chapter 4.1.2, Table 5
627       { RTLIB::OEQ_F32, RTLIB::__aeabi_fcmpeq__oeq },
628       { RTLIB::UNE_F32, RTLIB::__aeabi_fcmpeq__une },
629       { RTLIB::OLT_F32, RTLIB::__aeabi_fcmplt},
630       { RTLIB::OLE_F32, RTLIB::__aeabi_fcmple },
631       { RTLIB::OGE_F32, RTLIB::__aeabi_fcmpge },
632       { RTLIB::OGT_F32, RTLIB::__aeabi_fcmpgt },
633       { RTLIB::UO_F32,  RTLIB::__aeabi_fcmpun },
634 
635       // Floating-point to integer conversions.
636       // RTABI chapter 4.1.2, Table 6
637       { RTLIB::FPTOSINT_F64_I32, RTLIB::__aeabi_d2iz },
638       { RTLIB::FPTOUINT_F64_I32, RTLIB::__aeabi_d2uiz },
639       { RTLIB::FPTOSINT_F64_I64, RTLIB::__aeabi_d2lz },
640       { RTLIB::FPTOUINT_F64_I64, RTLIB::__aeabi_d2ulz },
641       { RTLIB::FPTOSINT_F32_I32, RTLIB::__aeabi_f2iz },
642       { RTLIB::FPTOUINT_F32_I32, RTLIB::__aeabi_f2uiz },
643       { RTLIB::FPTOSINT_F32_I64, RTLIB::__aeabi_f2lz },
644       { RTLIB::FPTOUINT_F32_I64, RTLIB::__aeabi_f2ulz },
645 
646       // Conversions between floating types.
647       // RTABI chapter 4.1.2, Table 7
648       { RTLIB::FPROUND_F64_F32, RTLIB::__aeabi_d2f },
649       { RTLIB::FPROUND_F64_F16, RTLIB::__aeabi_d2h },
650       { RTLIB::FPEXT_F32_F64,   RTLIB::__aeabi_f2d },
651 
652       // Integer to floating-point conversions.
653       // RTABI chapter 4.1.2, Table 8
654       { RTLIB::SINTTOFP_I32_F64, RTLIB::__aeabi_i2d },
655       { RTLIB::UINTTOFP_I32_F64, RTLIB::__aeabi_ui2d },
656       { RTLIB::SINTTOFP_I64_F64, RTLIB::__aeabi_l2d },
657       { RTLIB::UINTTOFP_I64_F64, RTLIB::__aeabi_ul2d },
658       { RTLIB::SINTTOFP_I32_F32, RTLIB::__aeabi_i2f },
659       { RTLIB::UINTTOFP_I32_F32, RTLIB::__aeabi_ui2f },
660       { RTLIB::SINTTOFP_I64_F32, RTLIB::__aeabi_l2f },
661       { RTLIB::UINTTOFP_I64_F32, RTLIB::__aeabi_ul2f },
662 
663       // Long long helper functions
664       // RTABI chapter 4.2, Table 9
665       { RTLIB::MUL_I64, RTLIB::__aeabi_lmul },
666       { RTLIB::SHL_I64, RTLIB::__aeabi_llsl },
667       { RTLIB::SRL_I64, RTLIB::__aeabi_llsr },
668       { RTLIB::SRA_I64, RTLIB::__aeabi_lasr },
669 
670       // Integer division functions
671       // RTABI chapter 4.3.1
672       { RTLIB::SDIV_I8,  RTLIB::__aeabi_idiv__i8 },
673       { RTLIB::SDIV_I16, RTLIB::__aeabi_idiv__i16 },
674       { RTLIB::SDIV_I32, RTLIB::__aeabi_idiv__i32},
675       { RTLIB::SDIV_I64, RTLIB::__aeabi_ldivmod },
676       { RTLIB::UDIV_I8,  RTLIB::__aeabi_uidiv__i8 },
677       { RTLIB::UDIV_I16, RTLIB::__aeabi_uidiv__i16 },
678       { RTLIB::UDIV_I32, RTLIB::__aeabi_uidiv__i32 },
679       { RTLIB::UDIV_I64, RTLIB::__aeabi_uldivmod },
680     };
681     // clang-format on
682 
683     for (const auto &LC : LibraryCalls)
684       setLibcallImpl(LC.Op, LC.Impl);
685 
686     // EABI dependent RTLIB
687     if (TM.Options.EABIVersion == EABI::EABI4 ||
688         TM.Options.EABIVersion == EABI::EABI5) {
689       static const struct {
690         const RTLIB::Libcall Op;
691         const RTLIB::LibcallImpl Impl;
692       } MemOpsLibraryCalls[] = {
693           // Memory operations
694           // RTABI chapter 4.3.4
695           {RTLIB::MEMCPY, RTLIB::__aeabi_memcpy},
696           {RTLIB::MEMMOVE, RTLIB::__aeabi_memmove},
697           {RTLIB::MEMSET, RTLIB::__aeabi_memset},
698           {RTLIB::AEABI_MEMCPY4, RTLIB::__aeabi_memcpy4},
699           {RTLIB::AEABI_MEMCPY8, RTLIB::__aeabi_memcpy8},
700           {RTLIB::AEABI_MEMMOVE4, RTLIB::__aeabi_memmove4},
701           {RTLIB::AEABI_MEMMOVE8, RTLIB::__aeabi_memmove8},
702           {RTLIB::AEABI_MEMSET4, RTLIB::__aeabi_memset4},
703           {RTLIB::AEABI_MEMSET8, RTLIB::__aeabi_memset8},
704           {RTLIB::AEABI_MEMCLR, RTLIB::__aeabi_memclr},
705           {RTLIB::AEABI_MEMCLR4, RTLIB::__aeabi_memclr4},
706           {RTLIB::AEABI_MEMCLR8, RTLIB::__aeabi_memclr8},
707       };
708 
709       for (const auto &LC : MemOpsLibraryCalls)
710         setLibcallImpl(LC.Op, LC.Impl);
711     }
712   }
713 
714   // The half <-> float conversion functions are always soft-float on
715   // non-watchos platforms, but are needed for some targets which use a
716   // hard-float calling convention by default.
717   if (!TT.isWatchABI()) {
718     if (TM.isAAPCS_ABI()) {
719       setLibcallImplCallingConv(RTLIB::__truncsfhf2, CallingConv::ARM_AAPCS);
720       setLibcallImplCallingConv(RTLIB::__truncdfhf2, CallingConv::ARM_AAPCS);
721       setLibcallImplCallingConv(RTLIB::__extendhfsf2, CallingConv::ARM_AAPCS);
722       setLibcallImplCallingConv(RTLIB::__gnu_h2f_ieee, CallingConv::ARM_AAPCS);
723       setLibcallImplCallingConv(RTLIB::__gnu_f2h_ieee, CallingConv::ARM_AAPCS);
724     } else {
725       setLibcallImplCallingConv(RTLIB::__truncsfhf2, CallingConv::ARM_APCS);
726       setLibcallImplCallingConv(RTLIB::__truncdfhf2, CallingConv::ARM_APCS);
727       setLibcallImplCallingConv(RTLIB::__extendhfsf2, CallingConv::ARM_APCS);
728       setLibcallImplCallingConv(RTLIB::__gnu_h2f_ieee, CallingConv::ARM_APCS);
729       setLibcallImplCallingConv(RTLIB::__gnu_f2h_ieee, CallingConv::ARM_APCS);
730     }
731   }
732 
733   // In EABI, these functions have an __aeabi_ prefix, but in GNUEABI they have
734   // a __gnu_ prefix (which is the default).
735   if (TT.isTargetAEABI()) {
736     // FIXME: This does not depend on the subtarget and should go directly into
737     // RuntimeLibcalls. This is only here because of missing support for setting
738     // the calling convention of an implementation.
739     static const struct {
740       const RTLIB::Libcall Op;
741       const RTLIB::LibcallImpl Impl;
742     } LibraryCalls[] = {
743         {RTLIB::FPROUND_F32_F16, RTLIB::__aeabi_f2h},
744         {RTLIB::FPROUND_F64_F16, RTLIB::__aeabi_d2h},
745         {RTLIB::FPEXT_F16_F32, RTLIB::__aeabi_h2f},
746     };
747 
748     for (const auto &LC : LibraryCalls) {
749       setLibcallImpl(LC.Op, LC.Impl);
750     }
751   } else if (!TT.isOSBinFormatMachO()) {
752     setLibcallImpl(RTLIB::FPROUND_F32_F16, RTLIB::__gnu_f2h_ieee);
753     setLibcallImpl(RTLIB::FPEXT_F16_F32, RTLIB::__gnu_h2f_ieee);
754   }
755 
756   if (Subtarget->isThumb1Only())
757     addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
758   else
759     addRegisterClass(MVT::i32, &ARM::GPRRegClass);
760 
761   if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only() &&
762       Subtarget->hasFPRegs()) {
763     addRegisterClass(MVT::f32, &ARM::SPRRegClass);
764     addRegisterClass(MVT::f64, &ARM::DPRRegClass);
765 
766     setOperationAction(ISD::FP_TO_SINT_SAT, MVT::i32, Custom);
767     setOperationAction(ISD::FP_TO_UINT_SAT, MVT::i32, Custom);
768     setOperationAction(ISD::FP_TO_SINT_SAT, MVT::i64, Custom);
769     setOperationAction(ISD::FP_TO_UINT_SAT, MVT::i64, Custom);
770 
771     if (!Subtarget->hasVFP2Base())
772       setAllExpand(MVT::f32);
773     if (!Subtarget->hasFP64())
774       setAllExpand(MVT::f64);
775   }
776 
777   if (Subtarget->hasFullFP16()) {
778     addRegisterClass(MVT::f16, &ARM::HPRRegClass);
779     setOperationAction(ISD::BITCAST, MVT::i16, Custom);
780     setOperationAction(ISD::BITCAST, MVT::f16, Custom);
781 
782     setOperationAction(ISD::FMINNUM, MVT::f16, Legal);
783     setOperationAction(ISD::FMAXNUM, MVT::f16, Legal);
784   }
785 
786   if (Subtarget->hasBF16()) {
787     addRegisterClass(MVT::bf16, &ARM::HPRRegClass);
788     setAllExpand(MVT::bf16);
789     if (!Subtarget->hasFullFP16())
790       setOperationAction(ISD::BITCAST, MVT::bf16, Custom);
791   } else {
792     setOperationAction(ISD::BF16_TO_FP, MVT::f32, Expand);
793     setOperationAction(ISD::BF16_TO_FP, MVT::f64, Expand);
794     setOperationAction(ISD::FP_TO_BF16, MVT::f32, Custom);
795     setOperationAction(ISD::FP_TO_BF16, MVT::f64, Custom);
796   }
797 
798   for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
799     for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) {
800       setTruncStoreAction(VT, InnerVT, Expand);
801       addAllExtLoads(VT, InnerVT, Expand);
802     }
803 
804     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
805     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
806 
807     setOperationAction(ISD::BSWAP, VT, Expand);
808   }
809 
810   setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
811   setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
812 
813   setOperationAction(ISD::READ_REGISTER, MVT::i64, Custom);
814   setOperationAction(ISD::WRITE_REGISTER, MVT::i64, Custom);
815 
816   if (Subtarget->hasMVEIntegerOps())
817     addMVEVectorTypes(Subtarget->hasMVEFloatOps());
818 
819   // Combine low-overhead loop intrinsics so that we can lower i1 types.
820   if (Subtarget->hasLOB()) {
821     setTargetDAGCombine({ISD::BRCOND, ISD::BR_CC});
822   }
823 
824   if (Subtarget->hasNEON()) {
825     addDRTypeForNEON(MVT::v2f32);
826     addDRTypeForNEON(MVT::v8i8);
827     addDRTypeForNEON(MVT::v4i16);
828     addDRTypeForNEON(MVT::v2i32);
829     addDRTypeForNEON(MVT::v1i64);
830 
831     addQRTypeForNEON(MVT::v4f32);
832     addQRTypeForNEON(MVT::v2f64);
833     addQRTypeForNEON(MVT::v16i8);
834     addQRTypeForNEON(MVT::v8i16);
835     addQRTypeForNEON(MVT::v4i32);
836     addQRTypeForNEON(MVT::v2i64);
837 
838     if (Subtarget->hasFullFP16()) {
839       addQRTypeForNEON(MVT::v8f16);
840       addDRTypeForNEON(MVT::v4f16);
841     }
842 
843     if (Subtarget->hasBF16()) {
844       addQRTypeForNEON(MVT::v8bf16);
845       addDRTypeForNEON(MVT::v4bf16);
846     }
847   }
848 
849   if (Subtarget->hasMVEIntegerOps() || Subtarget->hasNEON()) {
850     // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
851     // none of Neon, MVE or VFP supports any arithmetic operations on it.
852     setOperationAction(ISD::FADD, MVT::v2f64, Expand);
853     setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
854     setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
855     // FIXME: Code duplication: FDIV and FREM are expanded always, see
856     // ARMTargetLowering::addTypeForNEON method for details.
857     setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
858     setOperationAction(ISD::FREM, MVT::v2f64, Expand);
859     // FIXME: Create unittest.
860     // In another words, find a way when "copysign" appears in DAG with vector
861     // operands.
862     setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
863     // FIXME: Code duplication: SETCC has custom operation action, see
864     // ARMTargetLowering::addTypeForNEON method for details.
865     setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
866     // FIXME: Create unittest for FNEG and for FABS.
867     setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
868     setOperationAction(ISD::FABS, MVT::v2f64, Expand);
869     setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
870     setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
871     setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
872     setOperationAction(ISD::FTAN, MVT::v2f64, Expand);
873     setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
874     setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
875     setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
876     setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
877     setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
878     setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
879     setOperationAction(ISD::FEXP10, MVT::v2f64, Expand);
880     setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
881     setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
882     setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
883     setOperationAction(ISD::FROUNDEVEN, MVT::v2f64, Expand);
884     setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
885     setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
886     setOperationAction(ISD::FMA, MVT::v2f64, Expand);
887   }
888 
889   if (Subtarget->hasNEON()) {
890     // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
891     // supported for v4f32.
892     setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
893     setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
894     setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
895     setOperationAction(ISD::FTAN, MVT::v4f32, Expand);
896     setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
897     setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
898     setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
899     setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
900     setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
901     setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
902     setOperationAction(ISD::FEXP10, MVT::v4f32, Expand);
903     setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
904     setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
905     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
906     setOperationAction(ISD::FROUNDEVEN, MVT::v4f32, Expand);
907     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
908     setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
909 
910     // Mark v2f32 intrinsics.
911     setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
912     setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
913     setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
914     setOperationAction(ISD::FTAN, MVT::v2f32, Expand);
915     setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
916     setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
917     setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
918     setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
919     setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
920     setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
921     setOperationAction(ISD::FEXP10, MVT::v2f32, Expand);
922     setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
923     setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
924     setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
925     setOperationAction(ISD::FROUNDEVEN, MVT::v2f32, Expand);
926     setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
927     setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
928 
929     for (ISD::NodeType Op : {ISD::FFLOOR, ISD::FNEARBYINT, ISD::FCEIL,
930                               ISD::FRINT, ISD::FTRUNC, ISD::FROUNDEVEN}) {
931       setOperationAction(Op, MVT::v4f16, Expand);
932       setOperationAction(Op, MVT::v8f16, Expand);
933     }
934 
935     // Neon does not support some operations on v1i64 and v2i64 types.
936     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
937     // Custom handling for some quad-vector types to detect VMULL.
938     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
939     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
940     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
941     // Custom handling for some vector types to avoid expensive expansions
942     setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
943     setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
944     setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
945     setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
946     // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
947     // a destination type that is wider than the source, and nor does
948     // it have a FP_TO_[SU]INT instruction with a narrower destination than
949     // source.
950     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
951     setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Custom);
952     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
953     setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
954     setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
955     setOperationAction(ISD::FP_TO_UINT, MVT::v8i16, Custom);
956     setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
957     setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Custom);
958 
959     setOperationAction(ISD::FP_ROUND,   MVT::v2f32, Expand);
960     setOperationAction(ISD::FP_EXTEND,  MVT::v2f64, Expand);
961 
962     // NEON does not have single instruction CTPOP for vectors with element
963     // types wider than 8-bits.  However, custom lowering can leverage the
964     // v8i8/v16i8 vcnt instruction.
965     setOperationAction(ISD::CTPOP,      MVT::v2i32, Custom);
966     setOperationAction(ISD::CTPOP,      MVT::v4i32, Custom);
967     setOperationAction(ISD::CTPOP,      MVT::v4i16, Custom);
968     setOperationAction(ISD::CTPOP,      MVT::v8i16, Custom);
969     setOperationAction(ISD::CTPOP,      MVT::v1i64, Custom);
970     setOperationAction(ISD::CTPOP,      MVT::v2i64, Custom);
971 
972     setOperationAction(ISD::CTLZ,       MVT::v1i64, Expand);
973     setOperationAction(ISD::CTLZ,       MVT::v2i64, Expand);
974 
975     // NEON does not have single instruction CTTZ for vectors.
976     setOperationAction(ISD::CTTZ, MVT::v8i8, Custom);
977     setOperationAction(ISD::CTTZ, MVT::v4i16, Custom);
978     setOperationAction(ISD::CTTZ, MVT::v2i32, Custom);
979     setOperationAction(ISD::CTTZ, MVT::v1i64, Custom);
980 
981     setOperationAction(ISD::CTTZ, MVT::v16i8, Custom);
982     setOperationAction(ISD::CTTZ, MVT::v8i16, Custom);
983     setOperationAction(ISD::CTTZ, MVT::v4i32, Custom);
984     setOperationAction(ISD::CTTZ, MVT::v2i64, Custom);
985 
986     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i8, Custom);
987     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i16, Custom);
988     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i32, Custom);
989     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v1i64, Custom);
990 
991     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i8, Custom);
992     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i16, Custom);
993     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i32, Custom);
994     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i64, Custom);
995 
996     for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
997       setOperationAction(ISD::MULHS, VT, Expand);
998       setOperationAction(ISD::MULHU, VT, Expand);
999     }
1000 
1001     // NEON only has FMA instructions as of VFP4.
1002     if (!Subtarget->hasVFP4Base()) {
1003       setOperationAction(ISD::FMA, MVT::v2f32, Expand);
1004       setOperationAction(ISD::FMA, MVT::v4f32, Expand);
1005     }
1006 
1007     setTargetDAGCombine({ISD::SHL, ISD::SRL, ISD::SRA, ISD::FP_TO_SINT,
1008                          ISD::FP_TO_UINT, ISD::FMUL, ISD::LOAD});
1009 
1010     // It is legal to extload from v4i8 to v4i16 or v4i32.
1011     for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16,
1012                    MVT::v2i32}) {
1013       for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) {
1014         setLoadExtAction(ISD::EXTLOAD, VT, Ty, Legal);
1015         setLoadExtAction(ISD::ZEXTLOAD, VT, Ty, Legal);
1016         setLoadExtAction(ISD::SEXTLOAD, VT, Ty, Legal);
1017       }
1018     }
1019 
1020     for (auto VT : {MVT::v8i8, MVT::v4i16, MVT::v2i32, MVT::v16i8, MVT::v8i16,
1021                     MVT::v4i32}) {
1022       setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom);
1023       setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom);
1024       setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom);
1025       setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom);
1026     }
1027   }
1028 
1029   if (Subtarget->hasNEON() || Subtarget->hasMVEIntegerOps()) {
1030     setTargetDAGCombine(
1031         {ISD::BUILD_VECTOR, ISD::VECTOR_SHUFFLE, ISD::INSERT_SUBVECTOR,
1032          ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT,
1033          ISD::SIGN_EXTEND_INREG, ISD::STORE, ISD::SIGN_EXTEND, ISD::ZERO_EXTEND,
1034          ISD::ANY_EXTEND, ISD::INTRINSIC_WO_CHAIN, ISD::INTRINSIC_W_CHAIN,
1035          ISD::INTRINSIC_VOID, ISD::VECREDUCE_ADD, ISD::ADD, ISD::BITCAST});
1036   }
1037   if (Subtarget->hasMVEIntegerOps()) {
1038     setTargetDAGCombine({ISD::SMIN, ISD::UMIN, ISD::SMAX, ISD::UMAX,
1039                          ISD::FP_EXTEND, ISD::SELECT, ISD::SELECT_CC,
1040                          ISD::SETCC});
1041   }
1042   if (Subtarget->hasMVEFloatOps()) {
1043     setTargetDAGCombine(ISD::FADD);
1044   }
1045 
1046   if (!Subtarget->hasFP64()) {
1047     // When targeting a floating-point unit with only single-precision
1048     // operations, f64 is legal for the few double-precision instructions which
1049     // are present However, no double-precision operations other than moves,
1050     // loads and stores are provided by the hardware.
1051     setOperationAction(ISD::FADD,       MVT::f64, Expand);
1052     setOperationAction(ISD::FSUB,       MVT::f64, Expand);
1053     setOperationAction(ISD::FMUL,       MVT::f64, Expand);
1054     setOperationAction(ISD::FMA,        MVT::f64, Expand);
1055     setOperationAction(ISD::FDIV,       MVT::f64, Expand);
1056     setOperationAction(ISD::FREM,       MVT::f64, Expand);
1057     setOperationAction(ISD::FCOPYSIGN,  MVT::f64, Expand);
1058     setOperationAction(ISD::FGETSIGN,   MVT::f64, Expand);
1059     setOperationAction(ISD::FNEG,       MVT::f64, Expand);
1060     setOperationAction(ISD::FABS,       MVT::f64, Expand);
1061     setOperationAction(ISD::FSQRT,      MVT::f64, Expand);
1062     setOperationAction(ISD::FSIN,       MVT::f64, Expand);
1063     setOperationAction(ISD::FCOS,       MVT::f64, Expand);
1064     setOperationAction(ISD::FPOW,       MVT::f64, Expand);
1065     setOperationAction(ISD::FLOG,       MVT::f64, Expand);
1066     setOperationAction(ISD::FLOG2,      MVT::f64, Expand);
1067     setOperationAction(ISD::FLOG10,     MVT::f64, Expand);
1068     setOperationAction(ISD::FEXP,       MVT::f64, Expand);
1069     setOperationAction(ISD::FEXP2,      MVT::f64, Expand);
1070     setOperationAction(ISD::FEXP10,      MVT::f64, Expand);
1071     setOperationAction(ISD::FCEIL,      MVT::f64, Expand);
1072     setOperationAction(ISD::FTRUNC,     MVT::f64, Expand);
1073     setOperationAction(ISD::FRINT,      MVT::f64, Expand);
1074     setOperationAction(ISD::FROUNDEVEN, MVT::f64, Expand);
1075     setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand);
1076     setOperationAction(ISD::FFLOOR,     MVT::f64, Expand);
1077     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
1078     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
1079     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
1080     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
1081     setOperationAction(ISD::FP_TO_SINT, MVT::f64, Custom);
1082     setOperationAction(ISD::FP_TO_UINT, MVT::f64, Custom);
1083     setOperationAction(ISD::FP_ROUND,   MVT::f32, Custom);
1084     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom);
1085     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom);
1086     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::f64, Custom);
1087     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::f64, Custom);
1088     setOperationAction(ISD::STRICT_FP_ROUND,   MVT::f32, Custom);
1089   }
1090 
1091   if (!Subtarget->hasFP64() || !Subtarget->hasFPARMv8Base()) {
1092     setOperationAction(ISD::FP_EXTEND,  MVT::f64, Custom);
1093     setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f64, Custom);
1094     if (Subtarget->hasFullFP16()) {
1095       setOperationAction(ISD::FP_ROUND,  MVT::f16, Custom);
1096       setOperationAction(ISD::STRICT_FP_ROUND, MVT::f16, Custom);
1097     }
1098   }
1099 
1100   if (!Subtarget->hasFP16()) {
1101     setOperationAction(ISD::FP_EXTEND,  MVT::f32, Custom);
1102     setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f32, Custom);
1103   }
1104 
1105   computeRegisterProperties(Subtarget->getRegisterInfo());
1106 
1107   // ARM does not have floating-point extending loads.
1108   for (MVT VT : MVT::fp_valuetypes()) {
1109     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
1110     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
1111     setLoadExtAction(ISD::EXTLOAD, VT, MVT::bf16, Expand);
1112   }
1113 
1114   // ... or truncating stores
1115   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
1116   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
1117   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
1118   setTruncStoreAction(MVT::f32, MVT::bf16, Expand);
1119   setTruncStoreAction(MVT::f64, MVT::bf16, Expand);
1120 
1121   // ARM does not have i1 sign extending load.
1122   for (MVT VT : MVT::integer_valuetypes())
1123     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
1124 
1125   // ARM supports all 4 flavors of integer indexed load / store.
1126   if (!Subtarget->isThumb1Only()) {
1127     for (unsigned im = (unsigned)ISD::PRE_INC;
1128          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
1129       setIndexedLoadAction(im,  MVT::i1,  Legal);
1130       setIndexedLoadAction(im,  MVT::i8,  Legal);
1131       setIndexedLoadAction(im,  MVT::i16, Legal);
1132       setIndexedLoadAction(im,  MVT::i32, Legal);
1133       setIndexedStoreAction(im, MVT::i1,  Legal);
1134       setIndexedStoreAction(im, MVT::i8,  Legal);
1135       setIndexedStoreAction(im, MVT::i16, Legal);
1136       setIndexedStoreAction(im, MVT::i32, Legal);
1137     }
1138   } else {
1139     // Thumb-1 has limited post-inc load/store support - LDM r0!, {r1}.
1140     setIndexedLoadAction(ISD::POST_INC, MVT::i32,  Legal);
1141     setIndexedStoreAction(ISD::POST_INC, MVT::i32,  Legal);
1142   }
1143 
1144   setOperationAction(ISD::SADDO, MVT::i32, Custom);
1145   setOperationAction(ISD::UADDO, MVT::i32, Custom);
1146   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
1147   setOperationAction(ISD::USUBO, MVT::i32, Custom);
1148 
1149   setOperationAction(ISD::UADDO_CARRY, MVT::i32, Custom);
1150   setOperationAction(ISD::USUBO_CARRY, MVT::i32, Custom);
1151   if (Subtarget->hasDSP()) {
1152     setOperationAction(ISD::SADDSAT, MVT::i8, Custom);
1153     setOperationAction(ISD::SSUBSAT, MVT::i8, Custom);
1154     setOperationAction(ISD::SADDSAT, MVT::i16, Custom);
1155     setOperationAction(ISD::SSUBSAT, MVT::i16, Custom);
1156     setOperationAction(ISD::UADDSAT, MVT::i8, Custom);
1157     setOperationAction(ISD::USUBSAT, MVT::i8, Custom);
1158     setOperationAction(ISD::UADDSAT, MVT::i16, Custom);
1159     setOperationAction(ISD::USUBSAT, MVT::i16, Custom);
1160   }
1161   if (Subtarget->hasBaseDSP()) {
1162     setOperationAction(ISD::SADDSAT, MVT::i32, Legal);
1163     setOperationAction(ISD::SSUBSAT, MVT::i32, Legal);
1164   }
1165 
1166   // i64 operation support.
1167   setOperationAction(ISD::MUL,     MVT::i64, Expand);
1168   setOperationAction(ISD::MULHU,   MVT::i32, Expand);
1169   if (Subtarget->isThumb1Only()) {
1170     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
1171     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
1172   }
1173   if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
1174       || (Subtarget->isThumb2() && !Subtarget->hasDSP()))
1175     setOperationAction(ISD::MULHS, MVT::i32, Expand);
1176 
1177   setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
1178   setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
1179   setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
1180   setOperationAction(ISD::SRL,       MVT::i64, Custom);
1181   setOperationAction(ISD::SRA,       MVT::i64, Custom);
1182   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1183   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom);
1184   setOperationAction(ISD::LOAD, MVT::i64, Custom);
1185   setOperationAction(ISD::STORE, MVT::i64, Custom);
1186 
1187   // MVE lowers 64 bit shifts to lsll and lsrl
1188   // assuming that ISD::SRL and SRA of i64 are already marked custom
1189   if (Subtarget->hasMVEIntegerOps())
1190     setOperationAction(ISD::SHL, MVT::i64, Custom);
1191 
1192   // Expand to __aeabi_l{lsl,lsr,asr} calls for Thumb1.
1193   if (Subtarget->isThumb1Only()) {
1194     setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand);
1195     setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
1196     setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand);
1197   }
1198 
1199   if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops())
1200     setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
1201 
1202   // ARM does not have ROTL.
1203   setOperationAction(ISD::ROTL, MVT::i32, Expand);
1204   for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
1205     setOperationAction(ISD::ROTL, VT, Expand);
1206     setOperationAction(ISD::ROTR, VT, Expand);
1207   }
1208   setOperationAction(ISD::CTTZ,  MVT::i32, Custom);
1209   // TODO: These two should be set to LibCall, but this currently breaks
1210   //   the Linux kernel build. See #101786.
1211   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
1212   setOperationAction(ISD::CTPOP, MVT::i64, Expand);
1213   if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only()) {
1214     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
1215     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, LibCall);
1216   }
1217 
1218   // @llvm.readcyclecounter requires the Performance Monitors extension.
1219   // Default to the 0 expansion on unsupported platforms.
1220   // FIXME: Technically there are older ARM CPUs that have
1221   // implementation-specific ways of obtaining this information.
1222   if (Subtarget->hasPerfMon())
1223     setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
1224 
1225   // Only ARMv6 has BSWAP.
1226   if (!Subtarget->hasV6Ops())
1227     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
1228 
1229   bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode()
1230                                         : Subtarget->hasDivideInARMMode();
1231   if (!hasDivide) {
1232     // These are expanded into libcalls if the cpu doesn't have HW divider.
1233     setOperationAction(ISD::SDIV,  MVT::i32, LibCall);
1234     setOperationAction(ISD::UDIV,  MVT::i32, LibCall);
1235   }
1236 
1237   if (TT.isOSWindows() && !Subtarget->hasDivideInThumbMode()) {
1238     setOperationAction(ISD::SDIV, MVT::i32, Custom);
1239     setOperationAction(ISD::UDIV, MVT::i32, Custom);
1240 
1241     setOperationAction(ISD::SDIV, MVT::i64, Custom);
1242     setOperationAction(ISD::UDIV, MVT::i64, Custom);
1243   }
1244 
1245   setOperationAction(ISD::SREM,  MVT::i32, Expand);
1246   setOperationAction(ISD::UREM,  MVT::i32, Expand);
1247 
1248   // Register based DivRem for AEABI (RTABI 4.2)
1249   if (TT.isTargetAEABI() || TT.isAndroid() || TT.isTargetGNUAEABI() ||
1250       TT.isTargetMuslAEABI() || TT.isOSWindows()) {
1251     setOperationAction(ISD::SREM, MVT::i64, Custom);
1252     setOperationAction(ISD::UREM, MVT::i64, Custom);
1253     HasStandaloneRem = false;
1254 
1255     setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
1256     setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
1257     setOperationAction(ISD::SDIVREM, MVT::i64, Custom);
1258     setOperationAction(ISD::UDIVREM, MVT::i64, Custom);
1259   } else {
1260     setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
1261     setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
1262   }
1263 
1264   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
1265   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
1266   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
1267   setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
1268 
1269   setOperationAction(ISD::TRAP, MVT::Other, Legal);
1270   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
1271 
1272   // Use the default implementation.
1273   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
1274   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
1275   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
1276   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
1277   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
1278   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
1279 
1280   if (TT.isOSWindows())
1281     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
1282   else
1283     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
1284 
1285   // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
1286   // the default expansion.
1287   InsertFencesForAtomic = false;
1288   if (Subtarget->hasAnyDataBarrier() &&
1289       (!Subtarget->isThumb() || Subtarget->hasV8MBaselineOps())) {
1290     // ATOMIC_FENCE needs custom lowering; the others should have been expanded
1291     // to ldrex/strex loops already.
1292     setOperationAction(ISD::ATOMIC_FENCE,     MVT::Other, Custom);
1293     if (!Subtarget->isThumb() || !Subtarget->isMClass())
1294       setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i64, Custom);
1295 
1296     // On v8, we have particularly efficient implementations of atomic fences
1297     // if they can be combined with nearby atomic loads and stores.
1298     if (!Subtarget->hasAcquireRelease() ||
1299         getTargetMachine().getOptLevel() == CodeGenOptLevel::None) {
1300       // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc.
1301       InsertFencesForAtomic = true;
1302     }
1303   } else {
1304     // If there's anything we can use as a barrier, go through custom lowering
1305     // for ATOMIC_FENCE.
1306     // If target has DMB in thumb, Fences can be inserted.
1307     if (Subtarget->hasDataBarrier())
1308       InsertFencesForAtomic = true;
1309 
1310     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other,
1311                        Subtarget->hasAnyDataBarrier() ? Custom : Expand);
1312 
1313     // Set them all for libcall, which will force libcalls.
1314     setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, LibCall);
1315     setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, LibCall);
1316     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, LibCall);
1317     setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, LibCall);
1318     setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, LibCall);
1319     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, LibCall);
1320     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, LibCall);
1321     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, LibCall);
1322     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, LibCall);
1323     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, LibCall);
1324     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, LibCall);
1325     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, LibCall);
1326     // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
1327     // Unordered/Monotonic case.
1328     if (!InsertFencesForAtomic) {
1329       setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
1330       setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
1331     }
1332   }
1333 
1334   // Compute supported atomic widths.
1335   if (TT.isOSLinux() || (!Subtarget->isMClass() && Subtarget->hasV6Ops())) {
1336     // For targets where __sync_* routines are reliably available, we use them
1337     // if necessary.
1338     //
1339     // ARM Linux always supports 64-bit atomics through kernel-assisted atomic
1340     // routines (kernel 3.1 or later). FIXME: Not with compiler-rt?
1341     //
1342     // ARMv6 targets have native instructions in ARM mode. For Thumb mode,
1343     // such targets should provide __sync_* routines, which use the ARM mode
1344     // instructions. (ARMv6 doesn't have dmb, but it has an equivalent
1345     // encoding; see ARMISD::MEMBARRIER_MCR.)
1346     setMaxAtomicSizeInBitsSupported(64);
1347   } else if ((Subtarget->isMClass() && Subtarget->hasV8MBaselineOps()) ||
1348              Subtarget->hasForced32BitAtomics()) {
1349     // Cortex-M (besides Cortex-M0) have 32-bit atomics.
1350     setMaxAtomicSizeInBitsSupported(32);
1351   } else {
1352     // We can't assume anything about other targets; just use libatomic
1353     // routines.
1354     setMaxAtomicSizeInBitsSupported(0);
1355   }
1356 
1357   setMaxDivRemBitWidthSupported(64);
1358 
1359   setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
1360 
1361   // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
1362   if (!Subtarget->hasV6Ops()) {
1363     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
1364     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
1365   }
1366   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
1367 
1368   if (!Subtarget->useSoftFloat() && Subtarget->hasFPRegs() &&
1369       !Subtarget->isThumb1Only()) {
1370     // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
1371     // iff target supports vfp2.
1372     setOperationAction(ISD::BITCAST, MVT::i64, Custom);
1373     setOperationAction(ISD::GET_ROUNDING, MVT::i32, Custom);
1374     setOperationAction(ISD::SET_ROUNDING, MVT::Other, Custom);
1375     setOperationAction(ISD::GET_FPENV, MVT::i32, Legal);
1376     setOperationAction(ISD::SET_FPENV, MVT::i32, Legal);
1377     setOperationAction(ISD::RESET_FPENV, MVT::Other, Legal);
1378     setOperationAction(ISD::GET_FPMODE, MVT::i32, Legal);
1379     setOperationAction(ISD::SET_FPMODE, MVT::i32, Custom);
1380     setOperationAction(ISD::RESET_FPMODE, MVT::Other, Custom);
1381   }
1382 
1383   // We want to custom lower some of our intrinsics.
1384   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1385   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
1386   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
1387   setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom);
1388 
1389   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
1390   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
1391   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
1392   setOperationAction(ISD::SELECT,    MVT::i32, Custom);
1393   setOperationAction(ISD::SELECT,    MVT::f32, Custom);
1394   setOperationAction(ISD::SELECT,    MVT::f64, Custom);
1395   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
1396   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
1397   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
1398   if (Subtarget->hasFullFP16()) {
1399     setOperationAction(ISD::SETCC,     MVT::f16, Expand);
1400     setOperationAction(ISD::SELECT,    MVT::f16, Custom);
1401     setOperationAction(ISD::SELECT_CC, MVT::f16, Custom);
1402   }
1403 
1404   setOperationAction(ISD::SETCCCARRY, MVT::i32, Custom);
1405 
1406   setOperationAction(ISD::BRCOND,    MVT::Other, Custom);
1407   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
1408   if (Subtarget->hasFullFP16())
1409       setOperationAction(ISD::BR_CC, MVT::f16,   Custom);
1410   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
1411   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
1412   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
1413 
1414   // We don't support sin/cos/fmod/copysign/pow
1415   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
1416   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
1417   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
1418   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
1419   setOperationAction(ISD::FSINCOS,   MVT::f64, Expand);
1420   setOperationAction(ISD::FSINCOS,   MVT::f32, Expand);
1421   setOperationAction(ISD::FREM,      MVT::f64, Expand);
1422   setOperationAction(ISD::FREM,      MVT::f32, Expand);
1423   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2Base() &&
1424       !Subtarget->isThumb1Only()) {
1425     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
1426     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
1427   }
1428   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
1429   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
1430 
1431   if (!Subtarget->hasVFP4Base()) {
1432     setOperationAction(ISD::FMA, MVT::f64, Expand);
1433     setOperationAction(ISD::FMA, MVT::f32, Expand);
1434   }
1435 
1436   // Various VFP goodness
1437   if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) {
1438     // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded.
1439     if (!Subtarget->hasFPARMv8Base() || !Subtarget->hasFP64()) {
1440       setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
1441       setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
1442     }
1443 
1444     // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
1445     if (!Subtarget->hasFP16()) {
1446       setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
1447       setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
1448     }
1449 
1450     // Strict floating-point comparisons need custom lowering.
1451     setOperationAction(ISD::STRICT_FSETCC,  MVT::f16, Custom);
1452     setOperationAction(ISD::STRICT_FSETCCS, MVT::f16, Custom);
1453     setOperationAction(ISD::STRICT_FSETCC,  MVT::f32, Custom);
1454     setOperationAction(ISD::STRICT_FSETCCS, MVT::f32, Custom);
1455     setOperationAction(ISD::STRICT_FSETCC,  MVT::f64, Custom);
1456     setOperationAction(ISD::STRICT_FSETCCS, MVT::f64, Custom);
1457   }
1458 
1459   // Use __sincos_stret if available.
1460   if (getLibcallName(RTLIB::SINCOS_STRET_F32) != nullptr &&
1461       getLibcallName(RTLIB::SINCOS_STRET_F64) != nullptr) {
1462     setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1463     setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1464   }
1465 
1466   // FP-ARMv8 implements a lot of rounding-like FP operations.
1467   if (Subtarget->hasFPARMv8Base()) {
1468     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
1469     setOperationAction(ISD::FCEIL, MVT::f32, Legal);
1470     setOperationAction(ISD::FROUND, MVT::f32, Legal);
1471     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
1472     setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
1473     setOperationAction(ISD::FRINT, MVT::f32, Legal);
1474     setOperationAction(ISD::FROUNDEVEN, MVT::f32, Legal);
1475     setOperationAction(ISD::FMINNUM, MVT::f32, Legal);
1476     setOperationAction(ISD::FMAXNUM, MVT::f32, Legal);
1477     if (Subtarget->hasNEON()) {
1478       setOperationAction(ISD::FMINNUM, MVT::v2f32, Legal);
1479       setOperationAction(ISD::FMAXNUM, MVT::v2f32, Legal);
1480       setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
1481       setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
1482     }
1483 
1484     if (Subtarget->hasFP64()) {
1485       setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
1486       setOperationAction(ISD::FCEIL, MVT::f64, Legal);
1487       setOperationAction(ISD::FROUND, MVT::f64, Legal);
1488       setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
1489       setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
1490       setOperationAction(ISD::FRINT, MVT::f64, Legal);
1491       setOperationAction(ISD::FROUNDEVEN, MVT::f64, Legal);
1492       setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
1493       setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
1494     }
1495   }
1496 
1497   // FP16 often need to be promoted to call lib functions
1498   if (Subtarget->hasFullFP16()) {
1499     setOperationAction(ISD::FREM, MVT::f16, Promote);
1500     setOperationAction(ISD::FCOPYSIGN, MVT::f16, Expand);
1501     setOperationAction(ISD::FSIN, MVT::f16, Promote);
1502     setOperationAction(ISD::FCOS, MVT::f16, Promote);
1503     setOperationAction(ISD::FTAN, MVT::f16, Promote);
1504     setOperationAction(ISD::FSINCOS, MVT::f16, Promote);
1505     setOperationAction(ISD::FPOWI, MVT::f16, Promote);
1506     setOperationAction(ISD::FPOW, MVT::f16, Promote);
1507     setOperationAction(ISD::FEXP, MVT::f16, Promote);
1508     setOperationAction(ISD::FEXP2, MVT::f16, Promote);
1509     setOperationAction(ISD::FEXP10, MVT::f16, Promote);
1510     setOperationAction(ISD::FLOG, MVT::f16, Promote);
1511     setOperationAction(ISD::FLOG10, MVT::f16, Promote);
1512     setOperationAction(ISD::FLOG2, MVT::f16, Promote);
1513 
1514     setOperationAction(ISD::FROUND, MVT::f16, Legal);
1515     setOperationAction(ISD::FROUNDEVEN, MVT::f16, Legal);
1516     setOperationAction(ISD::FTRUNC, MVT::f16, Legal);
1517     setOperationAction(ISD::FNEARBYINT, MVT::f16, Legal);
1518     setOperationAction(ISD::FRINT, MVT::f16, Legal);
1519     setOperationAction(ISD::FFLOOR, MVT::f16, Legal);
1520     setOperationAction(ISD::FCEIL, MVT::f16, Legal);
1521   }
1522 
1523   if (Subtarget->hasNEON()) {
1524     // vmin and vmax aren't available in a scalar form, so we can use
1525     // a NEON instruction with an undef lane instead.
1526     setOperationAction(ISD::FMINIMUM, MVT::f32, Legal);
1527     setOperationAction(ISD::FMAXIMUM, MVT::f32, Legal);
1528     setOperationAction(ISD::FMINIMUM, MVT::f16, Legal);
1529     setOperationAction(ISD::FMAXIMUM, MVT::f16, Legal);
1530     setOperationAction(ISD::FMINIMUM, MVT::v2f32, Legal);
1531     setOperationAction(ISD::FMAXIMUM, MVT::v2f32, Legal);
1532     setOperationAction(ISD::FMINIMUM, MVT::v4f32, Legal);
1533     setOperationAction(ISD::FMAXIMUM, MVT::v4f32, Legal);
1534 
1535     if (Subtarget->hasV8Ops()) {
1536       setOperationAction(ISD::FFLOOR, MVT::v2f32, Legal);
1537       setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
1538       setOperationAction(ISD::FROUND, MVT::v2f32, Legal);
1539       setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
1540       setOperationAction(ISD::FROUNDEVEN, MVT::v2f32, Legal);
1541       setOperationAction(ISD::FROUNDEVEN, MVT::v4f32, Legal);
1542       setOperationAction(ISD::FCEIL, MVT::v2f32, Legal);
1543       setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
1544       setOperationAction(ISD::FTRUNC, MVT::v2f32, Legal);
1545       setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
1546       setOperationAction(ISD::FRINT, MVT::v2f32, Legal);
1547       setOperationAction(ISD::FRINT, MVT::v4f32, Legal);
1548     }
1549 
1550     if (Subtarget->hasFullFP16()) {
1551       setOperationAction(ISD::FMINNUM, MVT::v4f16, Legal);
1552       setOperationAction(ISD::FMAXNUM, MVT::v4f16, Legal);
1553       setOperationAction(ISD::FMINNUM, MVT::v8f16, Legal);
1554       setOperationAction(ISD::FMAXNUM, MVT::v8f16, Legal);
1555 
1556       setOperationAction(ISD::FMINIMUM, MVT::v4f16, Legal);
1557       setOperationAction(ISD::FMAXIMUM, MVT::v4f16, Legal);
1558       setOperationAction(ISD::FMINIMUM, MVT::v8f16, Legal);
1559       setOperationAction(ISD::FMAXIMUM, MVT::v8f16, Legal);
1560 
1561       setOperationAction(ISD::FFLOOR, MVT::v4f16, Legal);
1562       setOperationAction(ISD::FFLOOR, MVT::v8f16, Legal);
1563       setOperationAction(ISD::FROUND, MVT::v4f16, Legal);
1564       setOperationAction(ISD::FROUND, MVT::v8f16, Legal);
1565       setOperationAction(ISD::FROUNDEVEN, MVT::v4f16, Legal);
1566       setOperationAction(ISD::FROUNDEVEN, MVT::v8f16, Legal);
1567       setOperationAction(ISD::FCEIL, MVT::v4f16, Legal);
1568       setOperationAction(ISD::FCEIL, MVT::v8f16, Legal);
1569       setOperationAction(ISD::FTRUNC, MVT::v4f16, Legal);
1570       setOperationAction(ISD::FTRUNC, MVT::v8f16, Legal);
1571       setOperationAction(ISD::FRINT, MVT::v4f16, Legal);
1572       setOperationAction(ISD::FRINT, MVT::v8f16, Legal);
1573     }
1574   }
1575 
1576   // On MSVC, both 32-bit and 64-bit, ldexpf(f32) is not defined.  MinGW has
1577   // it, but it's just a wrapper around ldexp.
1578   if (TT.isOSWindows()) {
1579     for (ISD::NodeType Op : {ISD::FLDEXP, ISD::STRICT_FLDEXP, ISD::FFREXP})
1580       if (isOperationExpand(Op, MVT::f32))
1581         setOperationAction(Op, MVT::f32, Promote);
1582   }
1583 
1584   // LegalizeDAG currently can't expand fp16 LDEXP/FREXP on targets where i16
1585   // isn't legal.
1586   for (ISD::NodeType Op : {ISD::FLDEXP, ISD::STRICT_FLDEXP, ISD::FFREXP})
1587     if (isOperationExpand(Op, MVT::f16))
1588       setOperationAction(Op, MVT::f16, Promote);
1589 
1590   // We have target-specific dag combine patterns for the following nodes:
1591   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
1592   setTargetDAGCombine(
1593       {ISD::ADD, ISD::SUB, ISD::MUL, ISD::AND, ISD::OR, ISD::XOR});
1594 
1595   if (Subtarget->hasMVEIntegerOps())
1596     setTargetDAGCombine(ISD::VSELECT);
1597 
1598   if (Subtarget->hasV6Ops())
1599     setTargetDAGCombine(ISD::SRL);
1600   if (Subtarget->isThumb1Only())
1601     setTargetDAGCombine(ISD::SHL);
1602   // Attempt to lower smin/smax to ssat/usat
1603   if ((!Subtarget->isThumb() && Subtarget->hasV6Ops()) ||
1604       Subtarget->isThumb2()) {
1605     setTargetDAGCombine({ISD::SMIN, ISD::SMAX});
1606   }
1607 
1608   setStackPointerRegisterToSaveRestore(ARM::SP);
1609 
1610   if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() ||
1611       !Subtarget->hasVFP2Base() || Subtarget->hasMinSize())
1612     setSchedulingPreference(Sched::RegPressure);
1613   else
1614     setSchedulingPreference(Sched::Hybrid);
1615 
1616   //// temporary - rewrite interface to use type
1617   MaxStoresPerMemset = 8;
1618   MaxStoresPerMemsetOptSize = 4;
1619   MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
1620   MaxStoresPerMemcpyOptSize = 2;
1621   MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
1622   MaxStoresPerMemmoveOptSize = 2;
1623 
1624   // On ARM arguments smaller than 4 bytes are extended, so all arguments
1625   // are at least 4 bytes aligned.
1626   setMinStackArgumentAlignment(Align(4));
1627 
1628   // Prefer likely predicted branches to selects on out-of-order cores.
1629   PredictableSelectIsExpensive = Subtarget->getSchedModel().isOutOfOrder();
1630 
1631   setPrefLoopAlignment(Align(1ULL << Subtarget->getPreferBranchLogAlignment()));
1632   setPrefFunctionAlignment(
1633       Align(1ULL << Subtarget->getPreferBranchLogAlignment()));
1634 
1635   setMinFunctionAlignment(Subtarget->isThumb() ? Align(2) : Align(4));
1636 }
1637 
useSoftFloat() const1638 bool ARMTargetLowering::useSoftFloat() const {
1639   return Subtarget->useSoftFloat();
1640 }
1641 
1642 // FIXME: It might make sense to define the representative register class as the
1643 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
1644 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
1645 // SPR's representative would be DPR_VFP2. This should work well if register
1646 // pressure tracking were modified such that a register use would increment the
1647 // pressure of the register class's representative and all of it's super
1648 // classes' representatives transitively. We have not implemented this because
1649 // of the difficulty prior to coalescing of modeling operand register classes
1650 // due to the common occurrence of cross class copies and subregister insertions
1651 // and extractions.
1652 std::pair<const TargetRegisterClass *, uint8_t>
findRepresentativeClass(const TargetRegisterInfo * TRI,MVT VT) const1653 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1654                                            MVT VT) const {
1655   const TargetRegisterClass *RRC = nullptr;
1656   uint8_t Cost = 1;
1657   switch (VT.SimpleTy) {
1658   default:
1659     return TargetLowering::findRepresentativeClass(TRI, VT);
1660   // Use DPR as representative register class for all floating point
1661   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
1662   // the cost is 1 for both f32 and f64.
1663   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
1664   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
1665     RRC = &ARM::DPRRegClass;
1666     // When NEON is used for SP, only half of the register file is available
1667     // because operations that define both SP and DP results will be constrained
1668     // to the VFP2 class (D0-D15). We currently model this constraint prior to
1669     // coalescing by double-counting the SP regs. See the FIXME above.
1670     if (Subtarget->useNEONForSinglePrecisionFP())
1671       Cost = 2;
1672     break;
1673   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1674   case MVT::v4f32: case MVT::v2f64:
1675     RRC = &ARM::DPRRegClass;
1676     Cost = 2;
1677     break;
1678   case MVT::v4i64:
1679     RRC = &ARM::DPRRegClass;
1680     Cost = 4;
1681     break;
1682   case MVT::v8i64:
1683     RRC = &ARM::DPRRegClass;
1684     Cost = 8;
1685     break;
1686   }
1687   return std::make_pair(RRC, Cost);
1688 }
1689 
getTargetNodeName(unsigned Opcode) const1690 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1691 #define MAKE_CASE(V)                                                           \
1692   case V:                                                                      \
1693     return #V;
1694   switch ((ARMISD::NodeType)Opcode) {
1695   case ARMISD::FIRST_NUMBER:
1696     break;
1697     MAKE_CASE(ARMISD::Wrapper)
1698     MAKE_CASE(ARMISD::WrapperPIC)
1699     MAKE_CASE(ARMISD::WrapperJT)
1700     MAKE_CASE(ARMISD::COPY_STRUCT_BYVAL)
1701     MAKE_CASE(ARMISD::CALL)
1702     MAKE_CASE(ARMISD::CALL_PRED)
1703     MAKE_CASE(ARMISD::CALL_NOLINK)
1704     MAKE_CASE(ARMISD::tSECALL)
1705     MAKE_CASE(ARMISD::t2CALL_BTI)
1706     MAKE_CASE(ARMISD::BRCOND)
1707     MAKE_CASE(ARMISD::BR_JT)
1708     MAKE_CASE(ARMISD::BR2_JT)
1709     MAKE_CASE(ARMISD::RET_GLUE)
1710     MAKE_CASE(ARMISD::SERET_GLUE)
1711     MAKE_CASE(ARMISD::INTRET_GLUE)
1712     MAKE_CASE(ARMISD::PIC_ADD)
1713     MAKE_CASE(ARMISD::CMP)
1714     MAKE_CASE(ARMISD::CMN)
1715     MAKE_CASE(ARMISD::CMPZ)
1716     MAKE_CASE(ARMISD::CMPFP)
1717     MAKE_CASE(ARMISD::CMPFPE)
1718     MAKE_CASE(ARMISD::CMPFPw0)
1719     MAKE_CASE(ARMISD::CMPFPEw0)
1720     MAKE_CASE(ARMISD::BCC_i64)
1721     MAKE_CASE(ARMISD::FMSTAT)
1722     MAKE_CASE(ARMISD::CMOV)
1723     MAKE_CASE(ARMISD::SSAT)
1724     MAKE_CASE(ARMISD::USAT)
1725     MAKE_CASE(ARMISD::ASRL)
1726     MAKE_CASE(ARMISD::LSRL)
1727     MAKE_CASE(ARMISD::LSLL)
1728     MAKE_CASE(ARMISD::LSLS)
1729     MAKE_CASE(ARMISD::LSRS1)
1730     MAKE_CASE(ARMISD::ASRS1)
1731     MAKE_CASE(ARMISD::RRX)
1732     MAKE_CASE(ARMISD::ADDC)
1733     MAKE_CASE(ARMISD::ADDE)
1734     MAKE_CASE(ARMISD::SUBC)
1735     MAKE_CASE(ARMISD::SUBE)
1736     MAKE_CASE(ARMISD::VMOVRRD)
1737     MAKE_CASE(ARMISD::VMOVDRR)
1738     MAKE_CASE(ARMISD::VMOVhr)
1739     MAKE_CASE(ARMISD::VMOVrh)
1740     MAKE_CASE(ARMISD::VMOVSR)
1741     MAKE_CASE(ARMISD::EH_SJLJ_SETJMP)
1742     MAKE_CASE(ARMISD::EH_SJLJ_LONGJMP)
1743     MAKE_CASE(ARMISD::EH_SJLJ_SETUP_DISPATCH)
1744     MAKE_CASE(ARMISD::TC_RETURN)
1745     MAKE_CASE(ARMISD::THREAD_POINTER)
1746     MAKE_CASE(ARMISD::DYN_ALLOC)
1747     MAKE_CASE(ARMISD::MEMBARRIER_MCR)
1748     MAKE_CASE(ARMISD::PRELOAD)
1749     MAKE_CASE(ARMISD::LDRD)
1750     MAKE_CASE(ARMISD::STRD)
1751     MAKE_CASE(ARMISD::WIN__CHKSTK)
1752     MAKE_CASE(ARMISD::WIN__DBZCHK)
1753     MAKE_CASE(ARMISD::PREDICATE_CAST)
1754     MAKE_CASE(ARMISD::VECTOR_REG_CAST)
1755     MAKE_CASE(ARMISD::MVESEXT)
1756     MAKE_CASE(ARMISD::MVEZEXT)
1757     MAKE_CASE(ARMISD::MVETRUNC)
1758     MAKE_CASE(ARMISD::VCMP)
1759     MAKE_CASE(ARMISD::VCMPZ)
1760     MAKE_CASE(ARMISD::VTST)
1761     MAKE_CASE(ARMISD::VSHLs)
1762     MAKE_CASE(ARMISD::VSHLu)
1763     MAKE_CASE(ARMISD::VSHLIMM)
1764     MAKE_CASE(ARMISD::VSHRsIMM)
1765     MAKE_CASE(ARMISD::VSHRuIMM)
1766     MAKE_CASE(ARMISD::VRSHRsIMM)
1767     MAKE_CASE(ARMISD::VRSHRuIMM)
1768     MAKE_CASE(ARMISD::VRSHRNIMM)
1769     MAKE_CASE(ARMISD::VQSHLsIMM)
1770     MAKE_CASE(ARMISD::VQSHLuIMM)
1771     MAKE_CASE(ARMISD::VQSHLsuIMM)
1772     MAKE_CASE(ARMISD::VQSHRNsIMM)
1773     MAKE_CASE(ARMISD::VQSHRNuIMM)
1774     MAKE_CASE(ARMISD::VQSHRNsuIMM)
1775     MAKE_CASE(ARMISD::VQRSHRNsIMM)
1776     MAKE_CASE(ARMISD::VQRSHRNuIMM)
1777     MAKE_CASE(ARMISD::VQRSHRNsuIMM)
1778     MAKE_CASE(ARMISD::VSLIIMM)
1779     MAKE_CASE(ARMISD::VSRIIMM)
1780     MAKE_CASE(ARMISD::VGETLANEu)
1781     MAKE_CASE(ARMISD::VGETLANEs)
1782     MAKE_CASE(ARMISD::VMOVIMM)
1783     MAKE_CASE(ARMISD::VMVNIMM)
1784     MAKE_CASE(ARMISD::VMOVFPIMM)
1785     MAKE_CASE(ARMISD::VDUP)
1786     MAKE_CASE(ARMISD::VDUPLANE)
1787     MAKE_CASE(ARMISD::VEXT)
1788     MAKE_CASE(ARMISD::VREV64)
1789     MAKE_CASE(ARMISD::VREV32)
1790     MAKE_CASE(ARMISD::VREV16)
1791     MAKE_CASE(ARMISD::VZIP)
1792     MAKE_CASE(ARMISD::VUZP)
1793     MAKE_CASE(ARMISD::VTRN)
1794     MAKE_CASE(ARMISD::VTBL1)
1795     MAKE_CASE(ARMISD::VTBL2)
1796     MAKE_CASE(ARMISD::VMOVN)
1797     MAKE_CASE(ARMISD::VQMOVNs)
1798     MAKE_CASE(ARMISD::VQMOVNu)
1799     MAKE_CASE(ARMISD::VCVTN)
1800     MAKE_CASE(ARMISD::VCVTL)
1801     MAKE_CASE(ARMISD::VIDUP)
1802     MAKE_CASE(ARMISD::VMULLs)
1803     MAKE_CASE(ARMISD::VMULLu)
1804     MAKE_CASE(ARMISD::VQDMULH)
1805     MAKE_CASE(ARMISD::VADDVs)
1806     MAKE_CASE(ARMISD::VADDVu)
1807     MAKE_CASE(ARMISD::VADDVps)
1808     MAKE_CASE(ARMISD::VADDVpu)
1809     MAKE_CASE(ARMISD::VADDLVs)
1810     MAKE_CASE(ARMISD::VADDLVu)
1811     MAKE_CASE(ARMISD::VADDLVAs)
1812     MAKE_CASE(ARMISD::VADDLVAu)
1813     MAKE_CASE(ARMISD::VADDLVps)
1814     MAKE_CASE(ARMISD::VADDLVpu)
1815     MAKE_CASE(ARMISD::VADDLVAps)
1816     MAKE_CASE(ARMISD::VADDLVApu)
1817     MAKE_CASE(ARMISD::VMLAVs)
1818     MAKE_CASE(ARMISD::VMLAVu)
1819     MAKE_CASE(ARMISD::VMLAVps)
1820     MAKE_CASE(ARMISD::VMLAVpu)
1821     MAKE_CASE(ARMISD::VMLALVs)
1822     MAKE_CASE(ARMISD::VMLALVu)
1823     MAKE_CASE(ARMISD::VMLALVps)
1824     MAKE_CASE(ARMISD::VMLALVpu)
1825     MAKE_CASE(ARMISD::VMLALVAs)
1826     MAKE_CASE(ARMISD::VMLALVAu)
1827     MAKE_CASE(ARMISD::VMLALVAps)
1828     MAKE_CASE(ARMISD::VMLALVApu)
1829     MAKE_CASE(ARMISD::VMINVu)
1830     MAKE_CASE(ARMISD::VMINVs)
1831     MAKE_CASE(ARMISD::VMAXVu)
1832     MAKE_CASE(ARMISD::VMAXVs)
1833     MAKE_CASE(ARMISD::UMAAL)
1834     MAKE_CASE(ARMISD::UMLAL)
1835     MAKE_CASE(ARMISD::SMLAL)
1836     MAKE_CASE(ARMISD::SMLALBB)
1837     MAKE_CASE(ARMISD::SMLALBT)
1838     MAKE_CASE(ARMISD::SMLALTB)
1839     MAKE_CASE(ARMISD::SMLALTT)
1840     MAKE_CASE(ARMISD::SMULWB)
1841     MAKE_CASE(ARMISD::SMULWT)
1842     MAKE_CASE(ARMISD::SMLALD)
1843     MAKE_CASE(ARMISD::SMLALDX)
1844     MAKE_CASE(ARMISD::SMLSLD)
1845     MAKE_CASE(ARMISD::SMLSLDX)
1846     MAKE_CASE(ARMISD::SMMLAR)
1847     MAKE_CASE(ARMISD::SMMLSR)
1848     MAKE_CASE(ARMISD::QADD16b)
1849     MAKE_CASE(ARMISD::QSUB16b)
1850     MAKE_CASE(ARMISD::QADD8b)
1851     MAKE_CASE(ARMISD::QSUB8b)
1852     MAKE_CASE(ARMISD::UQADD16b)
1853     MAKE_CASE(ARMISD::UQSUB16b)
1854     MAKE_CASE(ARMISD::UQADD8b)
1855     MAKE_CASE(ARMISD::UQSUB8b)
1856     MAKE_CASE(ARMISD::BUILD_VECTOR)
1857     MAKE_CASE(ARMISD::BFI)
1858     MAKE_CASE(ARMISD::VORRIMM)
1859     MAKE_CASE(ARMISD::VBICIMM)
1860     MAKE_CASE(ARMISD::VBSP)
1861     MAKE_CASE(ARMISD::MEMCPY)
1862     MAKE_CASE(ARMISD::VLD1DUP)
1863     MAKE_CASE(ARMISD::VLD2DUP)
1864     MAKE_CASE(ARMISD::VLD3DUP)
1865     MAKE_CASE(ARMISD::VLD4DUP)
1866     MAKE_CASE(ARMISD::VLD1_UPD)
1867     MAKE_CASE(ARMISD::VLD2_UPD)
1868     MAKE_CASE(ARMISD::VLD3_UPD)
1869     MAKE_CASE(ARMISD::VLD4_UPD)
1870     MAKE_CASE(ARMISD::VLD1x2_UPD)
1871     MAKE_CASE(ARMISD::VLD1x3_UPD)
1872     MAKE_CASE(ARMISD::VLD1x4_UPD)
1873     MAKE_CASE(ARMISD::VLD2LN_UPD)
1874     MAKE_CASE(ARMISD::VLD3LN_UPD)
1875     MAKE_CASE(ARMISD::VLD4LN_UPD)
1876     MAKE_CASE(ARMISD::VLD1DUP_UPD)
1877     MAKE_CASE(ARMISD::VLD2DUP_UPD)
1878     MAKE_CASE(ARMISD::VLD3DUP_UPD)
1879     MAKE_CASE(ARMISD::VLD4DUP_UPD)
1880     MAKE_CASE(ARMISD::VST1_UPD)
1881     MAKE_CASE(ARMISD::VST2_UPD)
1882     MAKE_CASE(ARMISD::VST3_UPD)
1883     MAKE_CASE(ARMISD::VST4_UPD)
1884     MAKE_CASE(ARMISD::VST1x2_UPD)
1885     MAKE_CASE(ARMISD::VST1x3_UPD)
1886     MAKE_CASE(ARMISD::VST1x4_UPD)
1887     MAKE_CASE(ARMISD::VST2LN_UPD)
1888     MAKE_CASE(ARMISD::VST3LN_UPD)
1889     MAKE_CASE(ARMISD::VST4LN_UPD)
1890     MAKE_CASE(ARMISD::WLS)
1891     MAKE_CASE(ARMISD::WLSSETUP)
1892     MAKE_CASE(ARMISD::LE)
1893     MAKE_CASE(ARMISD::LOOP_DEC)
1894     MAKE_CASE(ARMISD::CSINV)
1895     MAKE_CASE(ARMISD::CSNEG)
1896     MAKE_CASE(ARMISD::CSINC)
1897     MAKE_CASE(ARMISD::MEMCPYLOOP)
1898     MAKE_CASE(ARMISD::MEMSETLOOP)
1899 #undef MAKE_CASE
1900   }
1901   return nullptr;
1902 }
1903 
getSetCCResultType(const DataLayout & DL,LLVMContext &,EVT VT) const1904 EVT ARMTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1905                                           EVT VT) const {
1906   if (!VT.isVector())
1907     return getPointerTy(DL);
1908 
1909   // MVE has a predicate register.
1910   if ((Subtarget->hasMVEIntegerOps() &&
1911        (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
1912         VT == MVT::v16i8)) ||
1913       (Subtarget->hasMVEFloatOps() &&
1914        (VT == MVT::v2f64 || VT == MVT::v4f32 || VT == MVT::v8f16)))
1915     return MVT::getVectorVT(MVT::i1, VT.getVectorElementCount());
1916   return VT.changeVectorElementTypeToInteger();
1917 }
1918 
1919 /// getRegClassFor - Return the register class that should be used for the
1920 /// specified value type.
1921 const TargetRegisterClass *
getRegClassFor(MVT VT,bool isDivergent) const1922 ARMTargetLowering::getRegClassFor(MVT VT, bool isDivergent) const {
1923   (void)isDivergent;
1924   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1925   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1926   // load / store 4 to 8 consecutive NEON D registers, or 2 to 4 consecutive
1927   // MVE Q registers.
1928   if (Subtarget->hasNEON()) {
1929     if (VT == MVT::v4i64)
1930       return &ARM::QQPRRegClass;
1931     if (VT == MVT::v8i64)
1932       return &ARM::QQQQPRRegClass;
1933   }
1934   if (Subtarget->hasMVEIntegerOps()) {
1935     if (VT == MVT::v4i64)
1936       return &ARM::MQQPRRegClass;
1937     if (VT == MVT::v8i64)
1938       return &ARM::MQQQQPRRegClass;
1939   }
1940   return TargetLowering::getRegClassFor(VT);
1941 }
1942 
1943 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the
1944 // source/dest is aligned and the copy size is large enough. We therefore want
1945 // to align such objects passed to memory intrinsics.
shouldAlignPointerArgs(CallInst * CI,unsigned & MinSize,Align & PrefAlign) const1946 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize,
1947                                                Align &PrefAlign) const {
1948   if (!isa<MemIntrinsic>(CI))
1949     return false;
1950   MinSize = 8;
1951   // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1
1952   // cycle faster than 4-byte aligned LDM.
1953   PrefAlign =
1954       (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? Align(8) : Align(4));
1955   return true;
1956 }
1957 
1958 // Create a fast isel object.
1959 FastISel *
createFastISel(FunctionLoweringInfo & funcInfo,const TargetLibraryInfo * libInfo) const1960 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1961                                   const TargetLibraryInfo *libInfo) const {
1962   return ARM::createFastISel(funcInfo, libInfo);
1963 }
1964 
getSchedulingPreference(SDNode * N) const1965 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1966   unsigned NumVals = N->getNumValues();
1967   if (!NumVals)
1968     return Sched::RegPressure;
1969 
1970   for (unsigned i = 0; i != NumVals; ++i) {
1971     EVT VT = N->getValueType(i);
1972     if (VT == MVT::Glue || VT == MVT::Other)
1973       continue;
1974     if (VT.isFloatingPoint() || VT.isVector())
1975       return Sched::ILP;
1976   }
1977 
1978   if (!N->isMachineOpcode())
1979     return Sched::RegPressure;
1980 
1981   // Load are scheduled for latency even if there instruction itinerary
1982   // is not available.
1983   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1984   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1985 
1986   if (MCID.getNumDefs() == 0)
1987     return Sched::RegPressure;
1988   if (!Itins->isEmpty() &&
1989       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2U)
1990     return Sched::ILP;
1991 
1992   return Sched::RegPressure;
1993 }
1994 
1995 //===----------------------------------------------------------------------===//
1996 // Lowering Code
1997 //===----------------------------------------------------------------------===//
1998 
isSRL16(const SDValue & Op)1999 static bool isSRL16(const SDValue &Op) {
2000   if (Op.getOpcode() != ISD::SRL)
2001     return false;
2002   if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
2003     return Const->getZExtValue() == 16;
2004   return false;
2005 }
2006 
isSRA16(const SDValue & Op)2007 static bool isSRA16(const SDValue &Op) {
2008   if (Op.getOpcode() != ISD::SRA)
2009     return false;
2010   if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
2011     return Const->getZExtValue() == 16;
2012   return false;
2013 }
2014 
isSHL16(const SDValue & Op)2015 static bool isSHL16(const SDValue &Op) {
2016   if (Op.getOpcode() != ISD::SHL)
2017     return false;
2018   if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
2019     return Const->getZExtValue() == 16;
2020   return false;
2021 }
2022 
2023 // Check for a signed 16-bit value. We special case SRA because it makes it
2024 // more simple when also looking for SRAs that aren't sign extending a
2025 // smaller value. Without the check, we'd need to take extra care with
2026 // checking order for some operations.
isS16(const SDValue & Op,SelectionDAG & DAG)2027 static bool isS16(const SDValue &Op, SelectionDAG &DAG) {
2028   if (isSRA16(Op))
2029     return isSHL16(Op.getOperand(0));
2030   return DAG.ComputeNumSignBits(Op) == 17;
2031 }
2032 
2033 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
IntCCToARMCC(ISD::CondCode CC)2034 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
2035   switch (CC) {
2036   default: llvm_unreachable("Unknown condition code!");
2037   case ISD::SETNE:  return ARMCC::NE;
2038   case ISD::SETEQ:  return ARMCC::EQ;
2039   case ISD::SETGT:  return ARMCC::GT;
2040   case ISD::SETGE:  return ARMCC::GE;
2041   case ISD::SETLT:  return ARMCC::LT;
2042   case ISD::SETLE:  return ARMCC::LE;
2043   case ISD::SETUGT: return ARMCC::HI;
2044   case ISD::SETUGE: return ARMCC::HS;
2045   case ISD::SETULT: return ARMCC::LO;
2046   case ISD::SETULE: return ARMCC::LS;
2047   }
2048 }
2049 
2050 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
FPCCToARMCC(ISD::CondCode CC,ARMCC::CondCodes & CondCode,ARMCC::CondCodes & CondCode2)2051 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
2052                         ARMCC::CondCodes &CondCode2) {
2053   CondCode2 = ARMCC::AL;
2054   switch (CC) {
2055   default: llvm_unreachable("Unknown FP condition!");
2056   case ISD::SETEQ:
2057   case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
2058   case ISD::SETGT:
2059   case ISD::SETOGT: CondCode = ARMCC::GT; break;
2060   case ISD::SETGE:
2061   case ISD::SETOGE: CondCode = ARMCC::GE; break;
2062   case ISD::SETOLT: CondCode = ARMCC::MI; break;
2063   case ISD::SETOLE: CondCode = ARMCC::LS; break;
2064   case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
2065   case ISD::SETO:   CondCode = ARMCC::VC; break;
2066   case ISD::SETUO:  CondCode = ARMCC::VS; break;
2067   case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
2068   case ISD::SETUGT: CondCode = ARMCC::HI; break;
2069   case ISD::SETUGE: CondCode = ARMCC::PL; break;
2070   case ISD::SETLT:
2071   case ISD::SETULT: CondCode = ARMCC::LT; break;
2072   case ISD::SETLE:
2073   case ISD::SETULE: CondCode = ARMCC::LE; break;
2074   case ISD::SETNE:
2075   case ISD::SETUNE: CondCode = ARMCC::NE; break;
2076   }
2077 }
2078 
2079 //===----------------------------------------------------------------------===//
2080 //                      Calling Convention Implementation
2081 //===----------------------------------------------------------------------===//
2082 
2083 /// getEffectiveCallingConv - Get the effective calling convention, taking into
2084 /// account presence of floating point hardware and calling convention
2085 /// limitations, such as support for variadic functions.
2086 CallingConv::ID
getEffectiveCallingConv(CallingConv::ID CC,bool isVarArg) const2087 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
2088                                            bool isVarArg) const {
2089   switch (CC) {
2090   default:
2091     report_fatal_error("Unsupported calling convention");
2092   case CallingConv::ARM_AAPCS:
2093   case CallingConv::ARM_APCS:
2094   case CallingConv::GHC:
2095   case CallingConv::CFGuard_Check:
2096     return CC;
2097   case CallingConv::PreserveMost:
2098     return CallingConv::PreserveMost;
2099   case CallingConv::PreserveAll:
2100     return CallingConv::PreserveAll;
2101   case CallingConv::ARM_AAPCS_VFP:
2102   case CallingConv::Swift:
2103   case CallingConv::SwiftTail:
2104     return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
2105   case CallingConv::C:
2106   case CallingConv::Tail:
2107     if (!getTM().isAAPCS_ABI())
2108       return CallingConv::ARM_APCS;
2109     else if (Subtarget->hasFPRegs() && !Subtarget->isThumb1Only() &&
2110              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
2111              !isVarArg)
2112       return CallingConv::ARM_AAPCS_VFP;
2113     else
2114       return CallingConv::ARM_AAPCS;
2115   case CallingConv::Fast:
2116   case CallingConv::CXX_FAST_TLS:
2117     if (!getTM().isAAPCS_ABI()) {
2118       if (Subtarget->hasVFP2Base() && !Subtarget->isThumb1Only() && !isVarArg)
2119         return CallingConv::Fast;
2120       return CallingConv::ARM_APCS;
2121     } else if (Subtarget->hasVFP2Base() && !Subtarget->isThumb1Only() &&
2122                !isVarArg)
2123       return CallingConv::ARM_AAPCS_VFP;
2124     else
2125       return CallingConv::ARM_AAPCS;
2126   }
2127 }
2128 
CCAssignFnForCall(CallingConv::ID CC,bool isVarArg) const2129 CCAssignFn *ARMTargetLowering::CCAssignFnForCall(CallingConv::ID CC,
2130                                                  bool isVarArg) const {
2131   return CCAssignFnForNode(CC, false, isVarArg);
2132 }
2133 
CCAssignFnForReturn(CallingConv::ID CC,bool isVarArg) const2134 CCAssignFn *ARMTargetLowering::CCAssignFnForReturn(CallingConv::ID CC,
2135                                                    bool isVarArg) const {
2136   return CCAssignFnForNode(CC, true, isVarArg);
2137 }
2138 
2139 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
2140 /// CallingConvention.
CCAssignFnForNode(CallingConv::ID CC,bool Return,bool isVarArg) const2141 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
2142                                                  bool Return,
2143                                                  bool isVarArg) const {
2144   switch (getEffectiveCallingConv(CC, isVarArg)) {
2145   default:
2146     report_fatal_error("Unsupported calling convention");
2147   case CallingConv::ARM_APCS:
2148     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
2149   case CallingConv::ARM_AAPCS:
2150     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
2151   case CallingConv::ARM_AAPCS_VFP:
2152     return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
2153   case CallingConv::Fast:
2154     return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
2155   case CallingConv::GHC:
2156     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
2157   case CallingConv::PreserveMost:
2158     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
2159   case CallingConv::PreserveAll:
2160     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
2161   case CallingConv::CFGuard_Check:
2162     return (Return ? RetCC_ARM_AAPCS : CC_ARM_Win32_CFGuard_Check);
2163   }
2164 }
2165 
MoveToHPR(const SDLoc & dl,SelectionDAG & DAG,MVT LocVT,MVT ValVT,SDValue Val) const2166 SDValue ARMTargetLowering::MoveToHPR(const SDLoc &dl, SelectionDAG &DAG,
2167                                      MVT LocVT, MVT ValVT, SDValue Val) const {
2168   Val = DAG.getNode(ISD::BITCAST, dl, MVT::getIntegerVT(LocVT.getSizeInBits()),
2169                     Val);
2170   if (Subtarget->hasFullFP16()) {
2171     Val = DAG.getNode(ARMISD::VMOVhr, dl, ValVT, Val);
2172   } else {
2173     Val = DAG.getNode(ISD::TRUNCATE, dl,
2174                       MVT::getIntegerVT(ValVT.getSizeInBits()), Val);
2175     Val = DAG.getNode(ISD::BITCAST, dl, ValVT, Val);
2176   }
2177   return Val;
2178 }
2179 
MoveFromHPR(const SDLoc & dl,SelectionDAG & DAG,MVT LocVT,MVT ValVT,SDValue Val) const2180 SDValue ARMTargetLowering::MoveFromHPR(const SDLoc &dl, SelectionDAG &DAG,
2181                                        MVT LocVT, MVT ValVT,
2182                                        SDValue Val) const {
2183   if (Subtarget->hasFullFP16()) {
2184     Val = DAG.getNode(ARMISD::VMOVrh, dl,
2185                       MVT::getIntegerVT(LocVT.getSizeInBits()), Val);
2186   } else {
2187     Val = DAG.getNode(ISD::BITCAST, dl,
2188                       MVT::getIntegerVT(ValVT.getSizeInBits()), Val);
2189     Val = DAG.getNode(ISD::ZERO_EXTEND, dl,
2190                       MVT::getIntegerVT(LocVT.getSizeInBits()), Val);
2191   }
2192   return DAG.getNode(ISD::BITCAST, dl, LocVT, Val);
2193 }
2194 
2195 /// LowerCallResult - Lower the result values of a call into the
2196 /// appropriate copies out of appropriate physical registers.
LowerCallResult(SDValue Chain,SDValue InGlue,CallingConv::ID CallConv,bool isVarArg,const SmallVectorImpl<ISD::InputArg> & Ins,const SDLoc & dl,SelectionDAG & DAG,SmallVectorImpl<SDValue> & InVals,bool isThisReturn,SDValue ThisVal,bool isCmseNSCall) const2197 SDValue ARMTargetLowering::LowerCallResult(
2198     SDValue Chain, SDValue InGlue, CallingConv::ID CallConv, bool isVarArg,
2199     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
2200     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
2201     SDValue ThisVal, bool isCmseNSCall) const {
2202   // Assign locations to each value returned by this call.
2203   SmallVector<CCValAssign, 16> RVLocs;
2204   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2205                  *DAG.getContext());
2206   CCInfo.AnalyzeCallResult(Ins, CCAssignFnForReturn(CallConv, isVarArg));
2207 
2208   // Copy all of the result registers out of their specified physreg.
2209   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2210     CCValAssign VA = RVLocs[i];
2211 
2212     // Pass 'this' value directly from the argument to return value, to avoid
2213     // reg unit interference
2214     if (i == 0 && isThisReturn) {
2215       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
2216              "unexpected return calling convention register assignment");
2217       InVals.push_back(ThisVal);
2218       continue;
2219     }
2220 
2221     SDValue Val;
2222     if (VA.needsCustom() &&
2223         (VA.getLocVT() == MVT::f64 || VA.getLocVT() == MVT::v2f64)) {
2224       // Handle f64 or half of a v2f64.
2225       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
2226                                       InGlue);
2227       Chain = Lo.getValue(1);
2228       InGlue = Lo.getValue(2);
2229       VA = RVLocs[++i]; // skip ahead to next loc
2230       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
2231                                       InGlue);
2232       Chain = Hi.getValue(1);
2233       InGlue = Hi.getValue(2);
2234       if (!Subtarget->isLittle())
2235         std::swap (Lo, Hi);
2236       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
2237 
2238       if (VA.getLocVT() == MVT::v2f64) {
2239         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
2240         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
2241                           DAG.getConstant(0, dl, MVT::i32));
2242 
2243         VA = RVLocs[++i]; // skip ahead to next loc
2244         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InGlue);
2245         Chain = Lo.getValue(1);
2246         InGlue = Lo.getValue(2);
2247         VA = RVLocs[++i]; // skip ahead to next loc
2248         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InGlue);
2249         Chain = Hi.getValue(1);
2250         InGlue = Hi.getValue(2);
2251         if (!Subtarget->isLittle())
2252           std::swap (Lo, Hi);
2253         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
2254         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
2255                           DAG.getConstant(1, dl, MVT::i32));
2256       }
2257     } else {
2258       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
2259                                InGlue);
2260       Chain = Val.getValue(1);
2261       InGlue = Val.getValue(2);
2262     }
2263 
2264     switch (VA.getLocInfo()) {
2265     default: llvm_unreachable("Unknown loc info!");
2266     case CCValAssign::Full: break;
2267     case CCValAssign::BCvt:
2268       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
2269       break;
2270     }
2271 
2272     // f16 arguments have their size extended to 4 bytes and passed as if they
2273     // had been copied to the LSBs of a 32-bit register.
2274     // For that, it's passed extended to i32 (soft ABI) or to f32 (hard ABI)
2275     if (VA.needsCustom() &&
2276         (VA.getValVT() == MVT::f16 || VA.getValVT() == MVT::bf16))
2277       Val = MoveToHPR(dl, DAG, VA.getLocVT(), VA.getValVT(), Val);
2278 
2279     // On CMSE Non-secure Calls, call results (returned values) whose bitwidth
2280     // is less than 32 bits must be sign- or zero-extended after the call for
2281     // security reasons. Although the ABI mandates an extension done by the
2282     // callee, the latter cannot be trusted to follow the rules of the ABI.
2283     const ISD::InputArg &Arg = Ins[VA.getValNo()];
2284     if (isCmseNSCall && Arg.ArgVT.isScalarInteger() &&
2285         VA.getLocVT().isScalarInteger() && Arg.ArgVT.bitsLT(MVT::i32))
2286       Val = handleCMSEValue(Val, Arg, DAG, dl);
2287 
2288     InVals.push_back(Val);
2289   }
2290 
2291   return Chain;
2292 }
2293 
computeAddrForCallArg(const SDLoc & dl,SelectionDAG & DAG,const CCValAssign & VA,SDValue StackPtr,bool IsTailCall,int SPDiff) const2294 std::pair<SDValue, MachinePointerInfo> ARMTargetLowering::computeAddrForCallArg(
2295     const SDLoc &dl, SelectionDAG &DAG, const CCValAssign &VA, SDValue StackPtr,
2296     bool IsTailCall, int SPDiff) const {
2297   SDValue DstAddr;
2298   MachinePointerInfo DstInfo;
2299   int32_t Offset = VA.getLocMemOffset();
2300   MachineFunction &MF = DAG.getMachineFunction();
2301 
2302   if (IsTailCall) {
2303         Offset += SPDiff;
2304         auto PtrVT = getPointerTy(DAG.getDataLayout());
2305         int Size = VA.getLocVT().getFixedSizeInBits() / 8;
2306         int FI = MF.getFrameInfo().CreateFixedObject(Size, Offset, true);
2307         DstAddr = DAG.getFrameIndex(FI, PtrVT);
2308         DstInfo =
2309             MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
2310   } else {
2311         SDValue PtrOff = DAG.getIntPtrConstant(Offset, dl);
2312         DstAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2313                               StackPtr, PtrOff);
2314         DstInfo =
2315             MachinePointerInfo::getStack(DAG.getMachineFunction(), Offset);
2316   }
2317 
2318   return std::make_pair(DstAddr, DstInfo);
2319 }
2320 
2321 // Returns the type of copying which is required to set up a byval argument to
2322 // a tail-called function. This isn't needed for non-tail calls, because they
2323 // always need the equivalent of CopyOnce, but tail-calls sometimes need two to
2324 // avoid clobbering another argument (CopyViaTemp), and sometimes can be
2325 // optimised to zero copies when forwarding an argument from the caller's
2326 // caller (NoCopy).
ByValNeedsCopyForTailCall(SelectionDAG & DAG,SDValue Src,SDValue Dst,ISD::ArgFlagsTy Flags) const2327 ARMTargetLowering::ByValCopyKind ARMTargetLowering::ByValNeedsCopyForTailCall(
2328     SelectionDAG &DAG, SDValue Src, SDValue Dst, ISD::ArgFlagsTy Flags) const {
2329   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
2330   ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
2331 
2332   // Globals are always safe to copy from.
2333   if (isa<GlobalAddressSDNode>(Src) || isa<ExternalSymbolSDNode>(Src))
2334     return CopyOnce;
2335 
2336   // Can only analyse frame index nodes, conservatively assume we need a
2337   // temporary.
2338   auto *SrcFrameIdxNode = dyn_cast<FrameIndexSDNode>(Src);
2339   auto *DstFrameIdxNode = dyn_cast<FrameIndexSDNode>(Dst);
2340   if (!SrcFrameIdxNode || !DstFrameIdxNode)
2341     return CopyViaTemp;
2342 
2343   int SrcFI = SrcFrameIdxNode->getIndex();
2344   int DstFI = DstFrameIdxNode->getIndex();
2345   assert(MFI.isFixedObjectIndex(DstFI) &&
2346          "byval passed in non-fixed stack slot");
2347 
2348   int64_t SrcOffset = MFI.getObjectOffset(SrcFI);
2349   int64_t DstOffset = MFI.getObjectOffset(DstFI);
2350 
2351   // If the source is in the local frame, then the copy to the argument memory
2352   // is always valid.
2353   bool FixedSrc = MFI.isFixedObjectIndex(SrcFI);
2354   if (!FixedSrc ||
2355       (FixedSrc && SrcOffset < -(int64_t)AFI->getArgRegsSaveSize()))
2356     return CopyOnce;
2357 
2358   // In the case of byval arguments split between registers and the stack,
2359   // computeAddrForCallArg returns a FrameIndex which corresponds only to the
2360   // stack portion, but the Src SDValue will refer to the full value, including
2361   // the local stack memory that the register portion gets stored into. We only
2362   // need to compare them for equality, so normalise on the full value version.
2363   uint64_t RegSize = Flags.getByValSize() - MFI.getObjectSize(DstFI);
2364   DstOffset -= RegSize;
2365 
2366   // If the value is already in the correct location, then no copying is
2367   // needed. If not, then we need to copy via a temporary.
2368   if (SrcOffset == DstOffset)
2369     return NoCopy;
2370   else
2371     return CopyViaTemp;
2372 }
2373 
PassF64ArgInRegs(const SDLoc & dl,SelectionDAG & DAG,SDValue Chain,SDValue & Arg,RegsToPassVector & RegsToPass,CCValAssign & VA,CCValAssign & NextVA,SDValue & StackPtr,SmallVectorImpl<SDValue> & MemOpChains,bool IsTailCall,int SPDiff) const2374 void ARMTargetLowering::PassF64ArgInRegs(const SDLoc &dl, SelectionDAG &DAG,
2375                                          SDValue Chain, SDValue &Arg,
2376                                          RegsToPassVector &RegsToPass,
2377                                          CCValAssign &VA, CCValAssign &NextVA,
2378                                          SDValue &StackPtr,
2379                                          SmallVectorImpl<SDValue> &MemOpChains,
2380                                          bool IsTailCall,
2381                                          int SPDiff) const {
2382   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2383                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
2384   unsigned id = Subtarget->isLittle() ? 0 : 1;
2385   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
2386 
2387   if (NextVA.isRegLoc())
2388     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
2389   else {
2390     assert(NextVA.isMemLoc());
2391     if (!StackPtr.getNode())
2392       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP,
2393                                     getPointerTy(DAG.getDataLayout()));
2394 
2395     SDValue DstAddr;
2396     MachinePointerInfo DstInfo;
2397     std::tie(DstAddr, DstInfo) =
2398         computeAddrForCallArg(dl, DAG, NextVA, StackPtr, IsTailCall, SPDiff);
2399     MemOpChains.push_back(
2400         DAG.getStore(Chain, dl, fmrrd.getValue(1 - id), DstAddr, DstInfo));
2401   }
2402 }
2403 
canGuaranteeTCO(CallingConv::ID CC,bool GuaranteeTailCalls)2404 static bool canGuaranteeTCO(CallingConv::ID CC, bool GuaranteeTailCalls) {
2405   return (CC == CallingConv::Fast && GuaranteeTailCalls) ||
2406          CC == CallingConv::Tail || CC == CallingConv::SwiftTail;
2407 }
2408 
2409 /// LowerCall - Lowering a call into a callseq_start <-
2410 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
2411 /// nodes.
2412 SDValue
LowerCall(TargetLowering::CallLoweringInfo & CLI,SmallVectorImpl<SDValue> & InVals) const2413 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2414                              SmallVectorImpl<SDValue> &InVals) const {
2415   SelectionDAG &DAG                     = CLI.DAG;
2416   SDLoc &dl                             = CLI.DL;
2417   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2418   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2419   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2420   SDValue Chain                         = CLI.Chain;
2421   SDValue Callee                        = CLI.Callee;
2422   bool &isTailCall                      = CLI.IsTailCall;
2423   CallingConv::ID CallConv              = CLI.CallConv;
2424   bool doesNotRet                       = CLI.DoesNotReturn;
2425   bool isVarArg                         = CLI.IsVarArg;
2426 
2427   MachineFunction &MF = DAG.getMachineFunction();
2428   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2429   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
2430   MachineFunction::CallSiteInfo CSInfo;
2431   bool isStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
2432   bool isThisReturn = false;
2433   bool isCmseNSCall   = false;
2434   bool isSibCall = false;
2435   bool PreferIndirect = false;
2436   bool GuardWithBTI = false;
2437 
2438   // Analyze operands of the call, assigning locations to each operand.
2439   SmallVector<CCValAssign, 16> ArgLocs;
2440   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2441                  *DAG.getContext());
2442   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CallConv, isVarArg));
2443 
2444   // Lower 'returns_twice' calls to a pseudo-instruction.
2445   if (CLI.CB && CLI.CB->getAttributes().hasFnAttr(Attribute::ReturnsTwice) &&
2446       !Subtarget->noBTIAtReturnTwice())
2447     GuardWithBTI = AFI->branchTargetEnforcement();
2448 
2449   // Determine whether this is a non-secure function call.
2450   if (CLI.CB && CLI.CB->getAttributes().hasFnAttr("cmse_nonsecure_call"))
2451     isCmseNSCall = true;
2452 
2453   // Disable tail calls if they're not supported.
2454   if (!Subtarget->supportsTailCall())
2455     isTailCall = false;
2456 
2457   // For both the non-secure calls and the returns from a CMSE entry function,
2458   // the function needs to do some extra work after the call, or before the
2459   // return, respectively, thus it cannot end with a tail call
2460   if (isCmseNSCall || AFI->isCmseNSEntryFunction())
2461     isTailCall = false;
2462 
2463   if (isa<GlobalAddressSDNode>(Callee)) {
2464     // If we're optimizing for minimum size and the function is called three or
2465     // more times in this block, we can improve codesize by calling indirectly
2466     // as BLXr has a 16-bit encoding.
2467     auto *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal();
2468     if (CLI.CB) {
2469       auto *BB = CLI.CB->getParent();
2470       PreferIndirect = Subtarget->isThumb() && Subtarget->hasMinSize() &&
2471                        count_if(GV->users(), [&BB](const User *U) {
2472                          return isa<Instruction>(U) &&
2473                                 cast<Instruction>(U)->getParent() == BB;
2474                        }) > 2;
2475     }
2476   }
2477   if (isTailCall) {
2478     // Check if it's really possible to do a tail call.
2479     isTailCall =
2480         IsEligibleForTailCallOptimization(CLI, CCInfo, ArgLocs, PreferIndirect);
2481 
2482     if (isTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt &&
2483         CallConv != CallingConv::Tail && CallConv != CallingConv::SwiftTail)
2484       isSibCall = true;
2485 
2486     // We don't support GuaranteedTailCallOpt for ARM, only automatically
2487     // detected sibcalls.
2488     if (isTailCall)
2489       ++NumTailCalls;
2490   }
2491 
2492   if (!isTailCall && CLI.CB && CLI.CB->isMustTailCall())
2493     report_fatal_error("failed to perform tail call elimination on a call "
2494                        "site marked musttail");
2495 
2496   // Get a count of how many bytes are to be pushed on the stack.
2497   unsigned NumBytes = CCInfo.getStackSize();
2498 
2499   // SPDiff is the byte offset of the call's argument area from the callee's.
2500   // Stores to callee stack arguments will be placed in FixedStackSlots offset
2501   // by this amount for a tail call. In a sibling call it must be 0 because the
2502   // caller will deallocate the entire stack and the callee still expects its
2503   // arguments to begin at SP+0. Completely unused for non-tail calls.
2504   int SPDiff = 0;
2505 
2506   if (isTailCall && !isSibCall) {
2507     auto FuncInfo = MF.getInfo<ARMFunctionInfo>();
2508     unsigned NumReusableBytes = FuncInfo->getArgumentStackSize();
2509 
2510     // Since callee will pop argument stack as a tail call, we must keep the
2511     // popped size 16-byte aligned.
2512     MaybeAlign StackAlign = DAG.getDataLayout().getStackAlignment();
2513     assert(StackAlign && "data layout string is missing stack alignment");
2514     NumBytes = alignTo(NumBytes, *StackAlign);
2515 
2516     // SPDiff will be negative if this tail call requires more space than we
2517     // would automatically have in our incoming argument space. Positive if we
2518     // can actually shrink the stack.
2519     SPDiff = NumReusableBytes - NumBytes;
2520 
2521     // If this call requires more stack than we have available from
2522     // LowerFormalArguments, tell FrameLowering to reserve space for it.
2523     if (SPDiff < 0 && AFI->getArgRegsSaveSize() < (unsigned)-SPDiff)
2524       AFI->setArgRegsSaveSize(-SPDiff);
2525   }
2526 
2527   if (isSibCall) {
2528     // For sibling tail calls, memory operands are available in our caller's stack.
2529     NumBytes = 0;
2530   } else {
2531     // Adjust the stack pointer for the new arguments...
2532     // These operations are automatically eliminated by the prolog/epilog pass
2533     Chain = DAG.getCALLSEQ_START(Chain, isTailCall ? 0 : NumBytes, 0, dl);
2534   }
2535 
2536   SDValue StackPtr =
2537       DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout()));
2538 
2539   RegsToPassVector RegsToPass;
2540   SmallVector<SDValue, 8> MemOpChains;
2541 
2542   // If we are doing a tail-call, any byval arguments will be written to stack
2543   // space which was used for incoming arguments. If any the values being used
2544   // are incoming byval arguments to this function, then they might be
2545   // overwritten by the stores of the outgoing arguments. To avoid this, we
2546   // need to make a temporary copy of them in local stack space, then copy back
2547   // to the argument area.
2548   DenseMap<unsigned, SDValue> ByValTemporaries;
2549   SDValue ByValTempChain;
2550   if (isTailCall) {
2551     SmallVector<SDValue, 8> ByValCopyChains;
2552     for (const CCValAssign &VA : ArgLocs) {
2553       unsigned ArgIdx = VA.getValNo();
2554       SDValue Src = OutVals[ArgIdx];
2555       ISD::ArgFlagsTy Flags = Outs[ArgIdx].Flags;
2556 
2557       if (!Flags.isByVal())
2558         continue;
2559 
2560       SDValue Dst;
2561       MachinePointerInfo DstInfo;
2562       std::tie(Dst, DstInfo) =
2563           computeAddrForCallArg(dl, DAG, VA, SDValue(), true, SPDiff);
2564       ByValCopyKind Copy = ByValNeedsCopyForTailCall(DAG, Src, Dst, Flags);
2565 
2566       if (Copy == NoCopy) {
2567         // If the argument is already at the correct offset on the stack
2568         // (because we are forwarding a byval argument from our caller), we
2569         // don't need any copying.
2570         continue;
2571       } else if (Copy == CopyOnce) {
2572         // If the argument is in our local stack frame, no other argument
2573         // preparation can clobber it, so we can copy it to the final location
2574         // later.
2575         ByValTemporaries[ArgIdx] = Src;
2576       } else {
2577         assert(Copy == CopyViaTemp && "unexpected enum value");
2578         // If we might be copying this argument from the outgoing argument
2579         // stack area, we need to copy via a temporary in the local stack
2580         // frame.
2581         int TempFrameIdx = MFI.CreateStackObject(
2582             Flags.getByValSize(), Flags.getNonZeroByValAlign(), false);
2583         SDValue Temp =
2584             DAG.getFrameIndex(TempFrameIdx, getPointerTy(DAG.getDataLayout()));
2585 
2586         SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
2587         SDValue AlignNode =
2588             DAG.getConstant(Flags.getNonZeroByValAlign().value(), dl, MVT::i32);
2589 
2590         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
2591         SDValue Ops[] = {Chain, Temp, Src, SizeNode, AlignNode};
2592         ByValCopyChains.push_back(
2593             DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs, Ops));
2594         ByValTemporaries[ArgIdx] = Temp;
2595       }
2596     }
2597     if (!ByValCopyChains.empty())
2598       ByValTempChain =
2599           DAG.getNode(ISD::TokenFactor, dl, MVT::Other, ByValCopyChains);
2600   }
2601 
2602   // During a tail call, stores to the argument area must happen after all of
2603   // the function's incoming arguments have been loaded because they may alias.
2604   // This is done by folding in a TokenFactor from LowerFormalArguments, but
2605   // there's no point in doing so repeatedly so this tracks whether that's
2606   // happened yet.
2607   bool AfterFormalArgLoads = false;
2608 
2609   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2610   // of tail call optimization, arguments are handled later.
2611   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2612        i != e;
2613        ++i, ++realArgIdx) {
2614     CCValAssign &VA = ArgLocs[i];
2615     SDValue Arg = OutVals[realArgIdx];
2616     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2617     bool isByVal = Flags.isByVal();
2618 
2619     // Promote the value if needed.
2620     switch (VA.getLocInfo()) {
2621     default: llvm_unreachable("Unknown loc info!");
2622     case CCValAssign::Full: break;
2623     case CCValAssign::SExt:
2624       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
2625       break;
2626     case CCValAssign::ZExt:
2627       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
2628       break;
2629     case CCValAssign::AExt:
2630       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
2631       break;
2632     case CCValAssign::BCvt:
2633       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2634       break;
2635     }
2636 
2637     if (isTailCall && VA.isMemLoc() && !AfterFormalArgLoads) {
2638       Chain = DAG.getStackArgumentTokenFactor(Chain);
2639       if (ByValTempChain)
2640         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chain,
2641                             ByValTempChain);
2642       AfterFormalArgLoads = true;
2643     }
2644 
2645     // f16 arguments have their size extended to 4 bytes and passed as if they
2646     // had been copied to the LSBs of a 32-bit register.
2647     // For that, it's passed extended to i32 (soft ABI) or to f32 (hard ABI)
2648     if (VA.needsCustom() &&
2649         (VA.getValVT() == MVT::f16 || VA.getValVT() == MVT::bf16)) {
2650       Arg = MoveFromHPR(dl, DAG, VA.getLocVT(), VA.getValVT(), Arg);
2651     } else {
2652       // f16 arguments could have been extended prior to argument lowering.
2653       // Mask them arguments if this is a CMSE nonsecure call.
2654       auto ArgVT = Outs[realArgIdx].ArgVT;
2655       if (isCmseNSCall && (ArgVT == MVT::f16)) {
2656         auto LocBits = VA.getLocVT().getSizeInBits();
2657         auto MaskValue = APInt::getLowBitsSet(LocBits, ArgVT.getSizeInBits());
2658         SDValue Mask =
2659             DAG.getConstant(MaskValue, dl, MVT::getIntegerVT(LocBits));
2660         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::getIntegerVT(LocBits), Arg);
2661         Arg = DAG.getNode(ISD::AND, dl, MVT::getIntegerVT(LocBits), Arg, Mask);
2662         Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2663       }
2664     }
2665 
2666     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
2667     if (VA.needsCustom() && VA.getLocVT() == MVT::v2f64) {
2668       SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2669                                 DAG.getConstant(0, dl, MVT::i32));
2670       SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2671                                 DAG.getConstant(1, dl, MVT::i32));
2672 
2673       PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass, VA, ArgLocs[++i],
2674                        StackPtr, MemOpChains, isTailCall, SPDiff);
2675 
2676       VA = ArgLocs[++i]; // skip ahead to next loc
2677       if (VA.isRegLoc()) {
2678         PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass, VA, ArgLocs[++i],
2679                          StackPtr, MemOpChains, isTailCall, SPDiff);
2680       } else {
2681         assert(VA.isMemLoc());
2682         SDValue DstAddr;
2683         MachinePointerInfo DstInfo;
2684         std::tie(DstAddr, DstInfo) =
2685             computeAddrForCallArg(dl, DAG, VA, StackPtr, isTailCall, SPDiff);
2686         MemOpChains.push_back(DAG.getStore(Chain, dl, Op1, DstAddr, DstInfo));
2687       }
2688     } else if (VA.needsCustom() && VA.getLocVT() == MVT::f64) {
2689       PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
2690                        StackPtr, MemOpChains, isTailCall, SPDiff);
2691     } else if (VA.isRegLoc()) {
2692       if (realArgIdx == 0 && Flags.isReturned() && !Flags.isSwiftSelf() &&
2693           Outs[0].VT == MVT::i32) {
2694         assert(VA.getLocVT() == MVT::i32 &&
2695                "unexpected calling convention register assignment");
2696         assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
2697                "unexpected use of 'returned'");
2698         isThisReturn = true;
2699       }
2700       const TargetOptions &Options = DAG.getTarget().Options;
2701       if (Options.EmitCallSiteInfo)
2702         CSInfo.ArgRegPairs.emplace_back(VA.getLocReg(), i);
2703       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2704     } else if (isByVal) {
2705       assert(VA.isMemLoc());
2706       unsigned offset = 0;
2707 
2708       // True if this byval aggregate will be split between registers
2709       // and memory.
2710       unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
2711       unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed();
2712 
2713       SDValue ByValSrc;
2714       bool NeedsStackCopy;
2715       if (auto It = ByValTemporaries.find(realArgIdx);
2716           It != ByValTemporaries.end()) {
2717         ByValSrc = It->second;
2718         NeedsStackCopy = true;
2719       } else {
2720         ByValSrc = Arg;
2721         NeedsStackCopy = !isTailCall;
2722       }
2723 
2724       // If part of the argument is in registers, load them.
2725       if (CurByValIdx < ByValArgsCount) {
2726         unsigned RegBegin, RegEnd;
2727         CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
2728 
2729         EVT PtrVT = getPointerTy(DAG.getDataLayout());
2730         unsigned int i, j;
2731         for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
2732           SDValue Const = DAG.getConstant(4*i, dl, MVT::i32);
2733           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, ByValSrc, Const);
2734           SDValue Load =
2735               DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo(),
2736                           DAG.InferPtrAlign(AddArg));
2737           MemOpChains.push_back(Load.getValue(1));
2738           RegsToPass.push_back(std::make_pair(j, Load));
2739         }
2740 
2741         // If parameter size outsides register area, "offset" value
2742         // helps us to calculate stack slot for remained part properly.
2743         offset = RegEnd - RegBegin;
2744 
2745         CCInfo.nextInRegsParam();
2746       }
2747 
2748       // If the memory part of the argument isn't already in the correct place
2749       // (which can happen with tail calls), copy it into the argument area.
2750       if (NeedsStackCopy && Flags.getByValSize() > 4 * offset) {
2751         auto PtrVT = getPointerTy(DAG.getDataLayout());
2752         SDValue Dst;
2753         MachinePointerInfo DstInfo;
2754         std::tie(Dst, DstInfo) =
2755             computeAddrForCallArg(dl, DAG, VA, StackPtr, isTailCall, SPDiff);
2756         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl);
2757         SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, ByValSrc, SrcOffset);
2758         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl,
2759                                            MVT::i32);
2760         SDValue AlignNode =
2761             DAG.getConstant(Flags.getNonZeroByValAlign().value(), dl, MVT::i32);
2762 
2763         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
2764         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
2765         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
2766                                           Ops));
2767       }
2768     } else {
2769       assert(VA.isMemLoc());
2770       SDValue DstAddr;
2771       MachinePointerInfo DstInfo;
2772       std::tie(DstAddr, DstInfo) =
2773           computeAddrForCallArg(dl, DAG, VA, StackPtr, isTailCall, SPDiff);
2774 
2775       SDValue Store = DAG.getStore(Chain, dl, Arg, DstAddr, DstInfo);
2776       MemOpChains.push_back(Store);
2777     }
2778   }
2779 
2780   if (!MemOpChains.empty())
2781     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2782 
2783   // Build a sequence of copy-to-reg nodes chained together with token chain
2784   // and flag operands which copy the outgoing args into the appropriate regs.
2785   SDValue InGlue;
2786   for (const auto &[Reg, N] : RegsToPass) {
2787     Chain = DAG.getCopyToReg(Chain, dl, Reg, N, InGlue);
2788     InGlue = Chain.getValue(1);
2789   }
2790 
2791   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
2792   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
2793   // node so that legalize doesn't hack it.
2794   bool isDirect = false;
2795 
2796   const TargetMachine &TM = getTargetMachine();
2797   const GlobalValue *GVal = nullptr;
2798   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
2799     GVal = G->getGlobal();
2800   bool isStub = !TM.shouldAssumeDSOLocal(GVal) && Subtarget->isTargetMachO();
2801 
2802   bool isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
2803   bool isLocalARMFunc = false;
2804   auto PtrVt = getPointerTy(DAG.getDataLayout());
2805 
2806   if (Subtarget->genLongCalls()) {
2807     assert((!isPositionIndependent() || Subtarget->isTargetWindows()) &&
2808            "long-calls codegen is not position independent!");
2809     // Handle a global address or an external symbol. If it's not one of
2810     // those, the target's already in a register, so we don't need to do
2811     // anything extra.
2812     if (isa<GlobalAddressSDNode>(Callee)) {
2813       if (Subtarget->genExecuteOnly()) {
2814         if (Subtarget->useMovt())
2815           ++NumMovwMovt;
2816         Callee = DAG.getNode(ARMISD::Wrapper, dl, PtrVt,
2817                              DAG.getTargetGlobalAddress(GVal, dl, PtrVt));
2818       } else {
2819         // Create a constant pool entry for the callee address
2820         unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2821         ARMConstantPoolValue *CPV = ARMConstantPoolConstant::Create(
2822             GVal, ARMPCLabelIndex, ARMCP::CPValue, 0);
2823 
2824         // Get the address of the callee into a register
2825         SDValue Addr = DAG.getTargetConstantPool(CPV, PtrVt, Align(4));
2826         Addr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Addr);
2827         Callee = DAG.getLoad(
2828             PtrVt, dl, DAG.getEntryNode(), Addr,
2829             MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2830       }
2831     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
2832       const char *Sym = S->getSymbol();
2833 
2834       if (Subtarget->genExecuteOnly()) {
2835         if (Subtarget->useMovt())
2836           ++NumMovwMovt;
2837         Callee = DAG.getNode(ARMISD::Wrapper, dl, PtrVt,
2838                              DAG.getTargetGlobalAddress(GVal, dl, PtrVt));
2839       } else {
2840         // Create a constant pool entry for the callee address
2841         unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2842         ARMConstantPoolValue *CPV = ARMConstantPoolSymbol::Create(
2843             *DAG.getContext(), Sym, ARMPCLabelIndex, 0);
2844 
2845         // Get the address of the callee into a register
2846         SDValue Addr = DAG.getTargetConstantPool(CPV, PtrVt, Align(4));
2847         Addr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Addr);
2848         Callee = DAG.getLoad(
2849             PtrVt, dl, DAG.getEntryNode(), Addr,
2850             MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2851       }
2852     }
2853   } else if (isa<GlobalAddressSDNode>(Callee)) {
2854     if (!PreferIndirect) {
2855       isDirect = true;
2856       bool isDef = GVal->isStrongDefinitionForLinker();
2857 
2858       // ARM call to a local ARM function is predicable.
2859       isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking);
2860       // tBX takes a register source operand.
2861       if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
2862         assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
2863         Callee = DAG.getNode(
2864             ARMISD::WrapperPIC, dl, PtrVt,
2865             DAG.getTargetGlobalAddress(GVal, dl, PtrVt, 0, ARMII::MO_NONLAZY));
2866         Callee = DAG.getLoad(
2867             PtrVt, dl, DAG.getEntryNode(), Callee,
2868             MachinePointerInfo::getGOT(DAG.getMachineFunction()), MaybeAlign(),
2869             MachineMemOperand::MODereferenceable |
2870                 MachineMemOperand::MOInvariant);
2871       } else if (Subtarget->isTargetCOFF()) {
2872         assert(Subtarget->isTargetWindows() &&
2873                "Windows is the only supported COFF target");
2874         unsigned TargetFlags = ARMII::MO_NO_FLAG;
2875         if (GVal->hasDLLImportStorageClass())
2876           TargetFlags = ARMII::MO_DLLIMPORT;
2877         else if (!TM.shouldAssumeDSOLocal(GVal))
2878           TargetFlags = ARMII::MO_COFFSTUB;
2879         Callee = DAG.getTargetGlobalAddress(GVal, dl, PtrVt, /*offset=*/0,
2880                                             TargetFlags);
2881         if (TargetFlags & (ARMII::MO_DLLIMPORT | ARMII::MO_COFFSTUB))
2882           Callee =
2883               DAG.getLoad(PtrVt, dl, DAG.getEntryNode(),
2884                           DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee),
2885                           MachinePointerInfo::getGOT(DAG.getMachineFunction()));
2886       } else {
2887         Callee = DAG.getTargetGlobalAddress(GVal, dl, PtrVt, 0, 0);
2888       }
2889     }
2890   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2891     isDirect = true;
2892     // tBX takes a register source operand.
2893     const char *Sym = S->getSymbol();
2894     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
2895       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2896       ARMConstantPoolValue *CPV =
2897         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
2898                                       ARMPCLabelIndex, 4);
2899       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, Align(4));
2900       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2901       Callee = DAG.getLoad(
2902           PtrVt, dl, DAG.getEntryNode(), CPAddr,
2903           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2904       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2905       Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel);
2906     } else {
2907       Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, 0);
2908     }
2909   }
2910 
2911   if (isCmseNSCall) {
2912     assert(!isARMFunc && !isDirect &&
2913            "Cannot handle call to ARM function or direct call");
2914     if (NumBytes > 0) {
2915       DAG.getContext()->diagnose(
2916           DiagnosticInfoUnsupported(DAG.getMachineFunction().getFunction(),
2917                                     "call to non-secure function would require "
2918                                     "passing arguments on stack",
2919                                     dl.getDebugLoc()));
2920     }
2921     if (isStructRet) {
2922       DAG.getContext()->diagnose(DiagnosticInfoUnsupported(
2923           DAG.getMachineFunction().getFunction(),
2924           "call to non-secure function would return value through pointer",
2925           dl.getDebugLoc()));
2926     }
2927   }
2928 
2929   // FIXME: handle tail calls differently.
2930   unsigned CallOpc;
2931   if (Subtarget->isThumb()) {
2932     if (GuardWithBTI)
2933       CallOpc = ARMISD::t2CALL_BTI;
2934     else if (isCmseNSCall)
2935       CallOpc = ARMISD::tSECALL;
2936     else if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
2937       CallOpc = ARMISD::CALL_NOLINK;
2938     else
2939       CallOpc = ARMISD::CALL;
2940   } else {
2941     if (!isDirect && !Subtarget->hasV5TOps())
2942       CallOpc = ARMISD::CALL_NOLINK;
2943     else if (doesNotRet && isDirect && Subtarget->hasRetAddrStack() &&
2944              // Emit regular call when code size is the priority
2945              !Subtarget->hasMinSize())
2946       // "mov lr, pc; b _foo" to avoid confusing the RSP
2947       CallOpc = ARMISD::CALL_NOLINK;
2948     else
2949       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
2950   }
2951 
2952   // We don't usually want to end the call-sequence here because we would tidy
2953   // the frame up *after* the call, however in the ABI-changing tail-call case
2954   // we've carefully laid out the parameters so that when sp is reset they'll be
2955   // in the correct location.
2956   if (isTailCall && !isSibCall) {
2957     Chain = DAG.getCALLSEQ_END(Chain, 0, 0, InGlue, dl);
2958     InGlue = Chain.getValue(1);
2959   }
2960 
2961   std::vector<SDValue> Ops;
2962   Ops.push_back(Chain);
2963   Ops.push_back(Callee);
2964 
2965   if (isTailCall) {
2966     Ops.push_back(DAG.getSignedTargetConstant(SPDiff, dl, MVT::i32));
2967   }
2968 
2969   // Add argument registers to the end of the list so that they are known live
2970   // into the call.
2971   for (const auto &[Reg, N] : RegsToPass)
2972     Ops.push_back(DAG.getRegister(Reg, N.getValueType()));
2973 
2974   // Add a register mask operand representing the call-preserved registers.
2975   const uint32_t *Mask;
2976   const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
2977   if (isThisReturn) {
2978     // For 'this' returns, use the R0-preserving mask if applicable
2979     Mask = ARI->getThisReturnPreservedMask(MF, CallConv);
2980     if (!Mask) {
2981       // Set isThisReturn to false if the calling convention is not one that
2982       // allows 'returned' to be modeled in this way, so LowerCallResult does
2983       // not try to pass 'this' straight through
2984       isThisReturn = false;
2985       Mask = ARI->getCallPreservedMask(MF, CallConv);
2986     }
2987   } else
2988     Mask = ARI->getCallPreservedMask(MF, CallConv);
2989 
2990   assert(Mask && "Missing call preserved mask for calling convention");
2991   Ops.push_back(DAG.getRegisterMask(Mask));
2992 
2993   if (InGlue.getNode())
2994     Ops.push_back(InGlue);
2995 
2996   if (isTailCall) {
2997     MF.getFrameInfo().setHasTailCall();
2998     SDValue Ret = DAG.getNode(ARMISD::TC_RETURN, dl, MVT::Other, Ops);
2999     DAG.addNoMergeSiteInfo(Ret.getNode(), CLI.NoMerge);
3000     DAG.addCallSiteInfo(Ret.getNode(), std::move(CSInfo));
3001     return Ret;
3002   }
3003 
3004   // Returns a chain and a flag for retval copy to use.
3005   Chain = DAG.getNode(CallOpc, dl, {MVT::Other, MVT::Glue}, Ops);
3006   DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge);
3007   InGlue = Chain.getValue(1);
3008   DAG.addCallSiteInfo(Chain.getNode(), std::move(CSInfo));
3009 
3010   // If we're guaranteeing tail-calls will be honoured, the callee must
3011   // pop its own argument stack on return. But this call is *not* a tail call so
3012   // we need to undo that after it returns to restore the status-quo.
3013   bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt;
3014   uint64_t CalleePopBytes =
3015       canGuaranteeTCO(CallConv, TailCallOpt) ? alignTo(NumBytes, 16) : -1U;
3016 
3017   Chain = DAG.getCALLSEQ_END(Chain, NumBytes, CalleePopBytes, InGlue, dl);
3018   if (!Ins.empty())
3019     InGlue = Chain.getValue(1);
3020 
3021   // Handle result values, copying them out of physregs into vregs that we
3022   // return.
3023   return LowerCallResult(Chain, InGlue, CallConv, isVarArg, Ins, dl, DAG,
3024                          InVals, isThisReturn,
3025                          isThisReturn ? OutVals[0] : SDValue(), isCmseNSCall);
3026 }
3027 
3028 /// HandleByVal - Every parameter *after* a byval parameter is passed
3029 /// on the stack.  Remember the next parameter register to allocate,
3030 /// and then confiscate the rest of the parameter registers to insure
3031 /// this.
HandleByVal(CCState * State,unsigned & Size,Align Alignment) const3032 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size,
3033                                     Align Alignment) const {
3034   // Byval (as with any stack) slots are always at least 4 byte aligned.
3035   Alignment = std::max(Alignment, Align(4));
3036 
3037   MCRegister Reg = State->AllocateReg(GPRArgRegs);
3038   if (!Reg)
3039     return;
3040 
3041   unsigned AlignInRegs = Alignment.value() / 4;
3042   unsigned Waste = (ARM::R4 - Reg) % AlignInRegs;
3043   for (unsigned i = 0; i < Waste; ++i)
3044     Reg = State->AllocateReg(GPRArgRegs);
3045 
3046   if (!Reg)
3047     return;
3048 
3049   unsigned Excess = 4 * (ARM::R4 - Reg);
3050 
3051   // Special case when NSAA != SP and parameter size greater than size of
3052   // all remained GPR regs. In that case we can't split parameter, we must
3053   // send it to stack. We also must set NCRN to R4, so waste all
3054   // remained registers.
3055   const unsigned NSAAOffset = State->getStackSize();
3056   if (NSAAOffset != 0 && Size > Excess) {
3057     while (State->AllocateReg(GPRArgRegs))
3058       ;
3059     return;
3060   }
3061 
3062   // First register for byval parameter is the first register that wasn't
3063   // allocated before this method call, so it would be "reg".
3064   // If parameter is small enough to be saved in range [reg, r4), then
3065   // the end (first after last) register would be reg + param-size-in-regs,
3066   // else parameter would be splitted between registers and stack,
3067   // end register would be r4 in this case.
3068   unsigned ByValRegBegin = Reg;
3069   unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4);
3070   State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
3071   // Note, first register is allocated in the beginning of function already,
3072   // allocate remained amount of registers we need.
3073   for (unsigned i = Reg + 1; i != ByValRegEnd; ++i)
3074     State->AllocateReg(GPRArgRegs);
3075   // A byval parameter that is split between registers and memory needs its
3076   // size truncated here.
3077   // In the case where the entire structure fits in registers, we set the
3078   // size in memory to zero.
3079   Size = std::max<int>(Size - Excess, 0);
3080 }
3081 
3082 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3083 /// for tail call optimization. Targets which want to do tail call
3084 /// optimization should implement this function. Note that this function also
3085 /// processes musttail calls, so when this function returns false on a valid
3086 /// musttail call, a fatal backend error occurs.
IsEligibleForTailCallOptimization(TargetLowering::CallLoweringInfo & CLI,CCState & CCInfo,SmallVectorImpl<CCValAssign> & ArgLocs,const bool isIndirect) const3087 bool ARMTargetLowering::IsEligibleForTailCallOptimization(
3088     TargetLowering::CallLoweringInfo &CLI, CCState &CCInfo,
3089     SmallVectorImpl<CCValAssign> &ArgLocs, const bool isIndirect) const {
3090   CallingConv::ID CalleeCC = CLI.CallConv;
3091   SDValue Callee = CLI.Callee;
3092   bool isVarArg = CLI.IsVarArg;
3093   const SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
3094   const SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
3095   const SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
3096   const SelectionDAG &DAG = CLI.DAG;
3097   MachineFunction &MF = DAG.getMachineFunction();
3098   const Function &CallerF = MF.getFunction();
3099   CallingConv::ID CallerCC = CallerF.getCallingConv();
3100 
3101   assert(Subtarget->supportsTailCall());
3102 
3103   // Indirect tail-calls require a register to hold the target address. That
3104   // register must be:
3105   // * Allocatable (i.e. r0-r7 if the target is Thumb1).
3106   // * Not callee-saved, so must be one of r0-r3 or r12.
3107   // * Not used to hold an argument to the tail-called function, which might be
3108   //   in r0-r3.
3109   // * Not used to hold the return address authentication code, which is in r12
3110   //   if enabled.
3111   // Sometimes, no register matches all of these conditions, so we can't do a
3112   // tail-call.
3113   if (!isa<GlobalAddressSDNode>(Callee.getNode()) || isIndirect) {
3114     SmallSet<MCPhysReg, 5> AddressRegisters = {ARM::R0, ARM::R1, ARM::R2,
3115                                                ARM::R3};
3116     if (!(Subtarget->isThumb1Only() ||
3117           MF.getInfo<ARMFunctionInfo>()->shouldSignReturnAddress(true)))
3118       AddressRegisters.insert(ARM::R12);
3119     for (const CCValAssign &AL : ArgLocs)
3120       if (AL.isRegLoc())
3121         AddressRegisters.erase(AL.getLocReg());
3122     if (AddressRegisters.empty()) {
3123       LLVM_DEBUG(dbgs() << "false (no reg to hold function pointer)\n");
3124       return false;
3125     }
3126   }
3127 
3128   // Look for obvious safe cases to perform tail call optimization that do not
3129   // require ABI changes. This is what gcc calls sibcall.
3130 
3131   // Exception-handling functions need a special set of instructions to indicate
3132   // a return to the hardware. Tail-calling another function would probably
3133   // break this.
3134   if (CallerF.hasFnAttribute("interrupt")) {
3135     LLVM_DEBUG(dbgs() << "false (interrupt attribute)\n");
3136     return false;
3137   }
3138 
3139   if (canGuaranteeTCO(CalleeCC,
3140                       getTargetMachine().Options.GuaranteedTailCallOpt)) {
3141     LLVM_DEBUG(dbgs() << (CalleeCC == CallerCC ? "true" : "false")
3142                       << " (guaranteed tail-call CC)\n");
3143     return CalleeCC == CallerCC;
3144   }
3145 
3146   // Also avoid sibcall optimization if either caller or callee uses struct
3147   // return semantics.
3148   bool isCalleeStructRet = Outs.empty() ? false : Outs[0].Flags.isSRet();
3149   bool isCallerStructRet = MF.getFunction().hasStructRetAttr();
3150   if (isCalleeStructRet != isCallerStructRet) {
3151     LLVM_DEBUG(dbgs() << "false (struct-ret)\n");
3152     return false;
3153   }
3154 
3155   // Externally-defined functions with weak linkage should not be
3156   // tail-called on ARM when the OS does not support dynamic
3157   // pre-emption of symbols, as the AAELF spec requires normal calls
3158   // to undefined weak functions to be replaced with a NOP or jump to the
3159   // next instruction. The behaviour of branch instructions in this
3160   // situation (as used for tail calls) is implementation-defined, so we
3161   // cannot rely on the linker replacing the tail call with a return.
3162   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3163     const GlobalValue *GV = G->getGlobal();
3164     const Triple &TT = getTargetMachine().getTargetTriple();
3165     if (GV->hasExternalWeakLinkage() &&
3166         (!TT.isOSWindows() || TT.isOSBinFormatELF() ||
3167          TT.isOSBinFormatMachO())) {
3168       LLVM_DEBUG(dbgs() << "false (external weak linkage)\n");
3169       return false;
3170     }
3171   }
3172 
3173   // Check that the call results are passed in the same way.
3174   LLVMContext &C = *DAG.getContext();
3175   if (!CCState::resultsCompatible(
3176           getEffectiveCallingConv(CalleeCC, isVarArg),
3177           getEffectiveCallingConv(CallerCC, CallerF.isVarArg()), MF, C, Ins,
3178           CCAssignFnForReturn(CalleeCC, isVarArg),
3179           CCAssignFnForReturn(CallerCC, CallerF.isVarArg()))) {
3180     LLVM_DEBUG(dbgs() << "false (incompatible results)\n");
3181     return false;
3182   }
3183   // The callee has to preserve all registers the caller needs to preserve.
3184   const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
3185   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
3186   if (CalleeCC != CallerCC) {
3187     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
3188     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) {
3189       LLVM_DEBUG(dbgs() << "false (not all registers preserved)\n");
3190       return false;
3191     }
3192   }
3193 
3194   // If Caller's vararg argument has been split between registers and stack, do
3195   // not perform tail call, since part of the argument is in caller's local
3196   // frame.
3197   const ARMFunctionInfo *AFI_Caller = MF.getInfo<ARMFunctionInfo>();
3198   if (CLI.IsVarArg && AFI_Caller->getArgRegsSaveSize()) {
3199     LLVM_DEBUG(dbgs() << "false (arg reg save area)\n");
3200     return false;
3201   }
3202 
3203   // If the callee takes no arguments then go on to check the results of the
3204   // call.
3205   const MachineRegisterInfo &MRI = MF.getRegInfo();
3206   if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals)) {
3207     LLVM_DEBUG(dbgs() << "false (parameters in CSRs do not match)\n");
3208     return false;
3209   }
3210 
3211   // If the stack arguments for this call do not fit into our own save area then
3212   // the call cannot be made tail.
3213   if (CCInfo.getStackSize() > AFI_Caller->getArgumentStackSize())
3214     return false;
3215 
3216   LLVM_DEBUG(dbgs() << "true\n");
3217   return true;
3218 }
3219 
3220 bool
CanLowerReturn(CallingConv::ID CallConv,MachineFunction & MF,bool isVarArg,const SmallVectorImpl<ISD::OutputArg> & Outs,LLVMContext & Context,const Type * RetTy) const3221 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
3222                                   MachineFunction &MF, bool isVarArg,
3223                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
3224                                   LLVMContext &Context, const Type *RetTy) const {
3225   SmallVector<CCValAssign, 16> RVLocs;
3226   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
3227   return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
3228 }
3229 
LowerInterruptReturn(SmallVectorImpl<SDValue> & RetOps,const SDLoc & DL,SelectionDAG & DAG)3230 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
3231                                     const SDLoc &DL, SelectionDAG &DAG) {
3232   const MachineFunction &MF = DAG.getMachineFunction();
3233   const Function &F = MF.getFunction();
3234 
3235   StringRef IntKind = F.getFnAttribute("interrupt").getValueAsString();
3236 
3237   // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
3238   // version of the "preferred return address". These offsets affect the return
3239   // instruction if this is a return from PL1 without hypervisor extensions.
3240   //    IRQ/FIQ: +4     "subs pc, lr, #4"
3241   //    SWI:     0      "subs pc, lr, #0"
3242   //    ABORT:   +4     "subs pc, lr, #4"
3243   //    UNDEF:   +4/+2  "subs pc, lr, #0"
3244   // UNDEF varies depending on where the exception came from ARM or Thumb
3245   // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
3246 
3247   int64_t LROffset;
3248   if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
3249       IntKind == "ABORT")
3250     LROffset = 4;
3251   else if (IntKind == "SWI" || IntKind == "UNDEF")
3252     LROffset = 0;
3253   else
3254     report_fatal_error("Unsupported interrupt attribute. If present, value "
3255                        "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
3256 
3257   RetOps.insert(RetOps.begin() + 1,
3258                 DAG.getConstant(LROffset, DL, MVT::i32, false));
3259 
3260   return DAG.getNode(ARMISD::INTRET_GLUE, DL, MVT::Other, RetOps);
3261 }
3262 
3263 SDValue
LowerReturn(SDValue Chain,CallingConv::ID CallConv,bool isVarArg,const SmallVectorImpl<ISD::OutputArg> & Outs,const SmallVectorImpl<SDValue> & OutVals,const SDLoc & dl,SelectionDAG & DAG) const3264 ARMTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
3265                                bool isVarArg,
3266                                const SmallVectorImpl<ISD::OutputArg> &Outs,
3267                                const SmallVectorImpl<SDValue> &OutVals,
3268                                const SDLoc &dl, SelectionDAG &DAG) const {
3269   // CCValAssign - represent the assignment of the return value to a location.
3270   SmallVector<CCValAssign, 16> RVLocs;
3271 
3272   // CCState - Info about the registers and stack slots.
3273   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
3274                  *DAG.getContext());
3275 
3276   // Analyze outgoing return values.
3277   CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
3278 
3279   SDValue Glue;
3280   SmallVector<SDValue, 4> RetOps;
3281   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
3282   bool isLittleEndian = Subtarget->isLittle();
3283 
3284   MachineFunction &MF = DAG.getMachineFunction();
3285   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3286   AFI->setReturnRegsCount(RVLocs.size());
3287 
3288  // Report error if cmse entry function returns structure through first ptr arg.
3289   if (AFI->isCmseNSEntryFunction() && MF.getFunction().hasStructRetAttr()) {
3290     // Note: using an empty SDLoc(), as the first line of the function is a
3291     // better place to report than the last line.
3292     DAG.getContext()->diagnose(DiagnosticInfoUnsupported(
3293         DAG.getMachineFunction().getFunction(),
3294         "secure entry function would return value through pointer",
3295         SDLoc().getDebugLoc()));
3296   }
3297 
3298   // Copy the result values into the output registers.
3299   for (unsigned i = 0, realRVLocIdx = 0;
3300        i != RVLocs.size();
3301        ++i, ++realRVLocIdx) {
3302     CCValAssign &VA = RVLocs[i];
3303     assert(VA.isRegLoc() && "Can only return in registers!");
3304 
3305     SDValue Arg = OutVals[realRVLocIdx];
3306     bool ReturnF16 = false;
3307 
3308     if (Subtarget->hasFullFP16() && getTM().isTargetHardFloat()) {
3309       // Half-precision return values can be returned like this:
3310       //
3311       // t11 f16 = fadd ...
3312       // t12: i16 = bitcast t11
3313       //   t13: i32 = zero_extend t12
3314       // t14: f32 = bitcast t13  <~~~~~~~ Arg
3315       //
3316       // to avoid code generation for bitcasts, we simply set Arg to the node
3317       // that produces the f16 value, t11 in this case.
3318       //
3319       if (Arg.getValueType() == MVT::f32 && Arg.getOpcode() == ISD::BITCAST) {
3320         SDValue ZE = Arg.getOperand(0);
3321         if (ZE.getOpcode() == ISD::ZERO_EXTEND && ZE.getValueType() == MVT::i32) {
3322           SDValue BC = ZE.getOperand(0);
3323           if (BC.getOpcode() == ISD::BITCAST && BC.getValueType() == MVT::i16) {
3324             Arg = BC.getOperand(0);
3325             ReturnF16 = true;
3326           }
3327         }
3328       }
3329     }
3330 
3331     switch (VA.getLocInfo()) {
3332     default: llvm_unreachable("Unknown loc info!");
3333     case CCValAssign::Full: break;
3334     case CCValAssign::BCvt:
3335       if (!ReturnF16)
3336         Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
3337       break;
3338     }
3339 
3340     // Mask f16 arguments if this is a CMSE nonsecure entry.
3341     auto RetVT = Outs[realRVLocIdx].ArgVT;
3342     if (AFI->isCmseNSEntryFunction() && (RetVT == MVT::f16)) {
3343       if (VA.needsCustom() && VA.getValVT() == MVT::f16) {
3344         Arg = MoveFromHPR(dl, DAG, VA.getLocVT(), VA.getValVT(), Arg);
3345       } else {
3346         auto LocBits = VA.getLocVT().getSizeInBits();
3347         auto MaskValue = APInt::getLowBitsSet(LocBits, RetVT.getSizeInBits());
3348         SDValue Mask =
3349             DAG.getConstant(MaskValue, dl, MVT::getIntegerVT(LocBits));
3350         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::getIntegerVT(LocBits), Arg);
3351         Arg = DAG.getNode(ISD::AND, dl, MVT::getIntegerVT(LocBits), Arg, Mask);
3352         Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
3353       }
3354     }
3355 
3356     if (VA.needsCustom() &&
3357         (VA.getLocVT() == MVT::v2f64 || VA.getLocVT() == MVT::f64)) {
3358       if (VA.getLocVT() == MVT::v2f64) {
3359         // Extract the first half and return it in two registers.
3360         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
3361                                    DAG.getConstant(0, dl, MVT::i32));
3362         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
3363                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
3364 
3365         Chain =
3366             DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
3367                              HalfGPRs.getValue(isLittleEndian ? 0 : 1), Glue);
3368         Glue = Chain.getValue(1);
3369         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3370         VA = RVLocs[++i]; // skip ahead to next loc
3371         Chain =
3372             DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
3373                              HalfGPRs.getValue(isLittleEndian ? 1 : 0), Glue);
3374         Glue = Chain.getValue(1);
3375         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3376         VA = RVLocs[++i]; // skip ahead to next loc
3377 
3378         // Extract the 2nd half and fall through to handle it as an f64 value.
3379         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
3380                           DAG.getConstant(1, dl, MVT::i32));
3381       }
3382       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
3383       // available.
3384       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
3385                                   DAG.getVTList(MVT::i32, MVT::i32), Arg);
3386       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
3387                                fmrrd.getValue(isLittleEndian ? 0 : 1), Glue);
3388       Glue = Chain.getValue(1);
3389       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3390       VA = RVLocs[++i]; // skip ahead to next loc
3391       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
3392                                fmrrd.getValue(isLittleEndian ? 1 : 0), Glue);
3393     } else
3394       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Glue);
3395 
3396     // Guarantee that all emitted copies are
3397     // stuck together, avoiding something bad.
3398     Glue = Chain.getValue(1);
3399     RetOps.push_back(DAG.getRegister(
3400         VA.getLocReg(), ReturnF16 ? Arg.getValueType() : VA.getLocVT()));
3401   }
3402   const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
3403   const MCPhysReg *I =
3404       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
3405   if (I) {
3406     for (; *I; ++I) {
3407       if (ARM::GPRRegClass.contains(*I))
3408         RetOps.push_back(DAG.getRegister(*I, MVT::i32));
3409       else if (ARM::DPRRegClass.contains(*I))
3410         RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
3411       else
3412         llvm_unreachable("Unexpected register class in CSRsViaCopy!");
3413     }
3414   }
3415 
3416   // Update chain and glue.
3417   RetOps[0] = Chain;
3418   if (Glue.getNode())
3419     RetOps.push_back(Glue);
3420 
3421   // CPUs which aren't M-class use a special sequence to return from
3422   // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
3423   // though we use "subs pc, lr, #N").
3424   //
3425   // M-class CPUs actually use a normal return sequence with a special
3426   // (hardware-provided) value in LR, so the normal code path works.
3427   if (DAG.getMachineFunction().getFunction().hasFnAttribute("interrupt") &&
3428       !Subtarget->isMClass()) {
3429     if (Subtarget->isThumb1Only())
3430       report_fatal_error("interrupt attribute is not supported in Thumb1");
3431     return LowerInterruptReturn(RetOps, dl, DAG);
3432   }
3433 
3434   ARMISD::NodeType RetNode = AFI->isCmseNSEntryFunction() ? ARMISD::SERET_GLUE :
3435                                                             ARMISD::RET_GLUE;
3436   return DAG.getNode(RetNode, dl, MVT::Other, RetOps);
3437 }
3438 
isUsedByReturnOnly(SDNode * N,SDValue & Chain) const3439 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
3440   if (N->getNumValues() != 1)
3441     return false;
3442   if (!N->hasNUsesOfValue(1, 0))
3443     return false;
3444 
3445   SDValue TCChain = Chain;
3446   SDNode *Copy = *N->user_begin();
3447   if (Copy->getOpcode() == ISD::CopyToReg) {
3448     // If the copy has a glue operand, we conservatively assume it isn't safe to
3449     // perform a tail call.
3450     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
3451       return false;
3452     TCChain = Copy->getOperand(0);
3453   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
3454     SDNode *VMov = Copy;
3455     // f64 returned in a pair of GPRs.
3456     SmallPtrSet<SDNode*, 2> Copies;
3457     for (SDNode *U : VMov->users()) {
3458       if (U->getOpcode() != ISD::CopyToReg)
3459         return false;
3460       Copies.insert(U);
3461     }
3462     if (Copies.size() > 2)
3463       return false;
3464 
3465     for (SDNode *U : VMov->users()) {
3466       SDValue UseChain = U->getOperand(0);
3467       if (Copies.count(UseChain.getNode()))
3468         // Second CopyToReg
3469         Copy = U;
3470       else {
3471         // We are at the top of this chain.
3472         // If the copy has a glue operand, we conservatively assume it
3473         // isn't safe to perform a tail call.
3474         if (U->getOperand(U->getNumOperands() - 1).getValueType() == MVT::Glue)
3475           return false;
3476         // First CopyToReg
3477         TCChain = UseChain;
3478       }
3479     }
3480   } else if (Copy->getOpcode() == ISD::BITCAST) {
3481     // f32 returned in a single GPR.
3482     if (!Copy->hasOneUse())
3483       return false;
3484     Copy = *Copy->user_begin();
3485     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
3486       return false;
3487     // If the copy has a glue operand, we conservatively assume it isn't safe to
3488     // perform a tail call.
3489     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
3490       return false;
3491     TCChain = Copy->getOperand(0);
3492   } else {
3493     return false;
3494   }
3495 
3496   bool HasRet = false;
3497   for (const SDNode *U : Copy->users()) {
3498     if (U->getOpcode() != ARMISD::RET_GLUE &&
3499         U->getOpcode() != ARMISD::INTRET_GLUE)
3500       return false;
3501     HasRet = true;
3502   }
3503 
3504   if (!HasRet)
3505     return false;
3506 
3507   Chain = TCChain;
3508   return true;
3509 }
3510 
mayBeEmittedAsTailCall(const CallInst * CI) const3511 bool ARMTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
3512   if (!Subtarget->supportsTailCall())
3513     return false;
3514 
3515   if (!CI->isTailCall())
3516     return false;
3517 
3518   return true;
3519 }
3520 
3521 // Trying to write a 64 bit value so need to split into two 32 bit values first,
3522 // and pass the lower and high parts through.
LowerWRITE_REGISTER(SDValue Op,SelectionDAG & DAG)3523 static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) {
3524   SDLoc DL(Op);
3525   SDValue WriteValue = Op->getOperand(2);
3526 
3527   // This function is only supposed to be called for i64 type argument.
3528   assert(WriteValue.getValueType() == MVT::i64
3529           && "LowerWRITE_REGISTER called for non-i64 type argument.");
3530 
3531   SDValue Lo, Hi;
3532   std::tie(Lo, Hi) = DAG.SplitScalar(WriteValue, DL, MVT::i32, MVT::i32);
3533   SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi };
3534   return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops);
3535 }
3536 
3537 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
3538 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
3539 // one of the above mentioned nodes. It has to be wrapped because otherwise
3540 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
3541 // be used to form addressing mode. These wrapped nodes will be selected
3542 // into MOVi.
LowerConstantPool(SDValue Op,SelectionDAG & DAG) const3543 SDValue ARMTargetLowering::LowerConstantPool(SDValue Op,
3544                                              SelectionDAG &DAG) const {
3545   EVT PtrVT = Op.getValueType();
3546   // FIXME there is no actual debug info here
3547   SDLoc dl(Op);
3548   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
3549   SDValue Res;
3550 
3551   // When generating execute-only code Constant Pools must be promoted to the
3552   // global data section. It's a bit ugly that we can't share them across basic
3553   // blocks, but this way we guarantee that execute-only behaves correct with
3554   // position-independent addressing modes.
3555   if (Subtarget->genExecuteOnly()) {
3556     auto AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3557     auto T = const_cast<Type*>(CP->getType());
3558     auto C = const_cast<Constant*>(CP->getConstVal());
3559     auto M = const_cast<Module*>(DAG.getMachineFunction().
3560                                  getFunction().getParent());
3561     auto GV = new GlobalVariable(
3562                     *M, T, /*isConstant=*/true, GlobalVariable::InternalLinkage, C,
3563                     Twine(DAG.getDataLayout().getPrivateGlobalPrefix()) + "CP" +
3564                     Twine(DAG.getMachineFunction().getFunctionNumber()) + "_" +
3565                     Twine(AFI->createPICLabelUId())
3566                   );
3567     SDValue GA = DAG.getTargetGlobalAddress(dyn_cast<GlobalValue>(GV),
3568                                             dl, PtrVT);
3569     return LowerGlobalAddress(GA, DAG);
3570   }
3571 
3572   // The 16-bit ADR instruction can only encode offsets that are multiples of 4,
3573   // so we need to align to at least 4 bytes when we don't have 32-bit ADR.
3574   Align CPAlign = CP->getAlign();
3575   if (Subtarget->isThumb1Only())
3576     CPAlign = std::max(CPAlign, Align(4));
3577   if (CP->isMachineConstantPoolEntry())
3578     Res =
3579         DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT, CPAlign);
3580   else
3581     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CPAlign);
3582   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
3583 }
3584 
getJumpTableEncoding() const3585 unsigned ARMTargetLowering::getJumpTableEncoding() const {
3586   // If we don't have a 32-bit pc-relative branch instruction then the jump
3587   // table consists of block addresses. Usually this is inline, but for
3588   // execute-only it must be placed out-of-line.
3589   if (Subtarget->genExecuteOnly() && !Subtarget->hasV8MBaselineOps())
3590     return MachineJumpTableInfo::EK_BlockAddress;
3591   return MachineJumpTableInfo::EK_Inline;
3592 }
3593 
LowerBlockAddress(SDValue Op,SelectionDAG & DAG) const3594 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
3595                                              SelectionDAG &DAG) const {
3596   MachineFunction &MF = DAG.getMachineFunction();
3597   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3598   unsigned ARMPCLabelIndex = 0;
3599   SDLoc DL(Op);
3600   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3601   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
3602   SDValue CPAddr;
3603   bool IsPositionIndependent = isPositionIndependent() || Subtarget->isROPI();
3604   if (!IsPositionIndependent) {
3605     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, Align(4));
3606   } else {
3607     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
3608     ARMPCLabelIndex = AFI->createPICLabelUId();
3609     ARMConstantPoolValue *CPV =
3610       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
3611                                       ARMCP::CPBlockAddress, PCAdj);
3612     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, Align(4));
3613   }
3614   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
3615   SDValue Result = DAG.getLoad(
3616       PtrVT, DL, DAG.getEntryNode(), CPAddr,
3617       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3618   if (!IsPositionIndependent)
3619     return Result;
3620   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32);
3621   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
3622 }
3623 
3624 /// Convert a TLS address reference into the correct sequence of loads
3625 /// and calls to compute the variable's address for Darwin, and return an
3626 /// SDValue containing the final node.
3627 
3628 /// Darwin only has one TLS scheme which must be capable of dealing with the
3629 /// fully general situation, in the worst case. This means:
3630 ///     + "extern __thread" declaration.
3631 ///     + Defined in a possibly unknown dynamic library.
3632 ///
3633 /// The general system is that each __thread variable has a [3 x i32] descriptor
3634 /// which contains information used by the runtime to calculate the address. The
3635 /// only part of this the compiler needs to know about is the first word, which
3636 /// contains a function pointer that must be called with the address of the
3637 /// entire descriptor in "r0".
3638 ///
3639 /// Since this descriptor may be in a different unit, in general access must
3640 /// proceed along the usual ARM rules. A common sequence to produce is:
3641 ///
3642 ///     movw rT1, :lower16:_var$non_lazy_ptr
3643 ///     movt rT1, :upper16:_var$non_lazy_ptr
3644 ///     ldr r0, [rT1]
3645 ///     ldr rT2, [r0]
3646 ///     blx rT2
3647 ///     [...address now in r0...]
3648 SDValue
LowerGlobalTLSAddressDarwin(SDValue Op,SelectionDAG & DAG) const3649 ARMTargetLowering::LowerGlobalTLSAddressDarwin(SDValue Op,
3650                                                SelectionDAG &DAG) const {
3651   assert(Subtarget->isTargetDarwin() &&
3652          "This function expects a Darwin target");
3653   SDLoc DL(Op);
3654 
3655   // First step is to get the address of the actua global symbol. This is where
3656   // the TLS descriptor lives.
3657   SDValue DescAddr = LowerGlobalAddressDarwin(Op, DAG);
3658 
3659   // The first entry in the descriptor is a function pointer that we must call
3660   // to obtain the address of the variable.
3661   SDValue Chain = DAG.getEntryNode();
3662   SDValue FuncTLVGet = DAG.getLoad(
3663       MVT::i32, DL, Chain, DescAddr,
3664       MachinePointerInfo::getGOT(DAG.getMachineFunction()), Align(4),
3665       MachineMemOperand::MONonTemporal | MachineMemOperand::MODereferenceable |
3666           MachineMemOperand::MOInvariant);
3667   Chain = FuncTLVGet.getValue(1);
3668 
3669   MachineFunction &F = DAG.getMachineFunction();
3670   MachineFrameInfo &MFI = F.getFrameInfo();
3671   MFI.setAdjustsStack(true);
3672 
3673   // TLS calls preserve all registers except those that absolutely must be
3674   // trashed: R0 (it takes an argument), LR (it's a call) and CPSR (let's not be
3675   // silly).
3676   auto TRI =
3677       getTargetMachine().getSubtargetImpl(F.getFunction())->getRegisterInfo();
3678   auto ARI = static_cast<const ARMRegisterInfo *>(TRI);
3679   const uint32_t *Mask = ARI->getTLSCallPreservedMask(DAG.getMachineFunction());
3680 
3681   // Finally, we can make the call. This is just a degenerate version of a
3682   // normal AArch64 call node: r0 takes the address of the descriptor, and
3683   // returns the address of the variable in this thread.
3684   Chain = DAG.getCopyToReg(Chain, DL, ARM::R0, DescAddr, SDValue());
3685   Chain =
3686       DAG.getNode(ARMISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
3687                   Chain, FuncTLVGet, DAG.getRegister(ARM::R0, MVT::i32),
3688                   DAG.getRegisterMask(Mask), Chain.getValue(1));
3689   return DAG.getCopyFromReg(Chain, DL, ARM::R0, MVT::i32, Chain.getValue(1));
3690 }
3691 
3692 SDValue
LowerGlobalTLSAddressWindows(SDValue Op,SelectionDAG & DAG) const3693 ARMTargetLowering::LowerGlobalTLSAddressWindows(SDValue Op,
3694                                                 SelectionDAG &DAG) const {
3695   assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering");
3696 
3697   SDValue Chain = DAG.getEntryNode();
3698   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3699   SDLoc DL(Op);
3700 
3701   // Load the current TEB (thread environment block)
3702   SDValue Ops[] = {Chain,
3703                    DAG.getTargetConstant(Intrinsic::arm_mrc, DL, MVT::i32),
3704                    DAG.getTargetConstant(15, DL, MVT::i32),
3705                    DAG.getTargetConstant(0, DL, MVT::i32),
3706                    DAG.getTargetConstant(13, DL, MVT::i32),
3707                    DAG.getTargetConstant(0, DL, MVT::i32),
3708                    DAG.getTargetConstant(2, DL, MVT::i32)};
3709   SDValue CurrentTEB = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
3710                                    DAG.getVTList(MVT::i32, MVT::Other), Ops);
3711 
3712   SDValue TEB = CurrentTEB.getValue(0);
3713   Chain = CurrentTEB.getValue(1);
3714 
3715   // Load the ThreadLocalStoragePointer from the TEB
3716   // A pointer to the TLS array is located at offset 0x2c from the TEB.
3717   SDValue TLSArray =
3718       DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x2c, DL));
3719   TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo());
3720 
3721   // The pointer to the thread's TLS data area is at the TLS Index scaled by 4
3722   // offset into the TLSArray.
3723 
3724   // Load the TLS index from the C runtime
3725   SDValue TLSIndex =
3726       DAG.getTargetExternalSymbol("_tls_index", PtrVT, ARMII::MO_NO_FLAG);
3727   TLSIndex = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, TLSIndex);
3728   TLSIndex = DAG.getLoad(PtrVT, DL, Chain, TLSIndex, MachinePointerInfo());
3729 
3730   SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex,
3731                               DAG.getConstant(2, DL, MVT::i32));
3732   SDValue TLS = DAG.getLoad(PtrVT, DL, Chain,
3733                             DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot),
3734                             MachinePointerInfo());
3735 
3736   // Get the offset of the start of the .tls section (section base)
3737   const auto *GA = cast<GlobalAddressSDNode>(Op);
3738   auto *CPV = ARMConstantPoolConstant::Create(GA->getGlobal(), ARMCP::SECREL);
3739   SDValue Offset = DAG.getLoad(
3740       PtrVT, DL, Chain,
3741       DAG.getNode(ARMISD::Wrapper, DL, MVT::i32,
3742                   DAG.getTargetConstantPool(CPV, PtrVT, Align(4))),
3743       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3744 
3745   return DAG.getNode(ISD::ADD, DL, PtrVT, TLS, Offset);
3746 }
3747 
3748 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
3749 SDValue
LowerToTLSGeneralDynamicModel(GlobalAddressSDNode * GA,SelectionDAG & DAG) const3750 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
3751                                                  SelectionDAG &DAG) const {
3752   SDLoc dl(GA);
3753   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3754   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
3755   MachineFunction &MF = DAG.getMachineFunction();
3756   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3757   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
3758   ARMConstantPoolValue *CPV =
3759     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
3760                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
3761   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, Align(4));
3762   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
3763   Argument = DAG.getLoad(
3764       PtrVT, dl, DAG.getEntryNode(), Argument,
3765       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3766   SDValue Chain = Argument.getValue(1);
3767 
3768   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
3769   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
3770 
3771   // call __tls_get_addr.
3772   ArgListTy Args;
3773   ArgListEntry Entry;
3774   Entry.Node = Argument;
3775   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
3776   Args.push_back(Entry);
3777 
3778   // FIXME: is there useful debug info available here?
3779   TargetLowering::CallLoweringInfo CLI(DAG);
3780   CLI.setDebugLoc(dl).setChain(Chain).setLibCallee(
3781       CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
3782       DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args));
3783 
3784   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
3785   return CallResult.first;
3786 }
3787 
3788 // Lower ISD::GlobalTLSAddress using the "initial exec" or
3789 // "local exec" model.
3790 SDValue
LowerToTLSExecModels(GlobalAddressSDNode * GA,SelectionDAG & DAG,TLSModel::Model model) const3791 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
3792                                         SelectionDAG &DAG,
3793                                         TLSModel::Model model) const {
3794   const GlobalValue *GV = GA->getGlobal();
3795   SDLoc dl(GA);
3796   SDValue Offset;
3797   SDValue Chain = DAG.getEntryNode();
3798   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3799   // Get the Thread Pointer
3800   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
3801 
3802   if (model == TLSModel::InitialExec) {
3803     MachineFunction &MF = DAG.getMachineFunction();
3804     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3805     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
3806     // Initial exec model.
3807     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
3808     ARMConstantPoolValue *CPV =
3809       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
3810                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
3811                                       true);
3812     Offset = DAG.getTargetConstantPool(CPV, PtrVT, Align(4));
3813     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
3814     Offset = DAG.getLoad(
3815         PtrVT, dl, Chain, Offset,
3816         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3817     Chain = Offset.getValue(1);
3818 
3819     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
3820     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
3821 
3822     Offset = DAG.getLoad(
3823         PtrVT, dl, Chain, Offset,
3824         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3825   } else {
3826     // local exec model
3827     assert(model == TLSModel::LocalExec);
3828     ARMConstantPoolValue *CPV =
3829       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
3830     Offset = DAG.getTargetConstantPool(CPV, PtrVT, Align(4));
3831     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
3832     Offset = DAG.getLoad(
3833         PtrVT, dl, Chain, Offset,
3834         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3835   }
3836 
3837   // The address of the thread local variable is the add of the thread
3838   // pointer with the offset of the variable.
3839   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
3840 }
3841 
3842 SDValue
LowerGlobalTLSAddress(SDValue Op,SelectionDAG & DAG) const3843 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
3844   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3845   if (DAG.getTarget().useEmulatedTLS())
3846     return LowerToTLSEmulatedModel(GA, DAG);
3847 
3848   if (Subtarget->isTargetDarwin())
3849     return LowerGlobalTLSAddressDarwin(Op, DAG);
3850 
3851   if (Subtarget->isTargetWindows())
3852     return LowerGlobalTLSAddressWindows(Op, DAG);
3853 
3854   // TODO: implement the "local dynamic" model
3855   assert(Subtarget->isTargetELF() && "Only ELF implemented here");
3856   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
3857 
3858   switch (model) {
3859     case TLSModel::GeneralDynamic:
3860     case TLSModel::LocalDynamic:
3861       return LowerToTLSGeneralDynamicModel(GA, DAG);
3862     case TLSModel::InitialExec:
3863     case TLSModel::LocalExec:
3864       return LowerToTLSExecModels(GA, DAG, model);
3865   }
3866   llvm_unreachable("bogus TLS model");
3867 }
3868 
3869 /// Return true if all users of V are within function F, looking through
3870 /// ConstantExprs.
allUsersAreInFunction(const Value * V,const Function * F)3871 static bool allUsersAreInFunction(const Value *V, const Function *F) {
3872   SmallVector<const User*,4> Worklist(V->users());
3873   while (!Worklist.empty()) {
3874     auto *U = Worklist.pop_back_val();
3875     if (isa<ConstantExpr>(U)) {
3876       append_range(Worklist, U->users());
3877       continue;
3878     }
3879 
3880     auto *I = dyn_cast<Instruction>(U);
3881     if (!I || I->getParent()->getParent() != F)
3882       return false;
3883   }
3884   return true;
3885 }
3886 
promoteToConstantPool(const ARMTargetLowering * TLI,const GlobalValue * GV,SelectionDAG & DAG,EVT PtrVT,const SDLoc & dl)3887 static SDValue promoteToConstantPool(const ARMTargetLowering *TLI,
3888                                      const GlobalValue *GV, SelectionDAG &DAG,
3889                                      EVT PtrVT, const SDLoc &dl) {
3890   // If we're creating a pool entry for a constant global with unnamed address,
3891   // and the global is small enough, we can emit it inline into the constant pool
3892   // to save ourselves an indirection.
3893   //
3894   // This is a win if the constant is only used in one function (so it doesn't
3895   // need to be duplicated) or duplicating the constant wouldn't increase code
3896   // size (implying the constant is no larger than 4 bytes).
3897   const Function &F = DAG.getMachineFunction().getFunction();
3898 
3899   // We rely on this decision to inline being idemopotent and unrelated to the
3900   // use-site. We know that if we inline a variable at one use site, we'll
3901   // inline it elsewhere too (and reuse the constant pool entry). Fast-isel
3902   // doesn't know about this optimization, so bail out if it's enabled else
3903   // we could decide to inline here (and thus never emit the GV) but require
3904   // the GV from fast-isel generated code.
3905   if (!EnableConstpoolPromotion ||
3906       DAG.getMachineFunction().getTarget().Options.EnableFastISel)
3907       return SDValue();
3908 
3909   auto *GVar = dyn_cast<GlobalVariable>(GV);
3910   if (!GVar || !GVar->hasInitializer() ||
3911       !GVar->isConstant() || !GVar->hasGlobalUnnamedAddr() ||
3912       !GVar->hasLocalLinkage())
3913     return SDValue();
3914 
3915   // If we inline a value that contains relocations, we move the relocations
3916   // from .data to .text. This is not allowed in position-independent code.
3917   auto *Init = GVar->getInitializer();
3918   if ((TLI->isPositionIndependent() || TLI->getSubtarget()->isROPI()) &&
3919       Init->needsDynamicRelocation())
3920     return SDValue();
3921 
3922   // The constant islands pass can only really deal with alignment requests
3923   // <= 4 bytes and cannot pad constants itself. Therefore we cannot promote
3924   // any type wanting greater alignment requirements than 4 bytes. We also
3925   // can only promote constants that are multiples of 4 bytes in size or
3926   // are paddable to a multiple of 4. Currently we only try and pad constants
3927   // that are strings for simplicity.
3928   auto *CDAInit = dyn_cast<ConstantDataArray>(Init);
3929   unsigned Size = DAG.getDataLayout().getTypeAllocSize(Init->getType());
3930   Align PrefAlign = DAG.getDataLayout().getPreferredAlign(GVar);
3931   unsigned RequiredPadding = 4 - (Size % 4);
3932   bool PaddingPossible =
3933     RequiredPadding == 4 || (CDAInit && CDAInit->isString());
3934   if (!PaddingPossible || PrefAlign > 4 || Size > ConstpoolPromotionMaxSize ||
3935       Size == 0)
3936     return SDValue();
3937 
3938   unsigned PaddedSize = Size + ((RequiredPadding == 4) ? 0 : RequiredPadding);
3939   MachineFunction &MF = DAG.getMachineFunction();
3940   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3941 
3942   // We can't bloat the constant pool too much, else the ConstantIslands pass
3943   // may fail to converge. If we haven't promoted this global yet (it may have
3944   // multiple uses), and promoting it would increase the constant pool size (Sz
3945   // > 4), ensure we have space to do so up to MaxTotal.
3946   if (!AFI->getGlobalsPromotedToConstantPool().count(GVar) && Size > 4)
3947     if (AFI->getPromotedConstpoolIncrease() + PaddedSize - 4 >=
3948         ConstpoolPromotionMaxTotal)
3949       return SDValue();
3950 
3951   // This is only valid if all users are in a single function; we can't clone
3952   // the constant in general. The LLVM IR unnamed_addr allows merging
3953   // constants, but not cloning them.
3954   //
3955   // We could potentially allow cloning if we could prove all uses of the
3956   // constant in the current function don't care about the address, like
3957   // printf format strings. But that isn't implemented for now.
3958   if (!allUsersAreInFunction(GVar, &F))
3959     return SDValue();
3960 
3961   // We're going to inline this global. Pad it out if needed.
3962   if (RequiredPadding != 4) {
3963     StringRef S = CDAInit->getAsString();
3964 
3965     SmallVector<uint8_t,16> V(S.size());
3966     std::copy(S.bytes_begin(), S.bytes_end(), V.begin());
3967     while (RequiredPadding--)
3968       V.push_back(0);
3969     Init = ConstantDataArray::get(*DAG.getContext(), V);
3970   }
3971 
3972   auto CPVal = ARMConstantPoolConstant::Create(GVar, Init);
3973   SDValue CPAddr = DAG.getTargetConstantPool(CPVal, PtrVT, Align(4));
3974   if (!AFI->getGlobalsPromotedToConstantPool().count(GVar)) {
3975     AFI->markGlobalAsPromotedToConstantPool(GVar);
3976     AFI->setPromotedConstpoolIncrease(AFI->getPromotedConstpoolIncrease() +
3977                                       PaddedSize - 4);
3978   }
3979   ++NumConstpoolPromoted;
3980   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3981 }
3982 
isReadOnly(const GlobalValue * GV) const3983 bool ARMTargetLowering::isReadOnly(const GlobalValue *GV) const {
3984   if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
3985     if (!(GV = GA->getAliaseeObject()))
3986       return false;
3987   if (const auto *V = dyn_cast<GlobalVariable>(GV))
3988     return V->isConstant();
3989   return isa<Function>(GV);
3990 }
3991 
LowerGlobalAddress(SDValue Op,SelectionDAG & DAG) const3992 SDValue ARMTargetLowering::LowerGlobalAddress(SDValue Op,
3993                                               SelectionDAG &DAG) const {
3994   switch (Subtarget->getTargetTriple().getObjectFormat()) {
3995   default: llvm_unreachable("unknown object format");
3996   case Triple::COFF:
3997     return LowerGlobalAddressWindows(Op, DAG);
3998   case Triple::ELF:
3999     return LowerGlobalAddressELF(Op, DAG);
4000   case Triple::MachO:
4001     return LowerGlobalAddressDarwin(Op, DAG);
4002   }
4003 }
4004 
LowerGlobalAddressELF(SDValue Op,SelectionDAG & DAG) const4005 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
4006                                                  SelectionDAG &DAG) const {
4007   EVT PtrVT = getPointerTy(DAG.getDataLayout());
4008   SDLoc dl(Op);
4009   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
4010   bool IsRO = isReadOnly(GV);
4011 
4012   // promoteToConstantPool only if not generating XO text section
4013   if (GV->isDSOLocal() && !Subtarget->genExecuteOnly())
4014     if (SDValue V = promoteToConstantPool(this, GV, DAG, PtrVT, dl))
4015       return V;
4016 
4017   if (isPositionIndependent()) {
4018     SDValue G = DAG.getTargetGlobalAddress(
4019         GV, dl, PtrVT, 0, GV->isDSOLocal() ? 0 : ARMII::MO_GOT);
4020     SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G);
4021     if (!GV->isDSOLocal())
4022       Result =
4023           DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
4024                       MachinePointerInfo::getGOT(DAG.getMachineFunction()));
4025     return Result;
4026   } else if (Subtarget->isROPI() && IsRO) {
4027     // PC-relative.
4028     SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT);
4029     SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G);
4030     return Result;
4031   } else if (Subtarget->isRWPI() && !IsRO) {
4032     // SB-relative.
4033     SDValue RelAddr;
4034     if (Subtarget->useMovt()) {
4035       ++NumMovwMovt;
4036       SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_SBREL);
4037       RelAddr = DAG.getNode(ARMISD::Wrapper, dl, PtrVT, G);
4038     } else { // use literal pool for address constant
4039       ARMConstantPoolValue *CPV =
4040         ARMConstantPoolConstant::Create(GV, ARMCP::SBREL);
4041       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, Align(4));
4042       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
4043       RelAddr = DAG.getLoad(
4044           PtrVT, dl, DAG.getEntryNode(), CPAddr,
4045           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
4046     }
4047     SDValue SB = DAG.getCopyFromReg(DAG.getEntryNode(), dl, ARM::R9, PtrVT);
4048     SDValue Result = DAG.getNode(ISD::ADD, dl, PtrVT, SB, RelAddr);
4049     return Result;
4050   }
4051 
4052   // If we have T2 ops, we can materialize the address directly via movt/movw
4053   // pair. This is always cheaper. If need to generate Execute Only code, and we
4054   // only have Thumb1 available, we can't use a constant pool and are forced to
4055   // use immediate relocations.
4056   if (Subtarget->useMovt() || Subtarget->genExecuteOnly()) {
4057     if (Subtarget->useMovt())
4058       ++NumMovwMovt;
4059     // FIXME: Once remat is capable of dealing with instructions with register
4060     // operands, expand this into two nodes.
4061     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
4062                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
4063   } else {
4064     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, Align(4));
4065     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
4066     return DAG.getLoad(
4067         PtrVT, dl, DAG.getEntryNode(), CPAddr,
4068         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
4069   }
4070 }
4071 
LowerGlobalAddressDarwin(SDValue Op,SelectionDAG & DAG) const4072 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
4073                                                     SelectionDAG &DAG) const {
4074   assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
4075          "ROPI/RWPI not currently supported for Darwin");
4076   EVT PtrVT = getPointerTy(DAG.getDataLayout());
4077   SDLoc dl(Op);
4078   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
4079 
4080   if (Subtarget->useMovt())
4081     ++NumMovwMovt;
4082 
4083   // FIXME: Once remat is capable of dealing with instructions with register
4084   // operands, expand this into multiple nodes
4085   unsigned Wrapper =
4086       isPositionIndependent() ? ARMISD::WrapperPIC : ARMISD::Wrapper;
4087 
4088   SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
4089   SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
4090 
4091   if (Subtarget->isGVIndirectSymbol(GV))
4092     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
4093                          MachinePointerInfo::getGOT(DAG.getMachineFunction()));
4094   return Result;
4095 }
4096 
LowerGlobalAddressWindows(SDValue Op,SelectionDAG & DAG) const4097 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
4098                                                      SelectionDAG &DAG) const {
4099   assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
4100   assert(Subtarget->useMovt() &&
4101          "Windows on ARM expects to use movw/movt");
4102   assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
4103          "ROPI/RWPI not currently supported for Windows");
4104 
4105   const TargetMachine &TM = getTargetMachine();
4106   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
4107   ARMII::TOF TargetFlags = ARMII::MO_NO_FLAG;
4108   if (GV->hasDLLImportStorageClass())
4109     TargetFlags = ARMII::MO_DLLIMPORT;
4110   else if (!TM.shouldAssumeDSOLocal(GV))
4111     TargetFlags = ARMII::MO_COFFSTUB;
4112   EVT PtrVT = getPointerTy(DAG.getDataLayout());
4113   SDValue Result;
4114   SDLoc DL(Op);
4115 
4116   ++NumMovwMovt;
4117 
4118   // FIXME: Once remat is capable of dealing with instructions with register
4119   // operands, expand this into two nodes.
4120   Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
4121                        DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*offset=*/0,
4122                                                   TargetFlags));
4123   if (TargetFlags & (ARMII::MO_DLLIMPORT | ARMII::MO_COFFSTUB))
4124     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
4125                          MachinePointerInfo::getGOT(DAG.getMachineFunction()));
4126   return Result;
4127 }
4128 
4129 SDValue
LowerEH_SJLJ_SETJMP(SDValue Op,SelectionDAG & DAG) const4130 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
4131   SDLoc dl(Op);
4132   SDValue Val = DAG.getConstant(0, dl, MVT::i32);
4133   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
4134                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
4135                      Op.getOperand(1), Val);
4136 }
4137 
4138 SDValue
LowerEH_SJLJ_LONGJMP(SDValue Op,SelectionDAG & DAG) const4139 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
4140   SDLoc dl(Op);
4141   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
4142                      Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32));
4143 }
4144 
LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op,SelectionDAG & DAG) const4145 SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op,
4146                                                       SelectionDAG &DAG) const {
4147   SDLoc dl(Op);
4148   return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other,
4149                      Op.getOperand(0));
4150 }
4151 
LowerINTRINSIC_VOID(SDValue Op,SelectionDAG & DAG,const ARMSubtarget * Subtarget) const4152 SDValue ARMTargetLowering::LowerINTRINSIC_VOID(
4153     SDValue Op, SelectionDAG &DAG, const ARMSubtarget *Subtarget) const {
4154   unsigned IntNo =
4155       Op.getConstantOperandVal(Op.getOperand(0).getValueType() == MVT::Other);
4156   switch (IntNo) {
4157     default:
4158       return SDValue();  // Don't custom lower most intrinsics.
4159     case Intrinsic::arm_gnu_eabi_mcount: {
4160       MachineFunction &MF = DAG.getMachineFunction();
4161       EVT PtrVT = getPointerTy(DAG.getDataLayout());
4162       SDLoc dl(Op);
4163       SDValue Chain = Op.getOperand(0);
4164       // call "\01__gnu_mcount_nc"
4165       const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
4166       const uint32_t *Mask =
4167           ARI->getCallPreservedMask(DAG.getMachineFunction(), CallingConv::C);
4168       assert(Mask && "Missing call preserved mask for calling convention");
4169       // Mark LR an implicit live-in.
4170       Register Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
4171       SDValue ReturnAddress =
4172           DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, PtrVT);
4173       constexpr EVT ResultTys[] = {MVT::Other, MVT::Glue};
4174       SDValue Callee =
4175           DAG.getTargetExternalSymbol("\01__gnu_mcount_nc", PtrVT, 0);
4176       SDValue RegisterMask = DAG.getRegisterMask(Mask);
4177       if (Subtarget->isThumb())
4178         return SDValue(
4179             DAG.getMachineNode(
4180                 ARM::tBL_PUSHLR, dl, ResultTys,
4181                 {ReturnAddress, DAG.getTargetConstant(ARMCC::AL, dl, PtrVT),
4182                  DAG.getRegister(0, PtrVT), Callee, RegisterMask, Chain}),
4183             0);
4184       return SDValue(
4185           DAG.getMachineNode(ARM::BL_PUSHLR, dl, ResultTys,
4186                              {ReturnAddress, Callee, RegisterMask, Chain}),
4187           0);
4188     }
4189   }
4190 }
4191 
4192 SDValue
LowerINTRINSIC_WO_CHAIN(SDValue Op,SelectionDAG & DAG,const ARMSubtarget * Subtarget) const4193 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
4194                                           const ARMSubtarget *Subtarget) const {
4195   unsigned IntNo = Op.getConstantOperandVal(0);
4196   SDLoc dl(Op);
4197   switch (IntNo) {
4198   default: return SDValue();    // Don't custom lower most intrinsics.
4199   case Intrinsic::thread_pointer: {
4200     EVT PtrVT = getPointerTy(DAG.getDataLayout());
4201     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
4202   }
4203   case Intrinsic::arm_cls: {
4204     const SDValue &Operand = Op.getOperand(1);
4205     const EVT VTy = Op.getValueType();
4206     SDValue SRA =
4207         DAG.getNode(ISD::SRA, dl, VTy, Operand, DAG.getConstant(31, dl, VTy));
4208     SDValue XOR = DAG.getNode(ISD::XOR, dl, VTy, SRA, Operand);
4209     SDValue SHL =
4210         DAG.getNode(ISD::SHL, dl, VTy, XOR, DAG.getConstant(1, dl, VTy));
4211     SDValue OR =
4212         DAG.getNode(ISD::OR, dl, VTy, SHL, DAG.getConstant(1, dl, VTy));
4213     SDValue Result = DAG.getNode(ISD::CTLZ, dl, VTy, OR);
4214     return Result;
4215   }
4216   case Intrinsic::arm_cls64: {
4217     // cls(x) = if cls(hi(x)) != 31 then cls(hi(x))
4218     //          else 31 + clz(if hi(x) == 0 then lo(x) else not(lo(x)))
4219     const SDValue &Operand = Op.getOperand(1);
4220     const EVT VTy = Op.getValueType();
4221     SDValue Lo, Hi;
4222     std::tie(Lo, Hi) = DAG.SplitScalar(Operand, dl, VTy, VTy);
4223     SDValue Constant0 = DAG.getConstant(0, dl, VTy);
4224     SDValue Constant1 = DAG.getConstant(1, dl, VTy);
4225     SDValue Constant31 = DAG.getConstant(31, dl, VTy);
4226     SDValue SRAHi = DAG.getNode(ISD::SRA, dl, VTy, Hi, Constant31);
4227     SDValue XORHi = DAG.getNode(ISD::XOR, dl, VTy, SRAHi, Hi);
4228     SDValue SHLHi = DAG.getNode(ISD::SHL, dl, VTy, XORHi, Constant1);
4229     SDValue ORHi = DAG.getNode(ISD::OR, dl, VTy, SHLHi, Constant1);
4230     SDValue CLSHi = DAG.getNode(ISD::CTLZ, dl, VTy, ORHi);
4231     SDValue CheckLo =
4232         DAG.getSetCC(dl, MVT::i1, CLSHi, Constant31, ISD::CondCode::SETEQ);
4233     SDValue HiIsZero =
4234         DAG.getSetCC(dl, MVT::i1, Hi, Constant0, ISD::CondCode::SETEQ);
4235     SDValue AdjustedLo =
4236         DAG.getSelect(dl, VTy, HiIsZero, Lo, DAG.getNOT(dl, Lo, VTy));
4237     SDValue CLZAdjustedLo = DAG.getNode(ISD::CTLZ, dl, VTy, AdjustedLo);
4238     SDValue Result =
4239         DAG.getSelect(dl, VTy, CheckLo,
4240                       DAG.getNode(ISD::ADD, dl, VTy, CLZAdjustedLo, Constant31), CLSHi);
4241     return Result;
4242   }
4243   case Intrinsic::eh_sjlj_lsda: {
4244     MachineFunction &MF = DAG.getMachineFunction();
4245     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
4246     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
4247     EVT PtrVT = getPointerTy(DAG.getDataLayout());
4248     SDValue CPAddr;
4249     bool IsPositionIndependent = isPositionIndependent();
4250     unsigned PCAdj = IsPositionIndependent ? (Subtarget->isThumb() ? 4 : 8) : 0;
4251     ARMConstantPoolValue *CPV =
4252       ARMConstantPoolConstant::Create(&MF.getFunction(), ARMPCLabelIndex,
4253                                       ARMCP::CPLSDA, PCAdj);
4254     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, Align(4));
4255     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
4256     SDValue Result = DAG.getLoad(
4257         PtrVT, dl, DAG.getEntryNode(), CPAddr,
4258         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
4259 
4260     if (IsPositionIndependent) {
4261       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
4262       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
4263     }
4264     return Result;
4265   }
4266   case Intrinsic::arm_neon_vabs:
4267     return DAG.getNode(ISD::ABS, SDLoc(Op), Op.getValueType(),
4268                        Op.getOperand(1));
4269   case Intrinsic::arm_neon_vabds:
4270     if (Op.getValueType().isInteger())
4271       return DAG.getNode(ISD::ABDS, SDLoc(Op), Op.getValueType(),
4272                          Op.getOperand(1), Op.getOperand(2));
4273     return SDValue();
4274   case Intrinsic::arm_neon_vabdu:
4275     return DAG.getNode(ISD::ABDU, SDLoc(Op), Op.getValueType(),
4276                        Op.getOperand(1), Op.getOperand(2));
4277   case Intrinsic::arm_neon_vmulls:
4278   case Intrinsic::arm_neon_vmullu: {
4279     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
4280       ? ARMISD::VMULLs : ARMISD::VMULLu;
4281     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
4282                        Op.getOperand(1), Op.getOperand(2));
4283   }
4284   case Intrinsic::arm_neon_vminnm:
4285   case Intrinsic::arm_neon_vmaxnm: {
4286     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminnm)
4287       ? ISD::FMINNUM : ISD::FMAXNUM;
4288     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
4289                        Op.getOperand(1), Op.getOperand(2));
4290   }
4291   case Intrinsic::arm_neon_vminu:
4292   case Intrinsic::arm_neon_vmaxu: {
4293     if (Op.getValueType().isFloatingPoint())
4294       return SDValue();
4295     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminu)
4296       ? ISD::UMIN : ISD::UMAX;
4297     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
4298                          Op.getOperand(1), Op.getOperand(2));
4299   }
4300   case Intrinsic::arm_neon_vmins:
4301   case Intrinsic::arm_neon_vmaxs: {
4302     // v{min,max}s is overloaded between signed integers and floats.
4303     if (!Op.getValueType().isFloatingPoint()) {
4304       unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
4305         ? ISD::SMIN : ISD::SMAX;
4306       return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
4307                          Op.getOperand(1), Op.getOperand(2));
4308     }
4309     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
4310       ? ISD::FMINIMUM : ISD::FMAXIMUM;
4311     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
4312                        Op.getOperand(1), Op.getOperand(2));
4313   }
4314   case Intrinsic::arm_neon_vtbl1:
4315     return DAG.getNode(ARMISD::VTBL1, SDLoc(Op), Op.getValueType(),
4316                        Op.getOperand(1), Op.getOperand(2));
4317   case Intrinsic::arm_neon_vtbl2:
4318     return DAG.getNode(ARMISD::VTBL2, SDLoc(Op), Op.getValueType(),
4319                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
4320   case Intrinsic::arm_mve_pred_i2v:
4321   case Intrinsic::arm_mve_pred_v2i:
4322     return DAG.getNode(ARMISD::PREDICATE_CAST, SDLoc(Op), Op.getValueType(),
4323                        Op.getOperand(1));
4324   case Intrinsic::arm_mve_vreinterpretq:
4325     return DAG.getNode(ARMISD::VECTOR_REG_CAST, SDLoc(Op), Op.getValueType(),
4326                        Op.getOperand(1));
4327   case Intrinsic::arm_mve_lsll:
4328     return DAG.getNode(ARMISD::LSLL, SDLoc(Op), Op->getVTList(),
4329                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
4330   case Intrinsic::arm_mve_asrl:
4331     return DAG.getNode(ARMISD::ASRL, SDLoc(Op), Op->getVTList(),
4332                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
4333   }
4334 }
4335 
LowerATOMIC_FENCE(SDValue Op,SelectionDAG & DAG,const ARMSubtarget * Subtarget)4336 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
4337                                  const ARMSubtarget *Subtarget) {
4338   SDLoc dl(Op);
4339   auto SSID = static_cast<SyncScope::ID>(Op.getConstantOperandVal(2));
4340   if (SSID == SyncScope::SingleThread)
4341     return Op;
4342 
4343   if (!Subtarget->hasDataBarrier()) {
4344     // Some ARMv6 cpus can support data barriers with an mcr instruction.
4345     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
4346     // here.
4347     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
4348            "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
4349     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
4350                        DAG.getConstant(0, dl, MVT::i32));
4351   }
4352 
4353   AtomicOrdering Ord =
4354       static_cast<AtomicOrdering>(Op.getConstantOperandVal(1));
4355   ARM_MB::MemBOpt Domain = ARM_MB::ISH;
4356   if (Subtarget->isMClass()) {
4357     // Only a full system barrier exists in the M-class architectures.
4358     Domain = ARM_MB::SY;
4359   } else if (Subtarget->preferISHSTBarriers() &&
4360              Ord == AtomicOrdering::Release) {
4361     // Swift happens to implement ISHST barriers in a way that's compatible with
4362     // Release semantics but weaker than ISH so we'd be fools not to use
4363     // it. Beware: other processors probably don't!
4364     Domain = ARM_MB::ISHST;
4365   }
4366 
4367   return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
4368                      DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32),
4369                      DAG.getConstant(Domain, dl, MVT::i32));
4370 }
4371 
LowerPREFETCH(SDValue Op,SelectionDAG & DAG,const ARMSubtarget * Subtarget)4372 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
4373                              const ARMSubtarget *Subtarget) {
4374   // ARM pre v5TE and Thumb1 does not have preload instructions.
4375   if (!(Subtarget->isThumb2() ||
4376         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
4377     // Just preserve the chain.
4378     return Op.getOperand(0);
4379 
4380   SDLoc dl(Op);
4381   unsigned isRead = ~Op.getConstantOperandVal(2) & 1;
4382   if (!isRead &&
4383       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
4384     // ARMv7 with MP extension has PLDW.
4385     return Op.getOperand(0);
4386 
4387   unsigned isData = Op.getConstantOperandVal(4);
4388   if (Subtarget->isThumb()) {
4389     // Invert the bits.
4390     isRead = ~isRead & 1;
4391     isData = ~isData & 1;
4392   }
4393 
4394   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
4395                      Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32),
4396                      DAG.getConstant(isData, dl, MVT::i32));
4397 }
4398 
LowerVASTART(SDValue Op,SelectionDAG & DAG)4399 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
4400   MachineFunction &MF = DAG.getMachineFunction();
4401   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
4402 
4403   // vastart just stores the address of the VarArgsFrameIndex slot into the
4404   // memory location argument.
4405   SDLoc dl(Op);
4406   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
4407   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4408   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4409   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
4410                       MachinePointerInfo(SV));
4411 }
4412 
GetF64FormalArgument(CCValAssign & VA,CCValAssign & NextVA,SDValue & Root,SelectionDAG & DAG,const SDLoc & dl) const4413 SDValue ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA,
4414                                                 CCValAssign &NextVA,
4415                                                 SDValue &Root,
4416                                                 SelectionDAG &DAG,
4417                                                 const SDLoc &dl) const {
4418   MachineFunction &MF = DAG.getMachineFunction();
4419   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
4420 
4421   const TargetRegisterClass *RC;
4422   if (AFI->isThumb1OnlyFunction())
4423     RC = &ARM::tGPRRegClass;
4424   else
4425     RC = &ARM::GPRRegClass;
4426 
4427   // Transform the arguments stored in physical registers into virtual ones.
4428   Register Reg = MF.addLiveIn(VA.getLocReg(), RC);
4429   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
4430 
4431   SDValue ArgValue2;
4432   if (NextVA.isMemLoc()) {
4433     MachineFrameInfo &MFI = MF.getFrameInfo();
4434     int FI = MFI.CreateFixedObject(4, NextVA.getLocMemOffset(), true);
4435 
4436     // Create load node to retrieve arguments from the stack.
4437     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
4438     ArgValue2 = DAG.getLoad(
4439         MVT::i32, dl, Root, FIN,
4440         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI));
4441   } else {
4442     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
4443     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
4444   }
4445   if (!Subtarget->isLittle())
4446     std::swap (ArgValue, ArgValue2);
4447   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
4448 }
4449 
4450 // The remaining GPRs hold either the beginning of variable-argument
4451 // data, or the beginning of an aggregate passed by value (usually
4452 // byval).  Either way, we allocate stack slots adjacent to the data
4453 // provided by our caller, and store the unallocated registers there.
4454 // If this is a variadic function, the va_list pointer will begin with
4455 // these values; otherwise, this reassembles a (byval) structure that
4456 // was split between registers and memory.
4457 // Return: The frame index registers were stored into.
StoreByValRegs(CCState & CCInfo,SelectionDAG & DAG,const SDLoc & dl,SDValue & Chain,const Value * OrigArg,unsigned InRegsParamRecordIdx,int ArgOffset,unsigned ArgSize) const4458 int ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
4459                                       const SDLoc &dl, SDValue &Chain,
4460                                       const Value *OrigArg,
4461                                       unsigned InRegsParamRecordIdx,
4462                                       int ArgOffset, unsigned ArgSize) const {
4463   // Currently, two use-cases possible:
4464   // Case #1. Non-var-args function, and we meet first byval parameter.
4465   //          Setup first unallocated register as first byval register;
4466   //          eat all remained registers
4467   //          (these two actions are performed by HandleByVal method).
4468   //          Then, here, we initialize stack frame with
4469   //          "store-reg" instructions.
4470   // Case #2. Var-args function, that doesn't contain byval parameters.
4471   //          The same: eat all remained unallocated registers,
4472   //          initialize stack frame.
4473 
4474   MachineFunction &MF = DAG.getMachineFunction();
4475   MachineFrameInfo &MFI = MF.getFrameInfo();
4476   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
4477   unsigned RBegin, REnd;
4478   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
4479     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
4480   } else {
4481     unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
4482     RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx];
4483     REnd = ARM::R4;
4484   }
4485 
4486   if (REnd != RBegin)
4487     ArgOffset = -4 * (ARM::R4 - RBegin);
4488 
4489   auto PtrVT = getPointerTy(DAG.getDataLayout());
4490   int FrameIndex = MFI.CreateFixedObject(ArgSize, ArgOffset, false);
4491   SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT);
4492 
4493   SmallVector<SDValue, 4> MemOps;
4494   const TargetRegisterClass *RC =
4495       AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
4496 
4497   for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) {
4498     Register VReg = MF.addLiveIn(Reg, RC);
4499     SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
4500     SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
4501                                  MachinePointerInfo(OrigArg, 4 * i));
4502     MemOps.push_back(Store);
4503     FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT));
4504   }
4505 
4506   if (!MemOps.empty())
4507     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4508   return FrameIndex;
4509 }
4510 
4511 // Setup stack frame, the va_list pointer will start from.
VarArgStyleRegisters(CCState & CCInfo,SelectionDAG & DAG,const SDLoc & dl,SDValue & Chain,unsigned ArgOffset,unsigned TotalArgRegsSaveSize,bool ForceMutable) const4512 void ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
4513                                              const SDLoc &dl, SDValue &Chain,
4514                                              unsigned ArgOffset,
4515                                              unsigned TotalArgRegsSaveSize,
4516                                              bool ForceMutable) const {
4517   MachineFunction &MF = DAG.getMachineFunction();
4518   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
4519 
4520   // Try to store any remaining integer argument regs
4521   // to their spots on the stack so that they may be loaded by dereferencing
4522   // the result of va_next.
4523   // If there is no regs to be stored, just point address after last
4524   // argument passed via stack.
4525   int FrameIndex = StoreByValRegs(
4526       CCInfo, DAG, dl, Chain, nullptr, CCInfo.getInRegsParamsCount(),
4527       CCInfo.getStackSize(), std::max(4U, TotalArgRegsSaveSize));
4528   AFI->setVarArgsFrameIndex(FrameIndex);
4529 }
4530 
splitValueIntoRegisterParts(SelectionDAG & DAG,const SDLoc & DL,SDValue Val,SDValue * Parts,unsigned NumParts,MVT PartVT,std::optional<CallingConv::ID> CC) const4531 bool ARMTargetLowering::splitValueIntoRegisterParts(
4532     SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts,
4533     unsigned NumParts, MVT PartVT, std::optional<CallingConv::ID> CC) const {
4534   EVT ValueVT = Val.getValueType();
4535   if ((ValueVT == MVT::f16 || ValueVT == MVT::bf16) && PartVT == MVT::f32) {
4536     unsigned ValueBits = ValueVT.getSizeInBits();
4537     unsigned PartBits = PartVT.getSizeInBits();
4538     Val = DAG.getNode(ISD::BITCAST, DL, MVT::getIntegerVT(ValueBits), Val);
4539     Val = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::getIntegerVT(PartBits), Val);
4540     Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
4541     Parts[0] = Val;
4542     return true;
4543   }
4544   return false;
4545 }
4546 
joinRegisterPartsIntoValue(SelectionDAG & DAG,const SDLoc & DL,const SDValue * Parts,unsigned NumParts,MVT PartVT,EVT ValueVT,std::optional<CallingConv::ID> CC) const4547 SDValue ARMTargetLowering::joinRegisterPartsIntoValue(
4548     SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts,
4549     MVT PartVT, EVT ValueVT, std::optional<CallingConv::ID> CC) const {
4550   if ((ValueVT == MVT::f16 || ValueVT == MVT::bf16) && PartVT == MVT::f32) {
4551     unsigned ValueBits = ValueVT.getSizeInBits();
4552     unsigned PartBits = PartVT.getSizeInBits();
4553     SDValue Val = Parts[0];
4554 
4555     Val = DAG.getNode(ISD::BITCAST, DL, MVT::getIntegerVT(PartBits), Val);
4556     Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::getIntegerVT(ValueBits), Val);
4557     Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
4558     return Val;
4559   }
4560   return SDValue();
4561 }
4562 
LowerFormalArguments(SDValue Chain,CallingConv::ID CallConv,bool isVarArg,const SmallVectorImpl<ISD::InputArg> & Ins,const SDLoc & dl,SelectionDAG & DAG,SmallVectorImpl<SDValue> & InVals) const4563 SDValue ARMTargetLowering::LowerFormalArguments(
4564     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
4565     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4566     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
4567   MachineFunction &MF = DAG.getMachineFunction();
4568   MachineFrameInfo &MFI = MF.getFrameInfo();
4569 
4570   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
4571 
4572   // Assign locations to all of the incoming arguments.
4573   SmallVector<CCValAssign, 16> ArgLocs;
4574   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
4575                  *DAG.getContext());
4576   CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForCall(CallConv, isVarArg));
4577 
4578   Function::const_arg_iterator CurOrigArg = MF.getFunction().arg_begin();
4579   unsigned CurArgIdx = 0;
4580 
4581   // Initially ArgRegsSaveSize is zero.
4582   // Then we increase this value each time we meet byval parameter.
4583   // We also increase this value in case of varargs function.
4584   AFI->setArgRegsSaveSize(0);
4585 
4586   // Calculate the amount of stack space that we need to allocate to store
4587   // byval and variadic arguments that are passed in registers.
4588   // We need to know this before we allocate the first byval or variadic
4589   // argument, as they will be allocated a stack slot below the CFA (Canonical
4590   // Frame Address, the stack pointer at entry to the function).
4591   unsigned ArgRegBegin = ARM::R4;
4592   for (const CCValAssign &VA : ArgLocs) {
4593     if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount())
4594       break;
4595 
4596     unsigned Index = VA.getValNo();
4597     ISD::ArgFlagsTy Flags = Ins[Index].Flags;
4598     if (!Flags.isByVal())
4599       continue;
4600 
4601     assert(VA.isMemLoc() && "unexpected byval pointer in reg");
4602     unsigned RBegin, REnd;
4603     CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd);
4604     ArgRegBegin = std::min(ArgRegBegin, RBegin);
4605 
4606     CCInfo.nextInRegsParam();
4607   }
4608   CCInfo.rewindByValRegsInfo();
4609 
4610   int lastInsIndex = -1;
4611   if (isVarArg && MFI.hasVAStart()) {
4612     unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
4613     if (RegIdx != std::size(GPRArgRegs))
4614       ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]);
4615   }
4616 
4617   unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin);
4618   AFI->setArgRegsSaveSize(TotalArgRegsSaveSize);
4619   auto PtrVT = getPointerTy(DAG.getDataLayout());
4620 
4621   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
4622     CCValAssign &VA = ArgLocs[i];
4623     if (Ins[VA.getValNo()].isOrigArg()) {
4624       std::advance(CurOrigArg,
4625                    Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx);
4626       CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex();
4627     }
4628     // Arguments stored in registers.
4629     if (VA.isRegLoc()) {
4630       EVT RegVT = VA.getLocVT();
4631       SDValue ArgValue;
4632 
4633       if (VA.needsCustom() && VA.getLocVT() == MVT::v2f64) {
4634         // f64 and vector types are split up into multiple registers or
4635         // combinations of registers and stack slots.
4636         SDValue ArgValue1 =
4637             GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
4638         VA = ArgLocs[++i]; // skip ahead to next loc
4639         SDValue ArgValue2;
4640         if (VA.isMemLoc()) {
4641           int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), true);
4642           SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4643           ArgValue2 = DAG.getLoad(
4644               MVT::f64, dl, Chain, FIN,
4645               MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI));
4646         } else {
4647           ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
4648         }
4649         ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
4650         ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, ArgValue,
4651                                ArgValue1, DAG.getIntPtrConstant(0, dl));
4652         ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, ArgValue,
4653                                ArgValue2, DAG.getIntPtrConstant(1, dl));
4654       } else if (VA.needsCustom() && VA.getLocVT() == MVT::f64) {
4655         ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
4656       } else {
4657         const TargetRegisterClass *RC;
4658 
4659         if (RegVT == MVT::f16 || RegVT == MVT::bf16)
4660           RC = &ARM::HPRRegClass;
4661         else if (RegVT == MVT::f32)
4662           RC = &ARM::SPRRegClass;
4663         else if (RegVT == MVT::f64 || RegVT == MVT::v4f16 ||
4664                  RegVT == MVT::v4bf16)
4665           RC = &ARM::DPRRegClass;
4666         else if (RegVT == MVT::v2f64 || RegVT == MVT::v8f16 ||
4667                  RegVT == MVT::v8bf16)
4668           RC = &ARM::QPRRegClass;
4669         else if (RegVT == MVT::i32)
4670           RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass
4671                                            : &ARM::GPRRegClass;
4672         else
4673           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
4674 
4675         // Transform the arguments in physical registers into virtual ones.
4676         Register Reg = MF.addLiveIn(VA.getLocReg(), RC);
4677         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
4678 
4679         // If this value is passed in r0 and has the returned attribute (e.g.
4680         // C++ 'structors), record this fact for later use.
4681         if (VA.getLocReg() == ARM::R0 && Ins[VA.getValNo()].Flags.isReturned()) {
4682           AFI->setPreservesR0();
4683         }
4684       }
4685 
4686       // If this is an 8 or 16-bit value, it is really passed promoted
4687       // to 32 bits.  Insert an assert[sz]ext to capture this, then
4688       // truncate to the right size.
4689       switch (VA.getLocInfo()) {
4690       default: llvm_unreachable("Unknown loc info!");
4691       case CCValAssign::Full: break;
4692       case CCValAssign::BCvt:
4693         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
4694         break;
4695       }
4696 
4697       // f16 arguments have their size extended to 4 bytes and passed as if they
4698       // had been copied to the LSBs of a 32-bit register.
4699       // For that, it's passed extended to i32 (soft ABI) or to f32 (hard ABI)
4700       if (VA.needsCustom() &&
4701           (VA.getValVT() == MVT::f16 || VA.getValVT() == MVT::bf16))
4702         ArgValue = MoveToHPR(dl, DAG, VA.getLocVT(), VA.getValVT(), ArgValue);
4703 
4704       // On CMSE Entry Functions, formal integer arguments whose bitwidth is
4705       // less than 32 bits must be sign- or zero-extended in the callee for
4706       // security reasons. Although the ABI mandates an extension done by the
4707       // caller, the latter cannot be trusted to follow the rules of the ABI.
4708       const ISD::InputArg &Arg = Ins[VA.getValNo()];
4709       if (AFI->isCmseNSEntryFunction() && Arg.ArgVT.isScalarInteger() &&
4710           RegVT.isScalarInteger() && Arg.ArgVT.bitsLT(MVT::i32))
4711         ArgValue = handleCMSEValue(ArgValue, Arg, DAG, dl);
4712 
4713       InVals.push_back(ArgValue);
4714     } else { // VA.isRegLoc()
4715       // Only arguments passed on the stack should make it here.
4716       assert(VA.isMemLoc());
4717       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
4718 
4719       int index = VA.getValNo();
4720 
4721       // Some Ins[] entries become multiple ArgLoc[] entries.
4722       // Process them only once.
4723       if (index != lastInsIndex)
4724         {
4725           ISD::ArgFlagsTy Flags = Ins[index].Flags;
4726           // FIXME: For now, all byval parameter objects are marked mutable.
4727           // This can be changed with more analysis.
4728           // In case of tail call optimization mark all arguments mutable.
4729           // Since they could be overwritten by lowering of arguments in case of
4730           // a tail call.
4731           if (Flags.isByVal()) {
4732             assert(Ins[index].isOrigArg() &&
4733                    "Byval arguments cannot be implicit");
4734             unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed();
4735 
4736             int FrameIndex = StoreByValRegs(
4737                 CCInfo, DAG, dl, Chain, &*CurOrigArg, CurByValIndex,
4738                 VA.getLocMemOffset(), Flags.getByValSize());
4739             InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT));
4740             CCInfo.nextInRegsParam();
4741           } else if (VA.needsCustom() && (VA.getValVT() == MVT::f16 ||
4742                                           VA.getValVT() == MVT::bf16)) {
4743             // f16 and bf16 values are passed in the least-significant half of
4744             // a 4 byte stack slot. This is done as-if the extension was done
4745             // in a 32-bit register, so the actual bytes used for the value
4746             // differ between little and big endian.
4747             assert(VA.getLocVT().getSizeInBits() == 32);
4748             unsigned FIOffset = VA.getLocMemOffset();
4749             int FI = MFI.CreateFixedObject(VA.getLocVT().getSizeInBits() / 8,
4750                                            FIOffset, true);
4751 
4752             SDValue Addr = DAG.getFrameIndex(FI, PtrVT);
4753             if (DAG.getDataLayout().isBigEndian())
4754               Addr = DAG.getObjectPtrOffset(dl, Addr, TypeSize::getFixed(2));
4755 
4756             InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, Addr,
4757                                          MachinePointerInfo::getFixedStack(
4758                                              DAG.getMachineFunction(), FI)));
4759 
4760           } else {
4761             unsigned FIOffset = VA.getLocMemOffset();
4762             int FI = MFI.CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
4763                                            FIOffset, true);
4764 
4765             // Create load nodes to retrieve arguments from the stack.
4766             SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4767             InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
4768                                          MachinePointerInfo::getFixedStack(
4769                                              DAG.getMachineFunction(), FI)));
4770           }
4771           lastInsIndex = index;
4772         }
4773     }
4774   }
4775 
4776   // varargs
4777   if (isVarArg && MFI.hasVAStart()) {
4778     VarArgStyleRegisters(CCInfo, DAG, dl, Chain, CCInfo.getStackSize(),
4779                          TotalArgRegsSaveSize);
4780     if (AFI->isCmseNSEntryFunction()) {
4781       DAG.getContext()->diagnose(DiagnosticInfoUnsupported(
4782           DAG.getMachineFunction().getFunction(),
4783           "secure entry function must not be variadic", dl.getDebugLoc()));
4784     }
4785   }
4786 
4787   unsigned StackArgSize = CCInfo.getStackSize();
4788   bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
4789   if (canGuaranteeTCO(CallConv, TailCallOpt)) {
4790     // The only way to guarantee a tail call is if the callee restores its
4791     // argument area, but it must also keep the stack aligned when doing so.
4792     MaybeAlign StackAlign = DAG.getDataLayout().getStackAlignment();
4793     assert(StackAlign && "data layout string is missing stack alignment");
4794     StackArgSize = alignTo(StackArgSize, *StackAlign);
4795 
4796     AFI->setArgumentStackToRestore(StackArgSize);
4797   }
4798   AFI->setArgumentStackSize(StackArgSize);
4799 
4800   if (CCInfo.getStackSize() > 0 && AFI->isCmseNSEntryFunction()) {
4801     DAG.getContext()->diagnose(DiagnosticInfoUnsupported(
4802         DAG.getMachineFunction().getFunction(),
4803         "secure entry function requires arguments on stack", dl.getDebugLoc()));
4804   }
4805 
4806   return Chain;
4807 }
4808 
4809 /// isFloatingPointZero - Return true if this is +0.0.
isFloatingPointZero(SDValue Op)4810 static bool isFloatingPointZero(SDValue Op) {
4811   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
4812     return CFP->getValueAPF().isPosZero();
4813   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
4814     // Maybe this has already been legalized into the constant pool?
4815     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
4816       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
4817       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
4818         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
4819           return CFP->getValueAPF().isPosZero();
4820     }
4821   } else if (Op->getOpcode() == ISD::BITCAST &&
4822              Op->getValueType(0) == MVT::f64) {
4823     // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64)
4824     // created by LowerConstantFP().
4825     SDValue BitcastOp = Op->getOperand(0);
4826     if (BitcastOp->getOpcode() == ARMISD::VMOVIMM &&
4827         isNullConstant(BitcastOp->getOperand(0)))
4828       return true;
4829   }
4830   return false;
4831 }
4832 
4833 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
4834 /// the given operands.
getARMCmp(SDValue LHS,SDValue RHS,ISD::CondCode CC,SDValue & ARMcc,SelectionDAG & DAG,const SDLoc & dl) const4835 SDValue ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
4836                                      SDValue &ARMcc, SelectionDAG &DAG,
4837                                      const SDLoc &dl) const {
4838   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
4839     unsigned C = RHSC->getZExtValue();
4840     if (!isLegalICmpImmediate((int32_t)C)) {
4841       // Constant does not fit, try adjusting it by one.
4842       switch (CC) {
4843       default: break;
4844       case ISD::SETLT:
4845       case ISD::SETGE:
4846         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
4847           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
4848           RHS = DAG.getConstant(C - 1, dl, MVT::i32);
4849         }
4850         break;
4851       case ISD::SETULT:
4852       case ISD::SETUGE:
4853         if (C != 0 && isLegalICmpImmediate(C-1)) {
4854           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
4855           RHS = DAG.getConstant(C - 1, dl, MVT::i32);
4856         }
4857         break;
4858       case ISD::SETLE:
4859       case ISD::SETGT:
4860         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
4861           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
4862           RHS = DAG.getConstant(C + 1, dl, MVT::i32);
4863         }
4864         break;
4865       case ISD::SETULE:
4866       case ISD::SETUGT:
4867         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
4868           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
4869           RHS = DAG.getConstant(C + 1, dl, MVT::i32);
4870         }
4871         break;
4872       }
4873     }
4874   } else if ((ARM_AM::getShiftOpcForNode(LHS.getOpcode()) != ARM_AM::no_shift) &&
4875              (ARM_AM::getShiftOpcForNode(RHS.getOpcode()) == ARM_AM::no_shift)) {
4876     // In ARM and Thumb-2, the compare instructions can shift their second
4877     // operand.
4878     CC = ISD::getSetCCSwappedOperands(CC);
4879     std::swap(LHS, RHS);
4880   }
4881 
4882   // Thumb1 has very limited immediate modes, so turning an "and" into a
4883   // shift can save multiple instructions.
4884   //
4885   // If we have (x & C1), and C1 is an appropriate mask, we can transform it
4886   // into "((x << n) >> n)".  But that isn't necessarily profitable on its
4887   // own. If it's the operand to an unsigned comparison with an immediate,
4888   // we can eliminate one of the shifts: we transform
4889   // "((x << n) >> n) == C2" to "(x << n) == (C2 << n)".
4890   //
4891   // We avoid transforming cases which aren't profitable due to encoding
4892   // details:
4893   //
4894   // 1. C2 fits into the immediate field of a cmp, and the transformed version
4895   // would not; in that case, we're essentially trading one immediate load for
4896   // another.
4897   // 2. C1 is 255 or 65535, so we can use uxtb or uxth.
4898   // 3. C2 is zero; we have other code for this special case.
4899   //
4900   // FIXME: Figure out profitability for Thumb2; we usually can't save an
4901   // instruction, since the AND is always one instruction anyway, but we could
4902   // use narrow instructions in some cases.
4903   if (Subtarget->isThumb1Only() && LHS->getOpcode() == ISD::AND &&
4904       LHS->hasOneUse() && isa<ConstantSDNode>(LHS.getOperand(1)) &&
4905       LHS.getValueType() == MVT::i32 && isa<ConstantSDNode>(RHS) &&
4906       !isSignedIntSetCC(CC)) {
4907     unsigned Mask = LHS.getConstantOperandVal(1);
4908     auto *RHSC = cast<ConstantSDNode>(RHS.getNode());
4909     uint64_t RHSV = RHSC->getZExtValue();
4910     if (isMask_32(Mask) && (RHSV & ~Mask) == 0 && Mask != 255 && Mask != 65535) {
4911       unsigned ShiftBits = llvm::countl_zero(Mask);
4912       if (RHSV && (RHSV > 255 || (RHSV << ShiftBits) <= 255)) {
4913         SDValue ShiftAmt = DAG.getConstant(ShiftBits, dl, MVT::i32);
4914         LHS = DAG.getNode(ISD::SHL, dl, MVT::i32, LHS.getOperand(0), ShiftAmt);
4915         RHS = DAG.getConstant(RHSV << ShiftBits, dl, MVT::i32);
4916       }
4917     }
4918   }
4919 
4920   // The specific comparison "(x<<c) > 0x80000000U" can be optimized to a
4921   // single "lsls x, c+1".  The shift sets the "C" and "Z" flags the same
4922   // way a cmp would.
4923   // FIXME: Add support for ARM/Thumb2; this would need isel patterns, and
4924   // some tweaks to the heuristics for the previous and->shift transform.
4925   // FIXME: Optimize cases where the LHS isn't a shift.
4926   if (Subtarget->isThumb1Only() && LHS->getOpcode() == ISD::SHL &&
4927       isa<ConstantSDNode>(RHS) && RHS->getAsZExtVal() == 0x80000000U &&
4928       CC == ISD::SETUGT && isa<ConstantSDNode>(LHS.getOperand(1)) &&
4929       LHS.getConstantOperandVal(1) < 31) {
4930     unsigned ShiftAmt = LHS.getConstantOperandVal(1) + 1;
4931     SDValue Shift =
4932         DAG.getNode(ARMISD::LSLS, dl, DAG.getVTList(MVT::i32, FlagsVT),
4933                     LHS.getOperand(0), DAG.getConstant(ShiftAmt, dl, MVT::i32));
4934     ARMcc = DAG.getConstant(ARMCC::HI, dl, MVT::i32);
4935     return Shift.getValue(1);
4936   }
4937 
4938   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
4939 
4940   // If the RHS is a constant zero then the V (overflow) flag will never be
4941   // set. This can allow us to simplify GE to PL or LT to MI, which can be
4942   // simpler for other passes (like the peephole optimiser) to deal with.
4943   if (isNullConstant(RHS)) {
4944     switch (CondCode) {
4945       default: break;
4946       case ARMCC::GE:
4947         CondCode = ARMCC::PL;
4948         break;
4949       case ARMCC::LT:
4950         CondCode = ARMCC::MI;
4951         break;
4952     }
4953   }
4954 
4955   ARMISD::NodeType CompareType;
4956   switch (CondCode) {
4957   default:
4958     CompareType = ARMISD::CMP;
4959     break;
4960   case ARMCC::EQ:
4961   case ARMCC::NE:
4962     // Uses only Z Flag
4963     CompareType = ARMISD::CMPZ;
4964     break;
4965   }
4966   ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
4967   return DAG.getNode(CompareType, dl, FlagsVT, LHS, RHS);
4968 }
4969 
4970 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
getVFPCmp(SDValue LHS,SDValue RHS,SelectionDAG & DAG,const SDLoc & dl,bool Signaling) const4971 SDValue ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS,
4972                                      SelectionDAG &DAG, const SDLoc &dl,
4973                                      bool Signaling) const {
4974   assert(Subtarget->hasFP64() || RHS.getValueType() != MVT::f64);
4975   SDValue Flags;
4976   if (!isFloatingPointZero(RHS))
4977     Flags = DAG.getNode(Signaling ? ARMISD::CMPFPE : ARMISD::CMPFP, dl, FlagsVT,
4978                         LHS, RHS);
4979   else
4980     Flags = DAG.getNode(Signaling ? ARMISD::CMPFPEw0 : ARMISD::CMPFPw0, dl,
4981                         FlagsVT, LHS);
4982   return DAG.getNode(ARMISD::FMSTAT, dl, FlagsVT, Flags);
4983 }
4984 
4985 // This function returns three things: the arithmetic computation itself
4986 // (Value), a comparison (OverflowCmp), and a condition code (ARMcc).  The
4987 // comparison and the condition code define the case in which the arithmetic
4988 // computation *does not* overflow.
4989 std::pair<SDValue, SDValue>
getARMXALUOOp(SDValue Op,SelectionDAG & DAG,SDValue & ARMcc) const4990 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
4991                                  SDValue &ARMcc) const {
4992   assert(Op.getValueType() == MVT::i32 &&  "Unsupported value type");
4993 
4994   SDValue Value, OverflowCmp;
4995   SDValue LHS = Op.getOperand(0);
4996   SDValue RHS = Op.getOperand(1);
4997   SDLoc dl(Op);
4998 
4999   // FIXME: We are currently always generating CMPs because we don't support
5000   // generating CMN through the backend. This is not as good as the natural
5001   // CMP case because it causes a register dependency and cannot be folded
5002   // later.
5003 
5004   switch (Op.getOpcode()) {
5005   default:
5006     llvm_unreachable("Unknown overflow instruction!");
5007   case ISD::SADDO:
5008     ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
5009     Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
5010     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, FlagsVT, Value, LHS);
5011     break;
5012   case ISD::UADDO:
5013     ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
5014     // We use ADDC here to correspond to its use in LowerUnsignedALUO.
5015     // We do not use it in the USUBO case as Value may not be used.
5016     Value = DAG.getNode(ARMISD::ADDC, dl,
5017                         DAG.getVTList(Op.getValueType(), MVT::i32), LHS, RHS)
5018                 .getValue(0);
5019     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, FlagsVT, Value, LHS);
5020     break;
5021   case ISD::SSUBO:
5022     ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
5023     Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
5024     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, FlagsVT, LHS, RHS);
5025     break;
5026   case ISD::USUBO:
5027     ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
5028     Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
5029     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, FlagsVT, LHS, RHS);
5030     break;
5031   case ISD::UMULO:
5032     // We generate a UMUL_LOHI and then check if the high word is 0.
5033     ARMcc = DAG.getConstant(ARMCC::EQ, dl, MVT::i32);
5034     Value = DAG.getNode(ISD::UMUL_LOHI, dl,
5035                         DAG.getVTList(Op.getValueType(), Op.getValueType()),
5036                         LHS, RHS);
5037     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, FlagsVT, Value.getValue(1),
5038                               DAG.getConstant(0, dl, MVT::i32));
5039     Value = Value.getValue(0); // We only want the low 32 bits for the result.
5040     break;
5041   case ISD::SMULO:
5042     // We generate a SMUL_LOHI and then check if all the bits of the high word
5043     // are the same as the sign bit of the low word.
5044     ARMcc = DAG.getConstant(ARMCC::EQ, dl, MVT::i32);
5045     Value = DAG.getNode(ISD::SMUL_LOHI, dl,
5046                         DAG.getVTList(Op.getValueType(), Op.getValueType()),
5047                         LHS, RHS);
5048     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, FlagsVT, Value.getValue(1),
5049                               DAG.getNode(ISD::SRA, dl, Op.getValueType(),
5050                                           Value.getValue(0),
5051                                           DAG.getConstant(31, dl, MVT::i32)));
5052     Value = Value.getValue(0); // We only want the low 32 bits for the result.
5053     break;
5054   } // switch (...)
5055 
5056   return std::make_pair(Value, OverflowCmp);
5057 }
5058 
5059 SDValue
LowerSignedALUO(SDValue Op,SelectionDAG & DAG) const5060 ARMTargetLowering::LowerSignedALUO(SDValue Op, SelectionDAG &DAG) const {
5061   // Let legalize expand this if it isn't a legal type yet.
5062   if (!isTypeLegal(Op.getValueType()))
5063     return SDValue();
5064 
5065   SDValue Value, OverflowCmp;
5066   SDValue ARMcc;
5067   std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
5068   SDLoc dl(Op);
5069   // We use 0 and 1 as false and true values.
5070   SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
5071   SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
5072   EVT VT = Op.getValueType();
5073 
5074   SDValue Overflow =
5075       DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal, ARMcc, OverflowCmp);
5076 
5077   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
5078   return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
5079 }
5080 
ConvertBooleanCarryToCarryFlag(SDValue BoolCarry,SelectionDAG & DAG)5081 static SDValue ConvertBooleanCarryToCarryFlag(SDValue BoolCarry,
5082                                               SelectionDAG &DAG) {
5083   SDLoc DL(BoolCarry);
5084   EVT CarryVT = BoolCarry.getValueType();
5085 
5086   // This converts the boolean value carry into the carry flag by doing
5087   // ARMISD::SUBC Carry, 1
5088   SDValue Carry = DAG.getNode(ARMISD::SUBC, DL,
5089                               DAG.getVTList(CarryVT, MVT::i32),
5090                               BoolCarry, DAG.getConstant(1, DL, CarryVT));
5091   return Carry.getValue(1);
5092 }
5093 
ConvertCarryFlagToBooleanCarry(SDValue Flags,EVT VT,SelectionDAG & DAG)5094 static SDValue ConvertCarryFlagToBooleanCarry(SDValue Flags, EVT VT,
5095                                               SelectionDAG &DAG) {
5096   SDLoc DL(Flags);
5097 
5098   // Now convert the carry flag into a boolean carry. We do this
5099   // using ARMISD:ADDE 0, 0, Carry
5100   return DAG.getNode(ARMISD::ADDE, DL, DAG.getVTList(VT, MVT::i32),
5101                      DAG.getConstant(0, DL, MVT::i32),
5102                      DAG.getConstant(0, DL, MVT::i32), Flags);
5103 }
5104 
LowerUnsignedALUO(SDValue Op,SelectionDAG & DAG) const5105 SDValue ARMTargetLowering::LowerUnsignedALUO(SDValue Op,
5106                                              SelectionDAG &DAG) const {
5107   // Let legalize expand this if it isn't a legal type yet.
5108   if (!isTypeLegal(Op.getValueType()))
5109     return SDValue();
5110 
5111   SDValue LHS = Op.getOperand(0);
5112   SDValue RHS = Op.getOperand(1);
5113   SDLoc dl(Op);
5114 
5115   EVT VT = Op.getValueType();
5116   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
5117   SDValue Value;
5118   SDValue Overflow;
5119   switch (Op.getOpcode()) {
5120   default:
5121     llvm_unreachable("Unknown overflow instruction!");
5122   case ISD::UADDO:
5123     Value = DAG.getNode(ARMISD::ADDC, dl, VTs, LHS, RHS);
5124     // Convert the carry flag into a boolean value.
5125     Overflow = ConvertCarryFlagToBooleanCarry(Value.getValue(1), VT, DAG);
5126     break;
5127   case ISD::USUBO: {
5128     Value = DAG.getNode(ARMISD::SUBC, dl, VTs, LHS, RHS);
5129     // Convert the carry flag into a boolean value.
5130     Overflow = ConvertCarryFlagToBooleanCarry(Value.getValue(1), VT, DAG);
5131     // ARMISD::SUBC returns 0 when we have to borrow, so make it an overflow
5132     // value. So compute 1 - C.
5133     Overflow = DAG.getNode(ISD::SUB, dl, MVT::i32,
5134                            DAG.getConstant(1, dl, MVT::i32), Overflow);
5135     break;
5136   }
5137   }
5138 
5139   return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
5140 }
5141 
LowerADDSUBSAT(SDValue Op,SelectionDAG & DAG,const ARMSubtarget * Subtarget)5142 static SDValue LowerADDSUBSAT(SDValue Op, SelectionDAG &DAG,
5143                               const ARMSubtarget *Subtarget) {
5144   EVT VT = Op.getValueType();
5145   if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP() || Subtarget->isThumb1Only())
5146     return SDValue();
5147   if (!VT.isSimple())
5148     return SDValue();
5149 
5150   unsigned NewOpcode;
5151   switch (VT.getSimpleVT().SimpleTy) {
5152   default:
5153     return SDValue();
5154   case MVT::i8:
5155     switch (Op->getOpcode()) {
5156     case ISD::UADDSAT:
5157       NewOpcode = ARMISD::UQADD8b;
5158       break;
5159     case ISD::SADDSAT:
5160       NewOpcode = ARMISD::QADD8b;
5161       break;
5162     case ISD::USUBSAT:
5163       NewOpcode = ARMISD::UQSUB8b;
5164       break;
5165     case ISD::SSUBSAT:
5166       NewOpcode = ARMISD::QSUB8b;
5167       break;
5168     }
5169     break;
5170   case MVT::i16:
5171     switch (Op->getOpcode()) {
5172     case ISD::UADDSAT:
5173       NewOpcode = ARMISD::UQADD16b;
5174       break;
5175     case ISD::SADDSAT:
5176       NewOpcode = ARMISD::QADD16b;
5177       break;
5178     case ISD::USUBSAT:
5179       NewOpcode = ARMISD::UQSUB16b;
5180       break;
5181     case ISD::SSUBSAT:
5182       NewOpcode = ARMISD::QSUB16b;
5183       break;
5184     }
5185     break;
5186   }
5187 
5188   SDLoc dl(Op);
5189   SDValue Add =
5190       DAG.getNode(NewOpcode, dl, MVT::i32,
5191                   DAG.getSExtOrTrunc(Op->getOperand(0), dl, MVT::i32),
5192                   DAG.getSExtOrTrunc(Op->getOperand(1), dl, MVT::i32));
5193   return DAG.getNode(ISD::TRUNCATE, dl, VT, Add);
5194 }
5195 
LowerSELECT(SDValue Op,SelectionDAG & DAG) const5196 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
5197   SDValue Cond = Op.getOperand(0);
5198   SDValue SelectTrue = Op.getOperand(1);
5199   SDValue SelectFalse = Op.getOperand(2);
5200   SDLoc dl(Op);
5201   unsigned Opc = Cond.getOpcode();
5202 
5203   if (Cond.getResNo() == 1 &&
5204       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
5205        Opc == ISD::USUBO)) {
5206     if (!isTypeLegal(Cond->getValueType(0)))
5207       return SDValue();
5208 
5209     SDValue Value, OverflowCmp;
5210     SDValue ARMcc;
5211     std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
5212     EVT VT = Op.getValueType();
5213 
5214     return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, OverflowCmp, DAG);
5215   }
5216 
5217   // Convert:
5218   //
5219   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
5220   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
5221   //
5222   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
5223     const ConstantSDNode *CMOVTrue =
5224       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
5225     const ConstantSDNode *CMOVFalse =
5226       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
5227 
5228     if (CMOVTrue && CMOVFalse) {
5229       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
5230       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
5231 
5232       SDValue True;
5233       SDValue False;
5234       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
5235         True = SelectTrue;
5236         False = SelectFalse;
5237       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
5238         True = SelectFalse;
5239         False = SelectTrue;
5240       }
5241 
5242       if (True.getNode() && False.getNode())
5243         return getCMOV(dl, Op.getValueType(), True, False, Cond.getOperand(2),
5244                        Cond.getOperand(3), DAG);
5245     }
5246   }
5247 
5248   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
5249   // undefined bits before doing a full-word comparison with zero.
5250   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
5251                      DAG.getConstant(1, dl, Cond.getValueType()));
5252 
5253   return DAG.getSelectCC(dl, Cond,
5254                          DAG.getConstant(0, dl, Cond.getValueType()),
5255                          SelectTrue, SelectFalse, ISD::SETNE);
5256 }
5257 
checkVSELConstraints(ISD::CondCode CC,ARMCC::CondCodes & CondCode,bool & swpCmpOps,bool & swpVselOps)5258 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
5259                                  bool &swpCmpOps, bool &swpVselOps) {
5260   // Start by selecting the GE condition code for opcodes that return true for
5261   // 'equality'
5262   if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
5263       CC == ISD::SETULE || CC == ISD::SETGE  || CC == ISD::SETLE)
5264     CondCode = ARMCC::GE;
5265 
5266   // and GT for opcodes that return false for 'equality'.
5267   else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
5268            CC == ISD::SETULT || CC == ISD::SETGT  || CC == ISD::SETLT)
5269     CondCode = ARMCC::GT;
5270 
5271   // Since we are constrained to GE/GT, if the opcode contains 'less', we need
5272   // to swap the compare operands.
5273   if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
5274       CC == ISD::SETULT || CC == ISD::SETLE  || CC == ISD::SETLT)
5275     swpCmpOps = true;
5276 
5277   // Both GT and GE are ordered comparisons, and return false for 'unordered'.
5278   // If we have an unordered opcode, we need to swap the operands to the VSEL
5279   // instruction (effectively negating the condition).
5280   //
5281   // This also has the effect of swapping which one of 'less' or 'greater'
5282   // returns true, so we also swap the compare operands. It also switches
5283   // whether we return true for 'equality', so we compensate by picking the
5284   // opposite condition code to our original choice.
5285   if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
5286       CC == ISD::SETUGT) {
5287     swpCmpOps = !swpCmpOps;
5288     swpVselOps = !swpVselOps;
5289     CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
5290   }
5291 
5292   // 'ordered' is 'anything but unordered', so use the VS condition code and
5293   // swap the VSEL operands.
5294   if (CC == ISD::SETO) {
5295     CondCode = ARMCC::VS;
5296     swpVselOps = true;
5297   }
5298 
5299   // 'unordered or not equal' is 'anything but equal', so use the EQ condition
5300   // code and swap the VSEL operands. Also do this if we don't care about the
5301   // unordered case.
5302   if (CC == ISD::SETUNE || CC == ISD::SETNE) {
5303     CondCode = ARMCC::EQ;
5304     swpVselOps = true;
5305   }
5306 }
5307 
getCMOV(const SDLoc & dl,EVT VT,SDValue FalseVal,SDValue TrueVal,SDValue ARMcc,SDValue Flags,SelectionDAG & DAG) const5308 SDValue ARMTargetLowering::getCMOV(const SDLoc &dl, EVT VT, SDValue FalseVal,
5309                                    SDValue TrueVal, SDValue ARMcc,
5310                                    SDValue Flags, SelectionDAG &DAG) const {
5311   if (!Subtarget->hasFP64() && VT == MVT::f64) {
5312     FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl,
5313                            DAG.getVTList(MVT::i32, MVT::i32), FalseVal);
5314     TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl,
5315                           DAG.getVTList(MVT::i32, MVT::i32), TrueVal);
5316 
5317     SDValue TrueLow = TrueVal.getValue(0);
5318     SDValue TrueHigh = TrueVal.getValue(1);
5319     SDValue FalseLow = FalseVal.getValue(0);
5320     SDValue FalseHigh = FalseVal.getValue(1);
5321 
5322     SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow,
5323                               ARMcc, Flags);
5324     SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh,
5325                                ARMcc, Flags);
5326 
5327     return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High);
5328   }
5329   return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, Flags);
5330 }
5331 
isGTorGE(ISD::CondCode CC)5332 static bool isGTorGE(ISD::CondCode CC) {
5333   return CC == ISD::SETGT || CC == ISD::SETGE;
5334 }
5335 
isLTorLE(ISD::CondCode CC)5336 static bool isLTorLE(ISD::CondCode CC) {
5337   return CC == ISD::SETLT || CC == ISD::SETLE;
5338 }
5339 
5340 // See if a conditional (LHS CC RHS ? TrueVal : FalseVal) is lower-saturating.
5341 // All of these conditions (and their <= and >= counterparts) will do:
5342 //          x < k ? k : x
5343 //          x > k ? x : k
5344 //          k < x ? x : k
5345 //          k > x ? k : x
isLowerSaturate(const SDValue LHS,const SDValue RHS,const SDValue TrueVal,const SDValue FalseVal,const ISD::CondCode CC,const SDValue K)5346 static bool isLowerSaturate(const SDValue LHS, const SDValue RHS,
5347                             const SDValue TrueVal, const SDValue FalseVal,
5348                             const ISD::CondCode CC, const SDValue K) {
5349   return (isGTorGE(CC) &&
5350           ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal))) ||
5351          (isLTorLE(CC) &&
5352           ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal)));
5353 }
5354 
5355 // Check if two chained conditionals could be converted into SSAT or USAT.
5356 //
5357 // SSAT can replace a set of two conditional selectors that bound a number to an
5358 // interval of type [k, ~k] when k + 1 is a power of 2. Here are some examples:
5359 //
5360 //     x < -k ? -k : (x > k ? k : x)
5361 //     x < -k ? -k : (x < k ? x : k)
5362 //     x > -k ? (x > k ? k : x) : -k
5363 //     x < k ? (x < -k ? -k : x) : k
5364 //     etc.
5365 //
5366 // LLVM canonicalizes these to either a min(max()) or a max(min())
5367 // pattern. This function tries to match one of these and will return a SSAT
5368 // node if successful.
5369 //
5370 // USAT works similarily to SSAT but bounds on the interval [0, k] where k + 1
5371 // is a power of 2.
LowerSaturatingConditional(SDValue Op,SelectionDAG & DAG)5372 static SDValue LowerSaturatingConditional(SDValue Op, SelectionDAG &DAG) {
5373   EVT VT = Op.getValueType();
5374   SDValue V1 = Op.getOperand(0);
5375   SDValue K1 = Op.getOperand(1);
5376   SDValue TrueVal1 = Op.getOperand(2);
5377   SDValue FalseVal1 = Op.getOperand(3);
5378   ISD::CondCode CC1 = cast<CondCodeSDNode>(Op.getOperand(4))->get();
5379 
5380   const SDValue Op2 = isa<ConstantSDNode>(TrueVal1) ? FalseVal1 : TrueVal1;
5381   if (Op2.getOpcode() != ISD::SELECT_CC)
5382     return SDValue();
5383 
5384   SDValue V2 = Op2.getOperand(0);
5385   SDValue K2 = Op2.getOperand(1);
5386   SDValue TrueVal2 = Op2.getOperand(2);
5387   SDValue FalseVal2 = Op2.getOperand(3);
5388   ISD::CondCode CC2 = cast<CondCodeSDNode>(Op2.getOperand(4))->get();
5389 
5390   SDValue V1Tmp = V1;
5391   SDValue V2Tmp = V2;
5392 
5393   // Check that the registers and the constants match a max(min()) or min(max())
5394   // pattern
5395   if (V1Tmp != TrueVal1 || V2Tmp != TrueVal2 || K1 != FalseVal1 ||
5396       K2 != FalseVal2 ||
5397       !((isGTorGE(CC1) && isLTorLE(CC2)) || (isLTorLE(CC1) && isGTorGE(CC2))))
5398     return SDValue();
5399 
5400   // Check that the constant in the lower-bound check is
5401   // the opposite of the constant in the upper-bound check
5402   // in 1's complement.
5403   if (!isa<ConstantSDNode>(K1) || !isa<ConstantSDNode>(K2))
5404     return SDValue();
5405 
5406   int64_t Val1 = cast<ConstantSDNode>(K1)->getSExtValue();
5407   int64_t Val2 = cast<ConstantSDNode>(K2)->getSExtValue();
5408   int64_t PosVal = std::max(Val1, Val2);
5409   int64_t NegVal = std::min(Val1, Val2);
5410 
5411   if (!((Val1 > Val2 && isLTorLE(CC1)) || (Val1 < Val2 && isLTorLE(CC2))) ||
5412       !isPowerOf2_64(PosVal + 1))
5413     return SDValue();
5414 
5415   // Handle the difference between USAT (unsigned) and SSAT (signed)
5416   // saturation
5417   // At this point, PosVal is guaranteed to be positive
5418   uint64_t K = PosVal;
5419   SDLoc dl(Op);
5420   if (Val1 == ~Val2)
5421     return DAG.getNode(ARMISD::SSAT, dl, VT, V2Tmp,
5422                        DAG.getConstant(llvm::countr_one(K), dl, VT));
5423   if (NegVal == 0)
5424     return DAG.getNode(ARMISD::USAT, dl, VT, V2Tmp,
5425                        DAG.getConstant(llvm::countr_one(K), dl, VT));
5426 
5427   return SDValue();
5428 }
5429 
5430 // Check if a condition of the type x < k ? k : x can be converted into a
5431 // bit operation instead of conditional moves.
5432 // Currently this is allowed given:
5433 // - The conditions and values match up
5434 // - k is 0 or -1 (all ones)
5435 // This function will not check the last condition, thats up to the caller
5436 // It returns true if the transformation can be made, and in such case
5437 // returns x in V, and k in SatK.
isLowerSaturatingConditional(const SDValue & Op,SDValue & V,SDValue & SatK)5438 static bool isLowerSaturatingConditional(const SDValue &Op, SDValue &V,
5439                                          SDValue &SatK)
5440 {
5441   SDValue LHS = Op.getOperand(0);
5442   SDValue RHS = Op.getOperand(1);
5443   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
5444   SDValue TrueVal = Op.getOperand(2);
5445   SDValue FalseVal = Op.getOperand(3);
5446 
5447   SDValue *K = isa<ConstantSDNode>(LHS) ? &LHS : isa<ConstantSDNode>(RHS)
5448                                                ? &RHS
5449                                                : nullptr;
5450 
5451   // No constant operation in comparison, early out
5452   if (!K)
5453     return false;
5454 
5455   SDValue KTmp = isa<ConstantSDNode>(TrueVal) ? TrueVal : FalseVal;
5456   V = (KTmp == TrueVal) ? FalseVal : TrueVal;
5457   SDValue VTmp = (K && *K == LHS) ? RHS : LHS;
5458 
5459   // If the constant on left and right side, or variable on left and right,
5460   // does not match, early out
5461   if (*K != KTmp || V != VTmp)
5462     return false;
5463 
5464   if (isLowerSaturate(LHS, RHS, TrueVal, FalseVal, CC, *K)) {
5465     SatK = *K;
5466     return true;
5467   }
5468 
5469   return false;
5470 }
5471 
isUnsupportedFloatingType(EVT VT) const5472 bool ARMTargetLowering::isUnsupportedFloatingType(EVT VT) const {
5473   if (VT == MVT::f32)
5474     return !Subtarget->hasVFP2Base();
5475   if (VT == MVT::f64)
5476     return !Subtarget->hasFP64();
5477   if (VT == MVT::f16)
5478     return !Subtarget->hasFullFP16();
5479   return false;
5480 }
5481 
LowerSELECT_CC(SDValue Op,SelectionDAG & DAG) const5482 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
5483   EVT VT = Op.getValueType();
5484   SDLoc dl(Op);
5485 
5486   // Try to convert two saturating conditional selects into a single SSAT
5487   if ((!Subtarget->isThumb() && Subtarget->hasV6Ops()) || Subtarget->isThumb2())
5488     if (SDValue SatValue = LowerSaturatingConditional(Op, DAG))
5489       return SatValue;
5490 
5491   // Try to convert expressions of the form x < k ? k : x (and similar forms)
5492   // into more efficient bit operations, which is possible when k is 0 or -1
5493   // On ARM and Thumb-2 which have flexible operand 2 this will result in
5494   // single instructions. On Thumb the shift and the bit operation will be two
5495   // instructions.
5496   // Only allow this transformation on full-width (32-bit) operations
5497   SDValue LowerSatConstant;
5498   SDValue SatValue;
5499   if (VT == MVT::i32 &&
5500       isLowerSaturatingConditional(Op, SatValue, LowerSatConstant)) {
5501     SDValue ShiftV = DAG.getNode(ISD::SRA, dl, VT, SatValue,
5502                                  DAG.getConstant(31, dl, VT));
5503     if (isNullConstant(LowerSatConstant)) {
5504       SDValue NotShiftV = DAG.getNode(ISD::XOR, dl, VT, ShiftV,
5505                                       DAG.getAllOnesConstant(dl, VT));
5506       return DAG.getNode(ISD::AND, dl, VT, SatValue, NotShiftV);
5507     } else if (isAllOnesConstant(LowerSatConstant))
5508       return DAG.getNode(ISD::OR, dl, VT, SatValue, ShiftV);
5509   }
5510 
5511   SDValue LHS = Op.getOperand(0);
5512   SDValue RHS = Op.getOperand(1);
5513   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
5514   SDValue TrueVal = Op.getOperand(2);
5515   SDValue FalseVal = Op.getOperand(3);
5516   ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FalseVal);
5517   ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TrueVal);
5518   ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS);
5519   if (Op.getValueType().isInteger()) {
5520     // Check for sign pattern (SELECT_CC setgt, iN lhs, -1, 1, -1) and transform
5521     // into (OR (ASR lhs, N-1), 1), which requires less instructions for the
5522     // supported types.
5523     if (CC == ISD::SETGT && RHSC && RHSC->isAllOnes() && CTVal && CFVal &&
5524         CTVal->isOne() && CFVal->isAllOnes() &&
5525         LHS.getValueType() == TrueVal.getValueType()) {
5526       EVT VT = LHS.getValueType();
5527       SDValue Shift =
5528           DAG.getNode(ISD::SRA, dl, VT, LHS,
5529                       DAG.getConstant(VT.getSizeInBits() - 1, dl, VT));
5530       return DAG.getNode(ISD::OR, dl, VT, Shift, DAG.getConstant(1, dl, VT));
5531     }
5532 
5533     // Check for SMAX(lhs, 0) and SMIN(lhs, 0) patterns.
5534     // (SELECT_CC setgt, lhs, 0, lhs, 0) -> (BIC lhs, (SRA lhs, typesize-1))
5535     // (SELECT_CC setlt, lhs, 0, lhs, 0) -> (AND lhs, (SRA lhs, typesize-1))
5536     // Both require less instructions than compare and conditional select.
5537     if ((CC == ISD::SETGT || CC == ISD::SETLT) && LHS == TrueVal && RHSC &&
5538         RHSC->isZero() && CFVal && CFVal->isZero() &&
5539         LHS.getValueType() == RHS.getValueType()) {
5540       EVT VT = LHS.getValueType();
5541       SDValue Shift =
5542           DAG.getNode(ISD::SRA, dl, VT, LHS,
5543                       DAG.getConstant(VT.getSizeInBits() - 1, dl, VT));
5544 
5545       if (CC == ISD::SETGT)
5546         Shift = DAG.getNOT(dl, Shift, VT);
5547 
5548       return DAG.getNode(ISD::AND, dl, VT, LHS, Shift);
5549     }
5550   }
5551 
5552   if (Subtarget->hasV8_1MMainlineOps() && CFVal && CTVal &&
5553       LHS.getValueType() == MVT::i32 && RHS.getValueType() == MVT::i32) {
5554     unsigned TVal = CTVal->getZExtValue();
5555     unsigned FVal = CFVal->getZExtValue();
5556     unsigned Opcode = 0;
5557 
5558     if (TVal == ~FVal) {
5559       Opcode = ARMISD::CSINV;
5560     } else if (TVal == ~FVal + 1) {
5561       Opcode = ARMISD::CSNEG;
5562     } else if (TVal + 1 == FVal) {
5563       Opcode = ARMISD::CSINC;
5564     } else if (TVal == FVal + 1) {
5565       Opcode = ARMISD::CSINC;
5566       std::swap(TrueVal, FalseVal);
5567       std::swap(TVal, FVal);
5568       CC = ISD::getSetCCInverse(CC, LHS.getValueType());
5569     }
5570 
5571     if (Opcode) {
5572       // If one of the constants is cheaper than another, materialise the
5573       // cheaper one and let the csel generate the other.
5574       if (Opcode != ARMISD::CSINC &&
5575           HasLowerConstantMaterializationCost(FVal, TVal, Subtarget)) {
5576         std::swap(TrueVal, FalseVal);
5577         std::swap(TVal, FVal);
5578         CC = ISD::getSetCCInverse(CC, LHS.getValueType());
5579       }
5580 
5581       // Attempt to use ZR checking TVal is 0, possibly inverting the condition
5582       // to get there. CSINC not is invertable like the other two (~(~a) == a,
5583       // -(-a) == a, but (a+1)+1 != a).
5584       if (FVal == 0 && Opcode != ARMISD::CSINC) {
5585         std::swap(TrueVal, FalseVal);
5586         std::swap(TVal, FVal);
5587         CC = ISD::getSetCCInverse(CC, LHS.getValueType());
5588       }
5589 
5590       // Drops F's value because we can get it by inverting/negating TVal.
5591       FalseVal = TrueVal;
5592 
5593       SDValue ARMcc;
5594       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
5595       EVT VT = TrueVal.getValueType();
5596       return DAG.getNode(Opcode, dl, VT, TrueVal, FalseVal, ARMcc, Cmp);
5597     }
5598   }
5599 
5600   if (isUnsupportedFloatingType(LHS.getValueType())) {
5601     softenSetCCOperands(DAG, LHS.getValueType(), LHS, RHS, CC, dl, LHS, RHS);
5602 
5603     // If softenSetCCOperands only returned one value, we should compare it to
5604     // zero.
5605     if (!RHS.getNode()) {
5606       RHS = DAG.getConstant(0, dl, LHS.getValueType());
5607       CC = ISD::SETNE;
5608     }
5609   }
5610 
5611   if (LHS.getValueType() == MVT::i32) {
5612     // Try to generate VSEL on ARMv8.
5613     // The VSEL instruction can't use all the usual ARM condition
5614     // codes: it only has two bits to select the condition code, so it's
5615     // constrained to use only GE, GT, VS and EQ.
5616     //
5617     // To implement all the various ISD::SETXXX opcodes, we sometimes need to
5618     // swap the operands of the previous compare instruction (effectively
5619     // inverting the compare condition, swapping 'less' and 'greater') and
5620     // sometimes need to swap the operands to the VSEL (which inverts the
5621     // condition in the sense of firing whenever the previous condition didn't)
5622     if (Subtarget->hasFPARMv8Base() && (TrueVal.getValueType() == MVT::f16 ||
5623                                         TrueVal.getValueType() == MVT::f32 ||
5624                                         TrueVal.getValueType() == MVT::f64)) {
5625       ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
5626       if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
5627           CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
5628         CC = ISD::getSetCCInverse(CC, LHS.getValueType());
5629         std::swap(TrueVal, FalseVal);
5630       }
5631     }
5632 
5633     SDValue ARMcc;
5634     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
5635     // Choose GE over PL, which vsel does now support
5636     if (ARMcc->getAsZExtVal() == ARMCC::PL)
5637       ARMcc = DAG.getConstant(ARMCC::GE, dl, MVT::i32);
5638     return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, Cmp, DAG);
5639   }
5640 
5641   ARMCC::CondCodes CondCode, CondCode2;
5642   FPCCToARMCC(CC, CondCode, CondCode2);
5643 
5644   // Normalize the fp compare. If RHS is zero we prefer to keep it there so we
5645   // match CMPFPw0 instead of CMPFP, though we don't do this for f16 because we
5646   // must use VSEL (limited condition codes), due to not having conditional f16
5647   // moves.
5648   if (Subtarget->hasFPARMv8Base() &&
5649       !(isFloatingPointZero(RHS) && TrueVal.getValueType() != MVT::f16) &&
5650       (TrueVal.getValueType() == MVT::f16 ||
5651        TrueVal.getValueType() == MVT::f32 ||
5652        TrueVal.getValueType() == MVT::f64)) {
5653     bool swpCmpOps = false;
5654     bool swpVselOps = false;
5655     checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
5656 
5657     if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
5658         CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
5659       if (swpCmpOps)
5660         std::swap(LHS, RHS);
5661       if (swpVselOps)
5662         std::swap(TrueVal, FalseVal);
5663     }
5664   }
5665 
5666   SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
5667   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
5668   SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, Cmp, DAG);
5669   if (CondCode2 != ARMCC::AL) {
5670     SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32);
5671     Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, Cmp, DAG);
5672   }
5673   return Result;
5674 }
5675 
5676 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
5677 /// to morph to an integer compare sequence.
canChangeToInt(SDValue Op,bool & SeenZero,const ARMSubtarget * Subtarget)5678 static bool canChangeToInt(SDValue Op, bool &SeenZero,
5679                            const ARMSubtarget *Subtarget) {
5680   SDNode *N = Op.getNode();
5681   if (!N->hasOneUse())
5682     // Otherwise it requires moving the value from fp to integer registers.
5683     return false;
5684   if (!N->getNumValues())
5685     return false;
5686   EVT VT = Op.getValueType();
5687   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
5688     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
5689     // vmrs are very slow, e.g. cortex-a8.
5690     return false;
5691 
5692   if (isFloatingPointZero(Op)) {
5693     SeenZero = true;
5694     return true;
5695   }
5696   return ISD::isNormalLoad(N);
5697 }
5698 
bitcastf32Toi32(SDValue Op,SelectionDAG & DAG)5699 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
5700   if (isFloatingPointZero(Op))
5701     return DAG.getConstant(0, SDLoc(Op), MVT::i32);
5702 
5703   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
5704     return DAG.getLoad(MVT::i32, SDLoc(Op), Ld->getChain(), Ld->getBasePtr(),
5705                        Ld->getPointerInfo(), Ld->getAlign(),
5706                        Ld->getMemOperand()->getFlags());
5707 
5708   llvm_unreachable("Unknown VFP cmp argument!");
5709 }
5710 
expandf64Toi32(SDValue Op,SelectionDAG & DAG,SDValue & RetVal1,SDValue & RetVal2)5711 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
5712                            SDValue &RetVal1, SDValue &RetVal2) {
5713   SDLoc dl(Op);
5714 
5715   if (isFloatingPointZero(Op)) {
5716     RetVal1 = DAG.getConstant(0, dl, MVT::i32);
5717     RetVal2 = DAG.getConstant(0, dl, MVT::i32);
5718     return;
5719   }
5720 
5721   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
5722     SDValue Ptr = Ld->getBasePtr();
5723     RetVal1 =
5724         DAG.getLoad(MVT::i32, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
5725                     Ld->getAlign(), Ld->getMemOperand()->getFlags());
5726 
5727     EVT PtrType = Ptr.getValueType();
5728     SDValue NewPtr = DAG.getNode(ISD::ADD, dl,
5729                                  PtrType, Ptr, DAG.getConstant(4, dl, PtrType));
5730     RetVal2 = DAG.getLoad(MVT::i32, dl, Ld->getChain(), NewPtr,
5731                           Ld->getPointerInfo().getWithOffset(4),
5732                           commonAlignment(Ld->getAlign(), 4),
5733                           Ld->getMemOperand()->getFlags());
5734     return;
5735   }
5736 
5737   llvm_unreachable("Unknown VFP cmp argument!");
5738 }
5739 
5740 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
5741 /// f32 and even f64 comparisons to integer ones.
5742 SDValue
OptimizeVFPBrcond(SDValue Op,SelectionDAG & DAG) const5743 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
5744   SDValue Chain = Op.getOperand(0);
5745   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
5746   SDValue LHS = Op.getOperand(2);
5747   SDValue RHS = Op.getOperand(3);
5748   SDValue Dest = Op.getOperand(4);
5749   SDLoc dl(Op);
5750 
5751   bool LHSSeenZero = false;
5752   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
5753   bool RHSSeenZero = false;
5754   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
5755   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
5756     // If unsafe fp math optimization is enabled and there are no other uses of
5757     // the CMP operands, and the condition code is EQ or NE, we can optimize it
5758     // to an integer comparison.
5759     if (CC == ISD::SETOEQ)
5760       CC = ISD::SETEQ;
5761     else if (CC == ISD::SETUNE)
5762       CC = ISD::SETNE;
5763 
5764     SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32);
5765     SDValue ARMcc;
5766     if (LHS.getValueType() == MVT::f32) {
5767       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
5768                         bitcastf32Toi32(LHS, DAG), Mask);
5769       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
5770                         bitcastf32Toi32(RHS, DAG), Mask);
5771       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
5772       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc,
5773                          Cmp);
5774     }
5775 
5776     SDValue LHS1, LHS2;
5777     SDValue RHS1, RHS2;
5778     expandf64Toi32(LHS, DAG, LHS1, LHS2);
5779     expandf64Toi32(RHS, DAG, RHS1, RHS2);
5780     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
5781     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
5782     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
5783     ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
5784     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
5785     return DAG.getNode(ARMISD::BCC_i64, dl, MVT::Other, Ops);
5786   }
5787 
5788   return SDValue();
5789 }
5790 
LowerBRCOND(SDValue Op,SelectionDAG & DAG) const5791 SDValue ARMTargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
5792   SDValue Chain = Op.getOperand(0);
5793   SDValue Cond = Op.getOperand(1);
5794   SDValue Dest = Op.getOperand(2);
5795   SDLoc dl(Op);
5796 
5797   // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
5798   // instruction.
5799   unsigned Opc = Cond.getOpcode();
5800   bool OptimizeMul = (Opc == ISD::SMULO || Opc == ISD::UMULO) &&
5801                       !Subtarget->isThumb1Only();
5802   if (Cond.getResNo() == 1 &&
5803       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
5804        Opc == ISD::USUBO || OptimizeMul)) {
5805     // Only lower legal XALUO ops.
5806     if (!isTypeLegal(Cond->getValueType(0)))
5807       return SDValue();
5808 
5809     // The actual operation with overflow check.
5810     SDValue Value, OverflowCmp;
5811     SDValue ARMcc;
5812     std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
5813 
5814     // Reverse the condition code.
5815     ARMCC::CondCodes CondCode =
5816         (ARMCC::CondCodes)cast<const ConstantSDNode>(ARMcc)->getZExtValue();
5817     CondCode = ARMCC::getOppositeCondition(CondCode);
5818     ARMcc = DAG.getConstant(CondCode, SDLoc(ARMcc), MVT::i32);
5819 
5820     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc,
5821                        OverflowCmp);
5822   }
5823 
5824   return SDValue();
5825 }
5826 
LowerBR_CC(SDValue Op,SelectionDAG & DAG) const5827 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
5828   SDValue Chain = Op.getOperand(0);
5829   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
5830   SDValue LHS = Op.getOperand(2);
5831   SDValue RHS = Op.getOperand(3);
5832   SDValue Dest = Op.getOperand(4);
5833   SDLoc dl(Op);
5834 
5835   if (isUnsupportedFloatingType(LHS.getValueType())) {
5836     softenSetCCOperands(DAG, LHS.getValueType(), LHS, RHS, CC, dl, LHS, RHS);
5837 
5838     // If softenSetCCOperands only returned one value, we should compare it to
5839     // zero.
5840     if (!RHS.getNode()) {
5841       RHS = DAG.getConstant(0, dl, LHS.getValueType());
5842       CC = ISD::SETNE;
5843     }
5844   }
5845 
5846   // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
5847   // instruction.
5848   unsigned Opc = LHS.getOpcode();
5849   bool OptimizeMul = (Opc == ISD::SMULO || Opc == ISD::UMULO) &&
5850                       !Subtarget->isThumb1Only();
5851   if (LHS.getResNo() == 1 && (isOneConstant(RHS) || isNullConstant(RHS)) &&
5852       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
5853        Opc == ISD::USUBO || OptimizeMul) &&
5854       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
5855     // Only lower legal XALUO ops.
5856     if (!isTypeLegal(LHS->getValueType(0)))
5857       return SDValue();
5858 
5859     // The actual operation with overflow check.
5860     SDValue Value, OverflowCmp;
5861     SDValue ARMcc;
5862     std::tie(Value, OverflowCmp) = getARMXALUOOp(LHS.getValue(0), DAG, ARMcc);
5863 
5864     if ((CC == ISD::SETNE) != isOneConstant(RHS)) {
5865       // Reverse the condition code.
5866       ARMCC::CondCodes CondCode =
5867           (ARMCC::CondCodes)cast<const ConstantSDNode>(ARMcc)->getZExtValue();
5868       CondCode = ARMCC::getOppositeCondition(CondCode);
5869       ARMcc = DAG.getConstant(CondCode, SDLoc(ARMcc), MVT::i32);
5870     }
5871 
5872     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc,
5873                        OverflowCmp);
5874   }
5875 
5876   if (LHS.getValueType() == MVT::i32) {
5877     SDValue ARMcc;
5878     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
5879     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc, Cmp);
5880   }
5881 
5882   if (getTargetMachine().Options.UnsafeFPMath &&
5883       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
5884        CC == ISD::SETNE || CC == ISD::SETUNE)) {
5885     if (SDValue Result = OptimizeVFPBrcond(Op, DAG))
5886       return Result;
5887   }
5888 
5889   ARMCC::CondCodes CondCode, CondCode2;
5890   FPCCToARMCC(CC, CondCode, CondCode2);
5891 
5892   SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
5893   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
5894   SDValue Ops[] = {Chain, Dest, ARMcc, Cmp};
5895   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Ops);
5896   if (CondCode2 != ARMCC::AL) {
5897     ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32);
5898     SDValue Ops[] = {Res, Dest, ARMcc, Cmp};
5899     Res = DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Ops);
5900   }
5901   return Res;
5902 }
5903 
LowerBR_JT(SDValue Op,SelectionDAG & DAG) const5904 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
5905   SDValue Chain = Op.getOperand(0);
5906   SDValue Table = Op.getOperand(1);
5907   SDValue Index = Op.getOperand(2);
5908   SDLoc dl(Op);
5909 
5910   EVT PTy = getPointerTy(DAG.getDataLayout());
5911   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
5912   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
5913   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI);
5914   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy));
5915   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Table, Index);
5916   if (Subtarget->isThumb2() || (Subtarget->hasV8MBaselineOps() && Subtarget->isThumb())) {
5917     // Thumb2 and ARMv8-M use a two-level jump. That is, it jumps into the jump table
5918     // which does another jump to the destination. This also makes it easier
5919     // to translate it to TBB / TBH later (Thumb2 only).
5920     // FIXME: This might not work if the function is extremely large.
5921     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
5922                        Addr, Op.getOperand(2), JTI);
5923   }
5924   if (isPositionIndependent() || Subtarget->isROPI()) {
5925     Addr =
5926         DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
5927                     MachinePointerInfo::getJumpTable(DAG.getMachineFunction()));
5928     Chain = Addr.getValue(1);
5929     Addr = DAG.getNode(ISD::ADD, dl, PTy, Table, Addr);
5930     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
5931   } else {
5932     Addr =
5933         DAG.getLoad(PTy, dl, Chain, Addr,
5934                     MachinePointerInfo::getJumpTable(DAG.getMachineFunction()));
5935     Chain = Addr.getValue(1);
5936     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
5937   }
5938 }
5939 
LowerVectorFP_TO_INT(SDValue Op,SelectionDAG & DAG)5940 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
5941   EVT VT = Op.getValueType();
5942   SDLoc dl(Op);
5943 
5944   if (Op.getValueType().getVectorElementType() == MVT::i32) {
5945     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
5946       return Op;
5947     return DAG.UnrollVectorOp(Op.getNode());
5948   }
5949 
5950   const bool HasFullFP16 = DAG.getSubtarget<ARMSubtarget>().hasFullFP16();
5951 
5952   EVT NewTy;
5953   const EVT OpTy = Op.getOperand(0).getValueType();
5954   if (OpTy == MVT::v4f32)
5955     NewTy = MVT::v4i32;
5956   else if (OpTy == MVT::v4f16 && HasFullFP16)
5957     NewTy = MVT::v4i16;
5958   else if (OpTy == MVT::v8f16 && HasFullFP16)
5959     NewTy = MVT::v8i16;
5960   else
5961     llvm_unreachable("Invalid type for custom lowering!");
5962 
5963   if (VT != MVT::v4i16 && VT != MVT::v8i16)
5964     return DAG.UnrollVectorOp(Op.getNode());
5965 
5966   Op = DAG.getNode(Op.getOpcode(), dl, NewTy, Op.getOperand(0));
5967   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
5968 }
5969 
LowerFP_TO_INT(SDValue Op,SelectionDAG & DAG) const5970 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
5971   EVT VT = Op.getValueType();
5972   if (VT.isVector())
5973     return LowerVectorFP_TO_INT(Op, DAG);
5974 
5975   bool IsStrict = Op->isStrictFPOpcode();
5976   SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0);
5977 
5978   if (isUnsupportedFloatingType(SrcVal.getValueType())) {
5979     RTLIB::Libcall LC;
5980     if (Op.getOpcode() == ISD::FP_TO_SINT ||
5981         Op.getOpcode() == ISD::STRICT_FP_TO_SINT)
5982       LC = RTLIB::getFPTOSINT(SrcVal.getValueType(),
5983                               Op.getValueType());
5984     else
5985       LC = RTLIB::getFPTOUINT(SrcVal.getValueType(),
5986                               Op.getValueType());
5987     SDLoc Loc(Op);
5988     MakeLibCallOptions CallOptions;
5989     SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
5990     SDValue Result;
5991     std::tie(Result, Chain) = makeLibCall(DAG, LC, Op.getValueType(), SrcVal,
5992                                           CallOptions, Loc, Chain);
5993     return IsStrict ? DAG.getMergeValues({Result, Chain}, Loc) : Result;
5994   }
5995 
5996   // FIXME: Remove this when we have strict fp instruction selection patterns
5997   if (IsStrict) {
5998     SDLoc Loc(Op);
5999     SDValue Result =
6000         DAG.getNode(Op.getOpcode() == ISD::STRICT_FP_TO_SINT ? ISD::FP_TO_SINT
6001                                                              : ISD::FP_TO_UINT,
6002                     Loc, Op.getValueType(), SrcVal);
6003     return DAG.getMergeValues({Result, Op.getOperand(0)}, Loc);
6004   }
6005 
6006   return Op;
6007 }
6008 
LowerFP_TO_INT_SAT(SDValue Op,SelectionDAG & DAG,const ARMSubtarget * Subtarget)6009 static SDValue LowerFP_TO_INT_SAT(SDValue Op, SelectionDAG &DAG,
6010                                   const ARMSubtarget *Subtarget) {
6011   EVT VT = Op.getValueType();
6012   EVT ToVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
6013   EVT FromVT = Op.getOperand(0).getValueType();
6014 
6015   if (VT == MVT::i32 && ToVT == MVT::i32 && FromVT == MVT::f32)
6016     return Op;
6017   if (VT == MVT::i32 && ToVT == MVT::i32 && FromVT == MVT::f64 &&
6018       Subtarget->hasFP64())
6019     return Op;
6020   if (VT == MVT::i32 && ToVT == MVT::i32 && FromVT == MVT::f16 &&
6021       Subtarget->hasFullFP16())
6022     return Op;
6023   if (VT == MVT::v4i32 && ToVT == MVT::i32 && FromVT == MVT::v4f32 &&
6024       Subtarget->hasMVEFloatOps())
6025     return Op;
6026   if (VT == MVT::v8i16 && ToVT == MVT::i16 && FromVT == MVT::v8f16 &&
6027       Subtarget->hasMVEFloatOps())
6028     return Op;
6029 
6030   if (FromVT != MVT::v4f32 && FromVT != MVT::v8f16)
6031     return SDValue();
6032 
6033   SDLoc DL(Op);
6034   bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT_SAT;
6035   unsigned BW = ToVT.getScalarSizeInBits() - IsSigned;
6036   SDValue CVT = DAG.getNode(Op.getOpcode(), DL, VT, Op.getOperand(0),
6037                             DAG.getValueType(VT.getScalarType()));
6038   SDValue Max = DAG.getNode(IsSigned ? ISD::SMIN : ISD::UMIN, DL, VT, CVT,
6039                             DAG.getConstant((1 << BW) - 1, DL, VT));
6040   if (IsSigned)
6041     Max = DAG.getNode(ISD::SMAX, DL, VT, Max,
6042                       DAG.getSignedConstant(-(1 << BW), DL, VT));
6043   return Max;
6044 }
6045 
LowerVectorINT_TO_FP(SDValue Op,SelectionDAG & DAG)6046 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
6047   EVT VT = Op.getValueType();
6048   SDLoc dl(Op);
6049 
6050   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
6051     if (VT.getVectorElementType() == MVT::f32)
6052       return Op;
6053     return DAG.UnrollVectorOp(Op.getNode());
6054   }
6055 
6056   assert((Op.getOperand(0).getValueType() == MVT::v4i16 ||
6057           Op.getOperand(0).getValueType() == MVT::v8i16) &&
6058          "Invalid type for custom lowering!");
6059 
6060   const bool HasFullFP16 = DAG.getSubtarget<ARMSubtarget>().hasFullFP16();
6061 
6062   EVT DestVecType;
6063   if (VT == MVT::v4f32)
6064     DestVecType = MVT::v4i32;
6065   else if (VT == MVT::v4f16 && HasFullFP16)
6066     DestVecType = MVT::v4i16;
6067   else if (VT == MVT::v8f16 && HasFullFP16)
6068     DestVecType = MVT::v8i16;
6069   else
6070     return DAG.UnrollVectorOp(Op.getNode());
6071 
6072   unsigned CastOpc;
6073   unsigned Opc;
6074   switch (Op.getOpcode()) {
6075   default: llvm_unreachable("Invalid opcode!");
6076   case ISD::SINT_TO_FP:
6077     CastOpc = ISD::SIGN_EXTEND;
6078     Opc = ISD::SINT_TO_FP;
6079     break;
6080   case ISD::UINT_TO_FP:
6081     CastOpc = ISD::ZERO_EXTEND;
6082     Opc = ISD::UINT_TO_FP;
6083     break;
6084   }
6085 
6086   Op = DAG.getNode(CastOpc, dl, DestVecType, Op.getOperand(0));
6087   return DAG.getNode(Opc, dl, VT, Op);
6088 }
6089 
LowerINT_TO_FP(SDValue Op,SelectionDAG & DAG) const6090 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
6091   EVT VT = Op.getValueType();
6092   if (VT.isVector())
6093     return LowerVectorINT_TO_FP(Op, DAG);
6094   if (isUnsupportedFloatingType(VT)) {
6095     RTLIB::Libcall LC;
6096     if (Op.getOpcode() == ISD::SINT_TO_FP)
6097       LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(),
6098                               Op.getValueType());
6099     else
6100       LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(),
6101                               Op.getValueType());
6102     MakeLibCallOptions CallOptions;
6103     return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0),
6104                        CallOptions, SDLoc(Op)).first;
6105   }
6106 
6107   return Op;
6108 }
6109 
LowerFCOPYSIGN(SDValue Op,SelectionDAG & DAG) const6110 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
6111   // Implement fcopysign with a fabs and a conditional fneg.
6112   SDValue Tmp0 = Op.getOperand(0);
6113   SDValue Tmp1 = Op.getOperand(1);
6114   SDLoc dl(Op);
6115   EVT VT = Op.getValueType();
6116   EVT SrcVT = Tmp1.getValueType();
6117   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
6118     Tmp0.getOpcode() == ARMISD::VMOVDRR;
6119   bool UseNEON = !InGPR && Subtarget->hasNEON();
6120 
6121   if (UseNEON) {
6122     // Use VBSL to copy the sign bit.
6123     unsigned EncodedVal = ARM_AM::createVMOVModImm(0x6, 0x80);
6124     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
6125                                DAG.getTargetConstant(EncodedVal, dl, MVT::i32));
6126     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
6127     if (VT == MVT::f64)
6128       Mask = DAG.getNode(ARMISD::VSHLIMM, dl, OpVT,
6129                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
6130                          DAG.getConstant(32, dl, MVT::i32));
6131     else /*if (VT == MVT::f32)*/
6132       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
6133     if (SrcVT == MVT::f32) {
6134       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
6135       if (VT == MVT::f64)
6136         Tmp1 = DAG.getNode(ARMISD::VSHLIMM, dl, OpVT,
6137                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
6138                            DAG.getConstant(32, dl, MVT::i32));
6139     } else if (VT == MVT::f32)
6140       Tmp1 = DAG.getNode(ARMISD::VSHRuIMM, dl, MVT::v1i64,
6141                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
6142                          DAG.getConstant(32, dl, MVT::i32));
6143     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
6144     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
6145 
6146     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createVMOVModImm(0xe, 0xff),
6147                                             dl, MVT::i32);
6148     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
6149     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
6150                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
6151 
6152     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
6153                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
6154                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
6155     if (VT == MVT::f32) {
6156       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
6157       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
6158                         DAG.getConstant(0, dl, MVT::i32));
6159     } else {
6160       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
6161     }
6162 
6163     return Res;
6164   }
6165 
6166   // Bitcast operand 1 to i32.
6167   if (SrcVT == MVT::f64)
6168     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
6169                        Tmp1).getValue(1);
6170   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
6171 
6172   // Or in the signbit with integer operations.
6173   SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32);
6174   SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32);
6175   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
6176   if (VT == MVT::f32) {
6177     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
6178                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
6179     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
6180                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
6181   }
6182 
6183   // f64: Or the high part with signbit and then combine two parts.
6184   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
6185                      Tmp0);
6186   SDValue Lo = Tmp0.getValue(0);
6187   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
6188   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
6189   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
6190 }
6191 
LowerRETURNADDR(SDValue Op,SelectionDAG & DAG) const6192 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
6193   MachineFunction &MF = DAG.getMachineFunction();
6194   MachineFrameInfo &MFI = MF.getFrameInfo();
6195   MFI.setReturnAddressIsTaken(true);
6196 
6197   EVT VT = Op.getValueType();
6198   SDLoc dl(Op);
6199   unsigned Depth = Op.getConstantOperandVal(0);
6200   if (Depth) {
6201     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
6202     SDValue Offset = DAG.getConstant(4, dl, MVT::i32);
6203     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
6204                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
6205                        MachinePointerInfo());
6206   }
6207 
6208   // Return LR, which contains the return address. Mark it an implicit live-in.
6209   Register Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
6210   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
6211 }
6212 
LowerFRAMEADDR(SDValue Op,SelectionDAG & DAG) const6213 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
6214   const ARMBaseRegisterInfo &ARI =
6215     *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
6216   MachineFunction &MF = DAG.getMachineFunction();
6217   MachineFrameInfo &MFI = MF.getFrameInfo();
6218   MFI.setFrameAddressIsTaken(true);
6219 
6220   EVT VT = Op.getValueType();
6221   SDLoc dl(Op);  // FIXME probably not meaningful
6222   unsigned Depth = Op.getConstantOperandVal(0);
6223   Register FrameReg = ARI.getFrameRegister(MF);
6224   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
6225   while (Depth--)
6226     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
6227                             MachinePointerInfo());
6228   return FrameAddr;
6229 }
6230 
6231 // FIXME? Maybe this could be a TableGen attribute on some registers and
6232 // this table could be generated automatically from RegInfo.
getRegisterByName(const char * RegName,LLT VT,const MachineFunction & MF) const6233 Register ARMTargetLowering::getRegisterByName(const char* RegName, LLT VT,
6234                                               const MachineFunction &MF) const {
6235   return StringSwitch<Register>(RegName)
6236       .Case("sp", ARM::SP)
6237       .Default(Register());
6238 }
6239 
6240 // Result is 64 bit value so split into two 32 bit values and return as a
6241 // pair of values.
ExpandREAD_REGISTER(SDNode * N,SmallVectorImpl<SDValue> & Results,SelectionDAG & DAG)6242 static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results,
6243                                 SelectionDAG &DAG) {
6244   SDLoc DL(N);
6245 
6246   // This function is only supposed to be called for i64 type destination.
6247   assert(N->getValueType(0) == MVT::i64
6248           && "ExpandREAD_REGISTER called for non-i64 type result.");
6249 
6250   SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL,
6251                              DAG.getVTList(MVT::i32, MVT::i32, MVT::Other),
6252                              N->getOperand(0),
6253                              N->getOperand(1));
6254 
6255   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0),
6256                     Read.getValue(1)));
6257   Results.push_back(Read.getValue(2)); // Chain
6258 }
6259 
6260 /// \p BC is a bitcast that is about to be turned into a VMOVDRR.
6261 /// When \p DstVT, the destination type of \p BC, is on the vector
6262 /// register bank and the source of bitcast, \p Op, operates on the same bank,
6263 /// it might be possible to combine them, such that everything stays on the
6264 /// vector register bank.
6265 /// \p return The node that would replace \p BT, if the combine
6266 /// is possible.
CombineVMOVDRRCandidateWithVecOp(const SDNode * BC,SelectionDAG & DAG)6267 static SDValue CombineVMOVDRRCandidateWithVecOp(const SDNode *BC,
6268                                                 SelectionDAG &DAG) {
6269   SDValue Op = BC->getOperand(0);
6270   EVT DstVT = BC->getValueType(0);
6271 
6272   // The only vector instruction that can produce a scalar (remember,
6273   // since the bitcast was about to be turned into VMOVDRR, the source
6274   // type is i64) from a vector is EXTRACT_VECTOR_ELT.
6275   // Moreover, we can do this combine only if there is one use.
6276   // Finally, if the destination type is not a vector, there is not
6277   // much point on forcing everything on the vector bank.
6278   if (!DstVT.isVector() || Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6279       !Op.hasOneUse())
6280     return SDValue();
6281 
6282   // If the index is not constant, we will introduce an additional
6283   // multiply that will stick.
6284   // Give up in that case.
6285   ConstantSDNode *Index = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6286   if (!Index)
6287     return SDValue();
6288   unsigned DstNumElt = DstVT.getVectorNumElements();
6289 
6290   // Compute the new index.
6291   const APInt &APIntIndex = Index->getAPIntValue();
6292   APInt NewIndex(APIntIndex.getBitWidth(), DstNumElt);
6293   NewIndex *= APIntIndex;
6294   // Check if the new constant index fits into i32.
6295   if (NewIndex.getBitWidth() > 32)
6296     return SDValue();
6297 
6298   // vMTy bitcast(i64 extractelt vNi64 src, i32 index) ->
6299   // vMTy extractsubvector vNxMTy (bitcast vNi64 src), i32 index*M)
6300   SDLoc dl(Op);
6301   SDValue ExtractSrc = Op.getOperand(0);
6302   EVT VecVT = EVT::getVectorVT(
6303       *DAG.getContext(), DstVT.getScalarType(),
6304       ExtractSrc.getValueType().getVectorNumElements() * DstNumElt);
6305   SDValue BitCast = DAG.getNode(ISD::BITCAST, dl, VecVT, ExtractSrc);
6306   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DstVT, BitCast,
6307                      DAG.getConstant(NewIndex.getZExtValue(), dl, MVT::i32));
6308 }
6309 
6310 /// ExpandBITCAST - If the target supports VFP, this function is called to
6311 /// expand a bit convert where either the source or destination type is i64 to
6312 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
6313 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
6314 /// vectors), since the legalizer won't know what to do with that.
ExpandBITCAST(SDNode * N,SelectionDAG & DAG,const ARMSubtarget * Subtarget) const6315 SDValue ARMTargetLowering::ExpandBITCAST(SDNode *N, SelectionDAG &DAG,
6316                                          const ARMSubtarget *Subtarget) const {
6317   SDLoc dl(N);
6318   SDValue Op = N->getOperand(0);
6319 
6320   // This function is only supposed to be called for i16 and i64 types, either
6321   // as the source or destination of the bit convert.
6322   EVT SrcVT = Op.getValueType();
6323   EVT DstVT = N->getValueType(0);
6324 
6325   if ((SrcVT == MVT::i16 || SrcVT == MVT::i32) &&
6326       (DstVT == MVT::f16 || DstVT == MVT::bf16))
6327     return MoveToHPR(SDLoc(N), DAG, MVT::i32, DstVT.getSimpleVT(),
6328                      DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), MVT::i32, Op));
6329 
6330   if ((DstVT == MVT::i16 || DstVT == MVT::i32) &&
6331       (SrcVT == MVT::f16 || SrcVT == MVT::bf16)) {
6332     if (Subtarget->hasFullFP16() && !Subtarget->hasBF16())
6333       Op = DAG.getBitcast(MVT::f16, Op);
6334     return DAG.getNode(
6335         ISD::TRUNCATE, SDLoc(N), DstVT,
6336         MoveFromHPR(SDLoc(N), DAG, MVT::i32, SrcVT.getSimpleVT(), Op));
6337   }
6338 
6339   if (!(SrcVT == MVT::i64 || DstVT == MVT::i64))
6340     return SDValue();
6341 
6342   // Turn i64->f64 into VMOVDRR.
6343   if (SrcVT == MVT::i64 && isTypeLegal(DstVT)) {
6344     // Do not force values to GPRs (this is what VMOVDRR does for the inputs)
6345     // if we can combine the bitcast with its source.
6346     if (SDValue Val = CombineVMOVDRRCandidateWithVecOp(N, DAG))
6347       return Val;
6348     SDValue Lo, Hi;
6349     std::tie(Lo, Hi) = DAG.SplitScalar(Op, dl, MVT::i32, MVT::i32);
6350     return DAG.getNode(ISD::BITCAST, dl, DstVT,
6351                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
6352   }
6353 
6354   // Turn f64->i64 into VMOVRRD.
6355   if (DstVT == MVT::i64 && isTypeLegal(SrcVT)) {
6356     SDValue Cvt;
6357     if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() &&
6358         SrcVT.getVectorNumElements() > 1)
6359       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
6360                         DAG.getVTList(MVT::i32, MVT::i32),
6361                         DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
6362     else
6363       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
6364                         DAG.getVTList(MVT::i32, MVT::i32), Op);
6365     // Merge the pieces into a single i64 value.
6366     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
6367   }
6368 
6369   return SDValue();
6370 }
6371 
6372 /// getZeroVector - Returns a vector of specified type with all zero elements.
6373 /// Zero vectors are used to represent vector negation and in those cases
6374 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
6375 /// not support i64 elements, so sometimes the zero vectors will need to be
6376 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
6377 /// zero vector.
getZeroVector(EVT VT,SelectionDAG & DAG,const SDLoc & dl)6378 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, const SDLoc &dl) {
6379   assert(VT.isVector() && "Expected a vector type");
6380   // The canonical modified immediate encoding of a zero vector is....0!
6381   SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32);
6382   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
6383   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
6384   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
6385 }
6386 
6387 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
6388 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
LowerShiftRightParts(SDValue Op,SelectionDAG & DAG) const6389 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
6390                                                 SelectionDAG &DAG) const {
6391   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
6392   EVT VT = Op.getValueType();
6393   unsigned VTBits = VT.getSizeInBits();
6394   SDLoc dl(Op);
6395   SDValue ShOpLo = Op.getOperand(0);
6396   SDValue ShOpHi = Op.getOperand(1);
6397   SDValue ShAmt  = Op.getOperand(2);
6398   SDValue ARMcc;
6399   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
6400 
6401   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
6402 
6403   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
6404                                  DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
6405   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
6406   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
6407                                    DAG.getConstant(VTBits, dl, MVT::i32));
6408   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
6409   SDValue LoSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
6410   SDValue LoBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
6411   SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
6412                             ISD::SETGE, ARMcc, DAG, dl);
6413   SDValue Lo =
6414       DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift, LoBigShift, ARMcc, CmpLo);
6415 
6416   SDValue HiSmallShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
6417   SDValue HiBigShift = Opc == ISD::SRA
6418                            ? DAG.getNode(Opc, dl, VT, ShOpHi,
6419                                          DAG.getConstant(VTBits - 1, dl, VT))
6420                            : DAG.getConstant(0, dl, VT);
6421   SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
6422                             ISD::SETGE, ARMcc, DAG, dl);
6423   SDValue Hi =
6424       DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift, ARMcc, CmpHi);
6425 
6426   SDValue Ops[2] = { Lo, Hi };
6427   return DAG.getMergeValues(Ops, dl);
6428 }
6429 
6430 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
6431 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
LowerShiftLeftParts(SDValue Op,SelectionDAG & DAG) const6432 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
6433                                                SelectionDAG &DAG) const {
6434   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
6435   EVT VT = Op.getValueType();
6436   unsigned VTBits = VT.getSizeInBits();
6437   SDLoc dl(Op);
6438   SDValue ShOpLo = Op.getOperand(0);
6439   SDValue ShOpHi = Op.getOperand(1);
6440   SDValue ShAmt  = Op.getOperand(2);
6441   SDValue ARMcc;
6442 
6443   assert(Op.getOpcode() == ISD::SHL_PARTS);
6444   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
6445                                  DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
6446   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
6447   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
6448   SDValue HiSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
6449 
6450   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
6451                                    DAG.getConstant(VTBits, dl, MVT::i32));
6452   SDValue HiBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
6453   SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
6454                             ISD::SETGE, ARMcc, DAG, dl);
6455   SDValue Hi =
6456       DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift, ARMcc, CmpHi);
6457 
6458   SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
6459                           ISD::SETGE, ARMcc, DAG, dl);
6460   SDValue LoSmallShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
6461   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift,
6462                            DAG.getConstant(0, dl, VT), ARMcc, CmpLo);
6463 
6464   SDValue Ops[2] = { Lo, Hi };
6465   return DAG.getMergeValues(Ops, dl);
6466 }
6467 
LowerGET_ROUNDING(SDValue Op,SelectionDAG & DAG) const6468 SDValue ARMTargetLowering::LowerGET_ROUNDING(SDValue Op,
6469                                              SelectionDAG &DAG) const {
6470   // The rounding mode is in bits 23:22 of the FPSCR.
6471   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
6472   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
6473   // so that the shift + and get folded into a bitfield extract.
6474   SDLoc dl(Op);
6475   SDValue Chain = Op.getOperand(0);
6476   SDValue Ops[] = {Chain,
6477                    DAG.getConstant(Intrinsic::arm_get_fpscr, dl, MVT::i32)};
6478 
6479   SDValue FPSCR =
6480       DAG.getNode(ISD::INTRINSIC_W_CHAIN, dl, {MVT::i32, MVT::Other}, Ops);
6481   Chain = FPSCR.getValue(1);
6482   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
6483                                   DAG.getConstant(1U << 22, dl, MVT::i32));
6484   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
6485                               DAG.getConstant(22, dl, MVT::i32));
6486   SDValue And = DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
6487                             DAG.getConstant(3, dl, MVT::i32));
6488   return DAG.getMergeValues({And, Chain}, dl);
6489 }
6490 
LowerSET_ROUNDING(SDValue Op,SelectionDAG & DAG) const6491 SDValue ARMTargetLowering::LowerSET_ROUNDING(SDValue Op,
6492                                              SelectionDAG &DAG) const {
6493   SDLoc DL(Op);
6494   SDValue Chain = Op->getOperand(0);
6495   SDValue RMValue = Op->getOperand(1);
6496 
6497   // The rounding mode is in bits 23:22 of the FPSCR.
6498   // The llvm.set.rounding argument value to ARM rounding mode value mapping
6499   // is 0->3, 1->0, 2->1, 3->2. The formula we use to implement this is
6500   // ((arg - 1) & 3) << 22).
6501   //
6502   // It is expected that the argument of llvm.set.rounding is within the
6503   // segment [0, 3], so NearestTiesToAway (4) is not handled here. It is
6504   // responsibility of the code generated llvm.set.rounding to ensure this
6505   // condition.
6506 
6507   // Calculate new value of FPSCR[23:22].
6508   RMValue = DAG.getNode(ISD::SUB, DL, MVT::i32, RMValue,
6509                         DAG.getConstant(1, DL, MVT::i32));
6510   RMValue = DAG.getNode(ISD::AND, DL, MVT::i32, RMValue,
6511                         DAG.getConstant(0x3, DL, MVT::i32));
6512   RMValue = DAG.getNode(ISD::SHL, DL, MVT::i32, RMValue,
6513                         DAG.getConstant(ARM::RoundingBitsPos, DL, MVT::i32));
6514 
6515   // Get current value of FPSCR.
6516   SDValue Ops[] = {Chain,
6517                    DAG.getConstant(Intrinsic::arm_get_fpscr, DL, MVT::i32)};
6518   SDValue FPSCR =
6519       DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL, {MVT::i32, MVT::Other}, Ops);
6520   Chain = FPSCR.getValue(1);
6521   FPSCR = FPSCR.getValue(0);
6522 
6523   // Put new rounding mode into FPSCR[23:22].
6524   const unsigned RMMask = ~(ARM::Rounding::rmMask << ARM::RoundingBitsPos);
6525   FPSCR = DAG.getNode(ISD::AND, DL, MVT::i32, FPSCR,
6526                       DAG.getConstant(RMMask, DL, MVT::i32));
6527   FPSCR = DAG.getNode(ISD::OR, DL, MVT::i32, FPSCR, RMValue);
6528   SDValue Ops2[] = {
6529       Chain, DAG.getConstant(Intrinsic::arm_set_fpscr, DL, MVT::i32), FPSCR};
6530   return DAG.getNode(ISD::INTRINSIC_VOID, DL, MVT::Other, Ops2);
6531 }
6532 
LowerSET_FPMODE(SDValue Op,SelectionDAG & DAG) const6533 SDValue ARMTargetLowering::LowerSET_FPMODE(SDValue Op,
6534                                            SelectionDAG &DAG) const {
6535   SDLoc DL(Op);
6536   SDValue Chain = Op->getOperand(0);
6537   SDValue Mode = Op->getOperand(1);
6538 
6539   // Generate nodes to build:
6540   // FPSCR = (FPSCR & FPStatusBits) | (Mode & ~FPStatusBits)
6541   SDValue Ops[] = {Chain,
6542                    DAG.getConstant(Intrinsic::arm_get_fpscr, DL, MVT::i32)};
6543   SDValue FPSCR =
6544       DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL, {MVT::i32, MVT::Other}, Ops);
6545   Chain = FPSCR.getValue(1);
6546   FPSCR = FPSCR.getValue(0);
6547 
6548   SDValue FPSCRMasked =
6549       DAG.getNode(ISD::AND, DL, MVT::i32, FPSCR,
6550                   DAG.getConstant(ARM::FPStatusBits, DL, MVT::i32));
6551   SDValue InputMasked =
6552       DAG.getNode(ISD::AND, DL, MVT::i32, Mode,
6553                   DAG.getConstant(~ARM::FPStatusBits, DL, MVT::i32));
6554   FPSCR = DAG.getNode(ISD::OR, DL, MVT::i32, FPSCRMasked, InputMasked);
6555 
6556   SDValue Ops2[] = {
6557       Chain, DAG.getConstant(Intrinsic::arm_set_fpscr, DL, MVT::i32), FPSCR};
6558   return DAG.getNode(ISD::INTRINSIC_VOID, DL, MVT::Other, Ops2);
6559 }
6560 
LowerRESET_FPMODE(SDValue Op,SelectionDAG & DAG) const6561 SDValue ARMTargetLowering::LowerRESET_FPMODE(SDValue Op,
6562                                              SelectionDAG &DAG) const {
6563   SDLoc DL(Op);
6564   SDValue Chain = Op->getOperand(0);
6565 
6566   // To get the default FP mode all control bits are cleared:
6567   // FPSCR = FPSCR & (FPStatusBits | FPReservedBits)
6568   SDValue Ops[] = {Chain,
6569                    DAG.getConstant(Intrinsic::arm_get_fpscr, DL, MVT::i32)};
6570   SDValue FPSCR =
6571       DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL, {MVT::i32, MVT::Other}, Ops);
6572   Chain = FPSCR.getValue(1);
6573   FPSCR = FPSCR.getValue(0);
6574 
6575   SDValue FPSCRMasked = DAG.getNode(
6576       ISD::AND, DL, MVT::i32, FPSCR,
6577       DAG.getConstant(ARM::FPStatusBits | ARM::FPReservedBits, DL, MVT::i32));
6578   SDValue Ops2[] = {Chain,
6579                     DAG.getConstant(Intrinsic::arm_set_fpscr, DL, MVT::i32),
6580                     FPSCRMasked};
6581   return DAG.getNode(ISD::INTRINSIC_VOID, DL, MVT::Other, Ops2);
6582 }
6583 
LowerCTTZ(SDNode * N,SelectionDAG & DAG,const ARMSubtarget * ST)6584 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
6585                          const ARMSubtarget *ST) {
6586   SDLoc dl(N);
6587   EVT VT = N->getValueType(0);
6588   if (VT.isVector() && ST->hasNEON()) {
6589 
6590     // Compute the least significant set bit: LSB = X & -X
6591     SDValue X = N->getOperand(0);
6592     SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X);
6593     SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX);
6594 
6595     EVT ElemTy = VT.getVectorElementType();
6596 
6597     if (ElemTy == MVT::i8) {
6598       // Compute with: cttz(x) = ctpop(lsb - 1)
6599       SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
6600                                 DAG.getTargetConstant(1, dl, ElemTy));
6601       SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
6602       return DAG.getNode(ISD::CTPOP, dl, VT, Bits);
6603     }
6604 
6605     if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) &&
6606         (N->getOpcode() == ISD::CTTZ_ZERO_UNDEF)) {
6607       // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0
6608       unsigned NumBits = ElemTy.getSizeInBits();
6609       SDValue WidthMinus1 =
6610           DAG.getNode(ARMISD::VMOVIMM, dl, VT,
6611                       DAG.getTargetConstant(NumBits - 1, dl, ElemTy));
6612       SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB);
6613       return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ);
6614     }
6615 
6616     // Compute with: cttz(x) = ctpop(lsb - 1)
6617 
6618     // Compute LSB - 1.
6619     SDValue Bits;
6620     if (ElemTy == MVT::i64) {
6621       // Load constant 0xffff'ffff'ffff'ffff to register.
6622       SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
6623                                DAG.getTargetConstant(0x1eff, dl, MVT::i32));
6624       Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF);
6625     } else {
6626       SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
6627                                 DAG.getTargetConstant(1, dl, ElemTy));
6628       Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
6629     }
6630     return DAG.getNode(ISD::CTPOP, dl, VT, Bits);
6631   }
6632 
6633   if (!ST->hasV6T2Ops())
6634     return SDValue();
6635 
6636   SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, VT, N->getOperand(0));
6637   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
6638 }
6639 
LowerCTPOP(SDNode * N,SelectionDAG & DAG,const ARMSubtarget * ST)6640 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
6641                           const ARMSubtarget *ST) {
6642   EVT VT = N->getValueType(0);
6643   SDLoc DL(N);
6644 
6645   assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
6646   assert((VT == MVT::v1i64 || VT == MVT::v2i64 || VT == MVT::v2i32 ||
6647           VT == MVT::v4i32 || VT == MVT::v4i16 || VT == MVT::v8i16) &&
6648          "Unexpected type for custom ctpop lowering");
6649 
6650   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6651   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
6652   SDValue Res = DAG.getBitcast(VT8Bit, N->getOperand(0));
6653   Res = DAG.getNode(ISD::CTPOP, DL, VT8Bit, Res);
6654 
6655   // Widen v8i8/v16i8 CTPOP result to VT by repeatedly widening pairwise adds.
6656   unsigned EltSize = 8;
6657   unsigned NumElts = VT.is64BitVector() ? 8 : 16;
6658   while (EltSize != VT.getScalarSizeInBits()) {
6659     SmallVector<SDValue, 8> Ops;
6660     Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddlu, DL,
6661                                   TLI.getPointerTy(DAG.getDataLayout())));
6662     Ops.push_back(Res);
6663 
6664     EltSize *= 2;
6665     NumElts /= 2;
6666     MVT WidenVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize), NumElts);
6667     Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, WidenVT, Ops);
6668   }
6669 
6670   return Res;
6671 }
6672 
6673 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
6674 /// operand of a vector shift operation, where all the elements of the
6675 /// build_vector must have the same constant integer value.
getVShiftImm(SDValue Op,unsigned ElementBits,int64_t & Cnt)6676 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
6677   // Ignore bit_converts.
6678   while (Op.getOpcode() == ISD::BITCAST)
6679     Op = Op.getOperand(0);
6680   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
6681   APInt SplatBits, SplatUndef;
6682   unsigned SplatBitSize;
6683   bool HasAnyUndefs;
6684   if (!BVN ||
6685       !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs,
6686                             ElementBits) ||
6687       SplatBitSize > ElementBits)
6688     return false;
6689   Cnt = SplatBits.getSExtValue();
6690   return true;
6691 }
6692 
6693 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
6694 /// operand of a vector shift left operation.  That value must be in the range:
6695 ///   0 <= Value < ElementBits for a left shift; or
6696 ///   0 <= Value <= ElementBits for a long left shift.
isVShiftLImm(SDValue Op,EVT VT,bool isLong,int64_t & Cnt)6697 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
6698   assert(VT.isVector() && "vector shift count is not a vector type");
6699   int64_t ElementBits = VT.getScalarSizeInBits();
6700   if (!getVShiftImm(Op, ElementBits, Cnt))
6701     return false;
6702   return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
6703 }
6704 
6705 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
6706 /// operand of a vector shift right operation.  For a shift opcode, the value
6707 /// is positive, but for an intrinsic the value count must be negative. The
6708 /// absolute value must be in the range:
6709 ///   1 <= |Value| <= ElementBits for a right shift; or
6710 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
isVShiftRImm(SDValue Op,EVT VT,bool isNarrow,bool isIntrinsic,int64_t & Cnt)6711 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
6712                          int64_t &Cnt) {
6713   assert(VT.isVector() && "vector shift count is not a vector type");
6714   int64_t ElementBits = VT.getScalarSizeInBits();
6715   if (!getVShiftImm(Op, ElementBits, Cnt))
6716     return false;
6717   if (!isIntrinsic)
6718     return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
6719   if (Cnt >= -(isNarrow ? ElementBits / 2 : ElementBits) && Cnt <= -1) {
6720     Cnt = -Cnt;
6721     return true;
6722   }
6723   return false;
6724 }
6725 
LowerShift(SDNode * N,SelectionDAG & DAG,const ARMSubtarget * ST)6726 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
6727                           const ARMSubtarget *ST) {
6728   EVT VT = N->getValueType(0);
6729   SDLoc dl(N);
6730   int64_t Cnt;
6731 
6732   if (!VT.isVector())
6733     return SDValue();
6734 
6735   // We essentially have two forms here. Shift by an immediate and shift by a
6736   // vector register (there are also shift by a gpr, but that is just handled
6737   // with a tablegen pattern). We cannot easily match shift by an immediate in
6738   // tablegen so we do that here and generate a VSHLIMM/VSHRsIMM/VSHRuIMM.
6739   // For shifting by a vector, we don't have VSHR, only VSHL (which can be
6740   // signed or unsigned, and a negative shift indicates a shift right).
6741   if (N->getOpcode() == ISD::SHL) {
6742     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
6743       return DAG.getNode(ARMISD::VSHLIMM, dl, VT, N->getOperand(0),
6744                          DAG.getConstant(Cnt, dl, MVT::i32));
6745     return DAG.getNode(ARMISD::VSHLu, dl, VT, N->getOperand(0),
6746                        N->getOperand(1));
6747   }
6748 
6749   assert((N->getOpcode() == ISD::SRA || N->getOpcode() == ISD::SRL) &&
6750          "unexpected vector shift opcode");
6751 
6752   if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
6753     unsigned VShiftOpc =
6754         (N->getOpcode() == ISD::SRA ? ARMISD::VSHRsIMM : ARMISD::VSHRuIMM);
6755     return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0),
6756                        DAG.getConstant(Cnt, dl, MVT::i32));
6757   }
6758 
6759   // Other right shifts we don't have operations for (we use a shift left by a
6760   // negative number).
6761   EVT ShiftVT = N->getOperand(1).getValueType();
6762   SDValue NegatedCount = DAG.getNode(
6763       ISD::SUB, dl, ShiftVT, getZeroVector(ShiftVT, DAG, dl), N->getOperand(1));
6764   unsigned VShiftOpc =
6765       (N->getOpcode() == ISD::SRA ? ARMISD::VSHLs : ARMISD::VSHLu);
6766   return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0), NegatedCount);
6767 }
6768 
Expand64BitShift(SDNode * N,SelectionDAG & DAG,const ARMSubtarget * ST)6769 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
6770                                 const ARMSubtarget *ST) {
6771   EVT VT = N->getValueType(0);
6772   SDLoc dl(N);
6773 
6774   // We can get here for a node like i32 = ISD::SHL i32, i64
6775   if (VT != MVT::i64)
6776     return SDValue();
6777 
6778   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA ||
6779           N->getOpcode() == ISD::SHL) &&
6780          "Unknown shift to lower!");
6781 
6782   unsigned ShOpc = N->getOpcode();
6783   if (ST->hasMVEIntegerOps()) {
6784     SDValue ShAmt = N->getOperand(1);
6785     unsigned ShPartsOpc = ARMISD::LSLL;
6786     ConstantSDNode *Con = dyn_cast<ConstantSDNode>(ShAmt);
6787 
6788     // If the shift amount is greater than 32 or has a greater bitwidth than 64
6789     // then do the default optimisation
6790     if ((!Con && ShAmt->getValueType(0).getSizeInBits() > 64) ||
6791         (Con && (Con->getAPIntValue() == 0 || Con->getAPIntValue().uge(32))))
6792       return SDValue();
6793 
6794     // Extract the lower 32 bits of the shift amount if it's not an i32
6795     if (ShAmt->getValueType(0) != MVT::i32)
6796       ShAmt = DAG.getZExtOrTrunc(ShAmt, dl, MVT::i32);
6797 
6798     if (ShOpc == ISD::SRL) {
6799       if (!Con)
6800         // There is no t2LSRLr instruction so negate and perform an lsll if the
6801         // shift amount is in a register, emulating a right shift.
6802         ShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
6803                             DAG.getConstant(0, dl, MVT::i32), ShAmt);
6804       else
6805         // Else generate an lsrl on the immediate shift amount
6806         ShPartsOpc = ARMISD::LSRL;
6807     } else if (ShOpc == ISD::SRA)
6808       ShPartsOpc = ARMISD::ASRL;
6809 
6810     // Split Lower/Upper 32 bits of the destination/source
6811     SDValue Lo, Hi;
6812     std::tie(Lo, Hi) =
6813         DAG.SplitScalar(N->getOperand(0), dl, MVT::i32, MVT::i32);
6814     // Generate the shift operation as computed above
6815     Lo = DAG.getNode(ShPartsOpc, dl, DAG.getVTList(MVT::i32, MVT::i32), Lo, Hi,
6816                      ShAmt);
6817     // The upper 32 bits come from the second return value of lsll
6818     Hi = SDValue(Lo.getNode(), 1);
6819     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
6820   }
6821 
6822   // We only lower SRA, SRL of 1 here, all others use generic lowering.
6823   if (!isOneConstant(N->getOperand(1)) || N->getOpcode() == ISD::SHL)
6824     return SDValue();
6825 
6826   // If we are in thumb mode, we don't have RRX.
6827   if (ST->isThumb1Only())
6828     return SDValue();
6829 
6830   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
6831   SDValue Lo, Hi;
6832   std::tie(Lo, Hi) = DAG.SplitScalar(N->getOperand(0), dl, MVT::i32, MVT::i32);
6833 
6834   // First, build a LSRS1/ASRS1 op, which shifts the top part by one and
6835   // captures the shifted out bit into a carry flag.
6836   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::LSRS1 : ARMISD::ASRS1;
6837   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, FlagsVT), Hi);
6838 
6839   // The low part is an ARMISD::RRX operand, which shifts the carry in.
6840   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
6841 
6842   // Merge the pieces into a single i64 value.
6843  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
6844 }
6845 
LowerVSETCC(SDValue Op,SelectionDAG & DAG,const ARMSubtarget * ST)6846 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG,
6847                            const ARMSubtarget *ST) {
6848   bool Invert = false;
6849   bool Swap = false;
6850   unsigned Opc = ARMCC::AL;
6851 
6852   SDValue Op0 = Op.getOperand(0);
6853   SDValue Op1 = Op.getOperand(1);
6854   SDValue CC = Op.getOperand(2);
6855   EVT VT = Op.getValueType();
6856   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
6857   SDLoc dl(Op);
6858 
6859   EVT CmpVT;
6860   if (ST->hasNEON())
6861     CmpVT = Op0.getValueType().changeVectorElementTypeToInteger();
6862   else {
6863     assert(ST->hasMVEIntegerOps() &&
6864            "No hardware support for integer vector comparison!");
6865 
6866     if (Op.getValueType().getVectorElementType() != MVT::i1)
6867       return SDValue();
6868 
6869     // Make sure we expand floating point setcc to scalar if we do not have
6870     // mve.fp, so that we can handle them from there.
6871     if (Op0.getValueType().isFloatingPoint() && !ST->hasMVEFloatOps())
6872       return SDValue();
6873 
6874     CmpVT = VT;
6875   }
6876 
6877   if (Op0.getValueType().getVectorElementType() == MVT::i64 &&
6878       (SetCCOpcode == ISD::SETEQ || SetCCOpcode == ISD::SETNE)) {
6879     // Special-case integer 64-bit equality comparisons. They aren't legal,
6880     // but they can be lowered with a few vector instructions.
6881     unsigned CmpElements = CmpVT.getVectorNumElements() * 2;
6882     EVT SplitVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, CmpElements);
6883     SDValue CastOp0 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op0);
6884     SDValue CastOp1 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op1);
6885     SDValue Cmp = DAG.getNode(ISD::SETCC, dl, SplitVT, CastOp0, CastOp1,
6886                               DAG.getCondCode(ISD::SETEQ));
6887     SDValue Reversed = DAG.getNode(ARMISD::VREV64, dl, SplitVT, Cmp);
6888     SDValue Merged = DAG.getNode(ISD::AND, dl, SplitVT, Cmp, Reversed);
6889     Merged = DAG.getNode(ISD::BITCAST, dl, CmpVT, Merged);
6890     if (SetCCOpcode == ISD::SETNE)
6891       Merged = DAG.getNOT(dl, Merged, CmpVT);
6892     Merged = DAG.getSExtOrTrunc(Merged, dl, VT);
6893     return Merged;
6894   }
6895 
6896   if (CmpVT.getVectorElementType() == MVT::i64)
6897     // 64-bit comparisons are not legal in general.
6898     return SDValue();
6899 
6900   if (Op1.getValueType().isFloatingPoint()) {
6901     switch (SetCCOpcode) {
6902     default: llvm_unreachable("Illegal FP comparison");
6903     case ISD::SETUNE:
6904     case ISD::SETNE:
6905       if (ST->hasMVEFloatOps()) {
6906         Opc = ARMCC::NE; break;
6907       } else {
6908         Invert = true; [[fallthrough]];
6909       }
6910     case ISD::SETOEQ:
6911     case ISD::SETEQ:  Opc = ARMCC::EQ; break;
6912     case ISD::SETOLT:
6913     case ISD::SETLT: Swap = true; [[fallthrough]];
6914     case ISD::SETOGT:
6915     case ISD::SETGT:  Opc = ARMCC::GT; break;
6916     case ISD::SETOLE:
6917     case ISD::SETLE:  Swap = true; [[fallthrough]];
6918     case ISD::SETOGE:
6919     case ISD::SETGE: Opc = ARMCC::GE; break;
6920     case ISD::SETUGE: Swap = true; [[fallthrough]];
6921     case ISD::SETULE: Invert = true; Opc = ARMCC::GT; break;
6922     case ISD::SETUGT: Swap = true; [[fallthrough]];
6923     case ISD::SETULT: Invert = true; Opc = ARMCC::GE; break;
6924     case ISD::SETUEQ: Invert = true; [[fallthrough]];
6925     case ISD::SETONE: {
6926       // Expand this to (OLT | OGT).
6927       SDValue TmpOp0 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op1, Op0,
6928                                    DAG.getConstant(ARMCC::GT, dl, MVT::i32));
6929       SDValue TmpOp1 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op0, Op1,
6930                                    DAG.getConstant(ARMCC::GT, dl, MVT::i32));
6931       SDValue Result = DAG.getNode(ISD::OR, dl, CmpVT, TmpOp0, TmpOp1);
6932       if (Invert)
6933         Result = DAG.getNOT(dl, Result, VT);
6934       return Result;
6935     }
6936     case ISD::SETUO: Invert = true; [[fallthrough]];
6937     case ISD::SETO: {
6938       // Expand this to (OLT | OGE).
6939       SDValue TmpOp0 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op1, Op0,
6940                                    DAG.getConstant(ARMCC::GT, dl, MVT::i32));
6941       SDValue TmpOp1 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op0, Op1,
6942                                    DAG.getConstant(ARMCC::GE, dl, MVT::i32));
6943       SDValue Result = DAG.getNode(ISD::OR, dl, CmpVT, TmpOp0, TmpOp1);
6944       if (Invert)
6945         Result = DAG.getNOT(dl, Result, VT);
6946       return Result;
6947     }
6948     }
6949   } else {
6950     // Integer comparisons.
6951     switch (SetCCOpcode) {
6952     default: llvm_unreachable("Illegal integer comparison");
6953     case ISD::SETNE:
6954       if (ST->hasMVEIntegerOps()) {
6955         Opc = ARMCC::NE; break;
6956       } else {
6957         Invert = true; [[fallthrough]];
6958       }
6959     case ISD::SETEQ:  Opc = ARMCC::EQ; break;
6960     case ISD::SETLT:  Swap = true; [[fallthrough]];
6961     case ISD::SETGT:  Opc = ARMCC::GT; break;
6962     case ISD::SETLE:  Swap = true; [[fallthrough]];
6963     case ISD::SETGE:  Opc = ARMCC::GE; break;
6964     case ISD::SETULT: Swap = true; [[fallthrough]];
6965     case ISD::SETUGT: Opc = ARMCC::HI; break;
6966     case ISD::SETULE: Swap = true; [[fallthrough]];
6967     case ISD::SETUGE: Opc = ARMCC::HS; break;
6968     }
6969 
6970     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
6971     if (ST->hasNEON() && Opc == ARMCC::EQ) {
6972       SDValue AndOp;
6973       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
6974         AndOp = Op0;
6975       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
6976         AndOp = Op1;
6977 
6978       // Ignore bitconvert.
6979       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
6980         AndOp = AndOp.getOperand(0);
6981 
6982       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
6983         Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0));
6984         Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1));
6985         SDValue Result = DAG.getNode(ARMISD::VTST, dl, CmpVT, Op0, Op1);
6986         if (!Invert)
6987           Result = DAG.getNOT(dl, Result, VT);
6988         return Result;
6989       }
6990     }
6991   }
6992 
6993   if (Swap)
6994     std::swap(Op0, Op1);
6995 
6996   // If one of the operands is a constant vector zero, attempt to fold the
6997   // comparison to a specialized compare-against-zero form.
6998   if (ISD::isBuildVectorAllZeros(Op0.getNode()) &&
6999       (Opc == ARMCC::GE || Opc == ARMCC::GT || Opc == ARMCC::EQ ||
7000        Opc == ARMCC::NE)) {
7001     if (Opc == ARMCC::GE)
7002       Opc = ARMCC::LE;
7003     else if (Opc == ARMCC::GT)
7004       Opc = ARMCC::LT;
7005     std::swap(Op0, Op1);
7006   }
7007 
7008   SDValue Result;
7009   if (ISD::isBuildVectorAllZeros(Op1.getNode()) &&
7010       (Opc == ARMCC::GE || Opc == ARMCC::GT || Opc == ARMCC::LE ||
7011        Opc == ARMCC::LT || Opc == ARMCC::NE || Opc == ARMCC::EQ))
7012     Result = DAG.getNode(ARMISD::VCMPZ, dl, CmpVT, Op0,
7013                          DAG.getConstant(Opc, dl, MVT::i32));
7014   else
7015     Result = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op0, Op1,
7016                          DAG.getConstant(Opc, dl, MVT::i32));
7017 
7018   Result = DAG.getSExtOrTrunc(Result, dl, VT);
7019 
7020   if (Invert)
7021     Result = DAG.getNOT(dl, Result, VT);
7022 
7023   return Result;
7024 }
7025 
LowerSETCCCARRY(SDValue Op,SelectionDAG & DAG)7026 static SDValue LowerSETCCCARRY(SDValue Op, SelectionDAG &DAG) {
7027   SDValue LHS = Op.getOperand(0);
7028   SDValue RHS = Op.getOperand(1);
7029   SDValue Carry = Op.getOperand(2);
7030   SDValue Cond = Op.getOperand(3);
7031   SDLoc DL(Op);
7032 
7033   assert(LHS.getSimpleValueType().isInteger() && "SETCCCARRY is integer only.");
7034 
7035   // ARMISD::SUBE expects a carry not a borrow like ISD::USUBO_CARRY so we
7036   // have to invert the carry first.
7037   Carry = DAG.getNode(ISD::SUB, DL, MVT::i32,
7038                       DAG.getConstant(1, DL, MVT::i32), Carry);
7039   // This converts the boolean value carry into the carry flag.
7040   Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG);
7041 
7042   SDVTList VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
7043   SDValue Cmp = DAG.getNode(ARMISD::SUBE, DL, VTs, LHS, RHS, Carry);
7044 
7045   SDValue FVal = DAG.getConstant(0, DL, MVT::i32);
7046   SDValue TVal = DAG.getConstant(1, DL, MVT::i32);
7047   SDValue ARMcc = DAG.getConstant(
7048       IntCCToARMCC(cast<CondCodeSDNode>(Cond)->get()), DL, MVT::i32);
7049   return DAG.getNode(ARMISD::CMOV, DL, Op.getValueType(), FVal, TVal, ARMcc,
7050                      Cmp.getValue(1));
7051 }
7052 
7053 /// isVMOVModifiedImm - Check if the specified splat value corresponds to a
7054 /// valid vector constant for a NEON or MVE instruction with a "modified
7055 /// immediate" operand (e.g., VMOV).  If so, return the encoded value.
isVMOVModifiedImm(uint64_t SplatBits,uint64_t SplatUndef,unsigned SplatBitSize,SelectionDAG & DAG,const SDLoc & dl,EVT & VT,EVT VectorVT,VMOVModImmType type)7056 static SDValue isVMOVModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
7057                                  unsigned SplatBitSize, SelectionDAG &DAG,
7058                                  const SDLoc &dl, EVT &VT, EVT VectorVT,
7059                                  VMOVModImmType type) {
7060   unsigned OpCmode, Imm;
7061   bool is128Bits = VectorVT.is128BitVector();
7062 
7063   // SplatBitSize is set to the smallest size that splats the vector, so a
7064   // zero vector will always have SplatBitSize == 8.  However, NEON modified
7065   // immediate instructions others than VMOV do not support the 8-bit encoding
7066   // of a zero vector, and the default encoding of zero is supposed to be the
7067   // 32-bit version.
7068   if (SplatBits == 0)
7069     SplatBitSize = 32;
7070 
7071   switch (SplatBitSize) {
7072   case 8:
7073     if (type != VMOVModImm)
7074       return SDValue();
7075     // Any 1-byte value is OK.  Op=0, Cmode=1110.
7076     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
7077     OpCmode = 0xe;
7078     Imm = SplatBits;
7079     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
7080     break;
7081 
7082   case 16:
7083     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
7084     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
7085     if ((SplatBits & ~0xff) == 0) {
7086       // Value = 0x00nn: Op=x, Cmode=100x.
7087       OpCmode = 0x8;
7088       Imm = SplatBits;
7089       break;
7090     }
7091     if ((SplatBits & ~0xff00) == 0) {
7092       // Value = 0xnn00: Op=x, Cmode=101x.
7093       OpCmode = 0xa;
7094       Imm = SplatBits >> 8;
7095       break;
7096     }
7097     return SDValue();
7098 
7099   case 32:
7100     // NEON's 32-bit VMOV supports splat values where:
7101     // * only one byte is nonzero, or
7102     // * the least significant byte is 0xff and the second byte is nonzero, or
7103     // * the least significant 2 bytes are 0xff and the third is nonzero.
7104     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
7105     if ((SplatBits & ~0xff) == 0) {
7106       // Value = 0x000000nn: Op=x, Cmode=000x.
7107       OpCmode = 0;
7108       Imm = SplatBits;
7109       break;
7110     }
7111     if ((SplatBits & ~0xff00) == 0) {
7112       // Value = 0x0000nn00: Op=x, Cmode=001x.
7113       OpCmode = 0x2;
7114       Imm = SplatBits >> 8;
7115       break;
7116     }
7117     if ((SplatBits & ~0xff0000) == 0) {
7118       // Value = 0x00nn0000: Op=x, Cmode=010x.
7119       OpCmode = 0x4;
7120       Imm = SplatBits >> 16;
7121       break;
7122     }
7123     if ((SplatBits & ~0xff000000) == 0) {
7124       // Value = 0xnn000000: Op=x, Cmode=011x.
7125       OpCmode = 0x6;
7126       Imm = SplatBits >> 24;
7127       break;
7128     }
7129 
7130     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
7131     if (type == OtherModImm) return SDValue();
7132 
7133     if ((SplatBits & ~0xffff) == 0 &&
7134         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
7135       // Value = 0x0000nnff: Op=x, Cmode=1100.
7136       OpCmode = 0xc;
7137       Imm = SplatBits >> 8;
7138       break;
7139     }
7140 
7141     // cmode == 0b1101 is not supported for MVE VMVN
7142     if (type == MVEVMVNModImm)
7143       return SDValue();
7144 
7145     if ((SplatBits & ~0xffffff) == 0 &&
7146         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
7147       // Value = 0x00nnffff: Op=x, Cmode=1101.
7148       OpCmode = 0xd;
7149       Imm = SplatBits >> 16;
7150       break;
7151     }
7152 
7153     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
7154     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
7155     // VMOV.I32.  A (very) minor optimization would be to replicate the value
7156     // and fall through here to test for a valid 64-bit splat.  But, then the
7157     // caller would also need to check and handle the change in size.
7158     return SDValue();
7159 
7160   case 64: {
7161     if (type != VMOVModImm)
7162       return SDValue();
7163     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
7164     uint64_t BitMask = 0xff;
7165     unsigned ImmMask = 1;
7166     Imm = 0;
7167     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
7168       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
7169         Imm |= ImmMask;
7170       } else if ((SplatBits & BitMask) != 0) {
7171         return SDValue();
7172       }
7173       BitMask <<= 8;
7174       ImmMask <<= 1;
7175     }
7176 
7177     // Op=1, Cmode=1110.
7178     OpCmode = 0x1e;
7179     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
7180     break;
7181   }
7182 
7183   default:
7184     llvm_unreachable("unexpected size for isVMOVModifiedImm");
7185   }
7186 
7187   unsigned EncodedVal = ARM_AM::createVMOVModImm(OpCmode, Imm);
7188   return DAG.getTargetConstant(EncodedVal, dl, MVT::i32);
7189 }
7190 
LowerConstantFP(SDValue Op,SelectionDAG & DAG,const ARMSubtarget * ST) const7191 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
7192                                            const ARMSubtarget *ST) const {
7193   EVT VT = Op.getValueType();
7194   bool IsDouble = (VT == MVT::f64);
7195   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
7196   const APFloat &FPVal = CFP->getValueAPF();
7197 
7198   // Prevent floating-point constants from using literal loads
7199   // when execute-only is enabled.
7200   if (ST->genExecuteOnly()) {
7201     // We shouldn't trigger this for v6m execute-only
7202     assert((!ST->isThumb1Only() || ST->hasV8MBaselineOps()) &&
7203            "Unexpected architecture");
7204 
7205     // If we can represent the constant as an immediate, don't lower it
7206     if (isFPImmLegal(FPVal, VT))
7207       return Op;
7208     // Otherwise, construct as integer, and move to float register
7209     APInt INTVal = FPVal.bitcastToAPInt();
7210     SDLoc DL(CFP);
7211     switch (VT.getSimpleVT().SimpleTy) {
7212       default:
7213         llvm_unreachable("Unknown floating point type!");
7214         break;
7215       case MVT::f64: {
7216         SDValue Lo = DAG.getConstant(INTVal.trunc(32), DL, MVT::i32);
7217         SDValue Hi = DAG.getConstant(INTVal.lshr(32).trunc(32), DL, MVT::i32);
7218         return DAG.getNode(ARMISD::VMOVDRR, DL, MVT::f64, Lo, Hi);
7219       }
7220       case MVT::f32:
7221           return DAG.getNode(ARMISD::VMOVSR, DL, VT,
7222               DAG.getConstant(INTVal, DL, MVT::i32));
7223     }
7224   }
7225 
7226   if (!ST->hasVFP3Base())
7227     return SDValue();
7228 
7229   // Use the default (constant pool) lowering for double constants when we have
7230   // an SP-only FPU
7231   if (IsDouble && !Subtarget->hasFP64())
7232     return SDValue();
7233 
7234   // Try splatting with a VMOV.f32...
7235   int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
7236 
7237   if (ImmVal != -1) {
7238     if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
7239       // We have code in place to select a valid ConstantFP already, no need to
7240       // do any mangling.
7241       return Op;
7242     }
7243 
7244     // It's a float and we are trying to use NEON operations where
7245     // possible. Lower it to a splat followed by an extract.
7246     SDLoc DL(Op);
7247     SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32);
7248     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
7249                                       NewVal);
7250     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
7251                        DAG.getConstant(0, DL, MVT::i32));
7252   }
7253 
7254   // The rest of our options are NEON only, make sure that's allowed before
7255   // proceeding..
7256   if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
7257     return SDValue();
7258 
7259   EVT VMovVT;
7260   uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
7261 
7262   // It wouldn't really be worth bothering for doubles except for one very
7263   // important value, which does happen to match: 0.0. So make sure we don't do
7264   // anything stupid.
7265   if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
7266     return SDValue();
7267 
7268   // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
7269   SDValue NewVal = isVMOVModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op),
7270                                      VMovVT, VT, VMOVModImm);
7271   if (NewVal != SDValue()) {
7272     SDLoc DL(Op);
7273     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
7274                                       NewVal);
7275     if (IsDouble)
7276       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
7277 
7278     // It's a float: cast and extract a vector element.
7279     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
7280                                        VecConstant);
7281     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
7282                        DAG.getConstant(0, DL, MVT::i32));
7283   }
7284 
7285   // Finally, try a VMVN.i32
7286   NewVal = isVMOVModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT,
7287                              VT, VMVNModImm);
7288   if (NewVal != SDValue()) {
7289     SDLoc DL(Op);
7290     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
7291 
7292     if (IsDouble)
7293       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
7294 
7295     // It's a float: cast and extract a vector element.
7296     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
7297                                        VecConstant);
7298     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
7299                        DAG.getConstant(0, DL, MVT::i32));
7300   }
7301 
7302   return SDValue();
7303 }
7304 
7305 // check if an VEXT instruction can handle the shuffle mask when the
7306 // vector sources of the shuffle are the same.
isSingletonVEXTMask(ArrayRef<int> M,EVT VT,unsigned & Imm)7307 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
7308   unsigned NumElts = VT.getVectorNumElements();
7309 
7310   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
7311   if (M[0] < 0)
7312     return false;
7313 
7314   Imm = M[0];
7315 
7316   // If this is a VEXT shuffle, the immediate value is the index of the first
7317   // element.  The other shuffle indices must be the successive elements after
7318   // the first one.
7319   unsigned ExpectedElt = Imm;
7320   for (unsigned i = 1; i < NumElts; ++i) {
7321     // Increment the expected index.  If it wraps around, just follow it
7322     // back to index zero and keep going.
7323     ++ExpectedElt;
7324     if (ExpectedElt == NumElts)
7325       ExpectedElt = 0;
7326 
7327     if (M[i] < 0) continue; // ignore UNDEF indices
7328     if (ExpectedElt != static_cast<unsigned>(M[i]))
7329       return false;
7330   }
7331 
7332   return true;
7333 }
7334 
isVEXTMask(ArrayRef<int> M,EVT VT,bool & ReverseVEXT,unsigned & Imm)7335 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
7336                        bool &ReverseVEXT, unsigned &Imm) {
7337   unsigned NumElts = VT.getVectorNumElements();
7338   ReverseVEXT = false;
7339 
7340   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
7341   if (M[0] < 0)
7342     return false;
7343 
7344   Imm = M[0];
7345 
7346   // If this is a VEXT shuffle, the immediate value is the index of the first
7347   // element.  The other shuffle indices must be the successive elements after
7348   // the first one.
7349   unsigned ExpectedElt = Imm;
7350   for (unsigned i = 1; i < NumElts; ++i) {
7351     // Increment the expected index.  If it wraps around, it may still be
7352     // a VEXT but the source vectors must be swapped.
7353     ExpectedElt += 1;
7354     if (ExpectedElt == NumElts * 2) {
7355       ExpectedElt = 0;
7356       ReverseVEXT = true;
7357     }
7358 
7359     if (M[i] < 0) continue; // ignore UNDEF indices
7360     if (ExpectedElt != static_cast<unsigned>(M[i]))
7361       return false;
7362   }
7363 
7364   // Adjust the index value if the source operands will be swapped.
7365   if (ReverseVEXT)
7366     Imm -= NumElts;
7367 
7368   return true;
7369 }
7370 
isVTBLMask(ArrayRef<int> M,EVT VT)7371 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
7372   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
7373   // range, then 0 is placed into the resulting vector. So pretty much any mask
7374   // of 8 elements can work here.
7375   return VT == MVT::v8i8 && M.size() == 8;
7376 }
7377 
SelectPairHalf(unsigned Elements,ArrayRef<int> Mask,unsigned Index)7378 static unsigned SelectPairHalf(unsigned Elements, ArrayRef<int> Mask,
7379                                unsigned Index) {
7380   if (Mask.size() == Elements * 2)
7381     return Index / Elements;
7382   return Mask[Index] == 0 ? 0 : 1;
7383 }
7384 
7385 // Checks whether the shuffle mask represents a vector transpose (VTRN) by
7386 // checking that pairs of elements in the shuffle mask represent the same index
7387 // in each vector, incrementing the expected index by 2 at each step.
7388 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 2, 6]
7389 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,c,g}
7390 //  v2={e,f,g,h}
7391 // WhichResult gives the offset for each element in the mask based on which
7392 // of the two results it belongs to.
7393 //
7394 // The transpose can be represented either as:
7395 // result1 = shufflevector v1, v2, result1_shuffle_mask
7396 // result2 = shufflevector v1, v2, result2_shuffle_mask
7397 // where v1/v2 and the shuffle masks have the same number of elements
7398 // (here WhichResult (see below) indicates which result is being checked)
7399 //
7400 // or as:
7401 // results = shufflevector v1, v2, shuffle_mask
7402 // where both results are returned in one vector and the shuffle mask has twice
7403 // as many elements as v1/v2 (here WhichResult will always be 0 if true) here we
7404 // want to check the low half and high half of the shuffle mask as if it were
7405 // the other case
isVTRNMask(ArrayRef<int> M,EVT VT,unsigned & WhichResult)7406 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
7407   unsigned EltSz = VT.getScalarSizeInBits();
7408   if (EltSz == 64)
7409     return false;
7410 
7411   unsigned NumElts = VT.getVectorNumElements();
7412   if (M.size() != NumElts && M.size() != NumElts*2)
7413     return false;
7414 
7415   // If the mask is twice as long as the input vector then we need to check the
7416   // upper and lower parts of the mask with a matching value for WhichResult
7417   // FIXME: A mask with only even values will be rejected in case the first
7418   // element is undefined, e.g. [-1, 4, 2, 6] will be rejected, because only
7419   // M[0] is used to determine WhichResult
7420   for (unsigned i = 0; i < M.size(); i += NumElts) {
7421     WhichResult = SelectPairHalf(NumElts, M, i);
7422     for (unsigned j = 0; j < NumElts; j += 2) {
7423       if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
7424           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + NumElts + WhichResult))
7425         return false;
7426     }
7427   }
7428 
7429   if (M.size() == NumElts*2)
7430     WhichResult = 0;
7431 
7432   return true;
7433 }
7434 
7435 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
7436 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
7437 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
isVTRN_v_undef_Mask(ArrayRef<int> M,EVT VT,unsigned & WhichResult)7438 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
7439   unsigned EltSz = VT.getScalarSizeInBits();
7440   if (EltSz == 64)
7441     return false;
7442 
7443   unsigned NumElts = VT.getVectorNumElements();
7444   if (M.size() != NumElts && M.size() != NumElts*2)
7445     return false;
7446 
7447   for (unsigned i = 0; i < M.size(); i += NumElts) {
7448     WhichResult = SelectPairHalf(NumElts, M, i);
7449     for (unsigned j = 0; j < NumElts; j += 2) {
7450       if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
7451           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + WhichResult))
7452         return false;
7453     }
7454   }
7455 
7456   if (M.size() == NumElts*2)
7457     WhichResult = 0;
7458 
7459   return true;
7460 }
7461 
7462 // Checks whether the shuffle mask represents a vector unzip (VUZP) by checking
7463 // that the mask elements are either all even and in steps of size 2 or all odd
7464 // and in steps of size 2.
7465 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 2, 4, 6]
7466 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,c,e,g}
7467 //  v2={e,f,g,h}
7468 // Requires similar checks to that of isVTRNMask with
7469 // respect the how results are returned.
isVUZPMask(ArrayRef<int> M,EVT VT,unsigned & WhichResult)7470 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
7471   unsigned EltSz = VT.getScalarSizeInBits();
7472   if (EltSz == 64)
7473     return false;
7474 
7475   unsigned NumElts = VT.getVectorNumElements();
7476   if (M.size() != NumElts && M.size() != NumElts*2)
7477     return false;
7478 
7479   for (unsigned i = 0; i < M.size(); i += NumElts) {
7480     WhichResult = SelectPairHalf(NumElts, M, i);
7481     for (unsigned j = 0; j < NumElts; ++j) {
7482       if (M[i+j] >= 0 && (unsigned) M[i+j] != 2 * j + WhichResult)
7483         return false;
7484     }
7485   }
7486 
7487   if (M.size() == NumElts*2)
7488     WhichResult = 0;
7489 
7490   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
7491   if (VT.is64BitVector() && EltSz == 32)
7492     return false;
7493 
7494   return true;
7495 }
7496 
7497 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
7498 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
7499 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
isVUZP_v_undef_Mask(ArrayRef<int> M,EVT VT,unsigned & WhichResult)7500 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
7501   unsigned EltSz = VT.getScalarSizeInBits();
7502   if (EltSz == 64)
7503     return false;
7504 
7505   unsigned NumElts = VT.getVectorNumElements();
7506   if (M.size() != NumElts && M.size() != NumElts*2)
7507     return false;
7508 
7509   unsigned Half = NumElts / 2;
7510   for (unsigned i = 0; i < M.size(); i += NumElts) {
7511     WhichResult = SelectPairHalf(NumElts, M, i);
7512     for (unsigned j = 0; j < NumElts; j += Half) {
7513       unsigned Idx = WhichResult;
7514       for (unsigned k = 0; k < Half; ++k) {
7515         int MIdx = M[i + j + k];
7516         if (MIdx >= 0 && (unsigned) MIdx != Idx)
7517           return false;
7518         Idx += 2;
7519       }
7520     }
7521   }
7522 
7523   if (M.size() == NumElts*2)
7524     WhichResult = 0;
7525 
7526   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
7527   if (VT.is64BitVector() && EltSz == 32)
7528     return false;
7529 
7530   return true;
7531 }
7532 
7533 // Checks whether the shuffle mask represents a vector zip (VZIP) by checking
7534 // that pairs of elements of the shufflemask represent the same index in each
7535 // vector incrementing sequentially through the vectors.
7536 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 1, 5]
7537 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,b,f}
7538 //  v2={e,f,g,h}
7539 // Requires similar checks to that of isVTRNMask with respect the how results
7540 // are returned.
isVZIPMask(ArrayRef<int> M,EVT VT,unsigned & WhichResult)7541 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
7542   unsigned EltSz = VT.getScalarSizeInBits();
7543   if (EltSz == 64)
7544     return false;
7545 
7546   unsigned NumElts = VT.getVectorNumElements();
7547   if (M.size() != NumElts && M.size() != NumElts*2)
7548     return false;
7549 
7550   for (unsigned i = 0; i < M.size(); i += NumElts) {
7551     WhichResult = SelectPairHalf(NumElts, M, i);
7552     unsigned Idx = WhichResult * NumElts / 2;
7553     for (unsigned j = 0; j < NumElts; j += 2) {
7554       if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
7555           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx + NumElts))
7556         return false;
7557       Idx += 1;
7558     }
7559   }
7560 
7561   if (M.size() == NumElts*2)
7562     WhichResult = 0;
7563 
7564   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
7565   if (VT.is64BitVector() && EltSz == 32)
7566     return false;
7567 
7568   return true;
7569 }
7570 
7571 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
7572 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
7573 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
isVZIP_v_undef_Mask(ArrayRef<int> M,EVT VT,unsigned & WhichResult)7574 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
7575   unsigned EltSz = VT.getScalarSizeInBits();
7576   if (EltSz == 64)
7577     return false;
7578 
7579   unsigned NumElts = VT.getVectorNumElements();
7580   if (M.size() != NumElts && M.size() != NumElts*2)
7581     return false;
7582 
7583   for (unsigned i = 0; i < M.size(); i += NumElts) {
7584     WhichResult = SelectPairHalf(NumElts, M, i);
7585     unsigned Idx = WhichResult * NumElts / 2;
7586     for (unsigned j = 0; j < NumElts; j += 2) {
7587       if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
7588           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx))
7589         return false;
7590       Idx += 1;
7591     }
7592   }
7593 
7594   if (M.size() == NumElts*2)
7595     WhichResult = 0;
7596 
7597   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
7598   if (VT.is64BitVector() && EltSz == 32)
7599     return false;
7600 
7601   return true;
7602 }
7603 
7604 /// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN),
7605 /// and return the corresponding ARMISD opcode if it is, or 0 if it isn't.
isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask,EVT VT,unsigned & WhichResult,bool & isV_UNDEF)7606 static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT,
7607                                            unsigned &WhichResult,
7608                                            bool &isV_UNDEF) {
7609   isV_UNDEF = false;
7610   if (isVTRNMask(ShuffleMask, VT, WhichResult))
7611     return ARMISD::VTRN;
7612   if (isVUZPMask(ShuffleMask, VT, WhichResult))
7613     return ARMISD::VUZP;
7614   if (isVZIPMask(ShuffleMask, VT, WhichResult))
7615     return ARMISD::VZIP;
7616 
7617   isV_UNDEF = true;
7618   if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
7619     return ARMISD::VTRN;
7620   if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
7621     return ARMISD::VUZP;
7622   if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
7623     return ARMISD::VZIP;
7624 
7625   return 0;
7626 }
7627 
7628 /// \return true if this is a reverse operation on an vector.
isReverseMask(ArrayRef<int> M,EVT VT)7629 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
7630   unsigned NumElts = VT.getVectorNumElements();
7631   // Make sure the mask has the right size.
7632   if (NumElts != M.size())
7633       return false;
7634 
7635   // Look for <15, ..., 3, -1, 1, 0>.
7636   for (unsigned i = 0; i != NumElts; ++i)
7637     if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
7638       return false;
7639 
7640   return true;
7641 }
7642 
isTruncMask(ArrayRef<int> M,EVT VT,bool Top,bool SingleSource)7643 static bool isTruncMask(ArrayRef<int> M, EVT VT, bool Top, bool SingleSource) {
7644   unsigned NumElts = VT.getVectorNumElements();
7645   // Make sure the mask has the right size.
7646   if (NumElts != M.size() || (VT != MVT::v8i16 && VT != MVT::v16i8))
7647     return false;
7648 
7649   // Half-width truncation patterns (e.g. v4i32 -> v8i16):
7650   // !Top &&  SingleSource: <0, 2, 4, 6, 0, 2, 4, 6>
7651   // !Top && !SingleSource: <0, 2, 4, 6, 8, 10, 12, 14>
7652   //  Top &&  SingleSource: <1, 3, 5, 7, 1, 3, 5, 7>
7653   //  Top && !SingleSource: <1, 3, 5, 7, 9, 11, 13, 15>
7654   int Ofs = Top ? 1 : 0;
7655   int Upper = SingleSource ? 0 : NumElts;
7656   for (int i = 0, e = NumElts / 2; i != e; ++i) {
7657     if (M[i] >= 0 && M[i] != (i * 2) + Ofs)
7658       return false;
7659     if (M[i + e] >= 0 && M[i + e] != (i * 2) + Ofs + Upper)
7660       return false;
7661   }
7662   return true;
7663 }
7664 
isVMOVNMask(ArrayRef<int> M,EVT VT,bool Top,bool SingleSource)7665 static bool isVMOVNMask(ArrayRef<int> M, EVT VT, bool Top, bool SingleSource) {
7666   unsigned NumElts = VT.getVectorNumElements();
7667   // Make sure the mask has the right size.
7668   if (NumElts != M.size() || (VT != MVT::v8i16 && VT != MVT::v16i8))
7669     return false;
7670 
7671   // If Top
7672   //   Look for <0, N, 2, N+2, 4, N+4, ..>.
7673   //   This inserts Input2 into Input1
7674   // else if not Top
7675   //   Look for <0, N+1, 2, N+3, 4, N+5, ..>
7676   //   This inserts Input1 into Input2
7677   unsigned Offset = Top ? 0 : 1;
7678   unsigned N = SingleSource ? 0 : NumElts;
7679   for (unsigned i = 0; i < NumElts; i += 2) {
7680     if (M[i] >= 0 && M[i] != (int)i)
7681       return false;
7682     if (M[i + 1] >= 0 && M[i + 1] != (int)(N + i + Offset))
7683       return false;
7684   }
7685 
7686   return true;
7687 }
7688 
isVMOVNTruncMask(ArrayRef<int> M,EVT ToVT,bool rev)7689 static bool isVMOVNTruncMask(ArrayRef<int> M, EVT ToVT, bool rev) {
7690   unsigned NumElts = ToVT.getVectorNumElements();
7691   if (NumElts != M.size())
7692     return false;
7693 
7694   // Test if the Trunc can be convertable to a VMOVN with this shuffle. We are
7695   // looking for patterns of:
7696   // !rev: 0 N/2 1 N/2+1 2 N/2+2 ...
7697   //  rev: N/2 0 N/2+1 1 N/2+2 2 ...
7698 
7699   unsigned Off0 = rev ? NumElts / 2 : 0;
7700   unsigned Off1 = rev ? 0 : NumElts / 2;
7701   for (unsigned i = 0; i < NumElts; i += 2) {
7702     if (M[i] >= 0 && M[i] != (int)(Off0 + i / 2))
7703       return false;
7704     if (M[i + 1] >= 0 && M[i + 1] != (int)(Off1 + i / 2))
7705       return false;
7706   }
7707 
7708   return true;
7709 }
7710 
7711 // Reconstruct an MVE VCVT from a BuildVector of scalar fptrunc, all extracted
7712 // from a pair of inputs. For example:
7713 // BUILDVECTOR(FP_ROUND(EXTRACT_ELT(X, 0),
7714 //             FP_ROUND(EXTRACT_ELT(Y, 0),
7715 //             FP_ROUND(EXTRACT_ELT(X, 1),
7716 //             FP_ROUND(EXTRACT_ELT(Y, 1), ...)
LowerBuildVectorOfFPTrunc(SDValue BV,SelectionDAG & DAG,const ARMSubtarget * ST)7717 static SDValue LowerBuildVectorOfFPTrunc(SDValue BV, SelectionDAG &DAG,
7718                                          const ARMSubtarget *ST) {
7719   assert(BV.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
7720   if (!ST->hasMVEFloatOps())
7721     return SDValue();
7722 
7723   SDLoc dl(BV);
7724   EVT VT = BV.getValueType();
7725   if (VT != MVT::v8f16)
7726     return SDValue();
7727 
7728   // We are looking for a buildvector of fptrunc elements, where all the
7729   // elements are interleavingly extracted from two sources. Check the first two
7730   // items are valid enough and extract some info from them (they are checked
7731   // properly in the loop below).
7732   if (BV.getOperand(0).getOpcode() != ISD::FP_ROUND ||
7733       BV.getOperand(0).getOperand(0).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
7734       BV.getOperand(0).getOperand(0).getConstantOperandVal(1) != 0)
7735     return SDValue();
7736   if (BV.getOperand(1).getOpcode() != ISD::FP_ROUND ||
7737       BV.getOperand(1).getOperand(0).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
7738       BV.getOperand(1).getOperand(0).getConstantOperandVal(1) != 0)
7739     return SDValue();
7740   SDValue Op0 = BV.getOperand(0).getOperand(0).getOperand(0);
7741   SDValue Op1 = BV.getOperand(1).getOperand(0).getOperand(0);
7742   if (Op0.getValueType() != MVT::v4f32 || Op1.getValueType() != MVT::v4f32)
7743     return SDValue();
7744 
7745   // Check all the values in the BuildVector line up with our expectations.
7746   for (unsigned i = 1; i < 4; i++) {
7747     auto Check = [](SDValue Trunc, SDValue Op, unsigned Idx) {
7748       return Trunc.getOpcode() == ISD::FP_ROUND &&
7749              Trunc.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7750              Trunc.getOperand(0).getOperand(0) == Op &&
7751              Trunc.getOperand(0).getConstantOperandVal(1) == Idx;
7752     };
7753     if (!Check(BV.getOperand(i * 2 + 0), Op0, i))
7754       return SDValue();
7755     if (!Check(BV.getOperand(i * 2 + 1), Op1, i))
7756       return SDValue();
7757   }
7758 
7759   SDValue N1 = DAG.getNode(ARMISD::VCVTN, dl, VT, DAG.getUNDEF(VT), Op0,
7760                            DAG.getConstant(0, dl, MVT::i32));
7761   return DAG.getNode(ARMISD::VCVTN, dl, VT, N1, Op1,
7762                      DAG.getConstant(1, dl, MVT::i32));
7763 }
7764 
7765 // Reconstruct an MVE VCVT from a BuildVector of scalar fpext, all extracted
7766 // from a single input on alternating lanes. For example:
7767 // BUILDVECTOR(FP_ROUND(EXTRACT_ELT(X, 0),
7768 //             FP_ROUND(EXTRACT_ELT(X, 2),
7769 //             FP_ROUND(EXTRACT_ELT(X, 4), ...)
LowerBuildVectorOfFPExt(SDValue BV,SelectionDAG & DAG,const ARMSubtarget * ST)7770 static SDValue LowerBuildVectorOfFPExt(SDValue BV, SelectionDAG &DAG,
7771                                        const ARMSubtarget *ST) {
7772   assert(BV.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
7773   if (!ST->hasMVEFloatOps())
7774     return SDValue();
7775 
7776   SDLoc dl(BV);
7777   EVT VT = BV.getValueType();
7778   if (VT != MVT::v4f32)
7779     return SDValue();
7780 
7781   // We are looking for a buildvector of fptext elements, where all the
7782   // elements are alternating lanes from a single source. For example <0,2,4,6>
7783   // or <1,3,5,7>. Check the first two items are valid enough and extract some
7784   // info from them (they are checked properly in the loop below).
7785   if (BV.getOperand(0).getOpcode() != ISD::FP_EXTEND ||
7786       BV.getOperand(0).getOperand(0).getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7787     return SDValue();
7788   SDValue Op0 = BV.getOperand(0).getOperand(0).getOperand(0);
7789   int Offset = BV.getOperand(0).getOperand(0).getConstantOperandVal(1);
7790   if (Op0.getValueType() != MVT::v8f16 || (Offset != 0 && Offset != 1))
7791     return SDValue();
7792 
7793   // Check all the values in the BuildVector line up with our expectations.
7794   for (unsigned i = 1; i < 4; i++) {
7795     auto Check = [](SDValue Trunc, SDValue Op, unsigned Idx) {
7796       return Trunc.getOpcode() == ISD::FP_EXTEND &&
7797              Trunc.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7798              Trunc.getOperand(0).getOperand(0) == Op &&
7799              Trunc.getOperand(0).getConstantOperandVal(1) == Idx;
7800     };
7801     if (!Check(BV.getOperand(i), Op0, 2 * i + Offset))
7802       return SDValue();
7803   }
7804 
7805   return DAG.getNode(ARMISD::VCVTL, dl, VT, Op0,
7806                      DAG.getConstant(Offset, dl, MVT::i32));
7807 }
7808 
7809 // If N is an integer constant that can be moved into a register in one
7810 // instruction, return an SDValue of such a constant (will become a MOV
7811 // instruction).  Otherwise return null.
IsSingleInstrConstant(SDValue N,SelectionDAG & DAG,const ARMSubtarget * ST,const SDLoc & dl)7812 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
7813                                      const ARMSubtarget *ST, const SDLoc &dl) {
7814   uint64_t Val;
7815   if (!isa<ConstantSDNode>(N))
7816     return SDValue();
7817   Val = N->getAsZExtVal();
7818 
7819   if (ST->isThumb1Only()) {
7820     if (Val <= 255 || ~Val <= 255)
7821       return DAG.getConstant(Val, dl, MVT::i32);
7822   } else {
7823     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
7824       return DAG.getConstant(Val, dl, MVT::i32);
7825   }
7826   return SDValue();
7827 }
7828 
LowerBUILD_VECTOR_i1(SDValue Op,SelectionDAG & DAG,const ARMSubtarget * ST)7829 static SDValue LowerBUILD_VECTOR_i1(SDValue Op, SelectionDAG &DAG,
7830                                     const ARMSubtarget *ST) {
7831   SDLoc dl(Op);
7832   EVT VT = Op.getValueType();
7833 
7834   assert(ST->hasMVEIntegerOps() && "LowerBUILD_VECTOR_i1 called without MVE!");
7835 
7836   unsigned NumElts = VT.getVectorNumElements();
7837   unsigned BoolMask;
7838   unsigned BitsPerBool;
7839   if (NumElts == 2) {
7840     BitsPerBool = 8;
7841     BoolMask = 0xff;
7842   } else if (NumElts == 4) {
7843     BitsPerBool = 4;
7844     BoolMask = 0xf;
7845   } else if (NumElts == 8) {
7846     BitsPerBool = 2;
7847     BoolMask = 0x3;
7848   } else if (NumElts == 16) {
7849     BitsPerBool = 1;
7850     BoolMask = 0x1;
7851   } else
7852     return SDValue();
7853 
7854   // If this is a single value copied into all lanes (a splat), we can just sign
7855   // extend that single value
7856   SDValue FirstOp = Op.getOperand(0);
7857   if (!isa<ConstantSDNode>(FirstOp) &&
7858       llvm::all_of(llvm::drop_begin(Op->ops()), [&FirstOp](const SDUse &U) {
7859         return U.get().isUndef() || U.get() == FirstOp;
7860       })) {
7861     SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::i32, FirstOp,
7862                               DAG.getValueType(MVT::i1));
7863     return DAG.getNode(ARMISD::PREDICATE_CAST, dl, Op.getValueType(), Ext);
7864   }
7865 
7866   // First create base with bits set where known
7867   unsigned Bits32 = 0;
7868   for (unsigned i = 0; i < NumElts; ++i) {
7869     SDValue V = Op.getOperand(i);
7870     if (!isa<ConstantSDNode>(V) && !V.isUndef())
7871       continue;
7872     bool BitSet = V.isUndef() ? false : V->getAsZExtVal();
7873     if (BitSet)
7874       Bits32 |= BoolMask << (i * BitsPerBool);
7875   }
7876 
7877   // Add in unknown nodes
7878   SDValue Base = DAG.getNode(ARMISD::PREDICATE_CAST, dl, VT,
7879                              DAG.getConstant(Bits32, dl, MVT::i32));
7880   for (unsigned i = 0; i < NumElts; ++i) {
7881     SDValue V = Op.getOperand(i);
7882     if (isa<ConstantSDNode>(V) || V.isUndef())
7883       continue;
7884     Base = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Base, V,
7885                        DAG.getConstant(i, dl, MVT::i32));
7886   }
7887 
7888   return Base;
7889 }
7890 
LowerBUILD_VECTORToVIDUP(SDValue Op,SelectionDAG & DAG,const ARMSubtarget * ST)7891 static SDValue LowerBUILD_VECTORToVIDUP(SDValue Op, SelectionDAG &DAG,
7892                                         const ARMSubtarget *ST) {
7893   if (!ST->hasMVEIntegerOps())
7894     return SDValue();
7895 
7896   // We are looking for a buildvector where each element is Op[0] + i*N
7897   EVT VT = Op.getValueType();
7898   SDValue Op0 = Op.getOperand(0);
7899   unsigned NumElts = VT.getVectorNumElements();
7900 
7901   // Get the increment value from operand 1
7902   SDValue Op1 = Op.getOperand(1);
7903   if (Op1.getOpcode() != ISD::ADD || Op1.getOperand(0) != Op0 ||
7904       !isa<ConstantSDNode>(Op1.getOperand(1)))
7905     return SDValue();
7906   unsigned N = Op1.getConstantOperandVal(1);
7907   if (N != 1 && N != 2 && N != 4 && N != 8)
7908     return SDValue();
7909 
7910   // Check that each other operand matches
7911   for (unsigned I = 2; I < NumElts; I++) {
7912     SDValue OpI = Op.getOperand(I);
7913     if (OpI.getOpcode() != ISD::ADD || OpI.getOperand(0) != Op0 ||
7914         !isa<ConstantSDNode>(OpI.getOperand(1)) ||
7915         OpI.getConstantOperandVal(1) != I * N)
7916       return SDValue();
7917   }
7918 
7919   SDLoc DL(Op);
7920   return DAG.getNode(ARMISD::VIDUP, DL, DAG.getVTList(VT, MVT::i32), Op0,
7921                      DAG.getConstant(N, DL, MVT::i32));
7922 }
7923 
7924 // Returns true if the operation N can be treated as qr instruction variant at
7925 // operand Op.
IsQRMVEInstruction(const SDNode * N,const SDNode * Op)7926 static bool IsQRMVEInstruction(const SDNode *N, const SDNode *Op) {
7927   switch (N->getOpcode()) {
7928   case ISD::ADD:
7929   case ISD::MUL:
7930   case ISD::SADDSAT:
7931   case ISD::UADDSAT:
7932   case ISD::AVGFLOORS:
7933   case ISD::AVGFLOORU:
7934     return true;
7935   case ISD::SUB:
7936   case ISD::SSUBSAT:
7937   case ISD::USUBSAT:
7938     return N->getOperand(1).getNode() == Op;
7939   case ISD::INTRINSIC_WO_CHAIN:
7940     switch (N->getConstantOperandVal(0)) {
7941     case Intrinsic::arm_mve_add_predicated:
7942     case Intrinsic::arm_mve_mul_predicated:
7943     case Intrinsic::arm_mve_qadd_predicated:
7944     case Intrinsic::arm_mve_vhadd:
7945     case Intrinsic::arm_mve_hadd_predicated:
7946     case Intrinsic::arm_mve_vqdmulh:
7947     case Intrinsic::arm_mve_qdmulh_predicated:
7948     case Intrinsic::arm_mve_vqrdmulh:
7949     case Intrinsic::arm_mve_qrdmulh_predicated:
7950     case Intrinsic::arm_mve_vqdmull:
7951     case Intrinsic::arm_mve_vqdmull_predicated:
7952       return true;
7953     case Intrinsic::arm_mve_sub_predicated:
7954     case Intrinsic::arm_mve_qsub_predicated:
7955     case Intrinsic::arm_mve_vhsub:
7956     case Intrinsic::arm_mve_hsub_predicated:
7957       return N->getOperand(2).getNode() == Op;
7958     default:
7959       return false;
7960     }
7961   default:
7962     return false;
7963   }
7964 }
7965 
7966 // If this is a case we can't handle, return null and let the default
7967 // expansion code take care of it.
LowerBUILD_VECTOR(SDValue Op,SelectionDAG & DAG,const ARMSubtarget * ST) const7968 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
7969                                              const ARMSubtarget *ST) const {
7970   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
7971   SDLoc dl(Op);
7972   EVT VT = Op.getValueType();
7973 
7974   if (ST->hasMVEIntegerOps() && VT.getScalarSizeInBits() == 1)
7975     return LowerBUILD_VECTOR_i1(Op, DAG, ST);
7976 
7977   if (SDValue R = LowerBUILD_VECTORToVIDUP(Op, DAG, ST))
7978     return R;
7979 
7980   APInt SplatBits, SplatUndef;
7981   unsigned SplatBitSize;
7982   bool HasAnyUndefs;
7983   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
7984     if (SplatUndef.isAllOnes())
7985       return DAG.getUNDEF(VT);
7986 
7987     // If all the users of this constant splat are qr instruction variants,
7988     // generate a vdup of the constant.
7989     if (ST->hasMVEIntegerOps() && VT.getScalarSizeInBits() == SplatBitSize &&
7990         (SplatBitSize == 8 || SplatBitSize == 16 || SplatBitSize == 32) &&
7991         all_of(BVN->users(),
7992                [BVN](const SDNode *U) { return IsQRMVEInstruction(U, BVN); })) {
7993       EVT DupVT = SplatBitSize == 32   ? MVT::v4i32
7994                   : SplatBitSize == 16 ? MVT::v8i16
7995                                        : MVT::v16i8;
7996       SDValue Const = DAG.getConstant(SplatBits.getZExtValue(), dl, MVT::i32);
7997       SDValue VDup = DAG.getNode(ARMISD::VDUP, dl, DupVT, Const);
7998       return DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, VT, VDup);
7999     }
8000 
8001     if ((ST->hasNEON() && SplatBitSize <= 64) ||
8002         (ST->hasMVEIntegerOps() && SplatBitSize <= 64)) {
8003       // Check if an immediate VMOV works.
8004       EVT VmovVT;
8005       SDValue Val =
8006           isVMOVModifiedImm(SplatBits.getZExtValue(), SplatUndef.getZExtValue(),
8007                             SplatBitSize, DAG, dl, VmovVT, VT, VMOVModImm);
8008 
8009       if (Val.getNode()) {
8010         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
8011         return DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, VT, Vmov);
8012       }
8013 
8014       // Try an immediate VMVN.
8015       uint64_t NegatedImm = (~SplatBits).getZExtValue();
8016       Val = isVMOVModifiedImm(
8017           NegatedImm, SplatUndef.getZExtValue(), SplatBitSize, DAG, dl, VmovVT,
8018           VT, ST->hasMVEIntegerOps() ? MVEVMVNModImm : VMVNModImm);
8019       if (Val.getNode()) {
8020         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
8021         return DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, VT, Vmov);
8022       }
8023 
8024       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
8025       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
8026         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
8027         if (ImmVal != -1) {
8028           SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32);
8029           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
8030         }
8031       }
8032 
8033       // If we are under MVE, generate a VDUP(constant), bitcast to the original
8034       // type.
8035       if (ST->hasMVEIntegerOps() &&
8036           (SplatBitSize == 8 || SplatBitSize == 16 || SplatBitSize == 32)) {
8037         EVT DupVT = SplatBitSize == 32   ? MVT::v4i32
8038                     : SplatBitSize == 16 ? MVT::v8i16
8039                                          : MVT::v16i8;
8040         SDValue Const = DAG.getConstant(SplatBits.getZExtValue(), dl, MVT::i32);
8041         SDValue VDup = DAG.getNode(ARMISD::VDUP, dl, DupVT, Const);
8042         return DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, VT, VDup);
8043       }
8044     }
8045   }
8046 
8047   // Scan through the operands to see if only one value is used.
8048   //
8049   // As an optimisation, even if more than one value is used it may be more
8050   // profitable to splat with one value then change some lanes.
8051   //
8052   // Heuristically we decide to do this if the vector has a "dominant" value,
8053   // defined as splatted to more than half of the lanes.
8054   unsigned NumElts = VT.getVectorNumElements();
8055   bool isOnlyLowElement = true;
8056   bool usesOnlyOneValue = true;
8057   bool hasDominantValue = false;
8058   bool isConstant = true;
8059 
8060   // Map of the number of times a particular SDValue appears in the
8061   // element list.
8062   DenseMap<SDValue, unsigned> ValueCounts;
8063   SDValue Value;
8064   for (unsigned i = 0; i < NumElts; ++i) {
8065     SDValue V = Op.getOperand(i);
8066     if (V.isUndef())
8067       continue;
8068     if (i > 0)
8069       isOnlyLowElement = false;
8070     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
8071       isConstant = false;
8072 
8073     unsigned &Count = ValueCounts[V];
8074 
8075     // Is this value dominant? (takes up more than half of the lanes)
8076     if (++Count > (NumElts / 2)) {
8077       hasDominantValue = true;
8078       Value = V;
8079     }
8080   }
8081   if (ValueCounts.size() != 1)
8082     usesOnlyOneValue = false;
8083   if (!Value.getNode() && !ValueCounts.empty())
8084     Value = ValueCounts.begin()->first;
8085 
8086   if (ValueCounts.empty())
8087     return DAG.getUNDEF(VT);
8088 
8089   // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
8090   // Keep going if we are hitting this case.
8091   if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
8092     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
8093 
8094   unsigned EltSize = VT.getScalarSizeInBits();
8095 
8096   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
8097   // i32 and try again.
8098   if (hasDominantValue && EltSize <= 32) {
8099     if (!isConstant) {
8100       SDValue N;
8101 
8102       // If we are VDUPing a value that comes directly from a vector, that will
8103       // cause an unnecessary move to and from a GPR, where instead we could
8104       // just use VDUPLANE. We can only do this if the lane being extracted
8105       // is at a constant index, as the VDUP from lane instructions only have
8106       // constant-index forms.
8107       ConstantSDNode *constIndex;
8108       if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
8109           (constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1)))) {
8110         // We need to create a new undef vector to use for the VDUPLANE if the
8111         // size of the vector from which we get the value is different than the
8112         // size of the vector that we need to create. We will insert the element
8113         // such that the register coalescer will remove unnecessary copies.
8114         if (VT != Value->getOperand(0).getValueType()) {
8115           unsigned index = constIndex->getAPIntValue().getLimitedValue() %
8116                              VT.getVectorNumElements();
8117           N =  DAG.getNode(ARMISD::VDUPLANE, dl, VT,
8118                  DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
8119                         Value, DAG.getConstant(index, dl, MVT::i32)),
8120                            DAG.getConstant(index, dl, MVT::i32));
8121         } else
8122           N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
8123                         Value->getOperand(0), Value->getOperand(1));
8124       } else
8125         N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
8126 
8127       if (!usesOnlyOneValue) {
8128         // The dominant value was splatted as 'N', but we now have to insert
8129         // all differing elements.
8130         for (unsigned I = 0; I < NumElts; ++I) {
8131           if (Op.getOperand(I) == Value)
8132             continue;
8133           SmallVector<SDValue, 3> Ops;
8134           Ops.push_back(N);
8135           Ops.push_back(Op.getOperand(I));
8136           Ops.push_back(DAG.getConstant(I, dl, MVT::i32));
8137           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
8138         }
8139       }
8140       return N;
8141     }
8142     if (VT.getVectorElementType().isFloatingPoint()) {
8143       SmallVector<SDValue, 8> Ops;
8144       MVT FVT = VT.getVectorElementType().getSimpleVT();
8145       assert(FVT == MVT::f32 || FVT == MVT::f16);
8146       MVT IVT = (FVT == MVT::f32) ? MVT::i32 : MVT::i16;
8147       for (unsigned i = 0; i < NumElts; ++i)
8148         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, IVT,
8149                                   Op.getOperand(i)));
8150       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), IVT, NumElts);
8151       SDValue Val = DAG.getBuildVector(VecVT, dl, Ops);
8152       Val = LowerBUILD_VECTOR(Val, DAG, ST);
8153       if (Val.getNode())
8154         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
8155     }
8156     if (usesOnlyOneValue) {
8157       SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
8158       if (isConstant && Val.getNode())
8159         return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
8160     }
8161   }
8162 
8163   // If all elements are constants and the case above didn't get hit, fall back
8164   // to the default expansion, which will generate a load from the constant
8165   // pool.
8166   if (isConstant)
8167     return SDValue();
8168 
8169   // Reconstruct the BUILDVECTOR to one of the legal shuffles (such as vext and
8170   // vmovn). Empirical tests suggest this is rarely worth it for vectors of
8171   // length <= 2.
8172   if (NumElts >= 4)
8173     if (SDValue shuffle = ReconstructShuffle(Op, DAG))
8174       return shuffle;
8175 
8176   // Attempt to turn a buildvector of scalar fptrunc's or fpext's back into
8177   // VCVT's
8178   if (SDValue VCVT = LowerBuildVectorOfFPTrunc(Op, DAG, Subtarget))
8179     return VCVT;
8180   if (SDValue VCVT = LowerBuildVectorOfFPExt(Op, DAG, Subtarget))
8181     return VCVT;
8182 
8183   if (ST->hasNEON() && VT.is128BitVector() && VT != MVT::v2f64 && VT != MVT::v4f32) {
8184     // If we haven't found an efficient lowering, try splitting a 128-bit vector
8185     // into two 64-bit vectors; we might discover a better way to lower it.
8186     SmallVector<SDValue, 64> Ops(Op->op_begin(), Op->op_begin() + NumElts);
8187     EVT ExtVT = VT.getVectorElementType();
8188     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElts / 2);
8189     SDValue Lower = DAG.getBuildVector(HVT, dl, ArrayRef(&Ops[0], NumElts / 2));
8190     if (Lower.getOpcode() == ISD::BUILD_VECTOR)
8191       Lower = LowerBUILD_VECTOR(Lower, DAG, ST);
8192     SDValue Upper =
8193         DAG.getBuildVector(HVT, dl, ArrayRef(&Ops[NumElts / 2], NumElts / 2));
8194     if (Upper.getOpcode() == ISD::BUILD_VECTOR)
8195       Upper = LowerBUILD_VECTOR(Upper, DAG, ST);
8196     if (Lower && Upper)
8197       return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lower, Upper);
8198   }
8199 
8200   // Vectors with 32- or 64-bit elements can be built by directly assigning
8201   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
8202   // will be legalized.
8203   if (EltSize >= 32) {
8204     // Do the expansion with floating-point types, since that is what the VFP
8205     // registers are defined to use, and since i64 is not legal.
8206     EVT EltVT = EVT::getFloatingPointVT(EltSize);
8207     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
8208     SmallVector<SDValue, 8> Ops;
8209     for (unsigned i = 0; i < NumElts; ++i)
8210       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
8211     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
8212     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
8213   }
8214 
8215   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
8216   // know the default expansion would otherwise fall back on something even
8217   // worse. For a vector with one or two non-undef values, that's
8218   // scalar_to_vector for the elements followed by a shuffle (provided the
8219   // shuffle is valid for the target) and materialization element by element
8220   // on the stack followed by a load for everything else.
8221   if (!isConstant && !usesOnlyOneValue) {
8222     SDValue Vec = DAG.getUNDEF(VT);
8223     for (unsigned i = 0 ; i < NumElts; ++i) {
8224       SDValue V = Op.getOperand(i);
8225       if (V.isUndef())
8226         continue;
8227       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32);
8228       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
8229     }
8230     return Vec;
8231   }
8232 
8233   return SDValue();
8234 }
8235 
8236 // Gather data to see if the operation can be modelled as a
8237 // shuffle in combination with VEXTs.
ReconstructShuffle(SDValue Op,SelectionDAG & DAG) const8238 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
8239                                               SelectionDAG &DAG) const {
8240   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
8241   SDLoc dl(Op);
8242   EVT VT = Op.getValueType();
8243   unsigned NumElts = VT.getVectorNumElements();
8244 
8245   struct ShuffleSourceInfo {
8246     SDValue Vec;
8247     unsigned MinElt = std::numeric_limits<unsigned>::max();
8248     unsigned MaxElt = 0;
8249 
8250     // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
8251     // be compatible with the shuffle we intend to construct. As a result
8252     // ShuffleVec will be some sliding window into the original Vec.
8253     SDValue ShuffleVec;
8254 
8255     // Code should guarantee that element i in Vec starts at element "WindowBase
8256     // + i * WindowScale in ShuffleVec".
8257     int WindowBase = 0;
8258     int WindowScale = 1;
8259 
8260     ShuffleSourceInfo(SDValue Vec) : Vec(Vec), ShuffleVec(Vec) {}
8261 
8262     bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
8263   };
8264 
8265   // First gather all vectors used as an immediate source for this BUILD_VECTOR
8266   // node.
8267   SmallVector<ShuffleSourceInfo, 2> Sources;
8268   for (unsigned i = 0; i < NumElts; ++i) {
8269     SDValue V = Op.getOperand(i);
8270     if (V.isUndef())
8271       continue;
8272     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
8273       // A shuffle can only come from building a vector from various
8274       // elements of other vectors.
8275       return SDValue();
8276     } else if (!isa<ConstantSDNode>(V.getOperand(1))) {
8277       // Furthermore, shuffles require a constant mask, whereas extractelts
8278       // accept variable indices.
8279       return SDValue();
8280     }
8281 
8282     // Add this element source to the list if it's not already there.
8283     SDValue SourceVec = V.getOperand(0);
8284     auto Source = llvm::find(Sources, SourceVec);
8285     if (Source == Sources.end())
8286       Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
8287 
8288     // Update the minimum and maximum lane number seen.
8289     unsigned EltNo = V.getConstantOperandVal(1);
8290     Source->MinElt = std::min(Source->MinElt, EltNo);
8291     Source->MaxElt = std::max(Source->MaxElt, EltNo);
8292   }
8293 
8294   // Currently only do something sane when at most two source vectors
8295   // are involved.
8296   if (Sources.size() > 2)
8297     return SDValue();
8298 
8299   // Find out the smallest element size among result and two sources, and use
8300   // it as element size to build the shuffle_vector.
8301   EVT SmallestEltTy = VT.getVectorElementType();
8302   for (auto &Source : Sources) {
8303     EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
8304     if (SrcEltTy.bitsLT(SmallestEltTy))
8305       SmallestEltTy = SrcEltTy;
8306   }
8307   unsigned ResMultiplier =
8308       VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits();
8309   NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
8310   EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
8311 
8312   // If the source vector is too wide or too narrow, we may nevertheless be able
8313   // to construct a compatible shuffle either by concatenating it with UNDEF or
8314   // extracting a suitable range of elements.
8315   for (auto &Src : Sources) {
8316     EVT SrcVT = Src.ShuffleVec.getValueType();
8317 
8318     uint64_t SrcVTSize = SrcVT.getFixedSizeInBits();
8319     uint64_t VTSize = VT.getFixedSizeInBits();
8320     if (SrcVTSize == VTSize)
8321       continue;
8322 
8323     // This stage of the search produces a source with the same element type as
8324     // the original, but with a total width matching the BUILD_VECTOR output.
8325     EVT EltVT = SrcVT.getVectorElementType();
8326     unsigned NumSrcElts = VTSize / EltVT.getFixedSizeInBits();
8327     EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
8328 
8329     if (SrcVTSize < VTSize) {
8330       if (2 * SrcVTSize != VTSize)
8331         return SDValue();
8332       // We can pad out the smaller vector for free, so if it's part of a
8333       // shuffle...
8334       Src.ShuffleVec =
8335           DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
8336                       DAG.getUNDEF(Src.ShuffleVec.getValueType()));
8337       continue;
8338     }
8339 
8340     if (SrcVTSize != 2 * VTSize)
8341       return SDValue();
8342 
8343     if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
8344       // Span too large for a VEXT to cope
8345       return SDValue();
8346     }
8347 
8348     if (Src.MinElt >= NumSrcElts) {
8349       // The extraction can just take the second half
8350       Src.ShuffleVec =
8351           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
8352                       DAG.getConstant(NumSrcElts, dl, MVT::i32));
8353       Src.WindowBase = -NumSrcElts;
8354     } else if (Src.MaxElt < NumSrcElts) {
8355       // The extraction can just take the first half
8356       Src.ShuffleVec =
8357           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
8358                       DAG.getConstant(0, dl, MVT::i32));
8359     } else {
8360       // An actual VEXT is needed
8361       SDValue VEXTSrc1 =
8362           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
8363                       DAG.getConstant(0, dl, MVT::i32));
8364       SDValue VEXTSrc2 =
8365           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
8366                       DAG.getConstant(NumSrcElts, dl, MVT::i32));
8367 
8368       Src.ShuffleVec = DAG.getNode(ARMISD::VEXT, dl, DestVT, VEXTSrc1,
8369                                    VEXTSrc2,
8370                                    DAG.getConstant(Src.MinElt, dl, MVT::i32));
8371       Src.WindowBase = -Src.MinElt;
8372     }
8373   }
8374 
8375   // Another possible incompatibility occurs from the vector element types. We
8376   // can fix this by bitcasting the source vectors to the same type we intend
8377   // for the shuffle.
8378   for (auto &Src : Sources) {
8379     EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
8380     if (SrcEltTy == SmallestEltTy)
8381       continue;
8382     assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
8383     Src.ShuffleVec = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, ShuffleVT, Src.ShuffleVec);
8384     Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
8385     Src.WindowBase *= Src.WindowScale;
8386   }
8387 
8388   // Final check before we try to actually produce a shuffle.
8389   LLVM_DEBUG({
8390     for (auto Src : Sources)
8391       assert(Src.ShuffleVec.getValueType() == ShuffleVT);
8392   });
8393 
8394   // The stars all align, our next step is to produce the mask for the shuffle.
8395   SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
8396   int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits();
8397   for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
8398     SDValue Entry = Op.getOperand(i);
8399     if (Entry.isUndef())
8400       continue;
8401 
8402     auto Src = llvm::find(Sources, Entry.getOperand(0));
8403     int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
8404 
8405     // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
8406     // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
8407     // segment.
8408     EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
8409     int BitsDefined = std::min(OrigEltTy.getScalarSizeInBits(),
8410                                VT.getScalarSizeInBits());
8411     int LanesDefined = BitsDefined / BitsPerShuffleLane;
8412 
8413     // This source is expected to fill ResMultiplier lanes of the final shuffle,
8414     // starting at the appropriate offset.
8415     int *LaneMask = &Mask[i * ResMultiplier];
8416 
8417     int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
8418     ExtractBase += NumElts * (Src - Sources.begin());
8419     for (int j = 0; j < LanesDefined; ++j)
8420       LaneMask[j] = ExtractBase + j;
8421   }
8422 
8423 
8424   // We can't handle more than two sources. This should have already
8425   // been checked before this point.
8426   assert(Sources.size() <= 2 && "Too many sources!");
8427 
8428   SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
8429   for (unsigned i = 0; i < Sources.size(); ++i)
8430     ShuffleOps[i] = Sources[i].ShuffleVec;
8431 
8432   SDValue Shuffle = buildLegalVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
8433                                             ShuffleOps[1], Mask, DAG);
8434   if (!Shuffle)
8435     return SDValue();
8436   return DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, VT, Shuffle);
8437 }
8438 
8439 enum ShuffleOpCodes {
8440   OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
8441   OP_VREV,
8442   OP_VDUP0,
8443   OP_VDUP1,
8444   OP_VDUP2,
8445   OP_VDUP3,
8446   OP_VEXT1,
8447   OP_VEXT2,
8448   OP_VEXT3,
8449   OP_VUZPL, // VUZP, left result
8450   OP_VUZPR, // VUZP, right result
8451   OP_VZIPL, // VZIP, left result
8452   OP_VZIPR, // VZIP, right result
8453   OP_VTRNL, // VTRN, left result
8454   OP_VTRNR  // VTRN, right result
8455 };
8456 
isLegalMVEShuffleOp(unsigned PFEntry)8457 static bool isLegalMVEShuffleOp(unsigned PFEntry) {
8458   unsigned OpNum = (PFEntry >> 26) & 0x0F;
8459   switch (OpNum) {
8460   case OP_COPY:
8461   case OP_VREV:
8462   case OP_VDUP0:
8463   case OP_VDUP1:
8464   case OP_VDUP2:
8465   case OP_VDUP3:
8466     return true;
8467   }
8468   return false;
8469 }
8470 
8471 /// isShuffleMaskLegal - Targets can use this to indicate that they only
8472 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
8473 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
8474 /// are assumed to be legal.
isShuffleMaskLegal(ArrayRef<int> M,EVT VT) const8475 bool ARMTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
8476   if (VT.getVectorNumElements() == 4 &&
8477       (VT.is128BitVector() || VT.is64BitVector())) {
8478     unsigned PFIndexes[4];
8479     for (unsigned i = 0; i != 4; ++i) {
8480       if (M[i] < 0)
8481         PFIndexes[i] = 8;
8482       else
8483         PFIndexes[i] = M[i];
8484     }
8485 
8486     // Compute the index in the perfect shuffle table.
8487     unsigned PFTableIndex =
8488       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
8489     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
8490     unsigned Cost = (PFEntry >> 30);
8491 
8492     if (Cost <= 4 && (Subtarget->hasNEON() || isLegalMVEShuffleOp(PFEntry)))
8493       return true;
8494   }
8495 
8496   bool ReverseVEXT, isV_UNDEF;
8497   unsigned Imm, WhichResult;
8498 
8499   unsigned EltSize = VT.getScalarSizeInBits();
8500   if (EltSize >= 32 ||
8501       ShuffleVectorSDNode::isSplatMask(M) ||
8502       ShuffleVectorInst::isIdentityMask(M, M.size()) ||
8503       isVREVMask(M, VT, 64) ||
8504       isVREVMask(M, VT, 32) ||
8505       isVREVMask(M, VT, 16))
8506     return true;
8507   else if (Subtarget->hasNEON() &&
8508            (isVEXTMask(M, VT, ReverseVEXT, Imm) ||
8509             isVTBLMask(M, VT) ||
8510             isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF)))
8511     return true;
8512   else if ((VT == MVT::v8i16 || VT == MVT::v8f16 || VT == MVT::v16i8) &&
8513            isReverseMask(M, VT))
8514     return true;
8515   else if (Subtarget->hasMVEIntegerOps() &&
8516            (isVMOVNMask(M, VT, true, false) ||
8517             isVMOVNMask(M, VT, false, false) || isVMOVNMask(M, VT, true, true)))
8518     return true;
8519   else if (Subtarget->hasMVEIntegerOps() &&
8520            (isTruncMask(M, VT, false, false) ||
8521             isTruncMask(M, VT, false, true) ||
8522             isTruncMask(M, VT, true, false) || isTruncMask(M, VT, true, true)))
8523     return true;
8524   else
8525     return false;
8526 }
8527 
8528 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
8529 /// the specified operations to build the shuffle.
GeneratePerfectShuffle(unsigned PFEntry,SDValue LHS,SDValue RHS,SelectionDAG & DAG,const SDLoc & dl)8530 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
8531                                       SDValue RHS, SelectionDAG &DAG,
8532                                       const SDLoc &dl) {
8533   unsigned OpNum = (PFEntry >> 26) & 0x0F;
8534   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
8535   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
8536 
8537   if (OpNum == OP_COPY) {
8538     if (LHSID == (1*9+2)*9+3) return LHS;
8539     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
8540     return RHS;
8541   }
8542 
8543   SDValue OpLHS, OpRHS;
8544   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
8545   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
8546   EVT VT = OpLHS.getValueType();
8547 
8548   switch (OpNum) {
8549   default: llvm_unreachable("Unknown shuffle opcode!");
8550   case OP_VREV:
8551     // VREV divides the vector in half and swaps within the half.
8552     if (VT.getScalarSizeInBits() == 32)
8553       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
8554     // vrev <4 x i16> -> VREV32
8555     if (VT.getScalarSizeInBits() == 16)
8556       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
8557     // vrev <4 x i8> -> VREV16
8558     assert(VT.getScalarSizeInBits() == 8);
8559     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
8560   case OP_VDUP0:
8561   case OP_VDUP1:
8562   case OP_VDUP2:
8563   case OP_VDUP3:
8564     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
8565                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32));
8566   case OP_VEXT1:
8567   case OP_VEXT2:
8568   case OP_VEXT3:
8569     return DAG.getNode(ARMISD::VEXT, dl, VT,
8570                        OpLHS, OpRHS,
8571                        DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32));
8572   case OP_VUZPL:
8573   case OP_VUZPR:
8574     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
8575                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
8576   case OP_VZIPL:
8577   case OP_VZIPR:
8578     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
8579                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
8580   case OP_VTRNL:
8581   case OP_VTRNR:
8582     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
8583                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
8584   }
8585 }
8586 
LowerVECTOR_SHUFFLEv8i8(SDValue Op,ArrayRef<int> ShuffleMask,SelectionDAG & DAG)8587 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
8588                                        ArrayRef<int> ShuffleMask,
8589                                        SelectionDAG &DAG) {
8590   // Check to see if we can use the VTBL instruction.
8591   SDValue V1 = Op.getOperand(0);
8592   SDValue V2 = Op.getOperand(1);
8593   SDLoc DL(Op);
8594 
8595   SmallVector<SDValue, 8> VTBLMask;
8596   for (int I : ShuffleMask)
8597     VTBLMask.push_back(DAG.getSignedConstant(I, DL, MVT::i32));
8598 
8599   if (V2.getNode()->isUndef())
8600     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
8601                        DAG.getBuildVector(MVT::v8i8, DL, VTBLMask));
8602 
8603   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
8604                      DAG.getBuildVector(MVT::v8i8, DL, VTBLMask));
8605 }
8606 
LowerReverse_VECTOR_SHUFFLE(SDValue Op,SelectionDAG & DAG)8607 static SDValue LowerReverse_VECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
8608   SDLoc DL(Op);
8609   EVT VT = Op.getValueType();
8610 
8611   assert((VT == MVT::v8i16 || VT == MVT::v8f16 || VT == MVT::v16i8) &&
8612          "Expect an v8i16/v16i8 type");
8613   SDValue OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, Op.getOperand(0));
8614   // For a v16i8 type: After the VREV, we have got <7, ..., 0, 15, ..., 8>. Now,
8615   // extract the first 8 bytes into the top double word and the last 8 bytes
8616   // into the bottom double word, through a new vector shuffle that will be
8617   // turned into a VEXT on Neon, or a couple of VMOVDs on MVE.
8618   std::vector<int> NewMask;
8619   for (unsigned i = 0; i < VT.getVectorNumElements() / 2; i++)
8620     NewMask.push_back(VT.getVectorNumElements() / 2 + i);
8621   for (unsigned i = 0; i < VT.getVectorNumElements() / 2; i++)
8622     NewMask.push_back(i);
8623   return DAG.getVectorShuffle(VT, DL, OpLHS, OpLHS, NewMask);
8624 }
8625 
getVectorTyFromPredicateVector(EVT VT)8626 static EVT getVectorTyFromPredicateVector(EVT VT) {
8627   switch (VT.getSimpleVT().SimpleTy) {
8628   case MVT::v2i1:
8629     return MVT::v2f64;
8630   case MVT::v4i1:
8631     return MVT::v4i32;
8632   case MVT::v8i1:
8633     return MVT::v8i16;
8634   case MVT::v16i1:
8635     return MVT::v16i8;
8636   default:
8637     llvm_unreachable("Unexpected vector predicate type");
8638   }
8639 }
8640 
PromoteMVEPredVector(SDLoc dl,SDValue Pred,EVT VT,SelectionDAG & DAG)8641 static SDValue PromoteMVEPredVector(SDLoc dl, SDValue Pred, EVT VT,
8642                                     SelectionDAG &DAG) {
8643   // Converting from boolean predicates to integers involves creating a vector
8644   // of all ones or all zeroes and selecting the lanes based upon the real
8645   // predicate.
8646   SDValue AllOnes =
8647       DAG.getTargetConstant(ARM_AM::createVMOVModImm(0xe, 0xff), dl, MVT::i32);
8648   AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v16i8, AllOnes);
8649 
8650   SDValue AllZeroes =
8651       DAG.getTargetConstant(ARM_AM::createVMOVModImm(0xe, 0x0), dl, MVT::i32);
8652   AllZeroes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v16i8, AllZeroes);
8653 
8654   // Get full vector type from predicate type
8655   EVT NewVT = getVectorTyFromPredicateVector(VT);
8656 
8657   SDValue RecastV1;
8658   // If the real predicate is an v8i1 or v4i1 (not v16i1) then we need to recast
8659   // this to a v16i1. This cannot be done with an ordinary bitcast because the
8660   // sizes are not the same. We have to use a MVE specific PREDICATE_CAST node,
8661   // since we know in hardware the sizes are really the same.
8662   if (VT != MVT::v16i1)
8663     RecastV1 = DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::v16i1, Pred);
8664   else
8665     RecastV1 = Pred;
8666 
8667   // Select either all ones or zeroes depending upon the real predicate bits.
8668   SDValue PredAsVector =
8669       DAG.getNode(ISD::VSELECT, dl, MVT::v16i8, RecastV1, AllOnes, AllZeroes);
8670 
8671   // Recast our new predicate-as-integer v16i8 vector into something
8672   // appropriate for the shuffle, i.e. v4i32 for a real v4i1 predicate.
8673   return DAG.getNode(ISD::BITCAST, dl, NewVT, PredAsVector);
8674 }
8675 
LowerVECTOR_SHUFFLE_i1(SDValue Op,SelectionDAG & DAG,const ARMSubtarget * ST)8676 static SDValue LowerVECTOR_SHUFFLE_i1(SDValue Op, SelectionDAG &DAG,
8677                                       const ARMSubtarget *ST) {
8678   EVT VT = Op.getValueType();
8679   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
8680   ArrayRef<int> ShuffleMask = SVN->getMask();
8681 
8682   assert(ST->hasMVEIntegerOps() &&
8683          "No support for vector shuffle of boolean predicates");
8684 
8685   SDValue V1 = Op.getOperand(0);
8686   SDValue V2 = Op.getOperand(1);
8687   SDLoc dl(Op);
8688   if (isReverseMask(ShuffleMask, VT)) {
8689     SDValue cast = DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, V1);
8690     SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, MVT::i32, cast);
8691     SDValue srl = DAG.getNode(ISD::SRL, dl, MVT::i32, rbit,
8692                               DAG.getConstant(16, dl, MVT::i32));
8693     return DAG.getNode(ARMISD::PREDICATE_CAST, dl, VT, srl);
8694   }
8695 
8696   // Until we can come up with optimised cases for every single vector
8697   // shuffle in existence we have chosen the least painful strategy. This is
8698   // to essentially promote the boolean predicate to a 8-bit integer, where
8699   // each predicate represents a byte. Then we fall back on a normal integer
8700   // vector shuffle and convert the result back into a predicate vector. In
8701   // many cases the generated code might be even better than scalar code
8702   // operating on bits. Just imagine trying to shuffle 8 arbitrary 2-bit
8703   // fields in a register into 8 other arbitrary 2-bit fields!
8704   SDValue PredAsVector1 = PromoteMVEPredVector(dl, V1, VT, DAG);
8705   EVT NewVT = PredAsVector1.getValueType();
8706   SDValue PredAsVector2 = V2.isUndef() ? DAG.getUNDEF(NewVT)
8707                                        : PromoteMVEPredVector(dl, V2, VT, DAG);
8708   assert(PredAsVector2.getValueType() == NewVT &&
8709          "Expected identical vector type in expanded i1 shuffle!");
8710 
8711   // Do the shuffle!
8712   SDValue Shuffled = DAG.getVectorShuffle(NewVT, dl, PredAsVector1,
8713                                           PredAsVector2, ShuffleMask);
8714 
8715   // Now return the result of comparing the shuffled vector with zero,
8716   // which will generate a real predicate, i.e. v4i1, v8i1 or v16i1. For a v2i1
8717   // we convert to a v4i1 compare to fill in the two halves of the i64 as i32s.
8718   if (VT == MVT::v2i1) {
8719     SDValue BC = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, MVT::v4i32, Shuffled);
8720     SDValue Cmp = DAG.getNode(ARMISD::VCMPZ, dl, MVT::v4i1, BC,
8721                               DAG.getConstant(ARMCC::NE, dl, MVT::i32));
8722     return DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::v2i1, Cmp);
8723   }
8724   return DAG.getNode(ARMISD::VCMPZ, dl, VT, Shuffled,
8725                      DAG.getConstant(ARMCC::NE, dl, MVT::i32));
8726 }
8727 
LowerVECTOR_SHUFFLEUsingMovs(SDValue Op,ArrayRef<int> ShuffleMask,SelectionDAG & DAG)8728 static SDValue LowerVECTOR_SHUFFLEUsingMovs(SDValue Op,
8729                                             ArrayRef<int> ShuffleMask,
8730                                             SelectionDAG &DAG) {
8731   // Attempt to lower the vector shuffle using as many whole register movs as
8732   // possible. This is useful for types smaller than 32bits, which would
8733   // often otherwise become a series for grp movs.
8734   SDLoc dl(Op);
8735   EVT VT = Op.getValueType();
8736   if (VT.getScalarSizeInBits() >= 32)
8737     return SDValue();
8738 
8739   assert((VT == MVT::v8i16 || VT == MVT::v8f16 || VT == MVT::v16i8) &&
8740          "Unexpected vector type");
8741   int NumElts = VT.getVectorNumElements();
8742   int QuarterSize = NumElts / 4;
8743   // The four final parts of the vector, as i32's
8744   SDValue Parts[4];
8745 
8746   // Look for full lane vmovs like <0,1,2,3> or <u,5,6,7> etc, (but not
8747   // <u,u,u,u>), returning the vmov lane index
8748   auto getMovIdx = [](ArrayRef<int> ShuffleMask, int Start, int Length) {
8749     // Detect which mov lane this would be from the first non-undef element.
8750     int MovIdx = -1;
8751     for (int i = 0; i < Length; i++) {
8752       if (ShuffleMask[Start + i] >= 0) {
8753         if (ShuffleMask[Start + i] % Length != i)
8754           return -1;
8755         MovIdx = ShuffleMask[Start + i] / Length;
8756         break;
8757       }
8758     }
8759     // If all items are undef, leave this for other combines
8760     if (MovIdx == -1)
8761       return -1;
8762     // Check the remaining values are the correct part of the same mov
8763     for (int i = 1; i < Length; i++) {
8764       if (ShuffleMask[Start + i] >= 0 &&
8765           (ShuffleMask[Start + i] / Length != MovIdx ||
8766            ShuffleMask[Start + i] % Length != i))
8767         return -1;
8768     }
8769     return MovIdx;
8770   };
8771 
8772   for (int Part = 0; Part < 4; ++Part) {
8773     // Does this part look like a mov
8774     int Elt = getMovIdx(ShuffleMask, Part * QuarterSize, QuarterSize);
8775     if (Elt != -1) {
8776       SDValue Input = Op->getOperand(0);
8777       if (Elt >= 4) {
8778         Input = Op->getOperand(1);
8779         Elt -= 4;
8780       }
8781       SDValue BitCast = DAG.getBitcast(MVT::v4f32, Input);
8782       Parts[Part] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, BitCast,
8783                                 DAG.getConstant(Elt, dl, MVT::i32));
8784     }
8785   }
8786 
8787   // Nothing interesting found, just return
8788   if (!Parts[0] && !Parts[1] && !Parts[2] && !Parts[3])
8789     return SDValue();
8790 
8791   // The other parts need to be built with the old shuffle vector, cast to a
8792   // v4i32 and extract_vector_elts
8793   if (!Parts[0] || !Parts[1] || !Parts[2] || !Parts[3]) {
8794     SmallVector<int, 16> NewShuffleMask;
8795     for (int Part = 0; Part < 4; ++Part)
8796       for (int i = 0; i < QuarterSize; i++)
8797         NewShuffleMask.push_back(
8798             Parts[Part] ? -1 : ShuffleMask[Part * QuarterSize + i]);
8799     SDValue NewShuffle = DAG.getVectorShuffle(
8800         VT, dl, Op->getOperand(0), Op->getOperand(1), NewShuffleMask);
8801     SDValue BitCast = DAG.getBitcast(MVT::v4f32, NewShuffle);
8802 
8803     for (int Part = 0; Part < 4; ++Part)
8804       if (!Parts[Part])
8805         Parts[Part] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32,
8806                                   BitCast, DAG.getConstant(Part, dl, MVT::i32));
8807   }
8808   // Build a vector out of the various parts and bitcast it back to the original
8809   // type.
8810   SDValue NewVec = DAG.getNode(ARMISD::BUILD_VECTOR, dl, MVT::v4f32, Parts);
8811   return DAG.getBitcast(VT, NewVec);
8812 }
8813 
LowerVECTOR_SHUFFLEUsingOneOff(SDValue Op,ArrayRef<int> ShuffleMask,SelectionDAG & DAG)8814 static SDValue LowerVECTOR_SHUFFLEUsingOneOff(SDValue Op,
8815                                               ArrayRef<int> ShuffleMask,
8816                                               SelectionDAG &DAG) {
8817   SDValue V1 = Op.getOperand(0);
8818   SDValue V2 = Op.getOperand(1);
8819   EVT VT = Op.getValueType();
8820   unsigned NumElts = VT.getVectorNumElements();
8821 
8822   // An One-Off Identity mask is one that is mostly an identity mask from as
8823   // single source but contains a single element out-of-place, either from a
8824   // different vector or from another position in the same vector. As opposed to
8825   // lowering this via a ARMISD::BUILD_VECTOR we can generate an extract/insert
8826   // pair directly.
8827   auto isOneOffIdentityMask = [](ArrayRef<int> Mask, EVT VT, int BaseOffset,
8828                                  int &OffElement) {
8829     OffElement = -1;
8830     int NonUndef = 0;
8831     for (int i = 0, NumMaskElts = Mask.size(); i < NumMaskElts; ++i) {
8832       if (Mask[i] == -1)
8833         continue;
8834       NonUndef++;
8835       if (Mask[i] != i + BaseOffset) {
8836         if (OffElement == -1)
8837           OffElement = i;
8838         else
8839           return false;
8840       }
8841     }
8842     return NonUndef > 2 && OffElement != -1;
8843   };
8844   int OffElement;
8845   SDValue VInput;
8846   if (isOneOffIdentityMask(ShuffleMask, VT, 0, OffElement))
8847     VInput = V1;
8848   else if (isOneOffIdentityMask(ShuffleMask, VT, NumElts, OffElement))
8849     VInput = V2;
8850   else
8851     return SDValue();
8852 
8853   SDLoc dl(Op);
8854   EVT SVT = VT.getScalarType() == MVT::i8 || VT.getScalarType() == MVT::i16
8855                 ? MVT::i32
8856                 : VT.getScalarType();
8857   SDValue Elt = DAG.getNode(
8858       ISD::EXTRACT_VECTOR_ELT, dl, SVT,
8859       ShuffleMask[OffElement] < (int)NumElts ? V1 : V2,
8860       DAG.getVectorIdxConstant(ShuffleMask[OffElement] % NumElts, dl));
8861   return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, VInput, Elt,
8862                      DAG.getVectorIdxConstant(OffElement % NumElts, dl));
8863 }
8864 
LowerVECTOR_SHUFFLE(SDValue Op,SelectionDAG & DAG,const ARMSubtarget * ST)8865 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG,
8866                                    const ARMSubtarget *ST) {
8867   SDValue V1 = Op.getOperand(0);
8868   SDValue V2 = Op.getOperand(1);
8869   SDLoc dl(Op);
8870   EVT VT = Op.getValueType();
8871   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
8872   unsigned EltSize = VT.getScalarSizeInBits();
8873 
8874   if (ST->hasMVEIntegerOps() && EltSize == 1)
8875     return LowerVECTOR_SHUFFLE_i1(Op, DAG, ST);
8876 
8877   // Convert shuffles that are directly supported on NEON to target-specific
8878   // DAG nodes, instead of keeping them as shuffles and matching them again
8879   // during code selection.  This is more efficient and avoids the possibility
8880   // of inconsistencies between legalization and selection.
8881   // FIXME: floating-point vectors should be canonicalized to integer vectors
8882   // of the same time so that they get CSEd properly.
8883   ArrayRef<int> ShuffleMask = SVN->getMask();
8884 
8885   if (EltSize <= 32) {
8886     if (SVN->isSplat()) {
8887       int Lane = SVN->getSplatIndex();
8888       // If this is undef splat, generate it via "just" vdup, if possible.
8889       if (Lane == -1) Lane = 0;
8890 
8891       // Test if V1 is a SCALAR_TO_VECTOR.
8892       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
8893         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
8894       }
8895       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
8896       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
8897       // reaches it).
8898       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
8899           !isa<ConstantSDNode>(V1.getOperand(0))) {
8900         bool IsScalarToVector = true;
8901         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
8902           if (!V1.getOperand(i).isUndef()) {
8903             IsScalarToVector = false;
8904             break;
8905           }
8906         if (IsScalarToVector)
8907           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
8908       }
8909       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
8910                          DAG.getConstant(Lane, dl, MVT::i32));
8911     }
8912 
8913     bool ReverseVEXT = false;
8914     unsigned Imm = 0;
8915     if (ST->hasNEON() && isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
8916       if (ReverseVEXT)
8917         std::swap(V1, V2);
8918       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
8919                          DAG.getConstant(Imm, dl, MVT::i32));
8920     }
8921 
8922     if (isVREVMask(ShuffleMask, VT, 64))
8923       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
8924     if (isVREVMask(ShuffleMask, VT, 32))
8925       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
8926     if (isVREVMask(ShuffleMask, VT, 16))
8927       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
8928 
8929     if (ST->hasNEON() && V2->isUndef() && isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
8930       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
8931                          DAG.getConstant(Imm, dl, MVT::i32));
8932     }
8933 
8934     // Check for Neon shuffles that modify both input vectors in place.
8935     // If both results are used, i.e., if there are two shuffles with the same
8936     // source operands and with masks corresponding to both results of one of
8937     // these operations, DAG memoization will ensure that a single node is
8938     // used for both shuffles.
8939     unsigned WhichResult = 0;
8940     bool isV_UNDEF = false;
8941     if (ST->hasNEON()) {
8942       if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
8943               ShuffleMask, VT, WhichResult, isV_UNDEF)) {
8944         if (isV_UNDEF)
8945           V2 = V1;
8946         return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2)
8947             .getValue(WhichResult);
8948       }
8949     }
8950     if (ST->hasMVEIntegerOps()) {
8951       if (isVMOVNMask(ShuffleMask, VT, false, false))
8952         return DAG.getNode(ARMISD::VMOVN, dl, VT, V2, V1,
8953                            DAG.getConstant(0, dl, MVT::i32));
8954       if (isVMOVNMask(ShuffleMask, VT, true, false))
8955         return DAG.getNode(ARMISD::VMOVN, dl, VT, V1, V2,
8956                            DAG.getConstant(1, dl, MVT::i32));
8957       if (isVMOVNMask(ShuffleMask, VT, true, true))
8958         return DAG.getNode(ARMISD::VMOVN, dl, VT, V1, V1,
8959                            DAG.getConstant(1, dl, MVT::i32));
8960     }
8961 
8962     // Also check for these shuffles through CONCAT_VECTORS: we canonicalize
8963     // shuffles that produce a result larger than their operands with:
8964     //   shuffle(concat(v1, undef), concat(v2, undef))
8965     // ->
8966     //   shuffle(concat(v1, v2), undef)
8967     // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine).
8968     //
8969     // This is useful in the general case, but there are special cases where
8970     // native shuffles produce larger results: the two-result ops.
8971     //
8972     // Look through the concat when lowering them:
8973     //   shuffle(concat(v1, v2), undef)
8974     // ->
8975     //   concat(VZIP(v1, v2):0, :1)
8976     //
8977     if (ST->hasNEON() && V1->getOpcode() == ISD::CONCAT_VECTORS && V2->isUndef()) {
8978       SDValue SubV1 = V1->getOperand(0);
8979       SDValue SubV2 = V1->getOperand(1);
8980       EVT SubVT = SubV1.getValueType();
8981 
8982       // We expect these to have been canonicalized to -1.
8983       assert(llvm::all_of(ShuffleMask, [&](int i) {
8984         return i < (int)VT.getVectorNumElements();
8985       }) && "Unexpected shuffle index into UNDEF operand!");
8986 
8987       if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
8988               ShuffleMask, SubVT, WhichResult, isV_UNDEF)) {
8989         if (isV_UNDEF)
8990           SubV2 = SubV1;
8991         assert((WhichResult == 0) &&
8992                "In-place shuffle of concat can only have one result!");
8993         SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT),
8994                                   SubV1, SubV2);
8995         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0),
8996                            Res.getValue(1));
8997       }
8998     }
8999   }
9000 
9001   if (ST->hasMVEIntegerOps() && EltSize <= 32) {
9002     if (SDValue V = LowerVECTOR_SHUFFLEUsingOneOff(Op, ShuffleMask, DAG))
9003       return V;
9004 
9005     for (bool Top : {false, true}) {
9006       for (bool SingleSource : {false, true}) {
9007         if (isTruncMask(ShuffleMask, VT, Top, SingleSource)) {
9008           MVT FromSVT = MVT::getIntegerVT(EltSize * 2);
9009           MVT FromVT = MVT::getVectorVT(FromSVT, ShuffleMask.size() / 2);
9010           SDValue Lo = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, FromVT, V1);
9011           SDValue Hi = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, FromVT,
9012                                    SingleSource ? V1 : V2);
9013           if (Top) {
9014             SDValue Amt = DAG.getConstant(EltSize, dl, FromVT);
9015             Lo = DAG.getNode(ISD::SRL, dl, FromVT, Lo, Amt);
9016             Hi = DAG.getNode(ISD::SRL, dl, FromVT, Hi, Amt);
9017           }
9018           return DAG.getNode(ARMISD::MVETRUNC, dl, VT, Lo, Hi);
9019         }
9020       }
9021     }
9022   }
9023 
9024   // If the shuffle is not directly supported and it has 4 elements, use
9025   // the PerfectShuffle-generated table to synthesize it from other shuffles.
9026   unsigned NumElts = VT.getVectorNumElements();
9027   if (NumElts == 4) {
9028     unsigned PFIndexes[4];
9029     for (unsigned i = 0; i != 4; ++i) {
9030       if (ShuffleMask[i] < 0)
9031         PFIndexes[i] = 8;
9032       else
9033         PFIndexes[i] = ShuffleMask[i];
9034     }
9035 
9036     // Compute the index in the perfect shuffle table.
9037     unsigned PFTableIndex =
9038       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
9039     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
9040     unsigned Cost = (PFEntry >> 30);
9041 
9042     if (Cost <= 4) {
9043       if (ST->hasNEON())
9044         return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
9045       else if (isLegalMVEShuffleOp(PFEntry)) {
9046         unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
9047         unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
9048         unsigned PFEntryLHS = PerfectShuffleTable[LHSID];
9049         unsigned PFEntryRHS = PerfectShuffleTable[RHSID];
9050         if (isLegalMVEShuffleOp(PFEntryLHS) && isLegalMVEShuffleOp(PFEntryRHS))
9051           return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
9052       }
9053     }
9054   }
9055 
9056   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
9057   if (EltSize >= 32) {
9058     // Do the expansion with floating-point types, since that is what the VFP
9059     // registers are defined to use, and since i64 is not legal.
9060     EVT EltVT = EVT::getFloatingPointVT(EltSize);
9061     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
9062     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
9063     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
9064     SmallVector<SDValue, 8> Ops;
9065     for (unsigned i = 0; i < NumElts; ++i) {
9066       if (ShuffleMask[i] < 0)
9067         Ops.push_back(DAG.getUNDEF(EltVT));
9068       else
9069         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
9070                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
9071                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
9072                                                   dl, MVT::i32)));
9073     }
9074     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
9075     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
9076   }
9077 
9078   if ((VT == MVT::v8i16 || VT == MVT::v8f16 || VT == MVT::v16i8) &&
9079       isReverseMask(ShuffleMask, VT))
9080     return LowerReverse_VECTOR_SHUFFLE(Op, DAG);
9081 
9082   if (ST->hasNEON() && VT == MVT::v8i8)
9083     if (SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG))
9084       return NewOp;
9085 
9086   if (ST->hasMVEIntegerOps())
9087     if (SDValue NewOp = LowerVECTOR_SHUFFLEUsingMovs(Op, ShuffleMask, DAG))
9088       return NewOp;
9089 
9090   return SDValue();
9091 }
9092 
LowerINSERT_VECTOR_ELT_i1(SDValue Op,SelectionDAG & DAG,const ARMSubtarget * ST)9093 static SDValue LowerINSERT_VECTOR_ELT_i1(SDValue Op, SelectionDAG &DAG,
9094                                          const ARMSubtarget *ST) {
9095   EVT VecVT = Op.getOperand(0).getValueType();
9096   SDLoc dl(Op);
9097 
9098   assert(ST->hasMVEIntegerOps() &&
9099          "LowerINSERT_VECTOR_ELT_i1 called without MVE!");
9100 
9101   SDValue Conv =
9102       DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, Op->getOperand(0));
9103   unsigned Lane = Op.getConstantOperandVal(2);
9104   unsigned LaneWidth =
9105       getVectorTyFromPredicateVector(VecVT).getScalarSizeInBits() / 8;
9106   unsigned Mask = ((1 << LaneWidth) - 1) << Lane * LaneWidth;
9107   SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::i32,
9108                             Op.getOperand(1), DAG.getValueType(MVT::i1));
9109   SDValue BFI = DAG.getNode(ARMISD::BFI, dl, MVT::i32, Conv, Ext,
9110                             DAG.getConstant(~Mask, dl, MVT::i32));
9111   return DAG.getNode(ARMISD::PREDICATE_CAST, dl, Op.getValueType(), BFI);
9112 }
9113 
LowerINSERT_VECTOR_ELT(SDValue Op,SelectionDAG & DAG) const9114 SDValue ARMTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
9115                                                   SelectionDAG &DAG) const {
9116   // INSERT_VECTOR_ELT is legal only for immediate indexes.
9117   SDValue Lane = Op.getOperand(2);
9118   if (!isa<ConstantSDNode>(Lane))
9119     return SDValue();
9120 
9121   SDValue Elt = Op.getOperand(1);
9122   EVT EltVT = Elt.getValueType();
9123 
9124   if (Subtarget->hasMVEIntegerOps() &&
9125       Op.getValueType().getScalarSizeInBits() == 1)
9126     return LowerINSERT_VECTOR_ELT_i1(Op, DAG, Subtarget);
9127 
9128   if (getTypeAction(*DAG.getContext(), EltVT) ==
9129       TargetLowering::TypeSoftPromoteHalf) {
9130     // INSERT_VECTOR_ELT doesn't want f16 operands promoting to f32,
9131     // but the type system will try to do that if we don't intervene.
9132     // Reinterpret any such vector-element insertion as one with the
9133     // corresponding integer types.
9134 
9135     SDLoc dl(Op);
9136 
9137     EVT IEltVT = MVT::getIntegerVT(EltVT.getScalarSizeInBits());
9138     assert(getTypeAction(*DAG.getContext(), IEltVT) !=
9139            TargetLowering::TypeSoftPromoteHalf);
9140 
9141     SDValue VecIn = Op.getOperand(0);
9142     EVT VecVT = VecIn.getValueType();
9143     EVT IVecVT = EVT::getVectorVT(*DAG.getContext(), IEltVT,
9144                                   VecVT.getVectorNumElements());
9145 
9146     SDValue IElt = DAG.getNode(ISD::BITCAST, dl, IEltVT, Elt);
9147     SDValue IVecIn = DAG.getNode(ISD::BITCAST, dl, IVecVT, VecIn);
9148     SDValue IVecOut = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, IVecVT,
9149                                   IVecIn, IElt, Lane);
9150     return DAG.getNode(ISD::BITCAST, dl, VecVT, IVecOut);
9151   }
9152 
9153   return Op;
9154 }
9155 
LowerEXTRACT_VECTOR_ELT_i1(SDValue Op,SelectionDAG & DAG,const ARMSubtarget * ST)9156 static SDValue LowerEXTRACT_VECTOR_ELT_i1(SDValue Op, SelectionDAG &DAG,
9157                                           const ARMSubtarget *ST) {
9158   EVT VecVT = Op.getOperand(0).getValueType();
9159   SDLoc dl(Op);
9160 
9161   assert(ST->hasMVEIntegerOps() &&
9162          "LowerINSERT_VECTOR_ELT_i1 called without MVE!");
9163 
9164   SDValue Conv =
9165       DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, Op->getOperand(0));
9166   unsigned Lane = Op.getConstantOperandVal(1);
9167   unsigned LaneWidth =
9168       getVectorTyFromPredicateVector(VecVT).getScalarSizeInBits() / 8;
9169   SDValue Shift = DAG.getNode(ISD::SRL, dl, MVT::i32, Conv,
9170                               DAG.getConstant(Lane * LaneWidth, dl, MVT::i32));
9171   return Shift;
9172 }
9173 
LowerEXTRACT_VECTOR_ELT(SDValue Op,SelectionDAG & DAG,const ARMSubtarget * ST)9174 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG,
9175                                        const ARMSubtarget *ST) {
9176   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
9177   SDValue Lane = Op.getOperand(1);
9178   if (!isa<ConstantSDNode>(Lane))
9179     return SDValue();
9180 
9181   SDValue Vec = Op.getOperand(0);
9182   EVT VT = Vec.getValueType();
9183 
9184   if (ST->hasMVEIntegerOps() && VT.getScalarSizeInBits() == 1)
9185     return LowerEXTRACT_VECTOR_ELT_i1(Op, DAG, ST);
9186 
9187   if (Op.getValueType() == MVT::i32 && Vec.getScalarValueSizeInBits() < 32) {
9188     SDLoc dl(Op);
9189     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
9190   }
9191 
9192   return Op;
9193 }
9194 
LowerCONCAT_VECTORS_i1(SDValue Op,SelectionDAG & DAG,const ARMSubtarget * ST)9195 static SDValue LowerCONCAT_VECTORS_i1(SDValue Op, SelectionDAG &DAG,
9196                                       const ARMSubtarget *ST) {
9197   SDLoc dl(Op);
9198   assert(Op.getValueType().getScalarSizeInBits() == 1 &&
9199          "Unexpected custom CONCAT_VECTORS lowering");
9200   assert(isPowerOf2_32(Op.getNumOperands()) &&
9201          "Unexpected custom CONCAT_VECTORS lowering");
9202   assert(ST->hasMVEIntegerOps() &&
9203          "CONCAT_VECTORS lowering only supported for MVE");
9204 
9205   auto ConcatPair = [&](SDValue V1, SDValue V2) {
9206     EVT Op1VT = V1.getValueType();
9207     EVT Op2VT = V2.getValueType();
9208     assert(Op1VT == Op2VT && "Operand types don't match!");
9209     assert((Op1VT == MVT::v2i1 || Op1VT == MVT::v4i1 || Op1VT == MVT::v8i1) &&
9210            "Unexpected i1 concat operations!");
9211     EVT VT = Op1VT.getDoubleNumVectorElementsVT(*DAG.getContext());
9212 
9213     SDValue NewV1 = PromoteMVEPredVector(dl, V1, Op1VT, DAG);
9214     SDValue NewV2 = PromoteMVEPredVector(dl, V2, Op2VT, DAG);
9215 
9216     // We now have Op1 + Op2 promoted to vectors of integers, where v8i1 gets
9217     // promoted to v8i16, etc.
9218     MVT ElType =
9219         getVectorTyFromPredicateVector(VT).getScalarType().getSimpleVT();
9220     unsigned NumElts = 2 * Op1VT.getVectorNumElements();
9221 
9222     EVT ConcatVT = MVT::getVectorVT(ElType, NumElts);
9223     if (Op1VT == MVT::v4i1 || Op1VT == MVT::v8i1) {
9224       // Use MVETRUNC to truncate the combined NewV1::NewV2 into the smaller
9225       // ConcatVT.
9226       SDValue ConVec =
9227           DAG.getNode(ARMISD::MVETRUNC, dl, ConcatVT, NewV1, NewV2);
9228       return DAG.getNode(ARMISD::VCMPZ, dl, VT, ConVec,
9229                          DAG.getConstant(ARMCC::NE, dl, MVT::i32));
9230     }
9231 
9232     // Extract the vector elements from Op1 and Op2 one by one and truncate them
9233     // to be the right size for the destination. For example, if Op1 is v4i1
9234     // then the promoted vector is v4i32. The result of concatenation gives a
9235     // v8i1, which when promoted is v8i16. That means each i32 element from Op1
9236     // needs truncating to i16 and inserting in the result.
9237     auto ExtractInto = [&DAG, &dl](SDValue NewV, SDValue ConVec, unsigned &j) {
9238       EVT NewVT = NewV.getValueType();
9239       EVT ConcatVT = ConVec.getValueType();
9240       unsigned ExtScale = 1;
9241       if (NewVT == MVT::v2f64) {
9242         NewV = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, MVT::v4i32, NewV);
9243         ExtScale = 2;
9244       }
9245       for (unsigned i = 0, e = NewVT.getVectorNumElements(); i < e; i++, j++) {
9246         SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, NewV,
9247                                   DAG.getIntPtrConstant(i * ExtScale, dl));
9248         ConVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ConcatVT, ConVec, Elt,
9249                              DAG.getConstant(j, dl, MVT::i32));
9250       }
9251       return ConVec;
9252     };
9253     unsigned j = 0;
9254     SDValue ConVec = DAG.getNode(ISD::UNDEF, dl, ConcatVT);
9255     ConVec = ExtractInto(NewV1, ConVec, j);
9256     ConVec = ExtractInto(NewV2, ConVec, j);
9257 
9258     // Now return the result of comparing the subvector with zero, which will
9259     // generate a real predicate, i.e. v4i1, v8i1 or v16i1.
9260     return DAG.getNode(ARMISD::VCMPZ, dl, VT, ConVec,
9261                        DAG.getConstant(ARMCC::NE, dl, MVT::i32));
9262   };
9263 
9264   // Concat each pair of subvectors and pack into the lower half of the array.
9265   SmallVector<SDValue> ConcatOps(Op->ops());
9266   while (ConcatOps.size() > 1) {
9267     for (unsigned I = 0, E = ConcatOps.size(); I != E; I += 2) {
9268       SDValue V1 = ConcatOps[I];
9269       SDValue V2 = ConcatOps[I + 1];
9270       ConcatOps[I / 2] = ConcatPair(V1, V2);
9271     }
9272     ConcatOps.resize(ConcatOps.size() / 2);
9273   }
9274   return ConcatOps[0];
9275 }
9276 
LowerCONCAT_VECTORS(SDValue Op,SelectionDAG & DAG,const ARMSubtarget * ST)9277 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG,
9278                                    const ARMSubtarget *ST) {
9279   EVT VT = Op->getValueType(0);
9280   if (ST->hasMVEIntegerOps() && VT.getScalarSizeInBits() == 1)
9281     return LowerCONCAT_VECTORS_i1(Op, DAG, ST);
9282 
9283   // The only time a CONCAT_VECTORS operation can have legal types is when
9284   // two 64-bit vectors are concatenated to a 128-bit vector.
9285   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
9286          "unexpected CONCAT_VECTORS");
9287   SDLoc dl(Op);
9288   SDValue Val = DAG.getUNDEF(MVT::v2f64);
9289   SDValue Op0 = Op.getOperand(0);
9290   SDValue Op1 = Op.getOperand(1);
9291   if (!Op0.isUndef())
9292     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
9293                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
9294                       DAG.getIntPtrConstant(0, dl));
9295   if (!Op1.isUndef())
9296     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
9297                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
9298                       DAG.getIntPtrConstant(1, dl));
9299   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
9300 }
9301 
LowerEXTRACT_SUBVECTOR(SDValue Op,SelectionDAG & DAG,const ARMSubtarget * ST)9302 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG,
9303                                       const ARMSubtarget *ST) {
9304   SDValue V1 = Op.getOperand(0);
9305   SDValue V2 = Op.getOperand(1);
9306   SDLoc dl(Op);
9307   EVT VT = Op.getValueType();
9308   EVT Op1VT = V1.getValueType();
9309   unsigned NumElts = VT.getVectorNumElements();
9310   unsigned Index = V2->getAsZExtVal();
9311 
9312   assert(VT.getScalarSizeInBits() == 1 &&
9313          "Unexpected custom EXTRACT_SUBVECTOR lowering");
9314   assert(ST->hasMVEIntegerOps() &&
9315          "EXTRACT_SUBVECTOR lowering only supported for MVE");
9316 
9317   SDValue NewV1 = PromoteMVEPredVector(dl, V1, Op1VT, DAG);
9318 
9319   // We now have Op1 promoted to a vector of integers, where v8i1 gets
9320   // promoted to v8i16, etc.
9321 
9322   MVT ElType = getVectorTyFromPredicateVector(VT).getScalarType().getSimpleVT();
9323 
9324   if (NumElts == 2) {
9325     EVT SubVT = MVT::v4i32;
9326     SDValue SubVec = DAG.getNode(ISD::UNDEF, dl, SubVT);
9327     for (unsigned i = Index, j = 0; i < (Index + NumElts); i++, j += 2) {
9328       SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, NewV1,
9329                                 DAG.getIntPtrConstant(i, dl));
9330       SubVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, SubVT, SubVec, Elt,
9331                            DAG.getConstant(j, dl, MVT::i32));
9332       SubVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, SubVT, SubVec, Elt,
9333                            DAG.getConstant(j + 1, dl, MVT::i32));
9334     }
9335     SDValue Cmp = DAG.getNode(ARMISD::VCMPZ, dl, MVT::v4i1, SubVec,
9336                               DAG.getConstant(ARMCC::NE, dl, MVT::i32));
9337     return DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::v2i1, Cmp);
9338   }
9339 
9340   EVT SubVT = MVT::getVectorVT(ElType, NumElts);
9341   SDValue SubVec = DAG.getNode(ISD::UNDEF, dl, SubVT);
9342   for (unsigned i = Index, j = 0; i < (Index + NumElts); i++, j++) {
9343     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, NewV1,
9344                               DAG.getIntPtrConstant(i, dl));
9345     SubVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, SubVT, SubVec, Elt,
9346                          DAG.getConstant(j, dl, MVT::i32));
9347   }
9348 
9349   // Now return the result of comparing the subvector with zero,
9350   // which will generate a real predicate, i.e. v4i1, v8i1 or v16i1.
9351   return DAG.getNode(ARMISD::VCMPZ, dl, VT, SubVec,
9352                      DAG.getConstant(ARMCC::NE, dl, MVT::i32));
9353 }
9354 
9355 // Turn a truncate into a predicate (an i1 vector) into icmp(and(x, 1), 0).
LowerTruncatei1(SDNode * N,SelectionDAG & DAG,const ARMSubtarget * ST)9356 static SDValue LowerTruncatei1(SDNode *N, SelectionDAG &DAG,
9357                                const ARMSubtarget *ST) {
9358   assert(ST->hasMVEIntegerOps() && "Expected MVE!");
9359   EVT VT = N->getValueType(0);
9360   assert((VT == MVT::v16i1 || VT == MVT::v8i1 || VT == MVT::v4i1) &&
9361          "Expected a vector i1 type!");
9362   SDValue Op = N->getOperand(0);
9363   EVT FromVT = Op.getValueType();
9364   SDLoc DL(N);
9365 
9366   SDValue And =
9367       DAG.getNode(ISD::AND, DL, FromVT, Op, DAG.getConstant(1, DL, FromVT));
9368   return DAG.getNode(ISD::SETCC, DL, VT, And, DAG.getConstant(0, DL, FromVT),
9369                      DAG.getCondCode(ISD::SETNE));
9370 }
9371 
LowerTruncate(SDNode * N,SelectionDAG & DAG,const ARMSubtarget * Subtarget)9372 static SDValue LowerTruncate(SDNode *N, SelectionDAG &DAG,
9373                              const ARMSubtarget *Subtarget) {
9374   if (!Subtarget->hasMVEIntegerOps())
9375     return SDValue();
9376 
9377   EVT ToVT = N->getValueType(0);
9378   if (ToVT.getScalarType() == MVT::i1)
9379     return LowerTruncatei1(N, DAG, Subtarget);
9380 
9381   // MVE does not have a single instruction to perform the truncation of a v4i32
9382   // into the lower half of a v8i16, in the same way that a NEON vmovn would.
9383   // Most of the instructions in MVE follow the 'Beats' system, where moving
9384   // values from different lanes is usually something that the instructions
9385   // avoid.
9386   //
9387   // Instead it has top/bottom instructions such as VMOVLT/B and VMOVNT/B,
9388   // which take a the top/bottom half of a larger lane and extend it (or do the
9389   // opposite, truncating into the top/bottom lane from a larger lane). Note
9390   // that because of the way we widen lanes, a v4i16 is really a v4i32 using the
9391   // bottom 16bits from each vector lane. This works really well with T/B
9392   // instructions, but that doesn't extend to v8i32->v8i16 where the lanes need
9393   // to move order.
9394   //
9395   // But truncates and sext/zext are always going to be fairly common from llvm.
9396   // We have several options for how to deal with them:
9397   // - Wherever possible combine them into an instruction that makes them
9398   //   "free". This includes loads/stores, which can perform the trunc as part
9399   //   of the memory operation. Or certain shuffles that can be turned into
9400   //   VMOVN/VMOVL.
9401   // - Lane Interleaving to transform blocks surrounded by ext/trunc. So
9402   //   trunc(mul(sext(a), sext(b))) may become
9403   //   VMOVNT(VMUL(VMOVLB(a), VMOVLB(b)), VMUL(VMOVLT(a), VMOVLT(b))). (Which in
9404   //   this case can use VMULL). This is performed in the
9405   //   MVELaneInterleavingPass.
9406   // - Otherwise we have an option. By default we would expand the
9407   //   zext/sext/trunc into a series of lane extract/inserts going via GPR
9408   //   registers. One for each vector lane in the vector. This can obviously be
9409   //   very expensive.
9410   // - The other option is to use the fact that loads/store can extend/truncate
9411   //   to turn a trunc into two truncating stack stores and a stack reload. This
9412   //   becomes 3 back-to-back memory operations, but at least that is less than
9413   //   all the insert/extracts.
9414   //
9415   // In order to do the last, we convert certain trunc's into MVETRUNC, which
9416   // are either optimized where they can be, or eventually lowered into stack
9417   // stores/loads. This prevents us from splitting a v8i16 trunc into two stores
9418   // two early, where other instructions would be better, and stops us from
9419   // having to reconstruct multiple buildvector shuffles into loads/stores.
9420   if (ToVT != MVT::v8i16 && ToVT != MVT::v16i8)
9421     return SDValue();
9422   EVT FromVT = N->getOperand(0).getValueType();
9423   if (FromVT != MVT::v8i32 && FromVT != MVT::v16i16)
9424     return SDValue();
9425 
9426   SDValue Lo, Hi;
9427   std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 0);
9428   SDLoc DL(N);
9429   return DAG.getNode(ARMISD::MVETRUNC, DL, ToVT, Lo, Hi);
9430 }
9431 
LowerVectorExtend(SDNode * N,SelectionDAG & DAG,const ARMSubtarget * Subtarget)9432 static SDValue LowerVectorExtend(SDNode *N, SelectionDAG &DAG,
9433                                  const ARMSubtarget *Subtarget) {
9434   if (!Subtarget->hasMVEIntegerOps())
9435     return SDValue();
9436 
9437   // See LowerTruncate above for an explanation of MVEEXT/MVETRUNC.
9438 
9439   EVT ToVT = N->getValueType(0);
9440   if (ToVT != MVT::v16i32 && ToVT != MVT::v8i32 && ToVT != MVT::v16i16)
9441     return SDValue();
9442   SDValue Op = N->getOperand(0);
9443   EVT FromVT = Op.getValueType();
9444   if (FromVT != MVT::v8i16 && FromVT != MVT::v16i8)
9445     return SDValue();
9446 
9447   SDLoc DL(N);
9448   EVT ExtVT = ToVT.getHalfNumVectorElementsVT(*DAG.getContext());
9449   if (ToVT.getScalarType() == MVT::i32 && FromVT.getScalarType() == MVT::i8)
9450     ExtVT = MVT::v8i16;
9451 
9452   unsigned Opcode =
9453       N->getOpcode() == ISD::SIGN_EXTEND ? ARMISD::MVESEXT : ARMISD::MVEZEXT;
9454   SDValue Ext = DAG.getNode(Opcode, DL, DAG.getVTList(ExtVT, ExtVT), Op);
9455   SDValue Ext1 = Ext.getValue(1);
9456 
9457   if (ToVT.getScalarType() == MVT::i32 && FromVT.getScalarType() == MVT::i8) {
9458     Ext = DAG.getNode(N->getOpcode(), DL, MVT::v8i32, Ext);
9459     Ext1 = DAG.getNode(N->getOpcode(), DL, MVT::v8i32, Ext1);
9460   }
9461 
9462   return DAG.getNode(ISD::CONCAT_VECTORS, DL, ToVT, Ext, Ext1);
9463 }
9464 
9465 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
9466 /// element has been zero/sign-extended, depending on the isSigned parameter,
9467 /// from an integer type half its size.
isExtendedBUILD_VECTOR(SDNode * N,SelectionDAG & DAG,bool isSigned)9468 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
9469                                    bool isSigned) {
9470   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
9471   EVT VT = N->getValueType(0);
9472   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
9473     SDNode *BVN = N->getOperand(0).getNode();
9474     if (BVN->getValueType(0) != MVT::v4i32 ||
9475         BVN->getOpcode() != ISD::BUILD_VECTOR)
9476       return false;
9477     unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
9478     unsigned HiElt = 1 - LoElt;
9479     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
9480     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
9481     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
9482     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
9483     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
9484       return false;
9485     if (isSigned) {
9486       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
9487           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
9488         return true;
9489     } else {
9490       if (Hi0->isZero() && Hi1->isZero())
9491         return true;
9492     }
9493     return false;
9494   }
9495 
9496   if (N->getOpcode() != ISD::BUILD_VECTOR)
9497     return false;
9498 
9499   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
9500     SDNode *Elt = N->getOperand(i).getNode();
9501     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
9502       unsigned EltSize = VT.getScalarSizeInBits();
9503       unsigned HalfSize = EltSize / 2;
9504       if (isSigned) {
9505         if (!isIntN(HalfSize, C->getSExtValue()))
9506           return false;
9507       } else {
9508         if (!isUIntN(HalfSize, C->getZExtValue()))
9509           return false;
9510       }
9511       continue;
9512     }
9513     return false;
9514   }
9515 
9516   return true;
9517 }
9518 
9519 /// isSignExtended - Check if a node is a vector value that is sign-extended
9520 /// or a constant BUILD_VECTOR with sign-extended elements.
isSignExtended(SDNode * N,SelectionDAG & DAG)9521 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
9522   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
9523     return true;
9524   if (isExtendedBUILD_VECTOR(N, DAG, true))
9525     return true;
9526   return false;
9527 }
9528 
9529 /// isZeroExtended - Check if a node is a vector value that is zero-extended (or
9530 /// any-extended) or a constant BUILD_VECTOR with zero-extended elements.
isZeroExtended(SDNode * N,SelectionDAG & DAG)9531 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
9532   if (N->getOpcode() == ISD::ZERO_EXTEND || N->getOpcode() == ISD::ANY_EXTEND ||
9533       ISD::isZEXTLoad(N))
9534     return true;
9535   if (isExtendedBUILD_VECTOR(N, DAG, false))
9536     return true;
9537   return false;
9538 }
9539 
getExtensionTo64Bits(const EVT & OrigVT)9540 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
9541   if (OrigVT.getSizeInBits() >= 64)
9542     return OrigVT;
9543 
9544   assert(OrigVT.isSimple() && "Expecting a simple value type");
9545 
9546   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
9547   switch (OrigSimpleTy) {
9548   default: llvm_unreachable("Unexpected Vector Type");
9549   case MVT::v2i8:
9550   case MVT::v2i16:
9551      return MVT::v2i32;
9552   case MVT::v4i8:
9553     return  MVT::v4i16;
9554   }
9555 }
9556 
9557 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
9558 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
9559 /// We insert the required extension here to get the vector to fill a D register.
AddRequiredExtensionForVMULL(SDValue N,SelectionDAG & DAG,const EVT & OrigTy,const EVT & ExtTy,unsigned ExtOpcode)9560 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
9561                                             const EVT &OrigTy,
9562                                             const EVT &ExtTy,
9563                                             unsigned ExtOpcode) {
9564   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
9565   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
9566   // 64-bits we need to insert a new extension so that it will be 64-bits.
9567   assert(ExtTy.is128BitVector() && "Unexpected extension size");
9568   if (OrigTy.getSizeInBits() >= 64)
9569     return N;
9570 
9571   // Must extend size to at least 64 bits to be used as an operand for VMULL.
9572   EVT NewVT = getExtensionTo64Bits(OrigTy);
9573 
9574   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
9575 }
9576 
9577 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
9578 /// does not do any sign/zero extension. If the original vector is less
9579 /// than 64 bits, an appropriate extension will be added after the load to
9580 /// reach a total size of 64 bits. We have to add the extension separately
9581 /// because ARM does not have a sign/zero extending load for vectors.
SkipLoadExtensionForVMULL(LoadSDNode * LD,SelectionDAG & DAG)9582 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
9583   EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
9584 
9585   // The load already has the right type.
9586   if (ExtendedTy == LD->getMemoryVT())
9587     return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
9588                        LD->getBasePtr(), LD->getPointerInfo(), LD->getAlign(),
9589                        LD->getMemOperand()->getFlags());
9590 
9591   // We need to create a zextload/sextload. We cannot just create a load
9592   // followed by a zext/zext node because LowerMUL is also run during normal
9593   // operation legalization where we can't create illegal types.
9594   return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
9595                         LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
9596                         LD->getMemoryVT(), LD->getAlign(),
9597                         LD->getMemOperand()->getFlags());
9598 }
9599 
9600 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
9601 /// ANY_EXTEND, extending load, or BUILD_VECTOR with extended elements, return
9602 /// the unextended value. The unextended vector should be 64 bits so that it can
9603 /// be used as an operand to a VMULL instruction. If the original vector size
9604 /// before extension is less than 64 bits we add a an extension to resize
9605 /// the vector to 64 bits.
SkipExtensionForVMULL(SDNode * N,SelectionDAG & DAG)9606 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
9607   if (N->getOpcode() == ISD::SIGN_EXTEND ||
9608       N->getOpcode() == ISD::ZERO_EXTEND || N->getOpcode() == ISD::ANY_EXTEND)
9609     return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
9610                                         N->getOperand(0)->getValueType(0),
9611                                         N->getValueType(0),
9612                                         N->getOpcode());
9613 
9614   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9615     assert((ISD::isSEXTLoad(LD) || ISD::isZEXTLoad(LD)) &&
9616            "Expected extending load");
9617 
9618     SDValue newLoad = SkipLoadExtensionForVMULL(LD, DAG);
9619     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), newLoad.getValue(1));
9620     unsigned Opcode = ISD::isSEXTLoad(LD) ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
9621     SDValue extLoad =
9622         DAG.getNode(Opcode, SDLoc(newLoad), LD->getValueType(0), newLoad);
9623     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 0), extLoad);
9624 
9625     return newLoad;
9626   }
9627 
9628   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
9629   // have been legalized as a BITCAST from v4i32.
9630   if (N->getOpcode() == ISD::BITCAST) {
9631     SDNode *BVN = N->getOperand(0).getNode();
9632     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
9633            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
9634     unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
9635     return DAG.getBuildVector(
9636         MVT::v2i32, SDLoc(N),
9637         {BVN->getOperand(LowElt), BVN->getOperand(LowElt + 2)});
9638   }
9639   // Construct a new BUILD_VECTOR with elements truncated to half the size.
9640   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
9641   EVT VT = N->getValueType(0);
9642   unsigned EltSize = VT.getScalarSizeInBits() / 2;
9643   unsigned NumElts = VT.getVectorNumElements();
9644   MVT TruncVT = MVT::getIntegerVT(EltSize);
9645   SmallVector<SDValue, 8> Ops;
9646   SDLoc dl(N);
9647   for (unsigned i = 0; i != NumElts; ++i) {
9648     const APInt &CInt = N->getConstantOperandAPInt(i);
9649     // Element types smaller than 32 bits are not legal, so use i32 elements.
9650     // The values are implicitly truncated so sext vs. zext doesn't matter.
9651     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
9652   }
9653   return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops);
9654 }
9655 
isAddSubSExt(SDNode * N,SelectionDAG & DAG)9656 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
9657   unsigned Opcode = N->getOpcode();
9658   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
9659     SDNode *N0 = N->getOperand(0).getNode();
9660     SDNode *N1 = N->getOperand(1).getNode();
9661     return N0->hasOneUse() && N1->hasOneUse() &&
9662       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
9663   }
9664   return false;
9665 }
9666 
isAddSubZExt(SDNode * N,SelectionDAG & DAG)9667 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
9668   unsigned Opcode = N->getOpcode();
9669   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
9670     SDNode *N0 = N->getOperand(0).getNode();
9671     SDNode *N1 = N->getOperand(1).getNode();
9672     return N0->hasOneUse() && N1->hasOneUse() &&
9673       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
9674   }
9675   return false;
9676 }
9677 
LowerMUL(SDValue Op,SelectionDAG & DAG)9678 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
9679   // Multiplications are only custom-lowered for 128-bit vectors so that
9680   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
9681   EVT VT = Op.getValueType();
9682   assert(VT.is128BitVector() && VT.isInteger() &&
9683          "unexpected type for custom-lowering ISD::MUL");
9684   SDNode *N0 = Op.getOperand(0).getNode();
9685   SDNode *N1 = Op.getOperand(1).getNode();
9686   unsigned NewOpc = 0;
9687   bool isMLA = false;
9688   bool isN0SExt = isSignExtended(N0, DAG);
9689   bool isN1SExt = isSignExtended(N1, DAG);
9690   if (isN0SExt && isN1SExt)
9691     NewOpc = ARMISD::VMULLs;
9692   else {
9693     bool isN0ZExt = isZeroExtended(N0, DAG);
9694     bool isN1ZExt = isZeroExtended(N1, DAG);
9695     if (isN0ZExt && isN1ZExt)
9696       NewOpc = ARMISD::VMULLu;
9697     else if (isN1SExt || isN1ZExt) {
9698       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
9699       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
9700       if (isN1SExt && isAddSubSExt(N0, DAG)) {
9701         NewOpc = ARMISD::VMULLs;
9702         isMLA = true;
9703       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
9704         NewOpc = ARMISD::VMULLu;
9705         isMLA = true;
9706       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
9707         std::swap(N0, N1);
9708         NewOpc = ARMISD::VMULLu;
9709         isMLA = true;
9710       }
9711     }
9712 
9713     if (!NewOpc) {
9714       if (VT == MVT::v2i64)
9715         // Fall through to expand this.  It is not legal.
9716         return SDValue();
9717       else
9718         // Other vector multiplications are legal.
9719         return Op;
9720     }
9721   }
9722 
9723   // Legalize to a VMULL instruction.
9724   SDLoc DL(Op);
9725   SDValue Op0;
9726   SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
9727   if (!isMLA) {
9728     Op0 = SkipExtensionForVMULL(N0, DAG);
9729     assert(Op0.getValueType().is64BitVector() &&
9730            Op1.getValueType().is64BitVector() &&
9731            "unexpected types for extended operands to VMULL");
9732     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
9733   }
9734 
9735   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
9736   // isel lowering to take advantage of no-stall back to back vmul + vmla.
9737   //   vmull q0, d4, d6
9738   //   vmlal q0, d5, d6
9739   // is faster than
9740   //   vaddl q0, d4, d5
9741   //   vmovl q1, d6
9742   //   vmul  q0, q0, q1
9743   SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
9744   SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
9745   EVT Op1VT = Op1.getValueType();
9746   return DAG.getNode(N0->getOpcode(), DL, VT,
9747                      DAG.getNode(NewOpc, DL, VT,
9748                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
9749                      DAG.getNode(NewOpc, DL, VT,
9750                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
9751 }
9752 
LowerSDIV_v4i8(SDValue X,SDValue Y,const SDLoc & dl,SelectionDAG & DAG)9753 static SDValue LowerSDIV_v4i8(SDValue X, SDValue Y, const SDLoc &dl,
9754                               SelectionDAG &DAG) {
9755   // TODO: Should this propagate fast-math-flags?
9756 
9757   // Convert to float
9758   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
9759   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
9760   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
9761   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
9762   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
9763   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
9764   // Get reciprocal estimate.
9765   // float4 recip = vrecpeq_f32(yf);
9766   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
9767                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
9768                    Y);
9769   // Because char has a smaller range than uchar, we can actually get away
9770   // without any newton steps.  This requires that we use a weird bias
9771   // of 0xb000, however (again, this has been exhaustively tested).
9772   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
9773   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
9774   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
9775   Y = DAG.getConstant(0xb000, dl, MVT::v4i32);
9776   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
9777   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
9778   // Convert back to short.
9779   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
9780   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
9781   return X;
9782 }
9783 
LowerSDIV_v4i16(SDValue N0,SDValue N1,const SDLoc & dl,SelectionDAG & DAG)9784 static SDValue LowerSDIV_v4i16(SDValue N0, SDValue N1, const SDLoc &dl,
9785                                SelectionDAG &DAG) {
9786   // TODO: Should this propagate fast-math-flags?
9787 
9788   SDValue N2;
9789   // Convert to float.
9790   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
9791   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
9792   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
9793   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
9794   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
9795   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
9796 
9797   // Use reciprocal estimate and one refinement step.
9798   // float4 recip = vrecpeq_f32(yf);
9799   // recip *= vrecpsq_f32(yf, recip);
9800   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
9801                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
9802                    N1);
9803   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
9804                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
9805                    N1, N2);
9806   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
9807   // Because short has a smaller range than ushort, we can actually get away
9808   // with only a single newton step.  This requires that we use a weird bias
9809   // of 89, however (again, this has been exhaustively tested).
9810   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
9811   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
9812   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
9813   N1 = DAG.getConstant(0x89, dl, MVT::v4i32);
9814   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
9815   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
9816   // Convert back to integer and return.
9817   // return vmovn_s32(vcvt_s32_f32(result));
9818   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
9819   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
9820   return N0;
9821 }
9822 
LowerSDIV(SDValue Op,SelectionDAG & DAG,const ARMSubtarget * ST)9823 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG,
9824                          const ARMSubtarget *ST) {
9825   EVT VT = Op.getValueType();
9826   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
9827          "unexpected type for custom-lowering ISD::SDIV");
9828 
9829   SDLoc dl(Op);
9830   SDValue N0 = Op.getOperand(0);
9831   SDValue N1 = Op.getOperand(1);
9832   SDValue N2, N3;
9833 
9834   if (VT == MVT::v8i8) {
9835     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
9836     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
9837 
9838     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
9839                      DAG.getIntPtrConstant(4, dl));
9840     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
9841                      DAG.getIntPtrConstant(4, dl));
9842     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
9843                      DAG.getIntPtrConstant(0, dl));
9844     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
9845                      DAG.getIntPtrConstant(0, dl));
9846 
9847     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
9848     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
9849 
9850     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
9851     N0 = LowerCONCAT_VECTORS(N0, DAG, ST);
9852 
9853     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
9854     return N0;
9855   }
9856   return LowerSDIV_v4i16(N0, N1, dl, DAG);
9857 }
9858 
LowerUDIV(SDValue Op,SelectionDAG & DAG,const ARMSubtarget * ST)9859 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG,
9860                          const ARMSubtarget *ST) {
9861   // TODO: Should this propagate fast-math-flags?
9862   EVT VT = Op.getValueType();
9863   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
9864          "unexpected type for custom-lowering ISD::UDIV");
9865 
9866   SDLoc dl(Op);
9867   SDValue N0 = Op.getOperand(0);
9868   SDValue N1 = Op.getOperand(1);
9869   SDValue N2, N3;
9870 
9871   if (VT == MVT::v8i8) {
9872     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
9873     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
9874 
9875     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
9876                      DAG.getIntPtrConstant(4, dl));
9877     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
9878                      DAG.getIntPtrConstant(4, dl));
9879     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
9880                      DAG.getIntPtrConstant(0, dl));
9881     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
9882                      DAG.getIntPtrConstant(0, dl));
9883 
9884     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
9885     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
9886 
9887     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
9888     N0 = LowerCONCAT_VECTORS(N0, DAG, ST);
9889 
9890     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
9891                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl,
9892                                      MVT::i32),
9893                      N0);
9894     return N0;
9895   }
9896 
9897   // v4i16 sdiv ... Convert to float.
9898   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
9899   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
9900   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
9901   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
9902   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
9903   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
9904 
9905   // Use reciprocal estimate and two refinement steps.
9906   // float4 recip = vrecpeq_f32(yf);
9907   // recip *= vrecpsq_f32(yf, recip);
9908   // recip *= vrecpsq_f32(yf, recip);
9909   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
9910                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
9911                    BN1);
9912   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
9913                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
9914                    BN1, N2);
9915   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
9916   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
9917                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
9918                    BN1, N2);
9919   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
9920   // Simply multiplying by the reciprocal estimate can leave us a few ulps
9921   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
9922   // and that it will never cause us to return an answer too large).
9923   // float4 result = as_float4(as_int4(xf*recip) + 2);
9924   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
9925   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
9926   N1 = DAG.getConstant(2, dl, MVT::v4i32);
9927   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
9928   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
9929   // Convert back to integer and return.
9930   // return vmovn_u32(vcvt_s32_f32(result));
9931   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
9932   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
9933   return N0;
9934 }
9935 
LowerUADDSUBO_CARRY(SDValue Op,SelectionDAG & DAG)9936 static SDValue LowerUADDSUBO_CARRY(SDValue Op, SelectionDAG &DAG) {
9937   SDNode *N = Op.getNode();
9938   EVT VT = N->getValueType(0);
9939   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
9940 
9941   SDValue Carry = Op.getOperand(2);
9942 
9943   SDLoc DL(Op);
9944 
9945   SDValue Result;
9946   if (Op.getOpcode() == ISD::UADDO_CARRY) {
9947     // This converts the boolean value carry into the carry flag.
9948     Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG);
9949 
9950     // Do the addition proper using the carry flag we wanted.
9951     Result = DAG.getNode(ARMISD::ADDE, DL, VTs, Op.getOperand(0),
9952                          Op.getOperand(1), Carry);
9953 
9954     // Now convert the carry flag into a boolean value.
9955     Carry = ConvertCarryFlagToBooleanCarry(Result.getValue(1), VT, DAG);
9956   } else {
9957     // ARMISD::SUBE expects a carry not a borrow like ISD::USUBO_CARRY so we
9958     // have to invert the carry first.
9959     Carry = DAG.getNode(ISD::SUB, DL, MVT::i32,
9960                         DAG.getConstant(1, DL, MVT::i32), Carry);
9961     // This converts the boolean value carry into the carry flag.
9962     Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG);
9963 
9964     // Do the subtraction proper using the carry flag we wanted.
9965     Result = DAG.getNode(ARMISD::SUBE, DL, VTs, Op.getOperand(0),
9966                          Op.getOperand(1), Carry);
9967 
9968     // Now convert the carry flag into a boolean value.
9969     Carry = ConvertCarryFlagToBooleanCarry(Result.getValue(1), VT, DAG);
9970     // But the carry returned by ARMISD::SUBE is not a borrow as expected
9971     // by ISD::USUBO_CARRY, so compute 1 - C.
9972     Carry = DAG.getNode(ISD::SUB, DL, MVT::i32,
9973                         DAG.getConstant(1, DL, MVT::i32), Carry);
9974   }
9975 
9976   // Return both values.
9977   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Result, Carry);
9978 }
9979 
LowerFSINCOS(SDValue Op,SelectionDAG & DAG) const9980 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
9981   assert(Subtarget->isTargetDarwin());
9982 
9983   // For iOS, we want to call an alternative entry point: __sincos_stret,
9984   // return values are passed via sret.
9985   SDLoc dl(Op);
9986   SDValue Arg = Op.getOperand(0);
9987   EVT ArgVT = Arg.getValueType();
9988   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
9989   auto PtrVT = getPointerTy(DAG.getDataLayout());
9990 
9991   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
9992 
9993   // Pair of floats / doubles used to pass the result.
9994   Type *RetTy = StructType::get(ArgTy, ArgTy);
9995   auto &DL = DAG.getDataLayout();
9996 
9997   ArgListTy Args;
9998   bool ShouldUseSRet = getTM().isAPCS_ABI();
9999   SDValue SRet;
10000   if (ShouldUseSRet) {
10001     // Create stack object for sret.
10002     const uint64_t ByteSize = DL.getTypeAllocSize(RetTy);
10003     const Align StackAlign = DL.getPrefTypeAlign(RetTy);
10004     int FrameIdx = MFI.CreateStackObject(ByteSize, StackAlign, false);
10005     SRet = DAG.getFrameIndex(FrameIdx, getPointerTy(DL));
10006 
10007     ArgListEntry Entry;
10008     Entry.Node = SRet;
10009     Entry.Ty = PointerType::getUnqual(RetTy->getContext());
10010     Entry.IsSExt = false;
10011     Entry.IsZExt = false;
10012     Entry.IsSRet = true;
10013     Args.push_back(Entry);
10014     RetTy = Type::getVoidTy(*DAG.getContext());
10015   }
10016 
10017   ArgListEntry Entry;
10018   Entry.Node = Arg;
10019   Entry.Ty = ArgTy;
10020   Entry.IsSExt = false;
10021   Entry.IsZExt = false;
10022   Args.push_back(Entry);
10023 
10024   RTLIB::Libcall LC =
10025       (ArgVT == MVT::f64) ? RTLIB::SINCOS_STRET_F64 : RTLIB::SINCOS_STRET_F32;
10026   const char *LibcallName = getLibcallName(LC);
10027   CallingConv::ID CC = getLibcallCallingConv(LC);
10028   SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DL));
10029 
10030   TargetLowering::CallLoweringInfo CLI(DAG);
10031   CLI.setDebugLoc(dl)
10032       .setChain(DAG.getEntryNode())
10033       .setCallee(CC, RetTy, Callee, std::move(Args))
10034       .setDiscardResult(ShouldUseSRet);
10035   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
10036 
10037   if (!ShouldUseSRet)
10038     return CallResult.first;
10039 
10040   SDValue LoadSin =
10041       DAG.getLoad(ArgVT, dl, CallResult.second, SRet, MachinePointerInfo());
10042 
10043   // Address of cos field.
10044   SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, SRet,
10045                             DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl));
10046   SDValue LoadCos =
10047       DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add, MachinePointerInfo());
10048 
10049   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
10050   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
10051                      LoadSin.getValue(0), LoadCos.getValue(0));
10052 }
10053 
LowerWindowsDIVLibCall(SDValue Op,SelectionDAG & DAG,bool Signed,SDValue & Chain) const10054 SDValue ARMTargetLowering::LowerWindowsDIVLibCall(SDValue Op, SelectionDAG &DAG,
10055                                                   bool Signed,
10056                                                   SDValue &Chain) const {
10057   EVT VT = Op.getValueType();
10058   assert((VT == MVT::i32 || VT == MVT::i64) &&
10059          "unexpected type for custom lowering DIV");
10060   SDLoc dl(Op);
10061 
10062   const auto &DL = DAG.getDataLayout();
10063   RTLIB::Libcall LC;
10064   if (Signed)
10065     LC = VT == MVT::i32 ? RTLIB::SDIVREM_I32 : RTLIB::SDIVREM_I64;
10066   else
10067     LC = VT == MVT::i32 ? RTLIB::UDIVREM_I32 : RTLIB::UDIVREM_I64;
10068 
10069   const char *Name = getLibcallName(LC);
10070   SDValue ES = DAG.getExternalSymbol(Name, getPointerTy(DL));
10071 
10072   ARMTargetLowering::ArgListTy Args;
10073 
10074   for (auto AI : {1, 0}) {
10075     ArgListEntry Arg;
10076     Arg.Node = Op.getOperand(AI);
10077     Arg.Ty = Arg.Node.getValueType().getTypeForEVT(*DAG.getContext());
10078     Args.push_back(Arg);
10079   }
10080 
10081   CallLoweringInfo CLI(DAG);
10082   CLI.setDebugLoc(dl)
10083     .setChain(Chain)
10084     .setCallee(CallingConv::ARM_AAPCS_VFP, VT.getTypeForEVT(*DAG.getContext()),
10085                ES, std::move(Args));
10086 
10087   return LowerCallTo(CLI).first;
10088 }
10089 
10090 // This is a code size optimisation: return the original SDIV node to
10091 // DAGCombiner when we don't want to expand SDIV into a sequence of
10092 // instructions, and an empty node otherwise which will cause the
10093 // SDIV to be expanded in DAGCombine.
10094 SDValue
BuildSDIVPow2(SDNode * N,const APInt & Divisor,SelectionDAG & DAG,SmallVectorImpl<SDNode * > & Created) const10095 ARMTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
10096                                  SelectionDAG &DAG,
10097                                  SmallVectorImpl<SDNode *> &Created) const {
10098   // TODO: Support SREM
10099   if (N->getOpcode() != ISD::SDIV)
10100     return SDValue();
10101 
10102   const auto &ST = DAG.getSubtarget<ARMSubtarget>();
10103   const bool MinSize = ST.hasMinSize();
10104   const bool HasDivide = ST.isThumb() ? ST.hasDivideInThumbMode()
10105                                       : ST.hasDivideInARMMode();
10106 
10107   // Don't touch vector types; rewriting this may lead to scalarizing
10108   // the int divs.
10109   if (N->getOperand(0).getValueType().isVector())
10110     return SDValue();
10111 
10112   // Bail if MinSize is not set, and also for both ARM and Thumb mode we need
10113   // hwdiv support for this to be really profitable.
10114   if (!(MinSize && HasDivide))
10115     return SDValue();
10116 
10117   // ARM mode is a bit simpler than Thumb: we can handle large power
10118   // of 2 immediates with 1 mov instruction; no further checks required,
10119   // just return the sdiv node.
10120   if (!ST.isThumb())
10121     return SDValue(N, 0);
10122 
10123   // In Thumb mode, immediates larger than 128 need a wide 4-byte MOV,
10124   // and thus lose the code size benefits of a MOVS that requires only 2.
10125   // TargetTransformInfo and 'getIntImmCodeSizeCost' could be helpful here,
10126   // but as it's doing exactly this, it's not worth the trouble to get TTI.
10127   if (Divisor.sgt(128))
10128     return SDValue();
10129 
10130   return SDValue(N, 0);
10131 }
10132 
LowerDIV_Windows(SDValue Op,SelectionDAG & DAG,bool Signed) const10133 SDValue ARMTargetLowering::LowerDIV_Windows(SDValue Op, SelectionDAG &DAG,
10134                                             bool Signed) const {
10135   assert(Op.getValueType() == MVT::i32 &&
10136          "unexpected type for custom lowering DIV");
10137   SDLoc dl(Op);
10138 
10139   SDValue DBZCHK = DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other,
10140                                DAG.getEntryNode(), Op.getOperand(1));
10141 
10142   return LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
10143 }
10144 
WinDBZCheckDenominator(SelectionDAG & DAG,SDNode * N,SDValue InChain)10145 static SDValue WinDBZCheckDenominator(SelectionDAG &DAG, SDNode *N, SDValue InChain) {
10146   SDLoc DL(N);
10147   SDValue Op = N->getOperand(1);
10148   if (N->getValueType(0) == MVT::i32)
10149     return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain, Op);
10150   SDValue Lo, Hi;
10151   std::tie(Lo, Hi) = DAG.SplitScalar(Op, DL, MVT::i32, MVT::i32);
10152   return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain,
10153                      DAG.getNode(ISD::OR, DL, MVT::i32, Lo, Hi));
10154 }
10155 
ExpandDIV_Windows(SDValue Op,SelectionDAG & DAG,bool Signed,SmallVectorImpl<SDValue> & Results) const10156 void ARMTargetLowering::ExpandDIV_Windows(
10157     SDValue Op, SelectionDAG &DAG, bool Signed,
10158     SmallVectorImpl<SDValue> &Results) const {
10159   const auto &DL = DAG.getDataLayout();
10160 
10161   assert(Op.getValueType() == MVT::i64 &&
10162          "unexpected type for custom lowering DIV");
10163   SDLoc dl(Op);
10164 
10165   SDValue DBZCHK = WinDBZCheckDenominator(DAG, Op.getNode(), DAG.getEntryNode());
10166 
10167   SDValue Result = LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
10168 
10169   SDValue Lower = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Result);
10170   SDValue Upper = DAG.getNode(ISD::SRL, dl, MVT::i64, Result,
10171                               DAG.getConstant(32, dl, getPointerTy(DL)));
10172   Upper = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Upper);
10173 
10174   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lower, Upper));
10175 }
10176 
LowerPredicateLoad(SDValue Op,SelectionDAG & DAG)10177 static SDValue LowerPredicateLoad(SDValue Op, SelectionDAG &DAG) {
10178   LoadSDNode *LD = cast<LoadSDNode>(Op.getNode());
10179   EVT MemVT = LD->getMemoryVT();
10180   assert((MemVT == MVT::v2i1 || MemVT == MVT::v4i1 || MemVT == MVT::v8i1 ||
10181           MemVT == MVT::v16i1) &&
10182          "Expected a predicate type!");
10183   assert(MemVT == Op.getValueType());
10184   assert(LD->getExtensionType() == ISD::NON_EXTLOAD &&
10185          "Expected a non-extending load");
10186   assert(LD->isUnindexed() && "Expected a unindexed load");
10187 
10188   // The basic MVE VLDR on a v2i1/v4i1/v8i1 actually loads the entire 16bit
10189   // predicate, with the "v4i1" bits spread out over the 16 bits loaded. We
10190   // need to make sure that 8/4/2 bits are actually loaded into the correct
10191   // place, which means loading the value and then shuffling the values into
10192   // the bottom bits of the predicate.
10193   // Equally, VLDR for an v16i1 will actually load 32bits (so will be incorrect
10194   // for BE).
10195   // Speaking of BE, apparently the rest of llvm will assume a reverse order to
10196   // a natural VMSR(load), so needs to be reversed.
10197 
10198   SDLoc dl(Op);
10199   SDValue Load = DAG.getExtLoad(
10200       ISD::EXTLOAD, dl, MVT::i32, LD->getChain(), LD->getBasePtr(),
10201       EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits()),
10202       LD->getMemOperand());
10203   SDValue Val = Load;
10204   if (DAG.getDataLayout().isBigEndian())
10205     Val = DAG.getNode(ISD::SRL, dl, MVT::i32,
10206                       DAG.getNode(ISD::BITREVERSE, dl, MVT::i32, Load),
10207                       DAG.getConstant(32 - MemVT.getSizeInBits(), dl, MVT::i32));
10208   SDValue Pred = DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::v16i1, Val);
10209   if (MemVT != MVT::v16i1)
10210     Pred = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MemVT, Pred,
10211                        DAG.getConstant(0, dl, MVT::i32));
10212   return DAG.getMergeValues({Pred, Load.getValue(1)}, dl);
10213 }
10214 
LowerLOAD(SDNode * N,SmallVectorImpl<SDValue> & Results,SelectionDAG & DAG) const10215 void ARMTargetLowering::LowerLOAD(SDNode *N, SmallVectorImpl<SDValue> &Results,
10216                                   SelectionDAG &DAG) const {
10217   LoadSDNode *LD = cast<LoadSDNode>(N);
10218   EVT MemVT = LD->getMemoryVT();
10219   assert(LD->isUnindexed() && "Loads should be unindexed at this point.");
10220 
10221   if (MemVT == MVT::i64 && Subtarget->hasV5TEOps() &&
10222       !Subtarget->isThumb1Only() && LD->isVolatile() &&
10223       LD->getAlign() >= Subtarget->getDualLoadStoreAlignment()) {
10224     SDLoc dl(N);
10225     SDValue Result = DAG.getMemIntrinsicNode(
10226         ARMISD::LDRD, dl, DAG.getVTList({MVT::i32, MVT::i32, MVT::Other}),
10227         {LD->getChain(), LD->getBasePtr()}, MemVT, LD->getMemOperand());
10228     SDValue Lo = Result.getValue(DAG.getDataLayout().isLittleEndian() ? 0 : 1);
10229     SDValue Hi = Result.getValue(DAG.getDataLayout().isLittleEndian() ? 1 : 0);
10230     SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
10231     Results.append({Pair, Result.getValue(2)});
10232   }
10233 }
10234 
LowerPredicateStore(SDValue Op,SelectionDAG & DAG)10235 static SDValue LowerPredicateStore(SDValue Op, SelectionDAG &DAG) {
10236   StoreSDNode *ST = cast<StoreSDNode>(Op.getNode());
10237   EVT MemVT = ST->getMemoryVT();
10238   assert((MemVT == MVT::v2i1 || MemVT == MVT::v4i1 || MemVT == MVT::v8i1 ||
10239           MemVT == MVT::v16i1) &&
10240          "Expected a predicate type!");
10241   assert(MemVT == ST->getValue().getValueType());
10242   assert(!ST->isTruncatingStore() && "Expected a non-extending store");
10243   assert(ST->isUnindexed() && "Expected a unindexed store");
10244 
10245   // Only store the v2i1 or v4i1 or v8i1 worth of bits, via a buildvector with
10246   // top bits unset and a scalar store.
10247   SDLoc dl(Op);
10248   SDValue Build = ST->getValue();
10249   if (MemVT != MVT::v16i1) {
10250     SmallVector<SDValue, 16> Ops;
10251     for (unsigned I = 0; I < MemVT.getVectorNumElements(); I++) {
10252       unsigned Elt = DAG.getDataLayout().isBigEndian()
10253                          ? MemVT.getVectorNumElements() - I - 1
10254                          : I;
10255       Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, Build,
10256                                 DAG.getConstant(Elt, dl, MVT::i32)));
10257     }
10258     for (unsigned I = MemVT.getVectorNumElements(); I < 16; I++)
10259       Ops.push_back(DAG.getUNDEF(MVT::i32));
10260     Build = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i1, Ops);
10261   }
10262   SDValue GRP = DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, Build);
10263   if (MemVT == MVT::v16i1 && DAG.getDataLayout().isBigEndian())
10264     GRP = DAG.getNode(ISD::SRL, dl, MVT::i32,
10265                       DAG.getNode(ISD::BITREVERSE, dl, MVT::i32, GRP),
10266                       DAG.getConstant(16, dl, MVT::i32));
10267   return DAG.getTruncStore(
10268       ST->getChain(), dl, GRP, ST->getBasePtr(),
10269       EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits()),
10270       ST->getMemOperand());
10271 }
10272 
LowerSTORE(SDValue Op,SelectionDAG & DAG,const ARMSubtarget * Subtarget)10273 static SDValue LowerSTORE(SDValue Op, SelectionDAG &DAG,
10274                           const ARMSubtarget *Subtarget) {
10275   StoreSDNode *ST = cast<StoreSDNode>(Op.getNode());
10276   EVT MemVT = ST->getMemoryVT();
10277   assert(ST->isUnindexed() && "Stores should be unindexed at this point.");
10278 
10279   if (MemVT == MVT::i64 && Subtarget->hasV5TEOps() &&
10280       !Subtarget->isThumb1Only() && ST->isVolatile() &&
10281       ST->getAlign() >= Subtarget->getDualLoadStoreAlignment()) {
10282     SDNode *N = Op.getNode();
10283     SDLoc dl(N);
10284 
10285     SDValue Lo = DAG.getNode(
10286         ISD::EXTRACT_ELEMENT, dl, MVT::i32, ST->getValue(),
10287         DAG.getTargetConstant(DAG.getDataLayout().isLittleEndian() ? 0 : 1, dl,
10288                               MVT::i32));
10289     SDValue Hi = DAG.getNode(
10290         ISD::EXTRACT_ELEMENT, dl, MVT::i32, ST->getValue(),
10291         DAG.getTargetConstant(DAG.getDataLayout().isLittleEndian() ? 1 : 0, dl,
10292                               MVT::i32));
10293 
10294     return DAG.getMemIntrinsicNode(ARMISD::STRD, dl, DAG.getVTList(MVT::Other),
10295                                    {ST->getChain(), Lo, Hi, ST->getBasePtr()},
10296                                    MemVT, ST->getMemOperand());
10297   } else if (Subtarget->hasMVEIntegerOps() &&
10298              ((MemVT == MVT::v2i1 || MemVT == MVT::v4i1 || MemVT == MVT::v8i1 ||
10299                MemVT == MVT::v16i1))) {
10300     return LowerPredicateStore(Op, DAG);
10301   }
10302 
10303   return SDValue();
10304 }
10305 
isZeroVector(SDValue N)10306 static bool isZeroVector(SDValue N) {
10307   return (ISD::isBuildVectorAllZeros(N.getNode()) ||
10308           (N->getOpcode() == ARMISD::VMOVIMM &&
10309            isNullConstant(N->getOperand(0))));
10310 }
10311 
LowerMLOAD(SDValue Op,SelectionDAG & DAG)10312 static SDValue LowerMLOAD(SDValue Op, SelectionDAG &DAG) {
10313   MaskedLoadSDNode *N = cast<MaskedLoadSDNode>(Op.getNode());
10314   MVT VT = Op.getSimpleValueType();
10315   SDValue Mask = N->getMask();
10316   SDValue PassThru = N->getPassThru();
10317   SDLoc dl(Op);
10318 
10319   if (isZeroVector(PassThru))
10320     return Op;
10321 
10322   // MVE Masked loads use zero as the passthru value. Here we convert undef to
10323   // zero too, and other values are lowered to a select.
10324   SDValue ZeroVec = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
10325                                 DAG.getTargetConstant(0, dl, MVT::i32));
10326   SDValue NewLoad = DAG.getMaskedLoad(
10327       VT, dl, N->getChain(), N->getBasePtr(), N->getOffset(), Mask, ZeroVec,
10328       N->getMemoryVT(), N->getMemOperand(), N->getAddressingMode(),
10329       N->getExtensionType(), N->isExpandingLoad());
10330   SDValue Combo = NewLoad;
10331   bool PassThruIsCastZero = (PassThru.getOpcode() == ISD::BITCAST ||
10332                              PassThru.getOpcode() == ARMISD::VECTOR_REG_CAST) &&
10333                             isZeroVector(PassThru->getOperand(0));
10334   if (!PassThru.isUndef() && !PassThruIsCastZero)
10335     Combo = DAG.getNode(ISD::VSELECT, dl, VT, Mask, NewLoad, PassThru);
10336   return DAG.getMergeValues({Combo, NewLoad.getValue(1)}, dl);
10337 }
10338 
LowerVecReduce(SDValue Op,SelectionDAG & DAG,const ARMSubtarget * ST)10339 static SDValue LowerVecReduce(SDValue Op, SelectionDAG &DAG,
10340                               const ARMSubtarget *ST) {
10341   if (!ST->hasMVEIntegerOps())
10342     return SDValue();
10343 
10344   SDLoc dl(Op);
10345   unsigned BaseOpcode = 0;
10346   switch (Op->getOpcode()) {
10347   default: llvm_unreachable("Expected VECREDUCE opcode");
10348   case ISD::VECREDUCE_FADD: BaseOpcode = ISD::FADD; break;
10349   case ISD::VECREDUCE_FMUL: BaseOpcode = ISD::FMUL; break;
10350   case ISD::VECREDUCE_MUL:  BaseOpcode = ISD::MUL; break;
10351   case ISD::VECREDUCE_AND:  BaseOpcode = ISD::AND; break;
10352   case ISD::VECREDUCE_OR:   BaseOpcode = ISD::OR; break;
10353   case ISD::VECREDUCE_XOR:  BaseOpcode = ISD::XOR; break;
10354   case ISD::VECREDUCE_FMAX: BaseOpcode = ISD::FMAXNUM; break;
10355   case ISD::VECREDUCE_FMIN: BaseOpcode = ISD::FMINNUM; break;
10356   }
10357 
10358   SDValue Op0 = Op->getOperand(0);
10359   EVT VT = Op0.getValueType();
10360   EVT EltVT = VT.getVectorElementType();
10361   unsigned NumElts = VT.getVectorNumElements();
10362   unsigned NumActiveLanes = NumElts;
10363 
10364   assert((NumActiveLanes == 16 || NumActiveLanes == 8 || NumActiveLanes == 4 ||
10365           NumActiveLanes == 2) &&
10366          "Only expected a power 2 vector size");
10367 
10368   // Use Mul(X, Rev(X)) until 4 items remain. Going down to 4 vector elements
10369   // allows us to easily extract vector elements from the lanes.
10370   while (NumActiveLanes > 4) {
10371     unsigned RevOpcode = NumActiveLanes == 16 ? ARMISD::VREV16 : ARMISD::VREV32;
10372     SDValue Rev = DAG.getNode(RevOpcode, dl, VT, Op0);
10373     Op0 = DAG.getNode(BaseOpcode, dl, VT, Op0, Rev);
10374     NumActiveLanes /= 2;
10375   }
10376 
10377   SDValue Res;
10378   if (NumActiveLanes == 4) {
10379     // The remaining 4 elements are summed sequentially
10380     SDValue Ext0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op0,
10381                               DAG.getConstant(0 * NumElts / 4, dl, MVT::i32));
10382     SDValue Ext1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op0,
10383                               DAG.getConstant(1 * NumElts / 4, dl, MVT::i32));
10384     SDValue Ext2 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op0,
10385                               DAG.getConstant(2 * NumElts / 4, dl, MVT::i32));
10386     SDValue Ext3 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op0,
10387                               DAG.getConstant(3 * NumElts / 4, dl, MVT::i32));
10388     SDValue Res0 = DAG.getNode(BaseOpcode, dl, EltVT, Ext0, Ext1, Op->getFlags());
10389     SDValue Res1 = DAG.getNode(BaseOpcode, dl, EltVT, Ext2, Ext3, Op->getFlags());
10390     Res = DAG.getNode(BaseOpcode, dl, EltVT, Res0, Res1, Op->getFlags());
10391   } else {
10392     SDValue Ext0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op0,
10393                               DAG.getConstant(0, dl, MVT::i32));
10394     SDValue Ext1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op0,
10395                               DAG.getConstant(1, dl, MVT::i32));
10396     Res = DAG.getNode(BaseOpcode, dl, EltVT, Ext0, Ext1, Op->getFlags());
10397   }
10398 
10399   // Result type may be wider than element type.
10400   if (EltVT != Op->getValueType(0))
10401     Res = DAG.getNode(ISD::ANY_EXTEND, dl, Op->getValueType(0), Res);
10402   return Res;
10403 }
10404 
LowerVecReduceF(SDValue Op,SelectionDAG & DAG,const ARMSubtarget * ST)10405 static SDValue LowerVecReduceF(SDValue Op, SelectionDAG &DAG,
10406                                const ARMSubtarget *ST) {
10407   if (!ST->hasMVEFloatOps())
10408     return SDValue();
10409   return LowerVecReduce(Op, DAG, ST);
10410 }
10411 
LowerVecReduceMinMax(SDValue Op,SelectionDAG & DAG,const ARMSubtarget * ST)10412 static SDValue LowerVecReduceMinMax(SDValue Op, SelectionDAG &DAG,
10413                                     const ARMSubtarget *ST) {
10414   if (!ST->hasNEON())
10415     return SDValue();
10416 
10417   SDLoc dl(Op);
10418   SDValue Op0 = Op->getOperand(0);
10419   EVT VT = Op0.getValueType();
10420   EVT EltVT = VT.getVectorElementType();
10421 
10422   unsigned PairwiseIntrinsic = 0;
10423   switch (Op->getOpcode()) {
10424   default:
10425     llvm_unreachable("Expected VECREDUCE opcode");
10426   case ISD::VECREDUCE_UMIN:
10427     PairwiseIntrinsic = Intrinsic::arm_neon_vpminu;
10428     break;
10429   case ISD::VECREDUCE_UMAX:
10430     PairwiseIntrinsic = Intrinsic::arm_neon_vpmaxu;
10431     break;
10432   case ISD::VECREDUCE_SMIN:
10433     PairwiseIntrinsic = Intrinsic::arm_neon_vpmins;
10434     break;
10435   case ISD::VECREDUCE_SMAX:
10436     PairwiseIntrinsic = Intrinsic::arm_neon_vpmaxs;
10437     break;
10438   }
10439   SDValue PairwiseOp = DAG.getConstant(PairwiseIntrinsic, dl, MVT::i32);
10440 
10441   unsigned NumElts = VT.getVectorNumElements();
10442   unsigned NumActiveLanes = NumElts;
10443 
10444   assert((NumActiveLanes == 16 || NumActiveLanes == 8 || NumActiveLanes == 4 ||
10445           NumActiveLanes == 2) &&
10446          "Only expected a power 2 vector size");
10447 
10448   // Split 128-bit vectors, since vpmin/max takes 2 64-bit vectors.
10449   if (VT.is128BitVector()) {
10450     SDValue Lo, Hi;
10451     std::tie(Lo, Hi) = DAG.SplitVector(Op0, dl);
10452     VT = Lo.getValueType();
10453     Op0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, {PairwiseOp, Lo, Hi});
10454     NumActiveLanes /= 2;
10455   }
10456 
10457   // Use pairwise reductions until one lane remains
10458   while (NumActiveLanes > 1) {
10459     Op0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, {PairwiseOp, Op0, Op0});
10460     NumActiveLanes /= 2;
10461   }
10462 
10463   SDValue Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op0,
10464                             DAG.getConstant(0, dl, MVT::i32));
10465 
10466   // Result type may be wider than element type.
10467   if (EltVT != Op.getValueType()) {
10468     unsigned Extend = 0;
10469     switch (Op->getOpcode()) {
10470     default:
10471       llvm_unreachable("Expected VECREDUCE opcode");
10472     case ISD::VECREDUCE_UMIN:
10473     case ISD::VECREDUCE_UMAX:
10474       Extend = ISD::ZERO_EXTEND;
10475       break;
10476     case ISD::VECREDUCE_SMIN:
10477     case ISD::VECREDUCE_SMAX:
10478       Extend = ISD::SIGN_EXTEND;
10479       break;
10480     }
10481     Res = DAG.getNode(Extend, dl, Op.getValueType(), Res);
10482   }
10483   return Res;
10484 }
10485 
LowerAtomicLoadStore(SDValue Op,SelectionDAG & DAG)10486 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
10487   if (isStrongerThanMonotonic(cast<AtomicSDNode>(Op)->getSuccessOrdering()))
10488     // Acquire/Release load/store is not legal for targets without a dmb or
10489     // equivalent available.
10490     return SDValue();
10491 
10492   // Monotonic load/store is legal for all targets.
10493   return Op;
10494 }
10495 
ReplaceREADCYCLECOUNTER(SDNode * N,SmallVectorImpl<SDValue> & Results,SelectionDAG & DAG,const ARMSubtarget * Subtarget)10496 static void ReplaceREADCYCLECOUNTER(SDNode *N,
10497                                     SmallVectorImpl<SDValue> &Results,
10498                                     SelectionDAG &DAG,
10499                                     const ARMSubtarget *Subtarget) {
10500   SDLoc DL(N);
10501   // Under Power Management extensions, the cycle-count is:
10502   //    mrc p15, #0, <Rt>, c9, c13, #0
10503   SDValue Ops[] = { N->getOperand(0), // Chain
10504                     DAG.getTargetConstant(Intrinsic::arm_mrc, DL, MVT::i32),
10505                     DAG.getTargetConstant(15, DL, MVT::i32),
10506                     DAG.getTargetConstant(0, DL, MVT::i32),
10507                     DAG.getTargetConstant(9, DL, MVT::i32),
10508                     DAG.getTargetConstant(13, DL, MVT::i32),
10509                     DAG.getTargetConstant(0, DL, MVT::i32)
10510   };
10511 
10512   SDValue Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
10513                                  DAG.getVTList(MVT::i32, MVT::Other), Ops);
10514   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Cycles32,
10515                                 DAG.getConstant(0, DL, MVT::i32)));
10516   Results.push_back(Cycles32.getValue(1));
10517 }
10518 
createGPRPairNode2xi32(SelectionDAG & DAG,SDValue V0,SDValue V1)10519 static SDValue createGPRPairNode2xi32(SelectionDAG &DAG, SDValue V0,
10520                                       SDValue V1) {
10521   SDLoc dl(V0.getNode());
10522   SDValue RegClass =
10523       DAG.getTargetConstant(ARM::GPRPairRegClassID, dl, MVT::i32);
10524   SDValue SubReg0 = DAG.getTargetConstant(ARM::gsub_0, dl, MVT::i32);
10525   SDValue SubReg1 = DAG.getTargetConstant(ARM::gsub_1, dl, MVT::i32);
10526   const SDValue Ops[] = {RegClass, V0, SubReg0, V1, SubReg1};
10527   return SDValue(
10528       DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0);
10529 }
10530 
createGPRPairNodei64(SelectionDAG & DAG,SDValue V)10531 static SDValue createGPRPairNodei64(SelectionDAG &DAG, SDValue V) {
10532   SDLoc dl(V.getNode());
10533   auto [VLo, VHi] = DAG.SplitScalar(V, dl, MVT::i32, MVT::i32);
10534   bool isBigEndian = DAG.getDataLayout().isBigEndian();
10535   if (isBigEndian)
10536     std::swap(VLo, VHi);
10537   return createGPRPairNode2xi32(DAG, VLo, VHi);
10538 }
10539 
ReplaceCMP_SWAP_64Results(SDNode * N,SmallVectorImpl<SDValue> & Results,SelectionDAG & DAG)10540 static void ReplaceCMP_SWAP_64Results(SDNode *N,
10541                                       SmallVectorImpl<SDValue> &Results,
10542                                       SelectionDAG &DAG) {
10543   assert(N->getValueType(0) == MVT::i64 &&
10544          "AtomicCmpSwap on types less than 64 should be legal");
10545   SDValue Ops[] = {
10546       createGPRPairNode2xi32(DAG, N->getOperand(1),
10547                              DAG.getUNDEF(MVT::i32)), // pointer, temp
10548       createGPRPairNodei64(DAG, N->getOperand(2)),    // expected
10549       createGPRPairNodei64(DAG, N->getOperand(3)),    // new
10550       N->getOperand(0),                               // chain in
10551   };
10552   SDNode *CmpSwap = DAG.getMachineNode(
10553       ARM::CMP_SWAP_64, SDLoc(N),
10554       DAG.getVTList(MVT::Untyped, MVT::Untyped, MVT::Other), Ops);
10555 
10556   MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand();
10557   DAG.setNodeMemRefs(cast<MachineSDNode>(CmpSwap), {MemOp});
10558 
10559   bool isBigEndian = DAG.getDataLayout().isBigEndian();
10560 
10561   SDValue Lo =
10562       DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_1 : ARM::gsub_0,
10563                                  SDLoc(N), MVT::i32, SDValue(CmpSwap, 0));
10564   SDValue Hi =
10565       DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_0 : ARM::gsub_1,
10566                                  SDLoc(N), MVT::i32, SDValue(CmpSwap, 0));
10567   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, SDLoc(N), MVT::i64, Lo, Hi));
10568   Results.push_back(SDValue(CmpSwap, 2));
10569 }
10570 
LowerFSETCC(SDValue Op,SelectionDAG & DAG) const10571 SDValue ARMTargetLowering::LowerFSETCC(SDValue Op, SelectionDAG &DAG) const {
10572   SDLoc dl(Op);
10573   EVT VT = Op.getValueType();
10574   SDValue Chain = Op.getOperand(0);
10575   SDValue LHS = Op.getOperand(1);
10576   SDValue RHS = Op.getOperand(2);
10577   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(3))->get();
10578   bool IsSignaling = Op.getOpcode() == ISD::STRICT_FSETCCS;
10579 
10580   // If we don't have instructions of this float type then soften to a libcall
10581   // and use SETCC instead.
10582   if (isUnsupportedFloatingType(LHS.getValueType())) {
10583     softenSetCCOperands(DAG, LHS.getValueType(), LHS, RHS, CC, dl, LHS, RHS,
10584                         Chain, IsSignaling);
10585     if (!RHS.getNode()) {
10586       RHS = DAG.getConstant(0, dl, LHS.getValueType());
10587       CC = ISD::SETNE;
10588     }
10589     SDValue Result = DAG.getNode(ISD::SETCC, dl, VT, LHS, RHS,
10590                                  DAG.getCondCode(CC));
10591     return DAG.getMergeValues({Result, Chain}, dl);
10592   }
10593 
10594   ARMCC::CondCodes CondCode, CondCode2;
10595   FPCCToARMCC(CC, CondCode, CondCode2);
10596 
10597   SDValue True = DAG.getConstant(1, dl, VT);
10598   SDValue False =  DAG.getConstant(0, dl, VT);
10599   SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
10600   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl, IsSignaling);
10601   SDValue Result = getCMOV(dl, VT, False, True, ARMcc, Cmp, DAG);
10602   if (CondCode2 != ARMCC::AL) {
10603     ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32);
10604     Result = getCMOV(dl, VT, Result, True, ARMcc, Cmp, DAG);
10605   }
10606   return DAG.getMergeValues({Result, Chain}, dl);
10607 }
10608 
LowerSPONENTRY(SDValue Op,SelectionDAG & DAG) const10609 SDValue ARMTargetLowering::LowerSPONENTRY(SDValue Op, SelectionDAG &DAG) const {
10610   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
10611 
10612   EVT VT = getPointerTy(DAG.getDataLayout());
10613   int FI = MFI.CreateFixedObject(4, 0, false);
10614   return DAG.getFrameIndex(FI, VT);
10615 }
10616 
LowerFP_TO_BF16(SDValue Op,SelectionDAG & DAG) const10617 SDValue ARMTargetLowering::LowerFP_TO_BF16(SDValue Op,
10618                                            SelectionDAG &DAG) const {
10619   SDLoc DL(Op);
10620   MakeLibCallOptions CallOptions;
10621   MVT SVT = Op.getOperand(0).getSimpleValueType();
10622   RTLIB::Libcall LC = RTLIB::getFPROUND(SVT, MVT::bf16);
10623   SDValue Res =
10624       makeLibCall(DAG, LC, MVT::f32, Op.getOperand(0), CallOptions, DL).first;
10625   return DAG.getBitcast(MVT::i32, Res);
10626 }
10627 
LowerOperation(SDValue Op,SelectionDAG & DAG) const10628 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
10629   LLVM_DEBUG(dbgs() << "Lowering node: "; Op.dump());
10630   switch (Op.getOpcode()) {
10631   default: llvm_unreachable("Don't know how to custom lower this!");
10632   case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG);
10633   case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
10634   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
10635   case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
10636   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
10637   case ISD::SELECT:        return LowerSELECT(Op, DAG);
10638   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
10639   case ISD::BRCOND:        return LowerBRCOND(Op, DAG);
10640   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
10641   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
10642   case ISD::VASTART:       return LowerVASTART(Op, DAG);
10643   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
10644   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
10645   case ISD::SINT_TO_FP:
10646   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
10647   case ISD::STRICT_FP_TO_SINT:
10648   case ISD::STRICT_FP_TO_UINT:
10649   case ISD::FP_TO_SINT:
10650   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
10651   case ISD::FP_TO_SINT_SAT:
10652   case ISD::FP_TO_UINT_SAT: return LowerFP_TO_INT_SAT(Op, DAG, Subtarget);
10653   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
10654   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
10655   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
10656   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
10657   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
10658   case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG);
10659   case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG, Subtarget);
10660   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
10661                                                                Subtarget);
10662   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG, Subtarget);
10663   case ISD::SHL:
10664   case ISD::SRL:
10665   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
10666   case ISD::SREM:          return LowerREM(Op.getNode(), DAG);
10667   case ISD::UREM:          return LowerREM(Op.getNode(), DAG);
10668   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
10669   case ISD::SRL_PARTS:
10670   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
10671   case ISD::CTTZ:
10672   case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
10673   case ISD::CTPOP:         return LowerCTPOP(Op.getNode(), DAG, Subtarget);
10674   case ISD::SETCC:         return LowerVSETCC(Op, DAG, Subtarget);
10675   case ISD::SETCCCARRY:    return LowerSETCCCARRY(Op, DAG);
10676   case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
10677   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
10678   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG, Subtarget);
10679   case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op, DAG, Subtarget);
10680   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
10681   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG, Subtarget);
10682   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG, Subtarget);
10683   case ISD::TRUNCATE:      return LowerTruncate(Op.getNode(), DAG, Subtarget);
10684   case ISD::SIGN_EXTEND:
10685   case ISD::ZERO_EXTEND:   return LowerVectorExtend(Op.getNode(), DAG, Subtarget);
10686   case ISD::GET_ROUNDING:  return LowerGET_ROUNDING(Op, DAG);
10687   case ISD::SET_ROUNDING:  return LowerSET_ROUNDING(Op, DAG);
10688   case ISD::SET_FPMODE:
10689     return LowerSET_FPMODE(Op, DAG);
10690   case ISD::RESET_FPMODE:
10691     return LowerRESET_FPMODE(Op, DAG);
10692   case ISD::MUL:           return LowerMUL(Op, DAG);
10693   case ISD::SDIV:
10694     if (Subtarget->isTargetWindows() && !Op.getValueType().isVector())
10695       return LowerDIV_Windows(Op, DAG, /* Signed */ true);
10696     return LowerSDIV(Op, DAG, Subtarget);
10697   case ISD::UDIV:
10698     if (Subtarget->isTargetWindows() && !Op.getValueType().isVector())
10699       return LowerDIV_Windows(Op, DAG, /* Signed */ false);
10700     return LowerUDIV(Op, DAG, Subtarget);
10701   case ISD::UADDO_CARRY:
10702   case ISD::USUBO_CARRY:
10703     return LowerUADDSUBO_CARRY(Op, DAG);
10704   case ISD::SADDO:
10705   case ISD::SSUBO:
10706     return LowerSignedALUO(Op, DAG);
10707   case ISD::UADDO:
10708   case ISD::USUBO:
10709     return LowerUnsignedALUO(Op, DAG);
10710   case ISD::SADDSAT:
10711   case ISD::SSUBSAT:
10712   case ISD::UADDSAT:
10713   case ISD::USUBSAT:
10714     return LowerADDSUBSAT(Op, DAG, Subtarget);
10715   case ISD::LOAD:
10716     return LowerPredicateLoad(Op, DAG);
10717   case ISD::STORE:
10718     return LowerSTORE(Op, DAG, Subtarget);
10719   case ISD::MLOAD:
10720     return LowerMLOAD(Op, DAG);
10721   case ISD::VECREDUCE_MUL:
10722   case ISD::VECREDUCE_AND:
10723   case ISD::VECREDUCE_OR:
10724   case ISD::VECREDUCE_XOR:
10725     return LowerVecReduce(Op, DAG, Subtarget);
10726   case ISD::VECREDUCE_FADD:
10727   case ISD::VECREDUCE_FMUL:
10728   case ISD::VECREDUCE_FMIN:
10729   case ISD::VECREDUCE_FMAX:
10730     return LowerVecReduceF(Op, DAG, Subtarget);
10731   case ISD::VECREDUCE_UMIN:
10732   case ISD::VECREDUCE_UMAX:
10733   case ISD::VECREDUCE_SMIN:
10734   case ISD::VECREDUCE_SMAX:
10735     return LowerVecReduceMinMax(Op, DAG, Subtarget);
10736   case ISD::ATOMIC_LOAD:
10737   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
10738   case ISD::FSINCOS:       return LowerFSINCOS(Op, DAG);
10739   case ISD::SDIVREM:
10740   case ISD::UDIVREM:       return LowerDivRem(Op, DAG);
10741   case ISD::DYNAMIC_STACKALLOC:
10742     if (Subtarget->isTargetWindows())
10743       return LowerDYNAMIC_STACKALLOC(Op, DAG);
10744     llvm_unreachable("Don't know how to custom lower this!");
10745   case ISD::STRICT_FP_ROUND:
10746   case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
10747   case ISD::STRICT_FP_EXTEND:
10748   case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
10749   case ISD::STRICT_FSETCC:
10750   case ISD::STRICT_FSETCCS: return LowerFSETCC(Op, DAG);
10751   case ISD::SPONENTRY:
10752     return LowerSPONENTRY(Op, DAG);
10753   case ISD::FP_TO_BF16:
10754     return LowerFP_TO_BF16(Op, DAG);
10755   case ARMISD::WIN__DBZCHK: return SDValue();
10756   }
10757 }
10758 
ReplaceLongIntrinsic(SDNode * N,SmallVectorImpl<SDValue> & Results,SelectionDAG & DAG)10759 static void ReplaceLongIntrinsic(SDNode *N, SmallVectorImpl<SDValue> &Results,
10760                                  SelectionDAG &DAG) {
10761   unsigned IntNo = N->getConstantOperandVal(0);
10762   unsigned Opc = 0;
10763   if (IntNo == Intrinsic::arm_smlald)
10764     Opc = ARMISD::SMLALD;
10765   else if (IntNo == Intrinsic::arm_smlaldx)
10766     Opc = ARMISD::SMLALDX;
10767   else if (IntNo == Intrinsic::arm_smlsld)
10768     Opc = ARMISD::SMLSLD;
10769   else if (IntNo == Intrinsic::arm_smlsldx)
10770     Opc = ARMISD::SMLSLDX;
10771   else
10772     return;
10773 
10774   SDLoc dl(N);
10775   SDValue Lo, Hi;
10776   std::tie(Lo, Hi) = DAG.SplitScalar(N->getOperand(3), dl, MVT::i32, MVT::i32);
10777 
10778   SDValue LongMul = DAG.getNode(Opc, dl,
10779                                 DAG.getVTList(MVT::i32, MVT::i32),
10780                                 N->getOperand(1), N->getOperand(2),
10781                                 Lo, Hi);
10782   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64,
10783                                 LongMul.getValue(0), LongMul.getValue(1)));
10784 }
10785 
10786 /// ReplaceNodeResults - Replace the results of node with an illegal result
10787 /// type with new values built out of custom code.
ReplaceNodeResults(SDNode * N,SmallVectorImpl<SDValue> & Results,SelectionDAG & DAG) const10788 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
10789                                            SmallVectorImpl<SDValue> &Results,
10790                                            SelectionDAG &DAG) const {
10791   SDValue Res;
10792   switch (N->getOpcode()) {
10793   default:
10794     llvm_unreachable("Don't know how to custom expand this!");
10795   case ISD::READ_REGISTER:
10796     ExpandREAD_REGISTER(N, Results, DAG);
10797     break;
10798   case ISD::BITCAST:
10799     Res = ExpandBITCAST(N, DAG, Subtarget);
10800     break;
10801   case ISD::SRL:
10802   case ISD::SRA:
10803   case ISD::SHL:
10804     Res = Expand64BitShift(N, DAG, Subtarget);
10805     break;
10806   case ISD::SREM:
10807   case ISD::UREM:
10808     Res = LowerREM(N, DAG);
10809     break;
10810   case ISD::SDIVREM:
10811   case ISD::UDIVREM:
10812     Res = LowerDivRem(SDValue(N, 0), DAG);
10813     assert(Res.getNumOperands() == 2 && "DivRem needs two values");
10814     Results.push_back(Res.getValue(0));
10815     Results.push_back(Res.getValue(1));
10816     return;
10817   case ISD::SADDSAT:
10818   case ISD::SSUBSAT:
10819   case ISD::UADDSAT:
10820   case ISD::USUBSAT:
10821     Res = LowerADDSUBSAT(SDValue(N, 0), DAG, Subtarget);
10822     break;
10823   case ISD::READCYCLECOUNTER:
10824     ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
10825     return;
10826   case ISD::UDIV:
10827   case ISD::SDIV:
10828     assert(Subtarget->isTargetWindows() && "can only expand DIV on Windows");
10829     return ExpandDIV_Windows(SDValue(N, 0), DAG, N->getOpcode() == ISD::SDIV,
10830                              Results);
10831   case ISD::ATOMIC_CMP_SWAP:
10832     ReplaceCMP_SWAP_64Results(N, Results, DAG);
10833     return;
10834   case ISD::INTRINSIC_WO_CHAIN:
10835     return ReplaceLongIntrinsic(N, Results, DAG);
10836   case ISD::LOAD:
10837     LowerLOAD(N, Results, DAG);
10838     break;
10839   case ISD::TRUNCATE:
10840     Res = LowerTruncate(N, DAG, Subtarget);
10841     break;
10842   case ISD::SIGN_EXTEND:
10843   case ISD::ZERO_EXTEND:
10844     Res = LowerVectorExtend(N, DAG, Subtarget);
10845     break;
10846   case ISD::FP_TO_SINT_SAT:
10847   case ISD::FP_TO_UINT_SAT:
10848     Res = LowerFP_TO_INT_SAT(SDValue(N, 0), DAG, Subtarget);
10849     break;
10850   }
10851   if (Res.getNode())
10852     Results.push_back(Res);
10853 }
10854 
10855 //===----------------------------------------------------------------------===//
10856 //                           ARM Scheduler Hooks
10857 //===----------------------------------------------------------------------===//
10858 
10859 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
10860 /// registers the function context.
SetupEntryBlockForSjLj(MachineInstr & MI,MachineBasicBlock * MBB,MachineBasicBlock * DispatchBB,int FI) const10861 void ARMTargetLowering::SetupEntryBlockForSjLj(MachineInstr &MI,
10862                                                MachineBasicBlock *MBB,
10863                                                MachineBasicBlock *DispatchBB,
10864                                                int FI) const {
10865   assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
10866          "ROPI/RWPI not currently supported with SjLj");
10867   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
10868   DebugLoc dl = MI.getDebugLoc();
10869   MachineFunction *MF = MBB->getParent();
10870   MachineRegisterInfo *MRI = &MF->getRegInfo();
10871   MachineConstantPool *MCP = MF->getConstantPool();
10872   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
10873   const Function &F = MF->getFunction();
10874 
10875   bool isThumb = Subtarget->isThumb();
10876   bool isThumb2 = Subtarget->isThumb2();
10877 
10878   unsigned PCLabelId = AFI->createPICLabelUId();
10879   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
10880   ARMConstantPoolValue *CPV =
10881     ARMConstantPoolMBB::Create(F.getContext(), DispatchBB, PCLabelId, PCAdj);
10882   unsigned CPI = MCP->getConstantPoolIndex(CPV, Align(4));
10883 
10884   const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass
10885                                            : &ARM::GPRRegClass;
10886 
10887   // Grab constant pool and fixed stack memory operands.
10888   MachineMemOperand *CPMMO =
10889       MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF),
10890                                MachineMemOperand::MOLoad, 4, Align(4));
10891 
10892   MachineMemOperand *FIMMOSt =
10893       MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI),
10894                                MachineMemOperand::MOStore, 4, Align(4));
10895 
10896   // Load the address of the dispatch MBB into the jump buffer.
10897   if (isThumb2) {
10898     // Incoming value: jbuf
10899     //   ldr.n  r5, LCPI1_1
10900     //   orr    r5, r5, #1
10901     //   add    r5, pc
10902     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
10903     Register NewVReg1 = MRI->createVirtualRegister(TRC);
10904     BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
10905         .addConstantPoolIndex(CPI)
10906         .addMemOperand(CPMMO)
10907         .add(predOps(ARMCC::AL));
10908     // Set the low bit because of thumb mode.
10909     Register NewVReg2 = MRI->createVirtualRegister(TRC);
10910     BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
10911         .addReg(NewVReg1, RegState::Kill)
10912         .addImm(0x01)
10913         .add(predOps(ARMCC::AL))
10914         .add(condCodeOp());
10915     Register NewVReg3 = MRI->createVirtualRegister(TRC);
10916     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
10917       .addReg(NewVReg2, RegState::Kill)
10918       .addImm(PCLabelId);
10919     BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
10920         .addReg(NewVReg3, RegState::Kill)
10921         .addFrameIndex(FI)
10922         .addImm(36) // &jbuf[1] :: pc
10923         .addMemOperand(FIMMOSt)
10924         .add(predOps(ARMCC::AL));
10925   } else if (isThumb) {
10926     // Incoming value: jbuf
10927     //   ldr.n  r1, LCPI1_4
10928     //   add    r1, pc
10929     //   mov    r2, #1
10930     //   orrs   r1, r2
10931     //   add    r2, $jbuf, #+4 ; &jbuf[1]
10932     //   str    r1, [r2]
10933     Register NewVReg1 = MRI->createVirtualRegister(TRC);
10934     BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
10935         .addConstantPoolIndex(CPI)
10936         .addMemOperand(CPMMO)
10937         .add(predOps(ARMCC::AL));
10938     Register NewVReg2 = MRI->createVirtualRegister(TRC);
10939     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
10940       .addReg(NewVReg1, RegState::Kill)
10941       .addImm(PCLabelId);
10942     // Set the low bit because of thumb mode.
10943     Register NewVReg3 = MRI->createVirtualRegister(TRC);
10944     BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
10945         .addReg(ARM::CPSR, RegState::Define)
10946         .addImm(1)
10947         .add(predOps(ARMCC::AL));
10948     Register NewVReg4 = MRI->createVirtualRegister(TRC);
10949     BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
10950         .addReg(ARM::CPSR, RegState::Define)
10951         .addReg(NewVReg2, RegState::Kill)
10952         .addReg(NewVReg3, RegState::Kill)
10953         .add(predOps(ARMCC::AL));
10954     Register NewVReg5 = MRI->createVirtualRegister(TRC);
10955     BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5)
10956             .addFrameIndex(FI)
10957             .addImm(36); // &jbuf[1] :: pc
10958     BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
10959         .addReg(NewVReg4, RegState::Kill)
10960         .addReg(NewVReg5, RegState::Kill)
10961         .addImm(0)
10962         .addMemOperand(FIMMOSt)
10963         .add(predOps(ARMCC::AL));
10964   } else {
10965     // Incoming value: jbuf
10966     //   ldr  r1, LCPI1_1
10967     //   add  r1, pc, r1
10968     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
10969     Register NewVReg1 = MRI->createVirtualRegister(TRC);
10970     BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1)
10971         .addConstantPoolIndex(CPI)
10972         .addImm(0)
10973         .addMemOperand(CPMMO)
10974         .add(predOps(ARMCC::AL));
10975     Register NewVReg2 = MRI->createVirtualRegister(TRC);
10976     BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
10977         .addReg(NewVReg1, RegState::Kill)
10978         .addImm(PCLabelId)
10979         .add(predOps(ARMCC::AL));
10980     BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
10981         .addReg(NewVReg2, RegState::Kill)
10982         .addFrameIndex(FI)
10983         .addImm(36) // &jbuf[1] :: pc
10984         .addMemOperand(FIMMOSt)
10985         .add(predOps(ARMCC::AL));
10986   }
10987 }
10988 
EmitSjLjDispatchBlock(MachineInstr & MI,MachineBasicBlock * MBB) const10989 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr &MI,
10990                                               MachineBasicBlock *MBB) const {
10991   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
10992   DebugLoc dl = MI.getDebugLoc();
10993   MachineFunction *MF = MBB->getParent();
10994   MachineRegisterInfo *MRI = &MF->getRegInfo();
10995   MachineFrameInfo &MFI = MF->getFrameInfo();
10996   int FI = MFI.getFunctionContextIndex();
10997 
10998   const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass
10999                                                         : &ARM::GPRnopcRegClass;
11000 
11001   // Get a mapping of the call site numbers to all of the landing pads they're
11002   // associated with.
11003   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2>> CallSiteNumToLPad;
11004   unsigned MaxCSNum = 0;
11005   for (MachineBasicBlock &BB : *MF) {
11006     if (!BB.isEHPad())
11007       continue;
11008 
11009     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
11010     // pad.
11011     for (MachineInstr &II : BB) {
11012       if (!II.isEHLabel())
11013         continue;
11014 
11015       MCSymbol *Sym = II.getOperand(0).getMCSymbol();
11016       if (!MF->hasCallSiteLandingPad(Sym)) continue;
11017 
11018       SmallVectorImpl<unsigned> &CallSiteIdxs = MF->getCallSiteLandingPad(Sym);
11019       for (unsigned Idx : CallSiteIdxs) {
11020         CallSiteNumToLPad[Idx].push_back(&BB);
11021         MaxCSNum = std::max(MaxCSNum, Idx);
11022       }
11023       break;
11024     }
11025   }
11026 
11027   // Get an ordered list of the machine basic blocks for the jump table.
11028   std::vector<MachineBasicBlock*> LPadList;
11029   SmallPtrSet<MachineBasicBlock*, 32> InvokeBBs;
11030   LPadList.reserve(CallSiteNumToLPad.size());
11031   for (unsigned I = 1; I <= MaxCSNum; ++I) {
11032     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
11033     for (MachineBasicBlock *MBB : MBBList) {
11034       LPadList.push_back(MBB);
11035       InvokeBBs.insert_range(MBB->predecessors());
11036     }
11037   }
11038 
11039   assert(!LPadList.empty() &&
11040          "No landing pad destinations for the dispatch jump table!");
11041 
11042   // Create the jump table and associated information.
11043   MachineJumpTableInfo *JTI =
11044     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
11045   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
11046 
11047   // Create the MBBs for the dispatch code.
11048 
11049   // Shove the dispatch's address into the return slot in the function context.
11050   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
11051   DispatchBB->setIsEHPad();
11052 
11053   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
11054   unsigned trap_opcode;
11055   if (Subtarget->isThumb())
11056     trap_opcode = ARM::tTRAP;
11057   else
11058     trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
11059 
11060   BuildMI(TrapBB, dl, TII->get(trap_opcode));
11061   DispatchBB->addSuccessor(TrapBB);
11062 
11063   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
11064   DispatchBB->addSuccessor(DispContBB);
11065 
11066   // Insert and MBBs.
11067   MF->insert(MF->end(), DispatchBB);
11068   MF->insert(MF->end(), DispContBB);
11069   MF->insert(MF->end(), TrapBB);
11070 
11071   // Insert code into the entry block that creates and registers the function
11072   // context.
11073   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
11074 
11075   MachineMemOperand *FIMMOLd = MF->getMachineMemOperand(
11076       MachinePointerInfo::getFixedStack(*MF, FI),
11077       MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile, 4, Align(4));
11078 
11079   MachineInstrBuilder MIB;
11080   MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
11081 
11082   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
11083   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
11084 
11085   // Add a register mask with no preserved registers.  This results in all
11086   // registers being marked as clobbered. This can't work if the dispatch block
11087   // is in a Thumb1 function and is linked with ARM code which uses the FP
11088   // registers, as there is no way to preserve the FP registers in Thumb1 mode.
11089   MIB.addRegMask(RI.getSjLjDispatchPreservedMask(*MF));
11090 
11091   bool IsPositionIndependent = isPositionIndependent();
11092   unsigned NumLPads = LPadList.size();
11093   if (Subtarget->isThumb2()) {
11094     Register NewVReg1 = MRI->createVirtualRegister(TRC);
11095     BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
11096         .addFrameIndex(FI)
11097         .addImm(4)
11098         .addMemOperand(FIMMOLd)
11099         .add(predOps(ARMCC::AL));
11100 
11101     if (NumLPads < 256) {
11102       BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
11103           .addReg(NewVReg1)
11104           .addImm(LPadList.size())
11105           .add(predOps(ARMCC::AL));
11106     } else {
11107       Register VReg1 = MRI->createVirtualRegister(TRC);
11108       BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
11109           .addImm(NumLPads & 0xFFFF)
11110           .add(predOps(ARMCC::AL));
11111 
11112       unsigned VReg2 = VReg1;
11113       if ((NumLPads & 0xFFFF0000) != 0) {
11114         VReg2 = MRI->createVirtualRegister(TRC);
11115         BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
11116             .addReg(VReg1)
11117             .addImm(NumLPads >> 16)
11118             .add(predOps(ARMCC::AL));
11119       }
11120 
11121       BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
11122           .addReg(NewVReg1)
11123           .addReg(VReg2)
11124           .add(predOps(ARMCC::AL));
11125     }
11126 
11127     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
11128       .addMBB(TrapBB)
11129       .addImm(ARMCC::HI)
11130       .addReg(ARM::CPSR);
11131 
11132     Register NewVReg3 = MRI->createVirtualRegister(TRC);
11133     BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT), NewVReg3)
11134         .addJumpTableIndex(MJTI)
11135         .add(predOps(ARMCC::AL));
11136 
11137     Register NewVReg4 = MRI->createVirtualRegister(TRC);
11138     BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
11139         .addReg(NewVReg3, RegState::Kill)
11140         .addReg(NewVReg1)
11141         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))
11142         .add(predOps(ARMCC::AL))
11143         .add(condCodeOp());
11144 
11145     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
11146       .addReg(NewVReg4, RegState::Kill)
11147       .addReg(NewVReg1)
11148       .addJumpTableIndex(MJTI);
11149   } else if (Subtarget->isThumb()) {
11150     Register NewVReg1 = MRI->createVirtualRegister(TRC);
11151     BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
11152         .addFrameIndex(FI)
11153         .addImm(1)
11154         .addMemOperand(FIMMOLd)
11155         .add(predOps(ARMCC::AL));
11156 
11157     if (NumLPads < 256) {
11158       BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
11159           .addReg(NewVReg1)
11160           .addImm(NumLPads)
11161           .add(predOps(ARMCC::AL));
11162     } else {
11163       MachineConstantPool *ConstantPool = MF->getConstantPool();
11164       Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext());
11165       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
11166 
11167       // MachineConstantPool wants an explicit alignment.
11168       Align Alignment = MF->getDataLayout().getPrefTypeAlign(Int32Ty);
11169       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Alignment);
11170 
11171       Register VReg1 = MRI->createVirtualRegister(TRC);
11172       BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
11173           .addReg(VReg1, RegState::Define)
11174           .addConstantPoolIndex(Idx)
11175           .add(predOps(ARMCC::AL));
11176       BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
11177           .addReg(NewVReg1)
11178           .addReg(VReg1)
11179           .add(predOps(ARMCC::AL));
11180     }
11181 
11182     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
11183       .addMBB(TrapBB)
11184       .addImm(ARMCC::HI)
11185       .addReg(ARM::CPSR);
11186 
11187     Register NewVReg2 = MRI->createVirtualRegister(TRC);
11188     BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
11189         .addReg(ARM::CPSR, RegState::Define)
11190         .addReg(NewVReg1)
11191         .addImm(2)
11192         .add(predOps(ARMCC::AL));
11193 
11194     Register NewVReg3 = MRI->createVirtualRegister(TRC);
11195     BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
11196         .addJumpTableIndex(MJTI)
11197         .add(predOps(ARMCC::AL));
11198 
11199     Register NewVReg4 = MRI->createVirtualRegister(TRC);
11200     BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
11201         .addReg(ARM::CPSR, RegState::Define)
11202         .addReg(NewVReg2, RegState::Kill)
11203         .addReg(NewVReg3)
11204         .add(predOps(ARMCC::AL));
11205 
11206     MachineMemOperand *JTMMOLd =
11207         MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(*MF),
11208                                  MachineMemOperand::MOLoad, 4, Align(4));
11209 
11210     Register NewVReg5 = MRI->createVirtualRegister(TRC);
11211     BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
11212         .addReg(NewVReg4, RegState::Kill)
11213         .addImm(0)
11214         .addMemOperand(JTMMOLd)
11215         .add(predOps(ARMCC::AL));
11216 
11217     unsigned NewVReg6 = NewVReg5;
11218     if (IsPositionIndependent) {
11219       NewVReg6 = MRI->createVirtualRegister(TRC);
11220       BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
11221           .addReg(ARM::CPSR, RegState::Define)
11222           .addReg(NewVReg5, RegState::Kill)
11223           .addReg(NewVReg3)
11224           .add(predOps(ARMCC::AL));
11225     }
11226 
11227     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
11228       .addReg(NewVReg6, RegState::Kill)
11229       .addJumpTableIndex(MJTI);
11230   } else {
11231     Register NewVReg1 = MRI->createVirtualRegister(TRC);
11232     BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
11233         .addFrameIndex(FI)
11234         .addImm(4)
11235         .addMemOperand(FIMMOLd)
11236         .add(predOps(ARMCC::AL));
11237 
11238     if (NumLPads < 256) {
11239       BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
11240           .addReg(NewVReg1)
11241           .addImm(NumLPads)
11242           .add(predOps(ARMCC::AL));
11243     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
11244       Register VReg1 = MRI->createVirtualRegister(TRC);
11245       BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
11246           .addImm(NumLPads & 0xFFFF)
11247           .add(predOps(ARMCC::AL));
11248 
11249       unsigned VReg2 = VReg1;
11250       if ((NumLPads & 0xFFFF0000) != 0) {
11251         VReg2 = MRI->createVirtualRegister(TRC);
11252         BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
11253             .addReg(VReg1)
11254             .addImm(NumLPads >> 16)
11255             .add(predOps(ARMCC::AL));
11256       }
11257 
11258       BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
11259           .addReg(NewVReg1)
11260           .addReg(VReg2)
11261           .add(predOps(ARMCC::AL));
11262     } else {
11263       MachineConstantPool *ConstantPool = MF->getConstantPool();
11264       Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext());
11265       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
11266 
11267       // MachineConstantPool wants an explicit alignment.
11268       Align Alignment = MF->getDataLayout().getPrefTypeAlign(Int32Ty);
11269       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Alignment);
11270 
11271       Register VReg1 = MRI->createVirtualRegister(TRC);
11272       BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
11273           .addReg(VReg1, RegState::Define)
11274           .addConstantPoolIndex(Idx)
11275           .addImm(0)
11276           .add(predOps(ARMCC::AL));
11277       BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
11278           .addReg(NewVReg1)
11279           .addReg(VReg1, RegState::Kill)
11280           .add(predOps(ARMCC::AL));
11281     }
11282 
11283     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
11284       .addMBB(TrapBB)
11285       .addImm(ARMCC::HI)
11286       .addReg(ARM::CPSR);
11287 
11288     Register NewVReg3 = MRI->createVirtualRegister(TRC);
11289     BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
11290         .addReg(NewVReg1)
11291         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))
11292         .add(predOps(ARMCC::AL))
11293         .add(condCodeOp());
11294     Register NewVReg4 = MRI->createVirtualRegister(TRC);
11295     BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
11296         .addJumpTableIndex(MJTI)
11297         .add(predOps(ARMCC::AL));
11298 
11299     MachineMemOperand *JTMMOLd =
11300         MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(*MF),
11301                                  MachineMemOperand::MOLoad, 4, Align(4));
11302     Register NewVReg5 = MRI->createVirtualRegister(TRC);
11303     BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
11304         .addReg(NewVReg3, RegState::Kill)
11305         .addReg(NewVReg4)
11306         .addImm(0)
11307         .addMemOperand(JTMMOLd)
11308         .add(predOps(ARMCC::AL));
11309 
11310     if (IsPositionIndependent) {
11311       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
11312         .addReg(NewVReg5, RegState::Kill)
11313         .addReg(NewVReg4)
11314         .addJumpTableIndex(MJTI);
11315     } else {
11316       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
11317         .addReg(NewVReg5, RegState::Kill)
11318         .addJumpTableIndex(MJTI);
11319     }
11320   }
11321 
11322   // Add the jump table entries as successors to the MBB.
11323   SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
11324   for (MachineBasicBlock *CurMBB : LPadList) {
11325     if (SeenMBBs.insert(CurMBB).second)
11326       DispContBB->addSuccessor(CurMBB);
11327   }
11328 
11329   // N.B. the order the invoke BBs are processed in doesn't matter here.
11330   const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
11331   SmallVector<MachineBasicBlock*, 64> MBBLPads;
11332   for (MachineBasicBlock *BB : InvokeBBs) {
11333 
11334     // Remove the landing pad successor from the invoke block and replace it
11335     // with the new dispatch block.
11336     SmallVector<MachineBasicBlock*, 4> Successors(BB->successors());
11337     while (!Successors.empty()) {
11338       MachineBasicBlock *SMBB = Successors.pop_back_val();
11339       if (SMBB->isEHPad()) {
11340         BB->removeSuccessor(SMBB);
11341         MBBLPads.push_back(SMBB);
11342       }
11343     }
11344 
11345     BB->addSuccessor(DispatchBB, BranchProbability::getZero());
11346     BB->normalizeSuccProbs();
11347 
11348     // Find the invoke call and mark all of the callee-saved registers as
11349     // 'implicit defined' so that they're spilled. This prevents code from
11350     // moving instructions to before the EH block, where they will never be
11351     // executed.
11352     for (MachineBasicBlock::reverse_iterator
11353            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
11354       if (!II->isCall()) continue;
11355 
11356       DenseSet<unsigned> DefRegs;
11357       for (MachineInstr::mop_iterator
11358              OI = II->operands_begin(), OE = II->operands_end();
11359            OI != OE; ++OI) {
11360         if (!OI->isReg()) continue;
11361         DefRegs.insert(OI->getReg());
11362       }
11363 
11364       MachineInstrBuilder MIB(*MF, &*II);
11365 
11366       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
11367         unsigned Reg = SavedRegs[i];
11368         if (Subtarget->isThumb2() &&
11369             !ARM::tGPRRegClass.contains(Reg) &&
11370             !ARM::hGPRRegClass.contains(Reg))
11371           continue;
11372         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
11373           continue;
11374         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
11375           continue;
11376         if (!DefRegs.contains(Reg))
11377           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
11378       }
11379 
11380       break;
11381     }
11382   }
11383 
11384   // Mark all former landing pads as non-landing pads. The dispatch is the only
11385   // landing pad now.
11386   for (MachineBasicBlock *MBBLPad : MBBLPads)
11387     MBBLPad->setIsEHPad(false);
11388 
11389   // The instruction is gone now.
11390   MI.eraseFromParent();
11391 }
11392 
11393 static
OtherSucc(MachineBasicBlock * MBB,MachineBasicBlock * Succ)11394 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
11395   for (MachineBasicBlock *S : MBB->successors())
11396     if (S != Succ)
11397       return S;
11398   llvm_unreachable("Expecting a BB with two successors!");
11399 }
11400 
11401 /// Return the load opcode for a given load size. If load size >= 8,
11402 /// neon opcode will be returned.
getLdOpcode(unsigned LdSize,bool IsThumb1,bool IsThumb2)11403 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
11404   if (LdSize >= 8)
11405     return LdSize == 16 ? ARM::VLD1q32wb_fixed
11406                         : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
11407   if (IsThumb1)
11408     return LdSize == 4 ? ARM::tLDRi
11409                        : LdSize == 2 ? ARM::tLDRHi
11410                                      : LdSize == 1 ? ARM::tLDRBi : 0;
11411   if (IsThumb2)
11412     return LdSize == 4 ? ARM::t2LDR_POST
11413                        : LdSize == 2 ? ARM::t2LDRH_POST
11414                                      : LdSize == 1 ? ARM::t2LDRB_POST : 0;
11415   return LdSize == 4 ? ARM::LDR_POST_IMM
11416                      : LdSize == 2 ? ARM::LDRH_POST
11417                                    : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
11418 }
11419 
11420 /// Return the store opcode for a given store size. If store size >= 8,
11421 /// neon opcode will be returned.
getStOpcode(unsigned StSize,bool IsThumb1,bool IsThumb2)11422 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
11423   if (StSize >= 8)
11424     return StSize == 16 ? ARM::VST1q32wb_fixed
11425                         : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
11426   if (IsThumb1)
11427     return StSize == 4 ? ARM::tSTRi
11428                        : StSize == 2 ? ARM::tSTRHi
11429                                      : StSize == 1 ? ARM::tSTRBi : 0;
11430   if (IsThumb2)
11431     return StSize == 4 ? ARM::t2STR_POST
11432                        : StSize == 2 ? ARM::t2STRH_POST
11433                                      : StSize == 1 ? ARM::t2STRB_POST : 0;
11434   return StSize == 4 ? ARM::STR_POST_IMM
11435                      : StSize == 2 ? ARM::STRH_POST
11436                                    : StSize == 1 ? ARM::STRB_POST_IMM : 0;
11437 }
11438 
11439 /// Emit a post-increment load operation with given size. The instructions
11440 /// will be added to BB at Pos.
emitPostLd(MachineBasicBlock * BB,MachineBasicBlock::iterator Pos,const TargetInstrInfo * TII,const DebugLoc & dl,unsigned LdSize,unsigned Data,unsigned AddrIn,unsigned AddrOut,bool IsThumb1,bool IsThumb2)11441 static void emitPostLd(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos,
11442                        const TargetInstrInfo *TII, const DebugLoc &dl,
11443                        unsigned LdSize, unsigned Data, unsigned AddrIn,
11444                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
11445   unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
11446   assert(LdOpc != 0 && "Should have a load opcode");
11447   if (LdSize >= 8) {
11448     BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
11449         .addReg(AddrOut, RegState::Define)
11450         .addReg(AddrIn)
11451         .addImm(0)
11452         .add(predOps(ARMCC::AL));
11453   } else if (IsThumb1) {
11454     // load + update AddrIn
11455     BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
11456         .addReg(AddrIn)
11457         .addImm(0)
11458         .add(predOps(ARMCC::AL));
11459     BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut)
11460         .add(t1CondCodeOp())
11461         .addReg(AddrIn)
11462         .addImm(LdSize)
11463         .add(predOps(ARMCC::AL));
11464   } else if (IsThumb2) {
11465     BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
11466         .addReg(AddrOut, RegState::Define)
11467         .addReg(AddrIn)
11468         .addImm(LdSize)
11469         .add(predOps(ARMCC::AL));
11470   } else { // arm
11471     BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
11472         .addReg(AddrOut, RegState::Define)
11473         .addReg(AddrIn)
11474         .addReg(0)
11475         .addImm(LdSize)
11476         .add(predOps(ARMCC::AL));
11477   }
11478 }
11479 
11480 /// Emit a post-increment store operation with given size. The instructions
11481 /// will be added to BB at Pos.
emitPostSt(MachineBasicBlock * BB,MachineBasicBlock::iterator Pos,const TargetInstrInfo * TII,const DebugLoc & dl,unsigned StSize,unsigned Data,unsigned AddrIn,unsigned AddrOut,bool IsThumb1,bool IsThumb2)11482 static void emitPostSt(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos,
11483                        const TargetInstrInfo *TII, const DebugLoc &dl,
11484                        unsigned StSize, unsigned Data, unsigned AddrIn,
11485                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
11486   unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
11487   assert(StOpc != 0 && "Should have a store opcode");
11488   if (StSize >= 8) {
11489     BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
11490         .addReg(AddrIn)
11491         .addImm(0)
11492         .addReg(Data)
11493         .add(predOps(ARMCC::AL));
11494   } else if (IsThumb1) {
11495     // store + update AddrIn
11496     BuildMI(*BB, Pos, dl, TII->get(StOpc))
11497         .addReg(Data)
11498         .addReg(AddrIn)
11499         .addImm(0)
11500         .add(predOps(ARMCC::AL));
11501     BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut)
11502         .add(t1CondCodeOp())
11503         .addReg(AddrIn)
11504         .addImm(StSize)
11505         .add(predOps(ARMCC::AL));
11506   } else if (IsThumb2) {
11507     BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
11508         .addReg(Data)
11509         .addReg(AddrIn)
11510         .addImm(StSize)
11511         .add(predOps(ARMCC::AL));
11512   } else { // arm
11513     BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
11514         .addReg(Data)
11515         .addReg(AddrIn)
11516         .addReg(0)
11517         .addImm(StSize)
11518         .add(predOps(ARMCC::AL));
11519   }
11520 }
11521 
11522 MachineBasicBlock *
EmitStructByval(MachineInstr & MI,MachineBasicBlock * BB) const11523 ARMTargetLowering::EmitStructByval(MachineInstr &MI,
11524                                    MachineBasicBlock *BB) const {
11525   // This pseudo instruction has 3 operands: dst, src, size
11526   // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
11527   // Otherwise, we will generate unrolled scalar copies.
11528   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
11529   const BasicBlock *LLVM_BB = BB->getBasicBlock();
11530   MachineFunction::iterator It = ++BB->getIterator();
11531 
11532   Register dest = MI.getOperand(0).getReg();
11533   Register src = MI.getOperand(1).getReg();
11534   unsigned SizeVal = MI.getOperand(2).getImm();
11535   unsigned Alignment = MI.getOperand(3).getImm();
11536   DebugLoc dl = MI.getDebugLoc();
11537 
11538   MachineFunction *MF = BB->getParent();
11539   MachineRegisterInfo &MRI = MF->getRegInfo();
11540   unsigned UnitSize = 0;
11541   const TargetRegisterClass *TRC = nullptr;
11542   const TargetRegisterClass *VecTRC = nullptr;
11543 
11544   bool IsThumb1 = Subtarget->isThumb1Only();
11545   bool IsThumb2 = Subtarget->isThumb2();
11546   bool IsThumb = Subtarget->isThumb();
11547 
11548   if (Alignment & 1) {
11549     UnitSize = 1;
11550   } else if (Alignment & 2) {
11551     UnitSize = 2;
11552   } else {
11553     // Check whether we can use NEON instructions.
11554     if (!MF->getFunction().hasFnAttribute(Attribute::NoImplicitFloat) &&
11555         Subtarget->hasNEON()) {
11556       if ((Alignment % 16 == 0) && SizeVal >= 16)
11557         UnitSize = 16;
11558       else if ((Alignment % 8 == 0) && SizeVal >= 8)
11559         UnitSize = 8;
11560     }
11561     // Can't use NEON instructions.
11562     if (UnitSize == 0)
11563       UnitSize = 4;
11564   }
11565 
11566   // Select the correct opcode and register class for unit size load/store
11567   bool IsNeon = UnitSize >= 8;
11568   TRC = IsThumb ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
11569   if (IsNeon)
11570     VecTRC = UnitSize == 16 ? &ARM::DPairRegClass
11571                             : UnitSize == 8 ? &ARM::DPRRegClass
11572                                             : nullptr;
11573 
11574   unsigned BytesLeft = SizeVal % UnitSize;
11575   unsigned LoopSize = SizeVal - BytesLeft;
11576 
11577   if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
11578     // Use LDR and STR to copy.
11579     // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
11580     // [destOut] = STR_POST(scratch, destIn, UnitSize)
11581     unsigned srcIn = src;
11582     unsigned destIn = dest;
11583     for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
11584       Register srcOut = MRI.createVirtualRegister(TRC);
11585       Register destOut = MRI.createVirtualRegister(TRC);
11586       Register scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
11587       emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
11588                  IsThumb1, IsThumb2);
11589       emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
11590                  IsThumb1, IsThumb2);
11591       srcIn = srcOut;
11592       destIn = destOut;
11593     }
11594 
11595     // Handle the leftover bytes with LDRB and STRB.
11596     // [scratch, srcOut] = LDRB_POST(srcIn, 1)
11597     // [destOut] = STRB_POST(scratch, destIn, 1)
11598     for (unsigned i = 0; i < BytesLeft; i++) {
11599       Register srcOut = MRI.createVirtualRegister(TRC);
11600       Register destOut = MRI.createVirtualRegister(TRC);
11601       Register scratch = MRI.createVirtualRegister(TRC);
11602       emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
11603                  IsThumb1, IsThumb2);
11604       emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
11605                  IsThumb1, IsThumb2);
11606       srcIn = srcOut;
11607       destIn = destOut;
11608     }
11609     MI.eraseFromParent(); // The instruction is gone now.
11610     return BB;
11611   }
11612 
11613   // Expand the pseudo op to a loop.
11614   // thisMBB:
11615   //   ...
11616   //   movw varEnd, # --> with thumb2
11617   //   movt varEnd, #
11618   //   ldrcp varEnd, idx --> without thumb2
11619   //   fallthrough --> loopMBB
11620   // loopMBB:
11621   //   PHI varPhi, varEnd, varLoop
11622   //   PHI srcPhi, src, srcLoop
11623   //   PHI destPhi, dst, destLoop
11624   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
11625   //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
11626   //   subs varLoop, varPhi, #UnitSize
11627   //   bne loopMBB
11628   //   fallthrough --> exitMBB
11629   // exitMBB:
11630   //   epilogue to handle left-over bytes
11631   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
11632   //   [destOut] = STRB_POST(scratch, destLoop, 1)
11633   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11634   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11635   MF->insert(It, loopMBB);
11636   MF->insert(It, exitMBB);
11637 
11638   // Set the call frame size on entry to the new basic blocks.
11639   unsigned CallFrameSize = TII->getCallFrameSizeAt(MI);
11640   loopMBB->setCallFrameSize(CallFrameSize);
11641   exitMBB->setCallFrameSize(CallFrameSize);
11642 
11643   // Transfer the remainder of BB and its successor edges to exitMBB.
11644   exitMBB->splice(exitMBB->begin(), BB,
11645                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
11646   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
11647 
11648   // Load an immediate to varEnd.
11649   Register varEnd = MRI.createVirtualRegister(TRC);
11650   if (Subtarget->useMovt()) {
11651     BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVi32imm : ARM::MOVi32imm),
11652             varEnd)
11653         .addImm(LoopSize);
11654   } else if (Subtarget->genExecuteOnly()) {
11655     assert(IsThumb && "Non-thumb expected to have used movt");
11656     BuildMI(BB, dl, TII->get(ARM::tMOVi32imm), varEnd).addImm(LoopSize);
11657   } else {
11658     MachineConstantPool *ConstantPool = MF->getConstantPool();
11659     Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext());
11660     const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
11661 
11662     // MachineConstantPool wants an explicit alignment.
11663     Align Alignment = MF->getDataLayout().getPrefTypeAlign(Int32Ty);
11664     unsigned Idx = ConstantPool->getConstantPoolIndex(C, Alignment);
11665     MachineMemOperand *CPMMO =
11666         MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF),
11667                                  MachineMemOperand::MOLoad, 4, Align(4));
11668 
11669     if (IsThumb)
11670       BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci))
11671           .addReg(varEnd, RegState::Define)
11672           .addConstantPoolIndex(Idx)
11673           .add(predOps(ARMCC::AL))
11674           .addMemOperand(CPMMO);
11675     else
11676       BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp))
11677           .addReg(varEnd, RegState::Define)
11678           .addConstantPoolIndex(Idx)
11679           .addImm(0)
11680           .add(predOps(ARMCC::AL))
11681           .addMemOperand(CPMMO);
11682   }
11683   BB->addSuccessor(loopMBB);
11684 
11685   // Generate the loop body:
11686   //   varPhi = PHI(varLoop, varEnd)
11687   //   srcPhi = PHI(srcLoop, src)
11688   //   destPhi = PHI(destLoop, dst)
11689   MachineBasicBlock *entryBB = BB;
11690   BB = loopMBB;
11691   Register varLoop = MRI.createVirtualRegister(TRC);
11692   Register varPhi = MRI.createVirtualRegister(TRC);
11693   Register srcLoop = MRI.createVirtualRegister(TRC);
11694   Register srcPhi = MRI.createVirtualRegister(TRC);
11695   Register destLoop = MRI.createVirtualRegister(TRC);
11696   Register destPhi = MRI.createVirtualRegister(TRC);
11697 
11698   BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
11699     .addReg(varLoop).addMBB(loopMBB)
11700     .addReg(varEnd).addMBB(entryBB);
11701   BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
11702     .addReg(srcLoop).addMBB(loopMBB)
11703     .addReg(src).addMBB(entryBB);
11704   BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
11705     .addReg(destLoop).addMBB(loopMBB)
11706     .addReg(dest).addMBB(entryBB);
11707 
11708   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
11709   //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
11710   Register scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
11711   emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
11712              IsThumb1, IsThumb2);
11713   emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
11714              IsThumb1, IsThumb2);
11715 
11716   // Decrement loop variable by UnitSize.
11717   if (IsThumb1) {
11718     BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop)
11719         .add(t1CondCodeOp())
11720         .addReg(varPhi)
11721         .addImm(UnitSize)
11722         .add(predOps(ARMCC::AL));
11723   } else {
11724     MachineInstrBuilder MIB =
11725         BuildMI(*BB, BB->end(), dl,
11726                 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
11727     MIB.addReg(varPhi)
11728         .addImm(UnitSize)
11729         .add(predOps(ARMCC::AL))
11730         .add(condCodeOp());
11731     MIB->getOperand(5).setReg(ARM::CPSR);
11732     MIB->getOperand(5).setIsDef(true);
11733   }
11734   BuildMI(*BB, BB->end(), dl,
11735           TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
11736       .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
11737 
11738   // loopMBB can loop back to loopMBB or fall through to exitMBB.
11739   BB->addSuccessor(loopMBB);
11740   BB->addSuccessor(exitMBB);
11741 
11742   // Add epilogue to handle BytesLeft.
11743   BB = exitMBB;
11744   auto StartOfExit = exitMBB->begin();
11745 
11746   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
11747   //   [destOut] = STRB_POST(scratch, destLoop, 1)
11748   unsigned srcIn = srcLoop;
11749   unsigned destIn = destLoop;
11750   for (unsigned i = 0; i < BytesLeft; i++) {
11751     Register srcOut = MRI.createVirtualRegister(TRC);
11752     Register destOut = MRI.createVirtualRegister(TRC);
11753     Register scratch = MRI.createVirtualRegister(TRC);
11754     emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
11755                IsThumb1, IsThumb2);
11756     emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
11757                IsThumb1, IsThumb2);
11758     srcIn = srcOut;
11759     destIn = destOut;
11760   }
11761 
11762   MI.eraseFromParent(); // The instruction is gone now.
11763   return BB;
11764 }
11765 
11766 MachineBasicBlock *
EmitLowered__chkstk(MachineInstr & MI,MachineBasicBlock * MBB) const11767 ARMTargetLowering::EmitLowered__chkstk(MachineInstr &MI,
11768                                        MachineBasicBlock *MBB) const {
11769   const TargetMachine &TM = getTargetMachine();
11770   const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
11771   DebugLoc DL = MI.getDebugLoc();
11772 
11773   assert(Subtarget->isTargetWindows() &&
11774          "__chkstk is only supported on Windows");
11775   assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
11776 
11777   // __chkstk takes the number of words to allocate on the stack in R4, and
11778   // returns the stack adjustment in number of bytes in R4.  This will not
11779   // clober any other registers (other than the obvious lr).
11780   //
11781   // Although, technically, IP should be considered a register which may be
11782   // clobbered, the call itself will not touch it.  Windows on ARM is a pure
11783   // thumb-2 environment, so there is no interworking required.  As a result, we
11784   // do not expect a veneer to be emitted by the linker, clobbering IP.
11785   //
11786   // Each module receives its own copy of __chkstk, so no import thunk is
11787   // required, again, ensuring that IP is not clobbered.
11788   //
11789   // Finally, although some linkers may theoretically provide a trampoline for
11790   // out of range calls (which is quite common due to a 32M range limitation of
11791   // branches for Thumb), we can generate the long-call version via
11792   // -mcmodel=large, alleviating the need for the trampoline which may clobber
11793   // IP.
11794 
11795   switch (TM.getCodeModel()) {
11796   case CodeModel::Tiny:
11797     llvm_unreachable("Tiny code model not available on ARM.");
11798   case CodeModel::Small:
11799   case CodeModel::Medium:
11800   case CodeModel::Kernel:
11801     BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
11802         .add(predOps(ARMCC::AL))
11803         .addExternalSymbol("__chkstk")
11804         .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
11805         .addReg(ARM::R4, RegState::Implicit | RegState::Define)
11806         .addReg(ARM::R12,
11807                 RegState::Implicit | RegState::Define | RegState::Dead)
11808         .addReg(ARM::CPSR,
11809                 RegState::Implicit | RegState::Define | RegState::Dead);
11810     break;
11811   case CodeModel::Large: {
11812     MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
11813     Register Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
11814 
11815     BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
11816       .addExternalSymbol("__chkstk");
11817     BuildMI(*MBB, MI, DL, TII.get(gettBLXrOpcode(*MBB->getParent())))
11818         .add(predOps(ARMCC::AL))
11819         .addReg(Reg, RegState::Kill)
11820         .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
11821         .addReg(ARM::R4, RegState::Implicit | RegState::Define)
11822         .addReg(ARM::R12,
11823                 RegState::Implicit | RegState::Define | RegState::Dead)
11824         .addReg(ARM::CPSR,
11825                 RegState::Implicit | RegState::Define | RegState::Dead);
11826     break;
11827   }
11828   }
11829 
11830   BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr), ARM::SP)
11831       .addReg(ARM::SP, RegState::Kill)
11832       .addReg(ARM::R4, RegState::Kill)
11833       .setMIFlags(MachineInstr::FrameSetup)
11834       .add(predOps(ARMCC::AL))
11835       .add(condCodeOp());
11836 
11837   MI.eraseFromParent();
11838   return MBB;
11839 }
11840 
11841 MachineBasicBlock *
EmitLowered__dbzchk(MachineInstr & MI,MachineBasicBlock * MBB) const11842 ARMTargetLowering::EmitLowered__dbzchk(MachineInstr &MI,
11843                                        MachineBasicBlock *MBB) const {
11844   DebugLoc DL = MI.getDebugLoc();
11845   MachineFunction *MF = MBB->getParent();
11846   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
11847 
11848   MachineBasicBlock *ContBB = MF->CreateMachineBasicBlock();
11849   MF->insert(++MBB->getIterator(), ContBB);
11850   ContBB->splice(ContBB->begin(), MBB,
11851                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
11852   ContBB->transferSuccessorsAndUpdatePHIs(MBB);
11853   MBB->addSuccessor(ContBB);
11854 
11855   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
11856   BuildMI(TrapBB, DL, TII->get(ARM::t__brkdiv0));
11857   MF->push_back(TrapBB);
11858   MBB->addSuccessor(TrapBB);
11859 
11860   BuildMI(*MBB, MI, DL, TII->get(ARM::tCMPi8))
11861       .addReg(MI.getOperand(0).getReg())
11862       .addImm(0)
11863       .add(predOps(ARMCC::AL));
11864   BuildMI(*MBB, MI, DL, TII->get(ARM::t2Bcc))
11865       .addMBB(TrapBB)
11866       .addImm(ARMCC::EQ)
11867       .addReg(ARM::CPSR);
11868 
11869   MI.eraseFromParent();
11870   return ContBB;
11871 }
11872 
11873 // The CPSR operand of SelectItr might be missing a kill marker
11874 // because there were multiple uses of CPSR, and ISel didn't know
11875 // which to mark. Figure out whether SelectItr should have had a
11876 // kill marker, and set it if it should. Returns the correct kill
11877 // marker value.
checkAndUpdateCPSRKill(MachineBasicBlock::iterator SelectItr,MachineBasicBlock * BB,const TargetRegisterInfo * TRI)11878 static bool checkAndUpdateCPSRKill(MachineBasicBlock::iterator SelectItr,
11879                                    MachineBasicBlock* BB,
11880                                    const TargetRegisterInfo* TRI) {
11881   // Scan forward through BB for a use/def of CPSR.
11882   MachineBasicBlock::iterator miI(std::next(SelectItr));
11883   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
11884     const MachineInstr& mi = *miI;
11885     if (mi.readsRegister(ARM::CPSR, /*TRI=*/nullptr))
11886       return false;
11887     if (mi.definesRegister(ARM::CPSR, /*TRI=*/nullptr))
11888       break; // Should have kill-flag - update below.
11889   }
11890 
11891   // If we hit the end of the block, check whether CPSR is live into a
11892   // successor.
11893   if (miI == BB->end()) {
11894     for (MachineBasicBlock *Succ : BB->successors())
11895       if (Succ->isLiveIn(ARM::CPSR))
11896         return false;
11897   }
11898 
11899   // We found a def, or hit the end of the basic block and CPSR wasn't live
11900   // out. SelectMI should have a kill flag on CPSR.
11901   SelectItr->addRegisterKilled(ARM::CPSR, TRI);
11902   return true;
11903 }
11904 
11905 /// Adds logic in loop entry MBB to calculate loop iteration count and adds
11906 /// t2WhileLoopSetup and t2WhileLoopStart to generate WLS loop
genTPEntry(MachineBasicBlock * TpEntry,MachineBasicBlock * TpLoopBody,MachineBasicBlock * TpExit,Register OpSizeReg,const TargetInstrInfo * TII,DebugLoc Dl,MachineRegisterInfo & MRI)11907 static Register genTPEntry(MachineBasicBlock *TpEntry,
11908                            MachineBasicBlock *TpLoopBody,
11909                            MachineBasicBlock *TpExit, Register OpSizeReg,
11910                            const TargetInstrInfo *TII, DebugLoc Dl,
11911                            MachineRegisterInfo &MRI) {
11912   // Calculates loop iteration count = ceil(n/16) = (n + 15) >> 4.
11913   Register AddDestReg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
11914   BuildMI(TpEntry, Dl, TII->get(ARM::t2ADDri), AddDestReg)
11915       .addUse(OpSizeReg)
11916       .addImm(15)
11917       .add(predOps(ARMCC::AL))
11918       .addReg(0);
11919 
11920   Register LsrDestReg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
11921   BuildMI(TpEntry, Dl, TII->get(ARM::t2LSRri), LsrDestReg)
11922       .addUse(AddDestReg, RegState::Kill)
11923       .addImm(4)
11924       .add(predOps(ARMCC::AL))
11925       .addReg(0);
11926 
11927   Register TotalIterationsReg = MRI.createVirtualRegister(&ARM::GPRlrRegClass);
11928   BuildMI(TpEntry, Dl, TII->get(ARM::t2WhileLoopSetup), TotalIterationsReg)
11929       .addUse(LsrDestReg, RegState::Kill);
11930 
11931   BuildMI(TpEntry, Dl, TII->get(ARM::t2WhileLoopStart))
11932       .addUse(TotalIterationsReg)
11933       .addMBB(TpExit);
11934 
11935   BuildMI(TpEntry, Dl, TII->get(ARM::t2B))
11936       .addMBB(TpLoopBody)
11937       .add(predOps(ARMCC::AL));
11938 
11939   return TotalIterationsReg;
11940 }
11941 
11942 /// Adds logic in the loopBody MBB to generate MVE_VCTP, t2DoLoopDec and
11943 /// t2DoLoopEnd. These are used by later passes to generate tail predicated
11944 /// loops.
genTPLoopBody(MachineBasicBlock * TpLoopBody,MachineBasicBlock * TpEntry,MachineBasicBlock * TpExit,const TargetInstrInfo * TII,DebugLoc Dl,MachineRegisterInfo & MRI,Register OpSrcReg,Register OpDestReg,Register ElementCountReg,Register TotalIterationsReg,bool IsMemcpy)11945 static void genTPLoopBody(MachineBasicBlock *TpLoopBody,
11946                           MachineBasicBlock *TpEntry, MachineBasicBlock *TpExit,
11947                           const TargetInstrInfo *TII, DebugLoc Dl,
11948                           MachineRegisterInfo &MRI, Register OpSrcReg,
11949                           Register OpDestReg, Register ElementCountReg,
11950                           Register TotalIterationsReg, bool IsMemcpy) {
11951   // First insert 4 PHI nodes for: Current pointer to Src (if memcpy), Dest
11952   // array, loop iteration counter, predication counter.
11953 
11954   Register SrcPhiReg, CurrSrcReg;
11955   if (IsMemcpy) {
11956     //  Current position in the src array
11957     SrcPhiReg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
11958     CurrSrcReg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
11959     BuildMI(TpLoopBody, Dl, TII->get(ARM::PHI), SrcPhiReg)
11960         .addUse(OpSrcReg)
11961         .addMBB(TpEntry)
11962         .addUse(CurrSrcReg)
11963         .addMBB(TpLoopBody);
11964   }
11965 
11966   // Current position in the dest array
11967   Register DestPhiReg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
11968   Register CurrDestReg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
11969   BuildMI(TpLoopBody, Dl, TII->get(ARM::PHI), DestPhiReg)
11970       .addUse(OpDestReg)
11971       .addMBB(TpEntry)
11972       .addUse(CurrDestReg)
11973       .addMBB(TpLoopBody);
11974 
11975   // Current loop counter
11976   Register LoopCounterPhiReg = MRI.createVirtualRegister(&ARM::GPRlrRegClass);
11977   Register RemainingLoopIterationsReg =
11978       MRI.createVirtualRegister(&ARM::GPRlrRegClass);
11979   BuildMI(TpLoopBody, Dl, TII->get(ARM::PHI), LoopCounterPhiReg)
11980       .addUse(TotalIterationsReg)
11981       .addMBB(TpEntry)
11982       .addUse(RemainingLoopIterationsReg)
11983       .addMBB(TpLoopBody);
11984 
11985   // Predication counter
11986   Register PredCounterPhiReg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
11987   Register RemainingElementsReg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
11988   BuildMI(TpLoopBody, Dl, TII->get(ARM::PHI), PredCounterPhiReg)
11989       .addUse(ElementCountReg)
11990       .addMBB(TpEntry)
11991       .addUse(RemainingElementsReg)
11992       .addMBB(TpLoopBody);
11993 
11994   // Pass predication counter to VCTP
11995   Register VccrReg = MRI.createVirtualRegister(&ARM::VCCRRegClass);
11996   BuildMI(TpLoopBody, Dl, TII->get(ARM::MVE_VCTP8), VccrReg)
11997       .addUse(PredCounterPhiReg)
11998       .addImm(ARMVCC::None)
11999       .addReg(0)
12000       .addReg(0);
12001 
12002   BuildMI(TpLoopBody, Dl, TII->get(ARM::t2SUBri), RemainingElementsReg)
12003       .addUse(PredCounterPhiReg)
12004       .addImm(16)
12005       .add(predOps(ARMCC::AL))
12006       .addReg(0);
12007 
12008   // VLDRB (only if memcpy) and VSTRB instructions, predicated using VPR
12009   Register SrcValueReg;
12010   if (IsMemcpy) {
12011     SrcValueReg = MRI.createVirtualRegister(&ARM::MQPRRegClass);
12012     BuildMI(TpLoopBody, Dl, TII->get(ARM::MVE_VLDRBU8_post))
12013         .addDef(CurrSrcReg)
12014         .addDef(SrcValueReg)
12015         .addReg(SrcPhiReg)
12016         .addImm(16)
12017         .addImm(ARMVCC::Then)
12018         .addUse(VccrReg)
12019         .addReg(0);
12020   } else
12021     SrcValueReg = OpSrcReg;
12022 
12023   BuildMI(TpLoopBody, Dl, TII->get(ARM::MVE_VSTRBU8_post))
12024       .addDef(CurrDestReg)
12025       .addUse(SrcValueReg)
12026       .addReg(DestPhiReg)
12027       .addImm(16)
12028       .addImm(ARMVCC::Then)
12029       .addUse(VccrReg)
12030       .addReg(0);
12031 
12032   // Add the pseudoInstrs for decrementing the loop counter and marking the
12033   // end:t2DoLoopDec and t2DoLoopEnd
12034   BuildMI(TpLoopBody, Dl, TII->get(ARM::t2LoopDec), RemainingLoopIterationsReg)
12035       .addUse(LoopCounterPhiReg)
12036       .addImm(1);
12037 
12038   BuildMI(TpLoopBody, Dl, TII->get(ARM::t2LoopEnd))
12039       .addUse(RemainingLoopIterationsReg)
12040       .addMBB(TpLoopBody);
12041 
12042   BuildMI(TpLoopBody, Dl, TII->get(ARM::t2B))
12043       .addMBB(TpExit)
12044       .add(predOps(ARMCC::AL));
12045 }
12046 
12047 MachineBasicBlock *
EmitInstrWithCustomInserter(MachineInstr & MI,MachineBasicBlock * BB) const12048 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
12049                                                MachineBasicBlock *BB) const {
12050   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
12051   DebugLoc dl = MI.getDebugLoc();
12052   bool isThumb2 = Subtarget->isThumb2();
12053   switch (MI.getOpcode()) {
12054   default: {
12055     MI.print(errs());
12056     llvm_unreachable("Unexpected instr type to insert");
12057   }
12058 
12059   // Thumb1 post-indexed loads are really just single-register LDMs.
12060   case ARM::tLDR_postidx: {
12061     MachineOperand Def(MI.getOperand(1));
12062     BuildMI(*BB, MI, dl, TII->get(ARM::tLDMIA_UPD))
12063         .add(Def)  // Rn_wb
12064         .add(MI.getOperand(2))  // Rn
12065         .add(MI.getOperand(3))  // PredImm
12066         .add(MI.getOperand(4))  // PredReg
12067         .add(MI.getOperand(0))  // Rt
12068         .cloneMemRefs(MI);
12069     MI.eraseFromParent();
12070     return BB;
12071   }
12072 
12073   case ARM::MVE_MEMCPYLOOPINST:
12074   case ARM::MVE_MEMSETLOOPINST: {
12075 
12076     // Transformation below expands MVE_MEMCPYLOOPINST/MVE_MEMSETLOOPINST Pseudo
12077     // into a Tail Predicated (TP) Loop. It adds the instructions to calculate
12078     // the iteration count =ceil(size_in_bytes/16)) in the TP entry block and
12079     // adds the relevant instructions in the TP loop Body for generation of a
12080     // WLSTP loop.
12081 
12082     // Below is relevant portion of the CFG after the transformation.
12083     // The Machine Basic Blocks are shown along with branch conditions (in
12084     // brackets). Note that TP entry/exit MBBs depict the entry/exit of this
12085     // portion of the CFG and may not necessarily be the entry/exit of the
12086     // function.
12087 
12088     //             (Relevant) CFG after transformation:
12089     //               TP entry MBB
12090     //                   |
12091     //          |-----------------|
12092     //       (n <= 0)          (n > 0)
12093     //          |                 |
12094     //          |         TP loop Body MBB<--|
12095     //          |                |           |
12096     //           \               |___________|
12097     //            \             /
12098     //              TP exit MBB
12099 
12100     MachineFunction *MF = BB->getParent();
12101     MachineFunctionProperties &Properties = MF->getProperties();
12102     MachineRegisterInfo &MRI = MF->getRegInfo();
12103 
12104     Register OpDestReg = MI.getOperand(0).getReg();
12105     Register OpSrcReg = MI.getOperand(1).getReg();
12106     Register OpSizeReg = MI.getOperand(2).getReg();
12107 
12108     // Allocate the required MBBs and add to parent function.
12109     MachineBasicBlock *TpEntry = BB;
12110     MachineBasicBlock *TpLoopBody = MF->CreateMachineBasicBlock();
12111     MachineBasicBlock *TpExit;
12112 
12113     MF->push_back(TpLoopBody);
12114 
12115     // If any instructions are present in the current block after
12116     // MVE_MEMCPYLOOPINST or MVE_MEMSETLOOPINST, split the current block and
12117     // move the instructions into the newly created exit block. If there are no
12118     // instructions add an explicit branch to the FallThrough block and then
12119     // split.
12120     //
12121     // The split is required for two reasons:
12122     // 1) A terminator(t2WhileLoopStart) will be placed at that site.
12123     // 2) Since a TPLoopBody will be added later, any phis in successive blocks
12124     //    need to be updated. splitAt() already handles this.
12125     TpExit = BB->splitAt(MI, false);
12126     if (TpExit == BB) {
12127       assert(BB->canFallThrough() && "Exit Block must be Fallthrough of the "
12128                                      "block containing memcpy/memset Pseudo");
12129       TpExit = BB->getFallThrough();
12130       BuildMI(BB, dl, TII->get(ARM::t2B))
12131           .addMBB(TpExit)
12132           .add(predOps(ARMCC::AL));
12133       TpExit = BB->splitAt(MI, false);
12134     }
12135 
12136     // Add logic for iteration count
12137     Register TotalIterationsReg =
12138         genTPEntry(TpEntry, TpLoopBody, TpExit, OpSizeReg, TII, dl, MRI);
12139 
12140     // Add the vectorized (and predicated) loads/store instructions
12141     bool IsMemcpy = MI.getOpcode() == ARM::MVE_MEMCPYLOOPINST;
12142     genTPLoopBody(TpLoopBody, TpEntry, TpExit, TII, dl, MRI, OpSrcReg,
12143                   OpDestReg, OpSizeReg, TotalIterationsReg, IsMemcpy);
12144 
12145     // Required to avoid conflict with the MachineVerifier during testing.
12146     Properties.resetNoPHIs();
12147 
12148     // Connect the blocks
12149     TpEntry->addSuccessor(TpLoopBody);
12150     TpLoopBody->addSuccessor(TpLoopBody);
12151     TpLoopBody->addSuccessor(TpExit);
12152 
12153     // Reorder for a more natural layout
12154     TpLoopBody->moveAfter(TpEntry);
12155     TpExit->moveAfter(TpLoopBody);
12156 
12157     // Finally, remove the memcpy Pseudo Instruction
12158     MI.eraseFromParent();
12159 
12160     // Return the exit block as it may contain other instructions requiring a
12161     // custom inserter
12162     return TpExit;
12163   }
12164 
12165   // The Thumb2 pre-indexed stores have the same MI operands, they just
12166   // define them differently in the .td files from the isel patterns, so
12167   // they need pseudos.
12168   case ARM::t2STR_preidx:
12169     MI.setDesc(TII->get(ARM::t2STR_PRE));
12170     return BB;
12171   case ARM::t2STRB_preidx:
12172     MI.setDesc(TII->get(ARM::t2STRB_PRE));
12173     return BB;
12174   case ARM::t2STRH_preidx:
12175     MI.setDesc(TII->get(ARM::t2STRH_PRE));
12176     return BB;
12177 
12178   case ARM::STRi_preidx:
12179   case ARM::STRBi_preidx: {
12180     unsigned NewOpc = MI.getOpcode() == ARM::STRi_preidx ? ARM::STR_PRE_IMM
12181                                                          : ARM::STRB_PRE_IMM;
12182     // Decode the offset.
12183     unsigned Offset = MI.getOperand(4).getImm();
12184     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
12185     Offset = ARM_AM::getAM2Offset(Offset);
12186     if (isSub)
12187       Offset = -Offset;
12188 
12189     MachineMemOperand *MMO = *MI.memoperands_begin();
12190     BuildMI(*BB, MI, dl, TII->get(NewOpc))
12191         .add(MI.getOperand(0)) // Rn_wb
12192         .add(MI.getOperand(1)) // Rt
12193         .add(MI.getOperand(2)) // Rn
12194         .addImm(Offset)        // offset (skip GPR==zero_reg)
12195         .add(MI.getOperand(5)) // pred
12196         .add(MI.getOperand(6))
12197         .addMemOperand(MMO);
12198     MI.eraseFromParent();
12199     return BB;
12200   }
12201   case ARM::STRr_preidx:
12202   case ARM::STRBr_preidx:
12203   case ARM::STRH_preidx: {
12204     unsigned NewOpc;
12205     switch (MI.getOpcode()) {
12206     default: llvm_unreachable("unexpected opcode!");
12207     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
12208     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
12209     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
12210     }
12211     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
12212     for (const MachineOperand &MO : MI.operands())
12213       MIB.add(MO);
12214     MI.eraseFromParent();
12215     return BB;
12216   }
12217 
12218   case ARM::tMOVCCr_pseudo: {
12219     // To "insert" a SELECT_CC instruction, we actually have to insert the
12220     // diamond control-flow pattern.  The incoming instruction knows the
12221     // destination vreg to set, the condition code register to branch on, the
12222     // true/false values to select between, and a branch opcode to use.
12223     const BasicBlock *LLVM_BB = BB->getBasicBlock();
12224     MachineFunction::iterator It = ++BB->getIterator();
12225 
12226     //  thisMBB:
12227     //  ...
12228     //   TrueVal = ...
12229     //   cmpTY ccX, r1, r2
12230     //   bCC copy1MBB
12231     //   fallthrough --> copy0MBB
12232     MachineBasicBlock *thisMBB  = BB;
12233     MachineFunction *F = BB->getParent();
12234     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
12235     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
12236     F->insert(It, copy0MBB);
12237     F->insert(It, sinkMBB);
12238 
12239     // Set the call frame size on entry to the new basic blocks.
12240     unsigned CallFrameSize = TII->getCallFrameSizeAt(MI);
12241     copy0MBB->setCallFrameSize(CallFrameSize);
12242     sinkMBB->setCallFrameSize(CallFrameSize);
12243 
12244     // Check whether CPSR is live past the tMOVCCr_pseudo.
12245     const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
12246     if (!MI.killsRegister(ARM::CPSR, /*TRI=*/nullptr) &&
12247         !checkAndUpdateCPSRKill(MI, thisMBB, TRI)) {
12248       copy0MBB->addLiveIn(ARM::CPSR);
12249       sinkMBB->addLiveIn(ARM::CPSR);
12250     }
12251 
12252     // Transfer the remainder of BB and its successor edges to sinkMBB.
12253     sinkMBB->splice(sinkMBB->begin(), BB,
12254                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
12255     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
12256 
12257     BB->addSuccessor(copy0MBB);
12258     BB->addSuccessor(sinkMBB);
12259 
12260     BuildMI(BB, dl, TII->get(ARM::tBcc))
12261         .addMBB(sinkMBB)
12262         .addImm(MI.getOperand(3).getImm())
12263         .addReg(MI.getOperand(4).getReg());
12264 
12265     //  copy0MBB:
12266     //   %FalseValue = ...
12267     //   # fallthrough to sinkMBB
12268     BB = copy0MBB;
12269 
12270     // Update machine-CFG edges
12271     BB->addSuccessor(sinkMBB);
12272 
12273     //  sinkMBB:
12274     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
12275     //  ...
12276     BB = sinkMBB;
12277     BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), MI.getOperand(0).getReg())
12278         .addReg(MI.getOperand(1).getReg())
12279         .addMBB(copy0MBB)
12280         .addReg(MI.getOperand(2).getReg())
12281         .addMBB(thisMBB);
12282 
12283     MI.eraseFromParent(); // The pseudo instruction is gone now.
12284     return BB;
12285   }
12286 
12287   case ARM::BCCi64:
12288   case ARM::BCCZi64: {
12289     // If there is an unconditional branch to the other successor, remove it.
12290     BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
12291 
12292     // Compare both parts that make up the double comparison separately for
12293     // equality.
12294     bool RHSisZero = MI.getOpcode() == ARM::BCCZi64;
12295 
12296     Register LHS1 = MI.getOperand(1).getReg();
12297     Register LHS2 = MI.getOperand(2).getReg();
12298     if (RHSisZero) {
12299       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
12300           .addReg(LHS1)
12301           .addImm(0)
12302           .add(predOps(ARMCC::AL));
12303       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
12304         .addReg(LHS2).addImm(0)
12305         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
12306     } else {
12307       Register RHS1 = MI.getOperand(3).getReg();
12308       Register RHS2 = MI.getOperand(4).getReg();
12309       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
12310           .addReg(LHS1)
12311           .addReg(RHS1)
12312           .add(predOps(ARMCC::AL));
12313       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
12314         .addReg(LHS2).addReg(RHS2)
12315         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
12316     }
12317 
12318     MachineBasicBlock *destMBB = MI.getOperand(RHSisZero ? 3 : 5).getMBB();
12319     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
12320     if (MI.getOperand(0).getImm() == ARMCC::NE)
12321       std::swap(destMBB, exitMBB);
12322 
12323     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
12324       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
12325     if (isThumb2)
12326       BuildMI(BB, dl, TII->get(ARM::t2B))
12327           .addMBB(exitMBB)
12328           .add(predOps(ARMCC::AL));
12329     else
12330       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
12331 
12332     MI.eraseFromParent(); // The pseudo instruction is gone now.
12333     return BB;
12334   }
12335 
12336   case ARM::Int_eh_sjlj_setjmp:
12337   case ARM::Int_eh_sjlj_setjmp_nofp:
12338   case ARM::tInt_eh_sjlj_setjmp:
12339   case ARM::t2Int_eh_sjlj_setjmp:
12340   case ARM::t2Int_eh_sjlj_setjmp_nofp:
12341     return BB;
12342 
12343   case ARM::Int_eh_sjlj_setup_dispatch:
12344     EmitSjLjDispatchBlock(MI, BB);
12345     return BB;
12346 
12347   case ARM::ABS:
12348   case ARM::t2ABS: {
12349     // To insert an ABS instruction, we have to insert the
12350     // diamond control-flow pattern.  The incoming instruction knows the
12351     // source vreg to test against 0, the destination vreg to set,
12352     // the condition code register to branch on, the
12353     // true/false values to select between, and a branch opcode to use.
12354     // It transforms
12355     //     V1 = ABS V0
12356     // into
12357     //     V2 = MOVS V0
12358     //     BCC                      (branch to SinkBB if V0 >= 0)
12359     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
12360     //     SinkBB: V1 = PHI(V2, V3)
12361     const BasicBlock *LLVM_BB = BB->getBasicBlock();
12362     MachineFunction::iterator BBI = ++BB->getIterator();
12363     MachineFunction *Fn = BB->getParent();
12364     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
12365     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
12366     Fn->insert(BBI, RSBBB);
12367     Fn->insert(BBI, SinkBB);
12368 
12369     // Set the call frame size on entry to the new basic blocks.
12370     unsigned CallFrameSize = TII->getCallFrameSizeAt(MI);
12371     RSBBB->setCallFrameSize(CallFrameSize);
12372     SinkBB->setCallFrameSize(CallFrameSize);
12373 
12374     Register ABSSrcReg = MI.getOperand(1).getReg();
12375     Register ABSDstReg = MI.getOperand(0).getReg();
12376     bool ABSSrcKIll = MI.getOperand(1).isKill();
12377     bool isThumb2 = Subtarget->isThumb2();
12378     MachineRegisterInfo &MRI = Fn->getRegInfo();
12379     // In Thumb mode S must not be specified if source register is the SP or
12380     // PC and if destination register is the SP, so restrict register class
12381     Register NewRsbDstReg = MRI.createVirtualRegister(
12382         isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass);
12383 
12384     // Transfer the remainder of BB and its successor edges to sinkMBB.
12385     SinkBB->splice(SinkBB->begin(), BB,
12386                    std::next(MachineBasicBlock::iterator(MI)), BB->end());
12387     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
12388 
12389     BB->addSuccessor(RSBBB);
12390     BB->addSuccessor(SinkBB);
12391 
12392     // fall through to SinkMBB
12393     RSBBB->addSuccessor(SinkBB);
12394 
12395     // insert a cmp at the end of BB
12396     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
12397         .addReg(ABSSrcReg)
12398         .addImm(0)
12399         .add(predOps(ARMCC::AL));
12400 
12401     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
12402     BuildMI(BB, dl,
12403       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
12404       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
12405 
12406     // insert rsbri in RSBBB
12407     // Note: BCC and rsbri will be converted into predicated rsbmi
12408     // by if-conversion pass
12409     BuildMI(*RSBBB, RSBBB->begin(), dl,
12410             TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
12411         .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0)
12412         .addImm(0)
12413         .add(predOps(ARMCC::AL))
12414         .add(condCodeOp());
12415 
12416     // insert PHI in SinkBB,
12417     // reuse ABSDstReg to not change uses of ABS instruction
12418     BuildMI(*SinkBB, SinkBB->begin(), dl,
12419       TII->get(ARM::PHI), ABSDstReg)
12420       .addReg(NewRsbDstReg).addMBB(RSBBB)
12421       .addReg(ABSSrcReg).addMBB(BB);
12422 
12423     // remove ABS instruction
12424     MI.eraseFromParent();
12425 
12426     // return last added BB
12427     return SinkBB;
12428   }
12429   case ARM::COPY_STRUCT_BYVAL_I32:
12430     ++NumLoopByVals;
12431     return EmitStructByval(MI, BB);
12432   case ARM::WIN__CHKSTK:
12433     return EmitLowered__chkstk(MI, BB);
12434   case ARM::WIN__DBZCHK:
12435     return EmitLowered__dbzchk(MI, BB);
12436   }
12437 }
12438 
12439 /// Attaches vregs to MEMCPY that it will use as scratch registers
12440 /// when it is expanded into LDM/STM. This is done as a post-isel lowering
12441 /// instead of as a custom inserter because we need the use list from the SDNode.
attachMEMCPYScratchRegs(const ARMSubtarget * Subtarget,MachineInstr & MI,const SDNode * Node)12442 static void attachMEMCPYScratchRegs(const ARMSubtarget *Subtarget,
12443                                     MachineInstr &MI, const SDNode *Node) {
12444   bool isThumb1 = Subtarget->isThumb1Only();
12445 
12446   MachineFunction *MF = MI.getParent()->getParent();
12447   MachineRegisterInfo &MRI = MF->getRegInfo();
12448   MachineInstrBuilder MIB(*MF, MI);
12449 
12450   // If the new dst/src is unused mark it as dead.
12451   if (!Node->hasAnyUseOfValue(0)) {
12452     MI.getOperand(0).setIsDead(true);
12453   }
12454   if (!Node->hasAnyUseOfValue(1)) {
12455     MI.getOperand(1).setIsDead(true);
12456   }
12457 
12458   // The MEMCPY both defines and kills the scratch registers.
12459   for (unsigned I = 0; I != MI.getOperand(4).getImm(); ++I) {
12460     Register TmpReg = MRI.createVirtualRegister(isThumb1 ? &ARM::tGPRRegClass
12461                                                          : &ARM::GPRRegClass);
12462     MIB.addReg(TmpReg, RegState::Define|RegState::Dead);
12463   }
12464 }
12465 
AdjustInstrPostInstrSelection(MachineInstr & MI,SDNode * Node) const12466 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
12467                                                       SDNode *Node) const {
12468   if (MI.getOpcode() == ARM::MEMCPY) {
12469     attachMEMCPYScratchRegs(Subtarget, MI, Node);
12470     return;
12471   }
12472 
12473   const MCInstrDesc *MCID = &MI.getDesc();
12474   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
12475   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
12476   // operand is still set to noreg. If needed, set the optional operand's
12477   // register to CPSR, and remove the redundant implicit def.
12478   //
12479   // e.g. ADCS (..., implicit-def CPSR) -> ADC (... opt:def CPSR).
12480 
12481   // Rename pseudo opcodes.
12482   unsigned NewOpc = convertAddSubFlagsOpcode(MI.getOpcode());
12483   unsigned ccOutIdx;
12484   if (NewOpc) {
12485     const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo();
12486     MCID = &TII->get(NewOpc);
12487 
12488     assert(MCID->getNumOperands() ==
12489            MI.getDesc().getNumOperands() + 5 - MI.getDesc().getSize()
12490         && "converted opcode should be the same except for cc_out"
12491            " (and, on Thumb1, pred)");
12492 
12493     MI.setDesc(*MCID);
12494 
12495     // Add the optional cc_out operand
12496     MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
12497 
12498     // On Thumb1, move all input operands to the end, then add the predicate
12499     if (Subtarget->isThumb1Only()) {
12500       for (unsigned c = MCID->getNumOperands() - 4; c--;) {
12501         MI.addOperand(MI.getOperand(1));
12502         MI.removeOperand(1);
12503       }
12504 
12505       // Restore the ties
12506       for (unsigned i = MI.getNumOperands(); i--;) {
12507         const MachineOperand& op = MI.getOperand(i);
12508         if (op.isReg() && op.isUse()) {
12509           int DefIdx = MCID->getOperandConstraint(i, MCOI::TIED_TO);
12510           if (DefIdx != -1)
12511             MI.tieOperands(DefIdx, i);
12512         }
12513       }
12514 
12515       MI.addOperand(MachineOperand::CreateImm(ARMCC::AL));
12516       MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/false));
12517       ccOutIdx = 1;
12518     } else
12519       ccOutIdx = MCID->getNumOperands() - 1;
12520   } else
12521     ccOutIdx = MCID->getNumOperands() - 1;
12522 
12523   // Any ARM instruction that sets the 's' bit should specify an optional
12524   // "cc_out" operand in the last operand position.
12525   if (!MI.hasOptionalDef() || !MCID->operands()[ccOutIdx].isOptionalDef()) {
12526     assert(!NewOpc && "Optional cc_out operand required");
12527     return;
12528   }
12529   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
12530   // since we already have an optional CPSR def.
12531   bool definesCPSR = false;
12532   bool deadCPSR = false;
12533   for (unsigned i = MCID->getNumOperands(), e = MI.getNumOperands(); i != e;
12534        ++i) {
12535     const MachineOperand &MO = MI.getOperand(i);
12536     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
12537       definesCPSR = true;
12538       if (MO.isDead())
12539         deadCPSR = true;
12540       MI.removeOperand(i);
12541       break;
12542     }
12543   }
12544   if (!definesCPSR) {
12545     assert(!NewOpc && "Optional cc_out operand required");
12546     return;
12547   }
12548   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
12549   if (deadCPSR) {
12550     assert(!MI.getOperand(ccOutIdx).getReg() &&
12551            "expect uninitialized optional cc_out operand");
12552     // Thumb1 instructions must have the S bit even if the CPSR is dead.
12553     if (!Subtarget->isThumb1Only())
12554       return;
12555   }
12556 
12557   // If this instruction was defined with an optional CPSR def and its dag node
12558   // had a live implicit CPSR def, then activate the optional CPSR def.
12559   MachineOperand &MO = MI.getOperand(ccOutIdx);
12560   MO.setReg(ARM::CPSR);
12561   MO.setIsDef(true);
12562 }
12563 
12564 //===----------------------------------------------------------------------===//
12565 //                           ARM Optimization Hooks
12566 //===----------------------------------------------------------------------===//
12567 
12568 // Helper function that checks if N is a null or all ones constant.
isZeroOrAllOnes(SDValue N,bool AllOnes)12569 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
12570   return AllOnes ? isAllOnesConstant(N) : isNullConstant(N);
12571 }
12572 
12573 // Return true if N is conditionally 0 or all ones.
12574 // Detects these expressions where cc is an i1 value:
12575 //
12576 //   (select cc 0, y)   [AllOnes=0]
12577 //   (select cc y, 0)   [AllOnes=0]
12578 //   (zext cc)          [AllOnes=0]
12579 //   (sext cc)          [AllOnes=0/1]
12580 //   (select cc -1, y)  [AllOnes=1]
12581 //   (select cc y, -1)  [AllOnes=1]
12582 //
12583 // Invert is set when N is the null/all ones constant when CC is false.
12584 // OtherOp is set to the alternative value of N.
isConditionalZeroOrAllOnes(SDNode * N,bool AllOnes,SDValue & CC,bool & Invert,SDValue & OtherOp,SelectionDAG & DAG)12585 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
12586                                        SDValue &CC, bool &Invert,
12587                                        SDValue &OtherOp,
12588                                        SelectionDAG &DAG) {
12589   switch (N->getOpcode()) {
12590   default: return false;
12591   case ISD::SELECT: {
12592     CC = N->getOperand(0);
12593     SDValue N1 = N->getOperand(1);
12594     SDValue N2 = N->getOperand(2);
12595     if (isZeroOrAllOnes(N1, AllOnes)) {
12596       Invert = false;
12597       OtherOp = N2;
12598       return true;
12599     }
12600     if (isZeroOrAllOnes(N2, AllOnes)) {
12601       Invert = true;
12602       OtherOp = N1;
12603       return true;
12604     }
12605     return false;
12606   }
12607   case ISD::ZERO_EXTEND:
12608     // (zext cc) can never be the all ones value.
12609     if (AllOnes)
12610       return false;
12611     [[fallthrough]];
12612   case ISD::SIGN_EXTEND: {
12613     SDLoc dl(N);
12614     EVT VT = N->getValueType(0);
12615     CC = N->getOperand(0);
12616     if (CC.getValueType() != MVT::i1 || CC.getOpcode() != ISD::SETCC)
12617       return false;
12618     Invert = !AllOnes;
12619     if (AllOnes)
12620       // When looking for an AllOnes constant, N is an sext, and the 'other'
12621       // value is 0.
12622       OtherOp = DAG.getConstant(0, dl, VT);
12623     else if (N->getOpcode() == ISD::ZERO_EXTEND)
12624       // When looking for a 0 constant, N can be zext or sext.
12625       OtherOp = DAG.getConstant(1, dl, VT);
12626     else
12627       OtherOp = DAG.getAllOnesConstant(dl, VT);
12628     return true;
12629   }
12630   }
12631 }
12632 
12633 // Combine a constant select operand into its use:
12634 //
12635 //   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
12636 //   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
12637 //   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
12638 //   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
12639 //   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
12640 //
12641 // The transform is rejected if the select doesn't have a constant operand that
12642 // is null, or all ones when AllOnes is set.
12643 //
12644 // Also recognize sext/zext from i1:
12645 //
12646 //   (add (zext cc), x) -> (select cc (add x, 1), x)
12647 //   (add (sext cc), x) -> (select cc (add x, -1), x)
12648 //
12649 // These transformations eventually create predicated instructions.
12650 //
12651 // @param N       The node to transform.
12652 // @param Slct    The N operand that is a select.
12653 // @param OtherOp The other N operand (x above).
12654 // @param DCI     Context.
12655 // @param AllOnes Require the select constant to be all ones instead of null.
12656 // @returns The new node, or SDValue() on failure.
12657 static
combineSelectAndUse(SDNode * N,SDValue Slct,SDValue OtherOp,TargetLowering::DAGCombinerInfo & DCI,bool AllOnes=false)12658 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
12659                             TargetLowering::DAGCombinerInfo &DCI,
12660                             bool AllOnes = false) {
12661   SelectionDAG &DAG = DCI.DAG;
12662   EVT VT = N->getValueType(0);
12663   SDValue NonConstantVal;
12664   SDValue CCOp;
12665   bool SwapSelectOps;
12666   if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
12667                                   NonConstantVal, DAG))
12668     return SDValue();
12669 
12670   // Slct is now know to be the desired identity constant when CC is true.
12671   SDValue TrueVal = OtherOp;
12672   SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
12673                                  OtherOp, NonConstantVal);
12674   // Unless SwapSelectOps says CC should be false.
12675   if (SwapSelectOps)
12676     std::swap(TrueVal, FalseVal);
12677 
12678   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
12679                      CCOp, TrueVal, FalseVal);
12680 }
12681 
12682 // Attempt combineSelectAndUse on each operand of a commutative operator N.
12683 static
combineSelectAndUseCommutative(SDNode * N,bool AllOnes,TargetLowering::DAGCombinerInfo & DCI)12684 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
12685                                        TargetLowering::DAGCombinerInfo &DCI) {
12686   SDValue N0 = N->getOperand(0);
12687   SDValue N1 = N->getOperand(1);
12688   if (N0.getNode()->hasOneUse())
12689     if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes))
12690       return Result;
12691   if (N1.getNode()->hasOneUse())
12692     if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes))
12693       return Result;
12694   return SDValue();
12695 }
12696 
IsVUZPShuffleNode(SDNode * N)12697 static bool IsVUZPShuffleNode(SDNode *N) {
12698   // VUZP shuffle node.
12699   if (N->getOpcode() == ARMISD::VUZP)
12700     return true;
12701 
12702   // "VUZP" on i32 is an alias for VTRN.
12703   if (N->getOpcode() == ARMISD::VTRN && N->getValueType(0) == MVT::v2i32)
12704     return true;
12705 
12706   return false;
12707 }
12708 
AddCombineToVPADD(SDNode * N,SDValue N0,SDValue N1,TargetLowering::DAGCombinerInfo & DCI,const ARMSubtarget * Subtarget)12709 static SDValue AddCombineToVPADD(SDNode *N, SDValue N0, SDValue N1,
12710                                  TargetLowering::DAGCombinerInfo &DCI,
12711                                  const ARMSubtarget *Subtarget) {
12712   // Look for ADD(VUZP.0, VUZP.1).
12713   if (!IsVUZPShuffleNode(N0.getNode()) || N0.getNode() != N1.getNode() ||
12714       N0 == N1)
12715    return SDValue();
12716 
12717   // Make sure the ADD is a 64-bit add; there is no 128-bit VPADD.
12718   if (!N->getValueType(0).is64BitVector())
12719     return SDValue();
12720 
12721   // Generate vpadd.
12722   SelectionDAG &DAG = DCI.DAG;
12723   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12724   SDLoc dl(N);
12725   SDNode *Unzip = N0.getNode();
12726   EVT VT = N->getValueType(0);
12727 
12728   SmallVector<SDValue, 8> Ops;
12729   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpadd, dl,
12730                                 TLI.getPointerTy(DAG.getDataLayout())));
12731   Ops.push_back(Unzip->getOperand(0));
12732   Ops.push_back(Unzip->getOperand(1));
12733 
12734   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops);
12735 }
12736 
AddCombineVUZPToVPADDL(SDNode * N,SDValue N0,SDValue N1,TargetLowering::DAGCombinerInfo & DCI,const ARMSubtarget * Subtarget)12737 static SDValue AddCombineVUZPToVPADDL(SDNode *N, SDValue N0, SDValue N1,
12738                                       TargetLowering::DAGCombinerInfo &DCI,
12739                                       const ARMSubtarget *Subtarget) {
12740   // Check for two extended operands.
12741   if (!(N0.getOpcode() == ISD::SIGN_EXTEND &&
12742         N1.getOpcode() == ISD::SIGN_EXTEND) &&
12743       !(N0.getOpcode() == ISD::ZERO_EXTEND &&
12744         N1.getOpcode() == ISD::ZERO_EXTEND))
12745     return SDValue();
12746 
12747   SDValue N00 = N0.getOperand(0);
12748   SDValue N10 = N1.getOperand(0);
12749 
12750   // Look for ADD(SEXT(VUZP.0), SEXT(VUZP.1))
12751   if (!IsVUZPShuffleNode(N00.getNode()) || N00.getNode() != N10.getNode() ||
12752       N00 == N10)
12753     return SDValue();
12754 
12755   // We only recognize Q register paddl here; this can't be reached until
12756   // after type legalization.
12757   if (!N00.getValueType().is64BitVector() ||
12758       !N0.getValueType().is128BitVector())
12759     return SDValue();
12760 
12761   // Generate vpaddl.
12762   SelectionDAG &DAG = DCI.DAG;
12763   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12764   SDLoc dl(N);
12765   EVT VT = N->getValueType(0);
12766 
12767   SmallVector<SDValue, 8> Ops;
12768   // Form vpaddl.sN or vpaddl.uN depending on the kind of extension.
12769   unsigned Opcode;
12770   if (N0.getOpcode() == ISD::SIGN_EXTEND)
12771     Opcode = Intrinsic::arm_neon_vpaddls;
12772   else
12773     Opcode = Intrinsic::arm_neon_vpaddlu;
12774   Ops.push_back(DAG.getConstant(Opcode, dl,
12775                                 TLI.getPointerTy(DAG.getDataLayout())));
12776   EVT ElemTy = N00.getValueType().getVectorElementType();
12777   unsigned NumElts = VT.getVectorNumElements();
12778   EVT ConcatVT = EVT::getVectorVT(*DAG.getContext(), ElemTy, NumElts * 2);
12779   SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), ConcatVT,
12780                                N00.getOperand(0), N00.getOperand(1));
12781   Ops.push_back(Concat);
12782 
12783   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops);
12784 }
12785 
12786 // FIXME: This function shouldn't be necessary; if we lower BUILD_VECTOR in
12787 // an appropriate manner, we end up with ADD(VUZP(ZEXT(N))), which is
12788 // much easier to match.
12789 static SDValue
AddCombineBUILD_VECTORToVPADDL(SDNode * N,SDValue N0,SDValue N1,TargetLowering::DAGCombinerInfo & DCI,const ARMSubtarget * Subtarget)12790 AddCombineBUILD_VECTORToVPADDL(SDNode *N, SDValue N0, SDValue N1,
12791                                TargetLowering::DAGCombinerInfo &DCI,
12792                                const ARMSubtarget *Subtarget) {
12793   // Only perform optimization if after legalize, and if NEON is available. We
12794   // also expected both operands to be BUILD_VECTORs.
12795   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
12796       || N0.getOpcode() != ISD::BUILD_VECTOR
12797       || N1.getOpcode() != ISD::BUILD_VECTOR)
12798     return SDValue();
12799 
12800   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
12801   EVT VT = N->getValueType(0);
12802   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
12803     return SDValue();
12804 
12805   // Check that the vector operands are of the right form.
12806   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
12807   // operands, where N is the size of the formed vector.
12808   // Each EXTRACT_VECTOR should have the same input vector and odd or even
12809   // index such that we have a pair wise add pattern.
12810 
12811   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
12812   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
12813     return SDValue();
12814   SDValue Vec = N0->getOperand(0)->getOperand(0);
12815   SDNode *V = Vec.getNode();
12816   unsigned nextIndex = 0;
12817 
12818   // For each operands to the ADD which are BUILD_VECTORs,
12819   // check to see if each of their operands are an EXTRACT_VECTOR with
12820   // the same vector and appropriate index.
12821   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
12822     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
12823         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
12824 
12825       SDValue ExtVec0 = N0->getOperand(i);
12826       SDValue ExtVec1 = N1->getOperand(i);
12827 
12828       // First operand is the vector, verify its the same.
12829       if (V != ExtVec0->getOperand(0).getNode() ||
12830           V != ExtVec1->getOperand(0).getNode())
12831         return SDValue();
12832 
12833       // Second is the constant, verify its correct.
12834       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
12835       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
12836 
12837       // For the constant, we want to see all the even or all the odd.
12838       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
12839           || C1->getZExtValue() != nextIndex+1)
12840         return SDValue();
12841 
12842       // Increment index.
12843       nextIndex+=2;
12844     } else
12845       return SDValue();
12846   }
12847 
12848   // Don't generate vpaddl+vmovn; we'll match it to vpadd later. Also make sure
12849   // we're using the entire input vector, otherwise there's a size/legality
12850   // mismatch somewhere.
12851   if (nextIndex != Vec.getValueType().getVectorNumElements() ||
12852       Vec.getValueType().getVectorElementType() == VT.getVectorElementType())
12853     return SDValue();
12854 
12855   // Create VPADDL node.
12856   SelectionDAG &DAG = DCI.DAG;
12857   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12858 
12859   SDLoc dl(N);
12860 
12861   // Build operand list.
12862   SmallVector<SDValue, 8> Ops;
12863   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl,
12864                                 TLI.getPointerTy(DAG.getDataLayout())));
12865 
12866   // Input is the vector.
12867   Ops.push_back(Vec);
12868 
12869   // Get widened type and narrowed type.
12870   MVT widenType;
12871   unsigned numElem = VT.getVectorNumElements();
12872 
12873   EVT inputLaneType = Vec.getValueType().getVectorElementType();
12874   switch (inputLaneType.getSimpleVT().SimpleTy) {
12875     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
12876     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
12877     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
12878     default:
12879       llvm_unreachable("Invalid vector element type for padd optimization.");
12880   }
12881 
12882   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops);
12883   unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
12884   return DAG.getNode(ExtOp, dl, VT, tmp);
12885 }
12886 
findMUL_LOHI(SDValue V)12887 static SDValue findMUL_LOHI(SDValue V) {
12888   if (V->getOpcode() == ISD::UMUL_LOHI ||
12889       V->getOpcode() == ISD::SMUL_LOHI)
12890     return V;
12891   return SDValue();
12892 }
12893 
AddCombineTo64BitSMLAL16(SDNode * AddcNode,SDNode * AddeNode,TargetLowering::DAGCombinerInfo & DCI,const ARMSubtarget * Subtarget)12894 static SDValue AddCombineTo64BitSMLAL16(SDNode *AddcNode, SDNode *AddeNode,
12895                                         TargetLowering::DAGCombinerInfo &DCI,
12896                                         const ARMSubtarget *Subtarget) {
12897   if (!Subtarget->hasBaseDSP())
12898     return SDValue();
12899 
12900   // SMLALBB, SMLALBT, SMLALTB, SMLALTT multiply two 16-bit values and
12901   // accumulates the product into a 64-bit value. The 16-bit values will
12902   // be sign extended somehow or SRA'd into 32-bit values
12903   // (addc (adde (mul 16bit, 16bit), lo), hi)
12904   SDValue Mul = AddcNode->getOperand(0);
12905   SDValue Lo = AddcNode->getOperand(1);
12906   if (Mul.getOpcode() != ISD::MUL) {
12907     Lo = AddcNode->getOperand(0);
12908     Mul = AddcNode->getOperand(1);
12909     if (Mul.getOpcode() != ISD::MUL)
12910       return SDValue();
12911   }
12912 
12913   SDValue SRA = AddeNode->getOperand(0);
12914   SDValue Hi = AddeNode->getOperand(1);
12915   if (SRA.getOpcode() != ISD::SRA) {
12916     SRA = AddeNode->getOperand(1);
12917     Hi = AddeNode->getOperand(0);
12918     if (SRA.getOpcode() != ISD::SRA)
12919       return SDValue();
12920   }
12921   if (auto Const = dyn_cast<ConstantSDNode>(SRA.getOperand(1))) {
12922     if (Const->getZExtValue() != 31)
12923       return SDValue();
12924   } else
12925     return SDValue();
12926 
12927   if (SRA.getOperand(0) != Mul)
12928     return SDValue();
12929 
12930   SelectionDAG &DAG = DCI.DAG;
12931   SDLoc dl(AddcNode);
12932   unsigned Opcode = 0;
12933   SDValue Op0;
12934   SDValue Op1;
12935 
12936   if (isS16(Mul.getOperand(0), DAG) && isS16(Mul.getOperand(1), DAG)) {
12937     Opcode = ARMISD::SMLALBB;
12938     Op0 = Mul.getOperand(0);
12939     Op1 = Mul.getOperand(1);
12940   } else if (isS16(Mul.getOperand(0), DAG) && isSRA16(Mul.getOperand(1))) {
12941     Opcode = ARMISD::SMLALBT;
12942     Op0 = Mul.getOperand(0);
12943     Op1 = Mul.getOperand(1).getOperand(0);
12944   } else if (isSRA16(Mul.getOperand(0)) && isS16(Mul.getOperand(1), DAG)) {
12945     Opcode = ARMISD::SMLALTB;
12946     Op0 = Mul.getOperand(0).getOperand(0);
12947     Op1 = Mul.getOperand(1);
12948   } else if (isSRA16(Mul.getOperand(0)) && isSRA16(Mul.getOperand(1))) {
12949     Opcode = ARMISD::SMLALTT;
12950     Op0 = Mul->getOperand(0).getOperand(0);
12951     Op1 = Mul->getOperand(1).getOperand(0);
12952   }
12953 
12954   if (!Op0 || !Op1)
12955     return SDValue();
12956 
12957   SDValue SMLAL = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
12958                               Op0, Op1, Lo, Hi);
12959   // Replace the ADDs' nodes uses by the MLA node's values.
12960   SDValue HiMLALResult(SMLAL.getNode(), 1);
12961   SDValue LoMLALResult(SMLAL.getNode(), 0);
12962 
12963   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
12964   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
12965 
12966   // Return original node to notify the driver to stop replacing.
12967   SDValue resNode(AddcNode, 0);
12968   return resNode;
12969 }
12970 
AddCombineTo64bitMLAL(SDNode * AddeSubeNode,TargetLowering::DAGCombinerInfo & DCI,const ARMSubtarget * Subtarget)12971 static SDValue AddCombineTo64bitMLAL(SDNode *AddeSubeNode,
12972                                      TargetLowering::DAGCombinerInfo &DCI,
12973                                      const ARMSubtarget *Subtarget) {
12974   // Look for multiply add opportunities.
12975   // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
12976   // each add nodes consumes a value from ISD::UMUL_LOHI and there is
12977   // a glue link from the first add to the second add.
12978   // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
12979   // a S/UMLAL instruction.
12980   //                  UMUL_LOHI
12981   //                 / :lo    \ :hi
12982   //                V          \          [no multiline comment]
12983   //    loAdd ->  ADDC         |
12984   //                 \ :carry /
12985   //                  V      V
12986   //                    ADDE   <- hiAdd
12987   //
12988   // In the special case where only the higher part of a signed result is used
12989   // and the add to the low part of the result of ISD::UMUL_LOHI adds or subtracts
12990   // a constant with the exact value of 0x80000000, we recognize we are dealing
12991   // with a "rounded multiply and add" (or subtract) and transform it into
12992   // either a ARMISD::SMMLAR or ARMISD::SMMLSR respectively.
12993 
12994   assert((AddeSubeNode->getOpcode() == ARMISD::ADDE ||
12995           AddeSubeNode->getOpcode() == ARMISD::SUBE) &&
12996          "Expect an ADDE or SUBE");
12997 
12998   assert(AddeSubeNode->getNumOperands() == 3 &&
12999          AddeSubeNode->getOperand(2).getValueType() == MVT::i32 &&
13000          "ADDE node has the wrong inputs");
13001 
13002   // Check that we are chained to the right ADDC or SUBC node.
13003   SDNode *AddcSubcNode = AddeSubeNode->getOperand(2).getNode();
13004   if ((AddeSubeNode->getOpcode() == ARMISD::ADDE &&
13005        AddcSubcNode->getOpcode() != ARMISD::ADDC) ||
13006       (AddeSubeNode->getOpcode() == ARMISD::SUBE &&
13007        AddcSubcNode->getOpcode() != ARMISD::SUBC))
13008     return SDValue();
13009 
13010   SDValue AddcSubcOp0 = AddcSubcNode->getOperand(0);
13011   SDValue AddcSubcOp1 = AddcSubcNode->getOperand(1);
13012 
13013   // Check if the two operands are from the same mul_lohi node.
13014   if (AddcSubcOp0.getNode() == AddcSubcOp1.getNode())
13015     return SDValue();
13016 
13017   assert(AddcSubcNode->getNumValues() == 2 &&
13018          AddcSubcNode->getValueType(0) == MVT::i32 &&
13019          "Expect ADDC with two result values. First: i32");
13020 
13021   // Check that the ADDC adds the low result of the S/UMUL_LOHI. If not, it
13022   // maybe a SMLAL which multiplies two 16-bit values.
13023   if (AddeSubeNode->getOpcode() == ARMISD::ADDE &&
13024       AddcSubcOp0->getOpcode() != ISD::UMUL_LOHI &&
13025       AddcSubcOp0->getOpcode() != ISD::SMUL_LOHI &&
13026       AddcSubcOp1->getOpcode() != ISD::UMUL_LOHI &&
13027       AddcSubcOp1->getOpcode() != ISD::SMUL_LOHI)
13028     return AddCombineTo64BitSMLAL16(AddcSubcNode, AddeSubeNode, DCI, Subtarget);
13029 
13030   // Check for the triangle shape.
13031   SDValue AddeSubeOp0 = AddeSubeNode->getOperand(0);
13032   SDValue AddeSubeOp1 = AddeSubeNode->getOperand(1);
13033 
13034   // Make sure that the ADDE/SUBE operands are not coming from the same node.
13035   if (AddeSubeOp0.getNode() == AddeSubeOp1.getNode())
13036     return SDValue();
13037 
13038   // Find the MUL_LOHI node walking up ADDE/SUBE's operands.
13039   bool IsLeftOperandMUL = false;
13040   SDValue MULOp = findMUL_LOHI(AddeSubeOp0);
13041   if (MULOp == SDValue())
13042     MULOp = findMUL_LOHI(AddeSubeOp1);
13043   else
13044     IsLeftOperandMUL = true;
13045   if (MULOp == SDValue())
13046     return SDValue();
13047 
13048   // Figure out the right opcode.
13049   unsigned Opc = MULOp->getOpcode();
13050   unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
13051 
13052   // Figure out the high and low input values to the MLAL node.
13053   SDValue *HiAddSub = nullptr;
13054   SDValue *LoMul = nullptr;
13055   SDValue *LowAddSub = nullptr;
13056 
13057   // Ensure that ADDE/SUBE is from high result of ISD::xMUL_LOHI.
13058   if ((AddeSubeOp0 != MULOp.getValue(1)) && (AddeSubeOp1 != MULOp.getValue(1)))
13059     return SDValue();
13060 
13061   if (IsLeftOperandMUL)
13062     HiAddSub = &AddeSubeOp1;
13063   else
13064     HiAddSub = &AddeSubeOp0;
13065 
13066   // Ensure that LoMul and LowAddSub are taken from correct ISD::SMUL_LOHI node
13067   // whose low result is fed to the ADDC/SUBC we are checking.
13068 
13069   if (AddcSubcOp0 == MULOp.getValue(0)) {
13070     LoMul = &AddcSubcOp0;
13071     LowAddSub = &AddcSubcOp1;
13072   }
13073   if (AddcSubcOp1 == MULOp.getValue(0)) {
13074     LoMul = &AddcSubcOp1;
13075     LowAddSub = &AddcSubcOp0;
13076   }
13077 
13078   if (!LoMul)
13079     return SDValue();
13080 
13081   // If HiAddSub is the same node as ADDC/SUBC or is a predecessor of ADDC/SUBC
13082   // the replacement below will create a cycle.
13083   if (AddcSubcNode == HiAddSub->getNode() ||
13084       AddcSubcNode->isPredecessorOf(HiAddSub->getNode()))
13085     return SDValue();
13086 
13087   // Create the merged node.
13088   SelectionDAG &DAG = DCI.DAG;
13089 
13090   // Start building operand list.
13091   SmallVector<SDValue, 8> Ops;
13092   Ops.push_back(LoMul->getOperand(0));
13093   Ops.push_back(LoMul->getOperand(1));
13094 
13095   // Check whether we can use SMMLAR, SMMLSR or SMMULR instead.  For this to be
13096   // the case, we must be doing signed multiplication and only use the higher
13097   // part of the result of the MLAL, furthermore the LowAddSub must be a constant
13098   // addition or subtraction with the value of 0x800000.
13099   if (Subtarget->hasV6Ops() && Subtarget->hasDSP() && Subtarget->useMulOps() &&
13100       FinalOpc == ARMISD::SMLAL && !AddeSubeNode->hasAnyUseOfValue(1) &&
13101       LowAddSub->getNode()->getOpcode() == ISD::Constant &&
13102       static_cast<ConstantSDNode *>(LowAddSub->getNode())->getZExtValue() ==
13103           0x80000000) {
13104     Ops.push_back(*HiAddSub);
13105     if (AddcSubcNode->getOpcode() == ARMISD::SUBC) {
13106       FinalOpc = ARMISD::SMMLSR;
13107     } else {
13108       FinalOpc = ARMISD::SMMLAR;
13109     }
13110     SDValue NewNode = DAG.getNode(FinalOpc, SDLoc(AddcSubcNode), MVT::i32, Ops);
13111     DAG.ReplaceAllUsesOfValueWith(SDValue(AddeSubeNode, 0), NewNode);
13112 
13113     return SDValue(AddeSubeNode, 0);
13114   } else if (AddcSubcNode->getOpcode() == ARMISD::SUBC)
13115     // SMMLS is generated during instruction selection and the rest of this
13116     // function can not handle the case where AddcSubcNode is a SUBC.
13117     return SDValue();
13118 
13119   // Finish building the operand list for {U/S}MLAL
13120   Ops.push_back(*LowAddSub);
13121   Ops.push_back(*HiAddSub);
13122 
13123   SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcSubcNode),
13124                                  DAG.getVTList(MVT::i32, MVT::i32), Ops);
13125 
13126   // Replace the ADDs' nodes uses by the MLA node's values.
13127   SDValue HiMLALResult(MLALNode.getNode(), 1);
13128   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeSubeNode, 0), HiMLALResult);
13129 
13130   SDValue LoMLALResult(MLALNode.getNode(), 0);
13131   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcSubcNode, 0), LoMLALResult);
13132 
13133   // Return original node to notify the driver to stop replacing.
13134   return SDValue(AddeSubeNode, 0);
13135 }
13136 
AddCombineTo64bitUMAAL(SDNode * AddeNode,TargetLowering::DAGCombinerInfo & DCI,const ARMSubtarget * Subtarget)13137 static SDValue AddCombineTo64bitUMAAL(SDNode *AddeNode,
13138                                       TargetLowering::DAGCombinerInfo &DCI,
13139                                       const ARMSubtarget *Subtarget) {
13140   // UMAAL is similar to UMLAL except that it adds two unsigned values.
13141   // While trying to combine for the other MLAL nodes, first search for the
13142   // chance to use UMAAL. Check if Addc uses a node which has already
13143   // been combined into a UMLAL. The other pattern is UMLAL using Addc/Adde
13144   // as the addend, and it's handled in PerformUMLALCombine.
13145 
13146   if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP())
13147     return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget);
13148 
13149   // Check that we have a glued ADDC node.
13150   SDNode* AddcNode = AddeNode->getOperand(2).getNode();
13151   if (AddcNode->getOpcode() != ARMISD::ADDC)
13152     return SDValue();
13153 
13154   // Find the converted UMAAL or quit if it doesn't exist.
13155   SDNode *UmlalNode = nullptr;
13156   SDValue AddHi;
13157   if (AddcNode->getOperand(0).getOpcode() == ARMISD::UMLAL) {
13158     UmlalNode = AddcNode->getOperand(0).getNode();
13159     AddHi = AddcNode->getOperand(1);
13160   } else if (AddcNode->getOperand(1).getOpcode() == ARMISD::UMLAL) {
13161     UmlalNode = AddcNode->getOperand(1).getNode();
13162     AddHi = AddcNode->getOperand(0);
13163   } else {
13164     return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget);
13165   }
13166 
13167   // The ADDC should be glued to an ADDE node, which uses the same UMLAL as
13168   // the ADDC as well as Zero.
13169   if (!isNullConstant(UmlalNode->getOperand(3)))
13170     return SDValue();
13171 
13172   if ((isNullConstant(AddeNode->getOperand(0)) &&
13173        AddeNode->getOperand(1).getNode() == UmlalNode) ||
13174       (AddeNode->getOperand(0).getNode() == UmlalNode &&
13175        isNullConstant(AddeNode->getOperand(1)))) {
13176     SelectionDAG &DAG = DCI.DAG;
13177     SDValue Ops[] = { UmlalNode->getOperand(0), UmlalNode->getOperand(1),
13178                       UmlalNode->getOperand(2), AddHi };
13179     SDValue UMAAL =  DAG.getNode(ARMISD::UMAAL, SDLoc(AddcNode),
13180                                  DAG.getVTList(MVT::i32, MVT::i32), Ops);
13181 
13182     // Replace the ADDs' nodes uses by the UMAAL node's values.
13183     DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), SDValue(UMAAL.getNode(), 1));
13184     DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), SDValue(UMAAL.getNode(), 0));
13185 
13186     // Return original node to notify the driver to stop replacing.
13187     return SDValue(AddeNode, 0);
13188   }
13189   return SDValue();
13190 }
13191 
PerformUMLALCombine(SDNode * N,SelectionDAG & DAG,const ARMSubtarget * Subtarget)13192 static SDValue PerformUMLALCombine(SDNode *N, SelectionDAG &DAG,
13193                                    const ARMSubtarget *Subtarget) {
13194   if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP())
13195     return SDValue();
13196 
13197   // Check that we have a pair of ADDC and ADDE as operands.
13198   // Both addends of the ADDE must be zero.
13199   SDNode* AddcNode = N->getOperand(2).getNode();
13200   SDNode* AddeNode = N->getOperand(3).getNode();
13201   if ((AddcNode->getOpcode() == ARMISD::ADDC) &&
13202       (AddeNode->getOpcode() == ARMISD::ADDE) &&
13203       isNullConstant(AddeNode->getOperand(0)) &&
13204       isNullConstant(AddeNode->getOperand(1)) &&
13205       (AddeNode->getOperand(2).getNode() == AddcNode))
13206     return DAG.getNode(ARMISD::UMAAL, SDLoc(N),
13207                        DAG.getVTList(MVT::i32, MVT::i32),
13208                        {N->getOperand(0), N->getOperand(1),
13209                         AddcNode->getOperand(0), AddcNode->getOperand(1)});
13210   else
13211     return SDValue();
13212 }
13213 
PerformAddcSubcCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI,const ARMSubtarget * Subtarget)13214 static SDValue PerformAddcSubcCombine(SDNode *N,
13215                                       TargetLowering::DAGCombinerInfo &DCI,
13216                                       const ARMSubtarget *Subtarget) {
13217   SelectionDAG &DAG(DCI.DAG);
13218 
13219   if (N->getOpcode() == ARMISD::SUBC && N->hasAnyUseOfValue(1)) {
13220     // (SUBC (ADDE 0, 0, C), 1) -> C
13221     SDValue LHS = N->getOperand(0);
13222     SDValue RHS = N->getOperand(1);
13223     if (LHS->getOpcode() == ARMISD::ADDE &&
13224         isNullConstant(LHS->getOperand(0)) &&
13225         isNullConstant(LHS->getOperand(1)) && isOneConstant(RHS)) {
13226       return DCI.CombineTo(N, SDValue(N, 0), LHS->getOperand(2));
13227     }
13228   }
13229 
13230   if (Subtarget->isThumb1Only()) {
13231     SDValue RHS = N->getOperand(1);
13232     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) {
13233       int32_t imm = C->getSExtValue();
13234       if (imm < 0 && imm > std::numeric_limits<int>::min()) {
13235         SDLoc DL(N);
13236         RHS = DAG.getConstant(-imm, DL, MVT::i32);
13237         unsigned Opcode = (N->getOpcode() == ARMISD::ADDC) ? ARMISD::SUBC
13238                                                            : ARMISD::ADDC;
13239         return DAG.getNode(Opcode, DL, N->getVTList(), N->getOperand(0), RHS);
13240       }
13241     }
13242   }
13243 
13244   return SDValue();
13245 }
13246 
PerformAddeSubeCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI,const ARMSubtarget * Subtarget)13247 static SDValue PerformAddeSubeCombine(SDNode *N,
13248                                       TargetLowering::DAGCombinerInfo &DCI,
13249                                       const ARMSubtarget *Subtarget) {
13250   if (Subtarget->isThumb1Only()) {
13251     SelectionDAG &DAG = DCI.DAG;
13252     SDValue RHS = N->getOperand(1);
13253     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) {
13254       int64_t imm = C->getSExtValue();
13255       if (imm < 0) {
13256         SDLoc DL(N);
13257 
13258         // The with-carry-in form matches bitwise not instead of the negation.
13259         // Effectively, the inverse interpretation of the carry flag already
13260         // accounts for part of the negation.
13261         RHS = DAG.getConstant(~imm, DL, MVT::i32);
13262 
13263         unsigned Opcode = (N->getOpcode() == ARMISD::ADDE) ? ARMISD::SUBE
13264                                                            : ARMISD::ADDE;
13265         return DAG.getNode(Opcode, DL, N->getVTList(),
13266                            N->getOperand(0), RHS, N->getOperand(2));
13267       }
13268     }
13269   } else if (N->getOperand(1)->getOpcode() == ISD::SMUL_LOHI) {
13270     return AddCombineTo64bitMLAL(N, DCI, Subtarget);
13271   }
13272   return SDValue();
13273 }
13274 
PerformSELECTCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI,const ARMSubtarget * Subtarget)13275 static SDValue PerformSELECTCombine(SDNode *N,
13276                                     TargetLowering::DAGCombinerInfo &DCI,
13277                                     const ARMSubtarget *Subtarget) {
13278   if (!Subtarget->hasMVEIntegerOps())
13279     return SDValue();
13280 
13281   SDLoc dl(N);
13282   SDValue SetCC;
13283   SDValue LHS;
13284   SDValue RHS;
13285   ISD::CondCode CC;
13286   SDValue TrueVal;
13287   SDValue FalseVal;
13288 
13289   if (N->getOpcode() == ISD::SELECT &&
13290       N->getOperand(0)->getOpcode() == ISD::SETCC) {
13291     SetCC = N->getOperand(0);
13292     LHS = SetCC->getOperand(0);
13293     RHS = SetCC->getOperand(1);
13294     CC = cast<CondCodeSDNode>(SetCC->getOperand(2))->get();
13295     TrueVal = N->getOperand(1);
13296     FalseVal = N->getOperand(2);
13297   } else if (N->getOpcode() == ISD::SELECT_CC) {
13298     LHS = N->getOperand(0);
13299     RHS = N->getOperand(1);
13300     CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
13301     TrueVal = N->getOperand(2);
13302     FalseVal = N->getOperand(3);
13303   } else {
13304     return SDValue();
13305   }
13306 
13307   unsigned int Opcode = 0;
13308   if ((TrueVal->getOpcode() == ISD::VECREDUCE_UMIN ||
13309        FalseVal->getOpcode() == ISD::VECREDUCE_UMIN) &&
13310       (CC == ISD::SETULT || CC == ISD::SETUGT)) {
13311     Opcode = ARMISD::VMINVu;
13312     if (CC == ISD::SETUGT)
13313       std::swap(TrueVal, FalseVal);
13314   } else if ((TrueVal->getOpcode() == ISD::VECREDUCE_SMIN ||
13315               FalseVal->getOpcode() == ISD::VECREDUCE_SMIN) &&
13316              (CC == ISD::SETLT || CC == ISD::SETGT)) {
13317     Opcode = ARMISD::VMINVs;
13318     if (CC == ISD::SETGT)
13319       std::swap(TrueVal, FalseVal);
13320   } else if ((TrueVal->getOpcode() == ISD::VECREDUCE_UMAX ||
13321               FalseVal->getOpcode() == ISD::VECREDUCE_UMAX) &&
13322              (CC == ISD::SETUGT || CC == ISD::SETULT)) {
13323     Opcode = ARMISD::VMAXVu;
13324     if (CC == ISD::SETULT)
13325       std::swap(TrueVal, FalseVal);
13326   } else if ((TrueVal->getOpcode() == ISD::VECREDUCE_SMAX ||
13327               FalseVal->getOpcode() == ISD::VECREDUCE_SMAX) &&
13328              (CC == ISD::SETGT || CC == ISD::SETLT)) {
13329     Opcode = ARMISD::VMAXVs;
13330     if (CC == ISD::SETLT)
13331       std::swap(TrueVal, FalseVal);
13332   } else
13333     return SDValue();
13334 
13335   // Normalise to the right hand side being the vector reduction
13336   switch (TrueVal->getOpcode()) {
13337   case ISD::VECREDUCE_UMIN:
13338   case ISD::VECREDUCE_SMIN:
13339   case ISD::VECREDUCE_UMAX:
13340   case ISD::VECREDUCE_SMAX:
13341     std::swap(LHS, RHS);
13342     std::swap(TrueVal, FalseVal);
13343     break;
13344   }
13345 
13346   EVT VectorType = FalseVal->getOperand(0).getValueType();
13347 
13348   if (VectorType != MVT::v16i8 && VectorType != MVT::v8i16 &&
13349       VectorType != MVT::v4i32)
13350     return SDValue();
13351 
13352   EVT VectorScalarType = VectorType.getVectorElementType();
13353 
13354   // The values being selected must also be the ones being compared
13355   if (TrueVal != LHS || FalseVal != RHS)
13356     return SDValue();
13357 
13358   EVT LeftType = LHS->getValueType(0);
13359   EVT RightType = RHS->getValueType(0);
13360 
13361   // The types must match the reduced type too
13362   if (LeftType != VectorScalarType || RightType != VectorScalarType)
13363     return SDValue();
13364 
13365   // Legalise the scalar to an i32
13366   if (VectorScalarType != MVT::i32)
13367     LHS = DCI.DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
13368 
13369   // Generate the reduction as an i32 for legalisation purposes
13370   auto Reduction =
13371       DCI.DAG.getNode(Opcode, dl, MVT::i32, LHS, RHS->getOperand(0));
13372 
13373   // The result isn't actually an i32 so truncate it back to its original type
13374   if (VectorScalarType != MVT::i32)
13375     Reduction = DCI.DAG.getNode(ISD::TRUNCATE, dl, VectorScalarType, Reduction);
13376 
13377   return Reduction;
13378 }
13379 
13380 // A special combine for the vqdmulh family of instructions. This is one of the
13381 // potential set of patterns that could patch this instruction. The base pattern
13382 // you would expect to be min(max(ashr(mul(mul(sext(x), 2), sext(y)), 16))).
13383 // This matches the different min(max(ashr(mul(mul(sext(x), sext(y)), 2), 16))),
13384 // which llvm will have optimized to min(ashr(mul(sext(x), sext(y)), 15))) as
13385 // the max is unnecessary.
PerformVQDMULHCombine(SDNode * N,SelectionDAG & DAG)13386 static SDValue PerformVQDMULHCombine(SDNode *N, SelectionDAG &DAG) {
13387   EVT VT = N->getValueType(0);
13388   SDValue Shft;
13389   ConstantSDNode *Clamp;
13390 
13391   if (!VT.isVector() || VT.getScalarSizeInBits() > 64)
13392     return SDValue();
13393 
13394   if (N->getOpcode() == ISD::SMIN) {
13395     Shft = N->getOperand(0);
13396     Clamp = isConstOrConstSplat(N->getOperand(1));
13397   } else if (N->getOpcode() == ISD::VSELECT) {
13398     // Detect a SMIN, which for an i64 node will be a vselect/setcc, not a smin.
13399     SDValue Cmp = N->getOperand(0);
13400     if (Cmp.getOpcode() != ISD::SETCC ||
13401         cast<CondCodeSDNode>(Cmp.getOperand(2))->get() != ISD::SETLT ||
13402         Cmp.getOperand(0) != N->getOperand(1) ||
13403         Cmp.getOperand(1) != N->getOperand(2))
13404       return SDValue();
13405     Shft = N->getOperand(1);
13406     Clamp = isConstOrConstSplat(N->getOperand(2));
13407   } else
13408     return SDValue();
13409 
13410   if (!Clamp)
13411     return SDValue();
13412 
13413   MVT ScalarType;
13414   int ShftAmt = 0;
13415   switch (Clamp->getSExtValue()) {
13416   case (1 << 7) - 1:
13417     ScalarType = MVT::i8;
13418     ShftAmt = 7;
13419     break;
13420   case (1 << 15) - 1:
13421     ScalarType = MVT::i16;
13422     ShftAmt = 15;
13423     break;
13424   case (1ULL << 31) - 1:
13425     ScalarType = MVT::i32;
13426     ShftAmt = 31;
13427     break;
13428   default:
13429     return SDValue();
13430   }
13431 
13432   if (Shft.getOpcode() != ISD::SRA)
13433     return SDValue();
13434   ConstantSDNode *N1 = isConstOrConstSplat(Shft.getOperand(1));
13435   if (!N1 || N1->getSExtValue() != ShftAmt)
13436     return SDValue();
13437 
13438   SDValue Mul = Shft.getOperand(0);
13439   if (Mul.getOpcode() != ISD::MUL)
13440     return SDValue();
13441 
13442   SDValue Ext0 = Mul.getOperand(0);
13443   SDValue Ext1 = Mul.getOperand(1);
13444   if (Ext0.getOpcode() != ISD::SIGN_EXTEND ||
13445       Ext1.getOpcode() != ISD::SIGN_EXTEND)
13446     return SDValue();
13447   EVT VecVT = Ext0.getOperand(0).getValueType();
13448   if (!VecVT.isPow2VectorType() || VecVT.getVectorNumElements() == 1)
13449     return SDValue();
13450   if (Ext1.getOperand(0).getValueType() != VecVT ||
13451       VecVT.getScalarType() != ScalarType ||
13452       VT.getScalarSizeInBits() < ScalarType.getScalarSizeInBits() * 2)
13453     return SDValue();
13454 
13455   SDLoc DL(Mul);
13456   unsigned LegalLanes = 128 / (ShftAmt + 1);
13457   EVT LegalVecVT = MVT::getVectorVT(ScalarType, LegalLanes);
13458   // For types smaller than legal vectors extend to be legal and only use needed
13459   // lanes.
13460   if (VecVT.getSizeInBits() < 128) {
13461     EVT ExtVecVT =
13462         MVT::getVectorVT(MVT::getIntegerVT(128 / VecVT.getVectorNumElements()),
13463                          VecVT.getVectorNumElements());
13464     SDValue Inp0 =
13465         DAG.getNode(ISD::ANY_EXTEND, DL, ExtVecVT, Ext0.getOperand(0));
13466     SDValue Inp1 =
13467         DAG.getNode(ISD::ANY_EXTEND, DL, ExtVecVT, Ext1.getOperand(0));
13468     Inp0 = DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, LegalVecVT, Inp0);
13469     Inp1 = DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, LegalVecVT, Inp1);
13470     SDValue VQDMULH = DAG.getNode(ARMISD::VQDMULH, DL, LegalVecVT, Inp0, Inp1);
13471     SDValue Trunc = DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, ExtVecVT, VQDMULH);
13472     Trunc = DAG.getNode(ISD::TRUNCATE, DL, VecVT, Trunc);
13473     return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Trunc);
13474   }
13475 
13476   // For larger types, split into legal sized chunks.
13477   assert(VecVT.getSizeInBits() % 128 == 0 && "Expected a power2 type");
13478   unsigned NumParts = VecVT.getSizeInBits() / 128;
13479   SmallVector<SDValue> Parts;
13480   for (unsigned I = 0; I < NumParts; ++I) {
13481     SDValue Inp0 =
13482         DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, LegalVecVT, Ext0.getOperand(0),
13483                     DAG.getVectorIdxConstant(I * LegalLanes, DL));
13484     SDValue Inp1 =
13485         DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, LegalVecVT, Ext1.getOperand(0),
13486                     DAG.getVectorIdxConstant(I * LegalLanes, DL));
13487     SDValue VQDMULH = DAG.getNode(ARMISD::VQDMULH, DL, LegalVecVT, Inp0, Inp1);
13488     Parts.push_back(VQDMULH);
13489   }
13490   return DAG.getNode(ISD::SIGN_EXTEND, DL, VT,
13491                      DAG.getNode(ISD::CONCAT_VECTORS, DL, VecVT, Parts));
13492 }
13493 
PerformVSELECTCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI,const ARMSubtarget * Subtarget)13494 static SDValue PerformVSELECTCombine(SDNode *N,
13495                                      TargetLowering::DAGCombinerInfo &DCI,
13496                                      const ARMSubtarget *Subtarget) {
13497   if (!Subtarget->hasMVEIntegerOps())
13498     return SDValue();
13499 
13500   if (SDValue V = PerformVQDMULHCombine(N, DCI.DAG))
13501     return V;
13502 
13503   // Transforms vselect(not(cond), lhs, rhs) into vselect(cond, rhs, lhs).
13504   //
13505   // We need to re-implement this optimization here as the implementation in the
13506   // Target-Independent DAGCombiner does not handle the kind of constant we make
13507   // (it calls isConstOrConstSplat with AllowTruncation set to false - and for
13508   // good reason, allowing truncation there would break other targets).
13509   //
13510   // Currently, this is only done for MVE, as it's the only target that benefits
13511   // from this transformation (e.g. VPNOT+VPSEL becomes a single VPSEL).
13512   if (N->getOperand(0).getOpcode() != ISD::XOR)
13513     return SDValue();
13514   SDValue XOR = N->getOperand(0);
13515 
13516   // Check if the XOR's RHS is either a 1, or a BUILD_VECTOR of 1s.
13517   // It is important to check with truncation allowed as the BUILD_VECTORs we
13518   // generate in those situations will truncate their operands.
13519   ConstantSDNode *Const =
13520       isConstOrConstSplat(XOR->getOperand(1), /*AllowUndefs*/ false,
13521                           /*AllowTruncation*/ true);
13522   if (!Const || !Const->isOne())
13523     return SDValue();
13524 
13525   // Rewrite into vselect(cond, rhs, lhs).
13526   SDValue Cond = XOR->getOperand(0);
13527   SDValue LHS = N->getOperand(1);
13528   SDValue RHS = N->getOperand(2);
13529   EVT Type = N->getValueType(0);
13530   return DCI.DAG.getNode(ISD::VSELECT, SDLoc(N), Type, Cond, RHS, LHS);
13531 }
13532 
13533 // Convert vsetcc([0,1,2,..], splat(n), ult) -> vctp n
PerformVSetCCToVCTPCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI,const ARMSubtarget * Subtarget)13534 static SDValue PerformVSetCCToVCTPCombine(SDNode *N,
13535                                           TargetLowering::DAGCombinerInfo &DCI,
13536                                           const ARMSubtarget *Subtarget) {
13537   SDValue Op0 = N->getOperand(0);
13538   SDValue Op1 = N->getOperand(1);
13539   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
13540   EVT VT = N->getValueType(0);
13541 
13542   if (!Subtarget->hasMVEIntegerOps() ||
13543       !DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
13544     return SDValue();
13545 
13546   if (CC == ISD::SETUGE) {
13547     std::swap(Op0, Op1);
13548     CC = ISD::SETULT;
13549   }
13550 
13551   if (CC != ISD::SETULT || VT.getScalarSizeInBits() != 1 ||
13552       Op0.getOpcode() != ISD::BUILD_VECTOR)
13553     return SDValue();
13554 
13555   // Check first operand is BuildVector of 0,1,2,...
13556   for (unsigned I = 0; I < VT.getVectorNumElements(); I++) {
13557     if (!Op0.getOperand(I).isUndef() &&
13558         !(isa<ConstantSDNode>(Op0.getOperand(I)) &&
13559           Op0.getConstantOperandVal(I) == I))
13560       return SDValue();
13561   }
13562 
13563   // The second is a Splat of Op1S
13564   SDValue Op1S = DCI.DAG.getSplatValue(Op1);
13565   if (!Op1S)
13566     return SDValue();
13567 
13568   unsigned Opc;
13569   switch (VT.getVectorNumElements()) {
13570   case 2:
13571     Opc = Intrinsic::arm_mve_vctp64;
13572     break;
13573   case 4:
13574     Opc = Intrinsic::arm_mve_vctp32;
13575     break;
13576   case 8:
13577     Opc = Intrinsic::arm_mve_vctp16;
13578     break;
13579   case 16:
13580     Opc = Intrinsic::arm_mve_vctp8;
13581     break;
13582   default:
13583     return SDValue();
13584   }
13585 
13586   SDLoc DL(N);
13587   return DCI.DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13588                          DCI.DAG.getConstant(Opc, DL, MVT::i32),
13589                          DCI.DAG.getZExtOrTrunc(Op1S, DL, MVT::i32));
13590 }
13591 
13592 /// PerformADDECombine - Target-specific dag combine transform from
13593 /// ARMISD::ADDC, ARMISD::ADDE, and ISD::MUL_LOHI to MLAL or
13594 /// ARMISD::ADDC, ARMISD::ADDE and ARMISD::UMLAL to ARMISD::UMAAL
PerformADDECombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI,const ARMSubtarget * Subtarget)13595 static SDValue PerformADDECombine(SDNode *N,
13596                                   TargetLowering::DAGCombinerInfo &DCI,
13597                                   const ARMSubtarget *Subtarget) {
13598   // Only ARM and Thumb2 support UMLAL/SMLAL.
13599   if (Subtarget->isThumb1Only())
13600     return PerformAddeSubeCombine(N, DCI, Subtarget);
13601 
13602   // Only perform the checks after legalize when the pattern is available.
13603   if (DCI.isBeforeLegalize()) return SDValue();
13604 
13605   return AddCombineTo64bitUMAAL(N, DCI, Subtarget);
13606 }
13607 
13608 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
13609 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
13610 /// called with the default operands, and if that fails, with commuted
13611 /// operands.
PerformADDCombineWithOperands(SDNode * N,SDValue N0,SDValue N1,TargetLowering::DAGCombinerInfo & DCI,const ARMSubtarget * Subtarget)13612 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
13613                                           TargetLowering::DAGCombinerInfo &DCI,
13614                                           const ARMSubtarget *Subtarget){
13615   // Attempt to create vpadd for this add.
13616   if (SDValue Result = AddCombineToVPADD(N, N0, N1, DCI, Subtarget))
13617     return Result;
13618 
13619   // Attempt to create vpaddl for this add.
13620   if (SDValue Result = AddCombineVUZPToVPADDL(N, N0, N1, DCI, Subtarget))
13621     return Result;
13622   if (SDValue Result = AddCombineBUILD_VECTORToVPADDL(N, N0, N1, DCI,
13623                                                       Subtarget))
13624     return Result;
13625 
13626   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
13627   if (N0.getNode()->hasOneUse())
13628     if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI))
13629       return Result;
13630   return SDValue();
13631 }
13632 
TryDistrubutionADDVecReduce(SDNode * N,SelectionDAG & DAG)13633 static SDValue TryDistrubutionADDVecReduce(SDNode *N, SelectionDAG &DAG) {
13634   EVT VT = N->getValueType(0);
13635   SDValue N0 = N->getOperand(0);
13636   SDValue N1 = N->getOperand(1);
13637   SDLoc dl(N);
13638 
13639   auto IsVecReduce = [](SDValue Op) {
13640     switch (Op.getOpcode()) {
13641     case ISD::VECREDUCE_ADD:
13642     case ARMISD::VADDVs:
13643     case ARMISD::VADDVu:
13644     case ARMISD::VMLAVs:
13645     case ARMISD::VMLAVu:
13646       return true;
13647     }
13648     return false;
13649   };
13650 
13651   auto DistrubuteAddAddVecReduce = [&](SDValue N0, SDValue N1) {
13652     // Distribute add(X, add(vecreduce(Y), vecreduce(Z))) ->
13653     //   add(add(X, vecreduce(Y)), vecreduce(Z))
13654     // to make better use of vaddva style instructions.
13655     if (VT == MVT::i32 && N1.getOpcode() == ISD::ADD && !IsVecReduce(N0) &&
13656         IsVecReduce(N1.getOperand(0)) && IsVecReduce(N1.getOperand(1)) &&
13657         !isa<ConstantSDNode>(N0) && N1->hasOneUse()) {
13658       SDValue Add0 = DAG.getNode(ISD::ADD, dl, VT, N0, N1.getOperand(0));
13659       return DAG.getNode(ISD::ADD, dl, VT, Add0, N1.getOperand(1));
13660     }
13661     // And turn add(add(A, reduce(B)), add(C, reduce(D))) ->
13662     //   add(add(add(A, C), reduce(B)), reduce(D))
13663     if (VT == MVT::i32 && N0.getOpcode() == ISD::ADD &&
13664         N1.getOpcode() == ISD::ADD && N0->hasOneUse() && N1->hasOneUse()) {
13665       unsigned N0RedOp = 0;
13666       if (!IsVecReduce(N0.getOperand(N0RedOp))) {
13667         N0RedOp = 1;
13668         if (!IsVecReduce(N0.getOperand(N0RedOp)))
13669           return SDValue();
13670       }
13671 
13672       unsigned N1RedOp = 0;
13673       if (!IsVecReduce(N1.getOperand(N1RedOp)))
13674         N1RedOp = 1;
13675       if (!IsVecReduce(N1.getOperand(N1RedOp)))
13676         return SDValue();
13677 
13678       SDValue Add0 = DAG.getNode(ISD::ADD, dl, VT, N0.getOperand(1 - N0RedOp),
13679                                  N1.getOperand(1 - N1RedOp));
13680       SDValue Add1 =
13681           DAG.getNode(ISD::ADD, dl, VT, Add0, N0.getOperand(N0RedOp));
13682       return DAG.getNode(ISD::ADD, dl, VT, Add1, N1.getOperand(N1RedOp));
13683     }
13684     return SDValue();
13685   };
13686   if (SDValue R = DistrubuteAddAddVecReduce(N0, N1))
13687     return R;
13688   if (SDValue R = DistrubuteAddAddVecReduce(N1, N0))
13689     return R;
13690 
13691   // Distribute add(vecreduce(load(Y)), vecreduce(load(Z)))
13692   // Or add(add(X, vecreduce(load(Y))), vecreduce(load(Z)))
13693   // by ascending load offsets. This can help cores prefetch if the order of
13694   // loads is more predictable.
13695   auto DistrubuteVecReduceLoad = [&](SDValue N0, SDValue N1, bool IsForward) {
13696     // Check if two reductions are known to load data where one is before/after
13697     // another. Return negative if N0 loads data before N1, positive if N1 is
13698     // before N0 and 0 otherwise if nothing is known.
13699     auto IsKnownOrderedLoad = [&](SDValue N0, SDValue N1) {
13700       // Look through to the first operand of a MUL, for the VMLA case.
13701       // Currently only looks at the first operand, in the hope they are equal.
13702       if (N0.getOpcode() == ISD::MUL)
13703         N0 = N0.getOperand(0);
13704       if (N1.getOpcode() == ISD::MUL)
13705         N1 = N1.getOperand(0);
13706 
13707       // Return true if the two operands are loads to the same object and the
13708       // offset of the first is known to be less than the offset of the second.
13709       LoadSDNode *Load0 = dyn_cast<LoadSDNode>(N0);
13710       LoadSDNode *Load1 = dyn_cast<LoadSDNode>(N1);
13711       if (!Load0 || !Load1 || Load0->getChain() != Load1->getChain() ||
13712           !Load0->isSimple() || !Load1->isSimple() || Load0->isIndexed() ||
13713           Load1->isIndexed())
13714         return 0;
13715 
13716       auto BaseLocDecomp0 = BaseIndexOffset::match(Load0, DAG);
13717       auto BaseLocDecomp1 = BaseIndexOffset::match(Load1, DAG);
13718 
13719       if (!BaseLocDecomp0.getBase() ||
13720           BaseLocDecomp0.getBase() != BaseLocDecomp1.getBase() ||
13721           !BaseLocDecomp0.hasValidOffset() || !BaseLocDecomp1.hasValidOffset())
13722         return 0;
13723       if (BaseLocDecomp0.getOffset() < BaseLocDecomp1.getOffset())
13724         return -1;
13725       if (BaseLocDecomp0.getOffset() > BaseLocDecomp1.getOffset())
13726         return 1;
13727       return 0;
13728     };
13729 
13730     SDValue X;
13731     if (N0.getOpcode() == ISD::ADD && N0->hasOneUse()) {
13732       if (IsVecReduce(N0.getOperand(0)) && IsVecReduce(N0.getOperand(1))) {
13733         int IsBefore = IsKnownOrderedLoad(N0.getOperand(0).getOperand(0),
13734                                          N0.getOperand(1).getOperand(0));
13735         if (IsBefore < 0) {
13736           X = N0.getOperand(0);
13737           N0 = N0.getOperand(1);
13738         } else if (IsBefore > 0) {
13739           X = N0.getOperand(1);
13740           N0 = N0.getOperand(0);
13741         } else
13742           return SDValue();
13743       } else if (IsVecReduce(N0.getOperand(0))) {
13744         X = N0.getOperand(1);
13745         N0 = N0.getOperand(0);
13746       } else if (IsVecReduce(N0.getOperand(1))) {
13747         X = N0.getOperand(0);
13748         N0 = N0.getOperand(1);
13749       } else
13750         return SDValue();
13751     } else if (IsForward && IsVecReduce(N0) && IsVecReduce(N1) &&
13752                IsKnownOrderedLoad(N0.getOperand(0), N1.getOperand(0)) < 0) {
13753       // Note this is backward to how you would expect. We create
13754       // add(reduce(load + 16), reduce(load + 0)) so that the
13755       // add(reduce(load+16), X) is combined into VADDVA(X, load+16)), leaving
13756       // the X as VADDV(load + 0)
13757       return DAG.getNode(ISD::ADD, dl, VT, N1, N0);
13758     } else
13759       return SDValue();
13760 
13761     if (!IsVecReduce(N0) || !IsVecReduce(N1))
13762       return SDValue();
13763 
13764     if (IsKnownOrderedLoad(N1.getOperand(0), N0.getOperand(0)) >= 0)
13765       return SDValue();
13766 
13767     // Switch from add(add(X, N0), N1) to add(add(X, N1), N0)
13768     SDValue Add0 = DAG.getNode(ISD::ADD, dl, VT, X, N1);
13769     return DAG.getNode(ISD::ADD, dl, VT, Add0, N0);
13770   };
13771   if (SDValue R = DistrubuteVecReduceLoad(N0, N1, true))
13772     return R;
13773   if (SDValue R = DistrubuteVecReduceLoad(N1, N0, false))
13774     return R;
13775   return SDValue();
13776 }
13777 
PerformADDVecReduce(SDNode * N,SelectionDAG & DAG,const ARMSubtarget * Subtarget)13778 static SDValue PerformADDVecReduce(SDNode *N, SelectionDAG &DAG,
13779                                    const ARMSubtarget *Subtarget) {
13780   if (!Subtarget->hasMVEIntegerOps())
13781     return SDValue();
13782 
13783   if (SDValue R = TryDistrubutionADDVecReduce(N, DAG))
13784     return R;
13785 
13786   EVT VT = N->getValueType(0);
13787   SDValue N0 = N->getOperand(0);
13788   SDValue N1 = N->getOperand(1);
13789   SDLoc dl(N);
13790 
13791   if (VT != MVT::i64)
13792     return SDValue();
13793 
13794   // We are looking for a i64 add of a VADDLVx. Due to these being i64's, this
13795   // will look like:
13796   //   t1: i32,i32 = ARMISD::VADDLVs x
13797   //   t2: i64 = build_pair t1, t1:1
13798   //   t3: i64 = add t2, y
13799   // Otherwise we try to push the add up above VADDLVAx, to potentially allow
13800   // the add to be simplified separately.
13801   // We also need to check for sext / zext and commutitive adds.
13802   auto MakeVecReduce = [&](unsigned Opcode, unsigned OpcodeA, SDValue NA,
13803                            SDValue NB) {
13804     if (NB->getOpcode() != ISD::BUILD_PAIR)
13805       return SDValue();
13806     SDValue VecRed = NB->getOperand(0);
13807     if ((VecRed->getOpcode() != Opcode && VecRed->getOpcode() != OpcodeA) ||
13808         VecRed.getResNo() != 0 ||
13809         NB->getOperand(1) != SDValue(VecRed.getNode(), 1))
13810       return SDValue();
13811 
13812     if (VecRed->getOpcode() == OpcodeA) {
13813       // add(NA, VADDLVA(Inp), Y) -> VADDLVA(add(NA, Inp), Y)
13814       SDValue Inp = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64,
13815                                 VecRed.getOperand(0), VecRed.getOperand(1));
13816       NA = DAG.getNode(ISD::ADD, dl, MVT::i64, Inp, NA);
13817     }
13818 
13819     SmallVector<SDValue, 4> Ops(2);
13820     std::tie(Ops[0], Ops[1]) = DAG.SplitScalar(NA, dl, MVT::i32, MVT::i32);
13821 
13822     unsigned S = VecRed->getOpcode() == OpcodeA ? 2 : 0;
13823     for (unsigned I = S, E = VecRed.getNumOperands(); I < E; I++)
13824       Ops.push_back(VecRed->getOperand(I));
13825     SDValue Red =
13826         DAG.getNode(OpcodeA, dl, DAG.getVTList({MVT::i32, MVT::i32}), Ops);
13827     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Red,
13828                        SDValue(Red.getNode(), 1));
13829   };
13830 
13831   if (SDValue M = MakeVecReduce(ARMISD::VADDLVs, ARMISD::VADDLVAs, N0, N1))
13832     return M;
13833   if (SDValue M = MakeVecReduce(ARMISD::VADDLVu, ARMISD::VADDLVAu, N0, N1))
13834     return M;
13835   if (SDValue M = MakeVecReduce(ARMISD::VADDLVs, ARMISD::VADDLVAs, N1, N0))
13836     return M;
13837   if (SDValue M = MakeVecReduce(ARMISD::VADDLVu, ARMISD::VADDLVAu, N1, N0))
13838     return M;
13839   if (SDValue M = MakeVecReduce(ARMISD::VADDLVps, ARMISD::VADDLVAps, N0, N1))
13840     return M;
13841   if (SDValue M = MakeVecReduce(ARMISD::VADDLVpu, ARMISD::VADDLVApu, N0, N1))
13842     return M;
13843   if (SDValue M = MakeVecReduce(ARMISD::VADDLVps, ARMISD::VADDLVAps, N1, N0))
13844     return M;
13845   if (SDValue M = MakeVecReduce(ARMISD::VADDLVpu, ARMISD::VADDLVApu, N1, N0))
13846     return M;
13847   if (SDValue M = MakeVecReduce(ARMISD::VMLALVs, ARMISD::VMLALVAs, N0, N1))
13848     return M;
13849   if (SDValue M = MakeVecReduce(ARMISD::VMLALVu, ARMISD::VMLALVAu, N0, N1))
13850     return M;
13851   if (SDValue M = MakeVecReduce(ARMISD::VMLALVs, ARMISD::VMLALVAs, N1, N0))
13852     return M;
13853   if (SDValue M = MakeVecReduce(ARMISD::VMLALVu, ARMISD::VMLALVAu, N1, N0))
13854     return M;
13855   if (SDValue M = MakeVecReduce(ARMISD::VMLALVps, ARMISD::VMLALVAps, N0, N1))
13856     return M;
13857   if (SDValue M = MakeVecReduce(ARMISD::VMLALVpu, ARMISD::VMLALVApu, N0, N1))
13858     return M;
13859   if (SDValue M = MakeVecReduce(ARMISD::VMLALVps, ARMISD::VMLALVAps, N1, N0))
13860     return M;
13861   if (SDValue M = MakeVecReduce(ARMISD::VMLALVpu, ARMISD::VMLALVApu, N1, N0))
13862     return M;
13863   return SDValue();
13864 }
13865 
13866 bool
isDesirableToCommuteWithShift(const SDNode * N,CombineLevel Level) const13867 ARMTargetLowering::isDesirableToCommuteWithShift(const SDNode *N,
13868                                                  CombineLevel Level) const {
13869   assert((N->getOpcode() == ISD::SHL || N->getOpcode() == ISD::SRA ||
13870           N->getOpcode() == ISD::SRL) &&
13871          "Expected shift op");
13872 
13873   SDValue ShiftLHS = N->getOperand(0);
13874   if (!ShiftLHS->hasOneUse())
13875     return false;
13876 
13877   if (ShiftLHS.getOpcode() == ISD::SIGN_EXTEND &&
13878       !ShiftLHS.getOperand(0)->hasOneUse())
13879     return false;
13880 
13881   if (Level == BeforeLegalizeTypes)
13882     return true;
13883 
13884   if (N->getOpcode() != ISD::SHL)
13885     return true;
13886 
13887   if (Subtarget->isThumb1Only()) {
13888     // Avoid making expensive immediates by commuting shifts. (This logic
13889     // only applies to Thumb1 because ARM and Thumb2 immediates can be shifted
13890     // for free.)
13891     if (N->getOpcode() != ISD::SHL)
13892       return true;
13893     SDValue N1 = N->getOperand(0);
13894     if (N1->getOpcode() != ISD::ADD && N1->getOpcode() != ISD::AND &&
13895         N1->getOpcode() != ISD::OR && N1->getOpcode() != ISD::XOR)
13896       return true;
13897     if (auto *Const = dyn_cast<ConstantSDNode>(N1->getOperand(1))) {
13898       if (Const->getAPIntValue().ult(256))
13899         return false;
13900       if (N1->getOpcode() == ISD::ADD && Const->getAPIntValue().slt(0) &&
13901           Const->getAPIntValue().sgt(-256))
13902         return false;
13903     }
13904     return true;
13905   }
13906 
13907   // Turn off commute-with-shift transform after legalization, so it doesn't
13908   // conflict with PerformSHLSimplify.  (We could try to detect when
13909   // PerformSHLSimplify would trigger more precisely, but it isn't
13910   // really necessary.)
13911   return false;
13912 }
13913 
isDesirableToCommuteXorWithShift(const SDNode * N) const13914 bool ARMTargetLowering::isDesirableToCommuteXorWithShift(
13915     const SDNode *N) const {
13916   assert(N->getOpcode() == ISD::XOR &&
13917          (N->getOperand(0).getOpcode() == ISD::SHL ||
13918           N->getOperand(0).getOpcode() == ISD::SRL) &&
13919          "Expected XOR(SHIFT) pattern");
13920 
13921   // Only commute if the entire NOT mask is a hidden shifted mask.
13922   auto *XorC = dyn_cast<ConstantSDNode>(N->getOperand(1));
13923   auto *ShiftC = dyn_cast<ConstantSDNode>(N->getOperand(0).getOperand(1));
13924   if (XorC && ShiftC) {
13925     unsigned MaskIdx, MaskLen;
13926     if (XorC->getAPIntValue().isShiftedMask(MaskIdx, MaskLen)) {
13927       unsigned ShiftAmt = ShiftC->getZExtValue();
13928       unsigned BitWidth = N->getValueType(0).getScalarSizeInBits();
13929       if (N->getOperand(0).getOpcode() == ISD::SHL)
13930         return MaskIdx == ShiftAmt && MaskLen == (BitWidth - ShiftAmt);
13931       return MaskIdx == 0 && MaskLen == (BitWidth - ShiftAmt);
13932     }
13933   }
13934 
13935   return false;
13936 }
13937 
shouldFoldConstantShiftPairToMask(const SDNode * N,CombineLevel Level) const13938 bool ARMTargetLowering::shouldFoldConstantShiftPairToMask(
13939     const SDNode *N, CombineLevel Level) const {
13940   assert(((N->getOpcode() == ISD::SHL &&
13941            N->getOperand(0).getOpcode() == ISD::SRL) ||
13942           (N->getOpcode() == ISD::SRL &&
13943            N->getOperand(0).getOpcode() == ISD::SHL)) &&
13944          "Expected shift-shift mask");
13945 
13946   if (!Subtarget->isThumb1Only())
13947     return true;
13948 
13949   if (Level == BeforeLegalizeTypes)
13950     return true;
13951 
13952   return false;
13953 }
13954 
shouldFoldSelectWithIdentityConstant(unsigned BinOpcode,EVT VT,unsigned SelectOpcode,SDValue X,SDValue Y) const13955 bool ARMTargetLowering::shouldFoldSelectWithIdentityConstant(
13956     unsigned BinOpcode, EVT VT, unsigned SelectOpcode, SDValue X,
13957     SDValue Y) const {
13958   return Subtarget->hasMVEIntegerOps() && isTypeLegal(VT) &&
13959          SelectOpcode == ISD::VSELECT;
13960 }
13961 
preferIncOfAddToSubOfNot(EVT VT) const13962 bool ARMTargetLowering::preferIncOfAddToSubOfNot(EVT VT) const {
13963   if (!Subtarget->hasNEON()) {
13964     if (Subtarget->isThumb1Only())
13965       return VT.getScalarSizeInBits() <= 32;
13966     return true;
13967   }
13968   return VT.isScalarInteger();
13969 }
13970 
shouldConvertFpToSat(unsigned Op,EVT FPVT,EVT VT) const13971 bool ARMTargetLowering::shouldConvertFpToSat(unsigned Op, EVT FPVT,
13972                                              EVT VT) const {
13973   if (!isOperationLegalOrCustom(Op, VT) || !FPVT.isSimple())
13974     return false;
13975 
13976   switch (FPVT.getSimpleVT().SimpleTy) {
13977   case MVT::f16:
13978     return Subtarget->hasVFP2Base();
13979   case MVT::f32:
13980     return Subtarget->hasVFP2Base();
13981   case MVT::f64:
13982     return Subtarget->hasFP64();
13983   case MVT::v4f32:
13984   case MVT::v8f16:
13985     return Subtarget->hasMVEFloatOps();
13986   default:
13987     return false;
13988   }
13989 }
13990 
PerformSHLSimplify(SDNode * N,TargetLowering::DAGCombinerInfo & DCI,const ARMSubtarget * ST)13991 static SDValue PerformSHLSimplify(SDNode *N,
13992                                 TargetLowering::DAGCombinerInfo &DCI,
13993                                 const ARMSubtarget *ST) {
13994   // Allow the generic combiner to identify potential bswaps.
13995   if (DCI.isBeforeLegalize())
13996     return SDValue();
13997 
13998   // DAG combiner will fold:
13999   // (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
14000   // (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2
14001   // Other code patterns that can be also be modified have the following form:
14002   // b + ((a << 1) | 510)
14003   // b + ((a << 1) & 510)
14004   // b + ((a << 1) ^ 510)
14005   // b + ((a << 1) + 510)
14006 
14007   // Many instructions can  perform the shift for free, but it requires both
14008   // the operands to be registers. If c1 << c2 is too large, a mov immediate
14009   // instruction will needed. So, unfold back to the original pattern if:
14010   // - if c1 and c2 are small enough that they don't require mov imms.
14011   // - the user(s) of the node can perform an shl
14012 
14013   // No shifted operands for 16-bit instructions.
14014   if (ST->isThumb() && ST->isThumb1Only())
14015     return SDValue();
14016 
14017   // Check that all the users could perform the shl themselves.
14018   for (auto *U : N->users()) {
14019     switch(U->getOpcode()) {
14020     default:
14021       return SDValue();
14022     case ISD::SUB:
14023     case ISD::ADD:
14024     case ISD::AND:
14025     case ISD::OR:
14026     case ISD::XOR:
14027     case ISD::SETCC:
14028     case ARMISD::CMP:
14029       // Check that the user isn't already using a constant because there
14030       // aren't any instructions that support an immediate operand and a
14031       // shifted operand.
14032       if (isa<ConstantSDNode>(U->getOperand(0)) ||
14033           isa<ConstantSDNode>(U->getOperand(1)))
14034         return SDValue();
14035 
14036       // Check that it's not already using a shift.
14037       if (U->getOperand(0).getOpcode() == ISD::SHL ||
14038           U->getOperand(1).getOpcode() == ISD::SHL)
14039         return SDValue();
14040       break;
14041     }
14042   }
14043 
14044   if (N->getOpcode() != ISD::ADD && N->getOpcode() != ISD::OR &&
14045       N->getOpcode() != ISD::XOR && N->getOpcode() != ISD::AND)
14046     return SDValue();
14047 
14048   if (N->getOperand(0).getOpcode() != ISD::SHL)
14049     return SDValue();
14050 
14051   SDValue SHL = N->getOperand(0);
14052 
14053   auto *C1ShlC2 = dyn_cast<ConstantSDNode>(N->getOperand(1));
14054   auto *C2 = dyn_cast<ConstantSDNode>(SHL.getOperand(1));
14055   if (!C1ShlC2 || !C2)
14056     return SDValue();
14057 
14058   APInt C2Int = C2->getAPIntValue();
14059   APInt C1Int = C1ShlC2->getAPIntValue();
14060   unsigned C2Width = C2Int.getBitWidth();
14061   if (C2Int.uge(C2Width))
14062     return SDValue();
14063   uint64_t C2Value = C2Int.getZExtValue();
14064 
14065   // Check that performing a lshr will not lose any information.
14066   APInt Mask = APInt::getHighBitsSet(C2Width, C2Width - C2Value);
14067   if ((C1Int & Mask) != C1Int)
14068     return SDValue();
14069 
14070   // Shift the first constant.
14071   C1Int.lshrInPlace(C2Int);
14072 
14073   // The immediates are encoded as an 8-bit value that can be rotated.
14074   auto LargeImm = [](const APInt &Imm) {
14075     unsigned Zeros = Imm.countl_zero() + Imm.countr_zero();
14076     return Imm.getBitWidth() - Zeros > 8;
14077   };
14078 
14079   if (LargeImm(C1Int) || LargeImm(C2Int))
14080     return SDValue();
14081 
14082   SelectionDAG &DAG = DCI.DAG;
14083   SDLoc dl(N);
14084   SDValue X = SHL.getOperand(0);
14085   SDValue BinOp = DAG.getNode(N->getOpcode(), dl, MVT::i32, X,
14086                               DAG.getConstant(C1Int, dl, MVT::i32));
14087   // Shift left to compensate for the lshr of C1Int.
14088   SDValue Res = DAG.getNode(ISD::SHL, dl, MVT::i32, BinOp, SHL.getOperand(1));
14089 
14090   LLVM_DEBUG(dbgs() << "Simplify shl use:\n"; SHL.getOperand(0).dump();
14091              SHL.dump(); N->dump());
14092   LLVM_DEBUG(dbgs() << "Into:\n"; X.dump(); BinOp.dump(); Res.dump());
14093   return Res;
14094 }
14095 
14096 
14097 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
14098 ///
PerformADDCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI,const ARMSubtarget * Subtarget)14099 static SDValue PerformADDCombine(SDNode *N,
14100                                  TargetLowering::DAGCombinerInfo &DCI,
14101                                  const ARMSubtarget *Subtarget) {
14102   SDValue N0 = N->getOperand(0);
14103   SDValue N1 = N->getOperand(1);
14104 
14105   // Only works one way, because it needs an immediate operand.
14106   if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
14107     return Result;
14108 
14109   if (SDValue Result = PerformADDVecReduce(N, DCI.DAG, Subtarget))
14110     return Result;
14111 
14112   // First try with the default operand order.
14113   if (SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget))
14114     return Result;
14115 
14116   // If that didn't work, try again with the operands commuted.
14117   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
14118 }
14119 
14120 // Combine (sub 0, (csinc X, Y, CC)) -> (csinv -X, Y, CC)
14121 //   providing -X is as cheap as X (currently, just a constant).
PerformSubCSINCCombine(SDNode * N,SelectionDAG & DAG)14122 static SDValue PerformSubCSINCCombine(SDNode *N, SelectionDAG &DAG) {
14123   if (N->getValueType(0) != MVT::i32 || !isNullConstant(N->getOperand(0)))
14124     return SDValue();
14125   SDValue CSINC = N->getOperand(1);
14126   if (CSINC.getOpcode() != ARMISD::CSINC || !CSINC.hasOneUse())
14127     return SDValue();
14128 
14129   ConstantSDNode *X = dyn_cast<ConstantSDNode>(CSINC.getOperand(0));
14130   if (!X)
14131     return SDValue();
14132 
14133   return DAG.getNode(ARMISD::CSINV, SDLoc(N), MVT::i32,
14134                      DAG.getNode(ISD::SUB, SDLoc(N), MVT::i32, N->getOperand(0),
14135                                  CSINC.getOperand(0)),
14136                      CSINC.getOperand(1), CSINC.getOperand(2),
14137                      CSINC.getOperand(3));
14138 }
14139 
14140 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
14141 ///
PerformSUBCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI,const ARMSubtarget * Subtarget)14142 static SDValue PerformSUBCombine(SDNode *N,
14143                                  TargetLowering::DAGCombinerInfo &DCI,
14144                                  const ARMSubtarget *Subtarget) {
14145   SDValue N0 = N->getOperand(0);
14146   SDValue N1 = N->getOperand(1);
14147 
14148   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
14149   if (N1.getNode()->hasOneUse())
14150     if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI))
14151       return Result;
14152 
14153   if (SDValue R = PerformSubCSINCCombine(N, DCI.DAG))
14154     return R;
14155 
14156   if (!Subtarget->hasMVEIntegerOps() || !N->getValueType(0).isVector())
14157     return SDValue();
14158 
14159   // Fold (sub (ARMvmovImm 0), (ARMvdup x)) -> (ARMvdup (sub 0, x))
14160   // so that we can readily pattern match more mve instructions which can use
14161   // a scalar operand.
14162   SDValue VDup = N->getOperand(1);
14163   if (VDup->getOpcode() != ARMISD::VDUP)
14164     return SDValue();
14165 
14166   SDValue VMov = N->getOperand(0);
14167   if (VMov->getOpcode() == ISD::BITCAST)
14168     VMov = VMov->getOperand(0);
14169 
14170   if (VMov->getOpcode() != ARMISD::VMOVIMM || !isZeroVector(VMov))
14171     return SDValue();
14172 
14173   SDLoc dl(N);
14174   SDValue Negate = DCI.DAG.getNode(ISD::SUB, dl, MVT::i32,
14175                                    DCI.DAG.getConstant(0, dl, MVT::i32),
14176                                    VDup->getOperand(0));
14177   return DCI.DAG.getNode(ARMISD::VDUP, dl, N->getValueType(0), Negate);
14178 }
14179 
14180 /// PerformVMULCombine
14181 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
14182 /// special multiplier accumulator forwarding.
14183 ///   vmul d3, d0, d2
14184 ///   vmla d3, d1, d2
14185 /// is faster than
14186 ///   vadd d3, d0, d1
14187 ///   vmul d3, d3, d2
14188 //  However, for (A + B) * (A + B),
14189 //    vadd d2, d0, d1
14190 //    vmul d3, d0, d2
14191 //    vmla d3, d1, d2
14192 //  is slower than
14193 //    vadd d2, d0, d1
14194 //    vmul d3, d2, d2
PerformVMULCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI,const ARMSubtarget * Subtarget)14195 static SDValue PerformVMULCombine(SDNode *N,
14196                                   TargetLowering::DAGCombinerInfo &DCI,
14197                                   const ARMSubtarget *Subtarget) {
14198   if (!Subtarget->hasVMLxForwarding())
14199     return SDValue();
14200 
14201   SelectionDAG &DAG = DCI.DAG;
14202   SDValue N0 = N->getOperand(0);
14203   SDValue N1 = N->getOperand(1);
14204   unsigned Opcode = N0.getOpcode();
14205   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
14206       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
14207     Opcode = N1.getOpcode();
14208     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
14209         Opcode != ISD::FADD && Opcode != ISD::FSUB)
14210       return SDValue();
14211     std::swap(N0, N1);
14212   }
14213 
14214   if (N0 == N1)
14215     return SDValue();
14216 
14217   EVT VT = N->getValueType(0);
14218   SDLoc DL(N);
14219   SDValue N00 = N0->getOperand(0);
14220   SDValue N01 = N0->getOperand(1);
14221   return DAG.getNode(Opcode, DL, VT,
14222                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
14223                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
14224 }
14225 
PerformMVEVMULLCombine(SDNode * N,SelectionDAG & DAG,const ARMSubtarget * Subtarget)14226 static SDValue PerformMVEVMULLCombine(SDNode *N, SelectionDAG &DAG,
14227                                       const ARMSubtarget *Subtarget) {
14228   EVT VT = N->getValueType(0);
14229   if (VT != MVT::v2i64)
14230     return SDValue();
14231 
14232   SDValue N0 = N->getOperand(0);
14233   SDValue N1 = N->getOperand(1);
14234 
14235   auto IsSignExt = [&](SDValue Op) {
14236     if (Op->getOpcode() != ISD::SIGN_EXTEND_INREG)
14237       return SDValue();
14238     EVT VT = cast<VTSDNode>(Op->getOperand(1))->getVT();
14239     if (VT.getScalarSizeInBits() == 32)
14240       return Op->getOperand(0);
14241     return SDValue();
14242   };
14243   auto IsZeroExt = [&](SDValue Op) {
14244     // Zero extends are a little more awkward. At the point we are matching
14245     // this, we are looking for an AND with a (-1, 0, -1, 0) buildvector mask.
14246     // That might be before of after a bitcast depending on how the and is
14247     // placed. Because this has to look through bitcasts, it is currently only
14248     // supported on LE.
14249     if (!Subtarget->isLittle())
14250       return SDValue();
14251 
14252     SDValue And = Op;
14253     if (And->getOpcode() == ISD::BITCAST)
14254       And = And->getOperand(0);
14255     if (And->getOpcode() != ISD::AND)
14256       return SDValue();
14257     SDValue Mask = And->getOperand(1);
14258     if (Mask->getOpcode() == ISD::BITCAST)
14259       Mask = Mask->getOperand(0);
14260 
14261     if (Mask->getOpcode() != ISD::BUILD_VECTOR ||
14262         Mask.getValueType() != MVT::v4i32)
14263       return SDValue();
14264     if (isAllOnesConstant(Mask->getOperand(0)) &&
14265         isNullConstant(Mask->getOperand(1)) &&
14266         isAllOnesConstant(Mask->getOperand(2)) &&
14267         isNullConstant(Mask->getOperand(3)))
14268       return And->getOperand(0);
14269     return SDValue();
14270   };
14271 
14272   SDLoc dl(N);
14273   if (SDValue Op0 = IsSignExt(N0)) {
14274     if (SDValue Op1 = IsSignExt(N1)) {
14275       SDValue New0a = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, MVT::v4i32, Op0);
14276       SDValue New1a = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, MVT::v4i32, Op1);
14277       return DAG.getNode(ARMISD::VMULLs, dl, VT, New0a, New1a);
14278     }
14279   }
14280   if (SDValue Op0 = IsZeroExt(N0)) {
14281     if (SDValue Op1 = IsZeroExt(N1)) {
14282       SDValue New0a = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, MVT::v4i32, Op0);
14283       SDValue New1a = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, MVT::v4i32, Op1);
14284       return DAG.getNode(ARMISD::VMULLu, dl, VT, New0a, New1a);
14285     }
14286   }
14287 
14288   return SDValue();
14289 }
14290 
PerformMULCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI,const ARMSubtarget * Subtarget)14291 static SDValue PerformMULCombine(SDNode *N,
14292                                  TargetLowering::DAGCombinerInfo &DCI,
14293                                  const ARMSubtarget *Subtarget) {
14294   SelectionDAG &DAG = DCI.DAG;
14295 
14296   EVT VT = N->getValueType(0);
14297   if (Subtarget->hasMVEIntegerOps() && VT == MVT::v2i64)
14298     return PerformMVEVMULLCombine(N, DAG, Subtarget);
14299 
14300   if (Subtarget->isThumb1Only())
14301     return SDValue();
14302 
14303   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
14304     return SDValue();
14305 
14306   if (VT.is64BitVector() || VT.is128BitVector())
14307     return PerformVMULCombine(N, DCI, Subtarget);
14308   if (VT != MVT::i32)
14309     return SDValue();
14310 
14311   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
14312   if (!C)
14313     return SDValue();
14314 
14315   int64_t MulAmt = C->getSExtValue();
14316   unsigned ShiftAmt = llvm::countr_zero<uint64_t>(MulAmt);
14317 
14318   ShiftAmt = ShiftAmt & (32 - 1);
14319   SDValue V = N->getOperand(0);
14320   SDLoc DL(N);
14321 
14322   SDValue Res;
14323   MulAmt >>= ShiftAmt;
14324 
14325   if (MulAmt >= 0) {
14326     if (llvm::has_single_bit<uint32_t>(MulAmt - 1)) {
14327       // (mul x, 2^N + 1) => (add (shl x, N), x)
14328       Res = DAG.getNode(ISD::ADD, DL, VT,
14329                         V,
14330                         DAG.getNode(ISD::SHL, DL, VT,
14331                                     V,
14332                                     DAG.getConstant(Log2_32(MulAmt - 1), DL,
14333                                                     MVT::i32)));
14334     } else if (llvm::has_single_bit<uint32_t>(MulAmt + 1)) {
14335       // (mul x, 2^N - 1) => (sub (shl x, N), x)
14336       Res = DAG.getNode(ISD::SUB, DL, VT,
14337                         DAG.getNode(ISD::SHL, DL, VT,
14338                                     V,
14339                                     DAG.getConstant(Log2_32(MulAmt + 1), DL,
14340                                                     MVT::i32)),
14341                         V);
14342     } else
14343       return SDValue();
14344   } else {
14345     uint64_t MulAmtAbs = -MulAmt;
14346     if (llvm::has_single_bit<uint32_t>(MulAmtAbs + 1)) {
14347       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
14348       Res = DAG.getNode(ISD::SUB, DL, VT,
14349                         V,
14350                         DAG.getNode(ISD::SHL, DL, VT,
14351                                     V,
14352                                     DAG.getConstant(Log2_32(MulAmtAbs + 1), DL,
14353                                                     MVT::i32)));
14354     } else if (llvm::has_single_bit<uint32_t>(MulAmtAbs - 1)) {
14355       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
14356       Res = DAG.getNode(ISD::ADD, DL, VT,
14357                         V,
14358                         DAG.getNode(ISD::SHL, DL, VT,
14359                                     V,
14360                                     DAG.getConstant(Log2_32(MulAmtAbs - 1), DL,
14361                                                     MVT::i32)));
14362       Res = DAG.getNode(ISD::SUB, DL, VT,
14363                         DAG.getConstant(0, DL, MVT::i32), Res);
14364     } else
14365       return SDValue();
14366   }
14367 
14368   if (ShiftAmt != 0)
14369     Res = DAG.getNode(ISD::SHL, DL, VT,
14370                       Res, DAG.getConstant(ShiftAmt, DL, MVT::i32));
14371 
14372   // Do not add new nodes to DAG combiner worklist.
14373   DCI.CombineTo(N, Res, false);
14374   return SDValue();
14375 }
14376 
CombineANDShift(SDNode * N,TargetLowering::DAGCombinerInfo & DCI,const ARMSubtarget * Subtarget)14377 static SDValue CombineANDShift(SDNode *N,
14378                                TargetLowering::DAGCombinerInfo &DCI,
14379                                const ARMSubtarget *Subtarget) {
14380   // Allow DAGCombine to pattern-match before we touch the canonical form.
14381   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
14382     return SDValue();
14383 
14384   if (N->getValueType(0) != MVT::i32)
14385     return SDValue();
14386 
14387   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1));
14388   if (!N1C)
14389     return SDValue();
14390 
14391   uint32_t C1 = (uint32_t)N1C->getZExtValue();
14392   // Don't transform uxtb/uxth.
14393   if (C1 == 255 || C1 == 65535)
14394     return SDValue();
14395 
14396   SDNode *N0 = N->getOperand(0).getNode();
14397   if (!N0->hasOneUse())
14398     return SDValue();
14399 
14400   if (N0->getOpcode() != ISD::SHL && N0->getOpcode() != ISD::SRL)
14401     return SDValue();
14402 
14403   bool LeftShift = N0->getOpcode() == ISD::SHL;
14404 
14405   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0->getOperand(1));
14406   if (!N01C)
14407     return SDValue();
14408 
14409   uint32_t C2 = (uint32_t)N01C->getZExtValue();
14410   if (!C2 || C2 >= 32)
14411     return SDValue();
14412 
14413   // Clear irrelevant bits in the mask.
14414   if (LeftShift)
14415     C1 &= (-1U << C2);
14416   else
14417     C1 &= (-1U >> C2);
14418 
14419   SelectionDAG &DAG = DCI.DAG;
14420   SDLoc DL(N);
14421 
14422   // We have a pattern of the form "(and (shl x, c2) c1)" or
14423   // "(and (srl x, c2) c1)", where c1 is a shifted mask. Try to
14424   // transform to a pair of shifts, to save materializing c1.
14425 
14426   // First pattern: right shift, then mask off leading bits.
14427   // FIXME: Use demanded bits?
14428   if (!LeftShift && isMask_32(C1)) {
14429     uint32_t C3 = llvm::countl_zero(C1);
14430     if (C2 < C3) {
14431       SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0),
14432                                 DAG.getConstant(C3 - C2, DL, MVT::i32));
14433       return DAG.getNode(ISD::SRL, DL, MVT::i32, SHL,
14434                          DAG.getConstant(C3, DL, MVT::i32));
14435     }
14436   }
14437 
14438   // First pattern, reversed: left shift, then mask off trailing bits.
14439   if (LeftShift && isMask_32(~C1)) {
14440     uint32_t C3 = llvm::countr_zero(C1);
14441     if (C2 < C3) {
14442       SDValue SHL = DAG.getNode(ISD::SRL, DL, MVT::i32, N0->getOperand(0),
14443                                 DAG.getConstant(C3 - C2, DL, MVT::i32));
14444       return DAG.getNode(ISD::SHL, DL, MVT::i32, SHL,
14445                          DAG.getConstant(C3, DL, MVT::i32));
14446     }
14447   }
14448 
14449   // Second pattern: left shift, then mask off leading bits.
14450   // FIXME: Use demanded bits?
14451   if (LeftShift && isShiftedMask_32(C1)) {
14452     uint32_t Trailing = llvm::countr_zero(C1);
14453     uint32_t C3 = llvm::countl_zero(C1);
14454     if (Trailing == C2 && C2 + C3 < 32) {
14455       SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0),
14456                                 DAG.getConstant(C2 + C3, DL, MVT::i32));
14457       return DAG.getNode(ISD::SRL, DL, MVT::i32, SHL,
14458                         DAG.getConstant(C3, DL, MVT::i32));
14459     }
14460   }
14461 
14462   // Second pattern, reversed: right shift, then mask off trailing bits.
14463   // FIXME: Handle other patterns of known/demanded bits.
14464   if (!LeftShift && isShiftedMask_32(C1)) {
14465     uint32_t Leading = llvm::countl_zero(C1);
14466     uint32_t C3 = llvm::countr_zero(C1);
14467     if (Leading == C2 && C2 + C3 < 32) {
14468       SDValue SHL = DAG.getNode(ISD::SRL, DL, MVT::i32, N0->getOperand(0),
14469                                 DAG.getConstant(C2 + C3, DL, MVT::i32));
14470       return DAG.getNode(ISD::SHL, DL, MVT::i32, SHL,
14471                          DAG.getConstant(C3, DL, MVT::i32));
14472     }
14473   }
14474 
14475   // Transform "(and (shl x, c2) c1)" into "(shl (and x, c1>>c2), c2)"
14476   // if "c1 >> c2" is a cheaper immediate than "c1"
14477   if (LeftShift &&
14478       HasLowerConstantMaterializationCost(C1 >> C2, C1, Subtarget)) {
14479 
14480     SDValue And = DAG.getNode(ISD::AND, DL, MVT::i32, N0->getOperand(0),
14481                               DAG.getConstant(C1 >> C2, DL, MVT::i32));
14482     return DAG.getNode(ISD::SHL, DL, MVT::i32, And,
14483                        DAG.getConstant(C2, DL, MVT::i32));
14484   }
14485 
14486   return SDValue();
14487 }
14488 
PerformANDCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI,const ARMSubtarget * Subtarget)14489 static SDValue PerformANDCombine(SDNode *N,
14490                                  TargetLowering::DAGCombinerInfo &DCI,
14491                                  const ARMSubtarget *Subtarget) {
14492   // Attempt to use immediate-form VBIC
14493   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
14494   SDLoc dl(N);
14495   EVT VT = N->getValueType(0);
14496   SelectionDAG &DAG = DCI.DAG;
14497 
14498   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT) || VT == MVT::v2i1 ||
14499       VT == MVT::v4i1 || VT == MVT::v8i1 || VT == MVT::v16i1)
14500     return SDValue();
14501 
14502   APInt SplatBits, SplatUndef;
14503   unsigned SplatBitSize;
14504   bool HasAnyUndefs;
14505   if (BVN && (Subtarget->hasNEON() || Subtarget->hasMVEIntegerOps()) &&
14506       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
14507     if (SplatBitSize == 8 || SplatBitSize == 16 || SplatBitSize == 32 ||
14508         SplatBitSize == 64) {
14509       EVT VbicVT;
14510       SDValue Val = isVMOVModifiedImm((~SplatBits).getZExtValue(),
14511                                       SplatUndef.getZExtValue(), SplatBitSize,
14512                                       DAG, dl, VbicVT, VT, OtherModImm);
14513       if (Val.getNode()) {
14514         SDValue Input =
14515             DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, VbicVT, N->getOperand(0));
14516         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
14517         return DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, VT, Vbic);
14518       }
14519     }
14520   }
14521 
14522   if (!Subtarget->isThumb1Only()) {
14523     // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
14524     if (SDValue Result = combineSelectAndUseCommutative(N, true, DCI))
14525       return Result;
14526 
14527     if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
14528       return Result;
14529   }
14530 
14531   if (Subtarget->isThumb1Only())
14532     if (SDValue Result = CombineANDShift(N, DCI, Subtarget))
14533       return Result;
14534 
14535   return SDValue();
14536 }
14537 
14538 // Try combining OR nodes to SMULWB, SMULWT.
PerformORCombineToSMULWBT(SDNode * OR,TargetLowering::DAGCombinerInfo & DCI,const ARMSubtarget * Subtarget)14539 static SDValue PerformORCombineToSMULWBT(SDNode *OR,
14540                                          TargetLowering::DAGCombinerInfo &DCI,
14541                                          const ARMSubtarget *Subtarget) {
14542   if (!Subtarget->hasV6Ops() ||
14543       (Subtarget->isThumb() &&
14544        (!Subtarget->hasThumb2() || !Subtarget->hasDSP())))
14545     return SDValue();
14546 
14547   SDValue SRL = OR->getOperand(0);
14548   SDValue SHL = OR->getOperand(1);
14549 
14550   if (SRL.getOpcode() != ISD::SRL || SHL.getOpcode() != ISD::SHL) {
14551     SRL = OR->getOperand(1);
14552     SHL = OR->getOperand(0);
14553   }
14554   if (!isSRL16(SRL) || !isSHL16(SHL))
14555     return SDValue();
14556 
14557   // The first operands to the shifts need to be the two results from the
14558   // same smul_lohi node.
14559   if ((SRL.getOperand(0).getNode() != SHL.getOperand(0).getNode()) ||
14560        SRL.getOperand(0).getOpcode() != ISD::SMUL_LOHI)
14561     return SDValue();
14562 
14563   SDNode *SMULLOHI = SRL.getOperand(0).getNode();
14564   if (SRL.getOperand(0) != SDValue(SMULLOHI, 0) ||
14565       SHL.getOperand(0) != SDValue(SMULLOHI, 1))
14566     return SDValue();
14567 
14568   // Now we have:
14569   // (or (srl (smul_lohi ?, ?), 16), (shl (smul_lohi ?, ?), 16)))
14570   // For SMUL[B|T] smul_lohi will take a 32-bit and a 16-bit arguments.
14571   // For SMUWB the 16-bit value will signed extended somehow.
14572   // For SMULWT only the SRA is required.
14573   // Check both sides of SMUL_LOHI
14574   SDValue OpS16 = SMULLOHI->getOperand(0);
14575   SDValue OpS32 = SMULLOHI->getOperand(1);
14576 
14577   SelectionDAG &DAG = DCI.DAG;
14578   if (!isS16(OpS16, DAG) && !isSRA16(OpS16)) {
14579     OpS16 = OpS32;
14580     OpS32 = SMULLOHI->getOperand(0);
14581   }
14582 
14583   SDLoc dl(OR);
14584   unsigned Opcode = 0;
14585   if (isS16(OpS16, DAG))
14586     Opcode = ARMISD::SMULWB;
14587   else if (isSRA16(OpS16)) {
14588     Opcode = ARMISD::SMULWT;
14589     OpS16 = OpS16->getOperand(0);
14590   }
14591   else
14592     return SDValue();
14593 
14594   SDValue Res = DAG.getNode(Opcode, dl, MVT::i32, OpS32, OpS16);
14595   DAG.ReplaceAllUsesOfValueWith(SDValue(OR, 0), Res);
14596   return SDValue(OR, 0);
14597 }
14598 
PerformORCombineToBFI(SDNode * N,TargetLowering::DAGCombinerInfo & DCI,const ARMSubtarget * Subtarget)14599 static SDValue PerformORCombineToBFI(SDNode *N,
14600                                      TargetLowering::DAGCombinerInfo &DCI,
14601                                      const ARMSubtarget *Subtarget) {
14602   // BFI is only available on V6T2+
14603   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
14604     return SDValue();
14605 
14606   EVT VT = N->getValueType(0);
14607   SDValue N0 = N->getOperand(0);
14608   SDValue N1 = N->getOperand(1);
14609   SelectionDAG &DAG = DCI.DAG;
14610   SDLoc DL(N);
14611   // 1) or (and A, mask), val => ARMbfi A, val, mask
14612   //      iff (val & mask) == val
14613   //
14614   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
14615   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
14616   //          && mask == ~mask2
14617   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
14618   //          && ~mask == mask2
14619   //  (i.e., copy a bitfield value into another bitfield of the same width)
14620 
14621   if (VT != MVT::i32)
14622     return SDValue();
14623 
14624   SDValue N00 = N0.getOperand(0);
14625 
14626   // The value and the mask need to be constants so we can verify this is
14627   // actually a bitfield set. If the mask is 0xffff, we can do better
14628   // via a movt instruction, so don't use BFI in that case.
14629   SDValue MaskOp = N0.getOperand(1);
14630   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
14631   if (!MaskC)
14632     return SDValue();
14633   unsigned Mask = MaskC->getZExtValue();
14634   if (Mask == 0xffff)
14635     return SDValue();
14636   SDValue Res;
14637   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
14638   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
14639   if (N1C) {
14640     unsigned Val = N1C->getZExtValue();
14641     if ((Val & ~Mask) != Val)
14642       return SDValue();
14643 
14644     if (ARM::isBitFieldInvertedMask(Mask)) {
14645       Val >>= llvm::countr_zero(~Mask);
14646 
14647       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
14648                         DAG.getConstant(Val, DL, MVT::i32),
14649                         DAG.getConstant(Mask, DL, MVT::i32));
14650 
14651       DCI.CombineTo(N, Res, false);
14652       // Return value from the original node to inform the combiner than N is
14653       // now dead.
14654       return SDValue(N, 0);
14655     }
14656   } else if (N1.getOpcode() == ISD::AND) {
14657     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
14658     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
14659     if (!N11C)
14660       return SDValue();
14661     unsigned Mask2 = N11C->getZExtValue();
14662 
14663     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
14664     // as is to match.
14665     if (ARM::isBitFieldInvertedMask(Mask) &&
14666         (Mask == ~Mask2)) {
14667       // The pack halfword instruction works better for masks that fit it,
14668       // so use that when it's available.
14669       if (Subtarget->hasDSP() &&
14670           (Mask == 0xffff || Mask == 0xffff0000))
14671         return SDValue();
14672       // 2a
14673       unsigned amt = llvm::countr_zero(Mask2);
14674       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
14675                         DAG.getConstant(amt, DL, MVT::i32));
14676       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
14677                         DAG.getConstant(Mask, DL, MVT::i32));
14678       DCI.CombineTo(N, Res, false);
14679       // Return value from the original node to inform the combiner than N is
14680       // now dead.
14681       return SDValue(N, 0);
14682     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
14683                (~Mask == Mask2)) {
14684       // The pack halfword instruction works better for masks that fit it,
14685       // so use that when it's available.
14686       if (Subtarget->hasDSP() &&
14687           (Mask2 == 0xffff || Mask2 == 0xffff0000))
14688         return SDValue();
14689       // 2b
14690       unsigned lsb = llvm::countr_zero(Mask);
14691       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
14692                         DAG.getConstant(lsb, DL, MVT::i32));
14693       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
14694                         DAG.getConstant(Mask2, DL, MVT::i32));
14695       DCI.CombineTo(N, Res, false);
14696       // Return value from the original node to inform the combiner than N is
14697       // now dead.
14698       return SDValue(N, 0);
14699     }
14700   }
14701 
14702   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
14703       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
14704       ARM::isBitFieldInvertedMask(~Mask)) {
14705     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
14706     // where lsb(mask) == #shamt and masked bits of B are known zero.
14707     SDValue ShAmt = N00.getOperand(1);
14708     unsigned ShAmtC = ShAmt->getAsZExtVal();
14709     unsigned LSB = llvm::countr_zero(Mask);
14710     if (ShAmtC != LSB)
14711       return SDValue();
14712 
14713     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
14714                       DAG.getConstant(~Mask, DL, MVT::i32));
14715 
14716     DCI.CombineTo(N, Res, false);
14717     // Return value from the original node to inform the combiner than N is
14718     // now dead.
14719     return SDValue(N, 0);
14720   }
14721 
14722   return SDValue();
14723 }
14724 
isValidMVECond(unsigned CC,bool IsFloat)14725 static bool isValidMVECond(unsigned CC, bool IsFloat) {
14726   switch (CC) {
14727   case ARMCC::EQ:
14728   case ARMCC::NE:
14729   case ARMCC::LE:
14730   case ARMCC::GT:
14731   case ARMCC::GE:
14732   case ARMCC::LT:
14733     return true;
14734   case ARMCC::HS:
14735   case ARMCC::HI:
14736     return !IsFloat;
14737   default:
14738     return false;
14739   };
14740 }
14741 
getVCMPCondCode(SDValue N)14742 static ARMCC::CondCodes getVCMPCondCode(SDValue N) {
14743   if (N->getOpcode() == ARMISD::VCMP)
14744     return (ARMCC::CondCodes)N->getConstantOperandVal(2);
14745   else if (N->getOpcode() == ARMISD::VCMPZ)
14746     return (ARMCC::CondCodes)N->getConstantOperandVal(1);
14747   else
14748     llvm_unreachable("Not a VCMP/VCMPZ!");
14749 }
14750 
CanInvertMVEVCMP(SDValue N)14751 static bool CanInvertMVEVCMP(SDValue N) {
14752   ARMCC::CondCodes CC = ARMCC::getOppositeCondition(getVCMPCondCode(N));
14753   return isValidMVECond(CC, N->getOperand(0).getValueType().isFloatingPoint());
14754 }
14755 
PerformORCombine_i1(SDNode * N,SelectionDAG & DAG,const ARMSubtarget * Subtarget)14756 static SDValue PerformORCombine_i1(SDNode *N, SelectionDAG &DAG,
14757                                    const ARMSubtarget *Subtarget) {
14758   // Try to invert "or A, B" -> "and ~A, ~B", as the "and" is easier to chain
14759   // together with predicates
14760   EVT VT = N->getValueType(0);
14761   SDLoc DL(N);
14762   SDValue N0 = N->getOperand(0);
14763   SDValue N1 = N->getOperand(1);
14764 
14765   auto IsFreelyInvertable = [&](SDValue V) {
14766     if (V->getOpcode() == ARMISD::VCMP || V->getOpcode() == ARMISD::VCMPZ)
14767       return CanInvertMVEVCMP(V);
14768     return false;
14769   };
14770 
14771   // At least one operand must be freely invertable.
14772   if (!(IsFreelyInvertable(N0) || IsFreelyInvertable(N1)))
14773     return SDValue();
14774 
14775   SDValue NewN0 = DAG.getLogicalNOT(DL, N0, VT);
14776   SDValue NewN1 = DAG.getLogicalNOT(DL, N1, VT);
14777   SDValue And = DAG.getNode(ISD::AND, DL, VT, NewN0, NewN1);
14778   return DAG.getLogicalNOT(DL, And, VT);
14779 }
14780 
14781 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
PerformORCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI,const ARMSubtarget * Subtarget)14782 static SDValue PerformORCombine(SDNode *N,
14783                                 TargetLowering::DAGCombinerInfo &DCI,
14784                                 const ARMSubtarget *Subtarget) {
14785   // Attempt to use immediate-form VORR
14786   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
14787   SDLoc dl(N);
14788   EVT VT = N->getValueType(0);
14789   SelectionDAG &DAG = DCI.DAG;
14790 
14791   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
14792     return SDValue();
14793 
14794   if (Subtarget->hasMVEIntegerOps() && (VT == MVT::v2i1 || VT == MVT::v4i1 ||
14795                                         VT == MVT::v8i1 || VT == MVT::v16i1))
14796     return PerformORCombine_i1(N, DAG, Subtarget);
14797 
14798   APInt SplatBits, SplatUndef;
14799   unsigned SplatBitSize;
14800   bool HasAnyUndefs;
14801   if (BVN && (Subtarget->hasNEON() || Subtarget->hasMVEIntegerOps()) &&
14802       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
14803     if (SplatBitSize == 8 || SplatBitSize == 16 || SplatBitSize == 32 ||
14804         SplatBitSize == 64) {
14805       EVT VorrVT;
14806       SDValue Val =
14807           isVMOVModifiedImm(SplatBits.getZExtValue(), SplatUndef.getZExtValue(),
14808                             SplatBitSize, DAG, dl, VorrVT, VT, OtherModImm);
14809       if (Val.getNode()) {
14810         SDValue Input =
14811             DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, VorrVT, N->getOperand(0));
14812         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
14813         return DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, VT, Vorr);
14814       }
14815     }
14816   }
14817 
14818   if (!Subtarget->isThumb1Only()) {
14819     // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
14820     if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI))
14821       return Result;
14822     if (SDValue Result = PerformORCombineToSMULWBT(N, DCI, Subtarget))
14823       return Result;
14824   }
14825 
14826   SDValue N0 = N->getOperand(0);
14827   SDValue N1 = N->getOperand(1);
14828 
14829   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
14830   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
14831       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
14832 
14833     // The code below optimizes (or (and X, Y), Z).
14834     // The AND operand needs to have a single user to make these optimizations
14835     // profitable.
14836     if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
14837       return SDValue();
14838 
14839     APInt SplatUndef;
14840     unsigned SplatBitSize;
14841     bool HasAnyUndefs;
14842 
14843     APInt SplatBits0, SplatBits1;
14844     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
14845     BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
14846     // Ensure that the second operand of both ands are constants
14847     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
14848                                       HasAnyUndefs) && !HasAnyUndefs) {
14849         if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
14850                                           HasAnyUndefs) && !HasAnyUndefs) {
14851             // Ensure that the bit width of the constants are the same and that
14852             // the splat arguments are logical inverses as per the pattern we
14853             // are trying to simplify.
14854             if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
14855                 SplatBits0 == ~SplatBits1) {
14856                 // Canonicalize the vector type to make instruction selection
14857                 // simpler.
14858                 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
14859                 SDValue Result = DAG.getNode(ARMISD::VBSP, dl, CanonicalVT,
14860                                              N0->getOperand(1),
14861                                              N0->getOperand(0),
14862                                              N1->getOperand(0));
14863                 return DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, VT, Result);
14864             }
14865         }
14866     }
14867   }
14868 
14869   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
14870   // reasonable.
14871   if (N0.getOpcode() == ISD::AND && N0.hasOneUse()) {
14872     if (SDValue Res = PerformORCombineToBFI(N, DCI, Subtarget))
14873       return Res;
14874   }
14875 
14876   if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
14877     return Result;
14878 
14879   return SDValue();
14880 }
14881 
PerformXORCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI,const ARMSubtarget * Subtarget)14882 static SDValue PerformXORCombine(SDNode *N,
14883                                  TargetLowering::DAGCombinerInfo &DCI,
14884                                  const ARMSubtarget *Subtarget) {
14885   EVT VT = N->getValueType(0);
14886   SelectionDAG &DAG = DCI.DAG;
14887 
14888   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
14889     return SDValue();
14890 
14891   if (!Subtarget->isThumb1Only()) {
14892     // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
14893     if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI))
14894       return Result;
14895 
14896     if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
14897       return Result;
14898   }
14899 
14900   if (Subtarget->hasMVEIntegerOps()) {
14901     // fold (xor(vcmp/z, 1)) into a vcmp with the opposite condition.
14902     SDValue N0 = N->getOperand(0);
14903     SDValue N1 = N->getOperand(1);
14904     const TargetLowering *TLI = Subtarget->getTargetLowering();
14905     if (TLI->isConstTrueVal(N1) &&
14906         (N0->getOpcode() == ARMISD::VCMP || N0->getOpcode() == ARMISD::VCMPZ)) {
14907       if (CanInvertMVEVCMP(N0)) {
14908         SDLoc DL(N0);
14909         ARMCC::CondCodes CC = ARMCC::getOppositeCondition(getVCMPCondCode(N0));
14910 
14911         SmallVector<SDValue, 4> Ops;
14912         Ops.push_back(N0->getOperand(0));
14913         if (N0->getOpcode() == ARMISD::VCMP)
14914           Ops.push_back(N0->getOperand(1));
14915         Ops.push_back(DAG.getConstant(CC, DL, MVT::i32));
14916         return DAG.getNode(N0->getOpcode(), DL, N0->getValueType(0), Ops);
14917       }
14918     }
14919   }
14920 
14921   return SDValue();
14922 }
14923 
14924 // ParseBFI - given a BFI instruction in N, extract the "from" value (Rn) and return it,
14925 // and fill in FromMask and ToMask with (consecutive) bits in "from" to be extracted and
14926 // their position in "to" (Rd).
ParseBFI(SDNode * N,APInt & ToMask,APInt & FromMask)14927 static SDValue ParseBFI(SDNode *N, APInt &ToMask, APInt &FromMask) {
14928   assert(N->getOpcode() == ARMISD::BFI);
14929 
14930   SDValue From = N->getOperand(1);
14931   ToMask = ~N->getConstantOperandAPInt(2);
14932   FromMask = APInt::getLowBitsSet(ToMask.getBitWidth(), ToMask.popcount());
14933 
14934   // If the Base came from a SHR #C, we can deduce that it is really testing bit
14935   // #C in the base of the SHR.
14936   if (From->getOpcode() == ISD::SRL &&
14937       isa<ConstantSDNode>(From->getOperand(1))) {
14938     APInt Shift = From->getConstantOperandAPInt(1);
14939     assert(Shift.getLimitedValue() < 32 && "Shift too large!");
14940     FromMask <<= Shift.getLimitedValue(31);
14941     From = From->getOperand(0);
14942   }
14943 
14944   return From;
14945 }
14946 
14947 // If A and B contain one contiguous set of bits, does A | B == A . B?
14948 //
14949 // Neither A nor B must be zero.
BitsProperlyConcatenate(const APInt & A,const APInt & B)14950 static bool BitsProperlyConcatenate(const APInt &A, const APInt &B) {
14951   unsigned LastActiveBitInA = A.countr_zero();
14952   unsigned FirstActiveBitInB = B.getBitWidth() - B.countl_zero() - 1;
14953   return LastActiveBitInA - 1 == FirstActiveBitInB;
14954 }
14955 
FindBFIToCombineWith(SDNode * N)14956 static SDValue FindBFIToCombineWith(SDNode *N) {
14957   // We have a BFI in N. Find a BFI it can combine with, if one exists.
14958   APInt ToMask, FromMask;
14959   SDValue From = ParseBFI(N, ToMask, FromMask);
14960   SDValue To = N->getOperand(0);
14961 
14962   SDValue V = To;
14963   if (V.getOpcode() != ARMISD::BFI)
14964     return SDValue();
14965 
14966   APInt NewToMask, NewFromMask;
14967   SDValue NewFrom = ParseBFI(V.getNode(), NewToMask, NewFromMask);
14968   if (NewFrom != From)
14969     return SDValue();
14970 
14971   // Do the written bits conflict with any we've seen so far?
14972   if ((NewToMask & ToMask).getBoolValue())
14973     // Conflicting bits.
14974     return SDValue();
14975 
14976   // Are the new bits contiguous when combined with the old bits?
14977   if (BitsProperlyConcatenate(ToMask, NewToMask) &&
14978       BitsProperlyConcatenate(FromMask, NewFromMask))
14979     return V;
14980   if (BitsProperlyConcatenate(NewToMask, ToMask) &&
14981       BitsProperlyConcatenate(NewFromMask, FromMask))
14982     return V;
14983 
14984   return SDValue();
14985 }
14986 
PerformBFICombine(SDNode * N,SelectionDAG & DAG)14987 static SDValue PerformBFICombine(SDNode *N, SelectionDAG &DAG) {
14988   SDValue N0 = N->getOperand(0);
14989   SDValue N1 = N->getOperand(1);
14990 
14991   if (N1.getOpcode() == ISD::AND) {
14992     // (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
14993     // the bits being cleared by the AND are not demanded by the BFI.
14994     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
14995     if (!N11C)
14996       return SDValue();
14997     unsigned InvMask = N->getConstantOperandVal(2);
14998     unsigned LSB = llvm::countr_zero(~InvMask);
14999     unsigned Width = llvm::bit_width<unsigned>(~InvMask) - LSB;
15000     assert(Width <
15001                static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
15002            "undefined behavior");
15003     unsigned Mask = (1u << Width) - 1;
15004     unsigned Mask2 = N11C->getZExtValue();
15005     if ((Mask & (~Mask2)) == 0)
15006       return DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
15007                          N->getOperand(0), N1.getOperand(0), N->getOperand(2));
15008     return SDValue();
15009   }
15010 
15011   // Look for another BFI to combine with.
15012   if (SDValue CombineBFI = FindBFIToCombineWith(N)) {
15013     // We've found a BFI.
15014     APInt ToMask1, FromMask1;
15015     SDValue From1 = ParseBFI(N, ToMask1, FromMask1);
15016 
15017     APInt ToMask2, FromMask2;
15018     SDValue From2 = ParseBFI(CombineBFI.getNode(), ToMask2, FromMask2);
15019     assert(From1 == From2);
15020     (void)From2;
15021 
15022     // Create a new BFI, combining the two together.
15023     APInt NewFromMask = FromMask1 | FromMask2;
15024     APInt NewToMask = ToMask1 | ToMask2;
15025 
15026     EVT VT = N->getValueType(0);
15027     SDLoc dl(N);
15028 
15029     if (NewFromMask[0] == 0)
15030       From1 = DAG.getNode(ISD::SRL, dl, VT, From1,
15031                           DAG.getConstant(NewFromMask.countr_zero(), dl, VT));
15032     return DAG.getNode(ARMISD::BFI, dl, VT, CombineBFI.getOperand(0), From1,
15033                        DAG.getConstant(~NewToMask, dl, VT));
15034   }
15035 
15036   // Reassociate BFI(BFI (A, B, M1), C, M2) to BFI(BFI (A, C, M2), B, M1) so
15037   // that lower bit insertions are performed first, providing that M1 and M2
15038   // do no overlap. This can allow multiple BFI instructions to be combined
15039   // together by the other folds above.
15040   if (N->getOperand(0).getOpcode() == ARMISD::BFI) {
15041     APInt ToMask1 = ~N->getConstantOperandAPInt(2);
15042     APInt ToMask2 = ~N0.getConstantOperandAPInt(2);
15043 
15044     if (!N0.hasOneUse() || (ToMask1 & ToMask2) != 0 ||
15045         ToMask1.countl_zero() < ToMask2.countl_zero())
15046       return SDValue();
15047 
15048     EVT VT = N->getValueType(0);
15049     SDLoc dl(N);
15050     SDValue BFI1 = DAG.getNode(ARMISD::BFI, dl, VT, N0.getOperand(0),
15051                                N->getOperand(1), N->getOperand(2));
15052     return DAG.getNode(ARMISD::BFI, dl, VT, BFI1, N0.getOperand(1),
15053                        N0.getOperand(2));
15054   }
15055 
15056   return SDValue();
15057 }
15058 
15059 // Check that N is CMPZ(CSINC(0, 0, CC, X)),
15060 //              or CMPZ(CMOV(1, 0, CC, X))
15061 // return X if valid.
IsCMPZCSINC(SDNode * Cmp,ARMCC::CondCodes & CC)15062 static SDValue IsCMPZCSINC(SDNode *Cmp, ARMCC::CondCodes &CC) {
15063   if (Cmp->getOpcode() != ARMISD::CMPZ || !isNullConstant(Cmp->getOperand(1)))
15064     return SDValue();
15065   SDValue CSInc = Cmp->getOperand(0);
15066 
15067   // Ignore any `And 1` nodes that may not yet have been removed. We are
15068   // looking for a value that produces 1/0, so these have no effect on the
15069   // code.
15070   while (CSInc.getOpcode() == ISD::AND &&
15071          isa<ConstantSDNode>(CSInc.getOperand(1)) &&
15072          CSInc.getConstantOperandVal(1) == 1 && CSInc->hasOneUse())
15073     CSInc = CSInc.getOperand(0);
15074 
15075   if (CSInc.getOpcode() == ARMISD::CSINC &&
15076       isNullConstant(CSInc.getOperand(0)) &&
15077       isNullConstant(CSInc.getOperand(1)) && CSInc->hasOneUse()) {
15078     CC = (ARMCC::CondCodes)CSInc.getConstantOperandVal(2);
15079     return CSInc.getOperand(3);
15080   }
15081   if (CSInc.getOpcode() == ARMISD::CMOV && isOneConstant(CSInc.getOperand(0)) &&
15082       isNullConstant(CSInc.getOperand(1)) && CSInc->hasOneUse()) {
15083     CC = (ARMCC::CondCodes)CSInc.getConstantOperandVal(2);
15084     return CSInc.getOperand(3);
15085   }
15086   if (CSInc.getOpcode() == ARMISD::CMOV && isOneConstant(CSInc.getOperand(1)) &&
15087       isNullConstant(CSInc.getOperand(0)) && CSInc->hasOneUse()) {
15088     CC = ARMCC::getOppositeCondition(
15089         (ARMCC::CondCodes)CSInc.getConstantOperandVal(2));
15090     return CSInc.getOperand(3);
15091   }
15092   return SDValue();
15093 }
15094 
PerformCMPZCombine(SDNode * N,SelectionDAG & DAG)15095 static SDValue PerformCMPZCombine(SDNode *N, SelectionDAG &DAG) {
15096   // Given CMPZ(CSINC(C, 0, 0, EQ), 0), we can just use C directly. As in
15097   //       t92: flags = ARMISD::CMPZ t74, 0
15098   //     t93: i32 = ARMISD::CSINC 0, 0, 1, t92
15099   //   t96: flags = ARMISD::CMPZ t93, 0
15100   // t114: i32 = ARMISD::CSINV 0, 0, 0, t96
15101   ARMCC::CondCodes Cond;
15102   if (SDValue C = IsCMPZCSINC(N, Cond))
15103     if (Cond == ARMCC::EQ)
15104       return C;
15105   return SDValue();
15106 }
15107 
PerformCSETCombine(SDNode * N,SelectionDAG & DAG)15108 static SDValue PerformCSETCombine(SDNode *N, SelectionDAG &DAG) {
15109   // Fold away an unneccessary CMPZ/CSINC
15110   // CSXYZ A, B, C1 (CMPZ (CSINC 0, 0, C2, D), 0) ->
15111   // if C1==EQ -> CSXYZ A, B, C2, D
15112   // if C1==NE -> CSXYZ A, B, NOT(C2), D
15113   ARMCC::CondCodes Cond;
15114   if (SDValue C = IsCMPZCSINC(N->getOperand(3).getNode(), Cond)) {
15115     if (N->getConstantOperandVal(2) == ARMCC::EQ)
15116       return DAG.getNode(N->getOpcode(), SDLoc(N), MVT::i32, N->getOperand(0),
15117                          N->getOperand(1),
15118                          DAG.getConstant(Cond, SDLoc(N), MVT::i32), C);
15119     if (N->getConstantOperandVal(2) == ARMCC::NE)
15120       return DAG.getNode(
15121           N->getOpcode(), SDLoc(N), MVT::i32, N->getOperand(0),
15122           N->getOperand(1),
15123           DAG.getConstant(ARMCC::getOppositeCondition(Cond), SDLoc(N), MVT::i32), C);
15124   }
15125   return SDValue();
15126 }
15127 
15128 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
15129 /// ARMISD::VMOVRRD.
PerformVMOVRRDCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI,const ARMSubtarget * Subtarget)15130 static SDValue PerformVMOVRRDCombine(SDNode *N,
15131                                      TargetLowering::DAGCombinerInfo &DCI,
15132                                      const ARMSubtarget *Subtarget) {
15133   // vmovrrd(vmovdrr x, y) -> x,y
15134   SDValue InDouble = N->getOperand(0);
15135   if (InDouble.getOpcode() == ARMISD::VMOVDRR && Subtarget->hasFP64())
15136     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
15137 
15138   // vmovrrd(load f64) -> (load i32), (load i32)
15139   SDNode *InNode = InDouble.getNode();
15140   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
15141       InNode->getValueType(0) == MVT::f64 &&
15142       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
15143       !cast<LoadSDNode>(InNode)->isVolatile()) {
15144     // TODO: Should this be done for non-FrameIndex operands?
15145     LoadSDNode *LD = cast<LoadSDNode>(InNode);
15146 
15147     SelectionDAG &DAG = DCI.DAG;
15148     SDLoc DL(LD);
15149     SDValue BasePtr = LD->getBasePtr();
15150     SDValue NewLD1 =
15151         DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr, LD->getPointerInfo(),
15152                     LD->getAlign(), LD->getMemOperand()->getFlags());
15153 
15154     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
15155                                     DAG.getConstant(4, DL, MVT::i32));
15156 
15157     SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, LD->getChain(), OffsetPtr,
15158                                  LD->getPointerInfo().getWithOffset(4),
15159                                  commonAlignment(LD->getAlign(), 4),
15160                                  LD->getMemOperand()->getFlags());
15161 
15162     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
15163     if (DCI.DAG.getDataLayout().isBigEndian())
15164       std::swap (NewLD1, NewLD2);
15165     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
15166     return Result;
15167   }
15168 
15169   // VMOVRRD(extract(..(build_vector(a, b, c, d)))) -> a,b or c,d
15170   // VMOVRRD(extract(insert_vector(insert_vector(.., a, l1), b, l2))) -> a,b
15171   if (InDouble.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
15172       isa<ConstantSDNode>(InDouble.getOperand(1))) {
15173     SDValue BV = InDouble.getOperand(0);
15174     // Look up through any nop bitcasts and vector_reg_casts. bitcasts may
15175     // change lane order under big endian.
15176     bool BVSwap = BV.getOpcode() == ISD::BITCAST;
15177     while (
15178         (BV.getOpcode() == ISD::BITCAST ||
15179          BV.getOpcode() == ARMISD::VECTOR_REG_CAST) &&
15180         (BV.getValueType() == MVT::v2f64 || BV.getValueType() == MVT::v2i64)) {
15181       BVSwap = BV.getOpcode() == ISD::BITCAST;
15182       BV = BV.getOperand(0);
15183     }
15184     if (BV.getValueType() != MVT::v4i32)
15185       return SDValue();
15186 
15187     // Handle buildvectors, pulling out the correct lane depending on
15188     // endianness.
15189     unsigned Offset = InDouble.getConstantOperandVal(1) == 1 ? 2 : 0;
15190     if (BV.getOpcode() == ISD::BUILD_VECTOR) {
15191       SDValue Op0 = BV.getOperand(Offset);
15192       SDValue Op1 = BV.getOperand(Offset + 1);
15193       if (!Subtarget->isLittle() && BVSwap)
15194         std::swap(Op0, Op1);
15195 
15196       return DCI.DAG.getMergeValues({Op0, Op1}, SDLoc(N));
15197     }
15198 
15199     // A chain of insert_vectors, grabbing the correct value of the chain of
15200     // inserts.
15201     SDValue Op0, Op1;
15202     while (BV.getOpcode() == ISD::INSERT_VECTOR_ELT) {
15203       if (isa<ConstantSDNode>(BV.getOperand(2))) {
15204         if (BV.getConstantOperandVal(2) == Offset && !Op0)
15205           Op0 = BV.getOperand(1);
15206         if (BV.getConstantOperandVal(2) == Offset + 1 && !Op1)
15207           Op1 = BV.getOperand(1);
15208       }
15209       BV = BV.getOperand(0);
15210     }
15211     if (!Subtarget->isLittle() && BVSwap)
15212       std::swap(Op0, Op1);
15213     if (Op0 && Op1)
15214       return DCI.DAG.getMergeValues({Op0, Op1}, SDLoc(N));
15215   }
15216 
15217   return SDValue();
15218 }
15219 
15220 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
15221 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
PerformVMOVDRRCombine(SDNode * N,SelectionDAG & DAG)15222 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
15223   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
15224   SDValue Op0 = N->getOperand(0);
15225   SDValue Op1 = N->getOperand(1);
15226   if (Op0.getOpcode() == ISD::BITCAST)
15227     Op0 = Op0.getOperand(0);
15228   if (Op1.getOpcode() == ISD::BITCAST)
15229     Op1 = Op1.getOperand(0);
15230   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
15231       Op0.getNode() == Op1.getNode() &&
15232       Op0.getResNo() == 0 && Op1.getResNo() == 1)
15233     return DAG.getNode(ISD::BITCAST, SDLoc(N),
15234                        N->getValueType(0), Op0.getOperand(0));
15235   return SDValue();
15236 }
15237 
PerformVMOVhrCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI)15238 static SDValue PerformVMOVhrCombine(SDNode *N,
15239                                     TargetLowering::DAGCombinerInfo &DCI) {
15240   SDValue Op0 = N->getOperand(0);
15241 
15242   // VMOVhr (VMOVrh (X)) -> X
15243   if (Op0->getOpcode() == ARMISD::VMOVrh)
15244     return Op0->getOperand(0);
15245 
15246   // FullFP16: half values are passed in S-registers, and we don't
15247   // need any of the bitcast and moves:
15248   //
15249   //     t2: f32,ch1,gl1? = CopyFromReg ch, Register:f32 %0, gl?
15250   //   t5: i32 = bitcast t2
15251   // t18: f16 = ARMISD::VMOVhr t5
15252   // =>
15253   // tN: f16,ch2,gl2? = CopyFromReg ch, Register::f32 %0, gl?
15254   if (Op0->getOpcode() == ISD::BITCAST) {
15255     SDValue Copy = Op0->getOperand(0);
15256     if (Copy.getValueType() == MVT::f32 &&
15257         Copy->getOpcode() == ISD::CopyFromReg) {
15258       bool HasGlue = Copy->getNumOperands() == 3;
15259       SDValue Ops[] = {Copy->getOperand(0), Copy->getOperand(1),
15260                        HasGlue ? Copy->getOperand(2) : SDValue()};
15261       EVT OutTys[] = {N->getValueType(0), MVT::Other, MVT::Glue};
15262       SDValue NewCopy =
15263           DCI.DAG.getNode(ISD::CopyFromReg, SDLoc(N),
15264                           DCI.DAG.getVTList(ArrayRef(OutTys, HasGlue ? 3 : 2)),
15265                           ArrayRef(Ops, HasGlue ? 3 : 2));
15266 
15267       // Update Users, Chains, and Potential Glue.
15268       DCI.DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), NewCopy.getValue(0));
15269       DCI.DAG.ReplaceAllUsesOfValueWith(Copy.getValue(1), NewCopy.getValue(1));
15270       if (HasGlue)
15271         DCI.DAG.ReplaceAllUsesOfValueWith(Copy.getValue(2),
15272                                           NewCopy.getValue(2));
15273 
15274       return NewCopy;
15275     }
15276   }
15277 
15278   // fold (VMOVhr (load x)) -> (load (f16*)x)
15279   if (LoadSDNode *LN0 = dyn_cast<LoadSDNode>(Op0)) {
15280     if (LN0->hasOneUse() && LN0->isUnindexed() &&
15281         LN0->getMemoryVT() == MVT::i16) {
15282       SDValue Load =
15283           DCI.DAG.getLoad(N->getValueType(0), SDLoc(N), LN0->getChain(),
15284                           LN0->getBasePtr(), LN0->getMemOperand());
15285       DCI.DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Load.getValue(0));
15286       DCI.DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), Load.getValue(1));
15287       return Load;
15288     }
15289   }
15290 
15291   // Only the bottom 16 bits of the source register are used.
15292   APInt DemandedMask = APInt::getLowBitsSet(32, 16);
15293   const TargetLowering &TLI = DCI.DAG.getTargetLoweringInfo();
15294   if (TLI.SimplifyDemandedBits(Op0, DemandedMask, DCI))
15295     return SDValue(N, 0);
15296 
15297   return SDValue();
15298 }
15299 
PerformVMOVrhCombine(SDNode * N,SelectionDAG & DAG)15300 static SDValue PerformVMOVrhCombine(SDNode *N, SelectionDAG &DAG) {
15301   SDValue N0 = N->getOperand(0);
15302   EVT VT = N->getValueType(0);
15303 
15304   // fold (VMOVrh (fpconst x)) -> const x
15305   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N0)) {
15306     APFloat V = C->getValueAPF();
15307     return DAG.getConstant(V.bitcastToAPInt().getZExtValue(), SDLoc(N), VT);
15308   }
15309 
15310   // fold (VMOVrh (load x)) -> (zextload (i16*)x)
15311   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse()) {
15312     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
15313 
15314     SDValue Load =
15315         DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT, LN0->getChain(),
15316                        LN0->getBasePtr(), MVT::i16, LN0->getMemOperand());
15317     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Load.getValue(0));
15318     DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
15319     return Load;
15320   }
15321 
15322   // Fold VMOVrh(extract(x, n)) -> vgetlaneu(x, n)
15323   if (N0->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
15324       isa<ConstantSDNode>(N0->getOperand(1)))
15325     return DAG.getNode(ARMISD::VGETLANEu, SDLoc(N), VT, N0->getOperand(0),
15326                        N0->getOperand(1));
15327 
15328   return SDValue();
15329 }
15330 
15331 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
15332 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
15333 /// i64 vector to have f64 elements, since the value can then be loaded
15334 /// directly into a VFP register.
hasNormalLoadOperand(SDNode * N)15335 static bool hasNormalLoadOperand(SDNode *N) {
15336   unsigned NumElts = N->getValueType(0).getVectorNumElements();
15337   for (unsigned i = 0; i < NumElts; ++i) {
15338     SDNode *Elt = N->getOperand(i).getNode();
15339     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
15340       return true;
15341   }
15342   return false;
15343 }
15344 
15345 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
15346 /// ISD::BUILD_VECTOR.
PerformBUILD_VECTORCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI,const ARMSubtarget * Subtarget)15347 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
15348                                           TargetLowering::DAGCombinerInfo &DCI,
15349                                           const ARMSubtarget *Subtarget) {
15350   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
15351   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
15352   // into a pair of GPRs, which is fine when the value is used as a scalar,
15353   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
15354   SelectionDAG &DAG = DCI.DAG;
15355   if (N->getNumOperands() == 2)
15356     if (SDValue RV = PerformVMOVDRRCombine(N, DAG))
15357       return RV;
15358 
15359   // Load i64 elements as f64 values so that type legalization does not split
15360   // them up into i32 values.
15361   EVT VT = N->getValueType(0);
15362   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
15363     return SDValue();
15364   SDLoc dl(N);
15365   SmallVector<SDValue, 8> Ops;
15366   unsigned NumElts = VT.getVectorNumElements();
15367   for (unsigned i = 0; i < NumElts; ++i) {
15368     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
15369     Ops.push_back(V);
15370     // Make the DAGCombiner fold the bitcast.
15371     DCI.AddToWorklist(V.getNode());
15372   }
15373   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
15374   SDValue BV = DAG.getBuildVector(FloatVT, dl, Ops);
15375   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
15376 }
15377 
15378 /// Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
15379 static SDValue
PerformARMBUILD_VECTORCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI)15380 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
15381   // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
15382   // At that time, we may have inserted bitcasts from integer to float.
15383   // If these bitcasts have survived DAGCombine, change the lowering of this
15384   // BUILD_VECTOR in something more vector friendly, i.e., that does not
15385   // force to use floating point types.
15386 
15387   // Make sure we can change the type of the vector.
15388   // This is possible iff:
15389   // 1. The vector is only used in a bitcast to a integer type. I.e.,
15390   //    1.1. Vector is used only once.
15391   //    1.2. Use is a bit convert to an integer type.
15392   // 2. The size of its operands are 32-bits (64-bits are not legal).
15393   EVT VT = N->getValueType(0);
15394   EVT EltVT = VT.getVectorElementType();
15395 
15396   // Check 1.1. and 2.
15397   if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
15398     return SDValue();
15399 
15400   // By construction, the input type must be float.
15401   assert(EltVT == MVT::f32 && "Unexpected type!");
15402 
15403   // Check 1.2.
15404   SDNode *Use = *N->user_begin();
15405   if (Use->getOpcode() != ISD::BITCAST ||
15406       Use->getValueType(0).isFloatingPoint())
15407     return SDValue();
15408 
15409   // Check profitability.
15410   // Model is, if more than half of the relevant operands are bitcast from
15411   // i32, turn the build_vector into a sequence of insert_vector_elt.
15412   // Relevant operands are everything that is not statically
15413   // (i.e., at compile time) bitcasted.
15414   unsigned NumOfBitCastedElts = 0;
15415   unsigned NumElts = VT.getVectorNumElements();
15416   unsigned NumOfRelevantElts = NumElts;
15417   for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
15418     SDValue Elt = N->getOperand(Idx);
15419     if (Elt->getOpcode() == ISD::BITCAST) {
15420       // Assume only bit cast to i32 will go away.
15421       if (Elt->getOperand(0).getValueType() == MVT::i32)
15422         ++NumOfBitCastedElts;
15423     } else if (Elt.isUndef() || isa<ConstantSDNode>(Elt))
15424       // Constants are statically casted, thus do not count them as
15425       // relevant operands.
15426       --NumOfRelevantElts;
15427   }
15428 
15429   // Check if more than half of the elements require a non-free bitcast.
15430   if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
15431     return SDValue();
15432 
15433   SelectionDAG &DAG = DCI.DAG;
15434   // Create the new vector type.
15435   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
15436   // Check if the type is legal.
15437   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15438   if (!TLI.isTypeLegal(VecVT))
15439     return SDValue();
15440 
15441   // Combine:
15442   // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
15443   // => BITCAST INSERT_VECTOR_ELT
15444   //                      (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
15445   //                      (BITCAST EN), N.
15446   SDValue Vec = DAG.getUNDEF(VecVT);
15447   SDLoc dl(N);
15448   for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
15449     SDValue V = N->getOperand(Idx);
15450     if (V.isUndef())
15451       continue;
15452     if (V.getOpcode() == ISD::BITCAST &&
15453         V->getOperand(0).getValueType() == MVT::i32)
15454       // Fold obvious case.
15455       V = V.getOperand(0);
15456     else {
15457       V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
15458       // Make the DAGCombiner fold the bitcasts.
15459       DCI.AddToWorklist(V.getNode());
15460     }
15461     SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32);
15462     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
15463   }
15464   Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
15465   // Make the DAGCombiner fold the bitcasts.
15466   DCI.AddToWorklist(Vec.getNode());
15467   return Vec;
15468 }
15469 
15470 static SDValue
PerformPREDICATE_CASTCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI)15471 PerformPREDICATE_CASTCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
15472   EVT VT = N->getValueType(0);
15473   SDValue Op = N->getOperand(0);
15474   SDLoc dl(N);
15475 
15476   // PREDICATE_CAST(PREDICATE_CAST(x)) == PREDICATE_CAST(x)
15477   if (Op->getOpcode() == ARMISD::PREDICATE_CAST) {
15478     // If the valuetypes are the same, we can remove the cast entirely.
15479     if (Op->getOperand(0).getValueType() == VT)
15480       return Op->getOperand(0);
15481     return DCI.DAG.getNode(ARMISD::PREDICATE_CAST, dl, VT, Op->getOperand(0));
15482   }
15483 
15484   // Turn pred_cast(xor x, -1) into xor(pred_cast x, -1), in order to produce
15485   // more VPNOT which might get folded as else predicates.
15486   if (Op.getValueType() == MVT::i32 && isBitwiseNot(Op)) {
15487     SDValue X =
15488         DCI.DAG.getNode(ARMISD::PREDICATE_CAST, dl, VT, Op->getOperand(0));
15489     SDValue C = DCI.DAG.getNode(ARMISD::PREDICATE_CAST, dl, VT,
15490                                 DCI.DAG.getConstant(65535, dl, MVT::i32));
15491     return DCI.DAG.getNode(ISD::XOR, dl, VT, X, C);
15492   }
15493 
15494   // Only the bottom 16 bits of the source register are used.
15495   if (Op.getValueType() == MVT::i32) {
15496     APInt DemandedMask = APInt::getLowBitsSet(32, 16);
15497     const TargetLowering &TLI = DCI.DAG.getTargetLoweringInfo();
15498     if (TLI.SimplifyDemandedBits(Op, DemandedMask, DCI))
15499       return SDValue(N, 0);
15500   }
15501   return SDValue();
15502 }
15503 
PerformVECTOR_REG_CASTCombine(SDNode * N,SelectionDAG & DAG,const ARMSubtarget * ST)15504 static SDValue PerformVECTOR_REG_CASTCombine(SDNode *N, SelectionDAG &DAG,
15505                                              const ARMSubtarget *ST) {
15506   EVT VT = N->getValueType(0);
15507   SDValue Op = N->getOperand(0);
15508   SDLoc dl(N);
15509 
15510   // Under Little endian, a VECTOR_REG_CAST is equivalent to a BITCAST
15511   if (ST->isLittle())
15512     return DAG.getNode(ISD::BITCAST, dl, VT, Op);
15513 
15514   // VT VECTOR_REG_CAST (VT Op) -> Op
15515   if (Op.getValueType() == VT)
15516     return Op;
15517   // VECTOR_REG_CAST undef -> undef
15518   if (Op.isUndef())
15519     return DAG.getUNDEF(VT);
15520 
15521   // VECTOR_REG_CAST(VECTOR_REG_CAST(x)) == VECTOR_REG_CAST(x)
15522   if (Op->getOpcode() == ARMISD::VECTOR_REG_CAST) {
15523     // If the valuetypes are the same, we can remove the cast entirely.
15524     if (Op->getOperand(0).getValueType() == VT)
15525       return Op->getOperand(0);
15526     return DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, VT, Op->getOperand(0));
15527   }
15528 
15529   return SDValue();
15530 }
15531 
PerformVCMPCombine(SDNode * N,SelectionDAG & DAG,const ARMSubtarget * Subtarget)15532 static SDValue PerformVCMPCombine(SDNode *N, SelectionDAG &DAG,
15533                                   const ARMSubtarget *Subtarget) {
15534   if (!Subtarget->hasMVEIntegerOps())
15535     return SDValue();
15536 
15537   EVT VT = N->getValueType(0);
15538   SDValue Op0 = N->getOperand(0);
15539   SDValue Op1 = N->getOperand(1);
15540   ARMCC::CondCodes Cond = (ARMCC::CondCodes)N->getConstantOperandVal(2);
15541   SDLoc dl(N);
15542 
15543   // vcmp X, 0, cc -> vcmpz X, cc
15544   if (isZeroVector(Op1))
15545     return DAG.getNode(ARMISD::VCMPZ, dl, VT, Op0, N->getOperand(2));
15546 
15547   unsigned SwappedCond = getSwappedCondition(Cond);
15548   if (isValidMVECond(SwappedCond, VT.isFloatingPoint())) {
15549     // vcmp 0, X, cc -> vcmpz X, reversed(cc)
15550     if (isZeroVector(Op0))
15551       return DAG.getNode(ARMISD::VCMPZ, dl, VT, Op1,
15552                          DAG.getConstant(SwappedCond, dl, MVT::i32));
15553     // vcmp vdup(Y), X, cc -> vcmp X, vdup(Y), reversed(cc)
15554     if (Op0->getOpcode() == ARMISD::VDUP && Op1->getOpcode() != ARMISD::VDUP)
15555       return DAG.getNode(ARMISD::VCMP, dl, VT, Op1, Op0,
15556                          DAG.getConstant(SwappedCond, dl, MVT::i32));
15557   }
15558 
15559   return SDValue();
15560 }
15561 
15562 /// PerformInsertEltCombine - Target-specific dag combine xforms for
15563 /// ISD::INSERT_VECTOR_ELT.
PerformInsertEltCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI)15564 static SDValue PerformInsertEltCombine(SDNode *N,
15565                                        TargetLowering::DAGCombinerInfo &DCI) {
15566   // Bitcast an i64 load inserted into a vector to f64.
15567   // Otherwise, the i64 value will be legalized to a pair of i32 values.
15568   EVT VT = N->getValueType(0);
15569   SDNode *Elt = N->getOperand(1).getNode();
15570   if (VT.getVectorElementType() != MVT::i64 ||
15571       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
15572     return SDValue();
15573 
15574   SelectionDAG &DAG = DCI.DAG;
15575   SDLoc dl(N);
15576   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
15577                                  VT.getVectorNumElements());
15578   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
15579   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
15580   // Make the DAGCombiner fold the bitcasts.
15581   DCI.AddToWorklist(Vec.getNode());
15582   DCI.AddToWorklist(V.getNode());
15583   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
15584                                Vec, V, N->getOperand(2));
15585   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
15586 }
15587 
15588 // Convert a pair of extracts from the same base vector to a VMOVRRD. Either
15589 // directly or bitcast to an integer if the original is a float vector.
15590 // extract(x, n); extract(x, n+1)  ->  VMOVRRD(extract v2f64 x, n/2)
15591 // bitcast(extract(x, n)); bitcast(extract(x, n+1))  ->  VMOVRRD(extract x, n/2)
15592 static SDValue
PerformExtractEltToVMOVRRD(SDNode * N,TargetLowering::DAGCombinerInfo & DCI)15593 PerformExtractEltToVMOVRRD(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
15594   EVT VT = N->getValueType(0);
15595   SDLoc dl(N);
15596 
15597   if (!DCI.isAfterLegalizeDAG() || VT != MVT::i32 ||
15598       !DCI.DAG.getTargetLoweringInfo().isTypeLegal(MVT::f64))
15599     return SDValue();
15600 
15601   SDValue Ext = SDValue(N, 0);
15602   if (Ext.getOpcode() == ISD::BITCAST &&
15603       Ext.getOperand(0).getValueType() == MVT::f32)
15604     Ext = Ext.getOperand(0);
15605   if (Ext.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
15606       !isa<ConstantSDNode>(Ext.getOperand(1)) ||
15607       Ext.getConstantOperandVal(1) % 2 != 0)
15608     return SDValue();
15609   if (Ext->hasOneUse() && (Ext->user_begin()->getOpcode() == ISD::SINT_TO_FP ||
15610                            Ext->user_begin()->getOpcode() == ISD::UINT_TO_FP))
15611     return SDValue();
15612 
15613   SDValue Op0 = Ext.getOperand(0);
15614   EVT VecVT = Op0.getValueType();
15615   unsigned ResNo = Op0.getResNo();
15616   unsigned Lane = Ext.getConstantOperandVal(1);
15617   if (VecVT.getVectorNumElements() != 4)
15618     return SDValue();
15619 
15620   // Find another extract, of Lane + 1
15621   auto OtherIt = find_if(Op0->users(), [&](SDNode *V) {
15622     return V->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
15623            isa<ConstantSDNode>(V->getOperand(1)) &&
15624            V->getConstantOperandVal(1) == Lane + 1 &&
15625            V->getOperand(0).getResNo() == ResNo;
15626   });
15627   if (OtherIt == Op0->users().end())
15628     return SDValue();
15629 
15630   // For float extracts, we need to be converting to a i32 for both vector
15631   // lanes.
15632   SDValue OtherExt(*OtherIt, 0);
15633   if (OtherExt.getValueType() != MVT::i32) {
15634     if (!OtherExt->hasOneUse() ||
15635         OtherExt->user_begin()->getOpcode() != ISD::BITCAST ||
15636         OtherExt->user_begin()->getValueType(0) != MVT::i32)
15637       return SDValue();
15638     OtherExt = SDValue(*OtherExt->user_begin(), 0);
15639   }
15640 
15641   // Convert the type to a f64 and extract with a VMOVRRD.
15642   SDValue F64 = DCI.DAG.getNode(
15643       ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
15644       DCI.DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, MVT::v2f64, Op0),
15645       DCI.DAG.getConstant(Ext.getConstantOperandVal(1) / 2, dl, MVT::i32));
15646   SDValue VMOVRRD =
15647       DCI.DAG.getNode(ARMISD::VMOVRRD, dl, {MVT::i32, MVT::i32}, F64);
15648 
15649   DCI.CombineTo(OtherExt.getNode(), SDValue(VMOVRRD.getNode(), 1));
15650   return VMOVRRD;
15651 }
15652 
PerformExtractEltCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI,const ARMSubtarget * ST)15653 static SDValue PerformExtractEltCombine(SDNode *N,
15654                                         TargetLowering::DAGCombinerInfo &DCI,
15655                                         const ARMSubtarget *ST) {
15656   SDValue Op0 = N->getOperand(0);
15657   EVT VT = N->getValueType(0);
15658   SDLoc dl(N);
15659 
15660   // extract (vdup x) -> x
15661   if (Op0->getOpcode() == ARMISD::VDUP) {
15662     SDValue X = Op0->getOperand(0);
15663     if (VT == MVT::f16 && X.getValueType() == MVT::i32)
15664       return DCI.DAG.getNode(ARMISD::VMOVhr, dl, VT, X);
15665     if (VT == MVT::i32 && X.getValueType() == MVT::f16)
15666       return DCI.DAG.getNode(ARMISD::VMOVrh, dl, VT, X);
15667     if (VT == MVT::f32 && X.getValueType() == MVT::i32)
15668       return DCI.DAG.getNode(ISD::BITCAST, dl, VT, X);
15669 
15670     while (X.getValueType() != VT && X->getOpcode() == ISD::BITCAST)
15671       X = X->getOperand(0);
15672     if (X.getValueType() == VT)
15673       return X;
15674   }
15675 
15676   // extract ARM_BUILD_VECTOR -> x
15677   if (Op0->getOpcode() == ARMISD::BUILD_VECTOR &&
15678       isa<ConstantSDNode>(N->getOperand(1)) &&
15679       N->getConstantOperandVal(1) < Op0.getNumOperands()) {
15680     return Op0.getOperand(N->getConstantOperandVal(1));
15681   }
15682 
15683   // extract(bitcast(BUILD_VECTOR(VMOVDRR(a, b), ..))) -> a or b
15684   if (Op0.getValueType() == MVT::v4i32 &&
15685       isa<ConstantSDNode>(N->getOperand(1)) &&
15686       Op0.getOpcode() == ISD::BITCAST &&
15687       Op0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
15688       Op0.getOperand(0).getValueType() == MVT::v2f64) {
15689     SDValue BV = Op0.getOperand(0);
15690     unsigned Offset = N->getConstantOperandVal(1);
15691     SDValue MOV = BV.getOperand(Offset < 2 ? 0 : 1);
15692     if (MOV.getOpcode() == ARMISD::VMOVDRR)
15693       return MOV.getOperand(ST->isLittle() ? Offset % 2 : 1 - Offset % 2);
15694   }
15695 
15696   // extract x, n; extract x, n+1  ->  VMOVRRD x
15697   if (SDValue R = PerformExtractEltToVMOVRRD(N, DCI))
15698     return R;
15699 
15700   // extract (MVETrunc(x)) -> extract x
15701   if (Op0->getOpcode() == ARMISD::MVETRUNC) {
15702     unsigned Idx = N->getConstantOperandVal(1);
15703     unsigned Vec =
15704         Idx / Op0->getOperand(0).getValueType().getVectorNumElements();
15705     unsigned SubIdx =
15706         Idx % Op0->getOperand(0).getValueType().getVectorNumElements();
15707     return DCI.DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Op0.getOperand(Vec),
15708                            DCI.DAG.getConstant(SubIdx, dl, MVT::i32));
15709   }
15710 
15711   return SDValue();
15712 }
15713 
PerformSignExtendInregCombine(SDNode * N,SelectionDAG & DAG)15714 static SDValue PerformSignExtendInregCombine(SDNode *N, SelectionDAG &DAG) {
15715   SDValue Op = N->getOperand(0);
15716   EVT VT = N->getValueType(0);
15717 
15718   // sext_inreg(VGETLANEu) -> VGETLANEs
15719   if (Op.getOpcode() == ARMISD::VGETLANEu &&
15720       cast<VTSDNode>(N->getOperand(1))->getVT() ==
15721           Op.getOperand(0).getValueType().getScalarType())
15722     return DAG.getNode(ARMISD::VGETLANEs, SDLoc(N), VT, Op.getOperand(0),
15723                        Op.getOperand(1));
15724 
15725   return SDValue();
15726 }
15727 
15728 static SDValue
PerformInsertSubvectorCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI)15729 PerformInsertSubvectorCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
15730   SDValue Vec = N->getOperand(0);
15731   SDValue SubVec = N->getOperand(1);
15732   uint64_t IdxVal = N->getConstantOperandVal(2);
15733   EVT VecVT = Vec.getValueType();
15734   EVT SubVT = SubVec.getValueType();
15735 
15736   // Only do this for legal fixed vector types.
15737   if (!VecVT.isFixedLengthVector() ||
15738       !DCI.DAG.getTargetLoweringInfo().isTypeLegal(VecVT) ||
15739       !DCI.DAG.getTargetLoweringInfo().isTypeLegal(SubVT))
15740     return SDValue();
15741 
15742   // Ignore widening patterns.
15743   if (IdxVal == 0 && Vec.isUndef())
15744     return SDValue();
15745 
15746   // Subvector must be half the width and an "aligned" insertion.
15747   unsigned NumSubElts = SubVT.getVectorNumElements();
15748   if ((SubVT.getSizeInBits() * 2) != VecVT.getSizeInBits() ||
15749       (IdxVal != 0 && IdxVal != NumSubElts))
15750     return SDValue();
15751 
15752   // Fold insert_subvector -> concat_vectors
15753   // insert_subvector(Vec,Sub,lo) -> concat_vectors(Sub,extract(Vec,hi))
15754   // insert_subvector(Vec,Sub,hi) -> concat_vectors(extract(Vec,lo),Sub)
15755   SDLoc DL(N);
15756   SDValue Lo, Hi;
15757   if (IdxVal == 0) {
15758     Lo = SubVec;
15759     Hi = DCI.DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, Vec,
15760                          DCI.DAG.getVectorIdxConstant(NumSubElts, DL));
15761   } else {
15762     Lo = DCI.DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, Vec,
15763                          DCI.DAG.getVectorIdxConstant(0, DL));
15764     Hi = SubVec;
15765   }
15766   return DCI.DAG.getNode(ISD::CONCAT_VECTORS, DL, VecVT, Lo, Hi);
15767 }
15768 
15769 // shuffle(MVETrunc(x, y)) -> VMOVN(x, y)
PerformShuffleVMOVNCombine(ShuffleVectorSDNode * N,SelectionDAG & DAG)15770 static SDValue PerformShuffleVMOVNCombine(ShuffleVectorSDNode *N,
15771                                           SelectionDAG &DAG) {
15772   SDValue Trunc = N->getOperand(0);
15773   EVT VT = Trunc.getValueType();
15774   if (Trunc.getOpcode() != ARMISD::MVETRUNC || !N->getOperand(1).isUndef())
15775     return SDValue();
15776 
15777   SDLoc DL(Trunc);
15778   if (isVMOVNTruncMask(N->getMask(), VT, false))
15779     return DAG.getNode(
15780         ARMISD::VMOVN, DL, VT,
15781         DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, VT, Trunc.getOperand(0)),
15782         DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, VT, Trunc.getOperand(1)),
15783         DAG.getConstant(1, DL, MVT::i32));
15784   else if (isVMOVNTruncMask(N->getMask(), VT, true))
15785     return DAG.getNode(
15786         ARMISD::VMOVN, DL, VT,
15787         DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, VT, Trunc.getOperand(1)),
15788         DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, VT, Trunc.getOperand(0)),
15789         DAG.getConstant(1, DL, MVT::i32));
15790   return SDValue();
15791 }
15792 
15793 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
15794 /// ISD::VECTOR_SHUFFLE.
PerformVECTOR_SHUFFLECombine(SDNode * N,SelectionDAG & DAG)15795 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
15796   if (SDValue R = PerformShuffleVMOVNCombine(cast<ShuffleVectorSDNode>(N), DAG))
15797     return R;
15798 
15799   // The LLVM shufflevector instruction does not require the shuffle mask
15800   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
15801   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
15802   // operands do not match the mask length, they are extended by concatenating
15803   // them with undef vectors.  That is probably the right thing for other
15804   // targets, but for NEON it is better to concatenate two double-register
15805   // size vector operands into a single quad-register size vector.  Do that
15806   // transformation here:
15807   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
15808   //   shuffle(concat(v1, v2), undef)
15809   SDValue Op0 = N->getOperand(0);
15810   SDValue Op1 = N->getOperand(1);
15811   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
15812       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
15813       Op0.getNumOperands() != 2 ||
15814       Op1.getNumOperands() != 2)
15815     return SDValue();
15816   SDValue Concat0Op1 = Op0.getOperand(1);
15817   SDValue Concat1Op1 = Op1.getOperand(1);
15818   if (!Concat0Op1.isUndef() || !Concat1Op1.isUndef())
15819     return SDValue();
15820   // Skip the transformation if any of the types are illegal.
15821   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15822   EVT VT = N->getValueType(0);
15823   if (!TLI.isTypeLegal(VT) ||
15824       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
15825       !TLI.isTypeLegal(Concat1Op1.getValueType()))
15826     return SDValue();
15827 
15828   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
15829                                   Op0.getOperand(0), Op1.getOperand(0));
15830   // Translate the shuffle mask.
15831   SmallVector<int, 16> NewMask;
15832   unsigned NumElts = VT.getVectorNumElements();
15833   unsigned HalfElts = NumElts/2;
15834   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
15835   for (unsigned n = 0; n < NumElts; ++n) {
15836     int MaskElt = SVN->getMaskElt(n);
15837     int NewElt = -1;
15838     if (MaskElt < (int)HalfElts)
15839       NewElt = MaskElt;
15840     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
15841       NewElt = HalfElts + MaskElt - NumElts;
15842     NewMask.push_back(NewElt);
15843   }
15844   return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
15845                               DAG.getUNDEF(VT), NewMask);
15846 }
15847 
15848 /// Load/store instruction that can be merged with a base address
15849 /// update
15850 struct BaseUpdateTarget {
15851   SDNode *N;
15852   bool isIntrinsic;
15853   bool isStore;
15854   unsigned AddrOpIdx;
15855 };
15856 
15857 struct BaseUpdateUser {
15858   /// Instruction that updates a pointer
15859   SDNode *N;
15860   /// Pointer increment operand
15861   SDValue Inc;
15862   /// Pointer increment value if it is a constant, or 0 otherwise
15863   unsigned ConstInc;
15864 };
15865 
isValidBaseUpdate(SDNode * N,SDNode * User)15866 static bool isValidBaseUpdate(SDNode *N, SDNode *User) {
15867   // Check that the add is independent of the load/store.
15868   // Otherwise, folding it would create a cycle. Search through Addr
15869   // as well, since the User may not be a direct user of Addr and
15870   // only share a base pointer.
15871   SmallPtrSet<const SDNode *, 32> Visited;
15872   SmallVector<const SDNode *, 16> Worklist;
15873   Worklist.push_back(N);
15874   Worklist.push_back(User);
15875   const unsigned MaxSteps = 1024;
15876   if (SDNode::hasPredecessorHelper(N, Visited, Worklist, MaxSteps) ||
15877       SDNode::hasPredecessorHelper(User, Visited, Worklist, MaxSteps))
15878     return false;
15879   return true;
15880 }
15881 
TryCombineBaseUpdate(struct BaseUpdateTarget & Target,struct BaseUpdateUser & User,bool SimpleConstIncOnly,TargetLowering::DAGCombinerInfo & DCI)15882 static bool TryCombineBaseUpdate(struct BaseUpdateTarget &Target,
15883                                  struct BaseUpdateUser &User,
15884                                  bool SimpleConstIncOnly,
15885                                  TargetLowering::DAGCombinerInfo &DCI) {
15886   SelectionDAG &DAG = DCI.DAG;
15887   SDNode *N = Target.N;
15888   MemSDNode *MemN = cast<MemSDNode>(N);
15889   SDLoc dl(N);
15890 
15891   // Find the new opcode for the updating load/store.
15892   bool isLoadOp = true;
15893   bool isLaneOp = false;
15894   // Workaround for vst1x and vld1x intrinsics which do not have alignment
15895   // as an operand.
15896   bool hasAlignment = true;
15897   unsigned NewOpc = 0;
15898   unsigned NumVecs = 0;
15899   if (Target.isIntrinsic) {
15900     unsigned IntNo = N->getConstantOperandVal(1);
15901     switch (IntNo) {
15902     default:
15903       llvm_unreachable("unexpected intrinsic for Neon base update");
15904     case Intrinsic::arm_neon_vld1:
15905       NewOpc = ARMISD::VLD1_UPD;
15906       NumVecs = 1;
15907       break;
15908     case Intrinsic::arm_neon_vld2:
15909       NewOpc = ARMISD::VLD2_UPD;
15910       NumVecs = 2;
15911       break;
15912     case Intrinsic::arm_neon_vld3:
15913       NewOpc = ARMISD::VLD3_UPD;
15914       NumVecs = 3;
15915       break;
15916     case Intrinsic::arm_neon_vld4:
15917       NewOpc = ARMISD::VLD4_UPD;
15918       NumVecs = 4;
15919       break;
15920     case Intrinsic::arm_neon_vld1x2:
15921       NewOpc = ARMISD::VLD1x2_UPD;
15922       NumVecs = 2;
15923       hasAlignment = false;
15924       break;
15925     case Intrinsic::arm_neon_vld1x3:
15926       NewOpc = ARMISD::VLD1x3_UPD;
15927       NumVecs = 3;
15928       hasAlignment = false;
15929       break;
15930     case Intrinsic::arm_neon_vld1x4:
15931       NewOpc = ARMISD::VLD1x4_UPD;
15932       NumVecs = 4;
15933       hasAlignment = false;
15934       break;
15935     case Intrinsic::arm_neon_vld2dup:
15936       NewOpc = ARMISD::VLD2DUP_UPD;
15937       NumVecs = 2;
15938       break;
15939     case Intrinsic::arm_neon_vld3dup:
15940       NewOpc = ARMISD::VLD3DUP_UPD;
15941       NumVecs = 3;
15942       break;
15943     case Intrinsic::arm_neon_vld4dup:
15944       NewOpc = ARMISD::VLD4DUP_UPD;
15945       NumVecs = 4;
15946       break;
15947     case Intrinsic::arm_neon_vld2lane:
15948       NewOpc = ARMISD::VLD2LN_UPD;
15949       NumVecs = 2;
15950       isLaneOp = true;
15951       break;
15952     case Intrinsic::arm_neon_vld3lane:
15953       NewOpc = ARMISD::VLD3LN_UPD;
15954       NumVecs = 3;
15955       isLaneOp = true;
15956       break;
15957     case Intrinsic::arm_neon_vld4lane:
15958       NewOpc = ARMISD::VLD4LN_UPD;
15959       NumVecs = 4;
15960       isLaneOp = true;
15961       break;
15962     case Intrinsic::arm_neon_vst1:
15963       NewOpc = ARMISD::VST1_UPD;
15964       NumVecs = 1;
15965       isLoadOp = false;
15966       break;
15967     case Intrinsic::arm_neon_vst2:
15968       NewOpc = ARMISD::VST2_UPD;
15969       NumVecs = 2;
15970       isLoadOp = false;
15971       break;
15972     case Intrinsic::arm_neon_vst3:
15973       NewOpc = ARMISD::VST3_UPD;
15974       NumVecs = 3;
15975       isLoadOp = false;
15976       break;
15977     case Intrinsic::arm_neon_vst4:
15978       NewOpc = ARMISD::VST4_UPD;
15979       NumVecs = 4;
15980       isLoadOp = false;
15981       break;
15982     case Intrinsic::arm_neon_vst2lane:
15983       NewOpc = ARMISD::VST2LN_UPD;
15984       NumVecs = 2;
15985       isLoadOp = false;
15986       isLaneOp = true;
15987       break;
15988     case Intrinsic::arm_neon_vst3lane:
15989       NewOpc = ARMISD::VST3LN_UPD;
15990       NumVecs = 3;
15991       isLoadOp = false;
15992       isLaneOp = true;
15993       break;
15994     case Intrinsic::arm_neon_vst4lane:
15995       NewOpc = ARMISD::VST4LN_UPD;
15996       NumVecs = 4;
15997       isLoadOp = false;
15998       isLaneOp = true;
15999       break;
16000     case Intrinsic::arm_neon_vst1x2:
16001       NewOpc = ARMISD::VST1x2_UPD;
16002       NumVecs = 2;
16003       isLoadOp = false;
16004       hasAlignment = false;
16005       break;
16006     case Intrinsic::arm_neon_vst1x3:
16007       NewOpc = ARMISD::VST1x3_UPD;
16008       NumVecs = 3;
16009       isLoadOp = false;
16010       hasAlignment = false;
16011       break;
16012     case Intrinsic::arm_neon_vst1x4:
16013       NewOpc = ARMISD::VST1x4_UPD;
16014       NumVecs = 4;
16015       isLoadOp = false;
16016       hasAlignment = false;
16017       break;
16018     }
16019   } else {
16020     isLaneOp = true;
16021     switch (N->getOpcode()) {
16022     default:
16023       llvm_unreachable("unexpected opcode for Neon base update");
16024     case ARMISD::VLD1DUP:
16025       NewOpc = ARMISD::VLD1DUP_UPD;
16026       NumVecs = 1;
16027       break;
16028     case ARMISD::VLD2DUP:
16029       NewOpc = ARMISD::VLD2DUP_UPD;
16030       NumVecs = 2;
16031       break;
16032     case ARMISD::VLD3DUP:
16033       NewOpc = ARMISD::VLD3DUP_UPD;
16034       NumVecs = 3;
16035       break;
16036     case ARMISD::VLD4DUP:
16037       NewOpc = ARMISD::VLD4DUP_UPD;
16038       NumVecs = 4;
16039       break;
16040     case ISD::LOAD:
16041       NewOpc = ARMISD::VLD1_UPD;
16042       NumVecs = 1;
16043       isLaneOp = false;
16044       break;
16045     case ISD::STORE:
16046       NewOpc = ARMISD::VST1_UPD;
16047       NumVecs = 1;
16048       isLaneOp = false;
16049       isLoadOp = false;
16050       break;
16051     }
16052   }
16053 
16054   // Find the size of memory referenced by the load/store.
16055   EVT VecTy;
16056   if (isLoadOp) {
16057     VecTy = N->getValueType(0);
16058   } else if (Target.isIntrinsic) {
16059     VecTy = N->getOperand(Target.AddrOpIdx + 1).getValueType();
16060   } else {
16061     assert(Target.isStore &&
16062            "Node has to be a load, a store, or an intrinsic!");
16063     VecTy = N->getOperand(1).getValueType();
16064   }
16065 
16066   bool isVLDDUPOp =
16067       NewOpc == ARMISD::VLD1DUP_UPD || NewOpc == ARMISD::VLD2DUP_UPD ||
16068       NewOpc == ARMISD::VLD3DUP_UPD || NewOpc == ARMISD::VLD4DUP_UPD;
16069 
16070   unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
16071   if (isLaneOp || isVLDDUPOp)
16072     NumBytes /= VecTy.getVectorNumElements();
16073 
16074   if (NumBytes >= 3 * 16 && User.ConstInc != NumBytes) {
16075     // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
16076     // separate instructions that make it harder to use a non-constant update.
16077     return false;
16078   }
16079 
16080   if (SimpleConstIncOnly && User.ConstInc != NumBytes)
16081     return false;
16082 
16083   if (!isValidBaseUpdate(N, User.N))
16084     return false;
16085 
16086   // OK, we found an ADD we can fold into the base update.
16087   // Now, create a _UPD node, taking care of not breaking alignment.
16088 
16089   EVT AlignedVecTy = VecTy;
16090   Align Alignment = MemN->getAlign();
16091 
16092   // If this is a less-than-standard-aligned load/store, change the type to
16093   // match the standard alignment.
16094   // The alignment is overlooked when selecting _UPD variants; and it's
16095   // easier to introduce bitcasts here than fix that.
16096   // There are 3 ways to get to this base-update combine:
16097   // - intrinsics: they are assumed to be properly aligned (to the standard
16098   //   alignment of the memory type), so we don't need to do anything.
16099   // - ARMISD::VLDx nodes: they are only generated from the aforementioned
16100   //   intrinsics, so, likewise, there's nothing to do.
16101   // - generic load/store instructions: the alignment is specified as an
16102   //   explicit operand, rather than implicitly as the standard alignment
16103   //   of the memory type (like the intrisics).  We need to change the
16104   //   memory type to match the explicit alignment.  That way, we don't
16105   //   generate non-standard-aligned ARMISD::VLDx nodes.
16106   if (isa<LSBaseSDNode>(N)) {
16107     if (Alignment.value() < VecTy.getScalarSizeInBits() / 8) {
16108       MVT EltTy = MVT::getIntegerVT(Alignment.value() * 8);
16109       assert(NumVecs == 1 && "Unexpected multi-element generic load/store.");
16110       assert(!isLaneOp && "Unexpected generic load/store lane.");
16111       unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8);
16112       AlignedVecTy = MVT::getVectorVT(EltTy, NumElts);
16113     }
16114     // Don't set an explicit alignment on regular load/stores that we want
16115     // to transform to VLD/VST 1_UPD nodes.
16116     // This matches the behavior of regular load/stores, which only get an
16117     // explicit alignment if the MMO alignment is larger than the standard
16118     // alignment of the memory type.
16119     // Intrinsics, however, always get an explicit alignment, set to the
16120     // alignment of the MMO.
16121     Alignment = Align(1);
16122   }
16123 
16124   // Create the new updating load/store node.
16125   // First, create an SDVTList for the new updating node's results.
16126   EVT Tys[6];
16127   unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
16128   unsigned n;
16129   for (n = 0; n < NumResultVecs; ++n)
16130     Tys[n] = AlignedVecTy;
16131   Tys[n++] = MVT::i32;
16132   Tys[n] = MVT::Other;
16133   SDVTList SDTys = DAG.getVTList(ArrayRef(Tys, NumResultVecs + 2));
16134 
16135   // Then, gather the new node's operands.
16136   SmallVector<SDValue, 8> Ops;
16137   Ops.push_back(N->getOperand(0)); // incoming chain
16138   Ops.push_back(N->getOperand(Target.AddrOpIdx));
16139   Ops.push_back(User.Inc);
16140 
16141   if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) {
16142     // Try to match the intrinsic's signature
16143     Ops.push_back(StN->getValue());
16144   } else {
16145     // Loads (and of course intrinsics) match the intrinsics' signature,
16146     // so just add all but the alignment operand.
16147     unsigned LastOperand =
16148         hasAlignment ? N->getNumOperands() - 1 : N->getNumOperands();
16149     for (unsigned i = Target.AddrOpIdx + 1; i < LastOperand; ++i)
16150       Ops.push_back(N->getOperand(i));
16151   }
16152 
16153   // For all node types, the alignment operand is always the last one.
16154   Ops.push_back(DAG.getConstant(Alignment.value(), dl, MVT::i32));
16155 
16156   // If this is a non-standard-aligned STORE, the penultimate operand is the
16157   // stored value.  Bitcast it to the aligned type.
16158   if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) {
16159     SDValue &StVal = Ops[Ops.size() - 2];
16160     StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal);
16161   }
16162 
16163   EVT LoadVT = isLaneOp ? VecTy.getVectorElementType() : AlignedVecTy;
16164   SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys, Ops, LoadVT,
16165                                          MemN->getMemOperand());
16166 
16167   // Update the uses.
16168   SmallVector<SDValue, 5> NewResults;
16169   for (unsigned i = 0; i < NumResultVecs; ++i)
16170     NewResults.push_back(SDValue(UpdN.getNode(), i));
16171 
16172   // If this is an non-standard-aligned LOAD, the first result is the loaded
16173   // value.  Bitcast it to the expected result type.
16174   if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) {
16175     SDValue &LdVal = NewResults[0];
16176     LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal);
16177   }
16178 
16179   NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1)); // chain
16180   DCI.CombineTo(N, NewResults);
16181   DCI.CombineTo(User.N, SDValue(UpdN.getNode(), NumResultVecs));
16182 
16183   return true;
16184 }
16185 
16186 // If (opcode ptr inc) is and ADD-like instruction, return the
16187 // increment value. Otherwise return 0.
getPointerConstIncrement(unsigned Opcode,SDValue Ptr,SDValue Inc,const SelectionDAG & DAG)16188 static unsigned getPointerConstIncrement(unsigned Opcode, SDValue Ptr,
16189                                          SDValue Inc, const SelectionDAG &DAG) {
16190   ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode());
16191   if (!CInc)
16192     return 0;
16193 
16194   switch (Opcode) {
16195   case ARMISD::VLD1_UPD:
16196   case ISD::ADD:
16197     return CInc->getZExtValue();
16198   case ISD::OR: {
16199     if (DAG.haveNoCommonBitsSet(Ptr, Inc)) {
16200       // (OR ptr inc) is the same as (ADD ptr inc)
16201       return CInc->getZExtValue();
16202     }
16203     return 0;
16204   }
16205   default:
16206     return 0;
16207   }
16208 }
16209 
findPointerConstIncrement(SDNode * N,SDValue * Ptr,SDValue * CInc)16210 static bool findPointerConstIncrement(SDNode *N, SDValue *Ptr, SDValue *CInc) {
16211   switch (N->getOpcode()) {
16212   case ISD::ADD:
16213   case ISD::OR: {
16214     if (isa<ConstantSDNode>(N->getOperand(1))) {
16215       *Ptr = N->getOperand(0);
16216       *CInc = N->getOperand(1);
16217       return true;
16218     }
16219     return false;
16220   }
16221   case ARMISD::VLD1_UPD: {
16222     if (isa<ConstantSDNode>(N->getOperand(2))) {
16223       *Ptr = N->getOperand(1);
16224       *CInc = N->getOperand(2);
16225       return true;
16226     }
16227     return false;
16228   }
16229   default:
16230     return false;
16231   }
16232 }
16233 
16234 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP,
16235 /// NEON load/store intrinsics, and generic vector load/stores, to merge
16236 /// base address updates.
16237 /// For generic load/stores, the memory type is assumed to be a vector.
16238 /// The caller is assumed to have checked legality.
CombineBaseUpdate(SDNode * N,TargetLowering::DAGCombinerInfo & DCI)16239 static SDValue CombineBaseUpdate(SDNode *N,
16240                                  TargetLowering::DAGCombinerInfo &DCI) {
16241   const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
16242                             N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
16243   const bool isStore = N->getOpcode() == ISD::STORE;
16244   const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1);
16245   BaseUpdateTarget Target = {N, isIntrinsic, isStore, AddrOpIdx};
16246 
16247   // Limit the number of possible base-updates we look at to prevent degenerate
16248   // cases.
16249   unsigned MaxBaseUpdates = ArmMaxBaseUpdatesToCheck;
16250 
16251   SDValue Addr = N->getOperand(AddrOpIdx);
16252 
16253   SmallVector<BaseUpdateUser, 8> BaseUpdates;
16254 
16255   // Search for a use of the address operand that is an increment.
16256   for (SDUse &Use : Addr->uses()) {
16257     SDNode *User = Use.getUser();
16258     if (Use.getResNo() != Addr.getResNo() || User->getNumOperands() != 2)
16259       continue;
16260 
16261     SDValue Inc = User->getOperand(Use.getOperandNo() == 1 ? 0 : 1);
16262     unsigned ConstInc =
16263         getPointerConstIncrement(User->getOpcode(), Addr, Inc, DCI.DAG);
16264 
16265     if (ConstInc || User->getOpcode() == ISD::ADD) {
16266       BaseUpdates.push_back({User, Inc, ConstInc});
16267       if (BaseUpdates.size() >= MaxBaseUpdates)
16268         break;
16269     }
16270   }
16271 
16272   // If the address is a constant pointer increment itself, find
16273   // another constant increment that has the same base operand
16274   SDValue Base;
16275   SDValue CInc;
16276   if (findPointerConstIncrement(Addr.getNode(), &Base, &CInc)) {
16277     unsigned Offset =
16278         getPointerConstIncrement(Addr->getOpcode(), Base, CInc, DCI.DAG);
16279     for (SDUse &Use : Base->uses()) {
16280 
16281       SDNode *User = Use.getUser();
16282       if (Use.getResNo() != Base.getResNo() || User == Addr.getNode() ||
16283           User->getNumOperands() != 2)
16284         continue;
16285 
16286       SDValue UserInc = User->getOperand(Use.getOperandNo() == 0 ? 1 : 0);
16287       unsigned UserOffset =
16288           getPointerConstIncrement(User->getOpcode(), Base, UserInc, DCI.DAG);
16289 
16290       if (!UserOffset || UserOffset <= Offset)
16291         continue;
16292 
16293       unsigned NewConstInc = UserOffset - Offset;
16294       SDValue NewInc = DCI.DAG.getConstant(NewConstInc, SDLoc(N), MVT::i32);
16295       BaseUpdates.push_back({User, NewInc, NewConstInc});
16296       if (BaseUpdates.size() >= MaxBaseUpdates)
16297         break;
16298     }
16299   }
16300 
16301   // Try to fold the load/store with an update that matches memory
16302   // access size. This should work well for sequential loads.
16303   unsigned NumValidUpd = BaseUpdates.size();
16304   for (unsigned I = 0; I < NumValidUpd; I++) {
16305     BaseUpdateUser &User = BaseUpdates[I];
16306     if (TryCombineBaseUpdate(Target, User, /*SimpleConstIncOnly=*/true, DCI))
16307       return SDValue();
16308   }
16309 
16310   // Try to fold with other users. Non-constant updates are considered
16311   // first, and constant updates are sorted to not break a sequence of
16312   // strided accesses (if there is any).
16313   llvm::stable_sort(BaseUpdates,
16314                     [](const BaseUpdateUser &LHS, const BaseUpdateUser &RHS) {
16315                       return LHS.ConstInc < RHS.ConstInc;
16316                     });
16317   for (BaseUpdateUser &User : BaseUpdates) {
16318     if (TryCombineBaseUpdate(Target, User, /*SimpleConstIncOnly=*/false, DCI))
16319       return SDValue();
16320   }
16321   return SDValue();
16322 }
16323 
PerformVLDCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI)16324 static SDValue PerformVLDCombine(SDNode *N,
16325                                  TargetLowering::DAGCombinerInfo &DCI) {
16326   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
16327     return SDValue();
16328 
16329   return CombineBaseUpdate(N, DCI);
16330 }
16331 
PerformMVEVLDCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI)16332 static SDValue PerformMVEVLDCombine(SDNode *N,
16333                                     TargetLowering::DAGCombinerInfo &DCI) {
16334   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
16335     return SDValue();
16336 
16337   SelectionDAG &DAG = DCI.DAG;
16338   SDValue Addr = N->getOperand(2);
16339   MemSDNode *MemN = cast<MemSDNode>(N);
16340   SDLoc dl(N);
16341 
16342   // For the stores, where there are multiple intrinsics we only actually want
16343   // to post-inc the last of the them.
16344   unsigned IntNo = N->getConstantOperandVal(1);
16345   if (IntNo == Intrinsic::arm_mve_vst2q && N->getConstantOperandVal(5) != 1)
16346     return SDValue();
16347   if (IntNo == Intrinsic::arm_mve_vst4q && N->getConstantOperandVal(7) != 3)
16348     return SDValue();
16349 
16350   // Search for a use of the address operand that is an increment.
16351   for (SDUse &Use : Addr->uses()) {
16352     SDNode *User = Use.getUser();
16353     if (User->getOpcode() != ISD::ADD || Use.getResNo() != Addr.getResNo())
16354       continue;
16355 
16356     // Check that the add is independent of the load/store.  Otherwise, folding
16357     // it would create a cycle. We can avoid searching through Addr as it's a
16358     // predecessor to both.
16359     SmallPtrSet<const SDNode *, 32> Visited;
16360     SmallVector<const SDNode *, 16> Worklist;
16361     Visited.insert(Addr.getNode());
16362     Worklist.push_back(N);
16363     Worklist.push_back(User);
16364     const unsigned MaxSteps = 1024;
16365     if (SDNode::hasPredecessorHelper(N, Visited, Worklist, MaxSteps) ||
16366         SDNode::hasPredecessorHelper(User, Visited, Worklist, MaxSteps))
16367       continue;
16368 
16369     // Find the new opcode for the updating load/store.
16370     bool isLoadOp = true;
16371     unsigned NewOpc = 0;
16372     unsigned NumVecs = 0;
16373     switch (IntNo) {
16374     default:
16375       llvm_unreachable("unexpected intrinsic for MVE VLDn combine");
16376     case Intrinsic::arm_mve_vld2q:
16377       NewOpc = ARMISD::VLD2_UPD;
16378       NumVecs = 2;
16379       break;
16380     case Intrinsic::arm_mve_vld4q:
16381       NewOpc = ARMISD::VLD4_UPD;
16382       NumVecs = 4;
16383       break;
16384     case Intrinsic::arm_mve_vst2q:
16385       NewOpc = ARMISD::VST2_UPD;
16386       NumVecs = 2;
16387       isLoadOp = false;
16388       break;
16389     case Intrinsic::arm_mve_vst4q:
16390       NewOpc = ARMISD::VST4_UPD;
16391       NumVecs = 4;
16392       isLoadOp = false;
16393       break;
16394     }
16395 
16396     // Find the size of memory referenced by the load/store.
16397     EVT VecTy;
16398     if (isLoadOp) {
16399       VecTy = N->getValueType(0);
16400     } else {
16401       VecTy = N->getOperand(3).getValueType();
16402     }
16403 
16404     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
16405 
16406     // If the increment is a constant, it must match the memory ref size.
16407     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
16408     ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode());
16409     if (!CInc || CInc->getZExtValue() != NumBytes)
16410       continue;
16411 
16412     // Create the new updating load/store node.
16413     // First, create an SDVTList for the new updating node's results.
16414     EVT Tys[6];
16415     unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
16416     unsigned n;
16417     for (n = 0; n < NumResultVecs; ++n)
16418       Tys[n] = VecTy;
16419     Tys[n++] = MVT::i32;
16420     Tys[n] = MVT::Other;
16421     SDVTList SDTys = DAG.getVTList(ArrayRef(Tys, NumResultVecs + 2));
16422 
16423     // Then, gather the new node's operands.
16424     SmallVector<SDValue, 8> Ops;
16425     Ops.push_back(N->getOperand(0)); // incoming chain
16426     Ops.push_back(N->getOperand(2)); // ptr
16427     Ops.push_back(Inc);
16428 
16429     for (unsigned i = 3; i < N->getNumOperands(); ++i)
16430       Ops.push_back(N->getOperand(i));
16431 
16432     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys, Ops, VecTy,
16433                                            MemN->getMemOperand());
16434 
16435     // Update the uses.
16436     SmallVector<SDValue, 5> NewResults;
16437     for (unsigned i = 0; i < NumResultVecs; ++i)
16438       NewResults.push_back(SDValue(UpdN.getNode(), i));
16439 
16440     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1)); // chain
16441     DCI.CombineTo(N, NewResults);
16442     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
16443 
16444     break;
16445   }
16446 
16447   return SDValue();
16448 }
16449 
16450 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
16451 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
16452 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
16453 /// return true.
CombineVLDDUP(SDNode * N,TargetLowering::DAGCombinerInfo & DCI)16454 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
16455   SelectionDAG &DAG = DCI.DAG;
16456   EVT VT = N->getValueType(0);
16457   // vldN-dup instructions only support 64-bit vectors for N > 1.
16458   if (!VT.is64BitVector())
16459     return false;
16460 
16461   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
16462   SDNode *VLD = N->getOperand(0).getNode();
16463   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
16464     return false;
16465   unsigned NumVecs = 0;
16466   unsigned NewOpc = 0;
16467   unsigned IntNo = VLD->getConstantOperandVal(1);
16468   if (IntNo == Intrinsic::arm_neon_vld2lane) {
16469     NumVecs = 2;
16470     NewOpc = ARMISD::VLD2DUP;
16471   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
16472     NumVecs = 3;
16473     NewOpc = ARMISD::VLD3DUP;
16474   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
16475     NumVecs = 4;
16476     NewOpc = ARMISD::VLD4DUP;
16477   } else {
16478     return false;
16479   }
16480 
16481   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
16482   // numbers match the load.
16483   unsigned VLDLaneNo = VLD->getConstantOperandVal(NumVecs + 3);
16484   for (SDUse &Use : VLD->uses()) {
16485     // Ignore uses of the chain result.
16486     if (Use.getResNo() == NumVecs)
16487       continue;
16488     SDNode *User = Use.getUser();
16489     if (User->getOpcode() != ARMISD::VDUPLANE ||
16490         VLDLaneNo != User->getConstantOperandVal(1))
16491       return false;
16492   }
16493 
16494   // Create the vldN-dup node.
16495   EVT Tys[5];
16496   unsigned n;
16497   for (n = 0; n < NumVecs; ++n)
16498     Tys[n] = VT;
16499   Tys[n] = MVT::Other;
16500   SDVTList SDTys = DAG.getVTList(ArrayRef(Tys, NumVecs + 1));
16501   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
16502   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
16503   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
16504                                            Ops, VLDMemInt->getMemoryVT(),
16505                                            VLDMemInt->getMemOperand());
16506 
16507   // Update the uses.
16508   for (SDUse &Use : VLD->uses()) {
16509     unsigned ResNo = Use.getResNo();
16510     // Ignore uses of the chain result.
16511     if (ResNo == NumVecs)
16512       continue;
16513     DCI.CombineTo(Use.getUser(), SDValue(VLDDup.getNode(), ResNo));
16514   }
16515 
16516   // Now the vldN-lane intrinsic is dead except for its chain result.
16517   // Update uses of the chain.
16518   std::vector<SDValue> VLDDupResults;
16519   for (unsigned n = 0; n < NumVecs; ++n)
16520     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
16521   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
16522   DCI.CombineTo(VLD, VLDDupResults);
16523 
16524   return true;
16525 }
16526 
16527 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
16528 /// ARMISD::VDUPLANE.
PerformVDUPLANECombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI,const ARMSubtarget * Subtarget)16529 static SDValue PerformVDUPLANECombine(SDNode *N,
16530                                       TargetLowering::DAGCombinerInfo &DCI,
16531                                       const ARMSubtarget *Subtarget) {
16532   SDValue Op = N->getOperand(0);
16533   EVT VT = N->getValueType(0);
16534 
16535   // On MVE, we just convert the VDUPLANE to a VDUP with an extract.
16536   if (Subtarget->hasMVEIntegerOps()) {
16537     EVT ExtractVT = VT.getVectorElementType();
16538     // We need to ensure we are creating a legal type.
16539     if (!DCI.DAG.getTargetLoweringInfo().isTypeLegal(ExtractVT))
16540       ExtractVT = MVT::i32;
16541     SDValue Extract = DCI.DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), ExtractVT,
16542                               N->getOperand(0), N->getOperand(1));
16543     return DCI.DAG.getNode(ARMISD::VDUP, SDLoc(N), VT, Extract);
16544   }
16545 
16546   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
16547   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
16548   if (CombineVLDDUP(N, DCI))
16549     return SDValue(N, 0);
16550 
16551   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
16552   // redundant.  Ignore bit_converts for now; element sizes are checked below.
16553   while (Op.getOpcode() == ISD::BITCAST)
16554     Op = Op.getOperand(0);
16555   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
16556     return SDValue();
16557 
16558   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
16559   unsigned EltSize = Op.getScalarValueSizeInBits();
16560   // The canonical VMOV for a zero vector uses a 32-bit element size.
16561   unsigned Imm = Op.getConstantOperandVal(0);
16562   unsigned EltBits;
16563   if (ARM_AM::decodeVMOVModImm(Imm, EltBits) == 0)
16564     EltSize = 8;
16565   if (EltSize > VT.getScalarSizeInBits())
16566     return SDValue();
16567 
16568   return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
16569 }
16570 
16571 /// PerformVDUPCombine - Target-specific dag combine xforms for ARMISD::VDUP.
PerformVDUPCombine(SDNode * N,SelectionDAG & DAG,const ARMSubtarget * Subtarget)16572 static SDValue PerformVDUPCombine(SDNode *N, SelectionDAG &DAG,
16573                                   const ARMSubtarget *Subtarget) {
16574   SDValue Op = N->getOperand(0);
16575   SDLoc dl(N);
16576 
16577   if (Subtarget->hasMVEIntegerOps()) {
16578     // Convert VDUP f32 -> VDUP BITCAST i32 under MVE, as we know the value will
16579     // need to come from a GPR.
16580     if (Op.getValueType() == MVT::f32)
16581       return DAG.getNode(ARMISD::VDUP, dl, N->getValueType(0),
16582                          DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op));
16583     else if (Op.getValueType() == MVT::f16)
16584       return DAG.getNode(ARMISD::VDUP, dl, N->getValueType(0),
16585                          DAG.getNode(ARMISD::VMOVrh, dl, MVT::i32, Op));
16586   }
16587 
16588   if (!Subtarget->hasNEON())
16589     return SDValue();
16590 
16591   // Match VDUP(LOAD) -> VLD1DUP.
16592   // We match this pattern here rather than waiting for isel because the
16593   // transform is only legal for unindexed loads.
16594   LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode());
16595   if (LD && Op.hasOneUse() && LD->isUnindexed() &&
16596       LD->getMemoryVT() == N->getValueType(0).getVectorElementType()) {
16597     SDValue Ops[] = {LD->getOperand(0), LD->getOperand(1),
16598                      DAG.getConstant(LD->getAlign().value(), SDLoc(N), MVT::i32)};
16599     SDVTList SDTys = DAG.getVTList(N->getValueType(0), MVT::Other);
16600     SDValue VLDDup =
16601         DAG.getMemIntrinsicNode(ARMISD::VLD1DUP, SDLoc(N), SDTys, Ops,
16602                                 LD->getMemoryVT(), LD->getMemOperand());
16603     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), VLDDup.getValue(1));
16604     return VLDDup;
16605   }
16606 
16607   return SDValue();
16608 }
16609 
PerformLOADCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI,const ARMSubtarget * Subtarget)16610 static SDValue PerformLOADCombine(SDNode *N,
16611                                   TargetLowering::DAGCombinerInfo &DCI,
16612                                   const ARMSubtarget *Subtarget) {
16613   EVT VT = N->getValueType(0);
16614 
16615   // If this is a legal vector load, try to combine it into a VLD1_UPD.
16616   if (Subtarget->hasNEON() && ISD::isNormalLoad(N) && VT.isVector() &&
16617       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
16618     return CombineBaseUpdate(N, DCI);
16619 
16620   return SDValue();
16621 }
16622 
16623 // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
16624 // pack all of the elements in one place.  Next, store to memory in fewer
16625 // chunks.
PerformTruncatingStoreCombine(StoreSDNode * St,SelectionDAG & DAG)16626 static SDValue PerformTruncatingStoreCombine(StoreSDNode *St,
16627                                              SelectionDAG &DAG) {
16628   SDValue StVal = St->getValue();
16629   EVT VT = StVal.getValueType();
16630   if (!St->isTruncatingStore() || !VT.isVector())
16631     return SDValue();
16632   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16633   EVT StVT = St->getMemoryVT();
16634   unsigned NumElems = VT.getVectorNumElements();
16635   assert(StVT != VT && "Cannot truncate to the same type");
16636   unsigned FromEltSz = VT.getScalarSizeInBits();
16637   unsigned ToEltSz = StVT.getScalarSizeInBits();
16638 
16639   // From, To sizes and ElemCount must be pow of two
16640   if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz))
16641     return SDValue();
16642 
16643   // We are going to use the original vector elt for storing.
16644   // Accumulated smaller vector elements must be a multiple of the store size.
16645   if (0 != (NumElems * FromEltSz) % ToEltSz)
16646     return SDValue();
16647 
16648   unsigned SizeRatio = FromEltSz / ToEltSz;
16649   assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
16650 
16651   // Create a type on which we perform the shuffle.
16652   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
16653                                    NumElems * SizeRatio);
16654   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
16655 
16656   SDLoc DL(St);
16657   SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
16658   SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
16659   for (unsigned i = 0; i < NumElems; ++i)
16660     ShuffleVec[i] = DAG.getDataLayout().isBigEndian() ? (i + 1) * SizeRatio - 1
16661                                                       : i * SizeRatio;
16662 
16663   // Can't shuffle using an illegal type.
16664   if (!TLI.isTypeLegal(WideVecVT))
16665     return SDValue();
16666 
16667   SDValue Shuff = DAG.getVectorShuffle(
16668       WideVecVT, DL, WideVec, DAG.getUNDEF(WideVec.getValueType()), ShuffleVec);
16669   // At this point all of the data is stored at the bottom of the
16670   // register. We now need to save it to mem.
16671 
16672   // Find the largest store unit
16673   MVT StoreType = MVT::i8;
16674   for (MVT Tp : MVT::integer_valuetypes()) {
16675     if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
16676       StoreType = Tp;
16677   }
16678   // Didn't find a legal store type.
16679   if (!TLI.isTypeLegal(StoreType))
16680     return SDValue();
16681 
16682   // Bitcast the original vector into a vector of store-size units
16683   EVT StoreVecVT =
16684       EVT::getVectorVT(*DAG.getContext(), StoreType,
16685                        VT.getSizeInBits() / EVT(StoreType).getSizeInBits());
16686   assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
16687   SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
16688   SmallVector<SDValue, 8> Chains;
16689   SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL,
16690                                       TLI.getPointerTy(DAG.getDataLayout()));
16691   SDValue BasePtr = St->getBasePtr();
16692 
16693   // Perform one or more big stores into memory.
16694   unsigned E = (ToEltSz * NumElems) / StoreType.getSizeInBits();
16695   for (unsigned I = 0; I < E; I++) {
16696     SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, StoreType,
16697                                  ShuffWide, DAG.getIntPtrConstant(I, DL));
16698     SDValue Ch =
16699         DAG.getStore(St->getChain(), DL, SubVec, BasePtr, St->getPointerInfo(),
16700                      St->getAlign(), St->getMemOperand()->getFlags());
16701     BasePtr =
16702         DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr, Increment);
16703     Chains.push_back(Ch);
16704   }
16705   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
16706 }
16707 
16708 // Try taking a single vector store from an fpround (which would otherwise turn
16709 // into an expensive buildvector) and splitting it into a series of narrowing
16710 // stores.
PerformSplittingToNarrowingStores(StoreSDNode * St,SelectionDAG & DAG)16711 static SDValue PerformSplittingToNarrowingStores(StoreSDNode *St,
16712                                                  SelectionDAG &DAG) {
16713   if (!St->isSimple() || St->isTruncatingStore() || !St->isUnindexed())
16714     return SDValue();
16715   SDValue Trunc = St->getValue();
16716   if (Trunc->getOpcode() != ISD::FP_ROUND)
16717     return SDValue();
16718   EVT FromVT = Trunc->getOperand(0).getValueType();
16719   EVT ToVT = Trunc.getValueType();
16720   if (!ToVT.isVector())
16721     return SDValue();
16722   assert(FromVT.getVectorNumElements() == ToVT.getVectorNumElements());
16723   EVT ToEltVT = ToVT.getVectorElementType();
16724   EVT FromEltVT = FromVT.getVectorElementType();
16725 
16726   if (FromEltVT != MVT::f32 || ToEltVT != MVT::f16)
16727     return SDValue();
16728 
16729   unsigned NumElements = 4;
16730   if (FromVT.getVectorNumElements() % NumElements != 0)
16731     return SDValue();
16732 
16733   // Test if the Trunc will be convertable to a VMOVN with a shuffle, and if so
16734   // use the VMOVN over splitting the store. We are looking for patterns of:
16735   // !rev: 0 N 1 N+1 2 N+2 ...
16736   //  rev: N 0 N+1 1 N+2 2 ...
16737   // The shuffle may either be a single source (in which case N = NumElts/2) or
16738   // two inputs extended with concat to the same size (in which case N =
16739   // NumElts).
16740   auto isVMOVNShuffle = [&](ShuffleVectorSDNode *SVN, bool Rev) {
16741     ArrayRef<int> M = SVN->getMask();
16742     unsigned NumElts = ToVT.getVectorNumElements();
16743     if (SVN->getOperand(1).isUndef())
16744       NumElts /= 2;
16745 
16746     unsigned Off0 = Rev ? NumElts : 0;
16747     unsigned Off1 = Rev ? 0 : NumElts;
16748 
16749     for (unsigned I = 0; I < NumElts; I += 2) {
16750       if (M[I] >= 0 && M[I] != (int)(Off0 + I / 2))
16751         return false;
16752       if (M[I + 1] >= 0 && M[I + 1] != (int)(Off1 + I / 2))
16753         return false;
16754     }
16755 
16756     return true;
16757   };
16758 
16759   if (auto *Shuffle = dyn_cast<ShuffleVectorSDNode>(Trunc.getOperand(0)))
16760     if (isVMOVNShuffle(Shuffle, false) || isVMOVNShuffle(Shuffle, true))
16761       return SDValue();
16762 
16763   LLVMContext &C = *DAG.getContext();
16764   SDLoc DL(St);
16765   // Details about the old store
16766   SDValue Ch = St->getChain();
16767   SDValue BasePtr = St->getBasePtr();
16768   Align Alignment = St->getBaseAlign();
16769   MachineMemOperand::Flags MMOFlags = St->getMemOperand()->getFlags();
16770   AAMDNodes AAInfo = St->getAAInfo();
16771 
16772   // We split the store into slices of NumElements. fp16 trunc stores are vcvt
16773   // and then stored as truncating integer stores.
16774   EVT NewFromVT = EVT::getVectorVT(C, FromEltVT, NumElements);
16775   EVT NewToVT = EVT::getVectorVT(
16776       C, EVT::getIntegerVT(C, ToEltVT.getSizeInBits()), NumElements);
16777 
16778   SmallVector<SDValue, 4> Stores;
16779   for (unsigned i = 0; i < FromVT.getVectorNumElements() / NumElements; i++) {
16780     unsigned NewOffset = i * NumElements * ToEltVT.getSizeInBits() / 8;
16781     SDValue NewPtr =
16782         DAG.getObjectPtrOffset(DL, BasePtr, TypeSize::getFixed(NewOffset));
16783 
16784     SDValue Extract =
16785         DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, NewFromVT, Trunc.getOperand(0),
16786                     DAG.getConstant(i * NumElements, DL, MVT::i32));
16787 
16788     SDValue FPTrunc =
16789         DAG.getNode(ARMISD::VCVTN, DL, MVT::v8f16, DAG.getUNDEF(MVT::v8f16),
16790                     Extract, DAG.getConstant(0, DL, MVT::i32));
16791     Extract = DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, MVT::v4i32, FPTrunc);
16792 
16793     SDValue Store = DAG.getTruncStore(
16794         Ch, DL, Extract, NewPtr, St->getPointerInfo().getWithOffset(NewOffset),
16795         NewToVT, Alignment, MMOFlags, AAInfo);
16796     Stores.push_back(Store);
16797   }
16798   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Stores);
16799 }
16800 
16801 // Try taking a single vector store from an MVETRUNC (which would otherwise turn
16802 // into an expensive buildvector) and splitting it into a series of narrowing
16803 // stores.
PerformSplittingMVETruncToNarrowingStores(StoreSDNode * St,SelectionDAG & DAG)16804 static SDValue PerformSplittingMVETruncToNarrowingStores(StoreSDNode *St,
16805                                                          SelectionDAG &DAG) {
16806   if (!St->isSimple() || St->isTruncatingStore() || !St->isUnindexed())
16807     return SDValue();
16808   SDValue Trunc = St->getValue();
16809   if (Trunc->getOpcode() != ARMISD::MVETRUNC)
16810     return SDValue();
16811   EVT FromVT = Trunc->getOperand(0).getValueType();
16812   EVT ToVT = Trunc.getValueType();
16813 
16814   LLVMContext &C = *DAG.getContext();
16815   SDLoc DL(St);
16816   // Details about the old store
16817   SDValue Ch = St->getChain();
16818   SDValue BasePtr = St->getBasePtr();
16819   Align Alignment = St->getBaseAlign();
16820   MachineMemOperand::Flags MMOFlags = St->getMemOperand()->getFlags();
16821   AAMDNodes AAInfo = St->getAAInfo();
16822 
16823   EVT NewToVT = EVT::getVectorVT(C, ToVT.getVectorElementType(),
16824                                  FromVT.getVectorNumElements());
16825 
16826   SmallVector<SDValue, 4> Stores;
16827   for (unsigned i = 0; i < Trunc.getNumOperands(); i++) {
16828     unsigned NewOffset =
16829         i * FromVT.getVectorNumElements() * ToVT.getScalarSizeInBits() / 8;
16830     SDValue NewPtr =
16831         DAG.getObjectPtrOffset(DL, BasePtr, TypeSize::getFixed(NewOffset));
16832 
16833     SDValue Extract = Trunc.getOperand(i);
16834     SDValue Store = DAG.getTruncStore(
16835         Ch, DL, Extract, NewPtr, St->getPointerInfo().getWithOffset(NewOffset),
16836         NewToVT, Alignment, MMOFlags, AAInfo);
16837     Stores.push_back(Store);
16838   }
16839   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Stores);
16840 }
16841 
16842 // Given a floating point store from an extracted vector, with an integer
16843 // VGETLANE that already exists, store the existing VGETLANEu directly. This can
16844 // help reduce fp register pressure, doesn't require the fp extract and allows
16845 // use of more integer post-inc stores not available with vstr.
PerformExtractFpToIntStores(StoreSDNode * St,SelectionDAG & DAG)16846 static SDValue PerformExtractFpToIntStores(StoreSDNode *St, SelectionDAG &DAG) {
16847   if (!St->isSimple() || St->isTruncatingStore() || !St->isUnindexed())
16848     return SDValue();
16849   SDValue Extract = St->getValue();
16850   EVT VT = Extract.getValueType();
16851   // For now only uses f16. This may be useful for f32 too, but that will
16852   // be bitcast(extract), not the VGETLANEu we currently check here.
16853   if (VT != MVT::f16 || Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
16854     return SDValue();
16855 
16856   SDNode *GetLane =
16857       DAG.getNodeIfExists(ARMISD::VGETLANEu, DAG.getVTList(MVT::i32),
16858                           {Extract.getOperand(0), Extract.getOperand(1)});
16859   if (!GetLane)
16860     return SDValue();
16861 
16862   LLVMContext &C = *DAG.getContext();
16863   SDLoc DL(St);
16864   // Create a new integer store to replace the existing floating point version.
16865   SDValue Ch = St->getChain();
16866   SDValue BasePtr = St->getBasePtr();
16867   Align Alignment = St->getBaseAlign();
16868   MachineMemOperand::Flags MMOFlags = St->getMemOperand()->getFlags();
16869   AAMDNodes AAInfo = St->getAAInfo();
16870   EVT NewToVT = EVT::getIntegerVT(C, VT.getSizeInBits());
16871   SDValue Store = DAG.getTruncStore(Ch, DL, SDValue(GetLane, 0), BasePtr,
16872                                     St->getPointerInfo(), NewToVT, Alignment,
16873                                     MMOFlags, AAInfo);
16874 
16875   return Store;
16876 }
16877 
16878 /// PerformSTORECombine - Target-specific dag combine xforms for
16879 /// ISD::STORE.
PerformSTORECombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI,const ARMSubtarget * Subtarget)16880 static SDValue PerformSTORECombine(SDNode *N,
16881                                    TargetLowering::DAGCombinerInfo &DCI,
16882                                    const ARMSubtarget *Subtarget) {
16883   StoreSDNode *St = cast<StoreSDNode>(N);
16884   if (St->isVolatile())
16885     return SDValue();
16886   SDValue StVal = St->getValue();
16887   EVT VT = StVal.getValueType();
16888 
16889   if (Subtarget->hasNEON())
16890     if (SDValue Store = PerformTruncatingStoreCombine(St, DCI.DAG))
16891       return Store;
16892 
16893   if (Subtarget->hasMVEFloatOps())
16894     if (SDValue NewToken = PerformSplittingToNarrowingStores(St, DCI.DAG))
16895       return NewToken;
16896 
16897   if (Subtarget->hasMVEIntegerOps()) {
16898     if (SDValue NewChain = PerformExtractFpToIntStores(St, DCI.DAG))
16899       return NewChain;
16900     if (SDValue NewToken =
16901             PerformSplittingMVETruncToNarrowingStores(St, DCI.DAG))
16902       return NewToken;
16903   }
16904 
16905   if (!ISD::isNormalStore(St))
16906     return SDValue();
16907 
16908   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
16909   // ARM stores of arguments in the same cache line.
16910   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
16911       StVal.getNode()->hasOneUse()) {
16912     SelectionDAG  &DAG = DCI.DAG;
16913     bool isBigEndian = DAG.getDataLayout().isBigEndian();
16914     SDLoc DL(St);
16915     SDValue BasePtr = St->getBasePtr();
16916     SDValue NewST1 = DAG.getStore(
16917         St->getChain(), DL, StVal.getNode()->getOperand(isBigEndian ? 1 : 0),
16918         BasePtr, St->getPointerInfo(), St->getBaseAlign(),
16919         St->getMemOperand()->getFlags());
16920 
16921     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
16922                                     DAG.getConstant(4, DL, MVT::i32));
16923     return DAG.getStore(NewST1.getValue(0), DL,
16924                         StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
16925                         OffsetPtr, St->getPointerInfo().getWithOffset(4),
16926                         St->getBaseAlign(), St->getMemOperand()->getFlags());
16927   }
16928 
16929   if (StVal.getValueType() == MVT::i64 &&
16930       StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
16931 
16932     // Bitcast an i64 store extracted from a vector to f64.
16933     // Otherwise, the i64 value will be legalized to a pair of i32 values.
16934     SelectionDAG &DAG = DCI.DAG;
16935     SDLoc dl(StVal);
16936     SDValue IntVec = StVal.getOperand(0);
16937     EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
16938                                    IntVec.getValueType().getVectorNumElements());
16939     SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
16940     SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
16941                                  Vec, StVal.getOperand(1));
16942     dl = SDLoc(N);
16943     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
16944     // Make the DAGCombiner fold the bitcasts.
16945     DCI.AddToWorklist(Vec.getNode());
16946     DCI.AddToWorklist(ExtElt.getNode());
16947     DCI.AddToWorklist(V.getNode());
16948     return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
16949                         St->getPointerInfo(), St->getAlign(),
16950                         St->getMemOperand()->getFlags(), St->getAAInfo());
16951   }
16952 
16953   // If this is a legal vector store, try to combine it into a VST1_UPD.
16954   if (Subtarget->hasNEON() && ISD::isNormalStore(N) && VT.isVector() &&
16955       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
16956     return CombineBaseUpdate(N, DCI);
16957 
16958   return SDValue();
16959 }
16960 
16961 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
16962 /// can replace combinations of VMUL and VCVT (floating-point to integer)
16963 /// when the VMUL has a constant operand that is a power of 2.
16964 ///
16965 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
16966 ///  vmul.f32        d16, d17, d16
16967 ///  vcvt.s32.f32    d16, d16
16968 /// becomes:
16969 ///  vcvt.s32.f32    d16, d16, #3
PerformVCVTCombine(SDNode * N,SelectionDAG & DAG,const ARMSubtarget * Subtarget)16970 static SDValue PerformVCVTCombine(SDNode *N, SelectionDAG &DAG,
16971                                   const ARMSubtarget *Subtarget) {
16972   if (!Subtarget->hasNEON())
16973     return SDValue();
16974 
16975   SDValue Op = N->getOperand(0);
16976   if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
16977       Op.getOpcode() != ISD::FMUL)
16978     return SDValue();
16979 
16980   SDValue ConstVec = Op->getOperand(1);
16981   if (!isa<BuildVectorSDNode>(ConstVec))
16982     return SDValue();
16983 
16984   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
16985   uint32_t FloatBits = FloatTy.getSizeInBits();
16986   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
16987   uint32_t IntBits = IntTy.getSizeInBits();
16988   unsigned NumLanes = Op.getValueType().getVectorNumElements();
16989   if (FloatBits != 32 || IntBits > 32 || (NumLanes != 4 && NumLanes != 2)) {
16990     // These instructions only exist converting from f32 to i32. We can handle
16991     // smaller integers by generating an extra truncate, but larger ones would
16992     // be lossy. We also can't handle anything other than 2 or 4 lanes, since
16993     // these intructions only support v2i32/v4i32 types.
16994     return SDValue();
16995   }
16996 
16997   BitVector UndefElements;
16998   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
16999   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33);
17000   if (C == -1 || C == 0 || C > 32)
17001     return SDValue();
17002 
17003   SDLoc dl(N);
17004   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
17005   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
17006     Intrinsic::arm_neon_vcvtfp2fxu;
17007   SDValue FixConv = DAG.getNode(
17008       ISD::INTRINSIC_WO_CHAIN, dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
17009       DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), Op->getOperand(0),
17010       DAG.getConstant(C, dl, MVT::i32));
17011 
17012   if (IntBits < FloatBits)
17013     FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv);
17014 
17015   return FixConv;
17016 }
17017 
PerformFAddVSelectCombine(SDNode * N,SelectionDAG & DAG,const ARMSubtarget * Subtarget)17018 static SDValue PerformFAddVSelectCombine(SDNode *N, SelectionDAG &DAG,
17019                                          const ARMSubtarget *Subtarget) {
17020   if (!Subtarget->hasMVEFloatOps())
17021     return SDValue();
17022 
17023   // Turn (fadd x, (vselect c, y, -0.0)) into (vselect c, (fadd x, y), x)
17024   // The second form can be more easily turned into a predicated vadd, and
17025   // possibly combined into a fma to become a predicated vfma.
17026   SDValue Op0 = N->getOperand(0);
17027   SDValue Op1 = N->getOperand(1);
17028   EVT VT = N->getValueType(0);
17029   SDLoc DL(N);
17030 
17031   // The identity element for a fadd is -0.0 or +0.0 when the nsz flag is set,
17032   // which these VMOV's represent.
17033   auto isIdentitySplat = [&](SDValue Op, bool NSZ) {
17034     if (Op.getOpcode() != ISD::BITCAST ||
17035         Op.getOperand(0).getOpcode() != ARMISD::VMOVIMM)
17036       return false;
17037     uint64_t ImmVal = Op.getOperand(0).getConstantOperandVal(0);
17038     if (VT == MVT::v4f32 && (ImmVal == 1664 || (ImmVal == 0 && NSZ)))
17039       return true;
17040     if (VT == MVT::v8f16 && (ImmVal == 2688 || (ImmVal == 0 && NSZ)))
17041       return true;
17042     return false;
17043   };
17044 
17045   if (Op0.getOpcode() == ISD::VSELECT && Op1.getOpcode() != ISD::VSELECT)
17046     std::swap(Op0, Op1);
17047 
17048   if (Op1.getOpcode() != ISD::VSELECT)
17049     return SDValue();
17050 
17051   SDNodeFlags FaddFlags = N->getFlags();
17052   bool NSZ = FaddFlags.hasNoSignedZeros();
17053   if (!isIdentitySplat(Op1.getOperand(2), NSZ))
17054     return SDValue();
17055 
17056   SDValue FAdd =
17057       DAG.getNode(ISD::FADD, DL, VT, Op0, Op1.getOperand(1), FaddFlags);
17058   return DAG.getNode(ISD::VSELECT, DL, VT, Op1.getOperand(0), FAdd, Op0, FaddFlags);
17059 }
17060 
PerformFADDVCMLACombine(SDNode * N,SelectionDAG & DAG)17061 static SDValue PerformFADDVCMLACombine(SDNode *N, SelectionDAG &DAG) {
17062   SDValue LHS = N->getOperand(0);
17063   SDValue RHS = N->getOperand(1);
17064   EVT VT = N->getValueType(0);
17065   SDLoc DL(N);
17066 
17067   if (!N->getFlags().hasAllowReassociation())
17068     return SDValue();
17069 
17070   // Combine fadd(a, vcmla(b, c, d)) -> vcmla(fadd(a, b), b, c)
17071   auto ReassocComplex = [&](SDValue A, SDValue B) {
17072     if (A.getOpcode() != ISD::INTRINSIC_WO_CHAIN)
17073       return SDValue();
17074     unsigned Opc = A.getConstantOperandVal(0);
17075     if (Opc != Intrinsic::arm_mve_vcmlaq)
17076       return SDValue();
17077     SDValue VCMLA = DAG.getNode(
17078         ISD::INTRINSIC_WO_CHAIN, DL, VT, A.getOperand(0), A.getOperand(1),
17079         DAG.getNode(ISD::FADD, DL, VT, A.getOperand(2), B, N->getFlags()),
17080         A.getOperand(3), A.getOperand(4));
17081     VCMLA->setFlags(A->getFlags());
17082     return VCMLA;
17083   };
17084   if (SDValue R = ReassocComplex(LHS, RHS))
17085     return R;
17086   if (SDValue R = ReassocComplex(RHS, LHS))
17087     return R;
17088 
17089   return SDValue();
17090 }
17091 
PerformFADDCombine(SDNode * N,SelectionDAG & DAG,const ARMSubtarget * Subtarget)17092 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
17093                                   const ARMSubtarget *Subtarget) {
17094   if (SDValue S = PerformFAddVSelectCombine(N, DAG, Subtarget))
17095     return S;
17096   if (SDValue S = PerformFADDVCMLACombine(N, DAG))
17097     return S;
17098   return SDValue();
17099 }
17100 
17101 /// PerformVMulVCTPCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
17102 /// can replace combinations of VCVT (integer to floating-point) and VMUL
17103 /// when the VMUL has a constant operand that is a power of 2.
17104 ///
17105 /// Example (assume d17 = <float 0.125, float 0.125>):
17106 ///  vcvt.f32.s32    d16, d16
17107 ///  vmul.f32        d16, d16, d17
17108 /// becomes:
17109 ///  vcvt.f32.s32    d16, d16, #3
PerformVMulVCTPCombine(SDNode * N,SelectionDAG & DAG,const ARMSubtarget * Subtarget)17110 static SDValue PerformVMulVCTPCombine(SDNode *N, SelectionDAG &DAG,
17111                                       const ARMSubtarget *Subtarget) {
17112   if (!Subtarget->hasNEON())
17113     return SDValue();
17114 
17115   SDValue Op = N->getOperand(0);
17116   unsigned OpOpcode = Op.getNode()->getOpcode();
17117   if (!N->getValueType(0).isVector() || !N->getValueType(0).isSimple() ||
17118       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
17119     return SDValue();
17120 
17121   SDValue ConstVec = N->getOperand(1);
17122   if (!isa<BuildVectorSDNode>(ConstVec))
17123     return SDValue();
17124 
17125   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
17126   uint32_t FloatBits = FloatTy.getSizeInBits();
17127   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
17128   uint32_t IntBits = IntTy.getSizeInBits();
17129   unsigned NumLanes = Op.getValueType().getVectorNumElements();
17130   if (FloatBits != 32 || IntBits > 32 || (NumLanes != 4 && NumLanes != 2)) {
17131     // These instructions only exist converting from i32 to f32. We can handle
17132     // smaller integers by generating an extra extend, but larger ones would
17133     // be lossy. We also can't handle anything other than 2 or 4 lanes, since
17134     // these intructions only support v2i32/v4i32 types.
17135     return SDValue();
17136   }
17137 
17138   ConstantFPSDNode *CN = isConstOrConstSplatFP(ConstVec, true);
17139   APFloat Recip(0.0f);
17140   if (!CN || !CN->getValueAPF().getExactInverse(&Recip))
17141     return SDValue();
17142 
17143   bool IsExact;
17144   APSInt IntVal(33);
17145   if (Recip.convertToInteger(IntVal, APFloat::rmTowardZero, &IsExact) !=
17146           APFloat::opOK ||
17147       !IsExact)
17148     return SDValue();
17149 
17150   int32_t C = IntVal.exactLogBase2();
17151   if (C == -1 || C == 0 || C > 32)
17152     return SDValue();
17153 
17154   SDLoc DL(N);
17155   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
17156   SDValue ConvInput = Op.getOperand(0);
17157   if (IntBits < FloatBits)
17158     ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, DL,
17159                             NumLanes == 2 ? MVT::v2i32 : MVT::v4i32, ConvInput);
17160 
17161   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp
17162                                       : Intrinsic::arm_neon_vcvtfxu2fp;
17163   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Op.getValueType(),
17164                      DAG.getConstant(IntrinsicOpcode, DL, MVT::i32), ConvInput,
17165                      DAG.getConstant(C, DL, MVT::i32));
17166 }
17167 
PerformVECREDUCE_ADDCombine(SDNode * N,SelectionDAG & DAG,const ARMSubtarget * ST)17168 static SDValue PerformVECREDUCE_ADDCombine(SDNode *N, SelectionDAG &DAG,
17169                                            const ARMSubtarget *ST) {
17170   if (!ST->hasMVEIntegerOps())
17171     return SDValue();
17172 
17173   assert(N->getOpcode() == ISD::VECREDUCE_ADD);
17174   EVT ResVT = N->getValueType(0);
17175   SDValue N0 = N->getOperand(0);
17176   SDLoc dl(N);
17177 
17178   // Try to turn vecreduce_add(add(x, y)) into vecreduce(x) + vecreduce(y)
17179   if (ResVT == MVT::i32 && N0.getOpcode() == ISD::ADD &&
17180       (N0.getValueType() == MVT::v4i32 || N0.getValueType() == MVT::v8i16 ||
17181        N0.getValueType() == MVT::v16i8)) {
17182     SDValue Red0 = DAG.getNode(ISD::VECREDUCE_ADD, dl, ResVT, N0.getOperand(0));
17183     SDValue Red1 = DAG.getNode(ISD::VECREDUCE_ADD, dl, ResVT, N0.getOperand(1));
17184     return DAG.getNode(ISD::ADD, dl, ResVT, Red0, Red1);
17185   }
17186 
17187   // We are looking for something that will have illegal types if left alone,
17188   // but that we can convert to a single instruction under MVE. For example
17189   // vecreduce_add(sext(A, v8i32)) => VADDV.s16 A
17190   // or
17191   // vecreduce_add(mul(zext(A, v16i32), zext(B, v16i32))) => VMLADAV.u8 A, B
17192 
17193   // The legal cases are:
17194   //   VADDV u/s 8/16/32
17195   //   VMLAV u/s 8/16/32
17196   //   VADDLV u/s 32
17197   //   VMLALV u/s 16/32
17198 
17199   // If the input vector is smaller than legal (v4i8/v4i16 for example) we can
17200   // extend it and use v4i32 instead.
17201   auto ExtTypeMatches = [](SDValue A, ArrayRef<MVT> ExtTypes) {
17202     EVT AVT = A.getValueType();
17203     return any_of(ExtTypes, [&](MVT Ty) {
17204       return AVT.getVectorNumElements() == Ty.getVectorNumElements() &&
17205              AVT.bitsLE(Ty);
17206     });
17207   };
17208   auto ExtendIfNeeded = [&](SDValue A, unsigned ExtendCode) {
17209     EVT AVT = A.getValueType();
17210     if (!AVT.is128BitVector())
17211       A = DAG.getNode(ExtendCode, dl,
17212                       AVT.changeVectorElementType(MVT::getIntegerVT(
17213                           128 / AVT.getVectorMinNumElements())),
17214                       A);
17215     return A;
17216   };
17217   auto IsVADDV = [&](MVT RetTy, unsigned ExtendCode, ArrayRef<MVT> ExtTypes) {
17218     if (ResVT != RetTy || N0->getOpcode() != ExtendCode)
17219       return SDValue();
17220     SDValue A = N0->getOperand(0);
17221     if (ExtTypeMatches(A, ExtTypes))
17222       return ExtendIfNeeded(A, ExtendCode);
17223     return SDValue();
17224   };
17225   auto IsPredVADDV = [&](MVT RetTy, unsigned ExtendCode,
17226                          ArrayRef<MVT> ExtTypes, SDValue &Mask) {
17227     if (ResVT != RetTy || N0->getOpcode() != ISD::VSELECT ||
17228         !ISD::isBuildVectorAllZeros(N0->getOperand(2).getNode()))
17229       return SDValue();
17230     Mask = N0->getOperand(0);
17231     SDValue Ext = N0->getOperand(1);
17232     if (Ext->getOpcode() != ExtendCode)
17233       return SDValue();
17234     SDValue A = Ext->getOperand(0);
17235     if (ExtTypeMatches(A, ExtTypes))
17236       return ExtendIfNeeded(A, ExtendCode);
17237     return SDValue();
17238   };
17239   auto IsVMLAV = [&](MVT RetTy, unsigned ExtendCode, ArrayRef<MVT> ExtTypes,
17240                      SDValue &A, SDValue &B) {
17241     // For a vmla we are trying to match a larger pattern:
17242     // ExtA = sext/zext A
17243     // ExtB = sext/zext B
17244     // Mul = mul ExtA, ExtB
17245     // vecreduce.add Mul
17246     // There might also be en extra extend between the mul and the addreduce, so
17247     // long as the bitwidth is high enough to make them equivalent (for example
17248     // original v8i16 might be mul at v8i32 and the reduce happens at v8i64).
17249     if (ResVT != RetTy)
17250       return false;
17251     SDValue Mul = N0;
17252     if (Mul->getOpcode() == ExtendCode &&
17253         Mul->getOperand(0).getScalarValueSizeInBits() * 2 >=
17254             ResVT.getScalarSizeInBits())
17255       Mul = Mul->getOperand(0);
17256     if (Mul->getOpcode() != ISD::MUL)
17257       return false;
17258     SDValue ExtA = Mul->getOperand(0);
17259     SDValue ExtB = Mul->getOperand(1);
17260     if (ExtA->getOpcode() != ExtendCode || ExtB->getOpcode() != ExtendCode)
17261       return false;
17262     A = ExtA->getOperand(0);
17263     B = ExtB->getOperand(0);
17264     if (ExtTypeMatches(A, ExtTypes) && ExtTypeMatches(B, ExtTypes)) {
17265       A = ExtendIfNeeded(A, ExtendCode);
17266       B = ExtendIfNeeded(B, ExtendCode);
17267       return true;
17268     }
17269     return false;
17270   };
17271   auto IsPredVMLAV = [&](MVT RetTy, unsigned ExtendCode, ArrayRef<MVT> ExtTypes,
17272                      SDValue &A, SDValue &B, SDValue &Mask) {
17273     // Same as the pattern above with a select for the zero predicated lanes
17274     // ExtA = sext/zext A
17275     // ExtB = sext/zext B
17276     // Mul = mul ExtA, ExtB
17277     // N0 = select Mask, Mul, 0
17278     // vecreduce.add N0
17279     if (ResVT != RetTy || N0->getOpcode() != ISD::VSELECT ||
17280         !ISD::isBuildVectorAllZeros(N0->getOperand(2).getNode()))
17281       return false;
17282     Mask = N0->getOperand(0);
17283     SDValue Mul = N0->getOperand(1);
17284     if (Mul->getOpcode() == ExtendCode &&
17285         Mul->getOperand(0).getScalarValueSizeInBits() * 2 >=
17286             ResVT.getScalarSizeInBits())
17287       Mul = Mul->getOperand(0);
17288     if (Mul->getOpcode() != ISD::MUL)
17289       return false;
17290     SDValue ExtA = Mul->getOperand(0);
17291     SDValue ExtB = Mul->getOperand(1);
17292     if (ExtA->getOpcode() != ExtendCode || ExtB->getOpcode() != ExtendCode)
17293       return false;
17294     A = ExtA->getOperand(0);
17295     B = ExtB->getOperand(0);
17296     if (ExtTypeMatches(A, ExtTypes) && ExtTypeMatches(B, ExtTypes)) {
17297       A = ExtendIfNeeded(A, ExtendCode);
17298       B = ExtendIfNeeded(B, ExtendCode);
17299       return true;
17300     }
17301     return false;
17302   };
17303   auto Create64bitNode = [&](unsigned Opcode, ArrayRef<SDValue> Ops) {
17304     // Split illegal MVT::v16i8->i64 vector reductions into two legal v8i16->i64
17305     // reductions. The operands are extended with MVEEXT, but as they are
17306     // reductions the lane orders do not matter. MVEEXT may be combined with
17307     // loads to produce two extending loads, or else they will be expanded to
17308     // VREV/VMOVL.
17309     EVT VT = Ops[0].getValueType();
17310     if (VT == MVT::v16i8) {
17311       assert((Opcode == ARMISD::VMLALVs || Opcode == ARMISD::VMLALVu) &&
17312              "Unexpected illegal long reduction opcode");
17313       bool IsUnsigned = Opcode == ARMISD::VMLALVu;
17314 
17315       SDValue Ext0 =
17316           DAG.getNode(IsUnsigned ? ARMISD::MVEZEXT : ARMISD::MVESEXT, dl,
17317                       DAG.getVTList(MVT::v8i16, MVT::v8i16), Ops[0]);
17318       SDValue Ext1 =
17319           DAG.getNode(IsUnsigned ? ARMISD::MVEZEXT : ARMISD::MVESEXT, dl,
17320                       DAG.getVTList(MVT::v8i16, MVT::v8i16), Ops[1]);
17321 
17322       SDValue MLA0 = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
17323                                  Ext0, Ext1);
17324       SDValue MLA1 =
17325           DAG.getNode(IsUnsigned ? ARMISD::VMLALVAu : ARMISD::VMLALVAs, dl,
17326                       DAG.getVTList(MVT::i32, MVT::i32), MLA0, MLA0.getValue(1),
17327                       Ext0.getValue(1), Ext1.getValue(1));
17328       return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, MLA1, MLA1.getValue(1));
17329     }
17330     SDValue Node = DAG.getNode(Opcode, dl, {MVT::i32, MVT::i32}, Ops);
17331     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Node,
17332                        SDValue(Node.getNode(), 1));
17333   };
17334 
17335   SDValue A, B;
17336   SDValue Mask;
17337   if (IsVMLAV(MVT::i32, ISD::SIGN_EXTEND, {MVT::v8i16, MVT::v16i8}, A, B))
17338     return DAG.getNode(ARMISD::VMLAVs, dl, ResVT, A, B);
17339   if (IsVMLAV(MVT::i32, ISD::ZERO_EXTEND, {MVT::v8i16, MVT::v16i8}, A, B))
17340     return DAG.getNode(ARMISD::VMLAVu, dl, ResVT, A, B);
17341   if (IsVMLAV(MVT::i64, ISD::SIGN_EXTEND, {MVT::v16i8, MVT::v8i16, MVT::v4i32},
17342               A, B))
17343     return Create64bitNode(ARMISD::VMLALVs, {A, B});
17344   if (IsVMLAV(MVT::i64, ISD::ZERO_EXTEND, {MVT::v16i8, MVT::v8i16, MVT::v4i32},
17345               A, B))
17346     return Create64bitNode(ARMISD::VMLALVu, {A, B});
17347   if (IsVMLAV(MVT::i16, ISD::SIGN_EXTEND, {MVT::v16i8}, A, B))
17348     return DAG.getNode(ISD::TRUNCATE, dl, ResVT,
17349                        DAG.getNode(ARMISD::VMLAVs, dl, MVT::i32, A, B));
17350   if (IsVMLAV(MVT::i16, ISD::ZERO_EXTEND, {MVT::v16i8}, A, B))
17351     return DAG.getNode(ISD::TRUNCATE, dl, ResVT,
17352                        DAG.getNode(ARMISD::VMLAVu, dl, MVT::i32, A, B));
17353 
17354   if (IsPredVMLAV(MVT::i32, ISD::SIGN_EXTEND, {MVT::v8i16, MVT::v16i8}, A, B,
17355                   Mask))
17356     return DAG.getNode(ARMISD::VMLAVps, dl, ResVT, A, B, Mask);
17357   if (IsPredVMLAV(MVT::i32, ISD::ZERO_EXTEND, {MVT::v8i16, MVT::v16i8}, A, B,
17358                   Mask))
17359     return DAG.getNode(ARMISD::VMLAVpu, dl, ResVT, A, B, Mask);
17360   if (IsPredVMLAV(MVT::i64, ISD::SIGN_EXTEND, {MVT::v8i16, MVT::v4i32}, A, B,
17361                   Mask))
17362     return Create64bitNode(ARMISD::VMLALVps, {A, B, Mask});
17363   if (IsPredVMLAV(MVT::i64, ISD::ZERO_EXTEND, {MVT::v8i16, MVT::v4i32}, A, B,
17364                   Mask))
17365     return Create64bitNode(ARMISD::VMLALVpu, {A, B, Mask});
17366   if (IsPredVMLAV(MVT::i16, ISD::SIGN_EXTEND, {MVT::v16i8}, A, B, Mask))
17367     return DAG.getNode(ISD::TRUNCATE, dl, ResVT,
17368                        DAG.getNode(ARMISD::VMLAVps, dl, MVT::i32, A, B, Mask));
17369   if (IsPredVMLAV(MVT::i16, ISD::ZERO_EXTEND, {MVT::v16i8}, A, B, Mask))
17370     return DAG.getNode(ISD::TRUNCATE, dl, ResVT,
17371                        DAG.getNode(ARMISD::VMLAVpu, dl, MVT::i32, A, B, Mask));
17372 
17373   if (SDValue A = IsVADDV(MVT::i32, ISD::SIGN_EXTEND, {MVT::v8i16, MVT::v16i8}))
17374     return DAG.getNode(ARMISD::VADDVs, dl, ResVT, A);
17375   if (SDValue A = IsVADDV(MVT::i32, ISD::ZERO_EXTEND, {MVT::v8i16, MVT::v16i8}))
17376     return DAG.getNode(ARMISD::VADDVu, dl, ResVT, A);
17377   if (SDValue A = IsVADDV(MVT::i64, ISD::SIGN_EXTEND, {MVT::v4i32}))
17378     return Create64bitNode(ARMISD::VADDLVs, {A});
17379   if (SDValue A = IsVADDV(MVT::i64, ISD::ZERO_EXTEND, {MVT::v4i32}))
17380     return Create64bitNode(ARMISD::VADDLVu, {A});
17381   if (SDValue A = IsVADDV(MVT::i16, ISD::SIGN_EXTEND, {MVT::v16i8}))
17382     return DAG.getNode(ISD::TRUNCATE, dl, ResVT,
17383                        DAG.getNode(ARMISD::VADDVs, dl, MVT::i32, A));
17384   if (SDValue A = IsVADDV(MVT::i16, ISD::ZERO_EXTEND, {MVT::v16i8}))
17385     return DAG.getNode(ISD::TRUNCATE, dl, ResVT,
17386                        DAG.getNode(ARMISD::VADDVu, dl, MVT::i32, A));
17387 
17388   if (SDValue A = IsPredVADDV(MVT::i32, ISD::SIGN_EXTEND, {MVT::v8i16, MVT::v16i8}, Mask))
17389     return DAG.getNode(ARMISD::VADDVps, dl, ResVT, A, Mask);
17390   if (SDValue A = IsPredVADDV(MVT::i32, ISD::ZERO_EXTEND, {MVT::v8i16, MVT::v16i8}, Mask))
17391     return DAG.getNode(ARMISD::VADDVpu, dl, ResVT, A, Mask);
17392   if (SDValue A = IsPredVADDV(MVT::i64, ISD::SIGN_EXTEND, {MVT::v4i32}, Mask))
17393     return Create64bitNode(ARMISD::VADDLVps, {A, Mask});
17394   if (SDValue A = IsPredVADDV(MVT::i64, ISD::ZERO_EXTEND, {MVT::v4i32}, Mask))
17395     return Create64bitNode(ARMISD::VADDLVpu, {A, Mask});
17396   if (SDValue A = IsPredVADDV(MVT::i16, ISD::SIGN_EXTEND, {MVT::v16i8}, Mask))
17397     return DAG.getNode(ISD::TRUNCATE, dl, ResVT,
17398                        DAG.getNode(ARMISD::VADDVps, dl, MVT::i32, A, Mask));
17399   if (SDValue A = IsPredVADDV(MVT::i16, ISD::ZERO_EXTEND, {MVT::v16i8}, Mask))
17400     return DAG.getNode(ISD::TRUNCATE, dl, ResVT,
17401                        DAG.getNode(ARMISD::VADDVpu, dl, MVT::i32, A, Mask));
17402 
17403   // Some complications. We can get a case where the two inputs of the mul are
17404   // the same, then the output sext will have been helpfully converted to a
17405   // zext. Turn it back.
17406   SDValue Op = N0;
17407   if (Op->getOpcode() == ISD::VSELECT)
17408     Op = Op->getOperand(1);
17409   if (Op->getOpcode() == ISD::ZERO_EXTEND &&
17410       Op->getOperand(0)->getOpcode() == ISD::MUL) {
17411     SDValue Mul = Op->getOperand(0);
17412     if (Mul->getOperand(0) == Mul->getOperand(1) &&
17413         Mul->getOperand(0)->getOpcode() == ISD::SIGN_EXTEND) {
17414       SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND, dl, N0->getValueType(0), Mul);
17415       if (Op != N0)
17416         Ext = DAG.getNode(ISD::VSELECT, dl, N0->getValueType(0),
17417                           N0->getOperand(0), Ext, N0->getOperand(2));
17418       return DAG.getNode(ISD::VECREDUCE_ADD, dl, ResVT, Ext);
17419     }
17420   }
17421 
17422   return SDValue();
17423 }
17424 
17425 // Looks for vaddv(shuffle) or vmlav(shuffle, shuffle), with a shuffle where all
17426 // the lanes are used. Due to the reduction being commutative the shuffle can be
17427 // removed.
PerformReduceShuffleCombine(SDNode * N,SelectionDAG & DAG)17428 static SDValue PerformReduceShuffleCombine(SDNode *N, SelectionDAG &DAG) {
17429   unsigned VecOp = N->getOperand(0).getValueType().isVector() ? 0 : 2;
17430   auto *Shuf = dyn_cast<ShuffleVectorSDNode>(N->getOperand(VecOp));
17431   if (!Shuf || !Shuf->getOperand(1).isUndef())
17432     return SDValue();
17433 
17434   // Check all elements are used once in the mask.
17435   ArrayRef<int> Mask = Shuf->getMask();
17436   APInt SetElts(Mask.size(), 0);
17437   for (int E : Mask) {
17438     if (E < 0 || E >= (int)Mask.size())
17439       return SDValue();
17440     SetElts.setBit(E);
17441   }
17442   if (!SetElts.isAllOnes())
17443     return SDValue();
17444 
17445   if (N->getNumOperands() != VecOp + 1) {
17446     auto *Shuf2 = dyn_cast<ShuffleVectorSDNode>(N->getOperand(VecOp + 1));
17447     if (!Shuf2 || !Shuf2->getOperand(1).isUndef() || Shuf2->getMask() != Mask)
17448       return SDValue();
17449   }
17450 
17451   SmallVector<SDValue> Ops;
17452   for (SDValue Op : N->ops()) {
17453     if (Op.getValueType().isVector())
17454       Ops.push_back(Op.getOperand(0));
17455     else
17456       Ops.push_back(Op);
17457   }
17458   return DAG.getNode(N->getOpcode(), SDLoc(N), N->getVTList(), Ops);
17459 }
17460 
PerformVMOVNCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI)17461 static SDValue PerformVMOVNCombine(SDNode *N,
17462                                    TargetLowering::DAGCombinerInfo &DCI) {
17463   SDValue Op0 = N->getOperand(0);
17464   SDValue Op1 = N->getOperand(1);
17465   unsigned IsTop = N->getConstantOperandVal(2);
17466 
17467   // VMOVNT a undef -> a
17468   // VMOVNB a undef -> a
17469   // VMOVNB undef a -> a
17470   if (Op1->isUndef())
17471     return Op0;
17472   if (Op0->isUndef() && !IsTop)
17473     return Op1;
17474 
17475   // VMOVNt(c, VQMOVNb(a, b)) => VQMOVNt(c, b)
17476   // VMOVNb(c, VQMOVNb(a, b)) => VQMOVNb(c, b)
17477   if ((Op1->getOpcode() == ARMISD::VQMOVNs ||
17478        Op1->getOpcode() == ARMISD::VQMOVNu) &&
17479       Op1->getConstantOperandVal(2) == 0)
17480     return DCI.DAG.getNode(Op1->getOpcode(), SDLoc(Op1), N->getValueType(0),
17481                            Op0, Op1->getOperand(1), N->getOperand(2));
17482 
17483   // Only the bottom lanes from Qm (Op1) and either the top or bottom lanes from
17484   // Qd (Op0) are demanded from a VMOVN, depending on whether we are inserting
17485   // into the top or bottom lanes.
17486   unsigned NumElts = N->getValueType(0).getVectorNumElements();
17487   APInt Op1DemandedElts = APInt::getSplat(NumElts, APInt::getLowBitsSet(2, 1));
17488   APInt Op0DemandedElts =
17489       IsTop ? Op1DemandedElts
17490             : APInt::getSplat(NumElts, APInt::getHighBitsSet(2, 1));
17491 
17492   const TargetLowering &TLI = DCI.DAG.getTargetLoweringInfo();
17493   if (TLI.SimplifyDemandedVectorElts(Op0, Op0DemandedElts, DCI))
17494     return SDValue(N, 0);
17495   if (TLI.SimplifyDemandedVectorElts(Op1, Op1DemandedElts, DCI))
17496     return SDValue(N, 0);
17497 
17498   return SDValue();
17499 }
17500 
PerformVQMOVNCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI)17501 static SDValue PerformVQMOVNCombine(SDNode *N,
17502                                     TargetLowering::DAGCombinerInfo &DCI) {
17503   SDValue Op0 = N->getOperand(0);
17504   unsigned IsTop = N->getConstantOperandVal(2);
17505 
17506   unsigned NumElts = N->getValueType(0).getVectorNumElements();
17507   APInt Op0DemandedElts =
17508       APInt::getSplat(NumElts, IsTop ? APInt::getLowBitsSet(2, 1)
17509                                      : APInt::getHighBitsSet(2, 1));
17510 
17511   const TargetLowering &TLI = DCI.DAG.getTargetLoweringInfo();
17512   if (TLI.SimplifyDemandedVectorElts(Op0, Op0DemandedElts, DCI))
17513     return SDValue(N, 0);
17514   return SDValue();
17515 }
17516 
PerformVQDMULHCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI)17517 static SDValue PerformVQDMULHCombine(SDNode *N,
17518                                      TargetLowering::DAGCombinerInfo &DCI) {
17519   EVT VT = N->getValueType(0);
17520   SDValue LHS = N->getOperand(0);
17521   SDValue RHS = N->getOperand(1);
17522 
17523   auto *Shuf0 = dyn_cast<ShuffleVectorSDNode>(LHS);
17524   auto *Shuf1 = dyn_cast<ShuffleVectorSDNode>(RHS);
17525   // Turn VQDMULH(shuffle, shuffle) -> shuffle(VQDMULH)
17526   if (Shuf0 && Shuf1 && Shuf0->getMask().equals(Shuf1->getMask()) &&
17527       LHS.getOperand(1).isUndef() && RHS.getOperand(1).isUndef() &&
17528       (LHS.hasOneUse() || RHS.hasOneUse() || LHS == RHS)) {
17529     SDLoc DL(N);
17530     SDValue NewBinOp = DCI.DAG.getNode(N->getOpcode(), DL, VT,
17531                                        LHS.getOperand(0), RHS.getOperand(0));
17532     SDValue UndefV = LHS.getOperand(1);
17533     return DCI.DAG.getVectorShuffle(VT, DL, NewBinOp, UndefV, Shuf0->getMask());
17534   }
17535   return SDValue();
17536 }
17537 
PerformLongShiftCombine(SDNode * N,SelectionDAG & DAG)17538 static SDValue PerformLongShiftCombine(SDNode *N, SelectionDAG &DAG) {
17539   SDLoc DL(N);
17540   SDValue Op0 = N->getOperand(0);
17541   SDValue Op1 = N->getOperand(1);
17542 
17543   // Turn X << -C -> X >> C and viceversa. The negative shifts can come up from
17544   // uses of the intrinsics.
17545   if (auto C = dyn_cast<ConstantSDNode>(N->getOperand(2))) {
17546     int ShiftAmt = C->getSExtValue();
17547     if (ShiftAmt == 0) {
17548       SDValue Merge = DAG.getMergeValues({Op0, Op1}, DL);
17549       DAG.ReplaceAllUsesWith(N, Merge.getNode());
17550       return SDValue();
17551     }
17552 
17553     if (ShiftAmt >= -32 && ShiftAmt < 0) {
17554       unsigned NewOpcode =
17555           N->getOpcode() == ARMISD::LSLL ? ARMISD::LSRL : ARMISD::LSLL;
17556       SDValue NewShift = DAG.getNode(NewOpcode, DL, N->getVTList(), Op0, Op1,
17557                                      DAG.getConstant(-ShiftAmt, DL, MVT::i32));
17558       DAG.ReplaceAllUsesWith(N, NewShift.getNode());
17559       return NewShift;
17560     }
17561   }
17562 
17563   return SDValue();
17564 }
17565 
17566 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
PerformIntrinsicCombine(SDNode * N,DAGCombinerInfo & DCI) const17567 SDValue ARMTargetLowering::PerformIntrinsicCombine(SDNode *N,
17568                                                    DAGCombinerInfo &DCI) const {
17569   SelectionDAG &DAG = DCI.DAG;
17570   unsigned IntNo = N->getConstantOperandVal(0);
17571   switch (IntNo) {
17572   default:
17573     // Don't do anything for most intrinsics.
17574     break;
17575 
17576   // Vector shifts: check for immediate versions and lower them.
17577   // Note: This is done during DAG combining instead of DAG legalizing because
17578   // the build_vectors for 64-bit vector element shift counts are generally
17579   // not legal, and it is hard to see their values after they get legalized to
17580   // loads from a constant pool.
17581   case Intrinsic::arm_neon_vshifts:
17582   case Intrinsic::arm_neon_vshiftu:
17583   case Intrinsic::arm_neon_vrshifts:
17584   case Intrinsic::arm_neon_vrshiftu:
17585   case Intrinsic::arm_neon_vrshiftn:
17586   case Intrinsic::arm_neon_vqshifts:
17587   case Intrinsic::arm_neon_vqshiftu:
17588   case Intrinsic::arm_neon_vqshiftsu:
17589   case Intrinsic::arm_neon_vqshiftns:
17590   case Intrinsic::arm_neon_vqshiftnu:
17591   case Intrinsic::arm_neon_vqshiftnsu:
17592   case Intrinsic::arm_neon_vqrshiftns:
17593   case Intrinsic::arm_neon_vqrshiftnu:
17594   case Intrinsic::arm_neon_vqrshiftnsu: {
17595     EVT VT = N->getOperand(1).getValueType();
17596     int64_t Cnt;
17597     unsigned VShiftOpc = 0;
17598 
17599     switch (IntNo) {
17600     case Intrinsic::arm_neon_vshifts:
17601     case Intrinsic::arm_neon_vshiftu:
17602       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
17603         VShiftOpc = ARMISD::VSHLIMM;
17604         break;
17605       }
17606       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
17607         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ? ARMISD::VSHRsIMM
17608                                                           : ARMISD::VSHRuIMM);
17609         break;
17610       }
17611       return SDValue();
17612 
17613     case Intrinsic::arm_neon_vrshifts:
17614     case Intrinsic::arm_neon_vrshiftu:
17615       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
17616         break;
17617       return SDValue();
17618 
17619     case Intrinsic::arm_neon_vqshifts:
17620     case Intrinsic::arm_neon_vqshiftu:
17621       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
17622         break;
17623       return SDValue();
17624 
17625     case Intrinsic::arm_neon_vqshiftsu:
17626       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
17627         break;
17628       llvm_unreachable("invalid shift count for vqshlu intrinsic");
17629 
17630     case Intrinsic::arm_neon_vrshiftn:
17631     case Intrinsic::arm_neon_vqshiftns:
17632     case Intrinsic::arm_neon_vqshiftnu:
17633     case Intrinsic::arm_neon_vqshiftnsu:
17634     case Intrinsic::arm_neon_vqrshiftns:
17635     case Intrinsic::arm_neon_vqrshiftnu:
17636     case Intrinsic::arm_neon_vqrshiftnsu:
17637       // Narrowing shifts require an immediate right shift.
17638       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
17639         break;
17640       llvm_unreachable("invalid shift count for narrowing vector shift "
17641                        "intrinsic");
17642 
17643     default:
17644       llvm_unreachable("unhandled vector shift");
17645     }
17646 
17647     switch (IntNo) {
17648     case Intrinsic::arm_neon_vshifts:
17649     case Intrinsic::arm_neon_vshiftu:
17650       // Opcode already set above.
17651       break;
17652     case Intrinsic::arm_neon_vrshifts:
17653       VShiftOpc = ARMISD::VRSHRsIMM;
17654       break;
17655     case Intrinsic::arm_neon_vrshiftu:
17656       VShiftOpc = ARMISD::VRSHRuIMM;
17657       break;
17658     case Intrinsic::arm_neon_vrshiftn:
17659       VShiftOpc = ARMISD::VRSHRNIMM;
17660       break;
17661     case Intrinsic::arm_neon_vqshifts:
17662       VShiftOpc = ARMISD::VQSHLsIMM;
17663       break;
17664     case Intrinsic::arm_neon_vqshiftu:
17665       VShiftOpc = ARMISD::VQSHLuIMM;
17666       break;
17667     case Intrinsic::arm_neon_vqshiftsu:
17668       VShiftOpc = ARMISD::VQSHLsuIMM;
17669       break;
17670     case Intrinsic::arm_neon_vqshiftns:
17671       VShiftOpc = ARMISD::VQSHRNsIMM;
17672       break;
17673     case Intrinsic::arm_neon_vqshiftnu:
17674       VShiftOpc = ARMISD::VQSHRNuIMM;
17675       break;
17676     case Intrinsic::arm_neon_vqshiftnsu:
17677       VShiftOpc = ARMISD::VQSHRNsuIMM;
17678       break;
17679     case Intrinsic::arm_neon_vqrshiftns:
17680       VShiftOpc = ARMISD::VQRSHRNsIMM;
17681       break;
17682     case Intrinsic::arm_neon_vqrshiftnu:
17683       VShiftOpc = ARMISD::VQRSHRNuIMM;
17684       break;
17685     case Intrinsic::arm_neon_vqrshiftnsu:
17686       VShiftOpc = ARMISD::VQRSHRNsuIMM;
17687       break;
17688     }
17689 
17690     SDLoc dl(N);
17691     return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
17692                        N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32));
17693   }
17694 
17695   case Intrinsic::arm_neon_vshiftins: {
17696     EVT VT = N->getOperand(1).getValueType();
17697     int64_t Cnt;
17698     unsigned VShiftOpc = 0;
17699 
17700     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
17701       VShiftOpc = ARMISD::VSLIIMM;
17702     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
17703       VShiftOpc = ARMISD::VSRIIMM;
17704     else {
17705       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
17706     }
17707 
17708     SDLoc dl(N);
17709     return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
17710                        N->getOperand(1), N->getOperand(2),
17711                        DAG.getConstant(Cnt, dl, MVT::i32));
17712   }
17713 
17714   case Intrinsic::arm_neon_vqrshifts:
17715   case Intrinsic::arm_neon_vqrshiftu:
17716     // No immediate versions of these to check for.
17717     break;
17718 
17719   case Intrinsic::arm_neon_vbsl: {
17720     SDLoc dl(N);
17721     return DAG.getNode(ARMISD::VBSP, dl, N->getValueType(0), N->getOperand(1),
17722                        N->getOperand(2), N->getOperand(3));
17723   }
17724   case Intrinsic::arm_mve_vqdmlah:
17725   case Intrinsic::arm_mve_vqdmlash:
17726   case Intrinsic::arm_mve_vqrdmlah:
17727   case Intrinsic::arm_mve_vqrdmlash:
17728   case Intrinsic::arm_mve_vmla_n_predicated:
17729   case Intrinsic::arm_mve_vmlas_n_predicated:
17730   case Intrinsic::arm_mve_vqdmlah_predicated:
17731   case Intrinsic::arm_mve_vqdmlash_predicated:
17732   case Intrinsic::arm_mve_vqrdmlah_predicated:
17733   case Intrinsic::arm_mve_vqrdmlash_predicated: {
17734     // These intrinsics all take an i32 scalar operand which is narrowed to the
17735     // size of a single lane of the vector type they return. So we don't need
17736     // any bits of that operand above that point, which allows us to eliminate
17737     // uxth/sxth.
17738     unsigned BitWidth = N->getValueType(0).getScalarSizeInBits();
17739     APInt DemandedMask = APInt::getLowBitsSet(32, BitWidth);
17740     if (SimplifyDemandedBits(N->getOperand(3), DemandedMask, DCI))
17741       return SDValue();
17742     break;
17743   }
17744 
17745   case Intrinsic::arm_mve_minv:
17746   case Intrinsic::arm_mve_maxv:
17747   case Intrinsic::arm_mve_minav:
17748   case Intrinsic::arm_mve_maxav:
17749   case Intrinsic::arm_mve_minv_predicated:
17750   case Intrinsic::arm_mve_maxv_predicated:
17751   case Intrinsic::arm_mve_minav_predicated:
17752   case Intrinsic::arm_mve_maxav_predicated: {
17753     // These intrinsics all take an i32 scalar operand which is narrowed to the
17754     // size of a single lane of the vector type they take as the other input.
17755     unsigned BitWidth = N->getOperand(2)->getValueType(0).getScalarSizeInBits();
17756     APInt DemandedMask = APInt::getLowBitsSet(32, BitWidth);
17757     if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))
17758       return SDValue();
17759     break;
17760   }
17761 
17762   case Intrinsic::arm_mve_addv: {
17763     // Turn this intrinsic straight into the appropriate ARMISD::VADDV node,
17764     // which allow PerformADDVecReduce to turn it into VADDLV when possible.
17765     bool Unsigned = N->getConstantOperandVal(2);
17766     unsigned Opc = Unsigned ? ARMISD::VADDVu : ARMISD::VADDVs;
17767     return DAG.getNode(Opc, SDLoc(N), N->getVTList(), N->getOperand(1));
17768   }
17769 
17770   case Intrinsic::arm_mve_addlv:
17771   case Intrinsic::arm_mve_addlv_predicated: {
17772     // Same for these, but ARMISD::VADDLV has to be followed by a BUILD_PAIR
17773     // which recombines the two outputs into an i64
17774     bool Unsigned = N->getConstantOperandVal(2);
17775     unsigned Opc = IntNo == Intrinsic::arm_mve_addlv ?
17776                     (Unsigned ? ARMISD::VADDLVu : ARMISD::VADDLVs) :
17777                     (Unsigned ? ARMISD::VADDLVpu : ARMISD::VADDLVps);
17778 
17779     SmallVector<SDValue, 4> Ops;
17780     for (unsigned i = 1, e = N->getNumOperands(); i < e; i++)
17781       if (i != 2)                      // skip the unsigned flag
17782         Ops.push_back(N->getOperand(i));
17783 
17784     SDLoc dl(N);
17785     SDValue val = DAG.getNode(Opc, dl, {MVT::i32, MVT::i32}, Ops);
17786     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, val.getValue(0),
17787                        val.getValue(1));
17788   }
17789   }
17790 
17791   return SDValue();
17792 }
17793 
17794 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
17795 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
17796 /// combining instead of DAG legalizing because the build_vectors for 64-bit
17797 /// vector element shift counts are generally not legal, and it is hard to see
17798 /// their values after they get legalized to loads from a constant pool.
PerformShiftCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI,const ARMSubtarget * ST)17799 static SDValue PerformShiftCombine(SDNode *N,
17800                                    TargetLowering::DAGCombinerInfo &DCI,
17801                                    const ARMSubtarget *ST) {
17802   SelectionDAG &DAG = DCI.DAG;
17803   EVT VT = N->getValueType(0);
17804 
17805   if (ST->isThumb1Only() && N->getOpcode() == ISD::SHL && VT == MVT::i32 &&
17806       N->getOperand(0)->getOpcode() == ISD::AND &&
17807       N->getOperand(0)->hasOneUse()) {
17808     if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
17809       return SDValue();
17810     // Look for the pattern (shl (and x, AndMask), ShiftAmt). This doesn't
17811     // usually show up because instcombine prefers to canonicalize it to
17812     // (and (shl x, ShiftAmt) (shl AndMask, ShiftAmt)), but the shift can come
17813     // out of GEP lowering in some cases.
17814     SDValue N0 = N->getOperand(0);
17815     ConstantSDNode *ShiftAmtNode = dyn_cast<ConstantSDNode>(N->getOperand(1));
17816     if (!ShiftAmtNode)
17817       return SDValue();
17818     uint32_t ShiftAmt = static_cast<uint32_t>(ShiftAmtNode->getZExtValue());
17819     ConstantSDNode *AndMaskNode = dyn_cast<ConstantSDNode>(N0->getOperand(1));
17820     if (!AndMaskNode)
17821       return SDValue();
17822     uint32_t AndMask = static_cast<uint32_t>(AndMaskNode->getZExtValue());
17823     // Don't transform uxtb/uxth.
17824     if (AndMask == 255 || AndMask == 65535)
17825       return SDValue();
17826     if (isMask_32(AndMask)) {
17827       uint32_t MaskedBits = llvm::countl_zero(AndMask);
17828       if (MaskedBits > ShiftAmt) {
17829         SDLoc DL(N);
17830         SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0),
17831                                   DAG.getConstant(MaskedBits, DL, MVT::i32));
17832         return DAG.getNode(
17833             ISD::SRL, DL, MVT::i32, SHL,
17834             DAG.getConstant(MaskedBits - ShiftAmt, DL, MVT::i32));
17835       }
17836     }
17837   }
17838 
17839   // Nothing to be done for scalar shifts.
17840   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17841   if (!VT.isVector() || !TLI.isTypeLegal(VT))
17842     return SDValue();
17843   if (ST->hasMVEIntegerOps())
17844     return SDValue();
17845 
17846   int64_t Cnt;
17847 
17848   switch (N->getOpcode()) {
17849   default: llvm_unreachable("unexpected shift opcode");
17850 
17851   case ISD::SHL:
17852     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) {
17853       SDLoc dl(N);
17854       return DAG.getNode(ARMISD::VSHLIMM, dl, VT, N->getOperand(0),
17855                          DAG.getConstant(Cnt, dl, MVT::i32));
17856     }
17857     break;
17858 
17859   case ISD::SRA:
17860   case ISD::SRL:
17861     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
17862       unsigned VShiftOpc =
17863           (N->getOpcode() == ISD::SRA ? ARMISD::VSHRsIMM : ARMISD::VSHRuIMM);
17864       SDLoc dl(N);
17865       return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0),
17866                          DAG.getConstant(Cnt, dl, MVT::i32));
17867     }
17868   }
17869   return SDValue();
17870 }
17871 
17872 // Look for a sign/zero/fpextend extend of a larger than legal load. This can be
17873 // split into multiple extending loads, which are simpler to deal with than an
17874 // arbitrary extend. For fp extends we use an integer extending load and a VCVTL
17875 // to convert the type to an f32.
PerformSplittingToWideningLoad(SDNode * N,SelectionDAG & DAG)17876 static SDValue PerformSplittingToWideningLoad(SDNode *N, SelectionDAG &DAG) {
17877   SDValue N0 = N->getOperand(0);
17878   if (N0.getOpcode() != ISD::LOAD)
17879     return SDValue();
17880   LoadSDNode *LD = cast<LoadSDNode>(N0.getNode());
17881   if (!LD->isSimple() || !N0.hasOneUse() || LD->isIndexed() ||
17882       LD->getExtensionType() != ISD::NON_EXTLOAD)
17883     return SDValue();
17884   EVT FromVT = LD->getValueType(0);
17885   EVT ToVT = N->getValueType(0);
17886   if (!ToVT.isVector())
17887     return SDValue();
17888   assert(FromVT.getVectorNumElements() == ToVT.getVectorNumElements());
17889   EVT ToEltVT = ToVT.getVectorElementType();
17890   EVT FromEltVT = FromVT.getVectorElementType();
17891 
17892   unsigned NumElements = 0;
17893   if (ToEltVT == MVT::i32 && FromEltVT == MVT::i8)
17894     NumElements = 4;
17895   if (ToEltVT == MVT::f32 && FromEltVT == MVT::f16)
17896     NumElements = 4;
17897   if (NumElements == 0 ||
17898       (FromEltVT != MVT::f16 && FromVT.getVectorNumElements() == NumElements) ||
17899       FromVT.getVectorNumElements() % NumElements != 0 ||
17900       !isPowerOf2_32(NumElements))
17901     return SDValue();
17902 
17903   LLVMContext &C = *DAG.getContext();
17904   SDLoc DL(LD);
17905   // Details about the old load
17906   SDValue Ch = LD->getChain();
17907   SDValue BasePtr = LD->getBasePtr();
17908   Align Alignment = LD->getBaseAlign();
17909   MachineMemOperand::Flags MMOFlags = LD->getMemOperand()->getFlags();
17910   AAMDNodes AAInfo = LD->getAAInfo();
17911 
17912   ISD::LoadExtType NewExtType =
17913       N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
17914   SDValue Offset = DAG.getUNDEF(BasePtr.getValueType());
17915   EVT NewFromVT = EVT::getVectorVT(
17916       C, EVT::getIntegerVT(C, FromEltVT.getScalarSizeInBits()), NumElements);
17917   EVT NewToVT = EVT::getVectorVT(
17918       C, EVT::getIntegerVT(C, ToEltVT.getScalarSizeInBits()), NumElements);
17919 
17920   SmallVector<SDValue, 4> Loads;
17921   SmallVector<SDValue, 4> Chains;
17922   for (unsigned i = 0; i < FromVT.getVectorNumElements() / NumElements; i++) {
17923     unsigned NewOffset = (i * NewFromVT.getSizeInBits()) / 8;
17924     SDValue NewPtr =
17925         DAG.getObjectPtrOffset(DL, BasePtr, TypeSize::getFixed(NewOffset));
17926 
17927     SDValue NewLoad =
17928         DAG.getLoad(ISD::UNINDEXED, NewExtType, NewToVT, DL, Ch, NewPtr, Offset,
17929                     LD->getPointerInfo().getWithOffset(NewOffset), NewFromVT,
17930                     Alignment, MMOFlags, AAInfo);
17931     Loads.push_back(NewLoad);
17932     Chains.push_back(SDValue(NewLoad.getNode(), 1));
17933   }
17934 
17935   // Float truncs need to extended with VCVTB's into their floating point types.
17936   if (FromEltVT == MVT::f16) {
17937     SmallVector<SDValue, 4> Extends;
17938 
17939     for (unsigned i = 0; i < Loads.size(); i++) {
17940       SDValue LoadBC =
17941           DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, MVT::v8f16, Loads[i]);
17942       SDValue FPExt = DAG.getNode(ARMISD::VCVTL, DL, MVT::v4f32, LoadBC,
17943                                   DAG.getConstant(0, DL, MVT::i32));
17944       Extends.push_back(FPExt);
17945     }
17946 
17947     Loads = Extends;
17948   }
17949 
17950   SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
17951   DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewChain);
17952   return DAG.getNode(ISD::CONCAT_VECTORS, DL, ToVT, Loads);
17953 }
17954 
17955 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
17956 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
PerformExtendCombine(SDNode * N,SelectionDAG & DAG,const ARMSubtarget * ST)17957 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
17958                                     const ARMSubtarget *ST) {
17959   SDValue N0 = N->getOperand(0);
17960 
17961   // Check for sign- and zero-extensions of vector extract operations of 8- and
17962   // 16-bit vector elements. NEON and MVE support these directly. They are
17963   // handled during DAG combining because type legalization will promote them
17964   // to 32-bit types and it is messy to recognize the operations after that.
17965   if ((ST->hasNEON() || ST->hasMVEIntegerOps()) &&
17966       N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
17967     SDValue Vec = N0.getOperand(0);
17968     SDValue Lane = N0.getOperand(1);
17969     EVT VT = N->getValueType(0);
17970     EVT EltVT = N0.getValueType();
17971     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17972 
17973     if (VT == MVT::i32 &&
17974         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
17975         TLI.isTypeLegal(Vec.getValueType()) &&
17976         isa<ConstantSDNode>(Lane)) {
17977 
17978       unsigned Opc = 0;
17979       switch (N->getOpcode()) {
17980       default: llvm_unreachable("unexpected opcode");
17981       case ISD::SIGN_EXTEND:
17982         Opc = ARMISD::VGETLANEs;
17983         break;
17984       case ISD::ZERO_EXTEND:
17985       case ISD::ANY_EXTEND:
17986         Opc = ARMISD::VGETLANEu;
17987         break;
17988       }
17989       return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
17990     }
17991   }
17992 
17993   if (ST->hasMVEIntegerOps())
17994     if (SDValue NewLoad = PerformSplittingToWideningLoad(N, DAG))
17995       return NewLoad;
17996 
17997   return SDValue();
17998 }
17999 
PerformFPExtendCombine(SDNode * N,SelectionDAG & DAG,const ARMSubtarget * ST)18000 static SDValue PerformFPExtendCombine(SDNode *N, SelectionDAG &DAG,
18001                                       const ARMSubtarget *ST) {
18002   if (ST->hasMVEFloatOps())
18003     if (SDValue NewLoad = PerformSplittingToWideningLoad(N, DAG))
18004       return NewLoad;
18005 
18006   return SDValue();
18007 }
18008 
18009 // Lower smin(smax(x, C1), C2) to ssat or usat, if they have saturating
18010 // constant bounds.
PerformMinMaxToSatCombine(SDValue Op,SelectionDAG & DAG,const ARMSubtarget * Subtarget)18011 static SDValue PerformMinMaxToSatCombine(SDValue Op, SelectionDAG &DAG,
18012                                          const ARMSubtarget *Subtarget) {
18013   if ((Subtarget->isThumb() || !Subtarget->hasV6Ops()) &&
18014       !Subtarget->isThumb2())
18015     return SDValue();
18016 
18017   EVT VT = Op.getValueType();
18018   SDValue Op0 = Op.getOperand(0);
18019 
18020   if (VT != MVT::i32 ||
18021       (Op0.getOpcode() != ISD::SMIN && Op0.getOpcode() != ISD::SMAX) ||
18022       !isa<ConstantSDNode>(Op.getOperand(1)) ||
18023       !isa<ConstantSDNode>(Op0.getOperand(1)))
18024     return SDValue();
18025 
18026   SDValue Min = Op;
18027   SDValue Max = Op0;
18028   SDValue Input = Op0.getOperand(0);
18029   if (Min.getOpcode() == ISD::SMAX)
18030     std::swap(Min, Max);
18031 
18032   APInt MinC = Min.getConstantOperandAPInt(1);
18033   APInt MaxC = Max.getConstantOperandAPInt(1);
18034 
18035   if (Min.getOpcode() != ISD::SMIN || Max.getOpcode() != ISD::SMAX ||
18036       !(MinC + 1).isPowerOf2())
18037     return SDValue();
18038 
18039   SDLoc DL(Op);
18040   if (MinC == ~MaxC)
18041     return DAG.getNode(ARMISD::SSAT, DL, VT, Input,
18042                        DAG.getConstant(MinC.countr_one(), DL, VT));
18043   if (MaxC == 0)
18044     return DAG.getNode(ARMISD::USAT, DL, VT, Input,
18045                        DAG.getConstant(MinC.countr_one(), DL, VT));
18046 
18047   return SDValue();
18048 }
18049 
18050 /// PerformMinMaxCombine - Target-specific DAG combining for creating truncating
18051 /// saturates.
PerformMinMaxCombine(SDNode * N,SelectionDAG & DAG,const ARMSubtarget * ST)18052 static SDValue PerformMinMaxCombine(SDNode *N, SelectionDAG &DAG,
18053                                     const ARMSubtarget *ST) {
18054   EVT VT = N->getValueType(0);
18055   SDValue N0 = N->getOperand(0);
18056 
18057   if (VT == MVT::i32)
18058     return PerformMinMaxToSatCombine(SDValue(N, 0), DAG, ST);
18059 
18060   if (!ST->hasMVEIntegerOps())
18061     return SDValue();
18062 
18063   if (SDValue V = PerformVQDMULHCombine(N, DAG))
18064     return V;
18065 
18066   if (VT != MVT::v4i32 && VT != MVT::v8i16)
18067     return SDValue();
18068 
18069   auto IsSignedSaturate = [&](SDNode *Min, SDNode *Max) {
18070     // Check one is a smin and the other is a smax
18071     if (Min->getOpcode() != ISD::SMIN)
18072       std::swap(Min, Max);
18073     if (Min->getOpcode() != ISD::SMIN || Max->getOpcode() != ISD::SMAX)
18074       return false;
18075 
18076     APInt SaturateC;
18077     if (VT == MVT::v4i32)
18078       SaturateC = APInt(32, (1 << 15) - 1, true);
18079     else //if (VT == MVT::v8i16)
18080       SaturateC = APInt(16, (1 << 7) - 1, true);
18081 
18082     APInt MinC, MaxC;
18083     if (!ISD::isConstantSplatVector(Min->getOperand(1).getNode(), MinC) ||
18084         MinC != SaturateC)
18085       return false;
18086     if (!ISD::isConstantSplatVector(Max->getOperand(1).getNode(), MaxC) ||
18087         MaxC != ~SaturateC)
18088       return false;
18089     return true;
18090   };
18091 
18092   if (IsSignedSaturate(N, N0.getNode())) {
18093     SDLoc DL(N);
18094     MVT ExtVT, HalfVT;
18095     if (VT == MVT::v4i32) {
18096       HalfVT = MVT::v8i16;
18097       ExtVT = MVT::v4i16;
18098     } else { // if (VT == MVT::v8i16)
18099       HalfVT = MVT::v16i8;
18100       ExtVT = MVT::v8i8;
18101     }
18102 
18103     // Create a VQMOVNB with undef top lanes, then signed extended into the top
18104     // half. That extend will hopefully be removed if only the bottom bits are
18105     // demanded (though a truncating store, for example).
18106     SDValue VQMOVN =
18107         DAG.getNode(ARMISD::VQMOVNs, DL, HalfVT, DAG.getUNDEF(HalfVT),
18108                     N0->getOperand(0), DAG.getConstant(0, DL, MVT::i32));
18109     SDValue Bitcast = DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, VT, VQMOVN);
18110     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, Bitcast,
18111                        DAG.getValueType(ExtVT));
18112   }
18113 
18114   auto IsUnsignedSaturate = [&](SDNode *Min) {
18115     // For unsigned, we just need to check for <= 0xffff
18116     if (Min->getOpcode() != ISD::UMIN)
18117       return false;
18118 
18119     APInt SaturateC;
18120     if (VT == MVT::v4i32)
18121       SaturateC = APInt(32, (1 << 16) - 1, true);
18122     else //if (VT == MVT::v8i16)
18123       SaturateC = APInt(16, (1 << 8) - 1, true);
18124 
18125     APInt MinC;
18126     if (!ISD::isConstantSplatVector(Min->getOperand(1).getNode(), MinC) ||
18127         MinC != SaturateC)
18128       return false;
18129     return true;
18130   };
18131 
18132   if (IsUnsignedSaturate(N)) {
18133     SDLoc DL(N);
18134     MVT HalfVT;
18135     unsigned ExtConst;
18136     if (VT == MVT::v4i32) {
18137       HalfVT = MVT::v8i16;
18138       ExtConst = 0x0000FFFF;
18139     } else { //if (VT == MVT::v8i16)
18140       HalfVT = MVT::v16i8;
18141       ExtConst = 0x00FF;
18142     }
18143 
18144     // Create a VQMOVNB with undef top lanes, then ZExt into the top half with
18145     // an AND. That extend will hopefully be removed if only the bottom bits are
18146     // demanded (though a truncating store, for example).
18147     SDValue VQMOVN =
18148         DAG.getNode(ARMISD::VQMOVNu, DL, HalfVT, DAG.getUNDEF(HalfVT), N0,
18149                     DAG.getConstant(0, DL, MVT::i32));
18150     SDValue Bitcast = DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, VT, VQMOVN);
18151     return DAG.getNode(ISD::AND, DL, VT, Bitcast,
18152                        DAG.getConstant(ExtConst, DL, VT));
18153   }
18154 
18155   return SDValue();
18156 }
18157 
isPowerOf2Constant(SDValue V)18158 static const APInt *isPowerOf2Constant(SDValue V) {
18159   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
18160   if (!C)
18161     return nullptr;
18162   const APInt *CV = &C->getAPIntValue();
18163   return CV->isPowerOf2() ? CV : nullptr;
18164 }
18165 
PerformCMOVToBFICombine(SDNode * CMOV,SelectionDAG & DAG) const18166 SDValue ARMTargetLowering::PerformCMOVToBFICombine(SDNode *CMOV, SelectionDAG &DAG) const {
18167   // If we have a CMOV, OR and AND combination such as:
18168   //   if (x & CN)
18169   //     y |= CM;
18170   //
18171   // And:
18172   //   * CN is a single bit;
18173   //   * All bits covered by CM are known zero in y
18174   //
18175   // Then we can convert this into a sequence of BFI instructions. This will
18176   // always be a win if CM is a single bit, will always be no worse than the
18177   // TST&OR sequence if CM is two bits, and for thumb will be no worse if CM is
18178   // three bits (due to the extra IT instruction).
18179 
18180   SDValue Op0 = CMOV->getOperand(0);
18181   SDValue Op1 = CMOV->getOperand(1);
18182   auto CC = CMOV->getConstantOperandAPInt(2).getLimitedValue();
18183   SDValue CmpZ = CMOV->getOperand(3);
18184 
18185   // The compare must be against zero.
18186   if (!isNullConstant(CmpZ->getOperand(1)))
18187     return SDValue();
18188 
18189   assert(CmpZ->getOpcode() == ARMISD::CMPZ);
18190   SDValue And = CmpZ->getOperand(0);
18191   if (And->getOpcode() != ISD::AND)
18192     return SDValue();
18193   const APInt *AndC = isPowerOf2Constant(And->getOperand(1));
18194   if (!AndC)
18195     return SDValue();
18196   SDValue X = And->getOperand(0);
18197 
18198   if (CC == ARMCC::EQ) {
18199     // We're performing an "equal to zero" compare. Swap the operands so we
18200     // canonicalize on a "not equal to zero" compare.
18201     std::swap(Op0, Op1);
18202   } else {
18203     assert(CC == ARMCC::NE && "How can a CMPZ node not be EQ or NE?");
18204   }
18205 
18206   if (Op1->getOpcode() != ISD::OR)
18207     return SDValue();
18208 
18209   ConstantSDNode *OrC = dyn_cast<ConstantSDNode>(Op1->getOperand(1));
18210   if (!OrC)
18211     return SDValue();
18212   SDValue Y = Op1->getOperand(0);
18213 
18214   if (Op0 != Y)
18215     return SDValue();
18216 
18217   // Now, is it profitable to continue?
18218   APInt OrCI = OrC->getAPIntValue();
18219   unsigned Heuristic = Subtarget->isThumb() ? 3 : 2;
18220   if (OrCI.popcount() > Heuristic)
18221     return SDValue();
18222 
18223   // Lastly, can we determine that the bits defined by OrCI
18224   // are zero in Y?
18225   KnownBits Known = DAG.computeKnownBits(Y);
18226   if ((OrCI & Known.Zero) != OrCI)
18227     return SDValue();
18228 
18229   // OK, we can do the combine.
18230   SDValue V = Y;
18231   SDLoc dl(X);
18232   EVT VT = X.getValueType();
18233   unsigned BitInX = AndC->logBase2();
18234 
18235   if (BitInX != 0) {
18236     // We must shift X first.
18237     X = DAG.getNode(ISD::SRL, dl, VT, X,
18238                     DAG.getConstant(BitInX, dl, VT));
18239   }
18240 
18241   for (unsigned BitInY = 0, NumActiveBits = OrCI.getActiveBits();
18242        BitInY < NumActiveBits; ++BitInY) {
18243     if (OrCI[BitInY] == 0)
18244       continue;
18245     APInt Mask(VT.getSizeInBits(), 0);
18246     Mask.setBit(BitInY);
18247     V = DAG.getNode(ARMISD::BFI, dl, VT, V, X,
18248                     // Confusingly, the operand is an *inverted* mask.
18249                     DAG.getConstant(~Mask, dl, VT));
18250   }
18251 
18252   return V;
18253 }
18254 
18255 // Given N, the value controlling the conditional branch, search for the loop
18256 // intrinsic, returning it, along with how the value is used. We need to handle
18257 // patterns such as the following:
18258 // (brcond (xor (setcc (loop.decrement), 0, ne), 1), exit)
18259 // (brcond (setcc (loop.decrement), 0, eq), exit)
18260 // (brcond (setcc (loop.decrement), 0, ne), header)
SearchLoopIntrinsic(SDValue N,ISD::CondCode & CC,int & Imm,bool & Negate)18261 static SDValue SearchLoopIntrinsic(SDValue N, ISD::CondCode &CC, int &Imm,
18262                                    bool &Negate) {
18263   switch (N->getOpcode()) {
18264   default:
18265     break;
18266   case ISD::XOR: {
18267     if (!isa<ConstantSDNode>(N.getOperand(1)))
18268       return SDValue();
18269     if (!cast<ConstantSDNode>(N.getOperand(1))->isOne())
18270       return SDValue();
18271     Negate = !Negate;
18272     return SearchLoopIntrinsic(N.getOperand(0), CC, Imm, Negate);
18273   }
18274   case ISD::SETCC: {
18275     auto *Const = dyn_cast<ConstantSDNode>(N.getOperand(1));
18276     if (!Const)
18277       return SDValue();
18278     if (Const->isZero())
18279       Imm = 0;
18280     else if (Const->isOne())
18281       Imm = 1;
18282     else
18283       return SDValue();
18284     CC = cast<CondCodeSDNode>(N.getOperand(2))->get();
18285     return SearchLoopIntrinsic(N->getOperand(0), CC, Imm, Negate);
18286   }
18287   case ISD::INTRINSIC_W_CHAIN: {
18288     unsigned IntOp = N.getConstantOperandVal(1);
18289     if (IntOp != Intrinsic::test_start_loop_iterations &&
18290         IntOp != Intrinsic::loop_decrement_reg)
18291       return SDValue();
18292     return N;
18293   }
18294   }
18295   return SDValue();
18296 }
18297 
PerformHWLoopCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI,const ARMSubtarget * ST)18298 static SDValue PerformHWLoopCombine(SDNode *N,
18299                                     TargetLowering::DAGCombinerInfo &DCI,
18300                                     const ARMSubtarget *ST) {
18301 
18302   // The hwloop intrinsics that we're interested are used for control-flow,
18303   // either for entering or exiting the loop:
18304   // - test.start.loop.iterations will test whether its operand is zero. If it
18305   //   is zero, the proceeding branch should not enter the loop.
18306   // - loop.decrement.reg also tests whether its operand is zero. If it is
18307   //   zero, the proceeding branch should not branch back to the beginning of
18308   //   the loop.
18309   // So here, we need to check that how the brcond is using the result of each
18310   // of the intrinsics to ensure that we're branching to the right place at the
18311   // right time.
18312 
18313   ISD::CondCode CC;
18314   SDValue Cond;
18315   int Imm = 1;
18316   bool Negate = false;
18317   SDValue Chain = N->getOperand(0);
18318   SDValue Dest;
18319 
18320   if (N->getOpcode() == ISD::BRCOND) {
18321     CC = ISD::SETEQ;
18322     Cond = N->getOperand(1);
18323     Dest = N->getOperand(2);
18324   } else {
18325     assert(N->getOpcode() == ISD::BR_CC && "Expected BRCOND or BR_CC!");
18326     CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
18327     Cond = N->getOperand(2);
18328     Dest = N->getOperand(4);
18329     if (auto *Const = dyn_cast<ConstantSDNode>(N->getOperand(3))) {
18330       if (!Const->isOne() && !Const->isZero())
18331         return SDValue();
18332       Imm = Const->getZExtValue();
18333     } else
18334       return SDValue();
18335   }
18336 
18337   SDValue Int = SearchLoopIntrinsic(Cond, CC, Imm, Negate);
18338   if (!Int)
18339     return SDValue();
18340 
18341   if (Negate)
18342     CC = ISD::getSetCCInverse(CC, /* Integer inverse */ MVT::i32);
18343 
18344   auto IsTrueIfZero = [](ISD::CondCode CC, int Imm) {
18345     return (CC == ISD::SETEQ && Imm == 0) ||
18346            (CC == ISD::SETNE && Imm == 1) ||
18347            (CC == ISD::SETLT && Imm == 1) ||
18348            (CC == ISD::SETULT && Imm == 1);
18349   };
18350 
18351   auto IsFalseIfZero = [](ISD::CondCode CC, int Imm) {
18352     return (CC == ISD::SETEQ && Imm == 1) ||
18353            (CC == ISD::SETNE && Imm == 0) ||
18354            (CC == ISD::SETGT && Imm == 0) ||
18355            (CC == ISD::SETUGT && Imm == 0) ||
18356            (CC == ISD::SETGE && Imm == 1) ||
18357            (CC == ISD::SETUGE && Imm == 1);
18358   };
18359 
18360   assert((IsTrueIfZero(CC, Imm) || IsFalseIfZero(CC, Imm)) &&
18361          "unsupported condition");
18362 
18363   SDLoc dl(Int);
18364   SelectionDAG &DAG = DCI.DAG;
18365   SDValue Elements = Int.getOperand(2);
18366   unsigned IntOp = Int->getConstantOperandVal(1);
18367   assert((N->hasOneUse() && N->user_begin()->getOpcode() == ISD::BR) &&
18368          "expected single br user");
18369   SDNode *Br = *N->user_begin();
18370   SDValue OtherTarget = Br->getOperand(1);
18371 
18372   // Update the unconditional branch to branch to the given Dest.
18373   auto UpdateUncondBr = [](SDNode *Br, SDValue Dest, SelectionDAG &DAG) {
18374     SDValue NewBrOps[] = { Br->getOperand(0), Dest };
18375     SDValue NewBr = DAG.getNode(ISD::BR, SDLoc(Br), MVT::Other, NewBrOps);
18376     DAG.ReplaceAllUsesOfValueWith(SDValue(Br, 0), NewBr);
18377   };
18378 
18379   if (IntOp == Intrinsic::test_start_loop_iterations) {
18380     SDValue Res;
18381     SDValue Setup = DAG.getNode(ARMISD::WLSSETUP, dl, MVT::i32, Elements);
18382     // We expect this 'instruction' to branch when the counter is zero.
18383     if (IsTrueIfZero(CC, Imm)) {
18384       SDValue Ops[] = {Chain, Setup, Dest};
18385       Res = DAG.getNode(ARMISD::WLS, dl, MVT::Other, Ops);
18386     } else {
18387       // The logic is the reverse of what we need for WLS, so find the other
18388       // basic block target: the target of the proceeding br.
18389       UpdateUncondBr(Br, Dest, DAG);
18390 
18391       SDValue Ops[] = {Chain, Setup, OtherTarget};
18392       Res = DAG.getNode(ARMISD::WLS, dl, MVT::Other, Ops);
18393     }
18394     // Update LR count to the new value
18395     DAG.ReplaceAllUsesOfValueWith(Int.getValue(0), Setup);
18396     // Update chain
18397     DAG.ReplaceAllUsesOfValueWith(Int.getValue(2), Int.getOperand(0));
18398     return Res;
18399   } else {
18400     SDValue Size =
18401         DAG.getTargetConstant(Int.getConstantOperandVal(3), dl, MVT::i32);
18402     SDValue Args[] = { Int.getOperand(0), Elements, Size, };
18403     SDValue LoopDec = DAG.getNode(ARMISD::LOOP_DEC, dl,
18404                                   DAG.getVTList(MVT::i32, MVT::Other), Args);
18405     DAG.ReplaceAllUsesWith(Int.getNode(), LoopDec.getNode());
18406 
18407     // We expect this instruction to branch when the count is not zero.
18408     SDValue Target = IsFalseIfZero(CC, Imm) ? Dest : OtherTarget;
18409 
18410     // Update the unconditional branch to target the loop preheader if we've
18411     // found the condition has been reversed.
18412     if (Target == OtherTarget)
18413       UpdateUncondBr(Br, Dest, DAG);
18414 
18415     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
18416                         SDValue(LoopDec.getNode(), 1), Chain);
18417 
18418     SDValue EndArgs[] = { Chain, SDValue(LoopDec.getNode(), 0), Target };
18419     return DAG.getNode(ARMISD::LE, dl, MVT::Other, EndArgs);
18420   }
18421   return SDValue();
18422 }
18423 
18424 /// PerformBRCONDCombine - Target-specific DAG combining for ARMISD::BRCOND.
18425 SDValue
PerformBRCONDCombine(SDNode * N,SelectionDAG & DAG) const18426 ARMTargetLowering::PerformBRCONDCombine(SDNode *N, SelectionDAG &DAG) const {
18427   SDValue Cmp = N->getOperand(3);
18428   if (Cmp.getOpcode() != ARMISD::CMPZ)
18429     // Only looking at NE cases.
18430     return SDValue();
18431 
18432   SDLoc dl(N);
18433   SDValue LHS = Cmp.getOperand(0);
18434   SDValue RHS = Cmp.getOperand(1);
18435   SDValue Chain = N->getOperand(0);
18436   SDValue BB = N->getOperand(1);
18437   SDValue ARMcc = N->getOperand(2);
18438   ARMCC::CondCodes CC = (ARMCC::CondCodes)ARMcc->getAsZExtVal();
18439 
18440   // (brcond Chain BB ne (cmpz (and (cmov 0 1 CC Flags) 1) 0))
18441   // -> (brcond Chain BB CC Flags)
18442   if (CC == ARMCC::NE && LHS.getOpcode() == ISD::AND && LHS->hasOneUse() &&
18443       LHS->getOperand(0)->getOpcode() == ARMISD::CMOV &&
18444       LHS->getOperand(0)->hasOneUse() &&
18445       isNullConstant(LHS->getOperand(0)->getOperand(0)) &&
18446       isOneConstant(LHS->getOperand(0)->getOperand(1)) &&
18447       isOneConstant(LHS->getOperand(1)) && isNullConstant(RHS)) {
18448     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, BB,
18449                        LHS->getOperand(0)->getOperand(2),
18450                        LHS->getOperand(0)->getOperand(3));
18451   }
18452 
18453   return SDValue();
18454 }
18455 
18456 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
18457 SDValue
PerformCMOVCombine(SDNode * N,SelectionDAG & DAG) const18458 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
18459   SDValue Cmp = N->getOperand(3);
18460   if (Cmp.getOpcode() != ARMISD::CMPZ)
18461     // Only looking at EQ and NE cases.
18462     return SDValue();
18463 
18464   EVT VT = N->getValueType(0);
18465   SDLoc dl(N);
18466   SDValue LHS = Cmp.getOperand(0);
18467   SDValue RHS = Cmp.getOperand(1);
18468   SDValue FalseVal = N->getOperand(0);
18469   SDValue TrueVal = N->getOperand(1);
18470   SDValue ARMcc = N->getOperand(2);
18471   ARMCC::CondCodes CC = (ARMCC::CondCodes)ARMcc->getAsZExtVal();
18472 
18473   // BFI is only available on V6T2+.
18474   if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) {
18475     SDValue R = PerformCMOVToBFICombine(N, DAG);
18476     if (R)
18477       return R;
18478   }
18479 
18480   // Simplify
18481   //   mov     r1, r0
18482   //   cmp     r1, x
18483   //   mov     r0, y
18484   //   moveq   r0, x
18485   // to
18486   //   cmp     r0, x
18487   //   movne   r0, y
18488   //
18489   //   mov     r1, r0
18490   //   cmp     r1, x
18491   //   mov     r0, x
18492   //   movne   r0, y
18493   // to
18494   //   cmp     r0, x
18495   //   movne   r0, y
18496   /// FIXME: Turn this into a target neutral optimization?
18497   SDValue Res;
18498   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
18499     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc, Cmp);
18500   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
18501     SDValue ARMcc;
18502     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
18503     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc, NewCmp);
18504   }
18505 
18506   // (cmov F T ne (cmpz (cmov 0 1 CC Flags) 0))
18507   // -> (cmov F T CC Flags)
18508   if (CC == ARMCC::NE && LHS.getOpcode() == ARMISD::CMOV && LHS->hasOneUse() &&
18509       isNullConstant(LHS->getOperand(0)) && isOneConstant(LHS->getOperand(1)) &&
18510       isNullConstant(RHS)) {
18511     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
18512                        LHS->getOperand(2), LHS->getOperand(3));
18513   }
18514 
18515   if (!VT.isInteger())
18516       return SDValue();
18517 
18518   // Fold away an unneccessary CMPZ/CMOV
18519   // CMOV A, B, C1, (CMPZ (CMOV 1, 0, C2, D), 0) ->
18520   // if C1==EQ -> CMOV A, B, C2, D
18521   // if C1==NE -> CMOV A, B, NOT(C2), D
18522   if (N->getConstantOperandVal(2) == ARMCC::EQ ||
18523       N->getConstantOperandVal(2) == ARMCC::NE) {
18524     ARMCC::CondCodes Cond;
18525     if (SDValue C = IsCMPZCSINC(N->getOperand(3).getNode(), Cond)) {
18526       if (N->getConstantOperandVal(2) == ARMCC::NE)
18527         Cond = ARMCC::getOppositeCondition(Cond);
18528       return DAG.getNode(N->getOpcode(), SDLoc(N), MVT::i32, N->getOperand(0),
18529                          N->getOperand(1),
18530                          DAG.getConstant(Cond, SDLoc(N), MVT::i32), C);
18531     }
18532   }
18533 
18534   // Materialize a boolean comparison for integers so we can avoid branching.
18535   if (isNullConstant(FalseVal)) {
18536     if (CC == ARMCC::EQ && isOneConstant(TrueVal)) {
18537       if (!Subtarget->isThumb1Only() && Subtarget->hasV5TOps()) {
18538         // If x == y then x - y == 0 and ARM's CLZ will return 32, shifting it
18539         // right 5 bits will make that 32 be 1, otherwise it will be 0.
18540         // CMOV 0, 1, ==, (CMPZ x, y) -> SRL (CTLZ (SUB x, y)), 5
18541         SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS);
18542         Res = DAG.getNode(ISD::SRL, dl, VT, DAG.getNode(ISD::CTLZ, dl, VT, Sub),
18543                           DAG.getConstant(5, dl, MVT::i32));
18544       } else {
18545         // CMOV 0, 1, ==, (CMPZ x, y) ->
18546         //     (UADDO_CARRY (SUB x, y), t:0, t:1)
18547         // where t = (USUBO_CARRY 0, (SUB x, y), 0)
18548         //
18549         // The USUBO_CARRY computes 0 - (x - y) and this will give a borrow when
18550         // x != y. In other words, a carry C == 1 when x == y, C == 0
18551         // otherwise.
18552         // The final UADDO_CARRY computes
18553         //     x - y + (0 - (x - y)) + C == C
18554         SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS);
18555         SDVTList VTs = DAG.getVTList(VT, MVT::i32);
18556         SDValue Neg = DAG.getNode(ISD::USUBO, dl, VTs, FalseVal, Sub);
18557         // ISD::USUBO_CARRY returns a borrow but we want the carry here
18558         // actually.
18559         SDValue Carry =
18560             DAG.getNode(ISD::SUB, dl, MVT::i32,
18561                         DAG.getConstant(1, dl, MVT::i32), Neg.getValue(1));
18562         Res = DAG.getNode(ISD::UADDO_CARRY, dl, VTs, Sub, Neg, Carry);
18563       }
18564     } else if (CC == ARMCC::NE && !isNullConstant(RHS) &&
18565                (!Subtarget->isThumb1Only() || isPowerOf2Constant(TrueVal))) {
18566       // This seems pointless but will allow us to combine it further below.
18567       // CMOV 0, z, !=, (CMPZ x, y) -> CMOV (SUBC x, y), z, !=, (SUBC x, y):1
18568       SDValue Sub =
18569           DAG.getNode(ARMISD::SUBC, dl, DAG.getVTList(VT, MVT::i32), LHS, RHS);
18570       Res = DAG.getNode(ARMISD::CMOV, dl, VT, Sub, TrueVal, ARMcc,
18571                         Sub.getValue(1));
18572       FalseVal = Sub;
18573     }
18574   } else if (isNullConstant(TrueVal)) {
18575     if (CC == ARMCC::EQ && !isNullConstant(RHS) &&
18576         (!Subtarget->isThumb1Only() || isPowerOf2Constant(FalseVal))) {
18577       // This seems pointless but will allow us to combine it further below
18578       // Note that we change == for != as this is the dual for the case above.
18579       // CMOV z, 0, ==, (CMPZ x, y) -> CMOV (SUBC x, y), z, !=, (SUBC x, y):1
18580       SDValue Sub =
18581           DAG.getNode(ARMISD::SUBC, dl, DAG.getVTList(VT, MVT::i32), LHS, RHS);
18582       Res = DAG.getNode(ARMISD::CMOV, dl, VT, Sub, FalseVal,
18583                         DAG.getConstant(ARMCC::NE, dl, MVT::i32),
18584                         Sub.getValue(1));
18585       FalseVal = Sub;
18586     }
18587   }
18588 
18589   // On Thumb1, the DAG above may be further combined if z is a power of 2
18590   // (z == 2 ^ K).
18591   // CMOV (SUBC x, y), z, !=, (SUBC x, y):1 ->
18592   // t1 = (USUBO (SUB x, y), 1)
18593   // t2 = (USUBO_CARRY (SUB x, y), t1:0, t1:1)
18594   // Result = if K != 0 then (SHL t2:0, K) else t2:0
18595   //
18596   // This also handles the special case of comparing against zero; it's
18597   // essentially, the same pattern, except there's no SUBC:
18598   // CMOV x, z, !=, (CMPZ x, 0) ->
18599   // t1 = (USUBO x, 1)
18600   // t2 = (USUBO_CARRY x, t1:0, t1:1)
18601   // Result = if K != 0 then (SHL t2:0, K) else t2:0
18602   const APInt *TrueConst;
18603   if (Subtarget->isThumb1Only() && CC == ARMCC::NE &&
18604       ((FalseVal.getOpcode() == ARMISD::SUBC && FalseVal.getOperand(0) == LHS &&
18605         FalseVal.getOperand(1) == RHS) ||
18606        (FalseVal == LHS && isNullConstant(RHS))) &&
18607       (TrueConst = isPowerOf2Constant(TrueVal))) {
18608     SDVTList VTs = DAG.getVTList(VT, MVT::i32);
18609     unsigned ShiftAmount = TrueConst->logBase2();
18610     if (ShiftAmount)
18611       TrueVal = DAG.getConstant(1, dl, VT);
18612     SDValue Subc = DAG.getNode(ISD::USUBO, dl, VTs, FalseVal, TrueVal);
18613     Res = DAG.getNode(ISD::USUBO_CARRY, dl, VTs, FalseVal, Subc,
18614                       Subc.getValue(1));
18615 
18616     if (ShiftAmount)
18617       Res = DAG.getNode(ISD::SHL, dl, VT, Res,
18618                         DAG.getConstant(ShiftAmount, dl, MVT::i32));
18619   }
18620 
18621   if (Res.getNode()) {
18622     KnownBits Known = DAG.computeKnownBits(SDValue(N,0));
18623     // Capture demanded bits information that would be otherwise lost.
18624     if (Known.Zero == 0xfffffffe)
18625       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
18626                         DAG.getValueType(MVT::i1));
18627     else if (Known.Zero == 0xffffff00)
18628       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
18629                         DAG.getValueType(MVT::i8));
18630     else if (Known.Zero == 0xffff0000)
18631       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
18632                         DAG.getValueType(MVT::i16));
18633   }
18634 
18635   return Res;
18636 }
18637 
PerformBITCASTCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI,const ARMSubtarget * ST)18638 static SDValue PerformBITCASTCombine(SDNode *N,
18639                                      TargetLowering::DAGCombinerInfo &DCI,
18640                                      const ARMSubtarget *ST) {
18641   SelectionDAG &DAG = DCI.DAG;
18642   SDValue Src = N->getOperand(0);
18643   EVT DstVT = N->getValueType(0);
18644 
18645   // Convert v4f32 bitcast (v4i32 vdup (i32)) -> v4f32 vdup (i32) under MVE.
18646   if (ST->hasMVEIntegerOps() && Src.getOpcode() == ARMISD::VDUP) {
18647     EVT SrcVT = Src.getValueType();
18648     if (SrcVT.getScalarSizeInBits() == DstVT.getScalarSizeInBits())
18649       return DAG.getNode(ARMISD::VDUP, SDLoc(N), DstVT, Src.getOperand(0));
18650   }
18651 
18652   // We may have a bitcast of something that has already had this bitcast
18653   // combine performed on it, so skip past any VECTOR_REG_CASTs.
18654   if (Src.getOpcode() == ARMISD::VECTOR_REG_CAST &&
18655       Src.getOperand(0).getValueType().getScalarSizeInBits() <=
18656           Src.getValueType().getScalarSizeInBits())
18657     Src = Src.getOperand(0);
18658 
18659   // Bitcast from element-wise VMOV or VMVN doesn't need VREV if the VREV that
18660   // would be generated is at least the width of the element type.
18661   EVT SrcVT = Src.getValueType();
18662   if ((Src.getOpcode() == ARMISD::VMOVIMM ||
18663        Src.getOpcode() == ARMISD::VMVNIMM ||
18664        Src.getOpcode() == ARMISD::VMOVFPIMM) &&
18665       SrcVT.getScalarSizeInBits() <= DstVT.getScalarSizeInBits() &&
18666       DAG.getDataLayout().isBigEndian())
18667     return DAG.getNode(ARMISD::VECTOR_REG_CAST, SDLoc(N), DstVT, Src);
18668 
18669   // bitcast(extract(x, n)); bitcast(extract(x, n+1))  ->  VMOVRRD x
18670   if (SDValue R = PerformExtractEltToVMOVRRD(N, DCI))
18671     return R;
18672 
18673   return SDValue();
18674 }
18675 
18676 // Some combines for the MVETrunc truncations legalizer helper. Also lowers the
18677 // node into stack operations after legalizeOps.
PerformMVETruncCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI) const18678 SDValue ARMTargetLowering::PerformMVETruncCombine(
18679     SDNode *N, TargetLowering::DAGCombinerInfo &DCI) const {
18680   SelectionDAG &DAG = DCI.DAG;
18681   EVT VT = N->getValueType(0);
18682   SDLoc DL(N);
18683 
18684   // MVETrunc(Undef, Undef) -> Undef
18685   if (all_of(N->ops(), [](SDValue Op) { return Op.isUndef(); }))
18686     return DAG.getUNDEF(VT);
18687 
18688   // MVETrunc(MVETrunc a b, MVETrunc c, d) -> MVETrunc
18689   if (N->getNumOperands() == 2 &&
18690       N->getOperand(0).getOpcode() == ARMISD::MVETRUNC &&
18691       N->getOperand(1).getOpcode() == ARMISD::MVETRUNC)
18692     return DAG.getNode(ARMISD::MVETRUNC, DL, VT, N->getOperand(0).getOperand(0),
18693                        N->getOperand(0).getOperand(1),
18694                        N->getOperand(1).getOperand(0),
18695                        N->getOperand(1).getOperand(1));
18696 
18697   // MVETrunc(shuffle, shuffle) -> VMOVN
18698   if (N->getNumOperands() == 2 &&
18699       N->getOperand(0).getOpcode() == ISD::VECTOR_SHUFFLE &&
18700       N->getOperand(1).getOpcode() == ISD::VECTOR_SHUFFLE) {
18701     auto *S0 = cast<ShuffleVectorSDNode>(N->getOperand(0).getNode());
18702     auto *S1 = cast<ShuffleVectorSDNode>(N->getOperand(1).getNode());
18703 
18704     if (S0->getOperand(0) == S1->getOperand(0) &&
18705         S0->getOperand(1) == S1->getOperand(1)) {
18706       // Construct complete shuffle mask
18707       SmallVector<int, 8> Mask(S0->getMask());
18708       Mask.append(S1->getMask().begin(), S1->getMask().end());
18709 
18710       if (isVMOVNTruncMask(Mask, VT, false))
18711         return DAG.getNode(
18712             ARMISD::VMOVN, DL, VT,
18713             DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, VT, S0->getOperand(0)),
18714             DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, VT, S0->getOperand(1)),
18715             DAG.getConstant(1, DL, MVT::i32));
18716       if (isVMOVNTruncMask(Mask, VT, true))
18717         return DAG.getNode(
18718             ARMISD::VMOVN, DL, VT,
18719             DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, VT, S0->getOperand(1)),
18720             DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, VT, S0->getOperand(0)),
18721             DAG.getConstant(1, DL, MVT::i32));
18722     }
18723   }
18724 
18725   // For MVETrunc of a buildvector or shuffle, it can be beneficial to lower the
18726   // truncate to a buildvector to allow the generic optimisations to kick in.
18727   if (all_of(N->ops(), [](SDValue Op) {
18728         return Op.getOpcode() == ISD::BUILD_VECTOR ||
18729                Op.getOpcode() == ISD::VECTOR_SHUFFLE ||
18730                (Op.getOpcode() == ISD::BITCAST &&
18731                 Op.getOperand(0).getOpcode() == ISD::BUILD_VECTOR);
18732       })) {
18733     SmallVector<SDValue, 8> Extracts;
18734     for (unsigned Op = 0; Op < N->getNumOperands(); Op++) {
18735       SDValue O = N->getOperand(Op);
18736       for (unsigned i = 0; i < O.getValueType().getVectorNumElements(); i++) {
18737         SDValue Ext = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, O,
18738                                   DAG.getConstant(i, DL, MVT::i32));
18739         Extracts.push_back(Ext);
18740       }
18741     }
18742     return DAG.getBuildVector(VT, DL, Extracts);
18743   }
18744 
18745   // If we are late in the legalization process and nothing has optimised
18746   // the trunc to anything better, lower it to a stack store and reload,
18747   // performing the truncation whilst keeping the lanes in the correct order:
18748   //   VSTRH.32 a, stack; VSTRH.32 b, stack+8; VLDRW.32 stack;
18749   if (!DCI.isAfterLegalizeDAG())
18750     return SDValue();
18751 
18752   SDValue StackPtr = DAG.CreateStackTemporary(TypeSize::getFixed(16), Align(4));
18753   int SPFI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
18754   int NumIns = N->getNumOperands();
18755   assert((NumIns == 2 || NumIns == 4) &&
18756          "Expected 2 or 4 inputs to an MVETrunc");
18757   EVT StoreVT = VT.getHalfNumVectorElementsVT(*DAG.getContext());
18758   if (N->getNumOperands() == 4)
18759     StoreVT = StoreVT.getHalfNumVectorElementsVT(*DAG.getContext());
18760 
18761   SmallVector<SDValue> Chains;
18762   for (int I = 0; I < NumIns; I++) {
18763     SDValue Ptr = DAG.getNode(
18764         ISD::ADD, DL, StackPtr.getValueType(), StackPtr,
18765         DAG.getConstant(I * 16 / NumIns, DL, StackPtr.getValueType()));
18766     MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(
18767         DAG.getMachineFunction(), SPFI, I * 16 / NumIns);
18768     SDValue Ch = DAG.getTruncStore(DAG.getEntryNode(), DL, N->getOperand(I),
18769                                    Ptr, MPI, StoreVT, Align(4));
18770     Chains.push_back(Ch);
18771   }
18772 
18773   SDValue Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
18774   MachinePointerInfo MPI =
18775       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI, 0);
18776   return DAG.getLoad(VT, DL, Chain, StackPtr, MPI, Align(4));
18777 }
18778 
18779 // Take a MVEEXT(load x) and split that into (extload x, extload x+8)
PerformSplittingMVEEXTToWideningLoad(SDNode * N,SelectionDAG & DAG)18780 static SDValue PerformSplittingMVEEXTToWideningLoad(SDNode *N,
18781                                                     SelectionDAG &DAG) {
18782   SDValue N0 = N->getOperand(0);
18783   LoadSDNode *LD = dyn_cast<LoadSDNode>(N0.getNode());
18784   if (!LD || !LD->isSimple() || !N0.hasOneUse() || LD->isIndexed())
18785     return SDValue();
18786 
18787   EVT FromVT = LD->getMemoryVT();
18788   EVT ToVT = N->getValueType(0);
18789   if (!ToVT.isVector())
18790     return SDValue();
18791   assert(FromVT.getVectorNumElements() == ToVT.getVectorNumElements() * 2);
18792   EVT ToEltVT = ToVT.getVectorElementType();
18793   EVT FromEltVT = FromVT.getVectorElementType();
18794 
18795   unsigned NumElements = 0;
18796   if (ToEltVT == MVT::i32 && (FromEltVT == MVT::i16 || FromEltVT == MVT::i8))
18797     NumElements = 4;
18798   if (ToEltVT == MVT::i16 && FromEltVT == MVT::i8)
18799     NumElements = 8;
18800   assert(NumElements != 0);
18801 
18802   ISD::LoadExtType NewExtType =
18803       N->getOpcode() == ARMISD::MVESEXT ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
18804   if (LD->getExtensionType() != ISD::NON_EXTLOAD &&
18805       LD->getExtensionType() != ISD::EXTLOAD &&
18806       LD->getExtensionType() != NewExtType)
18807     return SDValue();
18808 
18809   LLVMContext &C = *DAG.getContext();
18810   SDLoc DL(LD);
18811   // Details about the old load
18812   SDValue Ch = LD->getChain();
18813   SDValue BasePtr = LD->getBasePtr();
18814   Align Alignment = LD->getBaseAlign();
18815   MachineMemOperand::Flags MMOFlags = LD->getMemOperand()->getFlags();
18816   AAMDNodes AAInfo = LD->getAAInfo();
18817 
18818   SDValue Offset = DAG.getUNDEF(BasePtr.getValueType());
18819   EVT NewFromVT = EVT::getVectorVT(
18820       C, EVT::getIntegerVT(C, FromEltVT.getScalarSizeInBits()), NumElements);
18821   EVT NewToVT = EVT::getVectorVT(
18822       C, EVT::getIntegerVT(C, ToEltVT.getScalarSizeInBits()), NumElements);
18823 
18824   SmallVector<SDValue, 4> Loads;
18825   SmallVector<SDValue, 4> Chains;
18826   for (unsigned i = 0; i < FromVT.getVectorNumElements() / NumElements; i++) {
18827     unsigned NewOffset = (i * NewFromVT.getSizeInBits()) / 8;
18828     SDValue NewPtr =
18829         DAG.getObjectPtrOffset(DL, BasePtr, TypeSize::getFixed(NewOffset));
18830 
18831     SDValue NewLoad =
18832         DAG.getLoad(ISD::UNINDEXED, NewExtType, NewToVT, DL, Ch, NewPtr, Offset,
18833                     LD->getPointerInfo().getWithOffset(NewOffset), NewFromVT,
18834                     Alignment, MMOFlags, AAInfo);
18835     Loads.push_back(NewLoad);
18836     Chains.push_back(SDValue(NewLoad.getNode(), 1));
18837   }
18838 
18839   SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
18840   DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewChain);
18841   return DAG.getMergeValues(Loads, DL);
18842 }
18843 
18844 // Perform combines for MVEEXT. If it has not be optimized to anything better
18845 // before lowering, it gets converted to stack store and extloads performing the
18846 // extend whilst still keeping the same lane ordering.
PerformMVEExtCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI) const18847 SDValue ARMTargetLowering::PerformMVEExtCombine(
18848     SDNode *N, TargetLowering::DAGCombinerInfo &DCI) const {
18849   SelectionDAG &DAG = DCI.DAG;
18850   EVT VT = N->getValueType(0);
18851   SDLoc DL(N);
18852   assert(N->getNumValues() == 2 && "Expected MVEEXT with 2 elements");
18853   assert((VT == MVT::v4i32 || VT == MVT::v8i16) && "Unexpected MVEEXT type");
18854 
18855   EVT ExtVT = N->getOperand(0).getValueType().getHalfNumVectorElementsVT(
18856       *DAG.getContext());
18857   auto Extend = [&](SDValue V) {
18858     SDValue VVT = DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, VT, V);
18859     return N->getOpcode() == ARMISD::MVESEXT
18860                ? DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, VVT,
18861                              DAG.getValueType(ExtVT))
18862                : DAG.getZeroExtendInReg(VVT, DL, ExtVT);
18863   };
18864 
18865   // MVEEXT(VDUP) -> SIGN_EXTEND_INREG(VDUP)
18866   if (N->getOperand(0).getOpcode() == ARMISD::VDUP) {
18867     SDValue Ext = Extend(N->getOperand(0));
18868     return DAG.getMergeValues({Ext, Ext}, DL);
18869   }
18870 
18871   // MVEEXT(shuffle) -> SIGN_EXTEND_INREG/ZERO_EXTEND_INREG
18872   if (auto *SVN = dyn_cast<ShuffleVectorSDNode>(N->getOperand(0))) {
18873     ArrayRef<int> Mask = SVN->getMask();
18874     assert(Mask.size() == 2 * VT.getVectorNumElements());
18875     assert(Mask.size() == SVN->getValueType(0).getVectorNumElements());
18876     unsigned Rev = VT == MVT::v4i32 ? ARMISD::VREV32 : ARMISD::VREV16;
18877     SDValue Op0 = SVN->getOperand(0);
18878     SDValue Op1 = SVN->getOperand(1);
18879 
18880     auto CheckInregMask = [&](int Start, int Offset) {
18881       for (int Idx = 0, E = VT.getVectorNumElements(); Idx < E; ++Idx)
18882         if (Mask[Start + Idx] >= 0 && Mask[Start + Idx] != Idx * 2 + Offset)
18883           return false;
18884       return true;
18885     };
18886     SDValue V0 = SDValue(N, 0);
18887     SDValue V1 = SDValue(N, 1);
18888     if (CheckInregMask(0, 0))
18889       V0 = Extend(Op0);
18890     else if (CheckInregMask(0, 1))
18891       V0 = Extend(DAG.getNode(Rev, DL, SVN->getValueType(0), Op0));
18892     else if (CheckInregMask(0, Mask.size()))
18893       V0 = Extend(Op1);
18894     else if (CheckInregMask(0, Mask.size() + 1))
18895       V0 = Extend(DAG.getNode(Rev, DL, SVN->getValueType(0), Op1));
18896 
18897     if (CheckInregMask(VT.getVectorNumElements(), Mask.size()))
18898       V1 = Extend(Op1);
18899     else if (CheckInregMask(VT.getVectorNumElements(), Mask.size() + 1))
18900       V1 = Extend(DAG.getNode(Rev, DL, SVN->getValueType(0), Op1));
18901     else if (CheckInregMask(VT.getVectorNumElements(), 0))
18902       V1 = Extend(Op0);
18903     else if (CheckInregMask(VT.getVectorNumElements(), 1))
18904       V1 = Extend(DAG.getNode(Rev, DL, SVN->getValueType(0), Op0));
18905 
18906     if (V0.getNode() != N || V1.getNode() != N)
18907       return DAG.getMergeValues({V0, V1}, DL);
18908   }
18909 
18910   // MVEEXT(load) -> extload, extload
18911   if (N->getOperand(0)->getOpcode() == ISD::LOAD)
18912     if (SDValue L = PerformSplittingMVEEXTToWideningLoad(N, DAG))
18913       return L;
18914 
18915   if (!DCI.isAfterLegalizeDAG())
18916     return SDValue();
18917 
18918   // Lower to a stack store and reload:
18919   //  VSTRW.32 a, stack; VLDRH.32 stack; VLDRH.32 stack+8;
18920   SDValue StackPtr = DAG.CreateStackTemporary(TypeSize::getFixed(16), Align(4));
18921   int SPFI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
18922   int NumOuts = N->getNumValues();
18923   assert((NumOuts == 2 || NumOuts == 4) &&
18924          "Expected 2 or 4 outputs to an MVEEXT");
18925   EVT LoadVT = N->getOperand(0).getValueType().getHalfNumVectorElementsVT(
18926       *DAG.getContext());
18927   if (N->getNumOperands() == 4)
18928     LoadVT = LoadVT.getHalfNumVectorElementsVT(*DAG.getContext());
18929 
18930   MachinePointerInfo MPI =
18931       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI, 0);
18932   SDValue Chain = DAG.getStore(DAG.getEntryNode(), DL, N->getOperand(0),
18933                                StackPtr, MPI, Align(4));
18934 
18935   SmallVector<SDValue> Loads;
18936   for (int I = 0; I < NumOuts; I++) {
18937     SDValue Ptr = DAG.getNode(
18938         ISD::ADD, DL, StackPtr.getValueType(), StackPtr,
18939         DAG.getConstant(I * 16 / NumOuts, DL, StackPtr.getValueType()));
18940     MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(
18941         DAG.getMachineFunction(), SPFI, I * 16 / NumOuts);
18942     SDValue Load = DAG.getExtLoad(
18943         N->getOpcode() == ARMISD::MVESEXT ? ISD::SEXTLOAD : ISD::ZEXTLOAD, DL,
18944         VT, Chain, Ptr, MPI, LoadVT, Align(4));
18945     Loads.push_back(Load);
18946   }
18947 
18948   return DAG.getMergeValues(Loads, DL);
18949 }
18950 
PerformDAGCombine(SDNode * N,DAGCombinerInfo & DCI) const18951 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
18952                                              DAGCombinerInfo &DCI) const {
18953   switch (N->getOpcode()) {
18954   default: break;
18955   case ISD::SELECT_CC:
18956   case ISD::SELECT:     return PerformSELECTCombine(N, DCI, Subtarget);
18957   case ISD::VSELECT:    return PerformVSELECTCombine(N, DCI, Subtarget);
18958   case ISD::SETCC:      return PerformVSetCCToVCTPCombine(N, DCI, Subtarget);
18959   case ARMISD::ADDE:    return PerformADDECombine(N, DCI, Subtarget);
18960   case ARMISD::UMLAL:   return PerformUMLALCombine(N, DCI.DAG, Subtarget);
18961   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
18962   case ISD::SUB:        return PerformSUBCombine(N, DCI, Subtarget);
18963   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
18964   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
18965   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
18966   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
18967   case ISD::BRCOND:
18968   case ISD::BR_CC:      return PerformHWLoopCombine(N, DCI, Subtarget);
18969   case ARMISD::ADDC:
18970   case ARMISD::SUBC:    return PerformAddcSubcCombine(N, DCI, Subtarget);
18971   case ARMISD::SUBE:    return PerformAddeSubeCombine(N, DCI, Subtarget);
18972   case ARMISD::BFI:     return PerformBFICombine(N, DCI.DAG);
18973   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget);
18974   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
18975   case ARMISD::VMOVhr:  return PerformVMOVhrCombine(N, DCI);
18976   case ARMISD::VMOVrh:  return PerformVMOVrhCombine(N, DCI.DAG);
18977   case ISD::STORE:      return PerformSTORECombine(N, DCI, Subtarget);
18978   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget);
18979   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
18980   case ISD::EXTRACT_VECTOR_ELT:
18981     return PerformExtractEltCombine(N, DCI, Subtarget);
18982   case ISD::SIGN_EXTEND_INREG: return PerformSignExtendInregCombine(N, DCI.DAG);
18983   case ISD::INSERT_SUBVECTOR: return PerformInsertSubvectorCombine(N, DCI);
18984   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
18985   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI, Subtarget);
18986   case ARMISD::VDUP: return PerformVDUPCombine(N, DCI.DAG, Subtarget);
18987   case ISD::FP_TO_SINT:
18988   case ISD::FP_TO_UINT:
18989     return PerformVCVTCombine(N, DCI.DAG, Subtarget);
18990   case ISD::FADD:
18991     return PerformFADDCombine(N, DCI.DAG, Subtarget);
18992   case ISD::FMUL:
18993     return PerformVMulVCTPCombine(N, DCI.DAG, Subtarget);
18994   case ISD::INTRINSIC_WO_CHAIN:
18995     return PerformIntrinsicCombine(N, DCI);
18996   case ISD::SHL:
18997   case ISD::SRA:
18998   case ISD::SRL:
18999     return PerformShiftCombine(N, DCI, Subtarget);
19000   case ISD::SIGN_EXTEND:
19001   case ISD::ZERO_EXTEND:
19002   case ISD::ANY_EXTEND:
19003     return PerformExtendCombine(N, DCI.DAG, Subtarget);
19004   case ISD::FP_EXTEND:
19005     return PerformFPExtendCombine(N, DCI.DAG, Subtarget);
19006   case ISD::SMIN:
19007   case ISD::UMIN:
19008   case ISD::SMAX:
19009   case ISD::UMAX:
19010     return PerformMinMaxCombine(N, DCI.DAG, Subtarget);
19011   case ARMISD::CMOV:
19012     return PerformCMOVCombine(N, DCI.DAG);
19013   case ARMISD::BRCOND:
19014     return PerformBRCONDCombine(N, DCI.DAG);
19015   case ARMISD::CMPZ:
19016     return PerformCMPZCombine(N, DCI.DAG);
19017   case ARMISD::CSINC:
19018   case ARMISD::CSINV:
19019   case ARMISD::CSNEG:
19020     return PerformCSETCombine(N, DCI.DAG);
19021   case ISD::LOAD:
19022     return PerformLOADCombine(N, DCI, Subtarget);
19023   case ARMISD::VLD1DUP:
19024   case ARMISD::VLD2DUP:
19025   case ARMISD::VLD3DUP:
19026   case ARMISD::VLD4DUP:
19027     return PerformVLDCombine(N, DCI);
19028   case ARMISD::BUILD_VECTOR:
19029     return PerformARMBUILD_VECTORCombine(N, DCI);
19030   case ISD::BITCAST:
19031     return PerformBITCASTCombine(N, DCI, Subtarget);
19032   case ARMISD::PREDICATE_CAST:
19033     return PerformPREDICATE_CASTCombine(N, DCI);
19034   case ARMISD::VECTOR_REG_CAST:
19035     return PerformVECTOR_REG_CASTCombine(N, DCI.DAG, Subtarget);
19036   case ARMISD::MVETRUNC:
19037     return PerformMVETruncCombine(N, DCI);
19038   case ARMISD::MVESEXT:
19039   case ARMISD::MVEZEXT:
19040     return PerformMVEExtCombine(N, DCI);
19041   case ARMISD::VCMP:
19042     return PerformVCMPCombine(N, DCI.DAG, Subtarget);
19043   case ISD::VECREDUCE_ADD:
19044     return PerformVECREDUCE_ADDCombine(N, DCI.DAG, Subtarget);
19045   case ARMISD::VADDVs:
19046   case ARMISD::VADDVu:
19047   case ARMISD::VADDLVs:
19048   case ARMISD::VADDLVu:
19049   case ARMISD::VADDLVAs:
19050   case ARMISD::VADDLVAu:
19051   case ARMISD::VMLAVs:
19052   case ARMISD::VMLAVu:
19053   case ARMISD::VMLALVs:
19054   case ARMISD::VMLALVu:
19055   case ARMISD::VMLALVAs:
19056   case ARMISD::VMLALVAu:
19057     return PerformReduceShuffleCombine(N, DCI.DAG);
19058   case ARMISD::VMOVN:
19059     return PerformVMOVNCombine(N, DCI);
19060   case ARMISD::VQMOVNs:
19061   case ARMISD::VQMOVNu:
19062     return PerformVQMOVNCombine(N, DCI);
19063   case ARMISD::VQDMULH:
19064     return PerformVQDMULHCombine(N, DCI);
19065   case ARMISD::ASRL:
19066   case ARMISD::LSRL:
19067   case ARMISD::LSLL:
19068     return PerformLongShiftCombine(N, DCI.DAG);
19069   case ARMISD::SMULWB: {
19070     unsigned BitWidth = N->getValueType(0).getSizeInBits();
19071     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16);
19072     if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))
19073       return SDValue();
19074     break;
19075   }
19076   case ARMISD::SMULWT: {
19077     unsigned BitWidth = N->getValueType(0).getSizeInBits();
19078     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16);
19079     if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))
19080       return SDValue();
19081     break;
19082   }
19083   case ARMISD::SMLALBB:
19084   case ARMISD::QADD16b:
19085   case ARMISD::QSUB16b:
19086   case ARMISD::UQADD16b:
19087   case ARMISD::UQSUB16b: {
19088     unsigned BitWidth = N->getValueType(0).getSizeInBits();
19089     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16);
19090     if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) ||
19091         (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)))
19092       return SDValue();
19093     break;
19094   }
19095   case ARMISD::SMLALBT: {
19096     unsigned LowWidth = N->getOperand(0).getValueType().getSizeInBits();
19097     APInt LowMask = APInt::getLowBitsSet(LowWidth, 16);
19098     unsigned HighWidth = N->getOperand(1).getValueType().getSizeInBits();
19099     APInt HighMask = APInt::getHighBitsSet(HighWidth, 16);
19100     if ((SimplifyDemandedBits(N->getOperand(0), LowMask, DCI)) ||
19101         (SimplifyDemandedBits(N->getOperand(1), HighMask, DCI)))
19102       return SDValue();
19103     break;
19104   }
19105   case ARMISD::SMLALTB: {
19106     unsigned HighWidth = N->getOperand(0).getValueType().getSizeInBits();
19107     APInt HighMask = APInt::getHighBitsSet(HighWidth, 16);
19108     unsigned LowWidth = N->getOperand(1).getValueType().getSizeInBits();
19109     APInt LowMask = APInt::getLowBitsSet(LowWidth, 16);
19110     if ((SimplifyDemandedBits(N->getOperand(0), HighMask, DCI)) ||
19111         (SimplifyDemandedBits(N->getOperand(1), LowMask, DCI)))
19112       return SDValue();
19113     break;
19114   }
19115   case ARMISD::SMLALTT: {
19116     unsigned BitWidth = N->getValueType(0).getSizeInBits();
19117     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16);
19118     if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) ||
19119         (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)))
19120       return SDValue();
19121     break;
19122   }
19123   case ARMISD::QADD8b:
19124   case ARMISD::QSUB8b:
19125   case ARMISD::UQADD8b:
19126   case ARMISD::UQSUB8b: {
19127     unsigned BitWidth = N->getValueType(0).getSizeInBits();
19128     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 8);
19129     if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) ||
19130         (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)))
19131       return SDValue();
19132     break;
19133   }
19134   case ARMISD::VBSP:
19135     if (N->getOperand(1) == N->getOperand(2))
19136       return N->getOperand(1);
19137     return SDValue();
19138   case ISD::INTRINSIC_VOID:
19139   case ISD::INTRINSIC_W_CHAIN:
19140     switch (N->getConstantOperandVal(1)) {
19141     case Intrinsic::arm_neon_vld1:
19142     case Intrinsic::arm_neon_vld1x2:
19143     case Intrinsic::arm_neon_vld1x3:
19144     case Intrinsic::arm_neon_vld1x4:
19145     case Intrinsic::arm_neon_vld2:
19146     case Intrinsic::arm_neon_vld3:
19147     case Intrinsic::arm_neon_vld4:
19148     case Intrinsic::arm_neon_vld2lane:
19149     case Intrinsic::arm_neon_vld3lane:
19150     case Intrinsic::arm_neon_vld4lane:
19151     case Intrinsic::arm_neon_vld2dup:
19152     case Intrinsic::arm_neon_vld3dup:
19153     case Intrinsic::arm_neon_vld4dup:
19154     case Intrinsic::arm_neon_vst1:
19155     case Intrinsic::arm_neon_vst1x2:
19156     case Intrinsic::arm_neon_vst1x3:
19157     case Intrinsic::arm_neon_vst1x4:
19158     case Intrinsic::arm_neon_vst2:
19159     case Intrinsic::arm_neon_vst3:
19160     case Intrinsic::arm_neon_vst4:
19161     case Intrinsic::arm_neon_vst2lane:
19162     case Intrinsic::arm_neon_vst3lane:
19163     case Intrinsic::arm_neon_vst4lane:
19164       return PerformVLDCombine(N, DCI);
19165     case Intrinsic::arm_mve_vld2q:
19166     case Intrinsic::arm_mve_vld4q:
19167     case Intrinsic::arm_mve_vst2q:
19168     case Intrinsic::arm_mve_vst4q:
19169       return PerformMVEVLDCombine(N, DCI);
19170     default: break;
19171     }
19172     break;
19173   }
19174   return SDValue();
19175 }
19176 
isDesirableToTransformToIntegerOp(unsigned Opc,EVT VT) const19177 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
19178                                                           EVT VT) const {
19179   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
19180 }
19181 
allowsMisalignedMemoryAccesses(EVT VT,unsigned,Align Alignment,MachineMemOperand::Flags,unsigned * Fast) const19182 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, unsigned,
19183                                                        Align Alignment,
19184                                                        MachineMemOperand::Flags,
19185                                                        unsigned *Fast) const {
19186   // Depends what it gets converted into if the type is weird.
19187   if (!VT.isSimple())
19188     return false;
19189 
19190   // The AllowsUnaligned flag models the SCTLR.A setting in ARM cpus
19191   bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
19192   auto Ty = VT.getSimpleVT().SimpleTy;
19193 
19194   if (Ty == MVT::i8 || Ty == MVT::i16 || Ty == MVT::i32) {
19195     // Unaligned access can use (for example) LRDB, LRDH, LDR
19196     if (AllowsUnaligned) {
19197       if (Fast)
19198         *Fast = Subtarget->hasV7Ops();
19199       return true;
19200     }
19201   }
19202 
19203   if (Ty == MVT::f64 || Ty == MVT::v2f64) {
19204     // For any little-endian targets with neon, we can support unaligned ld/st
19205     // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
19206     // A big-endian target may also explicitly support unaligned accesses
19207     if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) {
19208       if (Fast)
19209         *Fast = 1;
19210       return true;
19211     }
19212   }
19213 
19214   if (!Subtarget->hasMVEIntegerOps())
19215     return false;
19216 
19217   // These are for predicates
19218   if ((Ty == MVT::v16i1 || Ty == MVT::v8i1 || Ty == MVT::v4i1 ||
19219        Ty == MVT::v2i1)) {
19220     if (Fast)
19221       *Fast = 1;
19222     return true;
19223   }
19224 
19225   // These are for truncated stores/narrowing loads. They are fine so long as
19226   // the alignment is at least the size of the item being loaded
19227   if ((Ty == MVT::v4i8 || Ty == MVT::v8i8 || Ty == MVT::v4i16) &&
19228       Alignment >= VT.getScalarSizeInBits() / 8) {
19229     if (Fast)
19230       *Fast = true;
19231     return true;
19232   }
19233 
19234   // In little-endian MVE, the store instructions VSTRB.U8, VSTRH.U16 and
19235   // VSTRW.U32 all store the vector register in exactly the same format, and
19236   // differ only in the range of their immediate offset field and the required
19237   // alignment. So there is always a store that can be used, regardless of
19238   // actual type.
19239   //
19240   // For big endian, that is not the case. But can still emit a (VSTRB.U8;
19241   // VREV64.8) pair and get the same effect. This will likely be better than
19242   // aligning the vector through the stack.
19243   if (Ty == MVT::v16i8 || Ty == MVT::v8i16 || Ty == MVT::v8f16 ||
19244       Ty == MVT::v4i32 || Ty == MVT::v4f32 || Ty == MVT::v2i64 ||
19245       Ty == MVT::v2f64) {
19246     if (Fast)
19247       *Fast = 1;
19248     return true;
19249   }
19250 
19251   return false;
19252 }
19253 
getOptimalMemOpType(LLVMContext & Context,const MemOp & Op,const AttributeList & FuncAttributes) const19254 EVT ARMTargetLowering::getOptimalMemOpType(
19255     LLVMContext &Context, const MemOp &Op,
19256     const AttributeList &FuncAttributes) const {
19257   // See if we can use NEON instructions for this...
19258   if ((Op.isMemcpy() || Op.isZeroMemset()) && Subtarget->hasNEON() &&
19259       !FuncAttributes.hasFnAttr(Attribute::NoImplicitFloat)) {
19260     unsigned Fast;
19261     if (Op.size() >= 16 &&
19262         (Op.isAligned(Align(16)) ||
19263          (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, Align(1),
19264                                          MachineMemOperand::MONone, &Fast) &&
19265           Fast))) {
19266       return MVT::v2f64;
19267     } else if (Op.size() >= 8 &&
19268                (Op.isAligned(Align(8)) ||
19269                 (allowsMisalignedMemoryAccesses(
19270                      MVT::f64, 0, Align(1), MachineMemOperand::MONone, &Fast) &&
19271                  Fast))) {
19272       return MVT::f64;
19273     }
19274   }
19275 
19276   // Let the target-independent logic figure it out.
19277   return MVT::Other;
19278 }
19279 
19280 // 64-bit integers are split into their high and low parts and held in two
19281 // different registers, so the trunc is free since the low register can just
19282 // be used.
isTruncateFree(Type * SrcTy,Type * DstTy) const19283 bool ARMTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const {
19284   if (!SrcTy->isIntegerTy() || !DstTy->isIntegerTy())
19285     return false;
19286   unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
19287   unsigned DestBits = DstTy->getPrimitiveSizeInBits();
19288   return (SrcBits == 64 && DestBits == 32);
19289 }
19290 
isTruncateFree(EVT SrcVT,EVT DstVT) const19291 bool ARMTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const {
19292   if (SrcVT.isVector() || DstVT.isVector() || !SrcVT.isInteger() ||
19293       !DstVT.isInteger())
19294     return false;
19295   unsigned SrcBits = SrcVT.getSizeInBits();
19296   unsigned DestBits = DstVT.getSizeInBits();
19297   return (SrcBits == 64 && DestBits == 32);
19298 }
19299 
isZExtFree(SDValue Val,EVT VT2) const19300 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
19301   if (Val.getOpcode() != ISD::LOAD)
19302     return false;
19303 
19304   EVT VT1 = Val.getValueType();
19305   if (!VT1.isSimple() || !VT1.isInteger() ||
19306       !VT2.isSimple() || !VT2.isInteger())
19307     return false;
19308 
19309   switch (VT1.getSimpleVT().SimpleTy) {
19310   default: break;
19311   case MVT::i1:
19312   case MVT::i8:
19313   case MVT::i16:
19314     // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
19315     return true;
19316   }
19317 
19318   return false;
19319 }
19320 
isFNegFree(EVT VT) const19321 bool ARMTargetLowering::isFNegFree(EVT VT) const {
19322   if (!VT.isSimple())
19323     return false;
19324 
19325   // There are quite a few FP16 instructions (e.g. VNMLA, VNMLS, etc.) that
19326   // negate values directly (fneg is free). So, we don't want to let the DAG
19327   // combiner rewrite fneg into xors and some other instructions.  For f16 and
19328   // FullFP16 argument passing, some bitcast nodes may be introduced,
19329   // triggering this DAG combine rewrite, so we are avoiding that with this.
19330   switch (VT.getSimpleVT().SimpleTy) {
19331   default: break;
19332   case MVT::f16:
19333     return Subtarget->hasFullFP16();
19334   }
19335 
19336   return false;
19337 }
19338 
shouldConvertSplatType(ShuffleVectorInst * SVI) const19339 Type *ARMTargetLowering::shouldConvertSplatType(ShuffleVectorInst *SVI) const {
19340   if (!Subtarget->hasMVEIntegerOps())
19341     return nullptr;
19342   Type *SVIType = SVI->getType();
19343   Type *ScalarType = SVIType->getScalarType();
19344 
19345   if (ScalarType->isFloatTy())
19346     return Type::getInt32Ty(SVIType->getContext());
19347   if (ScalarType->isHalfTy())
19348     return Type::getInt16Ty(SVIType->getContext());
19349   return nullptr;
19350 }
19351 
isVectorLoadExtDesirable(SDValue ExtVal) const19352 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
19353   EVT VT = ExtVal.getValueType();
19354 
19355   if (!isTypeLegal(VT))
19356     return false;
19357 
19358   if (auto *Ld = dyn_cast<MaskedLoadSDNode>(ExtVal.getOperand(0))) {
19359     if (Ld->isExpandingLoad())
19360       return false;
19361   }
19362 
19363   if (Subtarget->hasMVEIntegerOps())
19364     return true;
19365 
19366   // Don't create a loadext if we can fold the extension into a wide/long
19367   // instruction.
19368   // If there's more than one user instruction, the loadext is desirable no
19369   // matter what.  There can be two uses by the same instruction.
19370   if (ExtVal->use_empty() ||
19371       !ExtVal->user_begin()->isOnlyUserOf(ExtVal.getNode()))
19372     return true;
19373 
19374   SDNode *U = *ExtVal->user_begin();
19375   if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB ||
19376        U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHLIMM))
19377     return false;
19378 
19379   return true;
19380 }
19381 
allowTruncateForTailCall(Type * Ty1,Type * Ty2) const19382 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
19383   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
19384     return false;
19385 
19386   if (!isTypeLegal(EVT::getEVT(Ty1)))
19387     return false;
19388 
19389   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
19390 
19391   // Assuming the caller doesn't have a zeroext or signext return parameter,
19392   // truncation all the way down to i1 is valid.
19393   return true;
19394 }
19395 
19396 /// isFMAFasterThanFMulAndFAdd - Return true if an FMA operation is faster
19397 /// than a pair of fmul and fadd instructions. fmuladd intrinsics will be
19398 /// expanded to FMAs when this method returns true, otherwise fmuladd is
19399 /// expanded to fmul + fadd.
19400 ///
19401 /// ARM supports both fused and unfused multiply-add operations; we already
19402 /// lower a pair of fmul and fadd to the latter so it's not clear that there
19403 /// would be a gain or that the gain would be worthwhile enough to risk
19404 /// correctness bugs.
19405 ///
19406 /// For MVE, we set this to true as it helps simplify the need for some
19407 /// patterns (and we don't have the non-fused floating point instruction).
isFMAFasterThanFMulAndFAdd(const MachineFunction & MF,EVT VT) const19408 bool ARMTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
19409                                                    EVT VT) const {
19410   if (Subtarget->useSoftFloat())
19411     return false;
19412 
19413   if (!VT.isSimple())
19414     return false;
19415 
19416   switch (VT.getSimpleVT().SimpleTy) {
19417   case MVT::v4f32:
19418   case MVT::v8f16:
19419     return Subtarget->hasMVEFloatOps();
19420   case MVT::f16:
19421     return Subtarget->useFPVFMx16();
19422   case MVT::f32:
19423     return Subtarget->useFPVFMx();
19424   case MVT::f64:
19425     return Subtarget->useFPVFMx64();
19426   default:
19427     break;
19428   }
19429 
19430   return false;
19431 }
19432 
isLegalT1AddressImmediate(int64_t V,EVT VT)19433 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
19434   if (V < 0)
19435     return false;
19436 
19437   unsigned Scale = 1;
19438   switch (VT.getSimpleVT().SimpleTy) {
19439   case MVT::i1:
19440   case MVT::i8:
19441     // Scale == 1;
19442     break;
19443   case MVT::i16:
19444     // Scale == 2;
19445     Scale = 2;
19446     break;
19447   default:
19448     // On thumb1 we load most things (i32, i64, floats, etc) with a LDR
19449     // Scale == 4;
19450     Scale = 4;
19451     break;
19452   }
19453 
19454   if ((V & (Scale - 1)) != 0)
19455     return false;
19456   return isUInt<5>(V / Scale);
19457 }
19458 
isLegalT2AddressImmediate(int64_t V,EVT VT,const ARMSubtarget * Subtarget)19459 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
19460                                       const ARMSubtarget *Subtarget) {
19461   if (!VT.isInteger() && !VT.isFloatingPoint())
19462     return false;
19463   if (VT.isVector() && Subtarget->hasNEON())
19464     return false;
19465   if (VT.isVector() && VT.isFloatingPoint() && Subtarget->hasMVEIntegerOps() &&
19466       !Subtarget->hasMVEFloatOps())
19467     return false;
19468 
19469   bool IsNeg = false;
19470   if (V < 0) {
19471     IsNeg = true;
19472     V = -V;
19473   }
19474 
19475   unsigned NumBytes = std::max((unsigned)VT.getSizeInBits() / 8, 1U);
19476 
19477   // MVE: size * imm7
19478   if (VT.isVector() && Subtarget->hasMVEIntegerOps()) {
19479     switch (VT.getSimpleVT().getVectorElementType().SimpleTy) {
19480     case MVT::i32:
19481     case MVT::f32:
19482       return isShiftedUInt<7,2>(V);
19483     case MVT::i16:
19484     case MVT::f16:
19485       return isShiftedUInt<7,1>(V);
19486     case MVT::i8:
19487       return isUInt<7>(V);
19488     default:
19489       return false;
19490     }
19491   }
19492 
19493   // half VLDR: 2 * imm8
19494   if (VT.isFloatingPoint() && NumBytes == 2 && Subtarget->hasFPRegs16())
19495     return isShiftedUInt<8, 1>(V);
19496   // VLDR and LDRD: 4 * imm8
19497   if ((VT.isFloatingPoint() && Subtarget->hasVFP2Base()) || NumBytes == 8)
19498     return isShiftedUInt<8, 2>(V);
19499 
19500   if (NumBytes == 1 || NumBytes == 2 || NumBytes == 4) {
19501     // + imm12 or - imm8
19502     if (IsNeg)
19503       return isUInt<8>(V);
19504     return isUInt<12>(V);
19505   }
19506 
19507   return false;
19508 }
19509 
19510 /// isLegalAddressImmediate - Return true if the integer value can be used
19511 /// as the offset of the target addressing mode for load / store of the
19512 /// given type.
isLegalAddressImmediate(int64_t V,EVT VT,const ARMSubtarget * Subtarget)19513 static bool isLegalAddressImmediate(int64_t V, EVT VT,
19514                                     const ARMSubtarget *Subtarget) {
19515   if (V == 0)
19516     return true;
19517 
19518   if (!VT.isSimple())
19519     return false;
19520 
19521   if (Subtarget->isThumb1Only())
19522     return isLegalT1AddressImmediate(V, VT);
19523   else if (Subtarget->isThumb2())
19524     return isLegalT2AddressImmediate(V, VT, Subtarget);
19525 
19526   // ARM mode.
19527   if (V < 0)
19528     V = - V;
19529   switch (VT.getSimpleVT().SimpleTy) {
19530   default: return false;
19531   case MVT::i1:
19532   case MVT::i8:
19533   case MVT::i32:
19534     // +- imm12
19535     return isUInt<12>(V);
19536   case MVT::i16:
19537     // +- imm8
19538     return isUInt<8>(V);
19539   case MVT::f32:
19540   case MVT::f64:
19541     if (!Subtarget->hasVFP2Base()) // FIXME: NEON?
19542       return false;
19543     return isShiftedUInt<8, 2>(V);
19544   }
19545 }
19546 
isLegalT2ScaledAddressingMode(const AddrMode & AM,EVT VT) const19547 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
19548                                                       EVT VT) const {
19549   int Scale = AM.Scale;
19550   if (Scale < 0)
19551     return false;
19552 
19553   switch (VT.getSimpleVT().SimpleTy) {
19554   default: return false;
19555   case MVT::i1:
19556   case MVT::i8:
19557   case MVT::i16:
19558   case MVT::i32:
19559     if (Scale == 1)
19560       return true;
19561     // r + r << imm
19562     Scale = Scale & ~1;
19563     return Scale == 2 || Scale == 4 || Scale == 8;
19564   case MVT::i64:
19565     // FIXME: What are we trying to model here? ldrd doesn't have an r + r
19566     // version in Thumb mode.
19567     // r + r
19568     if (Scale == 1)
19569       return true;
19570     // r * 2 (this can be lowered to r + r).
19571     if (!AM.HasBaseReg && Scale == 2)
19572       return true;
19573     return false;
19574   case MVT::isVoid:
19575     // Note, we allow "void" uses (basically, uses that aren't loads or
19576     // stores), because arm allows folding a scale into many arithmetic
19577     // operations.  This should be made more precise and revisited later.
19578 
19579     // Allow r << imm, but the imm has to be a multiple of two.
19580     if (Scale & 1) return false;
19581     return isPowerOf2_32(Scale);
19582   }
19583 }
19584 
isLegalT1ScaledAddressingMode(const AddrMode & AM,EVT VT) const19585 bool ARMTargetLowering::isLegalT1ScaledAddressingMode(const AddrMode &AM,
19586                                                       EVT VT) const {
19587   const int Scale = AM.Scale;
19588 
19589   // Negative scales are not supported in Thumb1.
19590   if (Scale < 0)
19591     return false;
19592 
19593   // Thumb1 addressing modes do not support register scaling excepting the
19594   // following cases:
19595   // 1. Scale == 1 means no scaling.
19596   // 2. Scale == 2 this can be lowered to r + r if there is no base register.
19597   return (Scale == 1) || (!AM.HasBaseReg && Scale == 2);
19598 }
19599 
19600 /// isLegalAddressingMode - Return true if the addressing mode represented
19601 /// by AM is legal for this target, for a load/store of the specified type.
isLegalAddressingMode(const DataLayout & DL,const AddrMode & AM,Type * Ty,unsigned AS,Instruction * I) const19602 bool ARMTargetLowering::isLegalAddressingMode(const DataLayout &DL,
19603                                               const AddrMode &AM, Type *Ty,
19604                                               unsigned AS, Instruction *I) const {
19605   EVT VT = getValueType(DL, Ty, true);
19606   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
19607     return false;
19608 
19609   // Can never fold addr of global into load/store.
19610   if (AM.BaseGV)
19611     return false;
19612 
19613   switch (AM.Scale) {
19614   case 0:  // no scale reg, must be "r+i" or "r", or "i".
19615     break;
19616   default:
19617     // ARM doesn't support any R+R*scale+imm addr modes.
19618     if (AM.BaseOffs)
19619       return false;
19620 
19621     if (!VT.isSimple())
19622       return false;
19623 
19624     if (Subtarget->isThumb1Only())
19625       return isLegalT1ScaledAddressingMode(AM, VT);
19626 
19627     if (Subtarget->isThumb2())
19628       return isLegalT2ScaledAddressingMode(AM, VT);
19629 
19630     int Scale = AM.Scale;
19631     switch (VT.getSimpleVT().SimpleTy) {
19632     default: return false;
19633     case MVT::i1:
19634     case MVT::i8:
19635     case MVT::i32:
19636       if (Scale < 0) Scale = -Scale;
19637       if (Scale == 1)
19638         return true;
19639       // r + r << imm
19640       return isPowerOf2_32(Scale & ~1);
19641     case MVT::i16:
19642     case MVT::i64:
19643       // r +/- r
19644       if (Scale == 1 || (AM.HasBaseReg && Scale == -1))
19645         return true;
19646       // r * 2 (this can be lowered to r + r).
19647       if (!AM.HasBaseReg && Scale == 2)
19648         return true;
19649       return false;
19650 
19651     case MVT::isVoid:
19652       // Note, we allow "void" uses (basically, uses that aren't loads or
19653       // stores), because arm allows folding a scale into many arithmetic
19654       // operations.  This should be made more precise and revisited later.
19655 
19656       // Allow r << imm, but the imm has to be a multiple of two.
19657       if (Scale & 1) return false;
19658       return isPowerOf2_32(Scale);
19659     }
19660   }
19661   return true;
19662 }
19663 
19664 /// isLegalICmpImmediate - Return true if the specified immediate is legal
19665 /// icmp immediate, that is the target has icmp instructions which can compare
19666 /// a register against the immediate without having to materialize the
19667 /// immediate into a register.
isLegalICmpImmediate(int64_t Imm) const19668 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
19669   // Thumb2 and ARM modes can use cmn for negative immediates.
19670   if (!Subtarget->isThumb())
19671     return ARM_AM::getSOImmVal((uint32_t)Imm) != -1 ||
19672            ARM_AM::getSOImmVal(-(uint32_t)Imm) != -1;
19673   if (Subtarget->isThumb2())
19674     return ARM_AM::getT2SOImmVal((uint32_t)Imm) != -1 ||
19675            ARM_AM::getT2SOImmVal(-(uint32_t)Imm) != -1;
19676   // Thumb1 doesn't have cmn, and only 8-bit immediates.
19677   return Imm >= 0 && Imm <= 255;
19678 }
19679 
19680 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
19681 /// *or sub* immediate, that is the target has add or sub instructions which can
19682 /// add a register with the immediate without having to materialize the
19683 /// immediate into a register.
isLegalAddImmediate(int64_t Imm) const19684 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
19685   // Same encoding for add/sub, just flip the sign.
19686   uint64_t AbsImm = AbsoluteValue(Imm);
19687   if (!Subtarget->isThumb())
19688     return ARM_AM::getSOImmVal(AbsImm) != -1;
19689   if (Subtarget->isThumb2())
19690     return ARM_AM::getT2SOImmVal(AbsImm) != -1;
19691   // Thumb1 only has 8-bit unsigned immediate.
19692   return AbsImm <= 255;
19693 }
19694 
19695 // Return false to prevent folding
19696 // (mul (add r, c0), c1) -> (add (mul r, c1), c0*c1) in DAGCombine,
19697 // if the folding leads to worse code.
isMulAddWithConstProfitable(SDValue AddNode,SDValue ConstNode) const19698 bool ARMTargetLowering::isMulAddWithConstProfitable(SDValue AddNode,
19699                                                     SDValue ConstNode) const {
19700   // Let the DAGCombiner decide for vector types and large types.
19701   const EVT VT = AddNode.getValueType();
19702   if (VT.isVector() || VT.getScalarSizeInBits() > 32)
19703     return true;
19704 
19705   // It is worse if c0 is legal add immediate, while c1*c0 is not
19706   // and has to be composed by at least two instructions.
19707   const ConstantSDNode *C0Node = cast<ConstantSDNode>(AddNode.getOperand(1));
19708   const ConstantSDNode *C1Node = cast<ConstantSDNode>(ConstNode);
19709   const int64_t C0 = C0Node->getSExtValue();
19710   APInt CA = C0Node->getAPIntValue() * C1Node->getAPIntValue();
19711   if (!isLegalAddImmediate(C0) || isLegalAddImmediate(CA.getSExtValue()))
19712     return true;
19713   if (ConstantMaterializationCost((unsigned)CA.getZExtValue(), Subtarget) > 1)
19714     return false;
19715 
19716   // Default to true and let the DAGCombiner decide.
19717   return true;
19718 }
19719 
getARMIndexedAddressParts(SDNode * Ptr,EVT VT,bool isSEXTLoad,SDValue & Base,SDValue & Offset,bool & isInc,SelectionDAG & DAG)19720 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
19721                                       bool isSEXTLoad, SDValue &Base,
19722                                       SDValue &Offset, bool &isInc,
19723                                       SelectionDAG &DAG) {
19724   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
19725     return false;
19726 
19727   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
19728     // AddressingMode 3
19729     Base = Ptr->getOperand(0);
19730     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
19731       int RHSC = (int)RHS->getZExtValue();
19732       if (RHSC < 0 && RHSC > -256) {
19733         assert(Ptr->getOpcode() == ISD::ADD);
19734         isInc = false;
19735         Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
19736         return true;
19737       }
19738     }
19739     isInc = (Ptr->getOpcode() == ISD::ADD);
19740     Offset = Ptr->getOperand(1);
19741     return true;
19742   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
19743     // AddressingMode 2
19744     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
19745       int RHSC = (int)RHS->getZExtValue();
19746       if (RHSC < 0 && RHSC > -0x1000) {
19747         assert(Ptr->getOpcode() == ISD::ADD);
19748         isInc = false;
19749         Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
19750         Base = Ptr->getOperand(0);
19751         return true;
19752       }
19753     }
19754 
19755     if (Ptr->getOpcode() == ISD::ADD) {
19756       isInc = true;
19757       ARM_AM::ShiftOpc ShOpcVal=
19758         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
19759       if (ShOpcVal != ARM_AM::no_shift) {
19760         Base = Ptr->getOperand(1);
19761         Offset = Ptr->getOperand(0);
19762       } else {
19763         Base = Ptr->getOperand(0);
19764         Offset = Ptr->getOperand(1);
19765       }
19766       return true;
19767     }
19768 
19769     isInc = (Ptr->getOpcode() == ISD::ADD);
19770     Base = Ptr->getOperand(0);
19771     Offset = Ptr->getOperand(1);
19772     return true;
19773   }
19774 
19775   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
19776   return false;
19777 }
19778 
getT2IndexedAddressParts(SDNode * Ptr,EVT VT,bool isSEXTLoad,SDValue & Base,SDValue & Offset,bool & isInc,SelectionDAG & DAG)19779 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
19780                                      bool isSEXTLoad, SDValue &Base,
19781                                      SDValue &Offset, bool &isInc,
19782                                      SelectionDAG &DAG) {
19783   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
19784     return false;
19785 
19786   Base = Ptr->getOperand(0);
19787   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
19788     int RHSC = (int)RHS->getZExtValue();
19789     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
19790       assert(Ptr->getOpcode() == ISD::ADD);
19791       isInc = false;
19792       Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
19793       return true;
19794     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
19795       isInc = Ptr->getOpcode() == ISD::ADD;
19796       Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0));
19797       return true;
19798     }
19799   }
19800 
19801   return false;
19802 }
19803 
getMVEIndexedAddressParts(SDNode * Ptr,EVT VT,Align Alignment,bool isSEXTLoad,bool IsMasked,bool isLE,SDValue & Base,SDValue & Offset,bool & isInc,SelectionDAG & DAG)19804 static bool getMVEIndexedAddressParts(SDNode *Ptr, EVT VT, Align Alignment,
19805                                       bool isSEXTLoad, bool IsMasked, bool isLE,
19806                                       SDValue &Base, SDValue &Offset,
19807                                       bool &isInc, SelectionDAG &DAG) {
19808   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
19809     return false;
19810   if (!isa<ConstantSDNode>(Ptr->getOperand(1)))
19811     return false;
19812 
19813   // We allow LE non-masked loads to change the type (for example use a vldrb.8
19814   // as opposed to a vldrw.32). This can allow extra addressing modes or
19815   // alignments for what is otherwise an equivalent instruction.
19816   bool CanChangeType = isLE && !IsMasked;
19817 
19818   ConstantSDNode *RHS = cast<ConstantSDNode>(Ptr->getOperand(1));
19819   int RHSC = (int)RHS->getZExtValue();
19820 
19821   auto IsInRange = [&](int RHSC, int Limit, int Scale) {
19822     if (RHSC < 0 && RHSC > -Limit * Scale && RHSC % Scale == 0) {
19823       assert(Ptr->getOpcode() == ISD::ADD);
19824       isInc = false;
19825       Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
19826       return true;
19827     } else if (RHSC > 0 && RHSC < Limit * Scale && RHSC % Scale == 0) {
19828       isInc = Ptr->getOpcode() == ISD::ADD;
19829       Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0));
19830       return true;
19831     }
19832     return false;
19833   };
19834 
19835   // Try to find a matching instruction based on s/zext, Alignment, Offset and
19836   // (in BE/masked) type.
19837   Base = Ptr->getOperand(0);
19838   if (VT == MVT::v4i16) {
19839     if (Alignment >= 2 && IsInRange(RHSC, 0x80, 2))
19840       return true;
19841   } else if (VT == MVT::v4i8 || VT == MVT::v8i8) {
19842     if (IsInRange(RHSC, 0x80, 1))
19843       return true;
19844   } else if (Alignment >= 4 &&
19845              (CanChangeType || VT == MVT::v4i32 || VT == MVT::v4f32) &&
19846              IsInRange(RHSC, 0x80, 4))
19847     return true;
19848   else if (Alignment >= 2 &&
19849            (CanChangeType || VT == MVT::v8i16 || VT == MVT::v8f16) &&
19850            IsInRange(RHSC, 0x80, 2))
19851     return true;
19852   else if ((CanChangeType || VT == MVT::v16i8) && IsInRange(RHSC, 0x80, 1))
19853     return true;
19854   return false;
19855 }
19856 
19857 /// getPreIndexedAddressParts - returns true by value, base pointer and
19858 /// offset pointer and addressing mode by reference if the node's address
19859 /// can be legally represented as pre-indexed load / store address.
19860 bool
getPreIndexedAddressParts(SDNode * N,SDValue & Base,SDValue & Offset,ISD::MemIndexedMode & AM,SelectionDAG & DAG) const19861 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
19862                                              SDValue &Offset,
19863                                              ISD::MemIndexedMode &AM,
19864                                              SelectionDAG &DAG) const {
19865   if (Subtarget->isThumb1Only())
19866     return false;
19867 
19868   EVT VT;
19869   SDValue Ptr;
19870   Align Alignment;
19871   bool isSEXTLoad = false;
19872   bool IsMasked = false;
19873   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
19874     Ptr = LD->getBasePtr();
19875     VT = LD->getMemoryVT();
19876     Alignment = LD->getAlign();
19877     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
19878   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
19879     Ptr = ST->getBasePtr();
19880     VT = ST->getMemoryVT();
19881     Alignment = ST->getAlign();
19882   } else if (MaskedLoadSDNode *LD = dyn_cast<MaskedLoadSDNode>(N)) {
19883     Ptr = LD->getBasePtr();
19884     VT = LD->getMemoryVT();
19885     Alignment = LD->getAlign();
19886     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
19887     IsMasked = true;
19888   } else if (MaskedStoreSDNode *ST = dyn_cast<MaskedStoreSDNode>(N)) {
19889     Ptr = ST->getBasePtr();
19890     VT = ST->getMemoryVT();
19891     Alignment = ST->getAlign();
19892     IsMasked = true;
19893   } else
19894     return false;
19895 
19896   bool isInc;
19897   bool isLegal = false;
19898   if (VT.isVector())
19899     isLegal = Subtarget->hasMVEIntegerOps() &&
19900               getMVEIndexedAddressParts(
19901                   Ptr.getNode(), VT, Alignment, isSEXTLoad, IsMasked,
19902                   Subtarget->isLittle(), Base, Offset, isInc, DAG);
19903   else {
19904     if (Subtarget->isThumb2())
19905       isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
19906                                          Offset, isInc, DAG);
19907     else
19908       isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
19909                                           Offset, isInc, DAG);
19910   }
19911   if (!isLegal)
19912     return false;
19913 
19914   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
19915   return true;
19916 }
19917 
19918 /// getPostIndexedAddressParts - returns true by value, base pointer and
19919 /// offset pointer and addressing mode by reference if this node can be
19920 /// combined with a load / store to form a post-indexed load / store.
getPostIndexedAddressParts(SDNode * N,SDNode * Op,SDValue & Base,SDValue & Offset,ISD::MemIndexedMode & AM,SelectionDAG & DAG) const19921 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
19922                                                    SDValue &Base,
19923                                                    SDValue &Offset,
19924                                                    ISD::MemIndexedMode &AM,
19925                                                    SelectionDAG &DAG) const {
19926   EVT VT;
19927   SDValue Ptr;
19928   Align Alignment;
19929   bool isSEXTLoad = false, isNonExt;
19930   bool IsMasked = false;
19931   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
19932     VT = LD->getMemoryVT();
19933     Ptr = LD->getBasePtr();
19934     Alignment = LD->getAlign();
19935     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
19936     isNonExt = LD->getExtensionType() == ISD::NON_EXTLOAD;
19937   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
19938     VT = ST->getMemoryVT();
19939     Ptr = ST->getBasePtr();
19940     Alignment = ST->getAlign();
19941     isNonExt = !ST->isTruncatingStore();
19942   } else if (MaskedLoadSDNode *LD = dyn_cast<MaskedLoadSDNode>(N)) {
19943     VT = LD->getMemoryVT();
19944     Ptr = LD->getBasePtr();
19945     Alignment = LD->getAlign();
19946     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
19947     isNonExt = LD->getExtensionType() == ISD::NON_EXTLOAD;
19948     IsMasked = true;
19949   } else if (MaskedStoreSDNode *ST = dyn_cast<MaskedStoreSDNode>(N)) {
19950     VT = ST->getMemoryVT();
19951     Ptr = ST->getBasePtr();
19952     Alignment = ST->getAlign();
19953     isNonExt = !ST->isTruncatingStore();
19954     IsMasked = true;
19955   } else
19956     return false;
19957 
19958   if (Subtarget->isThumb1Only()) {
19959     // Thumb-1 can do a limited post-inc load or store as an updating LDM. It
19960     // must be non-extending/truncating, i32, with an offset of 4.
19961     assert(Op->getValueType(0) == MVT::i32 && "Non-i32 post-inc op?!");
19962     if (Op->getOpcode() != ISD::ADD || !isNonExt)
19963       return false;
19964     auto *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1));
19965     if (!RHS || RHS->getZExtValue() != 4)
19966       return false;
19967     if (Alignment < Align(4))
19968       return false;
19969 
19970     Offset = Op->getOperand(1);
19971     Base = Op->getOperand(0);
19972     AM = ISD::POST_INC;
19973     return true;
19974   }
19975 
19976   bool isInc;
19977   bool isLegal = false;
19978   if (VT.isVector())
19979     isLegal = Subtarget->hasMVEIntegerOps() &&
19980               getMVEIndexedAddressParts(Op, VT, Alignment, isSEXTLoad, IsMasked,
19981                                         Subtarget->isLittle(), Base, Offset,
19982                                         isInc, DAG);
19983   else {
19984     if (Subtarget->isThumb2())
19985       isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
19986                                          isInc, DAG);
19987     else
19988       isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
19989                                           isInc, DAG);
19990   }
19991   if (!isLegal)
19992     return false;
19993 
19994   if (Ptr != Base) {
19995     // Swap base ptr and offset to catch more post-index load / store when
19996     // it's legal. In Thumb2 mode, offset must be an immediate.
19997     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
19998         !Subtarget->isThumb2())
19999       std::swap(Base, Offset);
20000 
20001     // Post-indexed load / store update the base pointer.
20002     if (Ptr != Base)
20003       return false;
20004   }
20005 
20006   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
20007   return true;
20008 }
20009 
computeKnownBitsForTargetNode(const SDValue Op,KnownBits & Known,const APInt & DemandedElts,const SelectionDAG & DAG,unsigned Depth) const20010 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
20011                                                       KnownBits &Known,
20012                                                       const APInt &DemandedElts,
20013                                                       const SelectionDAG &DAG,
20014                                                       unsigned Depth) const {
20015   unsigned BitWidth = Known.getBitWidth();
20016   Known.resetAll();
20017   switch (Op.getOpcode()) {
20018   default: break;
20019   case ARMISD::ADDC:
20020   case ARMISD::ADDE:
20021   case ARMISD::SUBC:
20022   case ARMISD::SUBE:
20023     // Special cases when we convert a carry to a boolean.
20024     if (Op.getResNo() == 0) {
20025       SDValue LHS = Op.getOperand(0);
20026       SDValue RHS = Op.getOperand(1);
20027       // (ADDE 0, 0, C) will give us a single bit.
20028       if (Op->getOpcode() == ARMISD::ADDE && isNullConstant(LHS) &&
20029           isNullConstant(RHS)) {
20030         Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
20031         return;
20032       }
20033     }
20034     break;
20035   case ARMISD::CMOV: {
20036     // Bits are known zero/one if known on the LHS and RHS.
20037     Known = DAG.computeKnownBits(Op.getOperand(0), Depth+1);
20038     if (Known.isUnknown())
20039       return;
20040 
20041     KnownBits KnownRHS = DAG.computeKnownBits(Op.getOperand(1), Depth+1);
20042     Known = Known.intersectWith(KnownRHS);
20043     return;
20044   }
20045   case ISD::INTRINSIC_W_CHAIN: {
20046     Intrinsic::ID IntID =
20047         static_cast<Intrinsic::ID>(Op->getConstantOperandVal(1));
20048     switch (IntID) {
20049     default: return;
20050     case Intrinsic::arm_ldaex:
20051     case Intrinsic::arm_ldrex: {
20052       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
20053       unsigned MemBits = VT.getScalarSizeInBits();
20054       Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
20055       return;
20056     }
20057     }
20058   }
20059   case ARMISD::BFI: {
20060     // Conservatively, we can recurse down the first operand
20061     // and just mask out all affected bits.
20062     Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
20063 
20064     // The operand to BFI is already a mask suitable for removing the bits it
20065     // sets.
20066     const APInt &Mask = Op.getConstantOperandAPInt(2);
20067     Known.Zero &= Mask;
20068     Known.One &= Mask;
20069     return;
20070   }
20071   case ARMISD::VGETLANEs:
20072   case ARMISD::VGETLANEu: {
20073     const SDValue &SrcSV = Op.getOperand(0);
20074     EVT VecVT = SrcSV.getValueType();
20075     assert(VecVT.isVector() && "VGETLANE expected a vector type");
20076     const unsigned NumSrcElts = VecVT.getVectorNumElements();
20077     ConstantSDNode *Pos = cast<ConstantSDNode>(Op.getOperand(1).getNode());
20078     assert(Pos->getAPIntValue().ult(NumSrcElts) &&
20079            "VGETLANE index out of bounds");
20080     unsigned Idx = Pos->getZExtValue();
20081     APInt DemandedElt = APInt::getOneBitSet(NumSrcElts, Idx);
20082     Known = DAG.computeKnownBits(SrcSV, DemandedElt, Depth + 1);
20083 
20084     EVT VT = Op.getValueType();
20085     const unsigned DstSz = VT.getScalarSizeInBits();
20086     const unsigned SrcSz = VecVT.getVectorElementType().getSizeInBits();
20087     (void)SrcSz;
20088     assert(SrcSz == Known.getBitWidth());
20089     assert(DstSz > SrcSz);
20090     if (Op.getOpcode() == ARMISD::VGETLANEs)
20091       Known = Known.sext(DstSz);
20092     else {
20093       Known = Known.zext(DstSz);
20094     }
20095     assert(DstSz == Known.getBitWidth());
20096     break;
20097   }
20098   case ARMISD::VMOVrh: {
20099     KnownBits KnownOp = DAG.computeKnownBits(Op->getOperand(0), Depth + 1);
20100     assert(KnownOp.getBitWidth() == 16);
20101     Known = KnownOp.zext(32);
20102     break;
20103   }
20104   case ARMISD::CSINC:
20105   case ARMISD::CSINV:
20106   case ARMISD::CSNEG: {
20107     KnownBits KnownOp0 = DAG.computeKnownBits(Op->getOperand(0), Depth + 1);
20108     KnownBits KnownOp1 = DAG.computeKnownBits(Op->getOperand(1), Depth + 1);
20109 
20110     // The result is either:
20111     // CSINC: KnownOp0 or KnownOp1 + 1
20112     // CSINV: KnownOp0 or ~KnownOp1
20113     // CSNEG: KnownOp0 or KnownOp1 * -1
20114     if (Op.getOpcode() == ARMISD::CSINC)
20115       KnownOp1 =
20116           KnownBits::add(KnownOp1, KnownBits::makeConstant(APInt(32, 1)));
20117     else if (Op.getOpcode() == ARMISD::CSINV)
20118       std::swap(KnownOp1.Zero, KnownOp1.One);
20119     else if (Op.getOpcode() == ARMISD::CSNEG)
20120       KnownOp1 = KnownBits::mul(KnownOp1,
20121                                 KnownBits::makeConstant(APInt::getAllOnes(32)));
20122 
20123     Known = KnownOp0.intersectWith(KnownOp1);
20124     break;
20125   }
20126   }
20127 }
20128 
targetShrinkDemandedConstant(SDValue Op,const APInt & DemandedBits,const APInt & DemandedElts,TargetLoweringOpt & TLO) const20129 bool ARMTargetLowering::targetShrinkDemandedConstant(
20130     SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
20131     TargetLoweringOpt &TLO) const {
20132   // Delay optimization, so we don't have to deal with illegal types, or block
20133   // optimizations.
20134   if (!TLO.LegalOps)
20135     return false;
20136 
20137   // Only optimize AND for now.
20138   if (Op.getOpcode() != ISD::AND)
20139     return false;
20140 
20141   EVT VT = Op.getValueType();
20142 
20143   // Ignore vectors.
20144   if (VT.isVector())
20145     return false;
20146 
20147   assert(VT == MVT::i32 && "Unexpected integer type");
20148 
20149   // Make sure the RHS really is a constant.
20150   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
20151   if (!C)
20152     return false;
20153 
20154   unsigned Mask = C->getZExtValue();
20155 
20156   unsigned Demanded = DemandedBits.getZExtValue();
20157   unsigned ShrunkMask = Mask & Demanded;
20158   unsigned ExpandedMask = Mask | ~Demanded;
20159 
20160   // If the mask is all zeros, let the target-independent code replace the
20161   // result with zero.
20162   if (ShrunkMask == 0)
20163     return false;
20164 
20165   // If the mask is all ones, erase the AND. (Currently, the target-independent
20166   // code won't do this, so we have to do it explicitly to avoid an infinite
20167   // loop in obscure cases.)
20168   if (ExpandedMask == ~0U)
20169     return TLO.CombineTo(Op, Op.getOperand(0));
20170 
20171   auto IsLegalMask = [ShrunkMask, ExpandedMask](unsigned Mask) -> bool {
20172     return (ShrunkMask & Mask) == ShrunkMask && (~ExpandedMask & Mask) == 0;
20173   };
20174   auto UseMask = [Mask, Op, VT, &TLO](unsigned NewMask) -> bool {
20175     if (NewMask == Mask)
20176       return true;
20177     SDLoc DL(Op);
20178     SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT);
20179     SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC);
20180     return TLO.CombineTo(Op, NewOp);
20181   };
20182 
20183   // Prefer uxtb mask.
20184   if (IsLegalMask(0xFF))
20185     return UseMask(0xFF);
20186 
20187   // Prefer uxth mask.
20188   if (IsLegalMask(0xFFFF))
20189     return UseMask(0xFFFF);
20190 
20191   // [1, 255] is Thumb1 movs+ands, legal immediate for ARM/Thumb2.
20192   // FIXME: Prefer a contiguous sequence of bits for other optimizations.
20193   if (ShrunkMask < 256)
20194     return UseMask(ShrunkMask);
20195 
20196   // [-256, -2] is Thumb1 movs+bics, legal immediate for ARM/Thumb2.
20197   // FIXME: Prefer a contiguous sequence of bits for other optimizations.
20198   if ((int)ExpandedMask <= -2 && (int)ExpandedMask >= -256)
20199     return UseMask(ExpandedMask);
20200 
20201   // Potential improvements:
20202   //
20203   // We could try to recognize lsls+lsrs or lsrs+lsls pairs here.
20204   // We could try to prefer Thumb1 immediates which can be lowered to a
20205   // two-instruction sequence.
20206   // We could try to recognize more legal ARM/Thumb2 immediates here.
20207 
20208   return false;
20209 }
20210 
SimplifyDemandedBitsForTargetNode(SDValue Op,const APInt & OriginalDemandedBits,const APInt & OriginalDemandedElts,KnownBits & Known,TargetLoweringOpt & TLO,unsigned Depth) const20211 bool ARMTargetLowering::SimplifyDemandedBitsForTargetNode(
20212     SDValue Op, const APInt &OriginalDemandedBits,
20213     const APInt &OriginalDemandedElts, KnownBits &Known, TargetLoweringOpt &TLO,
20214     unsigned Depth) const {
20215   unsigned Opc = Op.getOpcode();
20216 
20217   switch (Opc) {
20218   case ARMISD::ASRL:
20219   case ARMISD::LSRL: {
20220     // If this is result 0 and the other result is unused, see if the demand
20221     // bits allow us to shrink this long shift into a standard small shift in
20222     // the opposite direction.
20223     if (Op.getResNo() == 0 && !Op->hasAnyUseOfValue(1) &&
20224         isa<ConstantSDNode>(Op->getOperand(2))) {
20225       unsigned ShAmt = Op->getConstantOperandVal(2);
20226       if (ShAmt < 32 && OriginalDemandedBits.isSubsetOf(APInt::getAllOnes(32)
20227                                                         << (32 - ShAmt)))
20228         return TLO.CombineTo(
20229             Op, TLO.DAG.getNode(
20230                     ISD::SHL, SDLoc(Op), MVT::i32, Op.getOperand(1),
20231                     TLO.DAG.getConstant(32 - ShAmt, SDLoc(Op), MVT::i32)));
20232     }
20233     break;
20234   }
20235   case ARMISD::VBICIMM: {
20236     SDValue Op0 = Op.getOperand(0);
20237     unsigned ModImm = Op.getConstantOperandVal(1);
20238     unsigned EltBits = 0;
20239     uint64_t Mask = ARM_AM::decodeVMOVModImm(ModImm, EltBits);
20240     if ((OriginalDemandedBits & Mask) == 0)
20241       return TLO.CombineTo(Op, Op0);
20242   }
20243   }
20244 
20245   return TargetLowering::SimplifyDemandedBitsForTargetNode(
20246       Op, OriginalDemandedBits, OriginalDemandedElts, Known, TLO, Depth);
20247 }
20248 
20249 //===----------------------------------------------------------------------===//
20250 //                           ARM Inline Assembly Support
20251 //===----------------------------------------------------------------------===//
20252 
ExpandInlineAsm(CallInst * CI) const20253 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
20254   // Looking for "rev" which is V6+.
20255   if (!Subtarget->hasV6Ops())
20256     return false;
20257 
20258   InlineAsm *IA = cast<InlineAsm>(CI->getCalledOperand());
20259   StringRef AsmStr = IA->getAsmString();
20260   SmallVector<StringRef, 4> AsmPieces;
20261   SplitString(AsmStr, AsmPieces, ";\n");
20262 
20263   switch (AsmPieces.size()) {
20264   default: return false;
20265   case 1:
20266     AsmStr = AsmPieces[0];
20267     AsmPieces.clear();
20268     SplitString(AsmStr, AsmPieces, " \t,");
20269 
20270     // rev $0, $1
20271     if (AsmPieces.size() == 3 && AsmPieces[0] == "rev" &&
20272         AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
20273         IA->getConstraintString().starts_with("=l,l")) {
20274       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
20275       if (Ty && Ty->getBitWidth() == 32)
20276         return IntrinsicLowering::LowerToByteSwap(CI);
20277     }
20278     break;
20279   }
20280 
20281   return false;
20282 }
20283 
LowerXConstraint(EVT ConstraintVT) const20284 const char *ARMTargetLowering::LowerXConstraint(EVT ConstraintVT) const {
20285   // At this point, we have to lower this constraint to something else, so we
20286   // lower it to an "r" or "w". However, by doing this we will force the result
20287   // to be in register, while the X constraint is much more permissive.
20288   //
20289   // Although we are correct (we are free to emit anything, without
20290   // constraints), we might break use cases that would expect us to be more
20291   // efficient and emit something else.
20292   if (!Subtarget->hasVFP2Base())
20293     return "r";
20294   if (ConstraintVT.isFloatingPoint())
20295     return "w";
20296   if (ConstraintVT.isVector() && Subtarget->hasNEON() &&
20297      (ConstraintVT.getSizeInBits() == 64 ||
20298       ConstraintVT.getSizeInBits() == 128))
20299     return "w";
20300 
20301   return "r";
20302 }
20303 
20304 /// getConstraintType - Given a constraint letter, return the type of
20305 /// constraint it is for this target.
20306 ARMTargetLowering::ConstraintType
getConstraintType(StringRef Constraint) const20307 ARMTargetLowering::getConstraintType(StringRef Constraint) const {
20308   unsigned S = Constraint.size();
20309   if (S == 1) {
20310     switch (Constraint[0]) {
20311     default:  break;
20312     case 'l': return C_RegisterClass;
20313     case 'w': return C_RegisterClass;
20314     case 'h': return C_RegisterClass;
20315     case 'x': return C_RegisterClass;
20316     case 't': return C_RegisterClass;
20317     case 'j': return C_Immediate; // Constant for movw.
20318     // An address with a single base register. Due to the way we
20319     // currently handle addresses it is the same as an 'r' memory constraint.
20320     case 'Q': return C_Memory;
20321     }
20322   } else if (S == 2) {
20323     switch (Constraint[0]) {
20324     default: break;
20325     case 'T': return C_RegisterClass;
20326     // All 'U+' constraints are addresses.
20327     case 'U': return C_Memory;
20328     }
20329   }
20330   return TargetLowering::getConstraintType(Constraint);
20331 }
20332 
20333 /// Examine constraint type and operand type and determine a weight value.
20334 /// This object must already have been set up with the operand type
20335 /// and the current alternative constraint selected.
20336 TargetLowering::ConstraintWeight
getSingleConstraintMatchWeight(AsmOperandInfo & info,const char * constraint) const20337 ARMTargetLowering::getSingleConstraintMatchWeight(
20338     AsmOperandInfo &info, const char *constraint) const {
20339   ConstraintWeight weight = CW_Invalid;
20340   Value *CallOperandVal = info.CallOperandVal;
20341     // If we don't have a value, we can't do a match,
20342     // but allow it at the lowest weight.
20343   if (!CallOperandVal)
20344     return CW_Default;
20345   Type *type = CallOperandVal->getType();
20346   // Look at the constraint type.
20347   switch (*constraint) {
20348   default:
20349     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
20350     break;
20351   case 'l':
20352     if (type->isIntegerTy()) {
20353       if (Subtarget->isThumb())
20354         weight = CW_SpecificReg;
20355       else
20356         weight = CW_Register;
20357     }
20358     break;
20359   case 'w':
20360     if (type->isFloatingPointTy())
20361       weight = CW_Register;
20362     break;
20363   }
20364   return weight;
20365 }
20366 
20367 using RCPair = std::pair<unsigned, const TargetRegisterClass *>;
20368 
getRegForInlineAsmConstraint(const TargetRegisterInfo * TRI,StringRef Constraint,MVT VT) const20369 RCPair ARMTargetLowering::getRegForInlineAsmConstraint(
20370     const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
20371   switch (Constraint.size()) {
20372   case 1:
20373     // GCC ARM Constraint Letters
20374     switch (Constraint[0]) {
20375     case 'l': // Low regs or general regs.
20376       if (Subtarget->isThumb())
20377         return RCPair(0U, &ARM::tGPRRegClass);
20378       return RCPair(0U, &ARM::GPRRegClass);
20379     case 'h': // High regs or no regs.
20380       if (Subtarget->isThumb())
20381         return RCPair(0U, &ARM::hGPRRegClass);
20382       break;
20383     case 'r':
20384       if (Subtarget->isThumb1Only())
20385         return RCPair(0U, &ARM::tGPRRegClass);
20386       return RCPair(0U, &ARM::GPRRegClass);
20387     case 'w':
20388       if (VT == MVT::Other)
20389         break;
20390       if (VT == MVT::f32 || VT == MVT::f16 || VT == MVT::bf16)
20391         return RCPair(0U, &ARM::SPRRegClass);
20392       if (VT.getSizeInBits() == 64)
20393         return RCPair(0U, &ARM::DPRRegClass);
20394       if (VT.getSizeInBits() == 128)
20395         return RCPair(0U, &ARM::QPRRegClass);
20396       break;
20397     case 'x':
20398       if (VT == MVT::Other)
20399         break;
20400       if (VT == MVT::f32 || VT == MVT::f16 || VT == MVT::bf16)
20401         return RCPair(0U, &ARM::SPR_8RegClass);
20402       if (VT.getSizeInBits() == 64)
20403         return RCPair(0U, &ARM::DPR_8RegClass);
20404       if (VT.getSizeInBits() == 128)
20405         return RCPair(0U, &ARM::QPR_8RegClass);
20406       break;
20407     case 't':
20408       if (VT == MVT::Other)
20409         break;
20410       if (VT == MVT::f32 || VT == MVT::i32 || VT == MVT::f16 || VT == MVT::bf16)
20411         return RCPair(0U, &ARM::SPRRegClass);
20412       if (VT.getSizeInBits() == 64)
20413         return RCPair(0U, &ARM::DPR_VFP2RegClass);
20414       if (VT.getSizeInBits() == 128)
20415         return RCPair(0U, &ARM::QPR_VFP2RegClass);
20416       break;
20417     }
20418     break;
20419 
20420   case 2:
20421     if (Constraint[0] == 'T') {
20422       switch (Constraint[1]) {
20423       default:
20424         break;
20425       case 'e':
20426         return RCPair(0U, &ARM::tGPREvenRegClass);
20427       case 'o':
20428         return RCPair(0U, &ARM::tGPROddRegClass);
20429       }
20430     }
20431     break;
20432 
20433   default:
20434     break;
20435   }
20436 
20437   if (StringRef("{cc}").equals_insensitive(Constraint))
20438     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
20439 
20440   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
20441 }
20442 
20443 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
20444 /// vector.  If it is invalid, don't add anything to Ops.
LowerAsmOperandForConstraint(SDValue Op,StringRef Constraint,std::vector<SDValue> & Ops,SelectionDAG & DAG) const20445 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
20446                                                      StringRef Constraint,
20447                                                      std::vector<SDValue> &Ops,
20448                                                      SelectionDAG &DAG) const {
20449   SDValue Result;
20450 
20451   // Currently only support length 1 constraints.
20452   if (Constraint.size() != 1)
20453     return;
20454 
20455   char ConstraintLetter = Constraint[0];
20456   switch (ConstraintLetter) {
20457   default: break;
20458   case 'j':
20459   case 'I': case 'J': case 'K': case 'L':
20460   case 'M': case 'N': case 'O':
20461     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
20462     if (!C)
20463       return;
20464 
20465     int64_t CVal64 = C->getSExtValue();
20466     int CVal = (int) CVal64;
20467     // None of these constraints allow values larger than 32 bits.  Check
20468     // that the value fits in an int.
20469     if (CVal != CVal64)
20470       return;
20471 
20472     switch (ConstraintLetter) {
20473       case 'j':
20474         // Constant suitable for movw, must be between 0 and
20475         // 65535.
20476         if (Subtarget->hasV6T2Ops() || (Subtarget->hasV8MBaselineOps()))
20477           if (CVal >= 0 && CVal <= 65535)
20478             break;
20479         return;
20480       case 'I':
20481         if (Subtarget->isThumb1Only()) {
20482           // This must be a constant between 0 and 255, for ADD
20483           // immediates.
20484           if (CVal >= 0 && CVal <= 255)
20485             break;
20486         } else if (Subtarget->isThumb2()) {
20487           // A constant that can be used as an immediate value in a
20488           // data-processing instruction.
20489           if (ARM_AM::getT2SOImmVal(CVal) != -1)
20490             break;
20491         } else {
20492           // A constant that can be used as an immediate value in a
20493           // data-processing instruction.
20494           if (ARM_AM::getSOImmVal(CVal) != -1)
20495             break;
20496         }
20497         return;
20498 
20499       case 'J':
20500         if (Subtarget->isThumb1Only()) {
20501           // This must be a constant between -255 and -1, for negated ADD
20502           // immediates. This can be used in GCC with an "n" modifier that
20503           // prints the negated value, for use with SUB instructions. It is
20504           // not useful otherwise but is implemented for compatibility.
20505           if (CVal >= -255 && CVal <= -1)
20506             break;
20507         } else {
20508           // This must be a constant between -4095 and 4095. It is not clear
20509           // what this constraint is intended for. Implemented for
20510           // compatibility with GCC.
20511           if (CVal >= -4095 && CVal <= 4095)
20512             break;
20513         }
20514         return;
20515 
20516       case 'K':
20517         if (Subtarget->isThumb1Only()) {
20518           // A 32-bit value where only one byte has a nonzero value. Exclude
20519           // zero to match GCC. This constraint is used by GCC internally for
20520           // constants that can be loaded with a move/shift combination.
20521           // It is not useful otherwise but is implemented for compatibility.
20522           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
20523             break;
20524         } else if (Subtarget->isThumb2()) {
20525           // A constant whose bitwise inverse can be used as an immediate
20526           // value in a data-processing instruction. This can be used in GCC
20527           // with a "B" modifier that prints the inverted value, for use with
20528           // BIC and MVN instructions. It is not useful otherwise but is
20529           // implemented for compatibility.
20530           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
20531             break;
20532         } else {
20533           // A constant whose bitwise inverse can be used as an immediate
20534           // value in a data-processing instruction. This can be used in GCC
20535           // with a "B" modifier that prints the inverted value, for use with
20536           // BIC and MVN instructions. It is not useful otherwise but is
20537           // implemented for compatibility.
20538           if (ARM_AM::getSOImmVal(~CVal) != -1)
20539             break;
20540         }
20541         return;
20542 
20543       case 'L':
20544         if (Subtarget->isThumb1Only()) {
20545           // This must be a constant between -7 and 7,
20546           // for 3-operand ADD/SUB immediate instructions.
20547           if (CVal >= -7 && CVal < 7)
20548             break;
20549         } else if (Subtarget->isThumb2()) {
20550           // A constant whose negation can be used as an immediate value in a
20551           // data-processing instruction. This can be used in GCC with an "n"
20552           // modifier that prints the negated value, for use with SUB
20553           // instructions. It is not useful otherwise but is implemented for
20554           // compatibility.
20555           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
20556             break;
20557         } else {
20558           // A constant whose negation can be used as an immediate value in a
20559           // data-processing instruction. This can be used in GCC with an "n"
20560           // modifier that prints the negated value, for use with SUB
20561           // instructions. It is not useful otherwise but is implemented for
20562           // compatibility.
20563           if (ARM_AM::getSOImmVal(-CVal) != -1)
20564             break;
20565         }
20566         return;
20567 
20568       case 'M':
20569         if (Subtarget->isThumb1Only()) {
20570           // This must be a multiple of 4 between 0 and 1020, for
20571           // ADD sp + immediate.
20572           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
20573             break;
20574         } else {
20575           // A power of two or a constant between 0 and 32.  This is used in
20576           // GCC for the shift amount on shifted register operands, but it is
20577           // useful in general for any shift amounts.
20578           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
20579             break;
20580         }
20581         return;
20582 
20583       case 'N':
20584         if (Subtarget->isThumb1Only()) {
20585           // This must be a constant between 0 and 31, for shift amounts.
20586           if (CVal >= 0 && CVal <= 31)
20587             break;
20588         }
20589         return;
20590 
20591       case 'O':
20592         if (Subtarget->isThumb1Only()) {
20593           // This must be a multiple of 4 between -508 and 508, for
20594           // ADD/SUB sp = sp + immediate.
20595           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
20596             break;
20597         }
20598         return;
20599     }
20600     Result = DAG.getSignedTargetConstant(CVal, SDLoc(Op), Op.getValueType());
20601     break;
20602   }
20603 
20604   if (Result.getNode()) {
20605     Ops.push_back(Result);
20606     return;
20607   }
20608   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
20609 }
20610 
getDivRemLibcall(const SDNode * N,MVT::SimpleValueType SVT)20611 static RTLIB::Libcall getDivRemLibcall(
20612     const SDNode *N, MVT::SimpleValueType SVT) {
20613   assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
20614           N->getOpcode() == ISD::SREM    || N->getOpcode() == ISD::UREM) &&
20615          "Unhandled Opcode in getDivRemLibcall");
20616   bool isSigned = N->getOpcode() == ISD::SDIVREM ||
20617                   N->getOpcode() == ISD::SREM;
20618   RTLIB::Libcall LC;
20619   switch (SVT) {
20620   default: llvm_unreachable("Unexpected request for libcall!");
20621   case MVT::i8:  LC = isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
20622   case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
20623   case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
20624   case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
20625   }
20626   return LC;
20627 }
20628 
getDivRemArgList(const SDNode * N,LLVMContext * Context,const ARMSubtarget * Subtarget)20629 static TargetLowering::ArgListTy getDivRemArgList(
20630     const SDNode *N, LLVMContext *Context, const ARMSubtarget *Subtarget) {
20631   assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
20632           N->getOpcode() == ISD::SREM    || N->getOpcode() == ISD::UREM) &&
20633          "Unhandled Opcode in getDivRemArgList");
20634   bool isSigned = N->getOpcode() == ISD::SDIVREM ||
20635                   N->getOpcode() == ISD::SREM;
20636   TargetLowering::ArgListTy Args;
20637   TargetLowering::ArgListEntry Entry;
20638   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
20639     EVT ArgVT = N->getOperand(i).getValueType();
20640     Type *ArgTy = ArgVT.getTypeForEVT(*Context);
20641     Entry.Node = N->getOperand(i);
20642     Entry.Ty = ArgTy;
20643     Entry.IsSExt = isSigned;
20644     Entry.IsZExt = !isSigned;
20645     Args.push_back(Entry);
20646   }
20647   if (Subtarget->isTargetWindows() && Args.size() >= 2)
20648     std::swap(Args[0], Args[1]);
20649   return Args;
20650 }
20651 
LowerDivRem(SDValue Op,SelectionDAG & DAG) const20652 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
20653   assert((Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() ||
20654           Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() ||
20655           Subtarget->isTargetWindows()) &&
20656          "Register-based DivRem lowering only");
20657   unsigned Opcode = Op->getOpcode();
20658   assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
20659          "Invalid opcode for Div/Rem lowering");
20660   bool isSigned = (Opcode == ISD::SDIVREM);
20661   EVT VT = Op->getValueType(0);
20662   SDLoc dl(Op);
20663 
20664   if (VT == MVT::i64 && isa<ConstantSDNode>(Op.getOperand(1))) {
20665     SmallVector<SDValue> Result;
20666     if (expandDIVREMByConstant(Op.getNode(), Result, MVT::i32, DAG)) {
20667         SDValue Res0 =
20668             DAG.getNode(ISD::BUILD_PAIR, dl, VT, Result[0], Result[1]);
20669         SDValue Res1 =
20670             DAG.getNode(ISD::BUILD_PAIR, dl, VT, Result[2], Result[3]);
20671         return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
20672                            {Res0, Res1});
20673     }
20674   }
20675 
20676   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
20677 
20678   // If the target has hardware divide, use divide + multiply + subtract:
20679   //     div = a / b
20680   //     rem = a - b * div
20681   //     return {div, rem}
20682   // This should be lowered into UDIV/SDIV + MLS later on.
20683   bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode()
20684                                         : Subtarget->hasDivideInARMMode();
20685   if (hasDivide && Op->getValueType(0).isSimple() &&
20686       Op->getSimpleValueType(0) == MVT::i32) {
20687     unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
20688     const SDValue Dividend = Op->getOperand(0);
20689     const SDValue Divisor = Op->getOperand(1);
20690     SDValue Div = DAG.getNode(DivOpcode, dl, VT, Dividend, Divisor);
20691     SDValue Mul = DAG.getNode(ISD::MUL, dl, VT, Div, Divisor);
20692     SDValue Rem = DAG.getNode(ISD::SUB, dl, VT, Dividend, Mul);
20693 
20694     SDValue Values[2] = {Div, Rem};
20695     return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VT, VT), Values);
20696   }
20697 
20698   RTLIB::Libcall LC = getDivRemLibcall(Op.getNode(),
20699                                        VT.getSimpleVT().SimpleTy);
20700   SDValue InChain = DAG.getEntryNode();
20701 
20702   TargetLowering::ArgListTy Args = getDivRemArgList(Op.getNode(),
20703                                                     DAG.getContext(),
20704                                                     Subtarget);
20705 
20706   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
20707                                          getPointerTy(DAG.getDataLayout()));
20708 
20709   Type *RetTy = StructType::get(Ty, Ty);
20710 
20711   if (Subtarget->isTargetWindows())
20712     InChain = WinDBZCheckDenominator(DAG, Op.getNode(), InChain);
20713 
20714   TargetLowering::CallLoweringInfo CLI(DAG);
20715   CLI.setDebugLoc(dl).setChain(InChain)
20716     .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args))
20717     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
20718 
20719   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
20720   return CallInfo.first;
20721 }
20722 
20723 // Lowers REM using divmod helpers
20724 // see RTABI section 4.2/4.3
LowerREM(SDNode * N,SelectionDAG & DAG) const20725 SDValue ARMTargetLowering::LowerREM(SDNode *N, SelectionDAG &DAG) const {
20726   EVT VT = N->getValueType(0);
20727 
20728   if (VT == MVT::i64 && isa<ConstantSDNode>(N->getOperand(1))) {
20729     SmallVector<SDValue> Result;
20730     if (expandDIVREMByConstant(N, Result, MVT::i32, DAG))
20731         return DAG.getNode(ISD::BUILD_PAIR, SDLoc(N), N->getValueType(0),
20732                            Result[0], Result[1]);
20733   }
20734 
20735   // Build return types (div and rem)
20736   std::vector<Type*> RetTyParams;
20737   Type *RetTyElement;
20738 
20739   switch (VT.getSimpleVT().SimpleTy) {
20740   default: llvm_unreachable("Unexpected request for libcall!");
20741   case MVT::i8:   RetTyElement = Type::getInt8Ty(*DAG.getContext());  break;
20742   case MVT::i16:  RetTyElement = Type::getInt16Ty(*DAG.getContext()); break;
20743   case MVT::i32:  RetTyElement = Type::getInt32Ty(*DAG.getContext()); break;
20744   case MVT::i64:  RetTyElement = Type::getInt64Ty(*DAG.getContext()); break;
20745   }
20746 
20747   RetTyParams.push_back(RetTyElement);
20748   RetTyParams.push_back(RetTyElement);
20749   ArrayRef<Type*> ret = ArrayRef<Type*>(RetTyParams);
20750   Type *RetTy = StructType::get(*DAG.getContext(), ret);
20751 
20752   RTLIB::Libcall LC = getDivRemLibcall(N, N->getValueType(0).getSimpleVT().
20753                                                              SimpleTy);
20754   SDValue InChain = DAG.getEntryNode();
20755   TargetLowering::ArgListTy Args = getDivRemArgList(N, DAG.getContext(),
20756                                                     Subtarget);
20757   bool isSigned = N->getOpcode() == ISD::SREM;
20758   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
20759                                          getPointerTy(DAG.getDataLayout()));
20760 
20761   if (Subtarget->isTargetWindows())
20762     InChain = WinDBZCheckDenominator(DAG, N, InChain);
20763 
20764   // Lower call
20765   CallLoweringInfo CLI(DAG);
20766   CLI.setChain(InChain)
20767      .setCallee(CallingConv::ARM_AAPCS, RetTy, Callee, std::move(Args))
20768      .setSExtResult(isSigned).setZExtResult(!isSigned).setDebugLoc(SDLoc(N));
20769   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
20770 
20771   // Return second (rem) result operand (first contains div)
20772   SDNode *ResNode = CallResult.first.getNode();
20773   assert(ResNode->getNumOperands() == 2 && "divmod should return two operands");
20774   return ResNode->getOperand(1);
20775 }
20776 
20777 SDValue
LowerDYNAMIC_STACKALLOC(SDValue Op,SelectionDAG & DAG) const20778 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
20779   assert(Subtarget->isTargetWindows() && "unsupported target platform");
20780   SDLoc DL(Op);
20781 
20782   // Get the inputs.
20783   SDValue Chain = Op.getOperand(0);
20784   SDValue Size  = Op.getOperand(1);
20785 
20786   if (DAG.getMachineFunction().getFunction().hasFnAttribute(
20787           "no-stack-arg-probe")) {
20788     MaybeAlign Align =
20789         cast<ConstantSDNode>(Op.getOperand(2))->getMaybeAlignValue();
20790     SDValue SP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
20791     Chain = SP.getValue(1);
20792     SP = DAG.getNode(ISD::SUB, DL, MVT::i32, SP, Size);
20793     if (Align)
20794       SP = DAG.getNode(
20795           ISD::AND, DL, MVT::i32, SP.getValue(0),
20796           DAG.getSignedConstant(-(uint64_t)Align->value(), DL, MVT::i32));
20797     Chain = DAG.getCopyToReg(Chain, DL, ARM::SP, SP);
20798     SDValue Ops[2] = { SP, Chain };
20799     return DAG.getMergeValues(Ops, DL);
20800   }
20801 
20802   SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
20803                               DAG.getConstant(2, DL, MVT::i32));
20804 
20805   SDValue Glue;
20806   Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Glue);
20807   Glue = Chain.getValue(1);
20808 
20809   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
20810   Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Glue);
20811 
20812   SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
20813   Chain = NewSP.getValue(1);
20814 
20815   SDValue Ops[2] = { NewSP, Chain };
20816   return DAG.getMergeValues(Ops, DL);
20817 }
20818 
LowerFP_EXTEND(SDValue Op,SelectionDAG & DAG) const20819 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
20820   bool IsStrict = Op->isStrictFPOpcode();
20821   SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0);
20822   const unsigned DstSz = Op.getValueType().getSizeInBits();
20823   const unsigned SrcSz = SrcVal.getValueType().getSizeInBits();
20824   assert(DstSz > SrcSz && DstSz <= 64 && SrcSz >= 16 &&
20825          "Unexpected type for custom-lowering FP_EXTEND");
20826 
20827   assert((!Subtarget->hasFP64() || !Subtarget->hasFPARMv8Base()) &&
20828          "With both FP DP and 16, any FP conversion is legal!");
20829 
20830   assert(!(DstSz == 32 && Subtarget->hasFP16()) &&
20831          "With FP16, 16 to 32 conversion is legal!");
20832 
20833   // Converting from 32 -> 64 is valid if we have FP64.
20834   if (SrcSz == 32 && DstSz == 64 && Subtarget->hasFP64()) {
20835     // FIXME: Remove this when we have strict fp instruction selection patterns
20836     if (IsStrict) {
20837       SDLoc Loc(Op);
20838       SDValue Result = DAG.getNode(ISD::FP_EXTEND,
20839                                    Loc, Op.getValueType(), SrcVal);
20840       return DAG.getMergeValues({Result, Op.getOperand(0)}, Loc);
20841     }
20842     return Op;
20843   }
20844 
20845   // Either we are converting from 16 -> 64, without FP16 and/or
20846   // FP.double-precision or without Armv8-fp. So we must do it in two
20847   // steps.
20848   // Or we are converting from 32 -> 64 without fp.double-precision or 16 -> 32
20849   // without FP16. So we must do a function call.
20850   SDLoc Loc(Op);
20851   RTLIB::Libcall LC;
20852   MakeLibCallOptions CallOptions;
20853   SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
20854   for (unsigned Sz = SrcSz; Sz <= 32 && Sz < DstSz; Sz *= 2) {
20855     bool Supported = (Sz == 16 ? Subtarget->hasFP16() : Subtarget->hasFP64());
20856     MVT SrcVT = (Sz == 16 ? MVT::f16 : MVT::f32);
20857     MVT DstVT = (Sz == 16 ? MVT::f32 : MVT::f64);
20858     if (Supported) {
20859       if (IsStrict) {
20860         SrcVal = DAG.getNode(ISD::STRICT_FP_EXTEND, Loc,
20861                              {DstVT, MVT::Other}, {Chain, SrcVal});
20862         Chain = SrcVal.getValue(1);
20863       } else {
20864         SrcVal = DAG.getNode(ISD::FP_EXTEND, Loc, DstVT, SrcVal);
20865       }
20866     } else {
20867       LC = RTLIB::getFPEXT(SrcVT, DstVT);
20868       assert(LC != RTLIB::UNKNOWN_LIBCALL &&
20869              "Unexpected type for custom-lowering FP_EXTEND");
20870       std::tie(SrcVal, Chain) = makeLibCall(DAG, LC, DstVT, SrcVal, CallOptions,
20871                                             Loc, Chain);
20872     }
20873   }
20874 
20875   return IsStrict ? DAG.getMergeValues({SrcVal, Chain}, Loc) : SrcVal;
20876 }
20877 
LowerFP_ROUND(SDValue Op,SelectionDAG & DAG) const20878 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
20879   bool IsStrict = Op->isStrictFPOpcode();
20880 
20881   SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0);
20882   EVT SrcVT = SrcVal.getValueType();
20883   EVT DstVT = Op.getValueType();
20884   const unsigned DstSz = Op.getValueType().getSizeInBits();
20885   const unsigned SrcSz = SrcVT.getSizeInBits();
20886   (void)DstSz;
20887   assert(DstSz < SrcSz && SrcSz <= 64 && DstSz >= 16 &&
20888          "Unexpected type for custom-lowering FP_ROUND");
20889 
20890   assert((!Subtarget->hasFP64() || !Subtarget->hasFPARMv8Base()) &&
20891          "With both FP DP and 16, any FP conversion is legal!");
20892 
20893   SDLoc Loc(Op);
20894 
20895   // Instruction from 32 -> 16 if hasFP16 is valid
20896   if (SrcSz == 32 && Subtarget->hasFP16())
20897     return Op;
20898 
20899   // Lib call from 32 -> 16 / 64 -> [32, 16]
20900   RTLIB::Libcall LC = RTLIB::getFPROUND(SrcVT, DstVT);
20901   assert(LC != RTLIB::UNKNOWN_LIBCALL &&
20902          "Unexpected type for custom-lowering FP_ROUND");
20903   MakeLibCallOptions CallOptions;
20904   SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
20905   SDValue Result;
20906   std::tie(Result, Chain) = makeLibCall(DAG, LC, DstVT, SrcVal, CallOptions,
20907                                         Loc, Chain);
20908   return IsStrict ? DAG.getMergeValues({Result, Chain}, Loc) : Result;
20909 }
20910 
20911 bool
isOffsetFoldingLegal(const GlobalAddressSDNode * GA) const20912 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
20913   // The ARM target isn't yet aware of offsets.
20914   return false;
20915 }
20916 
isBitFieldInvertedMask(unsigned v)20917 bool ARM::isBitFieldInvertedMask(unsigned v) {
20918   if (v == 0xffffffff)
20919     return false;
20920 
20921   // there can be 1's on either or both "outsides", all the "inside"
20922   // bits must be 0's
20923   return isShiftedMask_32(~v);
20924 }
20925 
20926 /// isFPImmLegal - Returns true if the target can instruction select the
20927 /// specified FP immediate natively. If false, the legalizer will
20928 /// materialize the FP immediate as a load from a constant pool.
isFPImmLegal(const APFloat & Imm,EVT VT,bool ForCodeSize) const20929 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
20930                                      bool ForCodeSize) const {
20931   if (!Subtarget->hasVFP3Base())
20932     return false;
20933   if (VT == MVT::f16 && Subtarget->hasFullFP16())
20934     return ARM_AM::getFP16Imm(Imm) != -1;
20935   if (VT == MVT::f32 && Subtarget->hasFullFP16() &&
20936       ARM_AM::getFP32FP16Imm(Imm) != -1)
20937     return true;
20938   if (VT == MVT::f32)
20939     return ARM_AM::getFP32Imm(Imm) != -1;
20940   if (VT == MVT::f64 && Subtarget->hasFP64())
20941     return ARM_AM::getFP64Imm(Imm) != -1;
20942   return false;
20943 }
20944 
20945 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
20946 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
20947 /// specified in the intrinsic calls.
getTgtMemIntrinsic(IntrinsicInfo & Info,const CallInst & I,MachineFunction & MF,unsigned Intrinsic) const20948 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
20949                                            const CallInst &I,
20950                                            MachineFunction &MF,
20951                                            unsigned Intrinsic) const {
20952   switch (Intrinsic) {
20953   case Intrinsic::arm_neon_vld1:
20954   case Intrinsic::arm_neon_vld2:
20955   case Intrinsic::arm_neon_vld3:
20956   case Intrinsic::arm_neon_vld4:
20957   case Intrinsic::arm_neon_vld2lane:
20958   case Intrinsic::arm_neon_vld3lane:
20959   case Intrinsic::arm_neon_vld4lane:
20960   case Intrinsic::arm_neon_vld2dup:
20961   case Intrinsic::arm_neon_vld3dup:
20962   case Intrinsic::arm_neon_vld4dup: {
20963     Info.opc = ISD::INTRINSIC_W_CHAIN;
20964     // Conservatively set memVT to the entire set of vectors loaded.
20965     auto &DL = I.getDataLayout();
20966     uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
20967     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
20968     Info.ptrVal = I.getArgOperand(0);
20969     Info.offset = 0;
20970     Value *AlignArg = I.getArgOperand(I.arg_size() - 1);
20971     Info.align = cast<ConstantInt>(AlignArg)->getMaybeAlignValue();
20972     // volatile loads with NEON intrinsics not supported
20973     Info.flags = MachineMemOperand::MOLoad;
20974     return true;
20975   }
20976   case Intrinsic::arm_neon_vld1x2:
20977   case Intrinsic::arm_neon_vld1x3:
20978   case Intrinsic::arm_neon_vld1x4: {
20979     Info.opc = ISD::INTRINSIC_W_CHAIN;
20980     // Conservatively set memVT to the entire set of vectors loaded.
20981     auto &DL = I.getDataLayout();
20982     uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
20983     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
20984     Info.ptrVal = I.getArgOperand(I.arg_size() - 1);
20985     Info.offset = 0;
20986     Info.align = I.getParamAlign(I.arg_size() - 1).valueOrOne();
20987     // volatile loads with NEON intrinsics not supported
20988     Info.flags = MachineMemOperand::MOLoad;
20989     return true;
20990   }
20991   case Intrinsic::arm_neon_vst1:
20992   case Intrinsic::arm_neon_vst2:
20993   case Intrinsic::arm_neon_vst3:
20994   case Intrinsic::arm_neon_vst4:
20995   case Intrinsic::arm_neon_vst2lane:
20996   case Intrinsic::arm_neon_vst3lane:
20997   case Intrinsic::arm_neon_vst4lane: {
20998     Info.opc = ISD::INTRINSIC_VOID;
20999     // Conservatively set memVT to the entire set of vectors stored.
21000     auto &DL = I.getDataLayout();
21001     unsigned NumElts = 0;
21002     for (unsigned ArgI = 1, ArgE = I.arg_size(); ArgI < ArgE; ++ArgI) {
21003       Type *ArgTy = I.getArgOperand(ArgI)->getType();
21004       if (!ArgTy->isVectorTy())
21005         break;
21006       NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
21007     }
21008     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
21009     Info.ptrVal = I.getArgOperand(0);
21010     Info.offset = 0;
21011     Value *AlignArg = I.getArgOperand(I.arg_size() - 1);
21012     Info.align = cast<ConstantInt>(AlignArg)->getMaybeAlignValue();
21013     // volatile stores with NEON intrinsics not supported
21014     Info.flags = MachineMemOperand::MOStore;
21015     return true;
21016   }
21017   case Intrinsic::arm_neon_vst1x2:
21018   case Intrinsic::arm_neon_vst1x3:
21019   case Intrinsic::arm_neon_vst1x4: {
21020     Info.opc = ISD::INTRINSIC_VOID;
21021     // Conservatively set memVT to the entire set of vectors stored.
21022     auto &DL = I.getDataLayout();
21023     unsigned NumElts = 0;
21024     for (unsigned ArgI = 1, ArgE = I.arg_size(); ArgI < ArgE; ++ArgI) {
21025       Type *ArgTy = I.getArgOperand(ArgI)->getType();
21026       if (!ArgTy->isVectorTy())
21027         break;
21028       NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
21029     }
21030     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
21031     Info.ptrVal = I.getArgOperand(0);
21032     Info.offset = 0;
21033     Info.align = I.getParamAlign(0).valueOrOne();
21034     // volatile stores with NEON intrinsics not supported
21035     Info.flags = MachineMemOperand::MOStore;
21036     return true;
21037   }
21038   case Intrinsic::arm_mve_vld2q:
21039   case Intrinsic::arm_mve_vld4q: {
21040     Info.opc = ISD::INTRINSIC_W_CHAIN;
21041     // Conservatively set memVT to the entire set of vectors loaded.
21042     Type *VecTy = cast<StructType>(I.getType())->getElementType(1);
21043     unsigned Factor = Intrinsic == Intrinsic::arm_mve_vld2q ? 2 : 4;
21044     Info.memVT = EVT::getVectorVT(VecTy->getContext(), MVT::i64, Factor * 2);
21045     Info.ptrVal = I.getArgOperand(0);
21046     Info.offset = 0;
21047     Info.align = Align(VecTy->getScalarSizeInBits() / 8);
21048     // volatile loads with MVE intrinsics not supported
21049     Info.flags = MachineMemOperand::MOLoad;
21050     return true;
21051   }
21052   case Intrinsic::arm_mve_vst2q:
21053   case Intrinsic::arm_mve_vst4q: {
21054     Info.opc = ISD::INTRINSIC_VOID;
21055     // Conservatively set memVT to the entire set of vectors stored.
21056     Type *VecTy = I.getArgOperand(1)->getType();
21057     unsigned Factor = Intrinsic == Intrinsic::arm_mve_vst2q ? 2 : 4;
21058     Info.memVT = EVT::getVectorVT(VecTy->getContext(), MVT::i64, Factor * 2);
21059     Info.ptrVal = I.getArgOperand(0);
21060     Info.offset = 0;
21061     Info.align = Align(VecTy->getScalarSizeInBits() / 8);
21062     // volatile stores with MVE intrinsics not supported
21063     Info.flags = MachineMemOperand::MOStore;
21064     return true;
21065   }
21066   case Intrinsic::arm_mve_vldr_gather_base:
21067   case Intrinsic::arm_mve_vldr_gather_base_predicated: {
21068     Info.opc = ISD::INTRINSIC_W_CHAIN;
21069     Info.ptrVal = nullptr;
21070     Info.memVT = MVT::getVT(I.getType());
21071     Info.align = Align(1);
21072     Info.flags |= MachineMemOperand::MOLoad;
21073     return true;
21074   }
21075   case Intrinsic::arm_mve_vldr_gather_base_wb:
21076   case Intrinsic::arm_mve_vldr_gather_base_wb_predicated: {
21077     Info.opc = ISD::INTRINSIC_W_CHAIN;
21078     Info.ptrVal = nullptr;
21079     Info.memVT = MVT::getVT(I.getType()->getContainedType(0));
21080     Info.align = Align(1);
21081     Info.flags |= MachineMemOperand::MOLoad;
21082     return true;
21083   }
21084   case Intrinsic::arm_mve_vldr_gather_offset:
21085   case Intrinsic::arm_mve_vldr_gather_offset_predicated: {
21086     Info.opc = ISD::INTRINSIC_W_CHAIN;
21087     Info.ptrVal = nullptr;
21088     MVT DataVT = MVT::getVT(I.getType());
21089     unsigned MemSize = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue();
21090     Info.memVT = MVT::getVectorVT(MVT::getIntegerVT(MemSize),
21091                                   DataVT.getVectorNumElements());
21092     Info.align = Align(1);
21093     Info.flags |= MachineMemOperand::MOLoad;
21094     return true;
21095   }
21096   case Intrinsic::arm_mve_vstr_scatter_base:
21097   case Intrinsic::arm_mve_vstr_scatter_base_predicated: {
21098     Info.opc = ISD::INTRINSIC_VOID;
21099     Info.ptrVal = nullptr;
21100     Info.memVT = MVT::getVT(I.getArgOperand(2)->getType());
21101     Info.align = Align(1);
21102     Info.flags |= MachineMemOperand::MOStore;
21103     return true;
21104   }
21105   case Intrinsic::arm_mve_vstr_scatter_base_wb:
21106   case Intrinsic::arm_mve_vstr_scatter_base_wb_predicated: {
21107     Info.opc = ISD::INTRINSIC_W_CHAIN;
21108     Info.ptrVal = nullptr;
21109     Info.memVT = MVT::getVT(I.getArgOperand(2)->getType());
21110     Info.align = Align(1);
21111     Info.flags |= MachineMemOperand::MOStore;
21112     return true;
21113   }
21114   case Intrinsic::arm_mve_vstr_scatter_offset:
21115   case Intrinsic::arm_mve_vstr_scatter_offset_predicated: {
21116     Info.opc = ISD::INTRINSIC_VOID;
21117     Info.ptrVal = nullptr;
21118     MVT DataVT = MVT::getVT(I.getArgOperand(2)->getType());
21119     unsigned MemSize = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
21120     Info.memVT = MVT::getVectorVT(MVT::getIntegerVT(MemSize),
21121                                   DataVT.getVectorNumElements());
21122     Info.align = Align(1);
21123     Info.flags |= MachineMemOperand::MOStore;
21124     return true;
21125   }
21126   case Intrinsic::arm_ldaex:
21127   case Intrinsic::arm_ldrex: {
21128     auto &DL = I.getDataLayout();
21129     Type *ValTy = I.getParamElementType(0);
21130     Info.opc = ISD::INTRINSIC_W_CHAIN;
21131     Info.memVT = MVT::getVT(ValTy);
21132     Info.ptrVal = I.getArgOperand(0);
21133     Info.offset = 0;
21134     Info.align = DL.getABITypeAlign(ValTy);
21135     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
21136     return true;
21137   }
21138   case Intrinsic::arm_stlex:
21139   case Intrinsic::arm_strex: {
21140     auto &DL = I.getDataLayout();
21141     Type *ValTy = I.getParamElementType(1);
21142     Info.opc = ISD::INTRINSIC_W_CHAIN;
21143     Info.memVT = MVT::getVT(ValTy);
21144     Info.ptrVal = I.getArgOperand(1);
21145     Info.offset = 0;
21146     Info.align = DL.getABITypeAlign(ValTy);
21147     Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
21148     return true;
21149   }
21150   case Intrinsic::arm_stlexd:
21151   case Intrinsic::arm_strexd:
21152     Info.opc = ISD::INTRINSIC_W_CHAIN;
21153     Info.memVT = MVT::i64;
21154     Info.ptrVal = I.getArgOperand(2);
21155     Info.offset = 0;
21156     Info.align = Align(8);
21157     Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
21158     return true;
21159 
21160   case Intrinsic::arm_ldaexd:
21161   case Intrinsic::arm_ldrexd:
21162     Info.opc = ISD::INTRINSIC_W_CHAIN;
21163     Info.memVT = MVT::i64;
21164     Info.ptrVal = I.getArgOperand(0);
21165     Info.offset = 0;
21166     Info.align = Align(8);
21167     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
21168     return true;
21169 
21170   default:
21171     break;
21172   }
21173 
21174   return false;
21175 }
21176 
21177 /// Returns true if it is beneficial to convert a load of a constant
21178 /// to just the constant itself.
shouldConvertConstantLoadToIntImm(const APInt & Imm,Type * Ty) const21179 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
21180                                                           Type *Ty) const {
21181   assert(Ty->isIntegerTy());
21182 
21183   unsigned Bits = Ty->getPrimitiveSizeInBits();
21184   if (Bits == 0 || Bits > 32)
21185     return false;
21186   return true;
21187 }
21188 
isExtractSubvectorCheap(EVT ResVT,EVT SrcVT,unsigned Index) const21189 bool ARMTargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT,
21190                                                 unsigned Index) const {
21191   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
21192     return false;
21193 
21194   return (Index == 0 || Index == ResVT.getVectorNumElements());
21195 }
21196 
makeDMB(IRBuilderBase & Builder,ARM_MB::MemBOpt Domain) const21197 Instruction *ARMTargetLowering::makeDMB(IRBuilderBase &Builder,
21198                                         ARM_MB::MemBOpt Domain) const {
21199   // First, if the target has no DMB, see what fallback we can use.
21200   if (!Subtarget->hasDataBarrier()) {
21201     // Some ARMv6 cpus can support data barriers with an mcr instruction.
21202     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
21203     // here.
21204     if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) {
21205       Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0),
21206                         Builder.getInt32(0), Builder.getInt32(7),
21207                         Builder.getInt32(10), Builder.getInt32(5)};
21208       return Builder.CreateIntrinsic(Intrinsic::arm_mcr, args);
21209     } else {
21210       // Instead of using barriers, atomic accesses on these subtargets use
21211       // libcalls.
21212       llvm_unreachable("makeDMB on a target so old that it has no barriers");
21213     }
21214   } else {
21215     // Only a full system barrier exists in the M-class architectures.
21216     Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain;
21217     Constant *CDomain = Builder.getInt32(Domain);
21218     return Builder.CreateIntrinsic(Intrinsic::arm_dmb, CDomain);
21219   }
21220 }
21221 
21222 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
emitLeadingFence(IRBuilderBase & Builder,Instruction * Inst,AtomicOrdering Ord) const21223 Instruction *ARMTargetLowering::emitLeadingFence(IRBuilderBase &Builder,
21224                                                  Instruction *Inst,
21225                                                  AtomicOrdering Ord) const {
21226   switch (Ord) {
21227   case AtomicOrdering::NotAtomic:
21228   case AtomicOrdering::Unordered:
21229     llvm_unreachable("Invalid fence: unordered/non-atomic");
21230   case AtomicOrdering::Monotonic:
21231   case AtomicOrdering::Acquire:
21232     return nullptr; // Nothing to do
21233   case AtomicOrdering::SequentiallyConsistent:
21234     if (!Inst->hasAtomicStore())
21235       return nullptr; // Nothing to do
21236     [[fallthrough]];
21237   case AtomicOrdering::Release:
21238   case AtomicOrdering::AcquireRelease:
21239     if (Subtarget->preferISHSTBarriers())
21240       return makeDMB(Builder, ARM_MB::ISHST);
21241     // FIXME: add a comment with a link to documentation justifying this.
21242     else
21243       return makeDMB(Builder, ARM_MB::ISH);
21244   }
21245   llvm_unreachable("Unknown fence ordering in emitLeadingFence");
21246 }
21247 
emitTrailingFence(IRBuilderBase & Builder,Instruction * Inst,AtomicOrdering Ord) const21248 Instruction *ARMTargetLowering::emitTrailingFence(IRBuilderBase &Builder,
21249                                                   Instruction *Inst,
21250                                                   AtomicOrdering Ord) const {
21251   switch (Ord) {
21252   case AtomicOrdering::NotAtomic:
21253   case AtomicOrdering::Unordered:
21254     llvm_unreachable("Invalid fence: unordered/not-atomic");
21255   case AtomicOrdering::Monotonic:
21256   case AtomicOrdering::Release:
21257     return nullptr; // Nothing to do
21258   case AtomicOrdering::Acquire:
21259   case AtomicOrdering::AcquireRelease:
21260   case AtomicOrdering::SequentiallyConsistent:
21261     return makeDMB(Builder, ARM_MB::ISH);
21262   }
21263   llvm_unreachable("Unknown fence ordering in emitTrailingFence");
21264 }
21265 
21266 // Loads and stores less than 64-bits are already atomic; ones above that
21267 // are doomed anyway, so defer to the default libcall and blame the OS when
21268 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
21269 // anything for those.
21270 TargetLoweringBase::AtomicExpansionKind
shouldExpandAtomicStoreInIR(StoreInst * SI) const21271 ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
21272   bool has64BitAtomicStore;
21273   if (Subtarget->isMClass())
21274     has64BitAtomicStore = false;
21275   else if (Subtarget->isThumb())
21276     has64BitAtomicStore = Subtarget->hasV7Ops();
21277   else
21278     has64BitAtomicStore = Subtarget->hasV6Ops();
21279 
21280   unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
21281   return Size == 64 && has64BitAtomicStore ? AtomicExpansionKind::Expand
21282                                            : AtomicExpansionKind::None;
21283 }
21284 
21285 // Loads and stores less than 64-bits are already atomic; ones above that
21286 // are doomed anyway, so defer to the default libcall and blame the OS when
21287 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
21288 // anything for those.
21289 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that
21290 // guarantee, see DDI0406C ARM architecture reference manual,
21291 // sections A8.8.72-74 LDRD)
21292 TargetLowering::AtomicExpansionKind
shouldExpandAtomicLoadInIR(LoadInst * LI) const21293 ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
21294   bool has64BitAtomicLoad;
21295   if (Subtarget->isMClass())
21296     has64BitAtomicLoad = false;
21297   else if (Subtarget->isThumb())
21298     has64BitAtomicLoad = Subtarget->hasV7Ops();
21299   else
21300     has64BitAtomicLoad = Subtarget->hasV6Ops();
21301 
21302   unsigned Size = LI->getType()->getPrimitiveSizeInBits();
21303   return (Size == 64 && has64BitAtomicLoad) ? AtomicExpansionKind::LLOnly
21304                                             : AtomicExpansionKind::None;
21305 }
21306 
21307 // For the real atomic operations, we have ldrex/strex up to 32 bits,
21308 // and up to 64 bits on the non-M profiles
21309 TargetLowering::AtomicExpansionKind
shouldExpandAtomicRMWInIR(AtomicRMWInst * AI) const21310 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
21311   if (AI->isFloatingPointOperation())
21312     return AtomicExpansionKind::CmpXChg;
21313 
21314   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
21315   bool hasAtomicRMW;
21316   if (Subtarget->isMClass())
21317     hasAtomicRMW = Subtarget->hasV8MBaselineOps();
21318   else if (Subtarget->isThumb())
21319     hasAtomicRMW = Subtarget->hasV7Ops();
21320   else
21321     hasAtomicRMW = Subtarget->hasV6Ops();
21322   if (Size <= (Subtarget->isMClass() ? 32U : 64U) && hasAtomicRMW) {
21323     // At -O0, fast-regalloc cannot cope with the live vregs necessary to
21324     // implement atomicrmw without spilling. If the target address is also on
21325     // the stack and close enough to the spill slot, this can lead to a
21326     // situation where the monitor always gets cleared and the atomic operation
21327     // can never succeed. So at -O0 lower this operation to a CAS loop.
21328     if (getTargetMachine().getOptLevel() == CodeGenOptLevel::None)
21329       return AtomicExpansionKind::CmpXChg;
21330     return AtomicExpansionKind::LLSC;
21331   }
21332   return AtomicExpansionKind::None;
21333 }
21334 
21335 // Similar to shouldExpandAtomicRMWInIR, ldrex/strex can be used  up to 32
21336 // bits, and up to 64 bits on the non-M profiles.
21337 TargetLowering::AtomicExpansionKind
shouldExpandAtomicCmpXchgInIR(AtomicCmpXchgInst * AI) const21338 ARMTargetLowering::shouldExpandAtomicCmpXchgInIR(AtomicCmpXchgInst *AI) const {
21339   // At -O0, fast-regalloc cannot cope with the live vregs necessary to
21340   // implement cmpxchg without spilling. If the address being exchanged is also
21341   // on the stack and close enough to the spill slot, this can lead to a
21342   // situation where the monitor always gets cleared and the atomic operation
21343   // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead.
21344   unsigned Size = AI->getOperand(1)->getType()->getPrimitiveSizeInBits();
21345   bool HasAtomicCmpXchg;
21346   if (Subtarget->isMClass())
21347     HasAtomicCmpXchg = Subtarget->hasV8MBaselineOps();
21348   else if (Subtarget->isThumb())
21349     HasAtomicCmpXchg = Subtarget->hasV7Ops();
21350   else
21351     HasAtomicCmpXchg = Subtarget->hasV6Ops();
21352   if (getTargetMachine().getOptLevel() != CodeGenOptLevel::None &&
21353       HasAtomicCmpXchg && Size <= (Subtarget->isMClass() ? 32U : 64U))
21354     return AtomicExpansionKind::LLSC;
21355   return AtomicExpansionKind::None;
21356 }
21357 
shouldInsertFencesForAtomic(const Instruction * I) const21358 bool ARMTargetLowering::shouldInsertFencesForAtomic(
21359     const Instruction *I) const {
21360   return InsertFencesForAtomic;
21361 }
21362 
useLoadStackGuardNode(const Module & M) const21363 bool ARMTargetLowering::useLoadStackGuardNode(const Module &M) const {
21364   // ROPI/RWPI are not supported currently.
21365   return !Subtarget->isROPI() && !Subtarget->isRWPI();
21366 }
21367 
insertSSPDeclarations(Module & M) const21368 void ARMTargetLowering::insertSSPDeclarations(Module &M) const {
21369   if (!Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
21370     return TargetLowering::insertSSPDeclarations(M);
21371 
21372   // MSVC CRT has a global variable holding security cookie.
21373   M.getOrInsertGlobal("__security_cookie",
21374                       PointerType::getUnqual(M.getContext()));
21375 
21376   // MSVC CRT has a function to validate security cookie.
21377   FunctionCallee SecurityCheckCookie = M.getOrInsertFunction(
21378       "__security_check_cookie", Type::getVoidTy(M.getContext()),
21379       PointerType::getUnqual(M.getContext()));
21380   if (Function *F = dyn_cast<Function>(SecurityCheckCookie.getCallee()))
21381     F->addParamAttr(0, Attribute::AttrKind::InReg);
21382 }
21383 
getSDagStackGuard(const Module & M) const21384 Value *ARMTargetLowering::getSDagStackGuard(const Module &M) const {
21385   // MSVC CRT has a global variable holding security cookie.
21386   if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
21387     return M.getGlobalVariable("__security_cookie");
21388   return TargetLowering::getSDagStackGuard(M);
21389 }
21390 
getSSPStackGuardCheck(const Module & M) const21391 Function *ARMTargetLowering::getSSPStackGuardCheck(const Module &M) const {
21392   // MSVC CRT has a function to validate security cookie.
21393   if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
21394     return M.getFunction("__security_check_cookie");
21395   return TargetLowering::getSSPStackGuardCheck(M);
21396 }
21397 
canCombineStoreAndExtract(Type * VectorTy,Value * Idx,unsigned & Cost) const21398 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
21399                                                   unsigned &Cost) const {
21400   // If we do not have NEON, vector types are not natively supported.
21401   if (!Subtarget->hasNEON())
21402     return false;
21403 
21404   // Floating point values and vector values map to the same register file.
21405   // Therefore, although we could do a store extract of a vector type, this is
21406   // better to leave at float as we have more freedom in the addressing mode for
21407   // those.
21408   if (VectorTy->isFPOrFPVectorTy())
21409     return false;
21410 
21411   // If the index is unknown at compile time, this is very expensive to lower
21412   // and it is not possible to combine the store with the extract.
21413   if (!isa<ConstantInt>(Idx))
21414     return false;
21415 
21416   assert(VectorTy->isVectorTy() && "VectorTy is not a vector type");
21417   unsigned BitWidth = VectorTy->getPrimitiveSizeInBits().getFixedValue();
21418   // We can do a store + vector extract on any vector that fits perfectly in a D
21419   // or Q register.
21420   if (BitWidth == 64 || BitWidth == 128) {
21421     Cost = 0;
21422     return true;
21423   }
21424   return false;
21425 }
21426 
isCheapToSpeculateCttz(Type * Ty) const21427 bool ARMTargetLowering::isCheapToSpeculateCttz(Type *Ty) const {
21428   return Subtarget->hasV6T2Ops();
21429 }
21430 
isCheapToSpeculateCtlz(Type * Ty) const21431 bool ARMTargetLowering::isCheapToSpeculateCtlz(Type *Ty) const {
21432   return Subtarget->hasV6T2Ops();
21433 }
21434 
isMaskAndCmp0FoldingBeneficial(const Instruction & AndI) const21435 bool ARMTargetLowering::isMaskAndCmp0FoldingBeneficial(
21436     const Instruction &AndI) const {
21437   if (!Subtarget->hasV7Ops())
21438     return false;
21439 
21440   // Sink the `and` instruction only if the mask would fit into a modified
21441   // immediate operand.
21442   ConstantInt *Mask = dyn_cast<ConstantInt>(AndI.getOperand(1));
21443   if (!Mask || Mask->getValue().getBitWidth() > 32u)
21444     return false;
21445   auto MaskVal = unsigned(Mask->getValue().getZExtValue());
21446   return (Subtarget->isThumb2() ? ARM_AM::getT2SOImmVal(MaskVal)
21447                                 : ARM_AM::getSOImmVal(MaskVal)) != -1;
21448 }
21449 
21450 TargetLowering::ShiftLegalizationStrategy
preferredShiftLegalizationStrategy(SelectionDAG & DAG,SDNode * N,unsigned ExpansionFactor) const21451 ARMTargetLowering::preferredShiftLegalizationStrategy(
21452     SelectionDAG &DAG, SDNode *N, unsigned ExpansionFactor) const {
21453   if (Subtarget->hasMinSize() && !Subtarget->isTargetWindows())
21454     return ShiftLegalizationStrategy::LowerToLibcall;
21455   return TargetLowering::preferredShiftLegalizationStrategy(DAG, N,
21456                                                             ExpansionFactor);
21457 }
21458 
emitLoadLinked(IRBuilderBase & Builder,Type * ValueTy,Value * Addr,AtomicOrdering Ord) const21459 Value *ARMTargetLowering::emitLoadLinked(IRBuilderBase &Builder, Type *ValueTy,
21460                                          Value *Addr,
21461                                          AtomicOrdering Ord) const {
21462   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
21463   bool IsAcquire = isAcquireOrStronger(Ord);
21464 
21465   // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
21466   // intrinsic must return {i32, i32} and we have to recombine them into a
21467   // single i64 here.
21468   if (ValueTy->getPrimitiveSizeInBits() == 64) {
21469     Intrinsic::ID Int =
21470         IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
21471 
21472     Value *LoHi =
21473         Builder.CreateIntrinsic(Int, Addr, /*FMFSource=*/nullptr, "lohi");
21474 
21475     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
21476     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
21477     if (!Subtarget->isLittle())
21478       std::swap (Lo, Hi);
21479     Lo = Builder.CreateZExt(Lo, ValueTy, "lo64");
21480     Hi = Builder.CreateZExt(Hi, ValueTy, "hi64");
21481     return Builder.CreateOr(
21482         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValueTy, 32)), "val64");
21483   }
21484 
21485   Type *Tys[] = { Addr->getType() };
21486   Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
21487   CallInst *CI = Builder.CreateIntrinsic(Int, Tys, Addr);
21488 
21489   CI->addParamAttr(
21490       0, Attribute::get(M->getContext(), Attribute::ElementType, ValueTy));
21491   return Builder.CreateTruncOrBitCast(CI, ValueTy);
21492 }
21493 
emitAtomicCmpXchgNoStoreLLBalance(IRBuilderBase & Builder) const21494 void ARMTargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
21495     IRBuilderBase &Builder) const {
21496   if (!Subtarget->hasV7Ops())
21497     return;
21498   Builder.CreateIntrinsic(Intrinsic::arm_clrex, {});
21499 }
21500 
emitStoreConditional(IRBuilderBase & Builder,Value * Val,Value * Addr,AtomicOrdering Ord) const21501 Value *ARMTargetLowering::emitStoreConditional(IRBuilderBase &Builder,
21502                                                Value *Val, Value *Addr,
21503                                                AtomicOrdering Ord) const {
21504   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
21505   bool IsRelease = isReleaseOrStronger(Ord);
21506 
21507   // Since the intrinsics must have legal type, the i64 intrinsics take two
21508   // parameters: "i32, i32". We must marshal Val into the appropriate form
21509   // before the call.
21510   if (Val->getType()->getPrimitiveSizeInBits() == 64) {
21511     Intrinsic::ID Int =
21512         IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
21513     Type *Int32Ty = Type::getInt32Ty(M->getContext());
21514 
21515     Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
21516     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
21517     if (!Subtarget->isLittle())
21518       std::swap(Lo, Hi);
21519     return Builder.CreateIntrinsic(Int, {Lo, Hi, Addr});
21520   }
21521 
21522   Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
21523   Type *Tys[] = { Addr->getType() };
21524   Function *Strex = Intrinsic::getOrInsertDeclaration(M, Int, Tys);
21525 
21526   CallInst *CI = Builder.CreateCall(
21527       Strex, {Builder.CreateZExtOrBitCast(
21528                   Val, Strex->getFunctionType()->getParamType(0)),
21529               Addr});
21530   CI->addParamAttr(1, Attribute::get(M->getContext(), Attribute::ElementType,
21531                                      Val->getType()));
21532   return CI;
21533 }
21534 
21535 
alignLoopsWithOptSize() const21536 bool ARMTargetLowering::alignLoopsWithOptSize() const {
21537   return Subtarget->isMClass();
21538 }
21539 
21540 /// A helper function for determining the number of interleaved accesses we
21541 /// will generate when lowering accesses of the given type.
21542 unsigned
getNumInterleavedAccesses(VectorType * VecTy,const DataLayout & DL) const21543 ARMTargetLowering::getNumInterleavedAccesses(VectorType *VecTy,
21544                                              const DataLayout &DL) const {
21545   return (DL.getTypeSizeInBits(VecTy) + 127) / 128;
21546 }
21547 
isLegalInterleavedAccessType(unsigned Factor,FixedVectorType * VecTy,Align Alignment,const DataLayout & DL) const21548 bool ARMTargetLowering::isLegalInterleavedAccessType(
21549     unsigned Factor, FixedVectorType *VecTy, Align Alignment,
21550     const DataLayout &DL) const {
21551 
21552   unsigned VecSize = DL.getTypeSizeInBits(VecTy);
21553   unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType());
21554 
21555   if (!Subtarget->hasNEON() && !Subtarget->hasMVEIntegerOps())
21556     return false;
21557 
21558   // Ensure the vector doesn't have f16 elements. Even though we could do an
21559   // i16 vldN, we can't hold the f16 vectors and will end up converting via
21560   // f32.
21561   if (Subtarget->hasNEON() && VecTy->getElementType()->isHalfTy())
21562     return false;
21563   if (Subtarget->hasMVEIntegerOps() && Factor == 3)
21564     return false;
21565 
21566   // Ensure the number of vector elements is greater than 1.
21567   if (VecTy->getNumElements() < 2)
21568     return false;
21569 
21570   // Ensure the element type is legal.
21571   if (ElSize != 8 && ElSize != 16 && ElSize != 32)
21572     return false;
21573   // And the alignment if high enough under MVE.
21574   if (Subtarget->hasMVEIntegerOps() && Alignment < ElSize / 8)
21575     return false;
21576 
21577   // Ensure the total vector size is 64 or a multiple of 128. Types larger than
21578   // 128 will be split into multiple interleaved accesses.
21579   if (Subtarget->hasNEON() && VecSize == 64)
21580     return true;
21581   return VecSize % 128 == 0;
21582 }
21583 
getMaxSupportedInterleaveFactor() const21584 unsigned ARMTargetLowering::getMaxSupportedInterleaveFactor() const {
21585   if (Subtarget->hasNEON())
21586     return 4;
21587   if (Subtarget->hasMVEIntegerOps())
21588     return MVEMaxSupportedInterleaveFactor;
21589   return TargetLoweringBase::getMaxSupportedInterleaveFactor();
21590 }
21591 
21592 /// Lower an interleaved load into a vldN intrinsic.
21593 ///
21594 /// E.g. Lower an interleaved load (Factor = 2):
21595 ///        %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4
21596 ///        %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6>  ; Extract even elements
21597 ///        %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7>  ; Extract odd elements
21598 ///
21599 ///      Into:
21600 ///        %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4)
21601 ///        %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0
21602 ///        %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1
lowerInterleavedLoad(LoadInst * LI,ArrayRef<ShuffleVectorInst * > Shuffles,ArrayRef<unsigned> Indices,unsigned Factor) const21603 bool ARMTargetLowering::lowerInterleavedLoad(
21604     LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
21605     ArrayRef<unsigned> Indices, unsigned Factor) const {
21606   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
21607          "Invalid interleave factor");
21608   assert(!Shuffles.empty() && "Empty shufflevector input");
21609   assert(Shuffles.size() == Indices.size() &&
21610          "Unmatched number of shufflevectors and indices");
21611 
21612   auto *VecTy = cast<FixedVectorType>(Shuffles[0]->getType());
21613   Type *EltTy = VecTy->getElementType();
21614 
21615   const DataLayout &DL = LI->getDataLayout();
21616   Align Alignment = LI->getAlign();
21617 
21618   // Skip if we do not have NEON and skip illegal vector types. We can
21619   // "legalize" wide vector types into multiple interleaved accesses as long as
21620   // the vector types are divisible by 128.
21621   if (!isLegalInterleavedAccessType(Factor, VecTy, Alignment, DL))
21622     return false;
21623 
21624   unsigned NumLoads = getNumInterleavedAccesses(VecTy, DL);
21625 
21626   // A pointer vector can not be the return type of the ldN intrinsics. Need to
21627   // load integer vectors first and then convert to pointer vectors.
21628   if (EltTy->isPointerTy())
21629     VecTy = FixedVectorType::get(DL.getIntPtrType(EltTy), VecTy);
21630 
21631   IRBuilder<> Builder(LI);
21632 
21633   // The base address of the load.
21634   Value *BaseAddr = LI->getPointerOperand();
21635 
21636   if (NumLoads > 1) {
21637     // If we're going to generate more than one load, reset the sub-vector type
21638     // to something legal.
21639     VecTy = FixedVectorType::get(VecTy->getElementType(),
21640                                  VecTy->getNumElements() / NumLoads);
21641   }
21642 
21643   assert(isTypeLegal(EVT::getEVT(VecTy)) && "Illegal vldN vector type!");
21644 
21645   auto createLoadIntrinsic = [&](Value *BaseAddr) {
21646     if (Subtarget->hasNEON()) {
21647       Type *PtrTy = Builder.getPtrTy(LI->getPointerAddressSpace());
21648       Type *Tys[] = {VecTy, PtrTy};
21649       static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2,
21650                                                 Intrinsic::arm_neon_vld3,
21651                                                 Intrinsic::arm_neon_vld4};
21652 
21653       SmallVector<Value *, 2> Ops;
21654       Ops.push_back(BaseAddr);
21655       Ops.push_back(Builder.getInt32(LI->getAlign().value()));
21656 
21657       return Builder.CreateIntrinsic(LoadInts[Factor - 2], Tys, Ops,
21658                                      /*FMFSource=*/nullptr, "vldN");
21659     } else {
21660       assert((Factor == 2 || Factor == 4) &&
21661              "expected interleave factor of 2 or 4 for MVE");
21662       Intrinsic::ID LoadInts =
21663           Factor == 2 ? Intrinsic::arm_mve_vld2q : Intrinsic::arm_mve_vld4q;
21664       Type *PtrTy = Builder.getPtrTy(LI->getPointerAddressSpace());
21665       Type *Tys[] = {VecTy, PtrTy};
21666 
21667       SmallVector<Value *, 2> Ops;
21668       Ops.push_back(BaseAddr);
21669       return Builder.CreateIntrinsic(LoadInts, Tys, Ops, /*FMFSource=*/nullptr,
21670                                      "vldN");
21671     }
21672   };
21673 
21674   // Holds sub-vectors extracted from the load intrinsic return values. The
21675   // sub-vectors are associated with the shufflevector instructions they will
21676   // replace.
21677   DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs;
21678 
21679   for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) {
21680     // If we're generating more than one load, compute the base address of
21681     // subsequent loads as an offset from the previous.
21682     if (LoadCount > 0)
21683       BaseAddr = Builder.CreateConstGEP1_32(VecTy->getElementType(), BaseAddr,
21684                                             VecTy->getNumElements() * Factor);
21685 
21686     CallInst *VldN = createLoadIntrinsic(BaseAddr);
21687 
21688     // Replace uses of each shufflevector with the corresponding vector loaded
21689     // by ldN.
21690     for (unsigned i = 0; i < Shuffles.size(); i++) {
21691       ShuffleVectorInst *SV = Shuffles[i];
21692       unsigned Index = Indices[i];
21693 
21694       Value *SubVec = Builder.CreateExtractValue(VldN, Index);
21695 
21696       // Convert the integer vector to pointer vector if the element is pointer.
21697       if (EltTy->isPointerTy())
21698         SubVec = Builder.CreateIntToPtr(
21699             SubVec,
21700             FixedVectorType::get(SV->getType()->getElementType(), VecTy));
21701 
21702       SubVecs[SV].push_back(SubVec);
21703     }
21704   }
21705 
21706   // Replace uses of the shufflevector instructions with the sub-vectors
21707   // returned by the load intrinsic. If a shufflevector instruction is
21708   // associated with more than one sub-vector, those sub-vectors will be
21709   // concatenated into a single wide vector.
21710   for (ShuffleVectorInst *SVI : Shuffles) {
21711     auto &SubVec = SubVecs[SVI];
21712     auto *WideVec =
21713         SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0];
21714     SVI->replaceAllUsesWith(WideVec);
21715   }
21716 
21717   return true;
21718 }
21719 
21720 /// Lower an interleaved store into a vstN intrinsic.
21721 ///
21722 /// E.g. Lower an interleaved store (Factor = 3):
21723 ///        %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
21724 ///                                  <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
21725 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4
21726 ///
21727 ///      Into:
21728 ///        %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
21729 ///        %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
21730 ///        %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
21731 ///        call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
21732 ///
21733 /// Note that the new shufflevectors will be removed and we'll only generate one
21734 /// vst3 instruction in CodeGen.
21735 ///
21736 /// Example for a more general valid mask (Factor 3). Lower:
21737 ///        %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1,
21738 ///                 <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19>
21739 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr
21740 ///
21741 ///      Into:
21742 ///        %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7>
21743 ///        %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35>
21744 ///        %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19>
21745 ///        call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
lowerInterleavedStore(StoreInst * SI,ShuffleVectorInst * SVI,unsigned Factor) const21746 bool ARMTargetLowering::lowerInterleavedStore(StoreInst *SI,
21747                                               ShuffleVectorInst *SVI,
21748                                               unsigned Factor) const {
21749   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
21750          "Invalid interleave factor");
21751 
21752   auto *VecTy = cast<FixedVectorType>(SVI->getType());
21753   assert(VecTy->getNumElements() % Factor == 0 && "Invalid interleaved store");
21754 
21755   unsigned LaneLen = VecTy->getNumElements() / Factor;
21756   Type *EltTy = VecTy->getElementType();
21757   auto *SubVecTy = FixedVectorType::get(EltTy, LaneLen);
21758 
21759   const DataLayout &DL = SI->getDataLayout();
21760   Align Alignment = SI->getAlign();
21761 
21762   // Skip if we do not have NEON and skip illegal vector types. We can
21763   // "legalize" wide vector types into multiple interleaved accesses as long as
21764   // the vector types are divisible by 128.
21765   if (!isLegalInterleavedAccessType(Factor, SubVecTy, Alignment, DL))
21766     return false;
21767 
21768   unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL);
21769 
21770   Value *Op0 = SVI->getOperand(0);
21771   Value *Op1 = SVI->getOperand(1);
21772   IRBuilder<> Builder(SI);
21773 
21774   // StN intrinsics don't support pointer vectors as arguments. Convert pointer
21775   // vectors to integer vectors.
21776   if (EltTy->isPointerTy()) {
21777     Type *IntTy = DL.getIntPtrType(EltTy);
21778 
21779     // Convert to the corresponding integer vector.
21780     auto *IntVecTy =
21781         FixedVectorType::get(IntTy, cast<FixedVectorType>(Op0->getType()));
21782     Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
21783     Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
21784 
21785     SubVecTy = FixedVectorType::get(IntTy, LaneLen);
21786   }
21787 
21788   // The base address of the store.
21789   Value *BaseAddr = SI->getPointerOperand();
21790 
21791   if (NumStores > 1) {
21792     // If we're going to generate more than one store, reset the lane length
21793     // and sub-vector type to something legal.
21794     LaneLen /= NumStores;
21795     SubVecTy = FixedVectorType::get(SubVecTy->getElementType(), LaneLen);
21796   }
21797 
21798   assert(isTypeLegal(EVT::getEVT(SubVecTy)) && "Illegal vstN vector type!");
21799 
21800   auto Mask = SVI->getShuffleMask();
21801 
21802   auto createStoreIntrinsic = [&](Value *BaseAddr,
21803                                   SmallVectorImpl<Value *> &Shuffles) {
21804     if (Subtarget->hasNEON()) {
21805       static const Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2,
21806                                                  Intrinsic::arm_neon_vst3,
21807                                                  Intrinsic::arm_neon_vst4};
21808       Type *PtrTy = Builder.getPtrTy(SI->getPointerAddressSpace());
21809       Type *Tys[] = {PtrTy, SubVecTy};
21810 
21811       SmallVector<Value *, 6> Ops;
21812       Ops.push_back(BaseAddr);
21813       append_range(Ops, Shuffles);
21814       Ops.push_back(Builder.getInt32(SI->getAlign().value()));
21815       Builder.CreateIntrinsic(StoreInts[Factor - 2], Tys, Ops);
21816     } else {
21817       assert((Factor == 2 || Factor == 4) &&
21818              "expected interleave factor of 2 or 4 for MVE");
21819       Intrinsic::ID StoreInts =
21820           Factor == 2 ? Intrinsic::arm_mve_vst2q : Intrinsic::arm_mve_vst4q;
21821       Type *PtrTy = Builder.getPtrTy(SI->getPointerAddressSpace());
21822       Type *Tys[] = {PtrTy, SubVecTy};
21823 
21824       SmallVector<Value *, 6> Ops;
21825       Ops.push_back(BaseAddr);
21826       append_range(Ops, Shuffles);
21827       for (unsigned F = 0; F < Factor; F++) {
21828         Ops.push_back(Builder.getInt32(F));
21829         Builder.CreateIntrinsic(StoreInts, Tys, Ops);
21830         Ops.pop_back();
21831       }
21832     }
21833   };
21834 
21835   for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) {
21836     // If we generating more than one store, we compute the base address of
21837     // subsequent stores as an offset from the previous.
21838     if (StoreCount > 0)
21839       BaseAddr = Builder.CreateConstGEP1_32(SubVecTy->getElementType(),
21840                                             BaseAddr, LaneLen * Factor);
21841 
21842     SmallVector<Value *, 4> Shuffles;
21843 
21844     // Split the shufflevector operands into sub vectors for the new vstN call.
21845     for (unsigned i = 0; i < Factor; i++) {
21846       unsigned IdxI = StoreCount * LaneLen * Factor + i;
21847       if (Mask[IdxI] >= 0) {
21848         Shuffles.push_back(Builder.CreateShuffleVector(
21849             Op0, Op1, createSequentialMask(Mask[IdxI], LaneLen, 0)));
21850       } else {
21851         unsigned StartMask = 0;
21852         for (unsigned j = 1; j < LaneLen; j++) {
21853           unsigned IdxJ = StoreCount * LaneLen * Factor + j;
21854           if (Mask[IdxJ * Factor + IdxI] >= 0) {
21855             StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ;
21856             break;
21857           }
21858         }
21859         // Note: If all elements in a chunk are undefs, StartMask=0!
21860         // Note: Filling undef gaps with random elements is ok, since
21861         // those elements were being written anyway (with undefs).
21862         // In the case of all undefs we're defaulting to using elems from 0
21863         // Note: StartMask cannot be negative, it's checked in
21864         // isReInterleaveMask
21865         Shuffles.push_back(Builder.CreateShuffleVector(
21866             Op0, Op1, createSequentialMask(StartMask, LaneLen, 0)));
21867       }
21868     }
21869 
21870     createStoreIntrinsic(BaseAddr, Shuffles);
21871   }
21872   return true;
21873 }
21874 
21875 enum HABaseType {
21876   HA_UNKNOWN = 0,
21877   HA_FLOAT,
21878   HA_DOUBLE,
21879   HA_VECT64,
21880   HA_VECT128
21881 };
21882 
isHomogeneousAggregate(Type * Ty,HABaseType & Base,uint64_t & Members)21883 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
21884                                    uint64_t &Members) {
21885   if (auto *ST = dyn_cast<StructType>(Ty)) {
21886     for (unsigned i = 0; i < ST->getNumElements(); ++i) {
21887       uint64_t SubMembers = 0;
21888       if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
21889         return false;
21890       Members += SubMembers;
21891     }
21892   } else if (auto *AT = dyn_cast<ArrayType>(Ty)) {
21893     uint64_t SubMembers = 0;
21894     if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
21895       return false;
21896     Members += SubMembers * AT->getNumElements();
21897   } else if (Ty->isFloatTy()) {
21898     if (Base != HA_UNKNOWN && Base != HA_FLOAT)
21899       return false;
21900     Members = 1;
21901     Base = HA_FLOAT;
21902   } else if (Ty->isDoubleTy()) {
21903     if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
21904       return false;
21905     Members = 1;
21906     Base = HA_DOUBLE;
21907   } else if (auto *VT = dyn_cast<VectorType>(Ty)) {
21908     Members = 1;
21909     switch (Base) {
21910     case HA_FLOAT:
21911     case HA_DOUBLE:
21912       return false;
21913     case HA_VECT64:
21914       return VT->getPrimitiveSizeInBits().getFixedValue() == 64;
21915     case HA_VECT128:
21916       return VT->getPrimitiveSizeInBits().getFixedValue() == 128;
21917     case HA_UNKNOWN:
21918       switch (VT->getPrimitiveSizeInBits().getFixedValue()) {
21919       case 64:
21920         Base = HA_VECT64;
21921         return true;
21922       case 128:
21923         Base = HA_VECT128;
21924         return true;
21925       default:
21926         return false;
21927       }
21928     }
21929   }
21930 
21931   return (Members > 0 && Members <= 4);
21932 }
21933 
21934 /// Return the correct alignment for the current calling convention.
getABIAlignmentForCallingConv(Type * ArgTy,const DataLayout & DL) const21935 Align ARMTargetLowering::getABIAlignmentForCallingConv(
21936     Type *ArgTy, const DataLayout &DL) const {
21937   const Align ABITypeAlign = DL.getABITypeAlign(ArgTy);
21938   if (!ArgTy->isVectorTy())
21939     return ABITypeAlign;
21940 
21941   // Avoid over-aligning vector parameters. It would require realigning the
21942   // stack and waste space for no real benefit.
21943   MaybeAlign StackAlign = DL.getStackAlignment();
21944   assert(StackAlign && "data layout string is missing stack alignment");
21945   return std::min(ABITypeAlign, *StackAlign);
21946 }
21947 
21948 /// Return true if a type is an AAPCS-VFP homogeneous aggregate or one of
21949 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when
21950 /// passing according to AAPCS rules.
functionArgumentNeedsConsecutiveRegisters(Type * Ty,CallingConv::ID CallConv,bool isVarArg,const DataLayout & DL) const21951 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
21952     Type *Ty, CallingConv::ID CallConv, bool isVarArg,
21953     const DataLayout &DL) const {
21954   if (getEffectiveCallingConv(CallConv, isVarArg) !=
21955       CallingConv::ARM_AAPCS_VFP)
21956     return false;
21957 
21958   HABaseType Base = HA_UNKNOWN;
21959   uint64_t Members = 0;
21960   bool IsHA = isHomogeneousAggregate(Ty, Base, Members);
21961   LLVM_DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump());
21962 
21963   bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy();
21964   return IsHA || IsIntArray;
21965 }
21966 
getExceptionPointerRegister(const Constant * PersonalityFn) const21967 Register ARMTargetLowering::getExceptionPointerRegister(
21968     const Constant *PersonalityFn) const {
21969   // Platforms which do not use SjLj EH may return values in these registers
21970   // via the personality function.
21971   ExceptionHandling EM = getTargetMachine().getExceptionModel();
21972   return EM == ExceptionHandling::SjLj ? Register() : ARM::R0;
21973 }
21974 
getExceptionSelectorRegister(const Constant * PersonalityFn) const21975 Register ARMTargetLowering::getExceptionSelectorRegister(
21976     const Constant *PersonalityFn) const {
21977   // Platforms which do not use SjLj EH may return values in these registers
21978   // via the personality function.
21979   ExceptionHandling EM = getTargetMachine().getExceptionModel();
21980   return EM == ExceptionHandling::SjLj ? Register() : ARM::R1;
21981 }
21982 
initializeSplitCSR(MachineBasicBlock * Entry) const21983 void ARMTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
21984   // Update IsSplitCSR in ARMFunctionInfo.
21985   ARMFunctionInfo *AFI = Entry->getParent()->getInfo<ARMFunctionInfo>();
21986   AFI->setIsSplitCSR(true);
21987 }
21988 
insertCopiesSplitCSR(MachineBasicBlock * Entry,const SmallVectorImpl<MachineBasicBlock * > & Exits) const21989 void ARMTargetLowering::insertCopiesSplitCSR(
21990     MachineBasicBlock *Entry,
21991     const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
21992   const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
21993   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
21994   if (!IStart)
21995     return;
21996 
21997   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21998   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
21999   MachineBasicBlock::iterator MBBI = Entry->begin();
22000   for (const MCPhysReg *I = IStart; *I; ++I) {
22001     const TargetRegisterClass *RC = nullptr;
22002     if (ARM::GPRRegClass.contains(*I))
22003       RC = &ARM::GPRRegClass;
22004     else if (ARM::DPRRegClass.contains(*I))
22005       RC = &ARM::DPRRegClass;
22006     else
22007       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
22008 
22009     Register NewVR = MRI->createVirtualRegister(RC);
22010     // Create copy from CSR to a virtual register.
22011     // FIXME: this currently does not emit CFI pseudo-instructions, it works
22012     // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
22013     // nounwind. If we want to generalize this later, we may need to emit
22014     // CFI pseudo-instructions.
22015     assert(Entry->getParent()->getFunction().hasFnAttribute(
22016                Attribute::NoUnwind) &&
22017            "Function should be nounwind in insertCopiesSplitCSR!");
22018     Entry->addLiveIn(*I);
22019     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
22020         .addReg(*I);
22021 
22022     // Insert the copy-back instructions right before the terminator.
22023     for (auto *Exit : Exits)
22024       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
22025               TII->get(TargetOpcode::COPY), *I)
22026           .addReg(NewVR);
22027   }
22028 }
22029 
finalizeLowering(MachineFunction & MF) const22030 void ARMTargetLowering::finalizeLowering(MachineFunction &MF) const {
22031   MF.getFrameInfo().computeMaxCallFrameSize(MF);
22032   TargetLoweringBase::finalizeLowering(MF);
22033 }
22034 
isComplexDeinterleavingSupported() const22035 bool ARMTargetLowering::isComplexDeinterleavingSupported() const {
22036   return Subtarget->hasMVEIntegerOps();
22037 }
22038 
isComplexDeinterleavingOperationSupported(ComplexDeinterleavingOperation Operation,Type * Ty) const22039 bool ARMTargetLowering::isComplexDeinterleavingOperationSupported(
22040     ComplexDeinterleavingOperation Operation, Type *Ty) const {
22041   auto *VTy = dyn_cast<FixedVectorType>(Ty);
22042   if (!VTy)
22043     return false;
22044 
22045   auto *ScalarTy = VTy->getScalarType();
22046   unsigned NumElements = VTy->getNumElements();
22047 
22048   unsigned VTyWidth = VTy->getScalarSizeInBits() * NumElements;
22049   if (VTyWidth < 128 || !llvm::isPowerOf2_32(VTyWidth))
22050     return false;
22051 
22052   // Both VCADD and VCMUL/VCMLA support the same types, F16 and F32
22053   if (ScalarTy->isHalfTy() || ScalarTy->isFloatTy())
22054     return Subtarget->hasMVEFloatOps();
22055 
22056   if (Operation != ComplexDeinterleavingOperation::CAdd)
22057     return false;
22058 
22059   return Subtarget->hasMVEIntegerOps() &&
22060          (ScalarTy->isIntegerTy(8) || ScalarTy->isIntegerTy(16) ||
22061           ScalarTy->isIntegerTy(32));
22062 }
22063 
createComplexDeinterleavingIR(IRBuilderBase & B,ComplexDeinterleavingOperation OperationType,ComplexDeinterleavingRotation Rotation,Value * InputA,Value * InputB,Value * Accumulator) const22064 Value *ARMTargetLowering::createComplexDeinterleavingIR(
22065     IRBuilderBase &B, ComplexDeinterleavingOperation OperationType,
22066     ComplexDeinterleavingRotation Rotation, Value *InputA, Value *InputB,
22067     Value *Accumulator) const {
22068 
22069   FixedVectorType *Ty = cast<FixedVectorType>(InputA->getType());
22070 
22071   unsigned TyWidth = Ty->getScalarSizeInBits() * Ty->getNumElements();
22072 
22073   assert(TyWidth >= 128 && "Width of vector type must be at least 128 bits");
22074 
22075   if (TyWidth > 128) {
22076     int Stride = Ty->getNumElements() / 2;
22077     auto SplitSeq = llvm::seq<int>(0, Ty->getNumElements());
22078     auto SplitSeqVec = llvm::to_vector(SplitSeq);
22079     ArrayRef<int> LowerSplitMask(&SplitSeqVec[0], Stride);
22080     ArrayRef<int> UpperSplitMask(&SplitSeqVec[Stride], Stride);
22081 
22082     auto *LowerSplitA = B.CreateShuffleVector(InputA, LowerSplitMask);
22083     auto *LowerSplitB = B.CreateShuffleVector(InputB, LowerSplitMask);
22084     auto *UpperSplitA = B.CreateShuffleVector(InputA, UpperSplitMask);
22085     auto *UpperSplitB = B.CreateShuffleVector(InputB, UpperSplitMask);
22086     Value *LowerSplitAcc = nullptr;
22087     Value *UpperSplitAcc = nullptr;
22088 
22089     if (Accumulator) {
22090       LowerSplitAcc = B.CreateShuffleVector(Accumulator, LowerSplitMask);
22091       UpperSplitAcc = B.CreateShuffleVector(Accumulator, UpperSplitMask);
22092     }
22093 
22094     auto *LowerSplitInt = createComplexDeinterleavingIR(
22095         B, OperationType, Rotation, LowerSplitA, LowerSplitB, LowerSplitAcc);
22096     auto *UpperSplitInt = createComplexDeinterleavingIR(
22097         B, OperationType, Rotation, UpperSplitA, UpperSplitB, UpperSplitAcc);
22098 
22099     ArrayRef<int> JoinMask(&SplitSeqVec[0], Ty->getNumElements());
22100     return B.CreateShuffleVector(LowerSplitInt, UpperSplitInt, JoinMask);
22101   }
22102 
22103   auto *IntTy = Type::getInt32Ty(B.getContext());
22104 
22105   ConstantInt *ConstRotation = nullptr;
22106   if (OperationType == ComplexDeinterleavingOperation::CMulPartial) {
22107     ConstRotation = ConstantInt::get(IntTy, (int)Rotation);
22108 
22109     if (Accumulator)
22110       return B.CreateIntrinsic(Intrinsic::arm_mve_vcmlaq, Ty,
22111                                {ConstRotation, Accumulator, InputB, InputA});
22112     return B.CreateIntrinsic(Intrinsic::arm_mve_vcmulq, Ty,
22113                              {ConstRotation, InputB, InputA});
22114   }
22115 
22116   if (OperationType == ComplexDeinterleavingOperation::CAdd) {
22117     // 1 means the value is not halved.
22118     auto *ConstHalving = ConstantInt::get(IntTy, 1);
22119 
22120     if (Rotation == ComplexDeinterleavingRotation::Rotation_90)
22121       ConstRotation = ConstantInt::get(IntTy, 0);
22122     else if (Rotation == ComplexDeinterleavingRotation::Rotation_270)
22123       ConstRotation = ConstantInt::get(IntTy, 1);
22124 
22125     if (!ConstRotation)
22126       return nullptr; // Invalid rotation for arm_mve_vcaddq
22127 
22128     return B.CreateIntrinsic(Intrinsic::arm_mve_vcaddq, Ty,
22129                              {ConstHalving, ConstRotation, InputA, InputB});
22130   }
22131 
22132   return nullptr;
22133 }
22134