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/MachineValueType.h"
57#include "llvm/CodeGen/RuntimeLibcalls.h"
58#include "llvm/CodeGen/SelectionDAG.h"
59#include "llvm/CodeGen/SelectionDAGAddressAnalysis.h"
60#include "llvm/CodeGen/SelectionDAGNodes.h"
61#include "llvm/CodeGen/TargetInstrInfo.h"
62#include "llvm/CodeGen/TargetLowering.h"
63#include "llvm/CodeGen/TargetOpcodes.h"
64#include "llvm/CodeGen/TargetRegisterInfo.h"
65#include "llvm/CodeGen/TargetSubtargetInfo.h"
66#include "llvm/CodeGen/ValueTypes.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/PatternMatch.h"
87#include "llvm/IR/Type.h"
88#include "llvm/IR/User.h"
89#include "llvm/IR/Value.h"
90#include "llvm/MC/MCInstrDesc.h"
91#include "llvm/MC/MCInstrItineraries.h"
92#include "llvm/MC/MCRegisterInfo.h"
93#include "llvm/MC/MCSchedule.h"
94#include "llvm/Support/AtomicOrdering.h"
95#include "llvm/Support/BranchProbability.h"
96#include "llvm/Support/Casting.h"
97#include "llvm/Support/CodeGen.h"
98#include "llvm/Support/CommandLine.h"
99#include "llvm/Support/Compiler.h"
100#include "llvm/Support/Debug.h"
101#include "llvm/Support/ErrorHandling.h"
102#include "llvm/Support/KnownBits.h"
103#include "llvm/Support/MathExtras.h"
104#include "llvm/Support/raw_ostream.h"
105#include "llvm/Target/TargetMachine.h"
106#include "llvm/Target/TargetOptions.h"
107#include "llvm/TargetParser/Triple.h"
108#include <algorithm>
109#include <cassert>
110#include <cstdint>
111#include <cstdlib>
112#include <iterator>
113#include <limits>
114#include <optional>
115#include <tuple>
116#include <utility>
117#include <vector>
118
119using namespace llvm;
120using namespace llvm::PatternMatch;
121
122#define DEBUG_TYPE "arm-isel"
123
124STATISTIC(NumTailCalls, "Number of tail calls");
125STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt");
126STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments");
127STATISTIC(NumConstpoolPromoted,
128  "Number of constants with their storage promoted into constant pools");
129
130static cl::opt<bool>
131ARMInterworking("arm-interworking", cl::Hidden,
132  cl::desc("Enable / disable ARM interworking (for debugging only)"),
133  cl::init(true));
134
135static cl::opt<bool> EnableConstpoolPromotion(
136    "arm-promote-constant", cl::Hidden,
137    cl::desc("Enable / disable promotion of unnamed_addr constants into "
138             "constant pools"),
139    cl::init(false)); // FIXME: set to true by default once PR32780 is fixed
140static cl::opt<unsigned> ConstpoolPromotionMaxSize(
141    "arm-promote-constant-max-size", cl::Hidden,
142    cl::desc("Maximum size of constant to promote into a constant pool"),
143    cl::init(64));
144static cl::opt<unsigned> ConstpoolPromotionMaxTotal(
145    "arm-promote-constant-max-total", cl::Hidden,
146    cl::desc("Maximum size of ALL constants to promote into a constant pool"),
147    cl::init(128));
148
149cl::opt<unsigned>
150MVEMaxSupportedInterleaveFactor("mve-max-interleave-factor", cl::Hidden,
151  cl::desc("Maximum interleave factor for MVE VLDn to generate."),
152  cl::init(2));
153
154// The APCS parameter registers.
155static const MCPhysReg GPRArgRegs[] = {
156  ARM::R0, ARM::R1, ARM::R2, ARM::R3
157};
158
159void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT) {
160  if (VT != PromotedLdStVT) {
161    setOperationAction(ISD::LOAD, VT, Promote);
162    AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT);
163
164    setOperationAction(ISD::STORE, VT, Promote);
165    AddPromotedToType (ISD::STORE, VT, PromotedLdStVT);
166  }
167
168  MVT ElemTy = VT.getVectorElementType();
169  if (ElemTy != MVT::f64)
170    setOperationAction(ISD::SETCC, VT, Custom);
171  setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
172  setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
173  if (ElemTy == MVT::i32) {
174    setOperationAction(ISD::SINT_TO_FP, VT, Custom);
175    setOperationAction(ISD::UINT_TO_FP, VT, Custom);
176    setOperationAction(ISD::FP_TO_SINT, VT, Custom);
177    setOperationAction(ISD::FP_TO_UINT, VT, Custom);
178  } else {
179    setOperationAction(ISD::SINT_TO_FP, VT, Expand);
180    setOperationAction(ISD::UINT_TO_FP, VT, Expand);
181    setOperationAction(ISD::FP_TO_SINT, VT, Expand);
182    setOperationAction(ISD::FP_TO_UINT, VT, Expand);
183  }
184  setOperationAction(ISD::BUILD_VECTOR,      VT, Custom);
185  setOperationAction(ISD::VECTOR_SHUFFLE,    VT, Custom);
186  setOperationAction(ISD::CONCAT_VECTORS,    VT, Legal);
187  setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
188  setOperationAction(ISD::SELECT,            VT, Expand);
189  setOperationAction(ISD::SELECT_CC,         VT, Expand);
190  setOperationAction(ISD::VSELECT,           VT, Expand);
191  setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
192  if (VT.isInteger()) {
193    setOperationAction(ISD::SHL, VT, Custom);
194    setOperationAction(ISD::SRA, VT, Custom);
195    setOperationAction(ISD::SRL, VT, Custom);
196  }
197
198  // Neon does not support vector divide/remainder operations.
199  setOperationAction(ISD::SDIV, VT, Expand);
200  setOperationAction(ISD::UDIV, VT, Expand);
201  setOperationAction(ISD::FDIV, VT, Expand);
202  setOperationAction(ISD::SREM, VT, Expand);
203  setOperationAction(ISD::UREM, VT, Expand);
204  setOperationAction(ISD::FREM, VT, Expand);
205  setOperationAction(ISD::SDIVREM, VT, Expand);
206  setOperationAction(ISD::UDIVREM, VT, Expand);
207
208  if (!VT.isFloatingPoint() &&
209      VT != MVT::v2i64 && VT != MVT::v1i64)
210    for (auto Opcode : {ISD::ABS, ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX})
211      setOperationAction(Opcode, VT, Legal);
212  if (!VT.isFloatingPoint())
213    for (auto Opcode : {ISD::SADDSAT, ISD::UADDSAT, ISD::SSUBSAT, ISD::USUBSAT})
214      setOperationAction(Opcode, VT, Legal);
215}
216
217void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
218  addRegisterClass(VT, &ARM::DPRRegClass);
219  addTypeForNEON(VT, MVT::f64);
220}
221
222void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
223  addRegisterClass(VT, &ARM::DPairRegClass);
224  addTypeForNEON(VT, MVT::v2f64);
225}
226
227void ARMTargetLowering::setAllExpand(MVT VT) {
228  for (unsigned Opc = 0; Opc < ISD::BUILTIN_OP_END; ++Opc)
229    setOperationAction(Opc, VT, Expand);
230
231  // We support these really simple operations even on types where all
232  // the actual arithmetic has to be broken down into simpler
233  // operations or turned into library calls.
234  setOperationAction(ISD::BITCAST, VT, Legal);
235  setOperationAction(ISD::LOAD, VT, Legal);
236  setOperationAction(ISD::STORE, VT, Legal);
237  setOperationAction(ISD::UNDEF, VT, Legal);
238}
239
240void ARMTargetLowering::addAllExtLoads(const MVT From, const MVT To,
241                                       LegalizeAction Action) {
242  setLoadExtAction(ISD::EXTLOAD,  From, To, Action);
243  setLoadExtAction(ISD::ZEXTLOAD, From, To, Action);
244  setLoadExtAction(ISD::SEXTLOAD, From, To, Action);
245}
246
247void ARMTargetLowering::addMVEVectorTypes(bool HasMVEFP) {
248  const MVT IntTypes[] = { MVT::v16i8, MVT::v8i16, MVT::v4i32 };
249
250  for (auto VT : IntTypes) {
251    addRegisterClass(VT, &ARM::MQPRRegClass);
252    setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
253    setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
254    setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
255    setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
256    setOperationAction(ISD::SHL, VT, Custom);
257    setOperationAction(ISD::SRA, VT, Custom);
258    setOperationAction(ISD::SRL, VT, Custom);
259    setOperationAction(ISD::SMIN, VT, Legal);
260    setOperationAction(ISD::SMAX, VT, Legal);
261    setOperationAction(ISD::UMIN, VT, Legal);
262    setOperationAction(ISD::UMAX, VT, Legal);
263    setOperationAction(ISD::ABS, VT, Legal);
264    setOperationAction(ISD::SETCC, VT, Custom);
265    setOperationAction(ISD::MLOAD, VT, Custom);
266    setOperationAction(ISD::MSTORE, VT, Legal);
267    setOperationAction(ISD::CTLZ, VT, Legal);
268    setOperationAction(ISD::CTTZ, VT, Custom);
269    setOperationAction(ISD::BITREVERSE, VT, Legal);
270    setOperationAction(ISD::BSWAP, VT, Legal);
271    setOperationAction(ISD::SADDSAT, VT, Legal);
272    setOperationAction(ISD::UADDSAT, VT, Legal);
273    setOperationAction(ISD::SSUBSAT, VT, Legal);
274    setOperationAction(ISD::USUBSAT, VT, Legal);
275    setOperationAction(ISD::ABDS, VT, Legal);
276    setOperationAction(ISD::ABDU, VT, Legal);
277    setOperationAction(ISD::AVGFLOORS, VT, Legal);
278    setOperationAction(ISD::AVGFLOORU, VT, Legal);
279    setOperationAction(ISD::AVGCEILS, VT, Legal);
280    setOperationAction(ISD::AVGCEILU, VT, Legal);
281
282    // No native support for these.
283    setOperationAction(ISD::UDIV, VT, Expand);
284    setOperationAction(ISD::SDIV, VT, Expand);
285    setOperationAction(ISD::UREM, VT, Expand);
286    setOperationAction(ISD::SREM, VT, Expand);
287    setOperationAction(ISD::UDIVREM, VT, Expand);
288    setOperationAction(ISD::SDIVREM, VT, Expand);
289    setOperationAction(ISD::CTPOP, VT, Expand);
290    setOperationAction(ISD::SELECT, VT, Expand);
291    setOperationAction(ISD::SELECT_CC, VT, Expand);
292
293    // Vector reductions
294    setOperationAction(ISD::VECREDUCE_ADD, VT, Legal);
295    setOperationAction(ISD::VECREDUCE_SMAX, VT, Legal);
296    setOperationAction(ISD::VECREDUCE_UMAX, VT, Legal);
297    setOperationAction(ISD::VECREDUCE_SMIN, VT, Legal);
298    setOperationAction(ISD::VECREDUCE_UMIN, VT, Legal);
299    setOperationAction(ISD::VECREDUCE_MUL, VT, Custom);
300    setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
301    setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
302    setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
303
304    if (!HasMVEFP) {
305      setOperationAction(ISD::SINT_TO_FP, VT, Expand);
306      setOperationAction(ISD::UINT_TO_FP, VT, Expand);
307      setOperationAction(ISD::FP_TO_SINT, VT, Expand);
308      setOperationAction(ISD::FP_TO_UINT, VT, Expand);
309    } else {
310      setOperationAction(ISD::FP_TO_SINT_SAT, VT, Custom);
311      setOperationAction(ISD::FP_TO_UINT_SAT, VT, Custom);
312    }
313
314    // Pre and Post inc are supported on loads and stores
315    for (unsigned im = (unsigned)ISD::PRE_INC;
316         im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
317      setIndexedLoadAction(im, VT, Legal);
318      setIndexedStoreAction(im, VT, Legal);
319      setIndexedMaskedLoadAction(im, VT, Legal);
320      setIndexedMaskedStoreAction(im, VT, Legal);
321    }
322  }
323
324  const MVT FloatTypes[] = { MVT::v8f16, MVT::v4f32 };
325  for (auto VT : FloatTypes) {
326    addRegisterClass(VT, &ARM::MQPRRegClass);
327    if (!HasMVEFP)
328      setAllExpand(VT);
329
330    // These are legal or custom whether we have MVE.fp or not
331    setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
332    setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
333    setOperationAction(ISD::INSERT_VECTOR_ELT, VT.getVectorElementType(), Custom);
334    setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
335    setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
336    setOperationAction(ISD::BUILD_VECTOR, VT.getVectorElementType(), Custom);
337    setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Legal);
338    setOperationAction(ISD::SETCC, VT, Custom);
339    setOperationAction(ISD::MLOAD, VT, Custom);
340    setOperationAction(ISD::MSTORE, VT, Legal);
341    setOperationAction(ISD::SELECT, VT, Expand);
342    setOperationAction(ISD::SELECT_CC, VT, Expand);
343
344    // Pre and Post inc are supported on loads and stores
345    for (unsigned im = (unsigned)ISD::PRE_INC;
346         im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
347      setIndexedLoadAction(im, VT, Legal);
348      setIndexedStoreAction(im, VT, Legal);
349      setIndexedMaskedLoadAction(im, VT, Legal);
350      setIndexedMaskedStoreAction(im, VT, Legal);
351    }
352
353    if (HasMVEFP) {
354      setOperationAction(ISD::FMINNUM, VT, Legal);
355      setOperationAction(ISD::FMAXNUM, VT, Legal);
356      setOperationAction(ISD::FROUND, VT, Legal);
357      setOperationAction(ISD::VECREDUCE_FADD, VT, Custom);
358      setOperationAction(ISD::VECREDUCE_FMUL, VT, Custom);
359      setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
360      setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
361
362      // No native support for these.
363      setOperationAction(ISD::FDIV, VT, Expand);
364      setOperationAction(ISD::FREM, VT, Expand);
365      setOperationAction(ISD::FSQRT, VT, Expand);
366      setOperationAction(ISD::FSIN, VT, Expand);
367      setOperationAction(ISD::FCOS, VT, Expand);
368      setOperationAction(ISD::FPOW, VT, Expand);
369      setOperationAction(ISD::FLOG, VT, Expand);
370      setOperationAction(ISD::FLOG2, VT, Expand);
371      setOperationAction(ISD::FLOG10, VT, Expand);
372      setOperationAction(ISD::FEXP, VT, Expand);
373      setOperationAction(ISD::FEXP2, VT, Expand);
374      setOperationAction(ISD::FEXP10, VT, Expand);
375      setOperationAction(ISD::FNEARBYINT, VT, Expand);
376    }
377  }
378
379  // Custom Expand smaller than legal vector reductions to prevent false zero
380  // items being added.
381  setOperationAction(ISD::VECREDUCE_FADD, MVT::v4f16, Custom);
382  setOperationAction(ISD::VECREDUCE_FMUL, MVT::v4f16, Custom);
383  setOperationAction(ISD::VECREDUCE_FMIN, MVT::v4f16, Custom);
384  setOperationAction(ISD::VECREDUCE_FMAX, MVT::v4f16, Custom);
385  setOperationAction(ISD::VECREDUCE_FADD, MVT::v2f16, Custom);
386  setOperationAction(ISD::VECREDUCE_FMUL, MVT::v2f16, Custom);
387  setOperationAction(ISD::VECREDUCE_FMIN, MVT::v2f16, Custom);
388  setOperationAction(ISD::VECREDUCE_FMAX, MVT::v2f16, Custom);
389
390  // We 'support' these types up to bitcast/load/store level, regardless of
391  // MVE integer-only / float support. Only doing FP data processing on the FP
392  // vector types is inhibited at integer-only level.
393  const MVT LongTypes[] = { MVT::v2i64, MVT::v2f64 };
394  for (auto VT : LongTypes) {
395    addRegisterClass(VT, &ARM::MQPRRegClass);
396    setAllExpand(VT);
397    setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
398    setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
399    setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
400    setOperationAction(ISD::VSELECT, VT, Legal);
401    setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
402  }
403  setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal);
404
405  // We can do bitwise operations on v2i64 vectors
406  setOperationAction(ISD::AND, MVT::v2i64, Legal);
407  setOperationAction(ISD::OR, MVT::v2i64, Legal);
408  setOperationAction(ISD::XOR, MVT::v2i64, Legal);
409
410  // It is legal to extload from v4i8 to v4i16 or v4i32.
411  addAllExtLoads(MVT::v8i16, MVT::v8i8, Legal);
412  addAllExtLoads(MVT::v4i32, MVT::v4i16, Legal);
413  addAllExtLoads(MVT::v4i32, MVT::v4i8, Legal);
414
415  // It is legal to sign extend from v4i8/v4i16 to v4i32 or v8i8 to v8i16.
416  setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8,  Legal);
417  setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Legal);
418  setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i32, Legal);
419  setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v8i8,  Legal);
420  setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v8i16, Legal);
421
422  // Some truncating stores are legal too.
423  setTruncStoreAction(MVT::v4i32, MVT::v4i16, Legal);
424  setTruncStoreAction(MVT::v4i32, MVT::v4i8,  Legal);
425  setTruncStoreAction(MVT::v8i16, MVT::v8i8,  Legal);
426
427  // Pre and Post inc on these are legal, given the correct extends
428  for (unsigned im = (unsigned)ISD::PRE_INC;
429       im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
430    for (auto VT : {MVT::v8i8, MVT::v4i8, MVT::v4i16}) {
431      setIndexedLoadAction(im, VT, Legal);
432      setIndexedStoreAction(im, VT, Legal);
433      setIndexedMaskedLoadAction(im, VT, Legal);
434      setIndexedMaskedStoreAction(im, VT, Legal);
435    }
436  }
437
438  // Predicate types
439  const MVT pTypes[] = {MVT::v16i1, MVT::v8i1, MVT::v4i1, MVT::v2i1};
440  for (auto VT : pTypes) {
441    addRegisterClass(VT, &ARM::VCCRRegClass);
442    setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
443    setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
444    setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
445    setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
446    setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
447    setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
448    setOperationAction(ISD::SETCC, VT, Custom);
449    setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
450    setOperationAction(ISD::LOAD, VT, Custom);
451    setOperationAction(ISD::STORE, VT, Custom);
452    setOperationAction(ISD::TRUNCATE, VT, Custom);
453    setOperationAction(ISD::VSELECT, VT, Expand);
454    setOperationAction(ISD::SELECT, VT, Expand);
455    setOperationAction(ISD::SELECT_CC, VT, Expand);
456
457    if (!HasMVEFP) {
458      setOperationAction(ISD::SINT_TO_FP, VT, Expand);
459      setOperationAction(ISD::UINT_TO_FP, VT, Expand);
460      setOperationAction(ISD::FP_TO_SINT, VT, Expand);
461      setOperationAction(ISD::FP_TO_UINT, VT, Expand);
462    }
463  }
464  setOperationAction(ISD::SETCC, MVT::v2i1, Expand);
465  setOperationAction(ISD::TRUNCATE, MVT::v2i1, Expand);
466  setOperationAction(ISD::AND, MVT::v2i1, Expand);
467  setOperationAction(ISD::OR, MVT::v2i1, Expand);
468  setOperationAction(ISD::XOR, MVT::v2i1, Expand);
469  setOperationAction(ISD::SINT_TO_FP, MVT::v2i1, Expand);
470  setOperationAction(ISD::UINT_TO_FP, MVT::v2i1, Expand);
471  setOperationAction(ISD::FP_TO_SINT, MVT::v2i1, Expand);
472  setOperationAction(ISD::FP_TO_UINT, MVT::v2i1, Expand);
473
474  setOperationAction(ISD::SIGN_EXTEND, MVT::v8i32, Custom);
475  setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
476  setOperationAction(ISD::SIGN_EXTEND, MVT::v16i32, Custom);
477  setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32, Custom);
478  setOperationAction(ISD::ZERO_EXTEND, MVT::v16i16, Custom);
479  setOperationAction(ISD::ZERO_EXTEND, MVT::v16i32, Custom);
480  setOperationAction(ISD::TRUNCATE, MVT::v8i32, Custom);
481  setOperationAction(ISD::TRUNCATE, MVT::v16i16, Custom);
482}
483
484ARMTargetLowering::ARMTargetLowering(const TargetMachine &TM,
485                                     const ARMSubtarget &STI)
486    : TargetLowering(TM), Subtarget(&STI) {
487  RegInfo = Subtarget->getRegisterInfo();
488  Itins = Subtarget->getInstrItineraryData();
489
490  setBooleanContents(ZeroOrOneBooleanContent);
491  setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
492
493  if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetIOS() &&
494      !Subtarget->isTargetWatchOS() && !Subtarget->isTargetDriverKit()) {
495    bool IsHFTarget = TM.Options.FloatABIType == FloatABI::Hard;
496    for (int LCID = 0; LCID < RTLIB::UNKNOWN_LIBCALL; ++LCID)
497      setLibcallCallingConv(static_cast<RTLIB::Libcall>(LCID),
498                            IsHFTarget ? CallingConv::ARM_AAPCS_VFP
499                                       : CallingConv::ARM_AAPCS);
500  }
501
502  if (Subtarget->isTargetMachO()) {
503    // Uses VFP for Thumb libfuncs if available.
504    if (Subtarget->isThumb() && Subtarget->hasVFP2Base() &&
505        Subtarget->hasARMOps() && !Subtarget->useSoftFloat()) {
506      static const struct {
507        const RTLIB::Libcall Op;
508        const char * const Name;
509        const ISD::CondCode Cond;
510      } LibraryCalls[] = {
511        // Single-precision floating-point arithmetic.
512        { RTLIB::ADD_F32, "__addsf3vfp", ISD::SETCC_INVALID },
513        { RTLIB::SUB_F32, "__subsf3vfp", ISD::SETCC_INVALID },
514        { RTLIB::MUL_F32, "__mulsf3vfp", ISD::SETCC_INVALID },
515        { RTLIB::DIV_F32, "__divsf3vfp", ISD::SETCC_INVALID },
516
517        // Double-precision floating-point arithmetic.
518        { RTLIB::ADD_F64, "__adddf3vfp", ISD::SETCC_INVALID },
519        { RTLIB::SUB_F64, "__subdf3vfp", ISD::SETCC_INVALID },
520        { RTLIB::MUL_F64, "__muldf3vfp", ISD::SETCC_INVALID },
521        { RTLIB::DIV_F64, "__divdf3vfp", ISD::SETCC_INVALID },
522
523        // Single-precision comparisons.
524        { RTLIB::OEQ_F32, "__eqsf2vfp",    ISD::SETNE },
525        { RTLIB::UNE_F32, "__nesf2vfp",    ISD::SETNE },
526        { RTLIB::OLT_F32, "__ltsf2vfp",    ISD::SETNE },
527        { RTLIB::OLE_F32, "__lesf2vfp",    ISD::SETNE },
528        { RTLIB::OGE_F32, "__gesf2vfp",    ISD::SETNE },
529        { RTLIB::OGT_F32, "__gtsf2vfp",    ISD::SETNE },
530        { RTLIB::UO_F32,  "__unordsf2vfp", ISD::SETNE },
531
532        // Double-precision comparisons.
533        { RTLIB::OEQ_F64, "__eqdf2vfp",    ISD::SETNE },
534        { RTLIB::UNE_F64, "__nedf2vfp",    ISD::SETNE },
535        { RTLIB::OLT_F64, "__ltdf2vfp",    ISD::SETNE },
536        { RTLIB::OLE_F64, "__ledf2vfp",    ISD::SETNE },
537        { RTLIB::OGE_F64, "__gedf2vfp",    ISD::SETNE },
538        { RTLIB::OGT_F64, "__gtdf2vfp",    ISD::SETNE },
539        { RTLIB::UO_F64,  "__unorddf2vfp", ISD::SETNE },
540
541        // Floating-point to integer conversions.
542        // i64 conversions are done via library routines even when generating VFP
543        // instructions, so use the same ones.
544        { RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp",    ISD::SETCC_INVALID },
545        { RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp", ISD::SETCC_INVALID },
546        { RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp",    ISD::SETCC_INVALID },
547        { RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp", ISD::SETCC_INVALID },
548
549        // Conversions between floating types.
550        { RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp",  ISD::SETCC_INVALID },
551        { RTLIB::FPEXT_F32_F64,   "__extendsfdf2vfp", ISD::SETCC_INVALID },
552
553        // Integer to floating-point conversions.
554        // i64 conversions are done via library routines even when generating VFP
555        // instructions, so use the same ones.
556        // FIXME: There appears to be some naming inconsistency in ARM libgcc:
557        // e.g., __floatunsidf vs. __floatunssidfvfp.
558        { RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp",    ISD::SETCC_INVALID },
559        { RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp", ISD::SETCC_INVALID },
560        { RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp",    ISD::SETCC_INVALID },
561        { RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp", ISD::SETCC_INVALID },
562      };
563
564      for (const auto &LC : LibraryCalls) {
565        setLibcallName(LC.Op, LC.Name);
566        if (LC.Cond != ISD::SETCC_INVALID)
567          setCmpLibcallCC(LC.Op, LC.Cond);
568      }
569    }
570  }
571
572  // These libcalls are not available in 32-bit.
573  setLibcallName(RTLIB::SHL_I128, nullptr);
574  setLibcallName(RTLIB::SRL_I128, nullptr);
575  setLibcallName(RTLIB::SRA_I128, nullptr);
576  setLibcallName(RTLIB::MUL_I128, nullptr);
577  setLibcallName(RTLIB::MULO_I64, nullptr);
578  setLibcallName(RTLIB::MULO_I128, nullptr);
579
580  // RTLIB
581  if (Subtarget->isAAPCS_ABI() &&
582      (Subtarget->isTargetAEABI() || Subtarget->isTargetGNUAEABI() ||
583       Subtarget->isTargetMuslAEABI() || Subtarget->isTargetAndroid())) {
584    static const struct {
585      const RTLIB::Libcall Op;
586      const char * const Name;
587      const CallingConv::ID CC;
588      const ISD::CondCode Cond;
589    } LibraryCalls[] = {
590      // Double-precision floating-point arithmetic helper functions
591      // RTABI chapter 4.1.2, Table 2
592      { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
593      { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
594      { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
595      { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
596
597      // Double-precision floating-point comparison helper functions
598      // RTABI chapter 4.1.2, Table 3
599      { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
600      { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
601      { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
602      { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
603      { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
604      { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
605      { RTLIB::UO_F64,  "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
606
607      // Single-precision floating-point arithmetic helper functions
608      // RTABI chapter 4.1.2, Table 4
609      { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
610      { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
611      { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
612      { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
613
614      // Single-precision floating-point comparison helper functions
615      // RTABI chapter 4.1.2, Table 5
616      { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
617      { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
618      { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
619      { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
620      { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
621      { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
622      { RTLIB::UO_F32,  "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
623
624      // Floating-point to integer conversions.
625      // RTABI chapter 4.1.2, Table 6
626      { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
627      { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
628      { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
629      { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
630      { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
631      { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
632      { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
633      { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
634
635      // Conversions between floating types.
636      // RTABI chapter 4.1.2, Table 7
637      { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
638      { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
639      { RTLIB::FPEXT_F32_F64,   "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
640
641      // Integer to floating-point conversions.
642      // RTABI chapter 4.1.2, Table 8
643      { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
644      { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
645      { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
646      { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
647      { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
648      { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
649      { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
650      { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
651
652      // Long long helper functions
653      // RTABI chapter 4.2, Table 9
654      { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
655      { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
656      { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
657      { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
658
659      // Integer division functions
660      // RTABI chapter 4.3.1
661      { RTLIB::SDIV_I8,  "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
662      { RTLIB::SDIV_I16, "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
663      { RTLIB::SDIV_I32, "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
664      { RTLIB::SDIV_I64, "__aeabi_ldivmod",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
665      { RTLIB::UDIV_I8,  "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
666      { RTLIB::UDIV_I16, "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
667      { RTLIB::UDIV_I32, "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
668      { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
669    };
670
671    for (const auto &LC : LibraryCalls) {
672      setLibcallName(LC.Op, LC.Name);
673      setLibcallCallingConv(LC.Op, LC.CC);
674      if (LC.Cond != ISD::SETCC_INVALID)
675        setCmpLibcallCC(LC.Op, LC.Cond);
676    }
677
678    // EABI dependent RTLIB
679    if (TM.Options.EABIVersion == EABI::EABI4 ||
680        TM.Options.EABIVersion == EABI::EABI5) {
681      static const struct {
682        const RTLIB::Libcall Op;
683        const char *const Name;
684        const CallingConv::ID CC;
685        const ISD::CondCode Cond;
686      } MemOpsLibraryCalls[] = {
687        // Memory operations
688        // RTABI chapter 4.3.4
689        { RTLIB::MEMCPY,  "__aeabi_memcpy",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
690        { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
691        { RTLIB::MEMSET,  "__aeabi_memset",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
692      };
693
694      for (const auto &LC : MemOpsLibraryCalls) {
695        setLibcallName(LC.Op, LC.Name);
696        setLibcallCallingConv(LC.Op, LC.CC);
697        if (LC.Cond != ISD::SETCC_INVALID)
698          setCmpLibcallCC(LC.Op, LC.Cond);
699      }
700    }
701  }
702
703  if (Subtarget->isTargetWindows()) {
704    static const struct {
705      const RTLIB::Libcall Op;
706      const char * const Name;
707      const CallingConv::ID CC;
708    } LibraryCalls[] = {
709      { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP },
710      { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP },
711      { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP },
712      { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP },
713      { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP },
714      { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP },
715      { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP },
716      { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP },
717    };
718
719    for (const auto &LC : LibraryCalls) {
720      setLibcallName(LC.Op, LC.Name);
721      setLibcallCallingConv(LC.Op, LC.CC);
722    }
723  }
724
725  // Use divmod compiler-rt calls for iOS 5.0 and later.
726  if (Subtarget->isTargetMachO() &&
727      !(Subtarget->isTargetIOS() &&
728        Subtarget->getTargetTriple().isOSVersionLT(5, 0))) {
729    setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
730    setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
731  }
732
733  // The half <-> float conversion functions are always soft-float on
734  // non-watchos platforms, but are needed for some targets which use a
735  // hard-float calling convention by default.
736  if (!Subtarget->isTargetWatchABI()) {
737    if (Subtarget->isAAPCS_ABI()) {
738      setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS);
739      setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS);
740      setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS);
741    } else {
742      setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS);
743      setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS);
744      setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS);
745    }
746  }
747
748  // In EABI, these functions have an __aeabi_ prefix, but in GNUEABI they have
749  // a __gnu_ prefix (which is the default).
750  if (Subtarget->isTargetAEABI()) {
751    static const struct {
752      const RTLIB::Libcall Op;
753      const char * const Name;
754      const CallingConv::ID CC;
755    } LibraryCalls[] = {
756      { RTLIB::FPROUND_F32_F16, "__aeabi_f2h", CallingConv::ARM_AAPCS },
757      { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS },
758      { RTLIB::FPEXT_F16_F32, "__aeabi_h2f", CallingConv::ARM_AAPCS },
759    };
760
761    for (const auto &LC : LibraryCalls) {
762      setLibcallName(LC.Op, LC.Name);
763      setLibcallCallingConv(LC.Op, LC.CC);
764    }
765  }
766
767  if (Subtarget->isThumb1Only())
768    addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
769  else
770    addRegisterClass(MVT::i32, &ARM::GPRRegClass);
771
772  if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only() &&
773      Subtarget->hasFPRegs()) {
774    addRegisterClass(MVT::f32, &ARM::SPRRegClass);
775    addRegisterClass(MVT::f64, &ARM::DPRRegClass);
776
777    setOperationAction(ISD::FP_TO_SINT_SAT, MVT::i32, Custom);
778    setOperationAction(ISD::FP_TO_UINT_SAT, MVT::i32, Custom);
779    setOperationAction(ISD::FP_TO_SINT_SAT, MVT::i64, Custom);
780    setOperationAction(ISD::FP_TO_UINT_SAT, MVT::i64, Custom);
781
782    if (!Subtarget->hasVFP2Base())
783      setAllExpand(MVT::f32);
784    if (!Subtarget->hasFP64())
785      setAllExpand(MVT::f64);
786  }
787
788  if (Subtarget->hasFullFP16()) {
789    addRegisterClass(MVT::f16, &ARM::HPRRegClass);
790    setOperationAction(ISD::BITCAST, MVT::i16, Custom);
791    setOperationAction(ISD::BITCAST, MVT::f16, Custom);
792
793    setOperationAction(ISD::FMINNUM, MVT::f16, Legal);
794    setOperationAction(ISD::FMAXNUM, MVT::f16, Legal);
795  }
796
797  if (Subtarget->hasBF16()) {
798    addRegisterClass(MVT::bf16, &ARM::HPRRegClass);
799    setAllExpand(MVT::bf16);
800    if (!Subtarget->hasFullFP16())
801      setOperationAction(ISD::BITCAST, MVT::bf16, Custom);
802  }
803
804  for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
805    for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) {
806      setTruncStoreAction(VT, InnerVT, Expand);
807      addAllExtLoads(VT, InnerVT, Expand);
808    }
809
810    setOperationAction(ISD::SMUL_LOHI, VT, Expand);
811    setOperationAction(ISD::UMUL_LOHI, VT, Expand);
812
813    setOperationAction(ISD::BSWAP, VT, Expand);
814  }
815
816  setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
817  setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
818
819  setOperationAction(ISD::READ_REGISTER, MVT::i64, Custom);
820  setOperationAction(ISD::WRITE_REGISTER, MVT::i64, Custom);
821
822  if (Subtarget->hasMVEIntegerOps())
823    addMVEVectorTypes(Subtarget->hasMVEFloatOps());
824
825  // Combine low-overhead loop intrinsics so that we can lower i1 types.
826  if (Subtarget->hasLOB()) {
827    setTargetDAGCombine({ISD::BRCOND, ISD::BR_CC});
828  }
829
830  if (Subtarget->hasNEON()) {
831    addDRTypeForNEON(MVT::v2f32);
832    addDRTypeForNEON(MVT::v8i8);
833    addDRTypeForNEON(MVT::v4i16);
834    addDRTypeForNEON(MVT::v2i32);
835    addDRTypeForNEON(MVT::v1i64);
836
837    addQRTypeForNEON(MVT::v4f32);
838    addQRTypeForNEON(MVT::v2f64);
839    addQRTypeForNEON(MVT::v16i8);
840    addQRTypeForNEON(MVT::v8i16);
841    addQRTypeForNEON(MVT::v4i32);
842    addQRTypeForNEON(MVT::v2i64);
843
844    if (Subtarget->hasFullFP16()) {
845      addQRTypeForNEON(MVT::v8f16);
846      addDRTypeForNEON(MVT::v4f16);
847    }
848
849    if (Subtarget->hasBF16()) {
850      addQRTypeForNEON(MVT::v8bf16);
851      addDRTypeForNEON(MVT::v4bf16);
852    }
853  }
854
855  if (Subtarget->hasMVEIntegerOps() || Subtarget->hasNEON()) {
856    // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
857    // none of Neon, MVE or VFP supports any arithmetic operations on it.
858    setOperationAction(ISD::FADD, MVT::v2f64, Expand);
859    setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
860    setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
861    // FIXME: Code duplication: FDIV and FREM are expanded always, see
862    // ARMTargetLowering::addTypeForNEON method for details.
863    setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
864    setOperationAction(ISD::FREM, MVT::v2f64, Expand);
865    // FIXME: Create unittest.
866    // In another words, find a way when "copysign" appears in DAG with vector
867    // operands.
868    setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
869    // FIXME: Code duplication: SETCC has custom operation action, see
870    // ARMTargetLowering::addTypeForNEON method for details.
871    setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
872    // FIXME: Create unittest for FNEG and for FABS.
873    setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
874    setOperationAction(ISD::FABS, MVT::v2f64, Expand);
875    setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
876    setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
877    setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
878    setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
879    setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
880    setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
881    setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
882    setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
883    setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
884    setOperationAction(ISD::FEXP10, MVT::v2f64, Expand);
885    // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
886    setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
887    setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
888    setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
889    setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
890    setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
891    setOperationAction(ISD::FMA, MVT::v2f64, Expand);
892  }
893
894  if (Subtarget->hasNEON()) {
895    // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
896    // supported for v4f32.
897    setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
898    setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
899    setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
900    setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
901    setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
902    setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
903    setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
904    setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
905    setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
906    setOperationAction(ISD::FEXP10, MVT::v4f32, Expand);
907    setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
908    setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
909    setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
910    setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
911    setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
912
913    // Mark v2f32 intrinsics.
914    setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
915    setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
916    setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
917    setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
918    setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
919    setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
920    setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
921    setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
922    setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
923    setOperationAction(ISD::FEXP10, MVT::v2f32, Expand);
924    setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
925    setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
926    setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
927    setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
928    setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
929
930    // Neon does not support some operations on v1i64 and v2i64 types.
931    setOperationAction(ISD::MUL, MVT::v1i64, Expand);
932    // Custom handling for some quad-vector types to detect VMULL.
933    setOperationAction(ISD::MUL, MVT::v8i16, Custom);
934    setOperationAction(ISD::MUL, MVT::v4i32, Custom);
935    setOperationAction(ISD::MUL, MVT::v2i64, Custom);
936    // Custom handling for some vector types to avoid expensive expansions
937    setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
938    setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
939    setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
940    setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
941    // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
942    // a destination type that is wider than the source, and nor does
943    // it have a FP_TO_[SU]INT instruction with a narrower destination than
944    // source.
945    setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
946    setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Custom);
947    setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
948    setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
949    setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
950    setOperationAction(ISD::FP_TO_UINT, MVT::v8i16, Custom);
951    setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
952    setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Custom);
953
954    setOperationAction(ISD::FP_ROUND,   MVT::v2f32, Expand);
955    setOperationAction(ISD::FP_EXTEND,  MVT::v2f64, Expand);
956
957    // NEON does not have single instruction CTPOP for vectors with element
958    // types wider than 8-bits.  However, custom lowering can leverage the
959    // v8i8/v16i8 vcnt instruction.
960    setOperationAction(ISD::CTPOP,      MVT::v2i32, Custom);
961    setOperationAction(ISD::CTPOP,      MVT::v4i32, Custom);
962    setOperationAction(ISD::CTPOP,      MVT::v4i16, Custom);
963    setOperationAction(ISD::CTPOP,      MVT::v8i16, Custom);
964    setOperationAction(ISD::CTPOP,      MVT::v1i64, Custom);
965    setOperationAction(ISD::CTPOP,      MVT::v2i64, Custom);
966
967    setOperationAction(ISD::CTLZ,       MVT::v1i64, Expand);
968    setOperationAction(ISD::CTLZ,       MVT::v2i64, Expand);
969
970    // NEON does not have single instruction CTTZ for vectors.
971    setOperationAction(ISD::CTTZ, MVT::v8i8, Custom);
972    setOperationAction(ISD::CTTZ, MVT::v4i16, Custom);
973    setOperationAction(ISD::CTTZ, MVT::v2i32, Custom);
974    setOperationAction(ISD::CTTZ, MVT::v1i64, Custom);
975
976    setOperationAction(ISD::CTTZ, MVT::v16i8, Custom);
977    setOperationAction(ISD::CTTZ, MVT::v8i16, Custom);
978    setOperationAction(ISD::CTTZ, MVT::v4i32, Custom);
979    setOperationAction(ISD::CTTZ, MVT::v2i64, Custom);
980
981    setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i8, Custom);
982    setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i16, Custom);
983    setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i32, Custom);
984    setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v1i64, Custom);
985
986    setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i8, Custom);
987    setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i16, Custom);
988    setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i32, Custom);
989    setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i64, Custom);
990
991    for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
992      setOperationAction(ISD::MULHS, VT, Expand);
993      setOperationAction(ISD::MULHU, VT, Expand);
994    }
995
996    // NEON only has FMA instructions as of VFP4.
997    if (!Subtarget->hasVFP4Base()) {
998      setOperationAction(ISD::FMA, MVT::v2f32, Expand);
999      setOperationAction(ISD::FMA, MVT::v4f32, Expand);
1000    }
1001
1002    setTargetDAGCombine({ISD::SHL, ISD::SRL, ISD::SRA, ISD::FP_TO_SINT,
1003                         ISD::FP_TO_UINT, ISD::FDIV, ISD::LOAD});
1004
1005    // It is legal to extload from v4i8 to v4i16 or v4i32.
1006    for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16,
1007                   MVT::v2i32}) {
1008      for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) {
1009        setLoadExtAction(ISD::EXTLOAD, VT, Ty, Legal);
1010        setLoadExtAction(ISD::ZEXTLOAD, VT, Ty, Legal);
1011        setLoadExtAction(ISD::SEXTLOAD, VT, Ty, Legal);
1012      }
1013    }
1014
1015    for (auto VT : {MVT::v8i8, MVT::v4i16, MVT::v2i32, MVT::v16i8, MVT::v8i16,
1016                    MVT::v4i32}) {
1017      setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom);
1018      setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom);
1019      setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom);
1020      setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom);
1021    }
1022  }
1023
1024  if (Subtarget->hasNEON() || Subtarget->hasMVEIntegerOps()) {
1025    setTargetDAGCombine(
1026        {ISD::BUILD_VECTOR, ISD::VECTOR_SHUFFLE, ISD::INSERT_SUBVECTOR,
1027         ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT,
1028         ISD::SIGN_EXTEND_INREG, ISD::STORE, ISD::SIGN_EXTEND, ISD::ZERO_EXTEND,
1029         ISD::ANY_EXTEND, ISD::INTRINSIC_WO_CHAIN, ISD::INTRINSIC_W_CHAIN,
1030         ISD::INTRINSIC_VOID, ISD::VECREDUCE_ADD, ISD::ADD, ISD::BITCAST});
1031  }
1032  if (Subtarget->hasMVEIntegerOps()) {
1033    setTargetDAGCombine({ISD::SMIN, ISD::UMIN, ISD::SMAX, ISD::UMAX,
1034                         ISD::FP_EXTEND, ISD::SELECT, ISD::SELECT_CC,
1035                         ISD::SETCC});
1036  }
1037  if (Subtarget->hasMVEFloatOps()) {
1038    setTargetDAGCombine(ISD::FADD);
1039  }
1040
1041  if (!Subtarget->hasFP64()) {
1042    // When targeting a floating-point unit with only single-precision
1043    // operations, f64 is legal for the few double-precision instructions which
1044    // are present However, no double-precision operations other than moves,
1045    // loads and stores are provided by the hardware.
1046    setOperationAction(ISD::FADD,       MVT::f64, Expand);
1047    setOperationAction(ISD::FSUB,       MVT::f64, Expand);
1048    setOperationAction(ISD::FMUL,       MVT::f64, Expand);
1049    setOperationAction(ISD::FMA,        MVT::f64, Expand);
1050    setOperationAction(ISD::FDIV,       MVT::f64, Expand);
1051    setOperationAction(ISD::FREM,       MVT::f64, Expand);
1052    setOperationAction(ISD::FCOPYSIGN,  MVT::f64, Expand);
1053    setOperationAction(ISD::FGETSIGN,   MVT::f64, Expand);
1054    setOperationAction(ISD::FNEG,       MVT::f64, Expand);
1055    setOperationAction(ISD::FABS,       MVT::f64, Expand);
1056    setOperationAction(ISD::FSQRT,      MVT::f64, Expand);
1057    setOperationAction(ISD::FSIN,       MVT::f64, Expand);
1058    setOperationAction(ISD::FCOS,       MVT::f64, Expand);
1059    setOperationAction(ISD::FPOW,       MVT::f64, Expand);
1060    setOperationAction(ISD::FLOG,       MVT::f64, Expand);
1061    setOperationAction(ISD::FLOG2,      MVT::f64, Expand);
1062    setOperationAction(ISD::FLOG10,     MVT::f64, Expand);
1063    setOperationAction(ISD::FEXP,       MVT::f64, Expand);
1064    setOperationAction(ISD::FEXP2,      MVT::f64, Expand);
1065    setOperationAction(ISD::FEXP10,      MVT::f64, Expand);
1066    setOperationAction(ISD::FCEIL,      MVT::f64, Expand);
1067    setOperationAction(ISD::FTRUNC,     MVT::f64, Expand);
1068    setOperationAction(ISD::FRINT,      MVT::f64, Expand);
1069    setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand);
1070    setOperationAction(ISD::FFLOOR,     MVT::f64, Expand);
1071    setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
1072    setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
1073    setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
1074    setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
1075    setOperationAction(ISD::FP_TO_SINT, MVT::f64, Custom);
1076    setOperationAction(ISD::FP_TO_UINT, MVT::f64, Custom);
1077    setOperationAction(ISD::FP_ROUND,   MVT::f32, Custom);
1078    setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom);
1079    setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom);
1080    setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::f64, Custom);
1081    setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::f64, Custom);
1082    setOperationAction(ISD::STRICT_FP_ROUND,   MVT::f32, Custom);
1083  }
1084
1085  if (!Subtarget->hasFP64() || !Subtarget->hasFPARMv8Base()) {
1086    setOperationAction(ISD::FP_EXTEND,  MVT::f64, Custom);
1087    setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f64, Custom);
1088    if (Subtarget->hasFullFP16()) {
1089      setOperationAction(ISD::FP_ROUND,  MVT::f16, Custom);
1090      setOperationAction(ISD::STRICT_FP_ROUND, MVT::f16, Custom);
1091    }
1092  }
1093
1094  if (!Subtarget->hasFP16()) {
1095    setOperationAction(ISD::FP_EXTEND,  MVT::f32, Custom);
1096    setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f32, Custom);
1097  }
1098
1099  computeRegisterProperties(Subtarget->getRegisterInfo());
1100
1101  // ARM does not have floating-point extending loads.
1102  for (MVT VT : MVT::fp_valuetypes()) {
1103    setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
1104    setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
1105  }
1106
1107  // ... or truncating stores
1108  setTruncStoreAction(MVT::f64, MVT::f32, Expand);
1109  setTruncStoreAction(MVT::f32, MVT::f16, Expand);
1110  setTruncStoreAction(MVT::f64, MVT::f16, Expand);
1111
1112  // ARM does not have i1 sign extending load.
1113  for (MVT VT : MVT::integer_valuetypes())
1114    setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
1115
1116  // ARM supports all 4 flavors of integer indexed load / store.
1117  if (!Subtarget->isThumb1Only()) {
1118    for (unsigned im = (unsigned)ISD::PRE_INC;
1119         im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
1120      setIndexedLoadAction(im,  MVT::i1,  Legal);
1121      setIndexedLoadAction(im,  MVT::i8,  Legal);
1122      setIndexedLoadAction(im,  MVT::i16, Legal);
1123      setIndexedLoadAction(im,  MVT::i32, Legal);
1124      setIndexedStoreAction(im, MVT::i1,  Legal);
1125      setIndexedStoreAction(im, MVT::i8,  Legal);
1126      setIndexedStoreAction(im, MVT::i16, Legal);
1127      setIndexedStoreAction(im, MVT::i32, Legal);
1128    }
1129  } else {
1130    // Thumb-1 has limited post-inc load/store support - LDM r0!, {r1}.
1131    setIndexedLoadAction(ISD::POST_INC, MVT::i32,  Legal);
1132    setIndexedStoreAction(ISD::POST_INC, MVT::i32,  Legal);
1133  }
1134
1135  setOperationAction(ISD::SADDO, MVT::i32, Custom);
1136  setOperationAction(ISD::UADDO, MVT::i32, Custom);
1137  setOperationAction(ISD::SSUBO, MVT::i32, Custom);
1138  setOperationAction(ISD::USUBO, MVT::i32, Custom);
1139
1140  setOperationAction(ISD::UADDO_CARRY, MVT::i32, Custom);
1141  setOperationAction(ISD::USUBO_CARRY, MVT::i32, Custom);
1142  if (Subtarget->hasDSP()) {
1143    setOperationAction(ISD::SADDSAT, MVT::i8, Custom);
1144    setOperationAction(ISD::SSUBSAT, MVT::i8, Custom);
1145    setOperationAction(ISD::SADDSAT, MVT::i16, Custom);
1146    setOperationAction(ISD::SSUBSAT, MVT::i16, Custom);
1147    setOperationAction(ISD::UADDSAT, MVT::i8, Custom);
1148    setOperationAction(ISD::USUBSAT, MVT::i8, Custom);
1149    setOperationAction(ISD::UADDSAT, MVT::i16, Custom);
1150    setOperationAction(ISD::USUBSAT, MVT::i16, Custom);
1151  }
1152  if (Subtarget->hasBaseDSP()) {
1153    setOperationAction(ISD::SADDSAT, MVT::i32, Legal);
1154    setOperationAction(ISD::SSUBSAT, MVT::i32, Legal);
1155  }
1156
1157  // i64 operation support.
1158  setOperationAction(ISD::MUL,     MVT::i64, Expand);
1159  setOperationAction(ISD::MULHU,   MVT::i32, Expand);
1160  if (Subtarget->isThumb1Only()) {
1161    setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
1162    setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
1163  }
1164  if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
1165      || (Subtarget->isThumb2() && !Subtarget->hasDSP()))
1166    setOperationAction(ISD::MULHS, MVT::i32, Expand);
1167
1168  setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
1169  setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
1170  setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
1171  setOperationAction(ISD::SRL,       MVT::i64, Custom);
1172  setOperationAction(ISD::SRA,       MVT::i64, Custom);
1173  setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1174  setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom);
1175  setOperationAction(ISD::LOAD, MVT::i64, Custom);
1176  setOperationAction(ISD::STORE, MVT::i64, Custom);
1177
1178  // MVE lowers 64 bit shifts to lsll and lsrl
1179  // assuming that ISD::SRL and SRA of i64 are already marked custom
1180  if (Subtarget->hasMVEIntegerOps())
1181    setOperationAction(ISD::SHL, MVT::i64, Custom);
1182
1183  // Expand to __aeabi_l{lsl,lsr,asr} calls for Thumb1.
1184  if (Subtarget->isThumb1Only()) {
1185    setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand);
1186    setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
1187    setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand);
1188  }
1189
1190  if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops())
1191    setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
1192
1193  // ARM does not have ROTL.
1194  setOperationAction(ISD::ROTL, MVT::i32, Expand);
1195  for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
1196    setOperationAction(ISD::ROTL, VT, Expand);
1197    setOperationAction(ISD::ROTR, VT, Expand);
1198  }
1199  setOperationAction(ISD::CTTZ,  MVT::i32, Custom);
1200  setOperationAction(ISD::CTPOP, MVT::i32, Expand);
1201  if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only()) {
1202    setOperationAction(ISD::CTLZ, MVT::i32, Expand);
1203    setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, LibCall);
1204  }
1205
1206  // @llvm.readcyclecounter requires the Performance Monitors extension.
1207  // Default to the 0 expansion on unsupported platforms.
1208  // FIXME: Technically there are older ARM CPUs that have
1209  // implementation-specific ways of obtaining this information.
1210  if (Subtarget->hasPerfMon())
1211    setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
1212
1213  // Only ARMv6 has BSWAP.
1214  if (!Subtarget->hasV6Ops())
1215    setOperationAction(ISD::BSWAP, MVT::i32, Expand);
1216
1217  bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode()
1218                                        : Subtarget->hasDivideInARMMode();
1219  if (!hasDivide) {
1220    // These are expanded into libcalls if the cpu doesn't have HW divider.
1221    setOperationAction(ISD::SDIV,  MVT::i32, LibCall);
1222    setOperationAction(ISD::UDIV,  MVT::i32, LibCall);
1223  }
1224
1225  if (Subtarget->isTargetWindows() && !Subtarget->hasDivideInThumbMode()) {
1226    setOperationAction(ISD::SDIV, MVT::i32, Custom);
1227    setOperationAction(ISD::UDIV, MVT::i32, Custom);
1228
1229    setOperationAction(ISD::SDIV, MVT::i64, Custom);
1230    setOperationAction(ISD::UDIV, MVT::i64, Custom);
1231  }
1232
1233  setOperationAction(ISD::SREM,  MVT::i32, Expand);
1234  setOperationAction(ISD::UREM,  MVT::i32, Expand);
1235
1236  // Register based DivRem for AEABI (RTABI 4.2)
1237  if (Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() ||
1238      Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() ||
1239      Subtarget->isTargetWindows()) {
1240    setOperationAction(ISD::SREM, MVT::i64, Custom);
1241    setOperationAction(ISD::UREM, MVT::i64, Custom);
1242    HasStandaloneRem = false;
1243
1244    if (Subtarget->isTargetWindows()) {
1245      const struct {
1246        const RTLIB::Libcall Op;
1247        const char * const Name;
1248        const CallingConv::ID CC;
1249      } LibraryCalls[] = {
1250        { RTLIB::SDIVREM_I8, "__rt_sdiv", CallingConv::ARM_AAPCS },
1251        { RTLIB::SDIVREM_I16, "__rt_sdiv", CallingConv::ARM_AAPCS },
1252        { RTLIB::SDIVREM_I32, "__rt_sdiv", CallingConv::ARM_AAPCS },
1253        { RTLIB::SDIVREM_I64, "__rt_sdiv64", CallingConv::ARM_AAPCS },
1254
1255        { RTLIB::UDIVREM_I8, "__rt_udiv", CallingConv::ARM_AAPCS },
1256        { RTLIB::UDIVREM_I16, "__rt_udiv", CallingConv::ARM_AAPCS },
1257        { RTLIB::UDIVREM_I32, "__rt_udiv", CallingConv::ARM_AAPCS },
1258        { RTLIB::UDIVREM_I64, "__rt_udiv64", CallingConv::ARM_AAPCS },
1259      };
1260
1261      for (const auto &LC : LibraryCalls) {
1262        setLibcallName(LC.Op, LC.Name);
1263        setLibcallCallingConv(LC.Op, LC.CC);
1264      }
1265    } else {
1266      const struct {
1267        const RTLIB::Libcall Op;
1268        const char * const Name;
1269        const CallingConv::ID CC;
1270      } LibraryCalls[] = {
1271        { RTLIB::SDIVREM_I8, "__aeabi_idivmod", CallingConv::ARM_AAPCS },
1272        { RTLIB::SDIVREM_I16, "__aeabi_idivmod", CallingConv::ARM_AAPCS },
1273        { RTLIB::SDIVREM_I32, "__aeabi_idivmod", CallingConv::ARM_AAPCS },
1274        { RTLIB::SDIVREM_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS },
1275
1276        { RTLIB::UDIVREM_I8, "__aeabi_uidivmod", CallingConv::ARM_AAPCS },
1277        { RTLIB::UDIVREM_I16, "__aeabi_uidivmod", CallingConv::ARM_AAPCS },
1278        { RTLIB::UDIVREM_I32, "__aeabi_uidivmod", CallingConv::ARM_AAPCS },
1279        { RTLIB::UDIVREM_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS },
1280      };
1281
1282      for (const auto &LC : LibraryCalls) {
1283        setLibcallName(LC.Op, LC.Name);
1284        setLibcallCallingConv(LC.Op, LC.CC);
1285      }
1286    }
1287
1288    setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
1289    setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
1290    setOperationAction(ISD::SDIVREM, MVT::i64, Custom);
1291    setOperationAction(ISD::UDIVREM, MVT::i64, Custom);
1292  } else {
1293    setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
1294    setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
1295  }
1296
1297  if (Subtarget->getTargetTriple().isOSMSVCRT()) {
1298    // MSVCRT doesn't have powi; fall back to pow
1299    setLibcallName(RTLIB::POWI_F32, nullptr);
1300    setLibcallName(RTLIB::POWI_F64, nullptr);
1301  }
1302
1303  setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
1304  setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
1305  setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
1306  setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
1307
1308  setOperationAction(ISD::TRAP, MVT::Other, Legal);
1309  setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
1310
1311  // Use the default implementation.
1312  setOperationAction(ISD::VASTART,            MVT::Other, Custom);
1313  setOperationAction(ISD::VAARG,              MVT::Other, Expand);
1314  setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
1315  setOperationAction(ISD::VAEND,              MVT::Other, Expand);
1316  setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
1317  setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
1318
1319  if (Subtarget->isTargetWindows())
1320    setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
1321  else
1322    setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
1323
1324  // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
1325  // the default expansion.
1326  InsertFencesForAtomic = false;
1327  if (Subtarget->hasAnyDataBarrier() &&
1328      (!Subtarget->isThumb() || Subtarget->hasV8MBaselineOps())) {
1329    // ATOMIC_FENCE needs custom lowering; the others should have been expanded
1330    // to ldrex/strex loops already.
1331    setOperationAction(ISD::ATOMIC_FENCE,     MVT::Other, Custom);
1332    if (!Subtarget->isThumb() || !Subtarget->isMClass())
1333      setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i64, Custom);
1334
1335    // On v8, we have particularly efficient implementations of atomic fences
1336    // if they can be combined with nearby atomic loads and stores.
1337    if (!Subtarget->hasAcquireRelease() ||
1338        getTargetMachine().getOptLevel() == CodeGenOptLevel::None) {
1339      // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc.
1340      InsertFencesForAtomic = true;
1341    }
1342  } else {
1343    // If there's anything we can use as a barrier, go through custom lowering
1344    // for ATOMIC_FENCE.
1345    // If target has DMB in thumb, Fences can be inserted.
1346    if (Subtarget->hasDataBarrier())
1347      InsertFencesForAtomic = true;
1348
1349    setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other,
1350                       Subtarget->hasAnyDataBarrier() ? Custom : Expand);
1351
1352    // Set them all for libcall, which will force libcalls.
1353    setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, LibCall);
1354    setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, LibCall);
1355    setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, LibCall);
1356    setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, LibCall);
1357    setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, LibCall);
1358    setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, LibCall);
1359    setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, LibCall);
1360    setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, LibCall);
1361    setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, LibCall);
1362    setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, LibCall);
1363    setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, LibCall);
1364    setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, LibCall);
1365    // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
1366    // Unordered/Monotonic case.
1367    if (!InsertFencesForAtomic) {
1368      setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
1369      setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
1370    }
1371  }
1372
1373  // Compute supported atomic widths.
1374  if (Subtarget->isTargetLinux() ||
1375      (!Subtarget->isMClass() && Subtarget->hasV6Ops())) {
1376    // For targets where __sync_* routines are reliably available, we use them
1377    // if necessary.
1378    //
1379    // ARM Linux always supports 64-bit atomics through kernel-assisted atomic
1380    // routines (kernel 3.1 or later). FIXME: Not with compiler-rt?
1381    //
1382    // ARMv6 targets have native instructions in ARM mode. For Thumb mode,
1383    // such targets should provide __sync_* routines, which use the ARM mode
1384    // instructions. (ARMv6 doesn't have dmb, but it has an equivalent
1385    // encoding; see ARMISD::MEMBARRIER_MCR.)
1386    setMaxAtomicSizeInBitsSupported(64);
1387  } else if ((Subtarget->isMClass() && Subtarget->hasV8MBaselineOps()) ||
1388             Subtarget->hasForced32BitAtomics()) {
1389    // Cortex-M (besides Cortex-M0) have 32-bit atomics.
1390    setMaxAtomicSizeInBitsSupported(32);
1391  } else {
1392    // We can't assume anything about other targets; just use libatomic
1393    // routines.
1394    setMaxAtomicSizeInBitsSupported(0);
1395  }
1396
1397  setMaxDivRemBitWidthSupported(64);
1398
1399  setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
1400
1401  // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
1402  if (!Subtarget->hasV6Ops()) {
1403    setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
1404    setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
1405  }
1406  setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
1407
1408  if (!Subtarget->useSoftFloat() && Subtarget->hasFPRegs() &&
1409      !Subtarget->isThumb1Only()) {
1410    // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
1411    // iff target supports vfp2.
1412    setOperationAction(ISD::BITCAST, MVT::i64, Custom);
1413    setOperationAction(ISD::GET_ROUNDING, MVT::i32, Custom);
1414    setOperationAction(ISD::SET_ROUNDING, MVT::Other, Custom);
1415    setOperationAction(ISD::GET_FPENV, MVT::i32, Legal);
1416    setOperationAction(ISD::SET_FPENV, MVT::i32, Legal);
1417    setOperationAction(ISD::RESET_FPENV, MVT::Other, Legal);
1418    setOperationAction(ISD::GET_FPMODE, MVT::i32, Legal);
1419    setOperationAction(ISD::SET_FPMODE, MVT::i32, Custom);
1420    setOperationAction(ISD::RESET_FPMODE, MVT::Other, Custom);
1421  }
1422
1423  // We want to custom lower some of our intrinsics.
1424  setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1425  setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
1426  setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
1427  setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom);
1428  if (Subtarget->useSjLjEH())
1429    setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
1430
1431  setOperationAction(ISD::SETCC,     MVT::i32, Expand);
1432  setOperationAction(ISD::SETCC,     MVT::f32, Expand);
1433  setOperationAction(ISD::SETCC,     MVT::f64, Expand);
1434  setOperationAction(ISD::SELECT,    MVT::i32, Custom);
1435  setOperationAction(ISD::SELECT,    MVT::f32, Custom);
1436  setOperationAction(ISD::SELECT,    MVT::f64, Custom);
1437  setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
1438  setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
1439  setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
1440  if (Subtarget->hasFullFP16()) {
1441    setOperationAction(ISD::SETCC,     MVT::f16, Expand);
1442    setOperationAction(ISD::SELECT,    MVT::f16, Custom);
1443    setOperationAction(ISD::SELECT_CC, MVT::f16, Custom);
1444  }
1445
1446  setOperationAction(ISD::SETCCCARRY, MVT::i32, Custom);
1447
1448  setOperationAction(ISD::BRCOND,    MVT::Other, Custom);
1449  setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
1450  if (Subtarget->hasFullFP16())
1451      setOperationAction(ISD::BR_CC, MVT::f16,   Custom);
1452  setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
1453  setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
1454  setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
1455
1456  // We don't support sin/cos/fmod/copysign/pow
1457  setOperationAction(ISD::FSIN,      MVT::f64, Expand);
1458  setOperationAction(ISD::FSIN,      MVT::f32, Expand);
1459  setOperationAction(ISD::FCOS,      MVT::f32, Expand);
1460  setOperationAction(ISD::FCOS,      MVT::f64, Expand);
1461  setOperationAction(ISD::FSINCOS,   MVT::f64, Expand);
1462  setOperationAction(ISD::FSINCOS,   MVT::f32, Expand);
1463  setOperationAction(ISD::FREM,      MVT::f64, Expand);
1464  setOperationAction(ISD::FREM,      MVT::f32, Expand);
1465  if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2Base() &&
1466      !Subtarget->isThumb1Only()) {
1467    setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
1468    setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
1469  }
1470  setOperationAction(ISD::FPOW,      MVT::f64, Expand);
1471  setOperationAction(ISD::FPOW,      MVT::f32, Expand);
1472
1473  if (!Subtarget->hasVFP4Base()) {
1474    setOperationAction(ISD::FMA, MVT::f64, Expand);
1475    setOperationAction(ISD::FMA, MVT::f32, Expand);
1476  }
1477
1478  // Various VFP goodness
1479  if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) {
1480    // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded.
1481    if (!Subtarget->hasFPARMv8Base() || !Subtarget->hasFP64()) {
1482      setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
1483      setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
1484    }
1485
1486    // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
1487    if (!Subtarget->hasFP16()) {
1488      setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
1489      setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
1490    }
1491
1492    // Strict floating-point comparisons need custom lowering.
1493    setOperationAction(ISD::STRICT_FSETCC,  MVT::f16, Custom);
1494    setOperationAction(ISD::STRICT_FSETCCS, MVT::f16, Custom);
1495    setOperationAction(ISD::STRICT_FSETCC,  MVT::f32, Custom);
1496    setOperationAction(ISD::STRICT_FSETCCS, MVT::f32, Custom);
1497    setOperationAction(ISD::STRICT_FSETCC,  MVT::f64, Custom);
1498    setOperationAction(ISD::STRICT_FSETCCS, MVT::f64, Custom);
1499  }
1500
1501  // Use __sincos_stret if available.
1502  if (getLibcallName(RTLIB::SINCOS_STRET_F32) != nullptr &&
1503      getLibcallName(RTLIB::SINCOS_STRET_F64) != nullptr) {
1504    setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1505    setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1506  }
1507
1508  // FP-ARMv8 implements a lot of rounding-like FP operations.
1509  if (Subtarget->hasFPARMv8Base()) {
1510    setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
1511    setOperationAction(ISD::FCEIL, MVT::f32, Legal);
1512    setOperationAction(ISD::FROUND, MVT::f32, Legal);
1513    setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
1514    setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
1515    setOperationAction(ISD::FRINT, MVT::f32, Legal);
1516    setOperationAction(ISD::FMINNUM, MVT::f32, Legal);
1517    setOperationAction(ISD::FMAXNUM, MVT::f32, Legal);
1518    if (Subtarget->hasNEON()) {
1519      setOperationAction(ISD::FMINNUM, MVT::v2f32, Legal);
1520      setOperationAction(ISD::FMAXNUM, MVT::v2f32, Legal);
1521      setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
1522      setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
1523    }
1524
1525    if (Subtarget->hasFP64()) {
1526      setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
1527      setOperationAction(ISD::FCEIL, MVT::f64, Legal);
1528      setOperationAction(ISD::FROUND, MVT::f64, Legal);
1529      setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
1530      setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
1531      setOperationAction(ISD::FRINT, MVT::f64, Legal);
1532      setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
1533      setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
1534    }
1535  }
1536
1537  // FP16 often need to be promoted to call lib functions
1538  if (Subtarget->hasFullFP16()) {
1539    setOperationAction(ISD::FREM, MVT::f16, Promote);
1540    setOperationAction(ISD::FCOPYSIGN, MVT::f16, Expand);
1541    setOperationAction(ISD::FSIN, MVT::f16, Promote);
1542    setOperationAction(ISD::FCOS, MVT::f16, Promote);
1543    setOperationAction(ISD::FSINCOS, MVT::f16, Promote);
1544    setOperationAction(ISD::FPOWI, MVT::f16, Promote);
1545    setOperationAction(ISD::FPOW, MVT::f16, Promote);
1546    setOperationAction(ISD::FEXP, MVT::f16, Promote);
1547    setOperationAction(ISD::FEXP2, MVT::f16, Promote);
1548    setOperationAction(ISD::FEXP10, MVT::f16, Promote);
1549    setOperationAction(ISD::FLOG, MVT::f16, Promote);
1550    setOperationAction(ISD::FLOG10, MVT::f16, Promote);
1551    setOperationAction(ISD::FLOG2, MVT::f16, Promote);
1552
1553    setOperationAction(ISD::FROUND, MVT::f16, Legal);
1554  }
1555
1556  if (Subtarget->hasNEON()) {
1557    // vmin and vmax aren't available in a scalar form, so we can use
1558    // a NEON instruction with an undef lane instead.  This has a performance
1559    // penalty on some cores, so we don't do this unless we have been
1560    // asked to by the core tuning model.
1561    if (Subtarget->useNEONForSinglePrecisionFP()) {
1562      setOperationAction(ISD::FMINIMUM, MVT::f32, Legal);
1563      setOperationAction(ISD::FMAXIMUM, MVT::f32, Legal);
1564      setOperationAction(ISD::FMINIMUM, MVT::f16, Legal);
1565      setOperationAction(ISD::FMAXIMUM, MVT::f16, Legal);
1566    }
1567    setOperationAction(ISD::FMINIMUM, MVT::v2f32, Legal);
1568    setOperationAction(ISD::FMAXIMUM, MVT::v2f32, Legal);
1569    setOperationAction(ISD::FMINIMUM, MVT::v4f32, Legal);
1570    setOperationAction(ISD::FMAXIMUM, MVT::v4f32, Legal);
1571
1572    if (Subtarget->hasFullFP16()) {
1573      setOperationAction(ISD::FMINNUM, MVT::v4f16, Legal);
1574      setOperationAction(ISD::FMAXNUM, MVT::v4f16, Legal);
1575      setOperationAction(ISD::FMINNUM, MVT::v8f16, Legal);
1576      setOperationAction(ISD::FMAXNUM, MVT::v8f16, Legal);
1577
1578      setOperationAction(ISD::FMINIMUM, MVT::v4f16, Legal);
1579      setOperationAction(ISD::FMAXIMUM, MVT::v4f16, Legal);
1580      setOperationAction(ISD::FMINIMUM, MVT::v8f16, Legal);
1581      setOperationAction(ISD::FMAXIMUM, MVT::v8f16, Legal);
1582    }
1583  }
1584
1585  // We have target-specific dag combine patterns for the following nodes:
1586  // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
1587  setTargetDAGCombine(
1588      {ISD::ADD, ISD::SUB, ISD::MUL, ISD::AND, ISD::OR, ISD::XOR});
1589
1590  if (Subtarget->hasMVEIntegerOps())
1591    setTargetDAGCombine(ISD::VSELECT);
1592
1593  if (Subtarget->hasV6Ops())
1594    setTargetDAGCombine(ISD::SRL);
1595  if (Subtarget->isThumb1Only())
1596    setTargetDAGCombine(ISD::SHL);
1597  // Attempt to lower smin/smax to ssat/usat
1598  if ((!Subtarget->isThumb() && Subtarget->hasV6Ops()) ||
1599      Subtarget->isThumb2()) {
1600    setTargetDAGCombine({ISD::SMIN, ISD::SMAX});
1601  }
1602
1603  setStackPointerRegisterToSaveRestore(ARM::SP);
1604
1605  if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() ||
1606      !Subtarget->hasVFP2Base() || Subtarget->hasMinSize())
1607    setSchedulingPreference(Sched::RegPressure);
1608  else
1609    setSchedulingPreference(Sched::Hybrid);
1610
1611  //// temporary - rewrite interface to use type
1612  MaxStoresPerMemset = 8;
1613  MaxStoresPerMemsetOptSize = 4;
1614  MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
1615  MaxStoresPerMemcpyOptSize = 2;
1616  MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
1617  MaxStoresPerMemmoveOptSize = 2;
1618
1619  // On ARM arguments smaller than 4 bytes are extended, so all arguments
1620  // are at least 4 bytes aligned.
1621  setMinStackArgumentAlignment(Align(4));
1622
1623  // Prefer likely predicted branches to selects on out-of-order cores.
1624  PredictableSelectIsExpensive = Subtarget->getSchedModel().isOutOfOrder();
1625
1626  setPrefLoopAlignment(Align(1ULL << Subtarget->getPrefLoopLogAlignment()));
1627  setPrefFunctionAlignment(Align(1ULL << Subtarget->getPrefLoopLogAlignment()));
1628
1629  setMinFunctionAlignment(Subtarget->isThumb() ? Align(2) : Align(4));
1630
1631  if (Subtarget->isThumb() || Subtarget->isThumb2())
1632    setTargetDAGCombine(ISD::ABS);
1633}
1634
1635bool ARMTargetLowering::useSoftFloat() const {
1636  return Subtarget->useSoftFloat();
1637}
1638
1639// FIXME: It might make sense to define the representative register class as the
1640// nearest super-register that has a non-null superset. For example, DPR_VFP2 is
1641// a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
1642// SPR's representative would be DPR_VFP2. This should work well if register
1643// pressure tracking were modified such that a register use would increment the
1644// pressure of the register class's representative and all of it's super
1645// classes' representatives transitively. We have not implemented this because
1646// of the difficulty prior to coalescing of modeling operand register classes
1647// due to the common occurrence of cross class copies and subregister insertions
1648// and extractions.
1649std::pair<const TargetRegisterClass *, uint8_t>
1650ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1651                                           MVT VT) const {
1652  const TargetRegisterClass *RRC = nullptr;
1653  uint8_t Cost = 1;
1654  switch (VT.SimpleTy) {
1655  default:
1656    return TargetLowering::findRepresentativeClass(TRI, VT);
1657  // Use DPR as representative register class for all floating point
1658  // and vector types. Since there are 32 SPR registers and 32 DPR registers so
1659  // the cost is 1 for both f32 and f64.
1660  case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
1661  case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
1662    RRC = &ARM::DPRRegClass;
1663    // When NEON is used for SP, only half of the register file is available
1664    // because operations that define both SP and DP results will be constrained
1665    // to the VFP2 class (D0-D15). We currently model this constraint prior to
1666    // coalescing by double-counting the SP regs. See the FIXME above.
1667    if (Subtarget->useNEONForSinglePrecisionFP())
1668      Cost = 2;
1669    break;
1670  case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1671  case MVT::v4f32: case MVT::v2f64:
1672    RRC = &ARM::DPRRegClass;
1673    Cost = 2;
1674    break;
1675  case MVT::v4i64:
1676    RRC = &ARM::DPRRegClass;
1677    Cost = 4;
1678    break;
1679  case MVT::v8i64:
1680    RRC = &ARM::DPRRegClass;
1681    Cost = 8;
1682    break;
1683  }
1684  return std::make_pair(RRC, Cost);
1685}
1686
1687const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1688#define MAKE_CASE(V)                                                           \
1689  case V:                                                                      \
1690    return #V;
1691  switch ((ARMISD::NodeType)Opcode) {
1692  case ARMISD::FIRST_NUMBER:
1693    break;
1694    MAKE_CASE(ARMISD::Wrapper)
1695    MAKE_CASE(ARMISD::WrapperPIC)
1696    MAKE_CASE(ARMISD::WrapperJT)
1697    MAKE_CASE(ARMISD::COPY_STRUCT_BYVAL)
1698    MAKE_CASE(ARMISD::CALL)
1699    MAKE_CASE(ARMISD::CALL_PRED)
1700    MAKE_CASE(ARMISD::CALL_NOLINK)
1701    MAKE_CASE(ARMISD::tSECALL)
1702    MAKE_CASE(ARMISD::t2CALL_BTI)
1703    MAKE_CASE(ARMISD::BRCOND)
1704    MAKE_CASE(ARMISD::BR_JT)
1705    MAKE_CASE(ARMISD::BR2_JT)
1706    MAKE_CASE(ARMISD::RET_GLUE)
1707    MAKE_CASE(ARMISD::SERET_GLUE)
1708    MAKE_CASE(ARMISD::INTRET_GLUE)
1709    MAKE_CASE(ARMISD::PIC_ADD)
1710    MAKE_CASE(ARMISD::CMP)
1711    MAKE_CASE(ARMISD::CMN)
1712    MAKE_CASE(ARMISD::CMPZ)
1713    MAKE_CASE(ARMISD::CMPFP)
1714    MAKE_CASE(ARMISD::CMPFPE)
1715    MAKE_CASE(ARMISD::CMPFPw0)
1716    MAKE_CASE(ARMISD::CMPFPEw0)
1717    MAKE_CASE(ARMISD::BCC_i64)
1718    MAKE_CASE(ARMISD::FMSTAT)
1719    MAKE_CASE(ARMISD::CMOV)
1720    MAKE_CASE(ARMISD::SUBS)
1721    MAKE_CASE(ARMISD::SSAT)
1722    MAKE_CASE(ARMISD::USAT)
1723    MAKE_CASE(ARMISD::ASRL)
1724    MAKE_CASE(ARMISD::LSRL)
1725    MAKE_CASE(ARMISD::LSLL)
1726    MAKE_CASE(ARMISD::SRL_GLUE)
1727    MAKE_CASE(ARMISD::SRA_GLUE)
1728    MAKE_CASE(ARMISD::RRX)
1729    MAKE_CASE(ARMISD::ADDC)
1730    MAKE_CASE(ARMISD::ADDE)
1731    MAKE_CASE(ARMISD::SUBC)
1732    MAKE_CASE(ARMISD::SUBE)
1733    MAKE_CASE(ARMISD::LSLS)
1734    MAKE_CASE(ARMISD::VMOVRRD)
1735    MAKE_CASE(ARMISD::VMOVDRR)
1736    MAKE_CASE(ARMISD::VMOVhr)
1737    MAKE_CASE(ARMISD::VMOVrh)
1738    MAKE_CASE(ARMISD::VMOVSR)
1739    MAKE_CASE(ARMISD::EH_SJLJ_SETJMP)
1740    MAKE_CASE(ARMISD::EH_SJLJ_LONGJMP)
1741    MAKE_CASE(ARMISD::EH_SJLJ_SETUP_DISPATCH)
1742    MAKE_CASE(ARMISD::TC_RETURN)
1743    MAKE_CASE(ARMISD::THREAD_POINTER)
1744    MAKE_CASE(ARMISD::DYN_ALLOC)
1745    MAKE_CASE(ARMISD::MEMBARRIER_MCR)
1746    MAKE_CASE(ARMISD::PRELOAD)
1747    MAKE_CASE(ARMISD::LDRD)
1748    MAKE_CASE(ARMISD::STRD)
1749    MAKE_CASE(ARMISD::WIN__CHKSTK)
1750    MAKE_CASE(ARMISD::WIN__DBZCHK)
1751    MAKE_CASE(ARMISD::PREDICATE_CAST)
1752    MAKE_CASE(ARMISD::VECTOR_REG_CAST)
1753    MAKE_CASE(ARMISD::MVESEXT)
1754    MAKE_CASE(ARMISD::MVEZEXT)
1755    MAKE_CASE(ARMISD::MVETRUNC)
1756    MAKE_CASE(ARMISD::VCMP)
1757    MAKE_CASE(ARMISD::VCMPZ)
1758    MAKE_CASE(ARMISD::VTST)
1759    MAKE_CASE(ARMISD::VSHLs)
1760    MAKE_CASE(ARMISD::VSHLu)
1761    MAKE_CASE(ARMISD::VSHLIMM)
1762    MAKE_CASE(ARMISD::VSHRsIMM)
1763    MAKE_CASE(ARMISD::VSHRuIMM)
1764    MAKE_CASE(ARMISD::VRSHRsIMM)
1765    MAKE_CASE(ARMISD::VRSHRuIMM)
1766    MAKE_CASE(ARMISD::VRSHRNIMM)
1767    MAKE_CASE(ARMISD::VQSHLsIMM)
1768    MAKE_CASE(ARMISD::VQSHLuIMM)
1769    MAKE_CASE(ARMISD::VQSHLsuIMM)
1770    MAKE_CASE(ARMISD::VQSHRNsIMM)
1771    MAKE_CASE(ARMISD::VQSHRNuIMM)
1772    MAKE_CASE(ARMISD::VQSHRNsuIMM)
1773    MAKE_CASE(ARMISD::VQRSHRNsIMM)
1774    MAKE_CASE(ARMISD::VQRSHRNuIMM)
1775    MAKE_CASE(ARMISD::VQRSHRNsuIMM)
1776    MAKE_CASE(ARMISD::VSLIIMM)
1777    MAKE_CASE(ARMISD::VSRIIMM)
1778    MAKE_CASE(ARMISD::VGETLANEu)
1779    MAKE_CASE(ARMISD::VGETLANEs)
1780    MAKE_CASE(ARMISD::VMOVIMM)
1781    MAKE_CASE(ARMISD::VMVNIMM)
1782    MAKE_CASE(ARMISD::VMOVFPIMM)
1783    MAKE_CASE(ARMISD::VDUP)
1784    MAKE_CASE(ARMISD::VDUPLANE)
1785    MAKE_CASE(ARMISD::VEXT)
1786    MAKE_CASE(ARMISD::VREV64)
1787    MAKE_CASE(ARMISD::VREV32)
1788    MAKE_CASE(ARMISD::VREV16)
1789    MAKE_CASE(ARMISD::VZIP)
1790    MAKE_CASE(ARMISD::VUZP)
1791    MAKE_CASE(ARMISD::VTRN)
1792    MAKE_CASE(ARMISD::VTBL1)
1793    MAKE_CASE(ARMISD::VTBL2)
1794    MAKE_CASE(ARMISD::VMOVN)
1795    MAKE_CASE(ARMISD::VQMOVNs)
1796    MAKE_CASE(ARMISD::VQMOVNu)
1797    MAKE_CASE(ARMISD::VCVTN)
1798    MAKE_CASE(ARMISD::VCVTL)
1799    MAKE_CASE(ARMISD::VIDUP)
1800    MAKE_CASE(ARMISD::VMULLs)
1801    MAKE_CASE(ARMISD::VMULLu)
1802    MAKE_CASE(ARMISD::VQDMULH)
1803    MAKE_CASE(ARMISD::VADDVs)
1804    MAKE_CASE(ARMISD::VADDVu)
1805    MAKE_CASE(ARMISD::VADDVps)
1806    MAKE_CASE(ARMISD::VADDVpu)
1807    MAKE_CASE(ARMISD::VADDLVs)
1808    MAKE_CASE(ARMISD::VADDLVu)
1809    MAKE_CASE(ARMISD::VADDLVAs)
1810    MAKE_CASE(ARMISD::VADDLVAu)
1811    MAKE_CASE(ARMISD::VADDLVps)
1812    MAKE_CASE(ARMISD::VADDLVpu)
1813    MAKE_CASE(ARMISD::VADDLVAps)
1814    MAKE_CASE(ARMISD::VADDLVApu)
1815    MAKE_CASE(ARMISD::VMLAVs)
1816    MAKE_CASE(ARMISD::VMLAVu)
1817    MAKE_CASE(ARMISD::VMLAVps)
1818    MAKE_CASE(ARMISD::VMLAVpu)
1819    MAKE_CASE(ARMISD::VMLALVs)
1820    MAKE_CASE(ARMISD::VMLALVu)
1821    MAKE_CASE(ARMISD::VMLALVps)
1822    MAKE_CASE(ARMISD::VMLALVpu)
1823    MAKE_CASE(ARMISD::VMLALVAs)
1824    MAKE_CASE(ARMISD::VMLALVAu)
1825    MAKE_CASE(ARMISD::VMLALVAps)
1826    MAKE_CASE(ARMISD::VMLALVApu)
1827    MAKE_CASE(ARMISD::VMINVu)
1828    MAKE_CASE(ARMISD::VMINVs)
1829    MAKE_CASE(ARMISD::VMAXVu)
1830    MAKE_CASE(ARMISD::VMAXVs)
1831    MAKE_CASE(ARMISD::UMAAL)
1832    MAKE_CASE(ARMISD::UMLAL)
1833    MAKE_CASE(ARMISD::SMLAL)
1834    MAKE_CASE(ARMISD::SMLALBB)
1835    MAKE_CASE(ARMISD::SMLALBT)
1836    MAKE_CASE(ARMISD::SMLALTB)
1837    MAKE_CASE(ARMISD::SMLALTT)
1838    MAKE_CASE(ARMISD::SMULWB)
1839    MAKE_CASE(ARMISD::SMULWT)
1840    MAKE_CASE(ARMISD::SMLALD)
1841    MAKE_CASE(ARMISD::SMLALDX)
1842    MAKE_CASE(ARMISD::SMLSLD)
1843    MAKE_CASE(ARMISD::SMLSLDX)
1844    MAKE_CASE(ARMISD::SMMLAR)
1845    MAKE_CASE(ARMISD::SMMLSR)
1846    MAKE_CASE(ARMISD::QADD16b)
1847    MAKE_CASE(ARMISD::QSUB16b)
1848    MAKE_CASE(ARMISD::QADD8b)
1849    MAKE_CASE(ARMISD::QSUB8b)
1850    MAKE_CASE(ARMISD::UQADD16b)
1851    MAKE_CASE(ARMISD::UQSUB16b)
1852    MAKE_CASE(ARMISD::UQADD8b)
1853    MAKE_CASE(ARMISD::UQSUB8b)
1854    MAKE_CASE(ARMISD::BUILD_VECTOR)
1855    MAKE_CASE(ARMISD::BFI)
1856    MAKE_CASE(ARMISD::VORRIMM)
1857    MAKE_CASE(ARMISD::VBICIMM)
1858    MAKE_CASE(ARMISD::VBSP)
1859    MAKE_CASE(ARMISD::MEMCPY)
1860    MAKE_CASE(ARMISD::VLD1DUP)
1861    MAKE_CASE(ARMISD::VLD2DUP)
1862    MAKE_CASE(ARMISD::VLD3DUP)
1863    MAKE_CASE(ARMISD::VLD4DUP)
1864    MAKE_CASE(ARMISD::VLD1_UPD)
1865    MAKE_CASE(ARMISD::VLD2_UPD)
1866    MAKE_CASE(ARMISD::VLD3_UPD)
1867    MAKE_CASE(ARMISD::VLD4_UPD)
1868    MAKE_CASE(ARMISD::VLD1x2_UPD)
1869    MAKE_CASE(ARMISD::VLD1x3_UPD)
1870    MAKE_CASE(ARMISD::VLD1x4_UPD)
1871    MAKE_CASE(ARMISD::VLD2LN_UPD)
1872    MAKE_CASE(ARMISD::VLD3LN_UPD)
1873    MAKE_CASE(ARMISD::VLD4LN_UPD)
1874    MAKE_CASE(ARMISD::VLD1DUP_UPD)
1875    MAKE_CASE(ARMISD::VLD2DUP_UPD)
1876    MAKE_CASE(ARMISD::VLD3DUP_UPD)
1877    MAKE_CASE(ARMISD::VLD4DUP_UPD)
1878    MAKE_CASE(ARMISD::VST1_UPD)
1879    MAKE_CASE(ARMISD::VST2_UPD)
1880    MAKE_CASE(ARMISD::VST3_UPD)
1881    MAKE_CASE(ARMISD::VST4_UPD)
1882    MAKE_CASE(ARMISD::VST1x2_UPD)
1883    MAKE_CASE(ARMISD::VST1x3_UPD)
1884    MAKE_CASE(ARMISD::VST1x4_UPD)
1885    MAKE_CASE(ARMISD::VST2LN_UPD)
1886    MAKE_CASE(ARMISD::VST3LN_UPD)
1887    MAKE_CASE(ARMISD::VST4LN_UPD)
1888    MAKE_CASE(ARMISD::WLS)
1889    MAKE_CASE(ARMISD::WLSSETUP)
1890    MAKE_CASE(ARMISD::LE)
1891    MAKE_CASE(ARMISD::LOOP_DEC)
1892    MAKE_CASE(ARMISD::CSINV)
1893    MAKE_CASE(ARMISD::CSNEG)
1894    MAKE_CASE(ARMISD::CSINC)
1895    MAKE_CASE(ARMISD::MEMCPYLOOP)
1896    MAKE_CASE(ARMISD::MEMSETLOOP)
1897#undef MAKE_CASE
1898  }
1899  return nullptr;
1900}
1901
1902EVT ARMTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1903                                          EVT VT) const {
1904  if (!VT.isVector())
1905    return getPointerTy(DL);
1906
1907  // MVE has a predicate register.
1908  if ((Subtarget->hasMVEIntegerOps() &&
1909       (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
1910        VT == MVT::v16i8)) ||
1911      (Subtarget->hasMVEFloatOps() &&
1912       (VT == MVT::v2f64 || VT == MVT::v4f32 || VT == MVT::v8f16)))
1913    return MVT::getVectorVT(MVT::i1, VT.getVectorElementCount());
1914  return VT.changeVectorElementTypeToInteger();
1915}
1916
1917/// getRegClassFor - Return the register class that should be used for the
1918/// specified value type.
1919const TargetRegisterClass *
1920ARMTargetLowering::getRegClassFor(MVT VT, bool isDivergent) const {
1921  (void)isDivergent;
1922  // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1923  // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1924  // load / store 4 to 8 consecutive NEON D registers, or 2 to 4 consecutive
1925  // MVE Q registers.
1926  if (Subtarget->hasNEON()) {
1927    if (VT == MVT::v4i64)
1928      return &ARM::QQPRRegClass;
1929    if (VT == MVT::v8i64)
1930      return &ARM::QQQQPRRegClass;
1931  }
1932  if (Subtarget->hasMVEIntegerOps()) {
1933    if (VT == MVT::v4i64)
1934      return &ARM::MQQPRRegClass;
1935    if (VT == MVT::v8i64)
1936      return &ARM::MQQQQPRRegClass;
1937  }
1938  return TargetLowering::getRegClassFor(VT);
1939}
1940
1941// memcpy, and other memory intrinsics, typically tries to use LDM/STM if the
1942// source/dest is aligned and the copy size is large enough. We therefore want
1943// to align such objects passed to memory intrinsics.
1944bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize,
1945                                               Align &PrefAlign) const {
1946  if (!isa<MemIntrinsic>(CI))
1947    return false;
1948  MinSize = 8;
1949  // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1
1950  // cycle faster than 4-byte aligned LDM.
1951  PrefAlign =
1952      (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? Align(8) : Align(4));
1953  return true;
1954}
1955
1956// Create a fast isel object.
1957FastISel *
1958ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1959                                  const TargetLibraryInfo *libInfo) const {
1960  return ARM::createFastISel(funcInfo, libInfo);
1961}
1962
1963Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1964  unsigned NumVals = N->getNumValues();
1965  if (!NumVals)
1966    return Sched::RegPressure;
1967
1968  for (unsigned i = 0; i != NumVals; ++i) {
1969    EVT VT = N->getValueType(i);
1970    if (VT == MVT::Glue || VT == MVT::Other)
1971      continue;
1972    if (VT.isFloatingPoint() || VT.isVector())
1973      return Sched::ILP;
1974  }
1975
1976  if (!N->isMachineOpcode())
1977    return Sched::RegPressure;
1978
1979  // Load are scheduled for latency even if there instruction itinerary
1980  // is not available.
1981  const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1982  const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1983
1984  if (MCID.getNumDefs() == 0)
1985    return Sched::RegPressure;
1986  if (!Itins->isEmpty() &&
1987      Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2U)
1988    return Sched::ILP;
1989
1990  return Sched::RegPressure;
1991}
1992
1993//===----------------------------------------------------------------------===//
1994// Lowering Code
1995//===----------------------------------------------------------------------===//
1996
1997static bool isSRL16(const SDValue &Op) {
1998  if (Op.getOpcode() != ISD::SRL)
1999    return false;
2000  if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
2001    return Const->getZExtValue() == 16;
2002  return false;
2003}
2004
2005static bool isSRA16(const SDValue &Op) {
2006  if (Op.getOpcode() != ISD::SRA)
2007    return false;
2008  if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
2009    return Const->getZExtValue() == 16;
2010  return false;
2011}
2012
2013static bool isSHL16(const SDValue &Op) {
2014  if (Op.getOpcode() != ISD::SHL)
2015    return false;
2016  if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
2017    return Const->getZExtValue() == 16;
2018  return false;
2019}
2020
2021// Check for a signed 16-bit value. We special case SRA because it makes it
2022// more simple when also looking for SRAs that aren't sign extending a
2023// smaller value. Without the check, we'd need to take extra care with
2024// checking order for some operations.
2025static bool isS16(const SDValue &Op, SelectionDAG &DAG) {
2026  if (isSRA16(Op))
2027    return isSHL16(Op.getOperand(0));
2028  return DAG.ComputeNumSignBits(Op) == 17;
2029}
2030
2031/// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
2032static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
2033  switch (CC) {
2034  default: llvm_unreachable("Unknown condition code!");
2035  case ISD::SETNE:  return ARMCC::NE;
2036  case ISD::SETEQ:  return ARMCC::EQ;
2037  case ISD::SETGT:  return ARMCC::GT;
2038  case ISD::SETGE:  return ARMCC::GE;
2039  case ISD::SETLT:  return ARMCC::LT;
2040  case ISD::SETLE:  return ARMCC::LE;
2041  case ISD::SETUGT: return ARMCC::HI;
2042  case ISD::SETUGE: return ARMCC::HS;
2043  case ISD::SETULT: return ARMCC::LO;
2044  case ISD::SETULE: return ARMCC::LS;
2045  }
2046}
2047
2048/// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
2049static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
2050                        ARMCC::CondCodes &CondCode2) {
2051  CondCode2 = ARMCC::AL;
2052  switch (CC) {
2053  default: llvm_unreachable("Unknown FP condition!");
2054  case ISD::SETEQ:
2055  case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
2056  case ISD::SETGT:
2057  case ISD::SETOGT: CondCode = ARMCC::GT; break;
2058  case ISD::SETGE:
2059  case ISD::SETOGE: CondCode = ARMCC::GE; break;
2060  case ISD::SETOLT: CondCode = ARMCC::MI; break;
2061  case ISD::SETOLE: CondCode = ARMCC::LS; break;
2062  case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
2063  case ISD::SETO:   CondCode = ARMCC::VC; break;
2064  case ISD::SETUO:  CondCode = ARMCC::VS; break;
2065  case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
2066  case ISD::SETUGT: CondCode = ARMCC::HI; break;
2067  case ISD::SETUGE: CondCode = ARMCC::PL; break;
2068  case ISD::SETLT:
2069  case ISD::SETULT: CondCode = ARMCC::LT; break;
2070  case ISD::SETLE:
2071  case ISD::SETULE: CondCode = ARMCC::LE; break;
2072  case ISD::SETNE:
2073  case ISD::SETUNE: CondCode = ARMCC::NE; break;
2074  }
2075}
2076
2077//===----------------------------------------------------------------------===//
2078//                      Calling Convention Implementation
2079//===----------------------------------------------------------------------===//
2080
2081/// getEffectiveCallingConv - Get the effective calling convention, taking into
2082/// account presence of floating point hardware and calling convention
2083/// limitations, such as support for variadic functions.
2084CallingConv::ID
2085ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
2086                                           bool isVarArg) const {
2087  switch (CC) {
2088  default:
2089    report_fatal_error("Unsupported calling convention");
2090  case CallingConv::ARM_AAPCS:
2091  case CallingConv::ARM_APCS:
2092  case CallingConv::GHC:
2093  case CallingConv::CFGuard_Check:
2094    return CC;
2095  case CallingConv::PreserveMost:
2096    return CallingConv::PreserveMost;
2097  case CallingConv::PreserveAll:
2098    return CallingConv::PreserveAll;
2099  case CallingConv::ARM_AAPCS_VFP:
2100  case CallingConv::Swift:
2101  case CallingConv::SwiftTail:
2102    return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
2103  case CallingConv::C:
2104  case CallingConv::Tail:
2105    if (!Subtarget->isAAPCS_ABI())
2106      return CallingConv::ARM_APCS;
2107    else if (Subtarget->hasFPRegs() && !Subtarget->isThumb1Only() &&
2108             getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
2109             !isVarArg)
2110      return CallingConv::ARM_AAPCS_VFP;
2111    else
2112      return CallingConv::ARM_AAPCS;
2113  case CallingConv::Fast:
2114  case CallingConv::CXX_FAST_TLS:
2115    if (!Subtarget->isAAPCS_ABI()) {
2116      if (Subtarget->hasVFP2Base() && !Subtarget->isThumb1Only() && !isVarArg)
2117        return CallingConv::Fast;
2118      return CallingConv::ARM_APCS;
2119    } else if (Subtarget->hasVFP2Base() &&
2120               !Subtarget->isThumb1Only() && !isVarArg)
2121      return CallingConv::ARM_AAPCS_VFP;
2122    else
2123      return CallingConv::ARM_AAPCS;
2124  }
2125}
2126
2127CCAssignFn *ARMTargetLowering::CCAssignFnForCall(CallingConv::ID CC,
2128                                                 bool isVarArg) const {
2129  return CCAssignFnForNode(CC, false, isVarArg);
2130}
2131
2132CCAssignFn *ARMTargetLowering::CCAssignFnForReturn(CallingConv::ID CC,
2133                                                   bool isVarArg) const {
2134  return CCAssignFnForNode(CC, true, isVarArg);
2135}
2136
2137/// CCAssignFnForNode - Selects the correct CCAssignFn for the given
2138/// CallingConvention.
2139CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
2140                                                 bool Return,
2141                                                 bool isVarArg) const {
2142  switch (getEffectiveCallingConv(CC, isVarArg)) {
2143  default:
2144    report_fatal_error("Unsupported calling convention");
2145  case CallingConv::ARM_APCS:
2146    return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
2147  case CallingConv::ARM_AAPCS:
2148    return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
2149  case CallingConv::ARM_AAPCS_VFP:
2150    return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
2151  case CallingConv::Fast:
2152    return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
2153  case CallingConv::GHC:
2154    return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
2155  case CallingConv::PreserveMost:
2156    return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
2157  case CallingConv::PreserveAll:
2158    return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
2159  case CallingConv::CFGuard_Check:
2160    return (Return ? RetCC_ARM_AAPCS : CC_ARM_Win32_CFGuard_Check);
2161  }
2162}
2163
2164SDValue ARMTargetLowering::MoveToHPR(const SDLoc &dl, SelectionDAG &DAG,
2165                                     MVT LocVT, MVT ValVT, SDValue Val) const {
2166  Val = DAG.getNode(ISD::BITCAST, dl, MVT::getIntegerVT(LocVT.getSizeInBits()),
2167                    Val);
2168  if (Subtarget->hasFullFP16()) {
2169    Val = DAG.getNode(ARMISD::VMOVhr, dl, ValVT, Val);
2170  } else {
2171    Val = DAG.getNode(ISD::TRUNCATE, dl,
2172                      MVT::getIntegerVT(ValVT.getSizeInBits()), Val);
2173    Val = DAG.getNode(ISD::BITCAST, dl, ValVT, Val);
2174  }
2175  return Val;
2176}
2177
2178SDValue ARMTargetLowering::MoveFromHPR(const SDLoc &dl, SelectionDAG &DAG,
2179                                       MVT LocVT, MVT ValVT,
2180                                       SDValue Val) const {
2181  if (Subtarget->hasFullFP16()) {
2182    Val = DAG.getNode(ARMISD::VMOVrh, dl,
2183                      MVT::getIntegerVT(LocVT.getSizeInBits()), Val);
2184  } else {
2185    Val = DAG.getNode(ISD::BITCAST, dl,
2186                      MVT::getIntegerVT(ValVT.getSizeInBits()), Val);
2187    Val = DAG.getNode(ISD::ZERO_EXTEND, dl,
2188                      MVT::getIntegerVT(LocVT.getSizeInBits()), Val);
2189  }
2190  return DAG.getNode(ISD::BITCAST, dl, LocVT, Val);
2191}
2192
2193/// LowerCallResult - Lower the result values of a call into the
2194/// appropriate copies out of appropriate physical registers.
2195SDValue ARMTargetLowering::LowerCallResult(
2196    SDValue Chain, SDValue InGlue, CallingConv::ID CallConv, bool isVarArg,
2197    const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
2198    SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
2199    SDValue ThisVal) const {
2200  // Assign locations to each value returned by this call.
2201  SmallVector<CCValAssign, 16> RVLocs;
2202  CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2203                 *DAG.getContext());
2204  CCInfo.AnalyzeCallResult(Ins, CCAssignFnForReturn(CallConv, isVarArg));
2205
2206  // Copy all of the result registers out of their specified physreg.
2207  for (unsigned i = 0; i != RVLocs.size(); ++i) {
2208    CCValAssign VA = RVLocs[i];
2209
2210    // Pass 'this' value directly from the argument to return value, to avoid
2211    // reg unit interference
2212    if (i == 0 && isThisReturn) {
2213      assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
2214             "unexpected return calling convention register assignment");
2215      InVals.push_back(ThisVal);
2216      continue;
2217    }
2218
2219    SDValue Val;
2220    if (VA.needsCustom() &&
2221        (VA.getLocVT() == MVT::f64 || VA.getLocVT() == MVT::v2f64)) {
2222      // Handle f64 or half of a v2f64.
2223      SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
2224                                      InGlue);
2225      Chain = Lo.getValue(1);
2226      InGlue = Lo.getValue(2);
2227      VA = RVLocs[++i]; // skip ahead to next loc
2228      SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
2229                                      InGlue);
2230      Chain = Hi.getValue(1);
2231      InGlue = Hi.getValue(2);
2232      if (!Subtarget->isLittle())
2233        std::swap (Lo, Hi);
2234      Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
2235
2236      if (VA.getLocVT() == MVT::v2f64) {
2237        SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
2238        Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
2239                          DAG.getConstant(0, dl, MVT::i32));
2240
2241        VA = RVLocs[++i]; // skip ahead to next loc
2242        Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InGlue);
2243        Chain = Lo.getValue(1);
2244        InGlue = Lo.getValue(2);
2245        VA = RVLocs[++i]; // skip ahead to next loc
2246        Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InGlue);
2247        Chain = Hi.getValue(1);
2248        InGlue = Hi.getValue(2);
2249        if (!Subtarget->isLittle())
2250          std::swap (Lo, Hi);
2251        Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
2252        Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
2253                          DAG.getConstant(1, dl, MVT::i32));
2254      }
2255    } else {
2256      Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
2257                               InGlue);
2258      Chain = Val.getValue(1);
2259      InGlue = Val.getValue(2);
2260    }
2261
2262    switch (VA.getLocInfo()) {
2263    default: llvm_unreachable("Unknown loc info!");
2264    case CCValAssign::Full: break;
2265    case CCValAssign::BCvt:
2266      Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
2267      break;
2268    }
2269
2270    // f16 arguments have their size extended to 4 bytes and passed as if they
2271    // had been copied to the LSBs of a 32-bit register.
2272    // For that, it's passed extended to i32 (soft ABI) or to f32 (hard ABI)
2273    if (VA.needsCustom() &&
2274        (VA.getValVT() == MVT::f16 || VA.getValVT() == MVT::bf16))
2275      Val = MoveToHPR(dl, DAG, VA.getLocVT(), VA.getValVT(), Val);
2276
2277    InVals.push_back(Val);
2278  }
2279
2280  return Chain;
2281}
2282
2283std::pair<SDValue, MachinePointerInfo> ARMTargetLowering::computeAddrForCallArg(
2284    const SDLoc &dl, SelectionDAG &DAG, const CCValAssign &VA, SDValue StackPtr,
2285    bool IsTailCall, int SPDiff) const {
2286  SDValue DstAddr;
2287  MachinePointerInfo DstInfo;
2288  int32_t Offset = VA.getLocMemOffset();
2289  MachineFunction &MF = DAG.getMachineFunction();
2290
2291  if (IsTailCall) {
2292        Offset += SPDiff;
2293        auto PtrVT = getPointerTy(DAG.getDataLayout());
2294        int Size = VA.getLocVT().getFixedSizeInBits() / 8;
2295        int FI = MF.getFrameInfo().CreateFixedObject(Size, Offset, true);
2296        DstAddr = DAG.getFrameIndex(FI, PtrVT);
2297        DstInfo =
2298            MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
2299  } else {
2300        SDValue PtrOff = DAG.getIntPtrConstant(Offset, dl);
2301        DstAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2302                              StackPtr, PtrOff);
2303        DstInfo =
2304            MachinePointerInfo::getStack(DAG.getMachineFunction(), Offset);
2305  }
2306
2307  return std::make_pair(DstAddr, DstInfo);
2308}
2309
2310void ARMTargetLowering::PassF64ArgInRegs(const SDLoc &dl, SelectionDAG &DAG,
2311                                         SDValue Chain, SDValue &Arg,
2312                                         RegsToPassVector &RegsToPass,
2313                                         CCValAssign &VA, CCValAssign &NextVA,
2314                                         SDValue &StackPtr,
2315                                         SmallVectorImpl<SDValue> &MemOpChains,
2316                                         bool IsTailCall,
2317                                         int SPDiff) const {
2318  SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2319                              DAG.getVTList(MVT::i32, MVT::i32), Arg);
2320  unsigned id = Subtarget->isLittle() ? 0 : 1;
2321  RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
2322
2323  if (NextVA.isRegLoc())
2324    RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
2325  else {
2326    assert(NextVA.isMemLoc());
2327    if (!StackPtr.getNode())
2328      StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP,
2329                                    getPointerTy(DAG.getDataLayout()));
2330
2331    SDValue DstAddr;
2332    MachinePointerInfo DstInfo;
2333    std::tie(DstAddr, DstInfo) =
2334        computeAddrForCallArg(dl, DAG, NextVA, StackPtr, IsTailCall, SPDiff);
2335    MemOpChains.push_back(
2336        DAG.getStore(Chain, dl, fmrrd.getValue(1 - id), DstAddr, DstInfo));
2337  }
2338}
2339
2340static bool canGuaranteeTCO(CallingConv::ID CC, bool GuaranteeTailCalls) {
2341  return (CC == CallingConv::Fast && GuaranteeTailCalls) ||
2342         CC == CallingConv::Tail || CC == CallingConv::SwiftTail;
2343}
2344
2345/// LowerCall - Lowering a call into a callseq_start <-
2346/// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
2347/// nodes.
2348SDValue
2349ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2350                             SmallVectorImpl<SDValue> &InVals) const {
2351  SelectionDAG &DAG                     = CLI.DAG;
2352  SDLoc &dl                             = CLI.DL;
2353  SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2354  SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2355  SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2356  SDValue Chain                         = CLI.Chain;
2357  SDValue Callee                        = CLI.Callee;
2358  bool &isTailCall                      = CLI.IsTailCall;
2359  CallingConv::ID CallConv              = CLI.CallConv;
2360  bool doesNotRet                       = CLI.DoesNotReturn;
2361  bool isVarArg                         = CLI.IsVarArg;
2362
2363  MachineFunction &MF = DAG.getMachineFunction();
2364  ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2365  MachineFunction::CallSiteInfo CSInfo;
2366  bool isStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
2367  bool isThisReturn = false;
2368  bool isCmseNSCall   = false;
2369  bool isSibCall = false;
2370  bool PreferIndirect = false;
2371  bool GuardWithBTI = false;
2372
2373  // Lower 'returns_twice' calls to a pseudo-instruction.
2374  if (CLI.CB && CLI.CB->getAttributes().hasFnAttr(Attribute::ReturnsTwice) &&
2375      !Subtarget->noBTIAtReturnTwice())
2376    GuardWithBTI = AFI->branchTargetEnforcement();
2377
2378  // Determine whether this is a non-secure function call.
2379  if (CLI.CB && CLI.CB->getAttributes().hasFnAttr("cmse_nonsecure_call"))
2380    isCmseNSCall = true;
2381
2382  // Disable tail calls if they're not supported.
2383  if (!Subtarget->supportsTailCall())
2384    isTailCall = false;
2385
2386  // For both the non-secure calls and the returns from a CMSE entry function,
2387  // the function needs to do some extra work afte r the call, or before the
2388  // return, respectively, thus it cannot end with atail call
2389  if (isCmseNSCall || AFI->isCmseNSEntryFunction())
2390    isTailCall = false;
2391
2392  if (isa<GlobalAddressSDNode>(Callee)) {
2393    // If we're optimizing for minimum size and the function is called three or
2394    // more times in this block, we can improve codesize by calling indirectly
2395    // as BLXr has a 16-bit encoding.
2396    auto *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal();
2397    if (CLI.CB) {
2398      auto *BB = CLI.CB->getParent();
2399      PreferIndirect = Subtarget->isThumb() && Subtarget->hasMinSize() &&
2400                       count_if(GV->users(), [&BB](const User *U) {
2401                         return isa<Instruction>(U) &&
2402                                cast<Instruction>(U)->getParent() == BB;
2403                       }) > 2;
2404    }
2405  }
2406  if (isTailCall) {
2407    // Check if it's really possible to do a tail call.
2408    isTailCall = IsEligibleForTailCallOptimization(
2409        Callee, CallConv, isVarArg, isStructRet,
2410        MF.getFunction().hasStructRetAttr(), Outs, OutVals, Ins, DAG,
2411        PreferIndirect);
2412
2413    if (isTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt &&
2414        CallConv != CallingConv::Tail && CallConv != CallingConv::SwiftTail)
2415      isSibCall = true;
2416
2417    // We don't support GuaranteedTailCallOpt for ARM, only automatically
2418    // detected sibcalls.
2419    if (isTailCall)
2420      ++NumTailCalls;
2421  }
2422
2423  if (!isTailCall && CLI.CB && CLI.CB->isMustTailCall())
2424    report_fatal_error("failed to perform tail call elimination on a call "
2425                       "site marked musttail");
2426  // Analyze operands of the call, assigning locations to each operand.
2427  SmallVector<CCValAssign, 16> ArgLocs;
2428  CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2429                 *DAG.getContext());
2430  CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CallConv, isVarArg));
2431
2432  // Get a count of how many bytes are to be pushed on the stack.
2433  unsigned NumBytes = CCInfo.getStackSize();
2434
2435  // SPDiff is the byte offset of the call's argument area from the callee's.
2436  // Stores to callee stack arguments will be placed in FixedStackSlots offset
2437  // by this amount for a tail call. In a sibling call it must be 0 because the
2438  // caller will deallocate the entire stack and the callee still expects its
2439  // arguments to begin at SP+0. Completely unused for non-tail calls.
2440  int SPDiff = 0;
2441
2442  if (isTailCall && !isSibCall) {
2443    auto FuncInfo = MF.getInfo<ARMFunctionInfo>();
2444    unsigned NumReusableBytes = FuncInfo->getArgumentStackSize();
2445
2446    // Since callee will pop argument stack as a tail call, we must keep the
2447    // popped size 16-byte aligned.
2448    Align StackAlign = DAG.getDataLayout().getStackAlignment();
2449    NumBytes = alignTo(NumBytes, StackAlign);
2450
2451    // SPDiff will be negative if this tail call requires more space than we
2452    // would automatically have in our incoming argument space. Positive if we
2453    // can actually shrink the stack.
2454    SPDiff = NumReusableBytes - NumBytes;
2455
2456    // If this call requires more stack than we have available from
2457    // LowerFormalArguments, tell FrameLowering to reserve space for it.
2458    if (SPDiff < 0 && AFI->getArgRegsSaveSize() < (unsigned)-SPDiff)
2459      AFI->setArgRegsSaveSize(-SPDiff);
2460  }
2461
2462  if (isSibCall) {
2463    // For sibling tail calls, memory operands are available in our caller's stack.
2464    NumBytes = 0;
2465  } else {
2466    // Adjust the stack pointer for the new arguments...
2467    // These operations are automatically eliminated by the prolog/epilog pass
2468    Chain = DAG.getCALLSEQ_START(Chain, isTailCall ? 0 : NumBytes, 0, dl);
2469  }
2470
2471  SDValue StackPtr =
2472      DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout()));
2473
2474  RegsToPassVector RegsToPass;
2475  SmallVector<SDValue, 8> MemOpChains;
2476
2477  // During a tail call, stores to the argument area must happen after all of
2478  // the function's incoming arguments have been loaded because they may alias.
2479  // This is done by folding in a TokenFactor from LowerFormalArguments, but
2480  // there's no point in doing so repeatedly so this tracks whether that's
2481  // happened yet.
2482  bool AfterFormalArgLoads = false;
2483
2484  // Walk the register/memloc assignments, inserting copies/loads.  In the case
2485  // of tail call optimization, arguments are handled later.
2486  for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2487       i != e;
2488       ++i, ++realArgIdx) {
2489    CCValAssign &VA = ArgLocs[i];
2490    SDValue Arg = OutVals[realArgIdx];
2491    ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2492    bool isByVal = Flags.isByVal();
2493
2494    // Promote the value if needed.
2495    switch (VA.getLocInfo()) {
2496    default: llvm_unreachable("Unknown loc info!");
2497    case CCValAssign::Full: break;
2498    case CCValAssign::SExt:
2499      Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
2500      break;
2501    case CCValAssign::ZExt:
2502      Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
2503      break;
2504    case CCValAssign::AExt:
2505      Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
2506      break;
2507    case CCValAssign::BCvt:
2508      Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2509      break;
2510    }
2511
2512    if (isTailCall && VA.isMemLoc() && !AfterFormalArgLoads) {
2513      Chain = DAG.getStackArgumentTokenFactor(Chain);
2514      AfterFormalArgLoads = true;
2515    }
2516
2517    // f16 arguments have their size extended to 4 bytes and passed as if they
2518    // had been copied to the LSBs of a 32-bit register.
2519    // For that, it's passed extended to i32 (soft ABI) or to f32 (hard ABI)
2520    if (VA.needsCustom() &&
2521        (VA.getValVT() == MVT::f16 || VA.getValVT() == MVT::bf16)) {
2522      Arg = MoveFromHPR(dl, DAG, VA.getLocVT(), VA.getValVT(), Arg);
2523    } else {
2524      // f16 arguments could have been extended prior to argument lowering.
2525      // Mask them arguments if this is a CMSE nonsecure call.
2526      auto ArgVT = Outs[realArgIdx].ArgVT;
2527      if (isCmseNSCall && (ArgVT == MVT::f16)) {
2528        auto LocBits = VA.getLocVT().getSizeInBits();
2529        auto MaskValue = APInt::getLowBitsSet(LocBits, ArgVT.getSizeInBits());
2530        SDValue Mask =
2531            DAG.getConstant(MaskValue, dl, MVT::getIntegerVT(LocBits));
2532        Arg = DAG.getNode(ISD::BITCAST, dl, MVT::getIntegerVT(LocBits), Arg);
2533        Arg = DAG.getNode(ISD::AND, dl, MVT::getIntegerVT(LocBits), Arg, Mask);
2534        Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2535      }
2536    }
2537
2538    // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
2539    if (VA.needsCustom() && VA.getLocVT() == MVT::v2f64) {
2540      SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2541                                DAG.getConstant(0, dl, MVT::i32));
2542      SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2543                                DAG.getConstant(1, dl, MVT::i32));
2544
2545      PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass, VA, ArgLocs[++i],
2546                       StackPtr, MemOpChains, isTailCall, SPDiff);
2547
2548      VA = ArgLocs[++i]; // skip ahead to next loc
2549      if (VA.isRegLoc()) {
2550        PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass, VA, ArgLocs[++i],
2551                         StackPtr, MemOpChains, isTailCall, SPDiff);
2552      } else {
2553        assert(VA.isMemLoc());
2554        SDValue DstAddr;
2555        MachinePointerInfo DstInfo;
2556        std::tie(DstAddr, DstInfo) =
2557            computeAddrForCallArg(dl, DAG, VA, StackPtr, isTailCall, SPDiff);
2558        MemOpChains.push_back(DAG.getStore(Chain, dl, Op1, DstAddr, DstInfo));
2559      }
2560    } else if (VA.needsCustom() && VA.getLocVT() == MVT::f64) {
2561      PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
2562                       StackPtr, MemOpChains, isTailCall, SPDiff);
2563    } else if (VA.isRegLoc()) {
2564      if (realArgIdx == 0 && Flags.isReturned() && !Flags.isSwiftSelf() &&
2565          Outs[0].VT == MVT::i32) {
2566        assert(VA.getLocVT() == MVT::i32 &&
2567               "unexpected calling convention register assignment");
2568        assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
2569               "unexpected use of 'returned'");
2570        isThisReturn = true;
2571      }
2572      const TargetOptions &Options = DAG.getTarget().Options;
2573      if (Options.EmitCallSiteInfo)
2574        CSInfo.emplace_back(VA.getLocReg(), i);
2575      RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2576    } else if (isByVal) {
2577      assert(VA.isMemLoc());
2578      unsigned offset = 0;
2579
2580      // True if this byval aggregate will be split between registers
2581      // and memory.
2582      unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
2583      unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed();
2584
2585      if (CurByValIdx < ByValArgsCount) {
2586
2587        unsigned RegBegin, RegEnd;
2588        CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
2589
2590        EVT PtrVT =
2591            DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2592        unsigned int i, j;
2593        for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
2594          SDValue Const = DAG.getConstant(4*i, dl, MVT::i32);
2595          SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
2596          SDValue Load =
2597              DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo(),
2598                          DAG.InferPtrAlign(AddArg));
2599          MemOpChains.push_back(Load.getValue(1));
2600          RegsToPass.push_back(std::make_pair(j, Load));
2601        }
2602
2603        // If parameter size outsides register area, "offset" value
2604        // helps us to calculate stack slot for remained part properly.
2605        offset = RegEnd - RegBegin;
2606
2607        CCInfo.nextInRegsParam();
2608      }
2609
2610      if (Flags.getByValSize() > 4*offset) {
2611        auto PtrVT = getPointerTy(DAG.getDataLayout());
2612        SDValue Dst;
2613        MachinePointerInfo DstInfo;
2614        std::tie(Dst, DstInfo) =
2615            computeAddrForCallArg(dl, DAG, VA, StackPtr, isTailCall, SPDiff);
2616        SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl);
2617        SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, SrcOffset);
2618        SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl,
2619                                           MVT::i32);
2620        SDValue AlignNode =
2621            DAG.getConstant(Flags.getNonZeroByValAlign().value(), dl, MVT::i32);
2622
2623        SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
2624        SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
2625        MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
2626                                          Ops));
2627      }
2628    } else {
2629      assert(VA.isMemLoc());
2630      SDValue DstAddr;
2631      MachinePointerInfo DstInfo;
2632      std::tie(DstAddr, DstInfo) =
2633          computeAddrForCallArg(dl, DAG, VA, StackPtr, isTailCall, SPDiff);
2634
2635      SDValue Store = DAG.getStore(Chain, dl, Arg, DstAddr, DstInfo);
2636      MemOpChains.push_back(Store);
2637    }
2638  }
2639
2640  if (!MemOpChains.empty())
2641    Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2642
2643  // Build a sequence of copy-to-reg nodes chained together with token chain
2644  // and flag operands which copy the outgoing args into the appropriate regs.
2645  SDValue InGlue;
2646  for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2647    Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2648                             RegsToPass[i].second, InGlue);
2649    InGlue = Chain.getValue(1);
2650  }
2651
2652  // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
2653  // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
2654  // node so that legalize doesn't hack it.
2655  bool isDirect = false;
2656
2657  const TargetMachine &TM = getTargetMachine();
2658  const Module *Mod = MF.getFunction().getParent();
2659  const GlobalValue *GVal = nullptr;
2660  if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
2661    GVal = G->getGlobal();
2662  bool isStub =
2663      !TM.shouldAssumeDSOLocal(*Mod, GVal) && Subtarget->isTargetMachO();
2664
2665  bool isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
2666  bool isLocalARMFunc = false;
2667  auto PtrVt = getPointerTy(DAG.getDataLayout());
2668
2669  if (Subtarget->genLongCalls()) {
2670    assert((!isPositionIndependent() || Subtarget->isTargetWindows()) &&
2671           "long-calls codegen is not position independent!");
2672    // Handle a global address or an external symbol. If it's not one of
2673    // those, the target's already in a register, so we don't need to do
2674    // anything extra.
2675    if (isa<GlobalAddressSDNode>(Callee)) {
2676      if (Subtarget->genExecuteOnly()) {
2677        if (Subtarget->useMovt())
2678          ++NumMovwMovt;
2679        Callee = DAG.getNode(ARMISD::Wrapper, dl, PtrVt,
2680                             DAG.getTargetGlobalAddress(GVal, dl, PtrVt));
2681      } else {
2682        // Create a constant pool entry for the callee address
2683        unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2684        ARMConstantPoolValue *CPV = ARMConstantPoolConstant::Create(
2685            GVal, ARMPCLabelIndex, ARMCP::CPValue, 0);
2686
2687        // Get the address of the callee into a register
2688        SDValue Addr = DAG.getTargetConstantPool(CPV, PtrVt, Align(4));
2689        Addr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Addr);
2690        Callee = DAG.getLoad(
2691            PtrVt, dl, DAG.getEntryNode(), Addr,
2692            MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2693      }
2694    } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
2695      const char *Sym = S->getSymbol();
2696
2697      if (Subtarget->genExecuteOnly()) {
2698        if (Subtarget->useMovt())
2699          ++NumMovwMovt;
2700        Callee = DAG.getNode(ARMISD::Wrapper, dl, PtrVt,
2701                             DAG.getTargetGlobalAddress(GVal, dl, PtrVt));
2702      } else {
2703        // Create a constant pool entry for the callee address
2704        unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2705        ARMConstantPoolValue *CPV = ARMConstantPoolSymbol::Create(
2706            *DAG.getContext(), Sym, ARMPCLabelIndex, 0);
2707
2708        // Get the address of the callee into a register
2709        SDValue Addr = DAG.getTargetConstantPool(CPV, PtrVt, Align(4));
2710        Addr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Addr);
2711        Callee = DAG.getLoad(
2712            PtrVt, dl, DAG.getEntryNode(), Addr,
2713            MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2714      }
2715    }
2716  } else if (isa<GlobalAddressSDNode>(Callee)) {
2717    if (!PreferIndirect) {
2718      isDirect = true;
2719      bool isDef = GVal->isStrongDefinitionForLinker();
2720
2721      // ARM call to a local ARM function is predicable.
2722      isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking);
2723      // tBX takes a register source operand.
2724      if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
2725        assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
2726        Callee = DAG.getNode(
2727            ARMISD::WrapperPIC, dl, PtrVt,
2728            DAG.getTargetGlobalAddress(GVal, dl, PtrVt, 0, ARMII::MO_NONLAZY));
2729        Callee = DAG.getLoad(
2730            PtrVt, dl, DAG.getEntryNode(), Callee,
2731            MachinePointerInfo::getGOT(DAG.getMachineFunction()), MaybeAlign(),
2732            MachineMemOperand::MODereferenceable |
2733                MachineMemOperand::MOInvariant);
2734      } else if (Subtarget->isTargetCOFF()) {
2735        assert(Subtarget->isTargetWindows() &&
2736               "Windows is the only supported COFF target");
2737        unsigned TargetFlags = ARMII::MO_NO_FLAG;
2738        if (GVal->hasDLLImportStorageClass())
2739          TargetFlags = ARMII::MO_DLLIMPORT;
2740        else if (!TM.shouldAssumeDSOLocal(*GVal->getParent(), GVal))
2741          TargetFlags = ARMII::MO_COFFSTUB;
2742        Callee = DAG.getTargetGlobalAddress(GVal, dl, PtrVt, /*offset=*/0,
2743                                            TargetFlags);
2744        if (TargetFlags & (ARMII::MO_DLLIMPORT | ARMII::MO_COFFSTUB))
2745          Callee =
2746              DAG.getLoad(PtrVt, dl, DAG.getEntryNode(),
2747                          DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee),
2748                          MachinePointerInfo::getGOT(DAG.getMachineFunction()));
2749      } else {
2750        Callee = DAG.getTargetGlobalAddress(GVal, dl, PtrVt, 0, 0);
2751      }
2752    }
2753  } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2754    isDirect = true;
2755    // tBX takes a register source operand.
2756    const char *Sym = S->getSymbol();
2757    if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
2758      unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2759      ARMConstantPoolValue *CPV =
2760        ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
2761                                      ARMPCLabelIndex, 4);
2762      SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, Align(4));
2763      CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2764      Callee = DAG.getLoad(
2765          PtrVt, dl, DAG.getEntryNode(), CPAddr,
2766          MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2767      SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2768      Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel);
2769    } else {
2770      Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, 0);
2771    }
2772  }
2773
2774  if (isCmseNSCall) {
2775    assert(!isARMFunc && !isDirect &&
2776           "Cannot handle call to ARM function or direct call");
2777    if (NumBytes > 0) {
2778      DiagnosticInfoUnsupported Diag(DAG.getMachineFunction().getFunction(),
2779                                     "call to non-secure function would "
2780                                     "require passing arguments on stack",
2781                                     dl.getDebugLoc());
2782      DAG.getContext()->diagnose(Diag);
2783    }
2784    if (isStructRet) {
2785      DiagnosticInfoUnsupported Diag(
2786          DAG.getMachineFunction().getFunction(),
2787          "call to non-secure function would return value through pointer",
2788          dl.getDebugLoc());
2789      DAG.getContext()->diagnose(Diag);
2790    }
2791  }
2792
2793  // FIXME: handle tail calls differently.
2794  unsigned CallOpc;
2795  if (Subtarget->isThumb()) {
2796    if (GuardWithBTI)
2797      CallOpc = ARMISD::t2CALL_BTI;
2798    else if (isCmseNSCall)
2799      CallOpc = ARMISD::tSECALL;
2800    else if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
2801      CallOpc = ARMISD::CALL_NOLINK;
2802    else
2803      CallOpc = ARMISD::CALL;
2804  } else {
2805    if (!isDirect && !Subtarget->hasV5TOps())
2806      CallOpc = ARMISD::CALL_NOLINK;
2807    else if (doesNotRet && isDirect && Subtarget->hasRetAddrStack() &&
2808             // Emit regular call when code size is the priority
2809             !Subtarget->hasMinSize())
2810      // "mov lr, pc; b _foo" to avoid confusing the RSP
2811      CallOpc = ARMISD::CALL_NOLINK;
2812    else
2813      CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
2814  }
2815
2816  // We don't usually want to end the call-sequence here because we would tidy
2817  // the frame up *after* the call, however in the ABI-changing tail-call case
2818  // we've carefully laid out the parameters so that when sp is reset they'll be
2819  // in the correct location.
2820  if (isTailCall && !isSibCall) {
2821    Chain = DAG.getCALLSEQ_END(Chain, 0, 0, InGlue, dl);
2822    InGlue = Chain.getValue(1);
2823  }
2824
2825  std::vector<SDValue> Ops;
2826  Ops.push_back(Chain);
2827  Ops.push_back(Callee);
2828
2829  if (isTailCall) {
2830    Ops.push_back(DAG.getTargetConstant(SPDiff, dl, MVT::i32));
2831  }
2832
2833  // Add argument registers to the end of the list so that they are known live
2834  // into the call.
2835  for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2836    Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2837                                  RegsToPass[i].second.getValueType()));
2838
2839  // Add a register mask operand representing the call-preserved registers.
2840  const uint32_t *Mask;
2841  const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
2842  if (isThisReturn) {
2843    // For 'this' returns, use the R0-preserving mask if applicable
2844    Mask = ARI->getThisReturnPreservedMask(MF, CallConv);
2845    if (!Mask) {
2846      // Set isThisReturn to false if the calling convention is not one that
2847      // allows 'returned' to be modeled in this way, so LowerCallResult does
2848      // not try to pass 'this' straight through
2849      isThisReturn = false;
2850      Mask = ARI->getCallPreservedMask(MF, CallConv);
2851    }
2852  } else
2853    Mask = ARI->getCallPreservedMask(MF, CallConv);
2854
2855  assert(Mask && "Missing call preserved mask for calling convention");
2856  Ops.push_back(DAG.getRegisterMask(Mask));
2857
2858  if (InGlue.getNode())
2859    Ops.push_back(InGlue);
2860
2861  SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2862  if (isTailCall) {
2863    MF.getFrameInfo().setHasTailCall();
2864    SDValue Ret = DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
2865    DAG.addNoMergeSiteInfo(Ret.getNode(), CLI.NoMerge);
2866    DAG.addCallSiteInfo(Ret.getNode(), std::move(CSInfo));
2867    return Ret;
2868  }
2869
2870  // Returns a chain and a flag for retval copy to use.
2871  Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
2872  DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge);
2873  InGlue = Chain.getValue(1);
2874  DAG.addCallSiteInfo(Chain.getNode(), std::move(CSInfo));
2875
2876  // If we're guaranteeing tail-calls will be honoured, the callee must
2877  // pop its own argument stack on return. But this call is *not* a tail call so
2878  // we need to undo that after it returns to restore the status-quo.
2879  bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt;
2880  uint64_t CalleePopBytes =
2881      canGuaranteeTCO(CallConv, TailCallOpt) ? alignTo(NumBytes, 16) : -1ULL;
2882
2883  Chain = DAG.getCALLSEQ_END(Chain, NumBytes, CalleePopBytes, InGlue, dl);
2884  if (!Ins.empty())
2885    InGlue = Chain.getValue(1);
2886
2887  // Handle result values, copying them out of physregs into vregs that we
2888  // return.
2889  return LowerCallResult(Chain, InGlue, CallConv, isVarArg, Ins, dl, DAG,
2890                         InVals, isThisReturn,
2891                         isThisReturn ? OutVals[0] : SDValue());
2892}
2893
2894/// HandleByVal - Every parameter *after* a byval parameter is passed
2895/// on the stack.  Remember the next parameter register to allocate,
2896/// and then confiscate the rest of the parameter registers to insure
2897/// this.
2898void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size,
2899                                    Align Alignment) const {
2900  // Byval (as with any stack) slots are always at least 4 byte aligned.
2901  Alignment = std::max(Alignment, Align(4));
2902
2903  unsigned Reg = State->AllocateReg(GPRArgRegs);
2904  if (!Reg)
2905    return;
2906
2907  unsigned AlignInRegs = Alignment.value() / 4;
2908  unsigned Waste = (ARM::R4 - Reg) % AlignInRegs;
2909  for (unsigned i = 0; i < Waste; ++i)
2910    Reg = State->AllocateReg(GPRArgRegs);
2911
2912  if (!Reg)
2913    return;
2914
2915  unsigned Excess = 4 * (ARM::R4 - Reg);
2916
2917  // Special case when NSAA != SP and parameter size greater than size of
2918  // all remained GPR regs. In that case we can't split parameter, we must
2919  // send it to stack. We also must set NCRN to R4, so waste all
2920  // remained registers.
2921  const unsigned NSAAOffset = State->getStackSize();
2922  if (NSAAOffset != 0 && Size > Excess) {
2923    while (State->AllocateReg(GPRArgRegs))
2924      ;
2925    return;
2926  }
2927
2928  // First register for byval parameter is the first register that wasn't
2929  // allocated before this method call, so it would be "reg".
2930  // If parameter is small enough to be saved in range [reg, r4), then
2931  // the end (first after last) register would be reg + param-size-in-regs,
2932  // else parameter would be splitted between registers and stack,
2933  // end register would be r4 in this case.
2934  unsigned ByValRegBegin = Reg;
2935  unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4);
2936  State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
2937  // Note, first register is allocated in the beginning of function already,
2938  // allocate remained amount of registers we need.
2939  for (unsigned i = Reg + 1; i != ByValRegEnd; ++i)
2940    State->AllocateReg(GPRArgRegs);
2941  // A byval parameter that is split between registers and memory needs its
2942  // size truncated here.
2943  // In the case where the entire structure fits in registers, we set the
2944  // size in memory to zero.
2945  Size = std::max<int>(Size - Excess, 0);
2946}
2947
2948/// MatchingStackOffset - Return true if the given stack call argument is
2949/// already available in the same position (relatively) of the caller's
2950/// incoming argument stack.
2951static
2952bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2953                         MachineFrameInfo &MFI, const MachineRegisterInfo *MRI,
2954                         const TargetInstrInfo *TII) {
2955  unsigned Bytes = Arg.getValueSizeInBits() / 8;
2956  int FI = std::numeric_limits<int>::max();
2957  if (Arg.getOpcode() == ISD::CopyFromReg) {
2958    Register VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2959    if (!VR.isVirtual())
2960      return false;
2961    MachineInstr *Def = MRI->getVRegDef(VR);
2962    if (!Def)
2963      return false;
2964    if (!Flags.isByVal()) {
2965      if (!TII->isLoadFromStackSlot(*Def, FI))
2966        return false;
2967    } else {
2968      return false;
2969    }
2970  } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2971    if (Flags.isByVal())
2972      // ByVal argument is passed in as a pointer but it's now being
2973      // dereferenced. e.g.
2974      // define @foo(%struct.X* %A) {
2975      //   tail call @bar(%struct.X* byval %A)
2976      // }
2977      return false;
2978    SDValue Ptr = Ld->getBasePtr();
2979    FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2980    if (!FINode)
2981      return false;
2982    FI = FINode->getIndex();
2983  } else
2984    return false;
2985
2986  assert(FI != std::numeric_limits<int>::max());
2987  if (!MFI.isFixedObjectIndex(FI))
2988    return false;
2989  return Offset == MFI.getObjectOffset(FI) && Bytes == MFI.getObjectSize(FI);
2990}
2991
2992/// IsEligibleForTailCallOptimization - Check whether the call is eligible
2993/// for tail call optimization. Targets which want to do tail call
2994/// optimization should implement this function.
2995bool ARMTargetLowering::IsEligibleForTailCallOptimization(
2996    SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
2997    bool isCalleeStructRet, bool isCallerStructRet,
2998    const SmallVectorImpl<ISD::OutputArg> &Outs,
2999    const SmallVectorImpl<SDValue> &OutVals,
3000    const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG,
3001    const bool isIndirect) const {
3002  MachineFunction &MF = DAG.getMachineFunction();
3003  const Function &CallerF = MF.getFunction();
3004  CallingConv::ID CallerCC = CallerF.getCallingConv();
3005
3006  assert(Subtarget->supportsTailCall());
3007
3008  // Indirect tail calls cannot be optimized for Thumb1 if the args
3009  // to the call take up r0-r3. The reason is that there are no legal registers
3010  // left to hold the pointer to the function to be called.
3011  // Similarly, if the function uses return address sign and authentication,
3012  // r12 is needed to hold the PAC and is not available to hold the callee
3013  // address.
3014  if (Outs.size() >= 4 &&
3015      (!isa<GlobalAddressSDNode>(Callee.getNode()) || isIndirect)) {
3016    if (Subtarget->isThumb1Only())
3017      return false;
3018    // Conservatively assume the function spills LR.
3019    if (MF.getInfo<ARMFunctionInfo>()->shouldSignReturnAddress(true))
3020      return false;
3021  }
3022
3023  // Look for obvious safe cases to perform tail call optimization that do not
3024  // require ABI changes. This is what gcc calls sibcall.
3025
3026  // Exception-handling functions need a special set of instructions to indicate
3027  // a return to the hardware. Tail-calling another function would probably
3028  // break this.
3029  if (CallerF.hasFnAttribute("interrupt"))
3030    return false;
3031
3032  if (canGuaranteeTCO(CalleeCC, getTargetMachine().Options.GuaranteedTailCallOpt))
3033    return CalleeCC == CallerCC;
3034
3035  // Also avoid sibcall optimization if either caller or callee uses struct
3036  // return semantics.
3037  if (isCalleeStructRet || isCallerStructRet)
3038    return false;
3039
3040  // Externally-defined functions with weak linkage should not be
3041  // tail-called on ARM when the OS does not support dynamic
3042  // pre-emption of symbols, as the AAELF spec requires normal calls
3043  // to undefined weak functions to be replaced with a NOP or jump to the
3044  // next instruction. The behaviour of branch instructions in this
3045  // situation (as used for tail calls) is implementation-defined, so we
3046  // cannot rely on the linker replacing the tail call with a return.
3047  if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3048    const GlobalValue *GV = G->getGlobal();
3049    const Triple &TT = getTargetMachine().getTargetTriple();
3050    if (GV->hasExternalWeakLinkage() &&
3051        (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
3052      return false;
3053  }
3054
3055  // Check that the call results are passed in the same way.
3056  LLVMContext &C = *DAG.getContext();
3057  if (!CCState::resultsCompatible(
3058          getEffectiveCallingConv(CalleeCC, isVarArg),
3059          getEffectiveCallingConv(CallerCC, CallerF.isVarArg()), MF, C, Ins,
3060          CCAssignFnForReturn(CalleeCC, isVarArg),
3061          CCAssignFnForReturn(CallerCC, CallerF.isVarArg())))
3062    return false;
3063  // The callee has to preserve all registers the caller needs to preserve.
3064  const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
3065  const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
3066  if (CalleeCC != CallerCC) {
3067    const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
3068    if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
3069      return false;
3070  }
3071
3072  // If Caller's vararg or byval argument has been split between registers and
3073  // stack, do not perform tail call, since part of the argument is in caller's
3074  // local frame.
3075  const ARMFunctionInfo *AFI_Caller = MF.getInfo<ARMFunctionInfo>();
3076  if (AFI_Caller->getArgRegsSaveSize())
3077    return false;
3078
3079  // If the callee takes no arguments then go on to check the results of the
3080  // call.
3081  if (!Outs.empty()) {
3082    // Check if stack adjustment is needed. For now, do not do this if any
3083    // argument is passed on the stack.
3084    SmallVector<CCValAssign, 16> ArgLocs;
3085    CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
3086    CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
3087    if (CCInfo.getStackSize()) {
3088      // Check if the arguments are already laid out in the right way as
3089      // the caller's fixed stack objects.
3090      MachineFrameInfo &MFI = MF.getFrameInfo();
3091      const MachineRegisterInfo *MRI = &MF.getRegInfo();
3092      const TargetInstrInfo *TII = Subtarget->getInstrInfo();
3093      for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
3094           i != e;
3095           ++i, ++realArgIdx) {
3096        CCValAssign &VA = ArgLocs[i];
3097        EVT RegVT = VA.getLocVT();
3098        SDValue Arg = OutVals[realArgIdx];
3099        ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
3100        if (VA.getLocInfo() == CCValAssign::Indirect)
3101          return false;
3102        if (VA.needsCustom() && (RegVT == MVT::f64 || RegVT == MVT::v2f64)) {
3103          // f64 and vector types are split into multiple registers or
3104          // register/stack-slot combinations.  The types will not match
3105          // the registers; give up on memory f64 refs until we figure
3106          // out what to do about this.
3107          if (!VA.isRegLoc())
3108            return false;
3109          if (!ArgLocs[++i].isRegLoc())
3110            return false;
3111          if (RegVT == MVT::v2f64) {
3112            if (!ArgLocs[++i].isRegLoc())
3113              return false;
3114            if (!ArgLocs[++i].isRegLoc())
3115              return false;
3116          }
3117        } else if (!VA.isRegLoc()) {
3118          if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3119                                   MFI, MRI, TII))
3120            return false;
3121        }
3122      }
3123    }
3124
3125    const MachineRegisterInfo &MRI = MF.getRegInfo();
3126    if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
3127      return false;
3128  }
3129
3130  return true;
3131}
3132
3133bool
3134ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
3135                                  MachineFunction &MF, bool isVarArg,
3136                                  const SmallVectorImpl<ISD::OutputArg> &Outs,
3137                                  LLVMContext &Context) const {
3138  SmallVector<CCValAssign, 16> RVLocs;
3139  CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
3140  return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
3141}
3142
3143static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
3144                                    const SDLoc &DL, SelectionDAG &DAG) {
3145  const MachineFunction &MF = DAG.getMachineFunction();
3146  const Function &F = MF.getFunction();
3147
3148  StringRef IntKind = F.getFnAttribute("interrupt").getValueAsString();
3149
3150  // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
3151  // version of the "preferred return address". These offsets affect the return
3152  // instruction if this is a return from PL1 without hypervisor extensions.
3153  //    IRQ/FIQ: +4     "subs pc, lr, #4"
3154  //    SWI:     0      "subs pc, lr, #0"
3155  //    ABORT:   +4     "subs pc, lr, #4"
3156  //    UNDEF:   +4/+2  "subs pc, lr, #0"
3157  // UNDEF varies depending on where the exception came from ARM or Thumb
3158  // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
3159
3160  int64_t LROffset;
3161  if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
3162      IntKind == "ABORT")
3163    LROffset = 4;
3164  else if (IntKind == "SWI" || IntKind == "UNDEF")
3165    LROffset = 0;
3166  else
3167    report_fatal_error("Unsupported interrupt attribute. If present, value "
3168                       "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
3169
3170  RetOps.insert(RetOps.begin() + 1,
3171                DAG.getConstant(LROffset, DL, MVT::i32, false));
3172
3173  return DAG.getNode(ARMISD::INTRET_GLUE, DL, MVT::Other, RetOps);
3174}
3175
3176SDValue
3177ARMTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
3178                               bool isVarArg,
3179                               const SmallVectorImpl<ISD::OutputArg> &Outs,
3180                               const SmallVectorImpl<SDValue> &OutVals,
3181                               const SDLoc &dl, SelectionDAG &DAG) const {
3182  // CCValAssign - represent the assignment of the return value to a location.
3183  SmallVector<CCValAssign, 16> RVLocs;
3184
3185  // CCState - Info about the registers and stack slots.
3186  CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
3187                 *DAG.getContext());
3188
3189  // Analyze outgoing return values.
3190  CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
3191
3192  SDValue Glue;
3193  SmallVector<SDValue, 4> RetOps;
3194  RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
3195  bool isLittleEndian = Subtarget->isLittle();
3196
3197  MachineFunction &MF = DAG.getMachineFunction();
3198  ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3199  AFI->setReturnRegsCount(RVLocs.size());
3200
3201 // Report error if cmse entry function returns structure through first ptr arg.
3202  if (AFI->isCmseNSEntryFunction() && MF.getFunction().hasStructRetAttr()) {
3203    // Note: using an empty SDLoc(), as the first line of the function is a
3204    // better place to report than the last line.
3205    DiagnosticInfoUnsupported Diag(
3206        DAG.getMachineFunction().getFunction(),
3207        "secure entry function would return value through pointer",
3208        SDLoc().getDebugLoc());
3209    DAG.getContext()->diagnose(Diag);
3210  }
3211
3212  // Copy the result values into the output registers.
3213  for (unsigned i = 0, realRVLocIdx = 0;
3214       i != RVLocs.size();
3215       ++i, ++realRVLocIdx) {
3216    CCValAssign &VA = RVLocs[i];
3217    assert(VA.isRegLoc() && "Can only return in registers!");
3218
3219    SDValue Arg = OutVals[realRVLocIdx];
3220    bool ReturnF16 = false;
3221
3222    if (Subtarget->hasFullFP16() && Subtarget->isTargetHardFloat()) {
3223      // Half-precision return values can be returned like this:
3224      //
3225      // t11 f16 = fadd ...
3226      // t12: i16 = bitcast t11
3227      //   t13: i32 = zero_extend t12
3228      // t14: f32 = bitcast t13  <~~~~~~~ Arg
3229      //
3230      // to avoid code generation for bitcasts, we simply set Arg to the node
3231      // that produces the f16 value, t11 in this case.
3232      //
3233      if (Arg.getValueType() == MVT::f32 && Arg.getOpcode() == ISD::BITCAST) {
3234        SDValue ZE = Arg.getOperand(0);
3235        if (ZE.getOpcode() == ISD::ZERO_EXTEND && ZE.getValueType() == MVT::i32) {
3236          SDValue BC = ZE.getOperand(0);
3237          if (BC.getOpcode() == ISD::BITCAST && BC.getValueType() == MVT::i16) {
3238            Arg = BC.getOperand(0);
3239            ReturnF16 = true;
3240          }
3241        }
3242      }
3243    }
3244
3245    switch (VA.getLocInfo()) {
3246    default: llvm_unreachable("Unknown loc info!");
3247    case CCValAssign::Full: break;
3248    case CCValAssign::BCvt:
3249      if (!ReturnF16)
3250        Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
3251      break;
3252    }
3253
3254    // Mask f16 arguments if this is a CMSE nonsecure entry.
3255    auto RetVT = Outs[realRVLocIdx].ArgVT;
3256    if (AFI->isCmseNSEntryFunction() && (RetVT == MVT::f16)) {
3257      if (VA.needsCustom() && VA.getValVT() == MVT::f16) {
3258        Arg = MoveFromHPR(dl, DAG, VA.getLocVT(), VA.getValVT(), Arg);
3259      } else {
3260        auto LocBits = VA.getLocVT().getSizeInBits();
3261        auto MaskValue = APInt::getLowBitsSet(LocBits, RetVT.getSizeInBits());
3262        SDValue Mask =
3263            DAG.getConstant(MaskValue, dl, MVT::getIntegerVT(LocBits));
3264        Arg = DAG.getNode(ISD::BITCAST, dl, MVT::getIntegerVT(LocBits), Arg);
3265        Arg = DAG.getNode(ISD::AND, dl, MVT::getIntegerVT(LocBits), Arg, Mask);
3266        Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
3267      }
3268    }
3269
3270    if (VA.needsCustom() &&
3271        (VA.getLocVT() == MVT::v2f64 || VA.getLocVT() == MVT::f64)) {
3272      if (VA.getLocVT() == MVT::v2f64) {
3273        // Extract the first half and return it in two registers.
3274        SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
3275                                   DAG.getConstant(0, dl, MVT::i32));
3276        SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
3277                                       DAG.getVTList(MVT::i32, MVT::i32), Half);
3278
3279        Chain =
3280            DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
3281                             HalfGPRs.getValue(isLittleEndian ? 0 : 1), Glue);
3282        Glue = Chain.getValue(1);
3283        RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3284        VA = RVLocs[++i]; // skip ahead to next loc
3285        Chain =
3286            DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
3287                             HalfGPRs.getValue(isLittleEndian ? 1 : 0), Glue);
3288        Glue = Chain.getValue(1);
3289        RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3290        VA = RVLocs[++i]; // skip ahead to next loc
3291
3292        // Extract the 2nd half and fall through to handle it as an f64 value.
3293        Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
3294                          DAG.getConstant(1, dl, MVT::i32));
3295      }
3296      // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
3297      // available.
3298      SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
3299                                  DAG.getVTList(MVT::i32, MVT::i32), Arg);
3300      Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
3301                               fmrrd.getValue(isLittleEndian ? 0 : 1), Glue);
3302      Glue = Chain.getValue(1);
3303      RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3304      VA = RVLocs[++i]; // skip ahead to next loc
3305      Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
3306                               fmrrd.getValue(isLittleEndian ? 1 : 0), Glue);
3307    } else
3308      Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Glue);
3309
3310    // Guarantee that all emitted copies are
3311    // stuck together, avoiding something bad.
3312    Glue = Chain.getValue(1);
3313    RetOps.push_back(DAG.getRegister(
3314        VA.getLocReg(), ReturnF16 ? Arg.getValueType() : VA.getLocVT()));
3315  }
3316  const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
3317  const MCPhysReg *I =
3318      TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
3319  if (I) {
3320    for (; *I; ++I) {
3321      if (ARM::GPRRegClass.contains(*I))
3322        RetOps.push_back(DAG.getRegister(*I, MVT::i32));
3323      else if (ARM::DPRRegClass.contains(*I))
3324        RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
3325      else
3326        llvm_unreachable("Unexpected register class in CSRsViaCopy!");
3327    }
3328  }
3329
3330  // Update chain and glue.
3331  RetOps[0] = Chain;
3332  if (Glue.getNode())
3333    RetOps.push_back(Glue);
3334
3335  // CPUs which aren't M-class use a special sequence to return from
3336  // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
3337  // though we use "subs pc, lr, #N").
3338  //
3339  // M-class CPUs actually use a normal return sequence with a special
3340  // (hardware-provided) value in LR, so the normal code path works.
3341  if (DAG.getMachineFunction().getFunction().hasFnAttribute("interrupt") &&
3342      !Subtarget->isMClass()) {
3343    if (Subtarget->isThumb1Only())
3344      report_fatal_error("interrupt attribute is not supported in Thumb1");
3345    return LowerInterruptReturn(RetOps, dl, DAG);
3346  }
3347
3348  ARMISD::NodeType RetNode = AFI->isCmseNSEntryFunction() ? ARMISD::SERET_GLUE :
3349                                                            ARMISD::RET_GLUE;
3350  return DAG.getNode(RetNode, dl, MVT::Other, RetOps);
3351}
3352
3353bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
3354  if (N->getNumValues() != 1)
3355    return false;
3356  if (!N->hasNUsesOfValue(1, 0))
3357    return false;
3358
3359  SDValue TCChain = Chain;
3360  SDNode *Copy = *N->use_begin();
3361  if (Copy->getOpcode() == ISD::CopyToReg) {
3362    // If the copy has a glue operand, we conservatively assume it isn't safe to
3363    // perform a tail call.
3364    if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
3365      return false;
3366    TCChain = Copy->getOperand(0);
3367  } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
3368    SDNode *VMov = Copy;
3369    // f64 returned in a pair of GPRs.
3370    SmallPtrSet<SDNode*, 2> Copies;
3371    for (SDNode *U : VMov->uses()) {
3372      if (U->getOpcode() != ISD::CopyToReg)
3373        return false;
3374      Copies.insert(U);
3375    }
3376    if (Copies.size() > 2)
3377      return false;
3378
3379    for (SDNode *U : VMov->uses()) {
3380      SDValue UseChain = U->getOperand(0);
3381      if (Copies.count(UseChain.getNode()))
3382        // Second CopyToReg
3383        Copy = U;
3384      else {
3385        // We are at the top of this chain.
3386        // If the copy has a glue operand, we conservatively assume it
3387        // isn't safe to perform a tail call.
3388        if (U->getOperand(U->getNumOperands() - 1).getValueType() == MVT::Glue)
3389          return false;
3390        // First CopyToReg
3391        TCChain = UseChain;
3392      }
3393    }
3394  } else if (Copy->getOpcode() == ISD::BITCAST) {
3395    // f32 returned in a single GPR.
3396    if (!Copy->hasOneUse())
3397      return false;
3398    Copy = *Copy->use_begin();
3399    if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
3400      return false;
3401    // If the copy has a glue operand, we conservatively assume it isn't safe to
3402    // perform a tail call.
3403    if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
3404      return false;
3405    TCChain = Copy->getOperand(0);
3406  } else {
3407    return false;
3408  }
3409
3410  bool HasRet = false;
3411  for (const SDNode *U : Copy->uses()) {
3412    if (U->getOpcode() != ARMISD::RET_GLUE &&
3413        U->getOpcode() != ARMISD::INTRET_GLUE)
3414      return false;
3415    HasRet = true;
3416  }
3417
3418  if (!HasRet)
3419    return false;
3420
3421  Chain = TCChain;
3422  return true;
3423}
3424
3425bool ARMTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
3426  if (!Subtarget->supportsTailCall())
3427    return false;
3428
3429  if (!CI->isTailCall())
3430    return false;
3431
3432  return true;
3433}
3434
3435// Trying to write a 64 bit value so need to split into two 32 bit values first,
3436// and pass the lower and high parts through.
3437static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) {
3438  SDLoc DL(Op);
3439  SDValue WriteValue = Op->getOperand(2);
3440
3441  // This function is only supposed to be called for i64 type argument.
3442  assert(WriteValue.getValueType() == MVT::i64
3443          && "LowerWRITE_REGISTER called for non-i64 type argument.");
3444
3445  SDValue Lo, Hi;
3446  std::tie(Lo, Hi) = DAG.SplitScalar(WriteValue, DL, MVT::i32, MVT::i32);
3447  SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi };
3448  return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops);
3449}
3450
3451// ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
3452// their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
3453// one of the above mentioned nodes. It has to be wrapped because otherwise
3454// Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
3455// be used to form addressing mode. These wrapped nodes will be selected
3456// into MOVi.
3457SDValue ARMTargetLowering::LowerConstantPool(SDValue Op,
3458                                             SelectionDAG &DAG) const {
3459  EVT PtrVT = Op.getValueType();
3460  // FIXME there is no actual debug info here
3461  SDLoc dl(Op);
3462  ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
3463  SDValue Res;
3464
3465  // When generating execute-only code Constant Pools must be promoted to the
3466  // global data section. It's a bit ugly that we can't share them across basic
3467  // blocks, but this way we guarantee that execute-only behaves correct with
3468  // position-independent addressing modes.
3469  if (Subtarget->genExecuteOnly()) {
3470    auto AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3471    auto T = const_cast<Type*>(CP->getType());
3472    auto C = const_cast<Constant*>(CP->getConstVal());
3473    auto M = const_cast<Module*>(DAG.getMachineFunction().
3474                                 getFunction().getParent());
3475    auto GV = new GlobalVariable(
3476                    *M, T, /*isConstant=*/true, GlobalVariable::InternalLinkage, C,
3477                    Twine(DAG.getDataLayout().getPrivateGlobalPrefix()) + "CP" +
3478                    Twine(DAG.getMachineFunction().getFunctionNumber()) + "_" +
3479                    Twine(AFI->createPICLabelUId())
3480                  );
3481    SDValue GA = DAG.getTargetGlobalAddress(dyn_cast<GlobalValue>(GV),
3482                                            dl, PtrVT);
3483    return LowerGlobalAddress(GA, DAG);
3484  }
3485
3486  // The 16-bit ADR instruction can only encode offsets that are multiples of 4,
3487  // so we need to align to at least 4 bytes when we don't have 32-bit ADR.
3488  Align CPAlign = CP->getAlign();
3489  if (Subtarget->isThumb1Only())
3490    CPAlign = std::max(CPAlign, Align(4));
3491  if (CP->isMachineConstantPoolEntry())
3492    Res =
3493        DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT, CPAlign);
3494  else
3495    Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CPAlign);
3496  return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
3497}
3498
3499unsigned ARMTargetLowering::getJumpTableEncoding() const {
3500  // If we don't have a 32-bit pc-relative branch instruction then the jump
3501  // table consists of block addresses. Usually this is inline, but for
3502  // execute-only it must be placed out-of-line.
3503  if (Subtarget->genExecuteOnly() && !Subtarget->hasV8MBaselineOps())
3504    return MachineJumpTableInfo::EK_BlockAddress;
3505  return MachineJumpTableInfo::EK_Inline;
3506}
3507
3508SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
3509                                             SelectionDAG &DAG) const {
3510  MachineFunction &MF = DAG.getMachineFunction();
3511  ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3512  unsigned ARMPCLabelIndex = 0;
3513  SDLoc DL(Op);
3514  EVT PtrVT = getPointerTy(DAG.getDataLayout());
3515  const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
3516  SDValue CPAddr;
3517  bool IsPositionIndependent = isPositionIndependent() || Subtarget->isROPI();
3518  if (!IsPositionIndependent) {
3519    CPAddr = DAG.getTargetConstantPool(BA, PtrVT, Align(4));
3520  } else {
3521    unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
3522    ARMPCLabelIndex = AFI->createPICLabelUId();
3523    ARMConstantPoolValue *CPV =
3524      ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
3525                                      ARMCP::CPBlockAddress, PCAdj);
3526    CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, Align(4));
3527  }
3528  CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
3529  SDValue Result = DAG.getLoad(
3530      PtrVT, DL, DAG.getEntryNode(), CPAddr,
3531      MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3532  if (!IsPositionIndependent)
3533    return Result;
3534  SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32);
3535  return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
3536}
3537
3538/// Convert a TLS address reference into the correct sequence of loads
3539/// and calls to compute the variable's address for Darwin, and return an
3540/// SDValue containing the final node.
3541
3542/// Darwin only has one TLS scheme which must be capable of dealing with the
3543/// fully general situation, in the worst case. This means:
3544///     + "extern __thread" declaration.
3545///     + Defined in a possibly unknown dynamic library.
3546///
3547/// The general system is that each __thread variable has a [3 x i32] descriptor
3548/// which contains information used by the runtime to calculate the address. The
3549/// only part of this the compiler needs to know about is the first word, which
3550/// contains a function pointer that must be called with the address of the
3551/// entire descriptor in "r0".
3552///
3553/// Since this descriptor may be in a different unit, in general access must
3554/// proceed along the usual ARM rules. A common sequence to produce is:
3555///
3556///     movw rT1, :lower16:_var$non_lazy_ptr
3557///     movt rT1, :upper16:_var$non_lazy_ptr
3558///     ldr r0, [rT1]
3559///     ldr rT2, [r0]
3560///     blx rT2
3561///     [...address now in r0...]
3562SDValue
3563ARMTargetLowering::LowerGlobalTLSAddressDarwin(SDValue Op,
3564                                               SelectionDAG &DAG) const {
3565  assert(Subtarget->isTargetDarwin() &&
3566         "This function expects a Darwin target");
3567  SDLoc DL(Op);
3568
3569  // First step is to get the address of the actua global symbol. This is where
3570  // the TLS descriptor lives.
3571  SDValue DescAddr = LowerGlobalAddressDarwin(Op, DAG);
3572
3573  // The first entry in the descriptor is a function pointer that we must call
3574  // to obtain the address of the variable.
3575  SDValue Chain = DAG.getEntryNode();
3576  SDValue FuncTLVGet = DAG.getLoad(
3577      MVT::i32, DL, Chain, DescAddr,
3578      MachinePointerInfo::getGOT(DAG.getMachineFunction()), Align(4),
3579      MachineMemOperand::MONonTemporal | MachineMemOperand::MODereferenceable |
3580          MachineMemOperand::MOInvariant);
3581  Chain = FuncTLVGet.getValue(1);
3582
3583  MachineFunction &F = DAG.getMachineFunction();
3584  MachineFrameInfo &MFI = F.getFrameInfo();
3585  MFI.setAdjustsStack(true);
3586
3587  // TLS calls preserve all registers except those that absolutely must be
3588  // trashed: R0 (it takes an argument), LR (it's a call) and CPSR (let's not be
3589  // silly).
3590  auto TRI =
3591      getTargetMachine().getSubtargetImpl(F.getFunction())->getRegisterInfo();
3592  auto ARI = static_cast<const ARMRegisterInfo *>(TRI);
3593  const uint32_t *Mask = ARI->getTLSCallPreservedMask(DAG.getMachineFunction());
3594
3595  // Finally, we can make the call. This is just a degenerate version of a
3596  // normal AArch64 call node: r0 takes the address of the descriptor, and
3597  // returns the address of the variable in this thread.
3598  Chain = DAG.getCopyToReg(Chain, DL, ARM::R0, DescAddr, SDValue());
3599  Chain =
3600      DAG.getNode(ARMISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
3601                  Chain, FuncTLVGet, DAG.getRegister(ARM::R0, MVT::i32),
3602                  DAG.getRegisterMask(Mask), Chain.getValue(1));
3603  return DAG.getCopyFromReg(Chain, DL, ARM::R0, MVT::i32, Chain.getValue(1));
3604}
3605
3606SDValue
3607ARMTargetLowering::LowerGlobalTLSAddressWindows(SDValue Op,
3608                                                SelectionDAG &DAG) const {
3609  assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering");
3610
3611  SDValue Chain = DAG.getEntryNode();
3612  EVT PtrVT = getPointerTy(DAG.getDataLayout());
3613  SDLoc DL(Op);
3614
3615  // Load the current TEB (thread environment block)
3616  SDValue Ops[] = {Chain,
3617                   DAG.getTargetConstant(Intrinsic::arm_mrc, DL, MVT::i32),
3618                   DAG.getTargetConstant(15, DL, MVT::i32),
3619                   DAG.getTargetConstant(0, DL, MVT::i32),
3620                   DAG.getTargetConstant(13, DL, MVT::i32),
3621                   DAG.getTargetConstant(0, DL, MVT::i32),
3622                   DAG.getTargetConstant(2, DL, MVT::i32)};
3623  SDValue CurrentTEB = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
3624                                   DAG.getVTList(MVT::i32, MVT::Other), Ops);
3625
3626  SDValue TEB = CurrentTEB.getValue(0);
3627  Chain = CurrentTEB.getValue(1);
3628
3629  // Load the ThreadLocalStoragePointer from the TEB
3630  // A pointer to the TLS array is located at offset 0x2c from the TEB.
3631  SDValue TLSArray =
3632      DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x2c, DL));
3633  TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo());
3634
3635  // The pointer to the thread's TLS data area is at the TLS Index scaled by 4
3636  // offset into the TLSArray.
3637
3638  // Load the TLS index from the C runtime
3639  SDValue TLSIndex =
3640      DAG.getTargetExternalSymbol("_tls_index", PtrVT, ARMII::MO_NO_FLAG);
3641  TLSIndex = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, TLSIndex);
3642  TLSIndex = DAG.getLoad(PtrVT, DL, Chain, TLSIndex, MachinePointerInfo());
3643
3644  SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex,
3645                              DAG.getConstant(2, DL, MVT::i32));
3646  SDValue TLS = DAG.getLoad(PtrVT, DL, Chain,
3647                            DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot),
3648                            MachinePointerInfo());
3649
3650  // Get the offset of the start of the .tls section (section base)
3651  const auto *GA = cast<GlobalAddressSDNode>(Op);
3652  auto *CPV = ARMConstantPoolConstant::Create(GA->getGlobal(), ARMCP::SECREL);
3653  SDValue Offset = DAG.getLoad(
3654      PtrVT, DL, Chain,
3655      DAG.getNode(ARMISD::Wrapper, DL, MVT::i32,
3656                  DAG.getTargetConstantPool(CPV, PtrVT, Align(4))),
3657      MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3658
3659  return DAG.getNode(ISD::ADD, DL, PtrVT, TLS, Offset);
3660}
3661
3662// Lower ISD::GlobalTLSAddress using the "general dynamic" model
3663SDValue
3664ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
3665                                                 SelectionDAG &DAG) const {
3666  SDLoc dl(GA);
3667  EVT PtrVT = getPointerTy(DAG.getDataLayout());
3668  unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
3669  MachineFunction &MF = DAG.getMachineFunction();
3670  ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3671  unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
3672  ARMConstantPoolValue *CPV =
3673    ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
3674                                    ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
3675  SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, Align(4));
3676  Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
3677  Argument = DAG.getLoad(
3678      PtrVT, dl, DAG.getEntryNode(), Argument,
3679      MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3680  SDValue Chain = Argument.getValue(1);
3681
3682  SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
3683  Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
3684
3685  // call __tls_get_addr.
3686  ArgListTy Args;
3687  ArgListEntry Entry;
3688  Entry.Node = Argument;
3689  Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
3690  Args.push_back(Entry);
3691
3692  // FIXME: is there useful debug info available here?
3693  TargetLowering::CallLoweringInfo CLI(DAG);
3694  CLI.setDebugLoc(dl).setChain(Chain).setLibCallee(
3695      CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
3696      DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args));
3697
3698  std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
3699  return CallResult.first;
3700}
3701
3702// Lower ISD::GlobalTLSAddress using the "initial exec" or
3703// "local exec" model.
3704SDValue
3705ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
3706                                        SelectionDAG &DAG,
3707                                        TLSModel::Model model) const {
3708  const GlobalValue *GV = GA->getGlobal();
3709  SDLoc dl(GA);
3710  SDValue Offset;
3711  SDValue Chain = DAG.getEntryNode();
3712  EVT PtrVT = getPointerTy(DAG.getDataLayout());
3713  // Get the Thread Pointer
3714  SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
3715
3716  if (model == TLSModel::InitialExec) {
3717    MachineFunction &MF = DAG.getMachineFunction();
3718    ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3719    unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
3720    // Initial exec model.
3721    unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
3722    ARMConstantPoolValue *CPV =
3723      ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
3724                                      ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
3725                                      true);
3726    Offset = DAG.getTargetConstantPool(CPV, PtrVT, Align(4));
3727    Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
3728    Offset = DAG.getLoad(
3729        PtrVT, dl, Chain, Offset,
3730        MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3731    Chain = Offset.getValue(1);
3732
3733    SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
3734    Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
3735
3736    Offset = DAG.getLoad(
3737        PtrVT, dl, Chain, Offset,
3738        MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3739  } else {
3740    // local exec model
3741    assert(model == TLSModel::LocalExec);
3742    ARMConstantPoolValue *CPV =
3743      ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
3744    Offset = DAG.getTargetConstantPool(CPV, PtrVT, Align(4));
3745    Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
3746    Offset = DAG.getLoad(
3747        PtrVT, dl, Chain, Offset,
3748        MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3749  }
3750
3751  // The address of the thread local variable is the add of the thread
3752  // pointer with the offset of the variable.
3753  return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
3754}
3755
3756SDValue
3757ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
3758  GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3759  if (DAG.getTarget().useEmulatedTLS())
3760    return LowerToTLSEmulatedModel(GA, DAG);
3761
3762  if (Subtarget->isTargetDarwin())
3763    return LowerGlobalTLSAddressDarwin(Op, DAG);
3764
3765  if (Subtarget->isTargetWindows())
3766    return LowerGlobalTLSAddressWindows(Op, DAG);
3767
3768  // TODO: implement the "local dynamic" model
3769  assert(Subtarget->isTargetELF() && "Only ELF implemented here");
3770  TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
3771
3772  switch (model) {
3773    case TLSModel::GeneralDynamic:
3774    case TLSModel::LocalDynamic:
3775      return LowerToTLSGeneralDynamicModel(GA, DAG);
3776    case TLSModel::InitialExec:
3777    case TLSModel::LocalExec:
3778      return LowerToTLSExecModels(GA, DAG, model);
3779  }
3780  llvm_unreachable("bogus TLS model");
3781}
3782
3783/// Return true if all users of V are within function F, looking through
3784/// ConstantExprs.
3785static bool allUsersAreInFunction(const Value *V, const Function *F) {
3786  SmallVector<const User*,4> Worklist(V->users());
3787  while (!Worklist.empty()) {
3788    auto *U = Worklist.pop_back_val();
3789    if (isa<ConstantExpr>(U)) {
3790      append_range(Worklist, U->users());
3791      continue;
3792    }
3793
3794    auto *I = dyn_cast<Instruction>(U);
3795    if (!I || I->getParent()->getParent() != F)
3796      return false;
3797  }
3798  return true;
3799}
3800
3801static SDValue promoteToConstantPool(const ARMTargetLowering *TLI,
3802                                     const GlobalValue *GV, SelectionDAG &DAG,
3803                                     EVT PtrVT, const SDLoc &dl) {
3804  // If we're creating a pool entry for a constant global with unnamed address,
3805  // and the global is small enough, we can emit it inline into the constant pool
3806  // to save ourselves an indirection.
3807  //
3808  // This is a win if the constant is only used in one function (so it doesn't
3809  // need to be duplicated) or duplicating the constant wouldn't increase code
3810  // size (implying the constant is no larger than 4 bytes).
3811  const Function &F = DAG.getMachineFunction().getFunction();
3812
3813  // We rely on this decision to inline being idemopotent and unrelated to the
3814  // use-site. We know that if we inline a variable at one use site, we'll
3815  // inline it elsewhere too (and reuse the constant pool entry). Fast-isel
3816  // doesn't know about this optimization, so bail out if it's enabled else
3817  // we could decide to inline here (and thus never emit the GV) but require
3818  // the GV from fast-isel generated code.
3819  if (!EnableConstpoolPromotion ||
3820      DAG.getMachineFunction().getTarget().Options.EnableFastISel)
3821      return SDValue();
3822
3823  auto *GVar = dyn_cast<GlobalVariable>(GV);
3824  if (!GVar || !GVar->hasInitializer() ||
3825      !GVar->isConstant() || !GVar->hasGlobalUnnamedAddr() ||
3826      !GVar->hasLocalLinkage())
3827    return SDValue();
3828
3829  // If we inline a value that contains relocations, we move the relocations
3830  // from .data to .text. This is not allowed in position-independent code.
3831  auto *Init = GVar->getInitializer();
3832  if ((TLI->isPositionIndependent() || TLI->getSubtarget()->isROPI()) &&
3833      Init->needsDynamicRelocation())
3834    return SDValue();
3835
3836  // The constant islands pass can only really deal with alignment requests
3837  // <= 4 bytes and cannot pad constants itself. Therefore we cannot promote
3838  // any type wanting greater alignment requirements than 4 bytes. We also
3839  // can only promote constants that are multiples of 4 bytes in size or
3840  // are paddable to a multiple of 4. Currently we only try and pad constants
3841  // that are strings for simplicity.
3842  auto *CDAInit = dyn_cast<ConstantDataArray>(Init);
3843  unsigned Size = DAG.getDataLayout().getTypeAllocSize(Init->getType());
3844  Align PrefAlign = DAG.getDataLayout().getPreferredAlign(GVar);
3845  unsigned RequiredPadding = 4 - (Size % 4);
3846  bool PaddingPossible =
3847    RequiredPadding == 4 || (CDAInit && CDAInit->isString());
3848  if (!PaddingPossible || PrefAlign > 4 || Size > ConstpoolPromotionMaxSize ||
3849      Size == 0)
3850    return SDValue();
3851
3852  unsigned PaddedSize = Size + ((RequiredPadding == 4) ? 0 : RequiredPadding);
3853  MachineFunction &MF = DAG.getMachineFunction();
3854  ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3855
3856  // We can't bloat the constant pool too much, else the ConstantIslands pass
3857  // may fail to converge. If we haven't promoted this global yet (it may have
3858  // multiple uses), and promoting it would increase the constant pool size (Sz
3859  // > 4), ensure we have space to do so up to MaxTotal.
3860  if (!AFI->getGlobalsPromotedToConstantPool().count(GVar) && Size > 4)
3861    if (AFI->getPromotedConstpoolIncrease() + PaddedSize - 4 >=
3862        ConstpoolPromotionMaxTotal)
3863      return SDValue();
3864
3865  // This is only valid if all users are in a single function; we can't clone
3866  // the constant in general. The LLVM IR unnamed_addr allows merging
3867  // constants, but not cloning them.
3868  //
3869  // We could potentially allow cloning if we could prove all uses of the
3870  // constant in the current function don't care about the address, like
3871  // printf format strings. But that isn't implemented for now.
3872  if (!allUsersAreInFunction(GVar, &F))
3873    return SDValue();
3874
3875  // We're going to inline this global. Pad it out if needed.
3876  if (RequiredPadding != 4) {
3877    StringRef S = CDAInit->getAsString();
3878
3879    SmallVector<uint8_t,16> V(S.size());
3880    std::copy(S.bytes_begin(), S.bytes_end(), V.begin());
3881    while (RequiredPadding--)
3882      V.push_back(0);
3883    Init = ConstantDataArray::get(*DAG.getContext(), V);
3884  }
3885
3886  auto CPVal = ARMConstantPoolConstant::Create(GVar, Init);
3887  SDValue CPAddr = DAG.getTargetConstantPool(CPVal, PtrVT, Align(4));
3888  if (!AFI->getGlobalsPromotedToConstantPool().count(GVar)) {
3889    AFI->markGlobalAsPromotedToConstantPool(GVar);
3890    AFI->setPromotedConstpoolIncrease(AFI->getPromotedConstpoolIncrease() +
3891                                      PaddedSize - 4);
3892  }
3893  ++NumConstpoolPromoted;
3894  return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3895}
3896
3897bool ARMTargetLowering::isReadOnly(const GlobalValue *GV) const {
3898  if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
3899    if (!(GV = GA->getAliaseeObject()))
3900      return false;
3901  if (const auto *V = dyn_cast<GlobalVariable>(GV))
3902    return V->isConstant();
3903  return isa<Function>(GV);
3904}
3905
3906SDValue ARMTargetLowering::LowerGlobalAddress(SDValue Op,
3907                                              SelectionDAG &DAG) const {
3908  switch (Subtarget->getTargetTriple().getObjectFormat()) {
3909  default: llvm_unreachable("unknown object format");
3910  case Triple::COFF:
3911    return LowerGlobalAddressWindows(Op, DAG);
3912  case Triple::ELF:
3913    return LowerGlobalAddressELF(Op, DAG);
3914  case Triple::MachO:
3915    return LowerGlobalAddressDarwin(Op, DAG);
3916  }
3917}
3918
3919SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
3920                                                 SelectionDAG &DAG) const {
3921  EVT PtrVT = getPointerTy(DAG.getDataLayout());
3922  SDLoc dl(Op);
3923  const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3924  const TargetMachine &TM = getTargetMachine();
3925  bool IsRO = isReadOnly(GV);
3926
3927  // promoteToConstantPool only if not generating XO text section
3928  if (TM.shouldAssumeDSOLocal(*GV->getParent(), GV) && !Subtarget->genExecuteOnly())
3929    if (SDValue V = promoteToConstantPool(this, GV, DAG, PtrVT, dl))
3930      return V;
3931
3932  if (isPositionIndependent()) {
3933    bool UseGOT_PREL = !TM.shouldAssumeDSOLocal(*GV->getParent(), GV);
3934    SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3935                                           UseGOT_PREL ? ARMII::MO_GOT : 0);
3936    SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G);
3937    if (UseGOT_PREL)
3938      Result =
3939          DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
3940                      MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3941    return Result;
3942  } else if (Subtarget->isROPI() && IsRO) {
3943    // PC-relative.
3944    SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT);
3945    SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G);
3946    return Result;
3947  } else if (Subtarget->isRWPI() && !IsRO) {
3948    // SB-relative.
3949    SDValue RelAddr;
3950    if (Subtarget->useMovt()) {
3951      ++NumMovwMovt;
3952      SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_SBREL);
3953      RelAddr = DAG.getNode(ARMISD::Wrapper, dl, PtrVT, G);
3954    } else { // use literal pool for address constant
3955      ARMConstantPoolValue *CPV =
3956        ARMConstantPoolConstant::Create(GV, ARMCP::SBREL);
3957      SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, Align(4));
3958      CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3959      RelAddr = DAG.getLoad(
3960          PtrVT, dl, DAG.getEntryNode(), CPAddr,
3961          MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3962    }
3963    SDValue SB = DAG.getCopyFromReg(DAG.getEntryNode(), dl, ARM::R9, PtrVT);
3964    SDValue Result = DAG.getNode(ISD::ADD, dl, PtrVT, SB, RelAddr);
3965    return Result;
3966  }
3967
3968  // If we have T2 ops, we can materialize the address directly via movt/movw
3969  // pair. This is always cheaper. If need to generate Execute Only code, and we
3970  // only have Thumb1 available, we can't use a constant pool and are forced to
3971  // use immediate relocations.
3972  if (Subtarget->useMovt() || Subtarget->genExecuteOnly()) {
3973    if (Subtarget->useMovt())
3974      ++NumMovwMovt;
3975    // FIXME: Once remat is capable of dealing with instructions with register
3976    // operands, expand this into two nodes.
3977    return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
3978                       DAG.getTargetGlobalAddress(GV, dl, PtrVT));
3979  } else {
3980    SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, Align(4));
3981    CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3982    return DAG.getLoad(
3983        PtrVT, dl, DAG.getEntryNode(), CPAddr,
3984        MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3985  }
3986}
3987
3988SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
3989                                                    SelectionDAG &DAG) const {
3990  assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
3991         "ROPI/RWPI not currently supported for Darwin");
3992  EVT PtrVT = getPointerTy(DAG.getDataLayout());
3993  SDLoc dl(Op);
3994  const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3995
3996  if (Subtarget->useMovt())
3997    ++NumMovwMovt;
3998
3999  // FIXME: Once remat is capable of dealing with instructions with register
4000  // operands, expand this into multiple nodes
4001  unsigned Wrapper =
4002      isPositionIndependent() ? ARMISD::WrapperPIC : ARMISD::Wrapper;
4003
4004  SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
4005  SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
4006
4007  if (Subtarget->isGVIndirectSymbol(GV))
4008    Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
4009                         MachinePointerInfo::getGOT(DAG.getMachineFunction()));
4010  return Result;
4011}
4012
4013SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
4014                                                     SelectionDAG &DAG) const {
4015  assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
4016  assert(Subtarget->useMovt() &&
4017         "Windows on ARM expects to use movw/movt");
4018  assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
4019         "ROPI/RWPI not currently supported for Windows");
4020
4021  const TargetMachine &TM = getTargetMachine();
4022  const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
4023  ARMII::TOF TargetFlags = ARMII::MO_NO_FLAG;
4024  if (GV->hasDLLImportStorageClass())
4025    TargetFlags = ARMII::MO_DLLIMPORT;
4026  else if (!TM.shouldAssumeDSOLocal(*GV->getParent(), GV))
4027    TargetFlags = ARMII::MO_COFFSTUB;
4028  EVT PtrVT = getPointerTy(DAG.getDataLayout());
4029  SDValue Result;
4030  SDLoc DL(Op);
4031
4032  ++NumMovwMovt;
4033
4034  // FIXME: Once remat is capable of dealing with instructions with register
4035  // operands, expand this into two nodes.
4036  Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
4037                       DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*offset=*/0,
4038                                                  TargetFlags));
4039  if (TargetFlags & (ARMII::MO_DLLIMPORT | ARMII::MO_COFFSTUB))
4040    Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
4041                         MachinePointerInfo::getGOT(DAG.getMachineFunction()));
4042  return Result;
4043}
4044
4045SDValue
4046ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
4047  SDLoc dl(Op);
4048  SDValue Val = DAG.getConstant(0, dl, MVT::i32);
4049  return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
4050                     DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
4051                     Op.getOperand(1), Val);
4052}
4053
4054SDValue
4055ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
4056  SDLoc dl(Op);
4057  return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
4058                     Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32));
4059}
4060
4061SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op,
4062                                                      SelectionDAG &DAG) const {
4063  SDLoc dl(Op);
4064  return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other,
4065                     Op.getOperand(0));
4066}
4067
4068SDValue ARMTargetLowering::LowerINTRINSIC_VOID(
4069    SDValue Op, SelectionDAG &DAG, const ARMSubtarget *Subtarget) const {
4070  unsigned IntNo =
4071      cast<ConstantSDNode>(
4072          Op.getOperand(Op.getOperand(0).getValueType() == MVT::Other))
4073          ->getZExtValue();
4074  switch (IntNo) {
4075    default:
4076      return SDValue();  // Don't custom lower most intrinsics.
4077    case Intrinsic::arm_gnu_eabi_mcount: {
4078      MachineFunction &MF = DAG.getMachineFunction();
4079      EVT PtrVT = getPointerTy(DAG.getDataLayout());
4080      SDLoc dl(Op);
4081      SDValue Chain = Op.getOperand(0);
4082      // call "\01__gnu_mcount_nc"
4083      const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
4084      const uint32_t *Mask =
4085          ARI->getCallPreservedMask(DAG.getMachineFunction(), CallingConv::C);
4086      assert(Mask && "Missing call preserved mask for calling convention");
4087      // Mark LR an implicit live-in.
4088      Register Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
4089      SDValue ReturnAddress =
4090          DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, PtrVT);
4091      constexpr EVT ResultTys[] = {MVT::Other, MVT::Glue};
4092      SDValue Callee =
4093          DAG.getTargetExternalSymbol("\01__gnu_mcount_nc", PtrVT, 0);
4094      SDValue RegisterMask = DAG.getRegisterMask(Mask);
4095      if (Subtarget->isThumb())
4096        return SDValue(
4097            DAG.getMachineNode(
4098                ARM::tBL_PUSHLR, dl, ResultTys,
4099                {ReturnAddress, DAG.getTargetConstant(ARMCC::AL, dl, PtrVT),
4100                 DAG.getRegister(0, PtrVT), Callee, RegisterMask, Chain}),
4101            0);
4102      return SDValue(
4103          DAG.getMachineNode(ARM::BL_PUSHLR, dl, ResultTys,
4104                             {ReturnAddress, Callee, RegisterMask, Chain}),
4105          0);
4106    }
4107  }
4108}
4109
4110SDValue
4111ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
4112                                          const ARMSubtarget *Subtarget) const {
4113  unsigned IntNo = Op.getConstantOperandVal(0);
4114  SDLoc dl(Op);
4115  switch (IntNo) {
4116  default: return SDValue();    // Don't custom lower most intrinsics.
4117  case Intrinsic::thread_pointer: {
4118    EVT PtrVT = getPointerTy(DAG.getDataLayout());
4119    return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
4120  }
4121  case Intrinsic::arm_cls: {
4122    const SDValue &Operand = Op.getOperand(1);
4123    const EVT VTy = Op.getValueType();
4124    SDValue SRA =
4125        DAG.getNode(ISD::SRA, dl, VTy, Operand, DAG.getConstant(31, dl, VTy));
4126    SDValue XOR = DAG.getNode(ISD::XOR, dl, VTy, SRA, Operand);
4127    SDValue SHL =
4128        DAG.getNode(ISD::SHL, dl, VTy, XOR, DAG.getConstant(1, dl, VTy));
4129    SDValue OR =
4130        DAG.getNode(ISD::OR, dl, VTy, SHL, DAG.getConstant(1, dl, VTy));
4131    SDValue Result = DAG.getNode(ISD::CTLZ, dl, VTy, OR);
4132    return Result;
4133  }
4134  case Intrinsic::arm_cls64: {
4135    // cls(x) = if cls(hi(x)) != 31 then cls(hi(x))
4136    //          else 31 + clz(if hi(x) == 0 then lo(x) else not(lo(x)))
4137    const SDValue &Operand = Op.getOperand(1);
4138    const EVT VTy = Op.getValueType();
4139    SDValue Lo, Hi;
4140    std::tie(Lo, Hi) = DAG.SplitScalar(Operand, dl, VTy, VTy);
4141    SDValue Constant0 = DAG.getConstant(0, dl, VTy);
4142    SDValue Constant1 = DAG.getConstant(1, dl, VTy);
4143    SDValue Constant31 = DAG.getConstant(31, dl, VTy);
4144    SDValue SRAHi = DAG.getNode(ISD::SRA, dl, VTy, Hi, Constant31);
4145    SDValue XORHi = DAG.getNode(ISD::XOR, dl, VTy, SRAHi, Hi);
4146    SDValue SHLHi = DAG.getNode(ISD::SHL, dl, VTy, XORHi, Constant1);
4147    SDValue ORHi = DAG.getNode(ISD::OR, dl, VTy, SHLHi, Constant1);
4148    SDValue CLSHi = DAG.getNode(ISD::CTLZ, dl, VTy, ORHi);
4149    SDValue CheckLo =
4150        DAG.getSetCC(dl, MVT::i1, CLSHi, Constant31, ISD::CondCode::SETEQ);
4151    SDValue HiIsZero =
4152        DAG.getSetCC(dl, MVT::i1, Hi, Constant0, ISD::CondCode::SETEQ);
4153    SDValue AdjustedLo =
4154        DAG.getSelect(dl, VTy, HiIsZero, Lo, DAG.getNOT(dl, Lo, VTy));
4155    SDValue CLZAdjustedLo = DAG.getNode(ISD::CTLZ, dl, VTy, AdjustedLo);
4156    SDValue Result =
4157        DAG.getSelect(dl, VTy, CheckLo,
4158                      DAG.getNode(ISD::ADD, dl, VTy, CLZAdjustedLo, Constant31), CLSHi);
4159    return Result;
4160  }
4161  case Intrinsic::eh_sjlj_lsda: {
4162    MachineFunction &MF = DAG.getMachineFunction();
4163    ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
4164    unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
4165    EVT PtrVT = getPointerTy(DAG.getDataLayout());
4166    SDValue CPAddr;
4167    bool IsPositionIndependent = isPositionIndependent();
4168    unsigned PCAdj = IsPositionIndependent ? (Subtarget->isThumb() ? 4 : 8) : 0;
4169    ARMConstantPoolValue *CPV =
4170      ARMConstantPoolConstant::Create(&MF.getFunction(), ARMPCLabelIndex,
4171                                      ARMCP::CPLSDA, PCAdj);
4172    CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, Align(4));
4173    CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
4174    SDValue Result = DAG.getLoad(
4175        PtrVT, dl, DAG.getEntryNode(), CPAddr,
4176        MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
4177
4178    if (IsPositionIndependent) {
4179      SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
4180      Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
4181    }
4182    return Result;
4183  }
4184  case Intrinsic::arm_neon_vabs:
4185    return DAG.getNode(ISD::ABS, SDLoc(Op), Op.getValueType(),
4186                        Op.getOperand(1));
4187  case Intrinsic::arm_neon_vmulls:
4188  case Intrinsic::arm_neon_vmullu: {
4189    unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
4190      ? ARMISD::VMULLs : ARMISD::VMULLu;
4191    return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
4192                       Op.getOperand(1), Op.getOperand(2));
4193  }
4194  case Intrinsic::arm_neon_vminnm:
4195  case Intrinsic::arm_neon_vmaxnm: {
4196    unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminnm)
4197      ? ISD::FMINNUM : ISD::FMAXNUM;
4198    return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
4199                       Op.getOperand(1), Op.getOperand(2));
4200  }
4201  case Intrinsic::arm_neon_vminu:
4202  case Intrinsic::arm_neon_vmaxu: {
4203    if (Op.getValueType().isFloatingPoint())
4204      return SDValue();
4205    unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminu)
4206      ? ISD::UMIN : ISD::UMAX;
4207    return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
4208                         Op.getOperand(1), Op.getOperand(2));
4209  }
4210  case Intrinsic::arm_neon_vmins:
4211  case Intrinsic::arm_neon_vmaxs: {
4212    // v{min,max}s is overloaded between signed integers and floats.
4213    if (!Op.getValueType().isFloatingPoint()) {
4214      unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
4215        ? ISD::SMIN : ISD::SMAX;
4216      return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
4217                         Op.getOperand(1), Op.getOperand(2));
4218    }
4219    unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
4220      ? ISD::FMINIMUM : ISD::FMAXIMUM;
4221    return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
4222                       Op.getOperand(1), Op.getOperand(2));
4223  }
4224  case Intrinsic::arm_neon_vtbl1:
4225    return DAG.getNode(ARMISD::VTBL1, SDLoc(Op), Op.getValueType(),
4226                       Op.getOperand(1), Op.getOperand(2));
4227  case Intrinsic::arm_neon_vtbl2:
4228    return DAG.getNode(ARMISD::VTBL2, SDLoc(Op), Op.getValueType(),
4229                       Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
4230  case Intrinsic::arm_mve_pred_i2v:
4231  case Intrinsic::arm_mve_pred_v2i:
4232    return DAG.getNode(ARMISD::PREDICATE_CAST, SDLoc(Op), Op.getValueType(),
4233                       Op.getOperand(1));
4234  case Intrinsic::arm_mve_vreinterpretq:
4235    return DAG.getNode(ARMISD::VECTOR_REG_CAST, SDLoc(Op), Op.getValueType(),
4236                       Op.getOperand(1));
4237  case Intrinsic::arm_mve_lsll:
4238    return DAG.getNode(ARMISD::LSLL, SDLoc(Op), Op->getVTList(),
4239                       Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
4240  case Intrinsic::arm_mve_asrl:
4241    return DAG.getNode(ARMISD::ASRL, SDLoc(Op), Op->getVTList(),
4242                       Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
4243  }
4244}
4245
4246static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
4247                                 const ARMSubtarget *Subtarget) {
4248  SDLoc dl(Op);
4249  auto SSID = static_cast<SyncScope::ID>(Op.getConstantOperandVal(2));
4250  if (SSID == SyncScope::SingleThread)
4251    return Op;
4252
4253  if (!Subtarget->hasDataBarrier()) {
4254    // Some ARMv6 cpus can support data barriers with an mcr instruction.
4255    // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
4256    // here.
4257    assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
4258           "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
4259    return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
4260                       DAG.getConstant(0, dl, MVT::i32));
4261  }
4262
4263  AtomicOrdering Ord =
4264      static_cast<AtomicOrdering>(Op.getConstantOperandVal(1));
4265  ARM_MB::MemBOpt Domain = ARM_MB::ISH;
4266  if (Subtarget->isMClass()) {
4267    // Only a full system barrier exists in the M-class architectures.
4268    Domain = ARM_MB::SY;
4269  } else if (Subtarget->preferISHSTBarriers() &&
4270             Ord == AtomicOrdering::Release) {
4271    // Swift happens to implement ISHST barriers in a way that's compatible with
4272    // Release semantics but weaker than ISH so we'd be fools not to use
4273    // it. Beware: other processors probably don't!
4274    Domain = ARM_MB::ISHST;
4275  }
4276
4277  return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
4278                     DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32),
4279                     DAG.getConstant(Domain, dl, MVT::i32));
4280}
4281
4282static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
4283                             const ARMSubtarget *Subtarget) {
4284  // ARM pre v5TE and Thumb1 does not have preload instructions.
4285  if (!(Subtarget->isThumb2() ||
4286        (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
4287    // Just preserve the chain.
4288    return Op.getOperand(0);
4289
4290  SDLoc dl(Op);
4291  unsigned isRead = ~Op.getConstantOperandVal(2) & 1;
4292  if (!isRead &&
4293      (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
4294    // ARMv7 with MP extension has PLDW.
4295    return Op.getOperand(0);
4296
4297  unsigned isData = Op.getConstantOperandVal(4);
4298  if (Subtarget->isThumb()) {
4299    // Invert the bits.
4300    isRead = ~isRead & 1;
4301    isData = ~isData & 1;
4302  }
4303
4304  return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
4305                     Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32),
4306                     DAG.getConstant(isData, dl, MVT::i32));
4307}
4308
4309static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
4310  MachineFunction &MF = DAG.getMachineFunction();
4311  ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
4312
4313  // vastart just stores the address of the VarArgsFrameIndex slot into the
4314  // memory location argument.
4315  SDLoc dl(Op);
4316  EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
4317  SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4318  const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4319  return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
4320                      MachinePointerInfo(SV));
4321}
4322
4323SDValue ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA,
4324                                                CCValAssign &NextVA,
4325                                                SDValue &Root,
4326                                                SelectionDAG &DAG,
4327                                                const SDLoc &dl) const {
4328  MachineFunction &MF = DAG.getMachineFunction();
4329  ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
4330
4331  const TargetRegisterClass *RC;
4332  if (AFI->isThumb1OnlyFunction())
4333    RC = &ARM::tGPRRegClass;
4334  else
4335    RC = &ARM::GPRRegClass;
4336
4337  // Transform the arguments stored in physical registers into virtual ones.
4338  Register Reg = MF.addLiveIn(VA.getLocReg(), RC);
4339  SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
4340
4341  SDValue ArgValue2;
4342  if (NextVA.isMemLoc()) {
4343    MachineFrameInfo &MFI = MF.getFrameInfo();
4344    int FI = MFI.CreateFixedObject(4, NextVA.getLocMemOffset(), true);
4345
4346    // Create load node to retrieve arguments from the stack.
4347    SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
4348    ArgValue2 = DAG.getLoad(
4349        MVT::i32, dl, Root, FIN,
4350        MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI));
4351  } else {
4352    Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
4353    ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
4354  }
4355  if (!Subtarget->isLittle())
4356    std::swap (ArgValue, ArgValue2);
4357  return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
4358}
4359
4360// The remaining GPRs hold either the beginning of variable-argument
4361// data, or the beginning of an aggregate passed by value (usually
4362// byval).  Either way, we allocate stack slots adjacent to the data
4363// provided by our caller, and store the unallocated registers there.
4364// If this is a variadic function, the va_list pointer will begin with
4365// these values; otherwise, this reassembles a (byval) structure that
4366// was split between registers and memory.
4367// Return: The frame index registers were stored into.
4368int ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
4369                                      const SDLoc &dl, SDValue &Chain,
4370                                      const Value *OrigArg,
4371                                      unsigned InRegsParamRecordIdx,
4372                                      int ArgOffset, unsigned ArgSize) const {
4373  // Currently, two use-cases possible:
4374  // Case #1. Non-var-args function, and we meet first byval parameter.
4375  //          Setup first unallocated register as first byval register;
4376  //          eat all remained registers
4377  //          (these two actions are performed by HandleByVal method).
4378  //          Then, here, we initialize stack frame with
4379  //          "store-reg" instructions.
4380  // Case #2. Var-args function, that doesn't contain byval parameters.
4381  //          The same: eat all remained unallocated registers,
4382  //          initialize stack frame.
4383
4384  MachineFunction &MF = DAG.getMachineFunction();
4385  MachineFrameInfo &MFI = MF.getFrameInfo();
4386  ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
4387  unsigned RBegin, REnd;
4388  if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
4389    CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
4390  } else {
4391    unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
4392    RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx];
4393    REnd = ARM::R4;
4394  }
4395
4396  if (REnd != RBegin)
4397    ArgOffset = -4 * (ARM::R4 - RBegin);
4398
4399  auto PtrVT = getPointerTy(DAG.getDataLayout());
4400  int FrameIndex = MFI.CreateFixedObject(ArgSize, ArgOffset, false);
4401  SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT);
4402
4403  SmallVector<SDValue, 4> MemOps;
4404  const TargetRegisterClass *RC =
4405      AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
4406
4407  for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) {
4408    Register VReg = MF.addLiveIn(Reg, RC);
4409    SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
4410    SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
4411                                 MachinePointerInfo(OrigArg, 4 * i));
4412    MemOps.push_back(Store);
4413    FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT));
4414  }
4415
4416  if (!MemOps.empty())
4417    Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4418  return FrameIndex;
4419}
4420
4421// Setup stack frame, the va_list pointer will start from.
4422void ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
4423                                             const SDLoc &dl, SDValue &Chain,
4424                                             unsigned ArgOffset,
4425                                             unsigned TotalArgRegsSaveSize,
4426                                             bool ForceMutable) const {
4427  MachineFunction &MF = DAG.getMachineFunction();
4428  ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
4429
4430  // Try to store any remaining integer argument regs
4431  // to their spots on the stack so that they may be loaded by dereferencing
4432  // the result of va_next.
4433  // If there is no regs to be stored, just point address after last
4434  // argument passed via stack.
4435  int FrameIndex = StoreByValRegs(
4436      CCInfo, DAG, dl, Chain, nullptr, CCInfo.getInRegsParamsCount(),
4437      CCInfo.getStackSize(), std::max(4U, TotalArgRegsSaveSize));
4438  AFI->setVarArgsFrameIndex(FrameIndex);
4439}
4440
4441bool ARMTargetLowering::splitValueIntoRegisterParts(
4442    SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts,
4443    unsigned NumParts, MVT PartVT, std::optional<CallingConv::ID> CC) const {
4444  EVT ValueVT = Val.getValueType();
4445  if ((ValueVT == MVT::f16 || ValueVT == MVT::bf16) && PartVT == MVT::f32) {
4446    unsigned ValueBits = ValueVT.getSizeInBits();
4447    unsigned PartBits = PartVT.getSizeInBits();
4448    Val = DAG.getNode(ISD::BITCAST, DL, MVT::getIntegerVT(ValueBits), Val);
4449    Val = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::getIntegerVT(PartBits), Val);
4450    Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
4451    Parts[0] = Val;
4452    return true;
4453  }
4454  return false;
4455}
4456
4457SDValue ARMTargetLowering::joinRegisterPartsIntoValue(
4458    SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts,
4459    MVT PartVT, EVT ValueVT, std::optional<CallingConv::ID> CC) const {
4460  if ((ValueVT == MVT::f16 || ValueVT == MVT::bf16) && PartVT == MVT::f32) {
4461    unsigned ValueBits = ValueVT.getSizeInBits();
4462    unsigned PartBits = PartVT.getSizeInBits();
4463    SDValue Val = Parts[0];
4464
4465    Val = DAG.getNode(ISD::BITCAST, DL, MVT::getIntegerVT(PartBits), Val);
4466    Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::getIntegerVT(ValueBits), Val);
4467    Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
4468    return Val;
4469  }
4470  return SDValue();
4471}
4472
4473SDValue ARMTargetLowering::LowerFormalArguments(
4474    SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
4475    const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4476    SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
4477  MachineFunction &MF = DAG.getMachineFunction();
4478  MachineFrameInfo &MFI = MF.getFrameInfo();
4479
4480  ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
4481
4482  // Assign locations to all of the incoming arguments.
4483  SmallVector<CCValAssign, 16> ArgLocs;
4484  CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
4485                 *DAG.getContext());
4486  CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForCall(CallConv, isVarArg));
4487
4488  SmallVector<SDValue, 16> ArgValues;
4489  SDValue ArgValue;
4490  Function::const_arg_iterator CurOrigArg = MF.getFunction().arg_begin();
4491  unsigned CurArgIdx = 0;
4492
4493  // Initially ArgRegsSaveSize is zero.
4494  // Then we increase this value each time we meet byval parameter.
4495  // We also increase this value in case of varargs function.
4496  AFI->setArgRegsSaveSize(0);
4497
4498  // Calculate the amount of stack space that we need to allocate to store
4499  // byval and variadic arguments that are passed in registers.
4500  // We need to know this before we allocate the first byval or variadic
4501  // argument, as they will be allocated a stack slot below the CFA (Canonical
4502  // Frame Address, the stack pointer at entry to the function).
4503  unsigned ArgRegBegin = ARM::R4;
4504  for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
4505    if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount())
4506      break;
4507
4508    CCValAssign &VA = ArgLocs[i];
4509    unsigned Index = VA.getValNo();
4510    ISD::ArgFlagsTy Flags = Ins[Index].Flags;
4511    if (!Flags.isByVal())
4512      continue;
4513
4514    assert(VA.isMemLoc() && "unexpected byval pointer in reg");
4515    unsigned RBegin, REnd;
4516    CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd);
4517    ArgRegBegin = std::min(ArgRegBegin, RBegin);
4518
4519    CCInfo.nextInRegsParam();
4520  }
4521  CCInfo.rewindByValRegsInfo();
4522
4523  int lastInsIndex = -1;
4524  if (isVarArg && MFI.hasVAStart()) {
4525    unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
4526    if (RegIdx != std::size(GPRArgRegs))
4527      ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]);
4528  }
4529
4530  unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin);
4531  AFI->setArgRegsSaveSize(TotalArgRegsSaveSize);
4532  auto PtrVT = getPointerTy(DAG.getDataLayout());
4533
4534  for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
4535    CCValAssign &VA = ArgLocs[i];
4536    if (Ins[VA.getValNo()].isOrigArg()) {
4537      std::advance(CurOrigArg,
4538                   Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx);
4539      CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex();
4540    }
4541    // Arguments stored in registers.
4542    if (VA.isRegLoc()) {
4543      EVT RegVT = VA.getLocVT();
4544
4545      if (VA.needsCustom() && VA.getLocVT() == MVT::v2f64) {
4546        // f64 and vector types are split up into multiple registers or
4547        // combinations of registers and stack slots.
4548        SDValue ArgValue1 =
4549            GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
4550        VA = ArgLocs[++i]; // skip ahead to next loc
4551        SDValue ArgValue2;
4552        if (VA.isMemLoc()) {
4553          int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), true);
4554          SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4555          ArgValue2 = DAG.getLoad(
4556              MVT::f64, dl, Chain, FIN,
4557              MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI));
4558        } else {
4559          ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
4560        }
4561        ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
4562        ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, ArgValue,
4563                               ArgValue1, DAG.getIntPtrConstant(0, dl));
4564        ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, ArgValue,
4565                               ArgValue2, DAG.getIntPtrConstant(1, dl));
4566      } else if (VA.needsCustom() && VA.getLocVT() == MVT::f64) {
4567        ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
4568      } else {
4569        const TargetRegisterClass *RC;
4570
4571        if (RegVT == MVT::f16 || RegVT == MVT::bf16)
4572          RC = &ARM::HPRRegClass;
4573        else if (RegVT == MVT::f32)
4574          RC = &ARM::SPRRegClass;
4575        else if (RegVT == MVT::f64 || RegVT == MVT::v4f16 ||
4576                 RegVT == MVT::v4bf16)
4577          RC = &ARM::DPRRegClass;
4578        else if (RegVT == MVT::v2f64 || RegVT == MVT::v8f16 ||
4579                 RegVT == MVT::v8bf16)
4580          RC = &ARM::QPRRegClass;
4581        else if (RegVT == MVT::i32)
4582          RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass
4583                                           : &ARM::GPRRegClass;
4584        else
4585          llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
4586
4587        // Transform the arguments in physical registers into virtual ones.
4588        Register Reg = MF.addLiveIn(VA.getLocReg(), RC);
4589        ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
4590
4591        // If this value is passed in r0 and has the returned attribute (e.g.
4592        // C++ 'structors), record this fact for later use.
4593        if (VA.getLocReg() == ARM::R0 && Ins[VA.getValNo()].Flags.isReturned()) {
4594          AFI->setPreservesR0();
4595        }
4596      }
4597
4598      // If this is an 8 or 16-bit value, it is really passed promoted
4599      // to 32 bits.  Insert an assert[sz]ext to capture this, then
4600      // truncate to the right size.
4601      switch (VA.getLocInfo()) {
4602      default: llvm_unreachable("Unknown loc info!");
4603      case CCValAssign::Full: break;
4604      case CCValAssign::BCvt:
4605        ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
4606        break;
4607      case CCValAssign::SExt:
4608        ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
4609                               DAG.getValueType(VA.getValVT()));
4610        ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
4611        break;
4612      case CCValAssign::ZExt:
4613        ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
4614                               DAG.getValueType(VA.getValVT()));
4615        ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
4616        break;
4617      }
4618
4619      // f16 arguments have their size extended to 4 bytes and passed as if they
4620      // had been copied to the LSBs of a 32-bit register.
4621      // For that, it's passed extended to i32 (soft ABI) or to f32 (hard ABI)
4622      if (VA.needsCustom() &&
4623          (VA.getValVT() == MVT::f16 || VA.getValVT() == MVT::bf16))
4624        ArgValue = MoveToHPR(dl, DAG, VA.getLocVT(), VA.getValVT(), ArgValue);
4625
4626      InVals.push_back(ArgValue);
4627    } else { // VA.isRegLoc()
4628      // Only arguments passed on the stack should make it here.
4629      assert(VA.isMemLoc());
4630      assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
4631
4632      int index = VA.getValNo();
4633
4634      // Some Ins[] entries become multiple ArgLoc[] entries.
4635      // Process them only once.
4636      if (index != lastInsIndex)
4637        {
4638          ISD::ArgFlagsTy Flags = Ins[index].Flags;
4639          // FIXME: For now, all byval parameter objects are marked mutable.
4640          // This can be changed with more analysis.
4641          // In case of tail call optimization mark all arguments mutable.
4642          // Since they could be overwritten by lowering of arguments in case of
4643          // a tail call.
4644          if (Flags.isByVal()) {
4645            assert(Ins[index].isOrigArg() &&
4646                   "Byval arguments cannot be implicit");
4647            unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed();
4648
4649            int FrameIndex = StoreByValRegs(
4650                CCInfo, DAG, dl, Chain, &*CurOrigArg, CurByValIndex,
4651                VA.getLocMemOffset(), Flags.getByValSize());
4652            InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT));
4653            CCInfo.nextInRegsParam();
4654          } else {
4655            unsigned FIOffset = VA.getLocMemOffset();
4656            int FI = MFI.CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
4657                                           FIOffset, true);
4658
4659            // Create load nodes to retrieve arguments from the stack.
4660            SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4661            InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
4662                                         MachinePointerInfo::getFixedStack(
4663                                             DAG.getMachineFunction(), FI)));
4664          }
4665          lastInsIndex = index;
4666        }
4667    }
4668  }
4669
4670  // varargs
4671  if (isVarArg && MFI.hasVAStart()) {
4672    VarArgStyleRegisters(CCInfo, DAG, dl, Chain, CCInfo.getStackSize(),
4673                         TotalArgRegsSaveSize);
4674    if (AFI->isCmseNSEntryFunction()) {
4675      DiagnosticInfoUnsupported Diag(
4676          DAG.getMachineFunction().getFunction(),
4677          "secure entry function must not be variadic", dl.getDebugLoc());
4678      DAG.getContext()->diagnose(Diag);
4679    }
4680  }
4681
4682  unsigned StackArgSize = CCInfo.getStackSize();
4683  bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
4684  if (canGuaranteeTCO(CallConv, TailCallOpt)) {
4685    // The only way to guarantee a tail call is if the callee restores its
4686    // argument area, but it must also keep the stack aligned when doing so.
4687    const DataLayout &DL = DAG.getDataLayout();
4688    StackArgSize = alignTo(StackArgSize, DL.getStackAlignment());
4689
4690    AFI->setArgumentStackToRestore(StackArgSize);
4691  }
4692  AFI->setArgumentStackSize(StackArgSize);
4693
4694  if (CCInfo.getStackSize() > 0 && AFI->isCmseNSEntryFunction()) {
4695    DiagnosticInfoUnsupported Diag(
4696        DAG.getMachineFunction().getFunction(),
4697        "secure entry function requires arguments on stack", dl.getDebugLoc());
4698    DAG.getContext()->diagnose(Diag);
4699  }
4700
4701  return Chain;
4702}
4703
4704/// isFloatingPointZero - Return true if this is +0.0.
4705static bool isFloatingPointZero(SDValue Op) {
4706  if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
4707    return CFP->getValueAPF().isPosZero();
4708  else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
4709    // Maybe this has already been legalized into the constant pool?
4710    if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
4711      SDValue WrapperOp = Op.getOperand(1).getOperand(0);
4712      if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
4713        if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
4714          return CFP->getValueAPF().isPosZero();
4715    }
4716  } else if (Op->getOpcode() == ISD::BITCAST &&
4717             Op->getValueType(0) == MVT::f64) {
4718    // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64)
4719    // created by LowerConstantFP().
4720    SDValue BitcastOp = Op->getOperand(0);
4721    if (BitcastOp->getOpcode() == ARMISD::VMOVIMM &&
4722        isNullConstant(BitcastOp->getOperand(0)))
4723      return true;
4724  }
4725  return false;
4726}
4727
4728/// Returns appropriate ARM CMP (cmp) and corresponding condition code for
4729/// the given operands.
4730SDValue ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
4731                                     SDValue &ARMcc, SelectionDAG &DAG,
4732                                     const SDLoc &dl) const {
4733  if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
4734    unsigned C = RHSC->getZExtValue();
4735    if (!isLegalICmpImmediate((int32_t)C)) {
4736      // Constant does not fit, try adjusting it by one.
4737      switch (CC) {
4738      default: break;
4739      case ISD::SETLT:
4740      case ISD::SETGE:
4741        if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
4742          CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
4743          RHS = DAG.getConstant(C - 1, dl, MVT::i32);
4744        }
4745        break;
4746      case ISD::SETULT:
4747      case ISD::SETUGE:
4748        if (C != 0 && isLegalICmpImmediate(C-1)) {
4749          CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
4750          RHS = DAG.getConstant(C - 1, dl, MVT::i32);
4751        }
4752        break;
4753      case ISD::SETLE:
4754      case ISD::SETGT:
4755        if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
4756          CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
4757          RHS = DAG.getConstant(C + 1, dl, MVT::i32);
4758        }
4759        break;
4760      case ISD::SETULE:
4761      case ISD::SETUGT:
4762        if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
4763          CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
4764          RHS = DAG.getConstant(C + 1, dl, MVT::i32);
4765        }
4766        break;
4767      }
4768    }
4769  } else if ((ARM_AM::getShiftOpcForNode(LHS.getOpcode()) != ARM_AM::no_shift) &&
4770             (ARM_AM::getShiftOpcForNode(RHS.getOpcode()) == ARM_AM::no_shift)) {
4771    // In ARM and Thumb-2, the compare instructions can shift their second
4772    // operand.
4773    CC = ISD::getSetCCSwappedOperands(CC);
4774    std::swap(LHS, RHS);
4775  }
4776
4777  // Thumb1 has very limited immediate modes, so turning an "and" into a
4778  // shift can save multiple instructions.
4779  //
4780  // If we have (x & C1), and C1 is an appropriate mask, we can transform it
4781  // into "((x << n) >> n)".  But that isn't necessarily profitable on its
4782  // own. If it's the operand to an unsigned comparison with an immediate,
4783  // we can eliminate one of the shifts: we transform
4784  // "((x << n) >> n) == C2" to "(x << n) == (C2 << n)".
4785  //
4786  // We avoid transforming cases which aren't profitable due to encoding
4787  // details:
4788  //
4789  // 1. C2 fits into the immediate field of a cmp, and the transformed version
4790  // would not; in that case, we're essentially trading one immediate load for
4791  // another.
4792  // 2. C1 is 255 or 65535, so we can use uxtb or uxth.
4793  // 3. C2 is zero; we have other code for this special case.
4794  //
4795  // FIXME: Figure out profitability for Thumb2; we usually can't save an
4796  // instruction, since the AND is always one instruction anyway, but we could
4797  // use narrow instructions in some cases.
4798  if (Subtarget->isThumb1Only() && LHS->getOpcode() == ISD::AND &&
4799      LHS->hasOneUse() && isa<ConstantSDNode>(LHS.getOperand(1)) &&
4800      LHS.getValueType() == MVT::i32 && isa<ConstantSDNode>(RHS) &&
4801      !isSignedIntSetCC(CC)) {
4802    unsigned Mask = LHS.getConstantOperandVal(1);
4803    auto *RHSC = cast<ConstantSDNode>(RHS.getNode());
4804    uint64_t RHSV = RHSC->getZExtValue();
4805    if (isMask_32(Mask) && (RHSV & ~Mask) == 0 && Mask != 255 && Mask != 65535) {
4806      unsigned ShiftBits = llvm::countl_zero(Mask);
4807      if (RHSV && (RHSV > 255 || (RHSV << ShiftBits) <= 255)) {
4808        SDValue ShiftAmt = DAG.getConstant(ShiftBits, dl, MVT::i32);
4809        LHS = DAG.getNode(ISD::SHL, dl, MVT::i32, LHS.getOperand(0), ShiftAmt);
4810        RHS = DAG.getConstant(RHSV << ShiftBits, dl, MVT::i32);
4811      }
4812    }
4813  }
4814
4815  // The specific comparison "(x<<c) > 0x80000000U" can be optimized to a
4816  // single "lsls x, c+1".  The shift sets the "C" and "Z" flags the same
4817  // way a cmp would.
4818  // FIXME: Add support for ARM/Thumb2; this would need isel patterns, and
4819  // some tweaks to the heuristics for the previous and->shift transform.
4820  // FIXME: Optimize cases where the LHS isn't a shift.
4821  if (Subtarget->isThumb1Only() && LHS->getOpcode() == ISD::SHL &&
4822      isa<ConstantSDNode>(RHS) && RHS->getAsZExtVal() == 0x80000000U &&
4823      CC == ISD::SETUGT && isa<ConstantSDNode>(LHS.getOperand(1)) &&
4824      LHS.getConstantOperandVal(1) < 31) {
4825    unsigned ShiftAmt = LHS.getConstantOperandVal(1) + 1;
4826    SDValue Shift = DAG.getNode(ARMISD::LSLS, dl,
4827                                DAG.getVTList(MVT::i32, MVT::i32),
4828                                LHS.getOperand(0),
4829                                DAG.getConstant(ShiftAmt, dl, MVT::i32));
4830    SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, ARM::CPSR,
4831                                     Shift.getValue(1), SDValue());
4832    ARMcc = DAG.getConstant(ARMCC::HI, dl, MVT::i32);
4833    return Chain.getValue(1);
4834  }
4835
4836  ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
4837
4838  // If the RHS is a constant zero then the V (overflow) flag will never be
4839  // set. This can allow us to simplify GE to PL or LT to MI, which can be
4840  // simpler for other passes (like the peephole optimiser) to deal with.
4841  if (isNullConstant(RHS)) {
4842    switch (CondCode) {
4843      default: break;
4844      case ARMCC::GE:
4845        CondCode = ARMCC::PL;
4846        break;
4847      case ARMCC::LT:
4848        CondCode = ARMCC::MI;
4849        break;
4850    }
4851  }
4852
4853  ARMISD::NodeType CompareType;
4854  switch (CondCode) {
4855  default:
4856    CompareType = ARMISD::CMP;
4857    break;
4858  case ARMCC::EQ:
4859  case ARMCC::NE:
4860    // Uses only Z Flag
4861    CompareType = ARMISD::CMPZ;
4862    break;
4863  }
4864  ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
4865  return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
4866}
4867
4868/// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
4869SDValue ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS,
4870                                     SelectionDAG &DAG, const SDLoc &dl,
4871                                     bool Signaling) const {
4872  assert(Subtarget->hasFP64() || RHS.getValueType() != MVT::f64);
4873  SDValue Cmp;
4874  if (!isFloatingPointZero(RHS))
4875    Cmp = DAG.getNode(Signaling ? ARMISD::CMPFPE : ARMISD::CMPFP,
4876                      dl, MVT::Glue, LHS, RHS);
4877  else
4878    Cmp = DAG.getNode(Signaling ? ARMISD::CMPFPEw0 : ARMISD::CMPFPw0,
4879                      dl, MVT::Glue, LHS);
4880  return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
4881}
4882
4883/// duplicateCmp - Glue values can have only one use, so this function
4884/// duplicates a comparison node.
4885SDValue
4886ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
4887  unsigned Opc = Cmp.getOpcode();
4888  SDLoc DL(Cmp);
4889  if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
4890    return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
4891
4892  assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
4893  Cmp = Cmp.getOperand(0);
4894  Opc = Cmp.getOpcode();
4895  if (Opc == ARMISD::CMPFP)
4896    Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
4897  else {
4898    assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
4899    Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
4900  }
4901  return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
4902}
4903
4904// This function returns three things: the arithmetic computation itself
4905// (Value), a comparison (OverflowCmp), and a condition code (ARMcc).  The
4906// comparison and the condition code define the case in which the arithmetic
4907// computation *does not* overflow.
4908std::pair<SDValue, SDValue>
4909ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
4910                                 SDValue &ARMcc) const {
4911  assert(Op.getValueType() == MVT::i32 &&  "Unsupported value type");
4912
4913  SDValue Value, OverflowCmp;
4914  SDValue LHS = Op.getOperand(0);
4915  SDValue RHS = Op.getOperand(1);
4916  SDLoc dl(Op);
4917
4918  // FIXME: We are currently always generating CMPs because we don't support
4919  // generating CMN through the backend. This is not as good as the natural
4920  // CMP case because it causes a register dependency and cannot be folded
4921  // later.
4922
4923  switch (Op.getOpcode()) {
4924  default:
4925    llvm_unreachable("Unknown overflow instruction!");
4926  case ISD::SADDO:
4927    ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
4928    Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
4929    OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
4930    break;
4931  case ISD::UADDO:
4932    ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
4933    // We use ADDC here to correspond to its use in LowerUnsignedALUO.
4934    // We do not use it in the USUBO case as Value may not be used.
4935    Value = DAG.getNode(ARMISD::ADDC, dl,
4936                        DAG.getVTList(Op.getValueType(), MVT::i32), LHS, RHS)
4937                .getValue(0);
4938    OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
4939    break;
4940  case ISD::SSUBO:
4941    ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
4942    Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
4943    OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
4944    break;
4945  case ISD::USUBO:
4946    ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
4947    Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
4948    OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
4949    break;
4950  case ISD::UMULO:
4951    // We generate a UMUL_LOHI and then check if the high word is 0.
4952    ARMcc = DAG.getConstant(ARMCC::EQ, dl, MVT::i32);
4953    Value = DAG.getNode(ISD::UMUL_LOHI, dl,
4954                        DAG.getVTList(Op.getValueType(), Op.getValueType()),
4955                        LHS, RHS);
4956    OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value.getValue(1),
4957                              DAG.getConstant(0, dl, MVT::i32));
4958    Value = Value.getValue(0); // We only want the low 32 bits for the result.
4959    break;
4960  case ISD::SMULO:
4961    // We generate a SMUL_LOHI and then check if all the bits of the high word
4962    // are the same as the sign bit of the low word.
4963    ARMcc = DAG.getConstant(ARMCC::EQ, dl, MVT::i32);
4964    Value = DAG.getNode(ISD::SMUL_LOHI, dl,
4965                        DAG.getVTList(Op.getValueType(), Op.getValueType()),
4966                        LHS, RHS);
4967    OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value.getValue(1),
4968                              DAG.getNode(ISD::SRA, dl, Op.getValueType(),
4969                                          Value.getValue(0),
4970                                          DAG.getConstant(31, dl, MVT::i32)));
4971    Value = Value.getValue(0); // We only want the low 32 bits for the result.
4972    break;
4973  } // switch (...)
4974
4975  return std::make_pair(Value, OverflowCmp);
4976}
4977
4978SDValue
4979ARMTargetLowering::LowerSignedALUO(SDValue Op, SelectionDAG &DAG) const {
4980  // Let legalize expand this if it isn't a legal type yet.
4981  if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
4982    return SDValue();
4983
4984  SDValue Value, OverflowCmp;
4985  SDValue ARMcc;
4986  std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
4987  SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4988  SDLoc dl(Op);
4989  // We use 0 and 1 as false and true values.
4990  SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
4991  SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
4992  EVT VT = Op.getValueType();
4993
4994  SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal,
4995                                 ARMcc, CCR, OverflowCmp);
4996
4997  SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
4998  return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
4999}
5000
5001static SDValue ConvertBooleanCarryToCarryFlag(SDValue BoolCarry,
5002                                              SelectionDAG &DAG) {
5003  SDLoc DL(BoolCarry);
5004  EVT CarryVT = BoolCarry.getValueType();
5005
5006  // This converts the boolean value carry into the carry flag by doing
5007  // ARMISD::SUBC Carry, 1
5008  SDValue Carry = DAG.getNode(ARMISD::SUBC, DL,
5009                              DAG.getVTList(CarryVT, MVT::i32),
5010                              BoolCarry, DAG.getConstant(1, DL, CarryVT));
5011  return Carry.getValue(1);
5012}
5013
5014static SDValue ConvertCarryFlagToBooleanCarry(SDValue Flags, EVT VT,
5015                                              SelectionDAG &DAG) {
5016  SDLoc DL(Flags);
5017
5018  // Now convert the carry flag into a boolean carry. We do this
5019  // using ARMISD:ADDE 0, 0, Carry
5020  return DAG.getNode(ARMISD::ADDE, DL, DAG.getVTList(VT, MVT::i32),
5021                     DAG.getConstant(0, DL, MVT::i32),
5022                     DAG.getConstant(0, DL, MVT::i32), Flags);
5023}
5024
5025SDValue ARMTargetLowering::LowerUnsignedALUO(SDValue Op,
5026                                             SelectionDAG &DAG) const {
5027  // Let legalize expand this if it isn't a legal type yet.
5028  if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
5029    return SDValue();
5030
5031  SDValue LHS = Op.getOperand(0);
5032  SDValue RHS = Op.getOperand(1);
5033  SDLoc dl(Op);
5034
5035  EVT VT = Op.getValueType();
5036  SDVTList VTs = DAG.getVTList(VT, MVT::i32);
5037  SDValue Value;
5038  SDValue Overflow;
5039  switch (Op.getOpcode()) {
5040  default:
5041    llvm_unreachable("Unknown overflow instruction!");
5042  case ISD::UADDO:
5043    Value = DAG.getNode(ARMISD::ADDC, dl, VTs, LHS, RHS);
5044    // Convert the carry flag into a boolean value.
5045    Overflow = ConvertCarryFlagToBooleanCarry(Value.getValue(1), VT, DAG);
5046    break;
5047  case ISD::USUBO: {
5048    Value = DAG.getNode(ARMISD::SUBC, dl, VTs, LHS, RHS);
5049    // Convert the carry flag into a boolean value.
5050    Overflow = ConvertCarryFlagToBooleanCarry(Value.getValue(1), VT, DAG);
5051    // ARMISD::SUBC returns 0 when we have to borrow, so make it an overflow
5052    // value. So compute 1 - C.
5053    Overflow = DAG.getNode(ISD::SUB, dl, MVT::i32,
5054                           DAG.getConstant(1, dl, MVT::i32), Overflow);
5055    break;
5056  }
5057  }
5058
5059  return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
5060}
5061
5062static SDValue LowerADDSUBSAT(SDValue Op, SelectionDAG &DAG,
5063                              const ARMSubtarget *Subtarget) {
5064  EVT VT = Op.getValueType();
5065  if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP() || Subtarget->isThumb1Only())
5066    return SDValue();
5067  if (!VT.isSimple())
5068    return SDValue();
5069
5070  unsigned NewOpcode;
5071  switch (VT.getSimpleVT().SimpleTy) {
5072  default:
5073    return SDValue();
5074  case MVT::i8:
5075    switch (Op->getOpcode()) {
5076    case ISD::UADDSAT:
5077      NewOpcode = ARMISD::UQADD8b;
5078      break;
5079    case ISD::SADDSAT:
5080      NewOpcode = ARMISD::QADD8b;
5081      break;
5082    case ISD::USUBSAT:
5083      NewOpcode = ARMISD::UQSUB8b;
5084      break;
5085    case ISD::SSUBSAT:
5086      NewOpcode = ARMISD::QSUB8b;
5087      break;
5088    }
5089    break;
5090  case MVT::i16:
5091    switch (Op->getOpcode()) {
5092    case ISD::UADDSAT:
5093      NewOpcode = ARMISD::UQADD16b;
5094      break;
5095    case ISD::SADDSAT:
5096      NewOpcode = ARMISD::QADD16b;
5097      break;
5098    case ISD::USUBSAT:
5099      NewOpcode = ARMISD::UQSUB16b;
5100      break;
5101    case ISD::SSUBSAT:
5102      NewOpcode = ARMISD::QSUB16b;
5103      break;
5104    }
5105    break;
5106  }
5107
5108  SDLoc dl(Op);
5109  SDValue Add =
5110      DAG.getNode(NewOpcode, dl, MVT::i32,
5111                  DAG.getSExtOrTrunc(Op->getOperand(0), dl, MVT::i32),
5112                  DAG.getSExtOrTrunc(Op->getOperand(1), dl, MVT::i32));
5113  return DAG.getNode(ISD::TRUNCATE, dl, VT, Add);
5114}
5115
5116SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
5117  SDValue Cond = Op.getOperand(0);
5118  SDValue SelectTrue = Op.getOperand(1);
5119  SDValue SelectFalse = Op.getOperand(2);
5120  SDLoc dl(Op);
5121  unsigned Opc = Cond.getOpcode();
5122
5123  if (Cond.getResNo() == 1 &&
5124      (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
5125       Opc == ISD::USUBO)) {
5126    if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
5127      return SDValue();
5128
5129    SDValue Value, OverflowCmp;
5130    SDValue ARMcc;
5131    std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
5132    SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5133    EVT VT = Op.getValueType();
5134
5135    return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR,
5136                   OverflowCmp, DAG);
5137  }
5138
5139  // Convert:
5140  //
5141  //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
5142  //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
5143  //
5144  if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
5145    const ConstantSDNode *CMOVTrue =
5146      dyn_cast<ConstantSDNode>(Cond.getOperand(0));
5147    const ConstantSDNode *CMOVFalse =
5148      dyn_cast<ConstantSDNode>(Cond.getOperand(1));
5149
5150    if (CMOVTrue && CMOVFalse) {
5151      unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
5152      unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
5153
5154      SDValue True;
5155      SDValue False;
5156      if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
5157        True = SelectTrue;
5158        False = SelectFalse;
5159      } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
5160        True = SelectFalse;
5161        False = SelectTrue;
5162      }
5163
5164      if (True.getNode() && False.getNode()) {
5165        EVT VT = Op.getValueType();
5166        SDValue ARMcc = Cond.getOperand(2);
5167        SDValue CCR = Cond.getOperand(3);
5168        SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
5169        assert(True.getValueType() == VT);
5170        return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG);
5171      }
5172    }
5173  }
5174
5175  // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
5176  // undefined bits before doing a full-word comparison with zero.
5177  Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
5178                     DAG.getConstant(1, dl, Cond.getValueType()));
5179
5180  return DAG.getSelectCC(dl, Cond,
5181                         DAG.getConstant(0, dl, Cond.getValueType()),
5182                         SelectTrue, SelectFalse, ISD::SETNE);
5183}
5184
5185static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
5186                                 bool &swpCmpOps, bool &swpVselOps) {
5187  // Start by selecting the GE condition code for opcodes that return true for
5188  // 'equality'
5189  if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
5190      CC == ISD::SETULE || CC == ISD::SETGE  || CC == ISD::SETLE)
5191    CondCode = ARMCC::GE;
5192
5193  // and GT for opcodes that return false for 'equality'.
5194  else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
5195           CC == ISD::SETULT || CC == ISD::SETGT  || CC == ISD::SETLT)
5196    CondCode = ARMCC::GT;
5197
5198  // Since we are constrained to GE/GT, if the opcode contains 'less', we need
5199  // to swap the compare operands.
5200  if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
5201      CC == ISD::SETULT || CC == ISD::SETLE  || CC == ISD::SETLT)
5202    swpCmpOps = true;
5203
5204  // Both GT and GE are ordered comparisons, and return false for 'unordered'.
5205  // If we have an unordered opcode, we need to swap the operands to the VSEL
5206  // instruction (effectively negating the condition).
5207  //
5208  // This also has the effect of swapping which one of 'less' or 'greater'
5209  // returns true, so we also swap the compare operands. It also switches
5210  // whether we return true for 'equality', so we compensate by picking the
5211  // opposite condition code to our original choice.
5212  if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
5213      CC == ISD::SETUGT) {
5214    swpCmpOps = !swpCmpOps;
5215    swpVselOps = !swpVselOps;
5216    CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
5217  }
5218
5219  // 'ordered' is 'anything but unordered', so use the VS condition code and
5220  // swap the VSEL operands.
5221  if (CC == ISD::SETO) {
5222    CondCode = ARMCC::VS;
5223    swpVselOps = true;
5224  }
5225
5226  // 'unordered or not equal' is 'anything but equal', so use the EQ condition
5227  // code and swap the VSEL operands. Also do this if we don't care about the
5228  // unordered case.
5229  if (CC == ISD::SETUNE || CC == ISD::SETNE) {
5230    CondCode = ARMCC::EQ;
5231    swpVselOps = true;
5232  }
5233}
5234
5235SDValue ARMTargetLowering::getCMOV(const SDLoc &dl, EVT VT, SDValue FalseVal,
5236                                   SDValue TrueVal, SDValue ARMcc, SDValue CCR,
5237                                   SDValue Cmp, SelectionDAG &DAG) const {
5238  if (!Subtarget->hasFP64() && VT == MVT::f64) {
5239    FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl,
5240                           DAG.getVTList(MVT::i32, MVT::i32), FalseVal);
5241    TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl,
5242                          DAG.getVTList(MVT::i32, MVT::i32), TrueVal);
5243
5244    SDValue TrueLow = TrueVal.getValue(0);
5245    SDValue TrueHigh = TrueVal.getValue(1);
5246    SDValue FalseLow = FalseVal.getValue(0);
5247    SDValue FalseHigh = FalseVal.getValue(1);
5248
5249    SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow,
5250                              ARMcc, CCR, Cmp);
5251    SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh,
5252                               ARMcc, CCR, duplicateCmp(Cmp, DAG));
5253
5254    return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High);
5255  } else {
5256    return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
5257                       Cmp);
5258  }
5259}
5260
5261static bool isGTorGE(ISD::CondCode CC) {
5262  return CC == ISD::SETGT || CC == ISD::SETGE;
5263}
5264
5265static bool isLTorLE(ISD::CondCode CC) {
5266  return CC == ISD::SETLT || CC == ISD::SETLE;
5267}
5268
5269// See if a conditional (LHS CC RHS ? TrueVal : FalseVal) is lower-saturating.
5270// All of these conditions (and their <= and >= counterparts) will do:
5271//          x < k ? k : x
5272//          x > k ? x : k
5273//          k < x ? x : k
5274//          k > x ? k : x
5275static bool isLowerSaturate(const SDValue LHS, const SDValue RHS,
5276                            const SDValue TrueVal, const SDValue FalseVal,
5277                            const ISD::CondCode CC, const SDValue K) {
5278  return (isGTorGE(CC) &&
5279          ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal))) ||
5280         (isLTorLE(CC) &&
5281          ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal)));
5282}
5283
5284// Check if two chained conditionals could be converted into SSAT or USAT.
5285//
5286// SSAT can replace a set of two conditional selectors that bound a number to an
5287// interval of type [k, ~k] when k + 1 is a power of 2. Here are some examples:
5288//
5289//     x < -k ? -k : (x > k ? k : x)
5290//     x < -k ? -k : (x < k ? x : k)
5291//     x > -k ? (x > k ? k : x) : -k
5292//     x < k ? (x < -k ? -k : x) : k
5293//     etc.
5294//
5295// LLVM canonicalizes these to either a min(max()) or a max(min())
5296// pattern. This function tries to match one of these and will return a SSAT
5297// node if successful.
5298//
5299// USAT works similarily to SSAT but bounds on the interval [0, k] where k + 1
5300// is a power of 2.
5301static SDValue LowerSaturatingConditional(SDValue Op, SelectionDAG &DAG) {
5302  EVT VT = Op.getValueType();
5303  SDValue V1 = Op.getOperand(0);
5304  SDValue K1 = Op.getOperand(1);
5305  SDValue TrueVal1 = Op.getOperand(2);
5306  SDValue FalseVal1 = Op.getOperand(3);
5307  ISD::CondCode CC1 = cast<CondCodeSDNode>(Op.getOperand(4))->get();
5308
5309  const SDValue Op2 = isa<ConstantSDNode>(TrueVal1) ? FalseVal1 : TrueVal1;
5310  if (Op2.getOpcode() != ISD::SELECT_CC)
5311    return SDValue();
5312
5313  SDValue V2 = Op2.getOperand(0);
5314  SDValue K2 = Op2.getOperand(1);
5315  SDValue TrueVal2 = Op2.getOperand(2);
5316  SDValue FalseVal2 = Op2.getOperand(3);
5317  ISD::CondCode CC2 = cast<CondCodeSDNode>(Op2.getOperand(4))->get();
5318
5319  SDValue V1Tmp = V1;
5320  SDValue V2Tmp = V2;
5321
5322  // Check that the registers and the constants match a max(min()) or min(max())
5323  // pattern
5324  if (V1Tmp != TrueVal1 || V2Tmp != TrueVal2 || K1 != FalseVal1 ||
5325      K2 != FalseVal2 ||
5326      !((isGTorGE(CC1) && isLTorLE(CC2)) || (isLTorLE(CC1) && isGTorGE(CC2))))
5327    return SDValue();
5328
5329  // Check that the constant in the lower-bound check is
5330  // the opposite of the constant in the upper-bound check
5331  // in 1's complement.
5332  if (!isa<ConstantSDNode>(K1) || !isa<ConstantSDNode>(K2))
5333    return SDValue();
5334
5335  int64_t Val1 = cast<ConstantSDNode>(K1)->getSExtValue();
5336  int64_t Val2 = cast<ConstantSDNode>(K2)->getSExtValue();
5337  int64_t PosVal = std::max(Val1, Val2);
5338  int64_t NegVal = std::min(Val1, Val2);
5339
5340  if (!((Val1 > Val2 && isLTorLE(CC1)) || (Val1 < Val2 && isLTorLE(CC2))) ||
5341      !isPowerOf2_64(PosVal + 1))
5342    return SDValue();
5343
5344  // Handle the difference between USAT (unsigned) and SSAT (signed)
5345  // saturation
5346  // At this point, PosVal is guaranteed to be positive
5347  uint64_t K = PosVal;
5348  SDLoc dl(Op);
5349  if (Val1 == ~Val2)
5350    return DAG.getNode(ARMISD::SSAT, dl, VT, V2Tmp,
5351                       DAG.getConstant(llvm::countr_one(K), dl, VT));
5352  if (NegVal == 0)
5353    return DAG.getNode(ARMISD::USAT, dl, VT, V2Tmp,
5354                       DAG.getConstant(llvm::countr_one(K), dl, VT));
5355
5356  return SDValue();
5357}
5358
5359// Check if a condition of the type x < k ? k : x can be converted into a
5360// bit operation instead of conditional moves.
5361// Currently this is allowed given:
5362// - The conditions and values match up
5363// - k is 0 or -1 (all ones)
5364// This function will not check the last condition, thats up to the caller
5365// It returns true if the transformation can be made, and in such case
5366// returns x in V, and k in SatK.
5367static bool isLowerSaturatingConditional(const SDValue &Op, SDValue &V,
5368                                         SDValue &SatK)
5369{
5370  SDValue LHS = Op.getOperand(0);
5371  SDValue RHS = Op.getOperand(1);
5372  ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
5373  SDValue TrueVal = Op.getOperand(2);
5374  SDValue FalseVal = Op.getOperand(3);
5375
5376  SDValue *K = isa<ConstantSDNode>(LHS) ? &LHS : isa<ConstantSDNode>(RHS)
5377                                               ? &RHS
5378                                               : nullptr;
5379
5380  // No constant operation in comparison, early out
5381  if (!K)
5382    return false;
5383
5384  SDValue KTmp = isa<ConstantSDNode>(TrueVal) ? TrueVal : FalseVal;
5385  V = (KTmp == TrueVal) ? FalseVal : TrueVal;
5386  SDValue VTmp = (K && *K == LHS) ? RHS : LHS;
5387
5388  // If the constant on left and right side, or variable on left and right,
5389  // does not match, early out
5390  if (*K != KTmp || V != VTmp)
5391    return false;
5392
5393  if (isLowerSaturate(LHS, RHS, TrueVal, FalseVal, CC, *K)) {
5394    SatK = *K;
5395    return true;
5396  }
5397
5398  return false;
5399}
5400
5401bool ARMTargetLowering::isUnsupportedFloatingType(EVT VT) const {
5402  if (VT == MVT::f32)
5403    return !Subtarget->hasVFP2Base();
5404  if (VT == MVT::f64)
5405    return !Subtarget->hasFP64();
5406  if (VT == MVT::f16)
5407    return !Subtarget->hasFullFP16();
5408  return false;
5409}
5410
5411SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
5412  EVT VT = Op.getValueType();
5413  SDLoc dl(Op);
5414
5415  // Try to convert two saturating conditional selects into a single SSAT
5416  if ((!Subtarget->isThumb() && Subtarget->hasV6Ops()) || Subtarget->isThumb2())
5417    if (SDValue SatValue = LowerSaturatingConditional(Op, DAG))
5418      return SatValue;
5419
5420  // Try to convert expressions of the form x < k ? k : x (and similar forms)
5421  // into more efficient bit operations, which is possible when k is 0 or -1
5422  // On ARM and Thumb-2 which have flexible operand 2 this will result in
5423  // single instructions. On Thumb the shift and the bit operation will be two
5424  // instructions.
5425  // Only allow this transformation on full-width (32-bit) operations
5426  SDValue LowerSatConstant;
5427  SDValue SatValue;
5428  if (VT == MVT::i32 &&
5429      isLowerSaturatingConditional(Op, SatValue, LowerSatConstant)) {
5430    SDValue ShiftV = DAG.getNode(ISD::SRA, dl, VT, SatValue,
5431                                 DAG.getConstant(31, dl, VT));
5432    if (isNullConstant(LowerSatConstant)) {
5433      SDValue NotShiftV = DAG.getNode(ISD::XOR, dl, VT, ShiftV,
5434                                      DAG.getAllOnesConstant(dl, VT));
5435      return DAG.getNode(ISD::AND, dl, VT, SatValue, NotShiftV);
5436    } else if (isAllOnesConstant(LowerSatConstant))
5437      return DAG.getNode(ISD::OR, dl, VT, SatValue, ShiftV);
5438  }
5439
5440  SDValue LHS = Op.getOperand(0);
5441  SDValue RHS = Op.getOperand(1);
5442  ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
5443  SDValue TrueVal = Op.getOperand(2);
5444  SDValue FalseVal = Op.getOperand(3);
5445  ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FalseVal);
5446  ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TrueVal);
5447
5448  if (Subtarget->hasV8_1MMainlineOps() && CFVal && CTVal &&
5449      LHS.getValueType() == MVT::i32 && RHS.getValueType() == MVT::i32) {
5450    unsigned TVal = CTVal->getZExtValue();
5451    unsigned FVal = CFVal->getZExtValue();
5452    unsigned Opcode = 0;
5453
5454    if (TVal == ~FVal) {
5455      Opcode = ARMISD::CSINV;
5456    } else if (TVal == ~FVal + 1) {
5457      Opcode = ARMISD::CSNEG;
5458    } else if (TVal + 1 == FVal) {
5459      Opcode = ARMISD::CSINC;
5460    } else if (TVal == FVal + 1) {
5461      Opcode = ARMISD::CSINC;
5462      std::swap(TrueVal, FalseVal);
5463      std::swap(TVal, FVal);
5464      CC = ISD::getSetCCInverse(CC, LHS.getValueType());
5465    }
5466
5467    if (Opcode) {
5468      // If one of the constants is cheaper than another, materialise the
5469      // cheaper one and let the csel generate the other.
5470      if (Opcode != ARMISD::CSINC &&
5471          HasLowerConstantMaterializationCost(FVal, TVal, Subtarget)) {
5472        std::swap(TrueVal, FalseVal);
5473        std::swap(TVal, FVal);
5474        CC = ISD::getSetCCInverse(CC, LHS.getValueType());
5475      }
5476
5477      // Attempt to use ZR checking TVal is 0, possibly inverting the condition
5478      // to get there. CSINC not is invertable like the other two (~(~a) == a,
5479      // -(-a) == a, but (a+1)+1 != a).
5480      if (FVal == 0 && Opcode != ARMISD::CSINC) {
5481        std::swap(TrueVal, FalseVal);
5482        std::swap(TVal, FVal);
5483        CC = ISD::getSetCCInverse(CC, LHS.getValueType());
5484      }
5485
5486      // Drops F's value because we can get it by inverting/negating TVal.
5487      FalseVal = TrueVal;
5488
5489      SDValue ARMcc;
5490      SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
5491      EVT VT = TrueVal.getValueType();
5492      return DAG.getNode(Opcode, dl, VT, TrueVal, FalseVal, ARMcc, Cmp);
5493    }
5494  }
5495
5496  if (isUnsupportedFloatingType(LHS.getValueType())) {
5497    DAG.getTargetLoweringInfo().softenSetCCOperands(
5498        DAG, LHS.getValueType(), LHS, RHS, CC, dl, LHS, RHS);
5499
5500    // If softenSetCCOperands only returned one value, we should compare it to
5501    // zero.
5502    if (!RHS.getNode()) {
5503      RHS = DAG.getConstant(0, dl, LHS.getValueType());
5504      CC = ISD::SETNE;
5505    }
5506  }
5507
5508  if (LHS.getValueType() == MVT::i32) {
5509    // Try to generate VSEL on ARMv8.
5510    // The VSEL instruction can't use all the usual ARM condition
5511    // codes: it only has two bits to select the condition code, so it's
5512    // constrained to use only GE, GT, VS and EQ.
5513    //
5514    // To implement all the various ISD::SETXXX opcodes, we sometimes need to
5515    // swap the operands of the previous compare instruction (effectively
5516    // inverting the compare condition, swapping 'less' and 'greater') and
5517    // sometimes need to swap the operands to the VSEL (which inverts the
5518    // condition in the sense of firing whenever the previous condition didn't)
5519    if (Subtarget->hasFPARMv8Base() && (TrueVal.getValueType() == MVT::f16 ||
5520                                        TrueVal.getValueType() == MVT::f32 ||
5521                                        TrueVal.getValueType() == MVT::f64)) {
5522      ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
5523      if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
5524          CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
5525        CC = ISD::getSetCCInverse(CC, LHS.getValueType());
5526        std::swap(TrueVal, FalseVal);
5527      }
5528    }
5529
5530    SDValue ARMcc;
5531    SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5532    SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
5533    // Choose GE over PL, which vsel does now support
5534    if (ARMcc->getAsZExtVal() == ARMCC::PL)
5535      ARMcc = DAG.getConstant(ARMCC::GE, dl, MVT::i32);
5536    return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
5537  }
5538
5539  ARMCC::CondCodes CondCode, CondCode2;
5540  FPCCToARMCC(CC, CondCode, CondCode2);
5541
5542  // Normalize the fp compare. If RHS is zero we prefer to keep it there so we
5543  // match CMPFPw0 instead of CMPFP, though we don't do this for f16 because we
5544  // must use VSEL (limited condition codes), due to not having conditional f16
5545  // moves.
5546  if (Subtarget->hasFPARMv8Base() &&
5547      !(isFloatingPointZero(RHS) && TrueVal.getValueType() != MVT::f16) &&
5548      (TrueVal.getValueType() == MVT::f16 ||
5549       TrueVal.getValueType() == MVT::f32 ||
5550       TrueVal.getValueType() == MVT::f64)) {
5551    bool swpCmpOps = false;
5552    bool swpVselOps = false;
5553    checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
5554
5555    if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
5556        CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
5557      if (swpCmpOps)
5558        std::swap(LHS, RHS);
5559      if (swpVselOps)
5560        std::swap(TrueVal, FalseVal);
5561    }
5562  }
5563
5564  SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
5565  SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
5566  SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5567  SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
5568  if (CondCode2 != ARMCC::AL) {
5569    SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32);
5570    // FIXME: Needs another CMP because flag can have but one use.
5571    SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
5572    Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG);
5573  }
5574  return Result;
5575}
5576
5577/// canChangeToInt - Given the fp compare operand, return true if it is suitable
5578/// to morph to an integer compare sequence.
5579static bool canChangeToInt(SDValue Op, bool &SeenZero,
5580                           const ARMSubtarget *Subtarget) {
5581  SDNode *N = Op.getNode();
5582  if (!N->hasOneUse())
5583    // Otherwise it requires moving the value from fp to integer registers.
5584    return false;
5585  if (!N->getNumValues())
5586    return false;
5587  EVT VT = Op.getValueType();
5588  if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
5589    // f32 case is generally profitable. f64 case only makes sense when vcmpe +
5590    // vmrs are very slow, e.g. cortex-a8.
5591    return false;
5592
5593  if (isFloatingPointZero(Op)) {
5594    SeenZero = true;
5595    return true;
5596  }
5597  return ISD::isNormalLoad(N);
5598}
5599
5600static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
5601  if (isFloatingPointZero(Op))
5602    return DAG.getConstant(0, SDLoc(Op), MVT::i32);
5603
5604  if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
5605    return DAG.getLoad(MVT::i32, SDLoc(Op), Ld->getChain(), Ld->getBasePtr(),
5606                       Ld->getPointerInfo(), Ld->getAlign(),
5607                       Ld->getMemOperand()->getFlags());
5608
5609  llvm_unreachable("Unknown VFP cmp argument!");
5610}
5611
5612static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
5613                           SDValue &RetVal1, SDValue &RetVal2) {
5614  SDLoc dl(Op);
5615
5616  if (isFloatingPointZero(Op)) {
5617    RetVal1 = DAG.getConstant(0, dl, MVT::i32);
5618    RetVal2 = DAG.getConstant(0, dl, MVT::i32);
5619    return;
5620  }
5621
5622  if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
5623    SDValue Ptr = Ld->getBasePtr();
5624    RetVal1 =
5625        DAG.getLoad(MVT::i32, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
5626                    Ld->getAlign(), Ld->getMemOperand()->getFlags());
5627
5628    EVT PtrType = Ptr.getValueType();
5629    SDValue NewPtr = DAG.getNode(ISD::ADD, dl,
5630                                 PtrType, Ptr, DAG.getConstant(4, dl, PtrType));
5631    RetVal2 = DAG.getLoad(MVT::i32, dl, Ld->getChain(), NewPtr,
5632                          Ld->getPointerInfo().getWithOffset(4),
5633                          commonAlignment(Ld->getAlign(), 4),
5634                          Ld->getMemOperand()->getFlags());
5635    return;
5636  }
5637
5638  llvm_unreachable("Unknown VFP cmp argument!");
5639}
5640
5641/// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
5642/// f32 and even f64 comparisons to integer ones.
5643SDValue
5644ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
5645  SDValue Chain = Op.getOperand(0);
5646  ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
5647  SDValue LHS = Op.getOperand(2);
5648  SDValue RHS = Op.getOperand(3);
5649  SDValue Dest = Op.getOperand(4);
5650  SDLoc dl(Op);
5651
5652  bool LHSSeenZero = false;
5653  bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
5654  bool RHSSeenZero = false;
5655  bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
5656  if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
5657    // If unsafe fp math optimization is enabled and there are no other uses of
5658    // the CMP operands, and the condition code is EQ or NE, we can optimize it
5659    // to an integer comparison.
5660    if (CC == ISD::SETOEQ)
5661      CC = ISD::SETEQ;
5662    else if (CC == ISD::SETUNE)
5663      CC = ISD::SETNE;
5664
5665    SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32);
5666    SDValue ARMcc;
5667    if (LHS.getValueType() == MVT::f32) {
5668      LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
5669                        bitcastf32Toi32(LHS, DAG), Mask);
5670      RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
5671                        bitcastf32Toi32(RHS, DAG), Mask);
5672      SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
5673      SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5674      return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
5675                         Chain, Dest, ARMcc, CCR, Cmp);
5676    }
5677
5678    SDValue LHS1, LHS2;
5679    SDValue RHS1, RHS2;
5680    expandf64Toi32(LHS, DAG, LHS1, LHS2);
5681    expandf64Toi32(RHS, DAG, RHS1, RHS2);
5682    LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
5683    RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
5684    ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
5685    ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
5686    SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
5687    SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
5688    return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
5689  }
5690
5691  return SDValue();
5692}
5693
5694SDValue ARMTargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
5695  SDValue Chain = Op.getOperand(0);
5696  SDValue Cond = Op.getOperand(1);
5697  SDValue Dest = Op.getOperand(2);
5698  SDLoc dl(Op);
5699
5700  // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
5701  // instruction.
5702  unsigned Opc = Cond.getOpcode();
5703  bool OptimizeMul = (Opc == ISD::SMULO || Opc == ISD::UMULO) &&
5704                      !Subtarget->isThumb1Only();
5705  if (Cond.getResNo() == 1 &&
5706      (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
5707       Opc == ISD::USUBO || OptimizeMul)) {
5708    // Only lower legal XALUO ops.
5709    if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
5710      return SDValue();
5711
5712    // The actual operation with overflow check.
5713    SDValue Value, OverflowCmp;
5714    SDValue ARMcc;
5715    std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
5716
5717    // Reverse the condition code.
5718    ARMCC::CondCodes CondCode =
5719        (ARMCC::CondCodes)cast<const ConstantSDNode>(ARMcc)->getZExtValue();
5720    CondCode = ARMCC::getOppositeCondition(CondCode);
5721    ARMcc = DAG.getConstant(CondCode, SDLoc(ARMcc), MVT::i32);
5722    SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5723
5724    return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc, CCR,
5725                       OverflowCmp);
5726  }
5727
5728  return SDValue();
5729}
5730
5731SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
5732  SDValue Chain = Op.getOperand(0);
5733  ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
5734  SDValue LHS = Op.getOperand(2);
5735  SDValue RHS = Op.getOperand(3);
5736  SDValue Dest = Op.getOperand(4);
5737  SDLoc dl(Op);
5738
5739  if (isUnsupportedFloatingType(LHS.getValueType())) {
5740    DAG.getTargetLoweringInfo().softenSetCCOperands(
5741        DAG, LHS.getValueType(), LHS, RHS, CC, dl, LHS, RHS);
5742
5743    // If softenSetCCOperands only returned one value, we should compare it to
5744    // zero.
5745    if (!RHS.getNode()) {
5746      RHS = DAG.getConstant(0, dl, LHS.getValueType());
5747      CC = ISD::SETNE;
5748    }
5749  }
5750
5751  // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
5752  // instruction.
5753  unsigned Opc = LHS.getOpcode();
5754  bool OptimizeMul = (Opc == ISD::SMULO || Opc == ISD::UMULO) &&
5755                      !Subtarget->isThumb1Only();
5756  if (LHS.getResNo() == 1 && (isOneConstant(RHS) || isNullConstant(RHS)) &&
5757      (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
5758       Opc == ISD::USUBO || OptimizeMul) &&
5759      (CC == ISD::SETEQ || CC == ISD::SETNE)) {
5760    // Only lower legal XALUO ops.
5761    if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
5762      return SDValue();
5763
5764    // The actual operation with overflow check.
5765    SDValue Value, OverflowCmp;
5766    SDValue ARMcc;
5767    std::tie(Value, OverflowCmp) = getARMXALUOOp(LHS.getValue(0), DAG, ARMcc);
5768
5769    if ((CC == ISD::SETNE) != isOneConstant(RHS)) {
5770      // Reverse the condition code.
5771      ARMCC::CondCodes CondCode =
5772          (ARMCC::CondCodes)cast<const ConstantSDNode>(ARMcc)->getZExtValue();
5773      CondCode = ARMCC::getOppositeCondition(CondCode);
5774      ARMcc = DAG.getConstant(CondCode, SDLoc(ARMcc), MVT::i32);
5775    }
5776    SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5777
5778    return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc, CCR,
5779                       OverflowCmp);
5780  }
5781
5782  if (LHS.getValueType() == MVT::i32) {
5783    SDValue ARMcc;
5784    SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
5785    SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5786    return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
5787                       Chain, Dest, ARMcc, CCR, Cmp);
5788  }
5789
5790  if (getTargetMachine().Options.UnsafeFPMath &&
5791      (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
5792       CC == ISD::SETNE || CC == ISD::SETUNE)) {
5793    if (SDValue Result = OptimizeVFPBrcond(Op, DAG))
5794      return Result;
5795  }
5796
5797  ARMCC::CondCodes CondCode, CondCode2;
5798  FPCCToARMCC(CC, CondCode, CondCode2);
5799
5800  SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
5801  SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
5802  SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5803  SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
5804  SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
5805  SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
5806  if (CondCode2 != ARMCC::AL) {
5807    ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32);
5808    SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
5809    Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
5810  }
5811  return Res;
5812}
5813
5814SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
5815  SDValue Chain = Op.getOperand(0);
5816  SDValue Table = Op.getOperand(1);
5817  SDValue Index = Op.getOperand(2);
5818  SDLoc dl(Op);
5819
5820  EVT PTy = getPointerTy(DAG.getDataLayout());
5821  JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
5822  SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
5823  Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI);
5824  Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy));
5825  SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Table, Index);
5826  if (Subtarget->isThumb2() || (Subtarget->hasV8MBaselineOps() && Subtarget->isThumb())) {
5827    // Thumb2 and ARMv8-M use a two-level jump. That is, it jumps into the jump table
5828    // which does another jump to the destination. This also makes it easier
5829    // to translate it to TBB / TBH later (Thumb2 only).
5830    // FIXME: This might not work if the function is extremely large.
5831    return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
5832                       Addr, Op.getOperand(2), JTI);
5833  }
5834  if (isPositionIndependent() || Subtarget->isROPI()) {
5835    Addr =
5836        DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
5837                    MachinePointerInfo::getJumpTable(DAG.getMachineFunction()));
5838    Chain = Addr.getValue(1);
5839    Addr = DAG.getNode(ISD::ADD, dl, PTy, Table, Addr);
5840    return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
5841  } else {
5842    Addr =
5843        DAG.getLoad(PTy, dl, Chain, Addr,
5844                    MachinePointerInfo::getJumpTable(DAG.getMachineFunction()));
5845    Chain = Addr.getValue(1);
5846    return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
5847  }
5848}
5849
5850static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
5851  EVT VT = Op.getValueType();
5852  SDLoc dl(Op);
5853
5854  if (Op.getValueType().getVectorElementType() == MVT::i32) {
5855    if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
5856      return Op;
5857    return DAG.UnrollVectorOp(Op.getNode());
5858  }
5859
5860  const bool HasFullFP16 = DAG.getSubtarget<ARMSubtarget>().hasFullFP16();
5861
5862  EVT NewTy;
5863  const EVT OpTy = Op.getOperand(0).getValueType();
5864  if (OpTy == MVT::v4f32)
5865    NewTy = MVT::v4i32;
5866  else if (OpTy == MVT::v4f16 && HasFullFP16)
5867    NewTy = MVT::v4i16;
5868  else if (OpTy == MVT::v8f16 && HasFullFP16)
5869    NewTy = MVT::v8i16;
5870  else
5871    llvm_unreachable("Invalid type for custom lowering!");
5872
5873  if (VT != MVT::v4i16 && VT != MVT::v8i16)
5874    return DAG.UnrollVectorOp(Op.getNode());
5875
5876  Op = DAG.getNode(Op.getOpcode(), dl, NewTy, Op.getOperand(0));
5877  return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
5878}
5879
5880SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
5881  EVT VT = Op.getValueType();
5882  if (VT.isVector())
5883    return LowerVectorFP_TO_INT(Op, DAG);
5884
5885  bool IsStrict = Op->isStrictFPOpcode();
5886  SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0);
5887
5888  if (isUnsupportedFloatingType(SrcVal.getValueType())) {
5889    RTLIB::Libcall LC;
5890    if (Op.getOpcode() == ISD::FP_TO_SINT ||
5891        Op.getOpcode() == ISD::STRICT_FP_TO_SINT)
5892      LC = RTLIB::getFPTOSINT(SrcVal.getValueType(),
5893                              Op.getValueType());
5894    else
5895      LC = RTLIB::getFPTOUINT(SrcVal.getValueType(),
5896                              Op.getValueType());
5897    SDLoc Loc(Op);
5898    MakeLibCallOptions CallOptions;
5899    SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
5900    SDValue Result;
5901    std::tie(Result, Chain) = makeLibCall(DAG, LC, Op.getValueType(), SrcVal,
5902                                          CallOptions, Loc, Chain);
5903    return IsStrict ? DAG.getMergeValues({Result, Chain}, Loc) : Result;
5904  }
5905
5906  // FIXME: Remove this when we have strict fp instruction selection patterns
5907  if (IsStrict) {
5908    SDLoc Loc(Op);
5909    SDValue Result =
5910        DAG.getNode(Op.getOpcode() == ISD::STRICT_FP_TO_SINT ? ISD::FP_TO_SINT
5911                                                             : ISD::FP_TO_UINT,
5912                    Loc, Op.getValueType(), SrcVal);
5913    return DAG.getMergeValues({Result, Op.getOperand(0)}, Loc);
5914  }
5915
5916  return Op;
5917}
5918
5919static SDValue LowerFP_TO_INT_SAT(SDValue Op, SelectionDAG &DAG,
5920                                  const ARMSubtarget *Subtarget) {
5921  EVT VT = Op.getValueType();
5922  EVT ToVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
5923  EVT FromVT = Op.getOperand(0).getValueType();
5924
5925  if (VT == MVT::i32 && ToVT == MVT::i32 && FromVT == MVT::f32)
5926    return Op;
5927  if (VT == MVT::i32 && ToVT == MVT::i32 && FromVT == MVT::f64 &&
5928      Subtarget->hasFP64())
5929    return Op;
5930  if (VT == MVT::i32 && ToVT == MVT::i32 && FromVT == MVT::f16 &&
5931      Subtarget->hasFullFP16())
5932    return Op;
5933  if (VT == MVT::v4i32 && ToVT == MVT::i32 && FromVT == MVT::v4f32 &&
5934      Subtarget->hasMVEFloatOps())
5935    return Op;
5936  if (VT == MVT::v8i16 && ToVT == MVT::i16 && FromVT == MVT::v8f16 &&
5937      Subtarget->hasMVEFloatOps())
5938    return Op;
5939
5940  if (FromVT != MVT::v4f32 && FromVT != MVT::v8f16)
5941    return SDValue();
5942
5943  SDLoc DL(Op);
5944  bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT_SAT;
5945  unsigned BW = ToVT.getScalarSizeInBits() - IsSigned;
5946  SDValue CVT = DAG.getNode(Op.getOpcode(), DL, VT, Op.getOperand(0),
5947                            DAG.getValueType(VT.getScalarType()));
5948  SDValue Max = DAG.getNode(IsSigned ? ISD::SMIN : ISD::UMIN, DL, VT, CVT,
5949                            DAG.getConstant((1 << BW) - 1, DL, VT));
5950  if (IsSigned)
5951    Max = DAG.getNode(ISD::SMAX, DL, VT, Max,
5952                      DAG.getConstant(-(1 << BW), DL, VT));
5953  return Max;
5954}
5955
5956static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
5957  EVT VT = Op.getValueType();
5958  SDLoc dl(Op);
5959
5960  if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
5961    if (VT.getVectorElementType() == MVT::f32)
5962      return Op;
5963    return DAG.UnrollVectorOp(Op.getNode());
5964  }
5965
5966  assert((Op.getOperand(0).getValueType() == MVT::v4i16 ||
5967          Op.getOperand(0).getValueType() == MVT::v8i16) &&
5968         "Invalid type for custom lowering!");
5969
5970  const bool HasFullFP16 = DAG.getSubtarget<ARMSubtarget>().hasFullFP16();
5971
5972  EVT DestVecType;
5973  if (VT == MVT::v4f32)
5974    DestVecType = MVT::v4i32;
5975  else if (VT == MVT::v4f16 && HasFullFP16)
5976    DestVecType = MVT::v4i16;
5977  else if (VT == MVT::v8f16 && HasFullFP16)
5978    DestVecType = MVT::v8i16;
5979  else
5980    return DAG.UnrollVectorOp(Op.getNode());
5981
5982  unsigned CastOpc;
5983  unsigned Opc;
5984  switch (Op.getOpcode()) {
5985  default: llvm_unreachable("Invalid opcode!");
5986  case ISD::SINT_TO_FP:
5987    CastOpc = ISD::SIGN_EXTEND;
5988    Opc = ISD::SINT_TO_FP;
5989    break;
5990  case ISD::UINT_TO_FP:
5991    CastOpc = ISD::ZERO_EXTEND;
5992    Opc = ISD::UINT_TO_FP;
5993    break;
5994  }
5995
5996  Op = DAG.getNode(CastOpc, dl, DestVecType, Op.getOperand(0));
5997  return DAG.getNode(Opc, dl, VT, Op);
5998}
5999
6000SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
6001  EVT VT = Op.getValueType();
6002  if (VT.isVector())
6003    return LowerVectorINT_TO_FP(Op, DAG);
6004  if (isUnsupportedFloatingType(VT)) {
6005    RTLIB::Libcall LC;
6006    if (Op.getOpcode() == ISD::SINT_TO_FP)
6007      LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(),
6008                              Op.getValueType());
6009    else
6010      LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(),
6011                              Op.getValueType());
6012    MakeLibCallOptions CallOptions;
6013    return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0),
6014                       CallOptions, SDLoc(Op)).first;
6015  }
6016
6017  return Op;
6018}
6019
6020SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
6021  // Implement fcopysign with a fabs and a conditional fneg.
6022  SDValue Tmp0 = Op.getOperand(0);
6023  SDValue Tmp1 = Op.getOperand(1);
6024  SDLoc dl(Op);
6025  EVT VT = Op.getValueType();
6026  EVT SrcVT = Tmp1.getValueType();
6027  bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
6028    Tmp0.getOpcode() == ARMISD::VMOVDRR;
6029  bool UseNEON = !InGPR && Subtarget->hasNEON();
6030
6031  if (UseNEON) {
6032    // Use VBSL to copy the sign bit.
6033    unsigned EncodedVal = ARM_AM::createVMOVModImm(0x6, 0x80);
6034    SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
6035                               DAG.getTargetConstant(EncodedVal, dl, MVT::i32));
6036    EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
6037    if (VT == MVT::f64)
6038      Mask = DAG.getNode(ARMISD::VSHLIMM, dl, OpVT,
6039                         DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
6040                         DAG.getConstant(32, dl, MVT::i32));
6041    else /*if (VT == MVT::f32)*/
6042      Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
6043    if (SrcVT == MVT::f32) {
6044      Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
6045      if (VT == MVT::f64)
6046        Tmp1 = DAG.getNode(ARMISD::VSHLIMM, dl, OpVT,
6047                           DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
6048                           DAG.getConstant(32, dl, MVT::i32));
6049    } else if (VT == MVT::f32)
6050      Tmp1 = DAG.getNode(ARMISD::VSHRuIMM, dl, MVT::v1i64,
6051                         DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
6052                         DAG.getConstant(32, dl, MVT::i32));
6053    Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
6054    Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
6055
6056    SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createVMOVModImm(0xe, 0xff),
6057                                            dl, MVT::i32);
6058    AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
6059    SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
6060                                  DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
6061
6062    SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
6063                              DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
6064                              DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
6065    if (VT == MVT::f32) {
6066      Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
6067      Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
6068                        DAG.getConstant(0, dl, MVT::i32));
6069    } else {
6070      Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
6071    }
6072
6073    return Res;
6074  }
6075
6076  // Bitcast operand 1 to i32.
6077  if (SrcVT == MVT::f64)
6078    Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
6079                       Tmp1).getValue(1);
6080  Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
6081
6082  // Or in the signbit with integer operations.
6083  SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32);
6084  SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32);
6085  Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
6086  if (VT == MVT::f32) {
6087    Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
6088                       DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
6089    return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
6090                       DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
6091  }
6092
6093  // f64: Or the high part with signbit and then combine two parts.
6094  Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
6095                     Tmp0);
6096  SDValue Lo = Tmp0.getValue(0);
6097  SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
6098  Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
6099  return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
6100}
6101
6102SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
6103  MachineFunction &MF = DAG.getMachineFunction();
6104  MachineFrameInfo &MFI = MF.getFrameInfo();
6105  MFI.setReturnAddressIsTaken(true);
6106
6107  if (verifyReturnAddressArgumentIsConstant(Op, DAG))
6108    return SDValue();
6109
6110  EVT VT = Op.getValueType();
6111  SDLoc dl(Op);
6112  unsigned Depth = Op.getConstantOperandVal(0);
6113  if (Depth) {
6114    SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
6115    SDValue Offset = DAG.getConstant(4, dl, MVT::i32);
6116    return DAG.getLoad(VT, dl, DAG.getEntryNode(),
6117                       DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
6118                       MachinePointerInfo());
6119  }
6120
6121  // Return LR, which contains the return address. Mark it an implicit live-in.
6122  Register Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
6123  return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
6124}
6125
6126SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
6127  const ARMBaseRegisterInfo &ARI =
6128    *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
6129  MachineFunction &MF = DAG.getMachineFunction();
6130  MachineFrameInfo &MFI = MF.getFrameInfo();
6131  MFI.setFrameAddressIsTaken(true);
6132
6133  EVT VT = Op.getValueType();
6134  SDLoc dl(Op);  // FIXME probably not meaningful
6135  unsigned Depth = Op.getConstantOperandVal(0);
6136  Register FrameReg = ARI.getFrameRegister(MF);
6137  SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
6138  while (Depth--)
6139    FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
6140                            MachinePointerInfo());
6141  return FrameAddr;
6142}
6143
6144// FIXME? Maybe this could be a TableGen attribute on some registers and
6145// this table could be generated automatically from RegInfo.
6146Register ARMTargetLowering::getRegisterByName(const char* RegName, LLT VT,
6147                                              const MachineFunction &MF) const {
6148  Register Reg = StringSwitch<unsigned>(RegName)
6149                       .Case("sp", ARM::SP)
6150                       .Default(0);
6151  if (Reg)
6152    return Reg;
6153  report_fatal_error(Twine("Invalid register name \""
6154                              + StringRef(RegName)  + "\"."));
6155}
6156
6157// Result is 64 bit value so split into two 32 bit values and return as a
6158// pair of values.
6159static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results,
6160                                SelectionDAG &DAG) {
6161  SDLoc DL(N);
6162
6163  // This function is only supposed to be called for i64 type destination.
6164  assert(N->getValueType(0) == MVT::i64
6165          && "ExpandREAD_REGISTER called for non-i64 type result.");
6166
6167  SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL,
6168                             DAG.getVTList(MVT::i32, MVT::i32, MVT::Other),
6169                             N->getOperand(0),
6170                             N->getOperand(1));
6171
6172  Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0),
6173                    Read.getValue(1)));
6174  Results.push_back(Read.getOperand(0));
6175}
6176
6177/// \p BC is a bitcast that is about to be turned into a VMOVDRR.
6178/// When \p DstVT, the destination type of \p BC, is on the vector
6179/// register bank and the source of bitcast, \p Op, operates on the same bank,
6180/// it might be possible to combine them, such that everything stays on the
6181/// vector register bank.
6182/// \p return The node that would replace \p BT, if the combine
6183/// is possible.
6184static SDValue CombineVMOVDRRCandidateWithVecOp(const SDNode *BC,
6185                                                SelectionDAG &DAG) {
6186  SDValue Op = BC->getOperand(0);
6187  EVT DstVT = BC->getValueType(0);
6188
6189  // The only vector instruction that can produce a scalar (remember,
6190  // since the bitcast was about to be turned into VMOVDRR, the source
6191  // type is i64) from a vector is EXTRACT_VECTOR_ELT.
6192  // Moreover, we can do this combine only if there is one use.
6193  // Finally, if the destination type is not a vector, there is not
6194  // much point on forcing everything on the vector bank.
6195  if (!DstVT.isVector() || Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6196      !Op.hasOneUse())
6197    return SDValue();
6198
6199  // If the index is not constant, we will introduce an additional
6200  // multiply that will stick.
6201  // Give up in that case.
6202  ConstantSDNode *Index = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6203  if (!Index)
6204    return SDValue();
6205  unsigned DstNumElt = DstVT.getVectorNumElements();
6206
6207  // Compute the new index.
6208  const APInt &APIntIndex = Index->getAPIntValue();
6209  APInt NewIndex(APIntIndex.getBitWidth(), DstNumElt);
6210  NewIndex *= APIntIndex;
6211  // Check if the new constant index fits into i32.
6212  if (NewIndex.getBitWidth() > 32)
6213    return SDValue();
6214
6215  // vMTy bitcast(i64 extractelt vNi64 src, i32 index) ->
6216  // vMTy extractsubvector vNxMTy (bitcast vNi64 src), i32 index*M)
6217  SDLoc dl(Op);
6218  SDValue ExtractSrc = Op.getOperand(0);
6219  EVT VecVT = EVT::getVectorVT(
6220      *DAG.getContext(), DstVT.getScalarType(),
6221      ExtractSrc.getValueType().getVectorNumElements() * DstNumElt);
6222  SDValue BitCast = DAG.getNode(ISD::BITCAST, dl, VecVT, ExtractSrc);
6223  return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DstVT, BitCast,
6224                     DAG.getConstant(NewIndex.getZExtValue(), dl, MVT::i32));
6225}
6226
6227/// ExpandBITCAST - If the target supports VFP, this function is called to
6228/// expand a bit convert where either the source or destination type is i64 to
6229/// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
6230/// operand type is illegal (e.g., v2f32 for a target that doesn't support
6231/// vectors), since the legalizer won't know what to do with that.
6232SDValue ARMTargetLowering::ExpandBITCAST(SDNode *N, SelectionDAG &DAG,
6233                                         const ARMSubtarget *Subtarget) const {
6234  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6235  SDLoc dl(N);
6236  SDValue Op = N->getOperand(0);
6237
6238  // This function is only supposed to be called for i16 and i64 types, either
6239  // as the source or destination of the bit convert.
6240  EVT SrcVT = Op.getValueType();
6241  EVT DstVT = N->getValueType(0);
6242
6243  if ((SrcVT == MVT::i16 || SrcVT == MVT::i32) &&
6244      (DstVT == MVT::f16 || DstVT == MVT::bf16))
6245    return MoveToHPR(SDLoc(N), DAG, MVT::i32, DstVT.getSimpleVT(),
6246                     DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), MVT::i32, Op));
6247
6248  if ((DstVT == MVT::i16 || DstVT == MVT::i32) &&
6249      (SrcVT == MVT::f16 || SrcVT == MVT::bf16))
6250    return DAG.getNode(
6251        ISD::TRUNCATE, SDLoc(N), DstVT,
6252        MoveFromHPR(SDLoc(N), DAG, MVT::i32, SrcVT.getSimpleVT(), Op));
6253
6254  if (!(SrcVT == MVT::i64 || DstVT == MVT::i64))
6255    return SDValue();
6256
6257  // Turn i64->f64 into VMOVDRR.
6258  if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
6259    // Do not force values to GPRs (this is what VMOVDRR does for the inputs)
6260    // if we can combine the bitcast with its source.
6261    if (SDValue Val = CombineVMOVDRRCandidateWithVecOp(N, DAG))
6262      return Val;
6263    SDValue Lo, Hi;
6264    std::tie(Lo, Hi) = DAG.SplitScalar(Op, dl, MVT::i32, MVT::i32);
6265    return DAG.getNode(ISD::BITCAST, dl, DstVT,
6266                       DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
6267  }
6268
6269  // Turn f64->i64 into VMOVRRD.
6270  if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
6271    SDValue Cvt;
6272    if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() &&
6273        SrcVT.getVectorNumElements() > 1)
6274      Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
6275                        DAG.getVTList(MVT::i32, MVT::i32),
6276                        DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
6277    else
6278      Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
6279                        DAG.getVTList(MVT::i32, MVT::i32), Op);
6280    // Merge the pieces into a single i64 value.
6281    return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
6282  }
6283
6284  return SDValue();
6285}
6286
6287/// getZeroVector - Returns a vector of specified type with all zero elements.
6288/// Zero vectors are used to represent vector negation and in those cases
6289/// will be implemented with the NEON VNEG instruction.  However, VNEG does
6290/// not support i64 elements, so sometimes the zero vectors will need to be
6291/// explicitly constructed.  Regardless, use a canonical VMOV to create the
6292/// zero vector.
6293static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, const SDLoc &dl) {
6294  assert(VT.isVector() && "Expected a vector type");
6295  // The canonical modified immediate encoding of a zero vector is....0!
6296  SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32);
6297  EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
6298  SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
6299  return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
6300}
6301
6302/// LowerShiftRightParts - Lower SRA_PARTS, which returns two
6303/// i32 values and take a 2 x i32 value to shift plus a shift amount.
6304SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
6305                                                SelectionDAG &DAG) const {
6306  assert(Op.getNumOperands() == 3 && "Not a double-shift!");
6307  EVT VT = Op.getValueType();
6308  unsigned VTBits = VT.getSizeInBits();
6309  SDLoc dl(Op);
6310  SDValue ShOpLo = Op.getOperand(0);
6311  SDValue ShOpHi = Op.getOperand(1);
6312  SDValue ShAmt  = Op.getOperand(2);
6313  SDValue ARMcc;
6314  SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
6315  unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
6316
6317  assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
6318
6319  SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
6320                                 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
6321  SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
6322  SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
6323                                   DAG.getConstant(VTBits, dl, MVT::i32));
6324  SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
6325  SDValue LoSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
6326  SDValue LoBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
6327  SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
6328                            ISD::SETGE, ARMcc, DAG, dl);
6329  SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift, LoBigShift,
6330                           ARMcc, CCR, CmpLo);
6331
6332  SDValue HiSmallShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
6333  SDValue HiBigShift = Opc == ISD::SRA
6334                           ? DAG.getNode(Opc, dl, VT, ShOpHi,
6335                                         DAG.getConstant(VTBits - 1, dl, VT))
6336                           : DAG.getConstant(0, dl, VT);
6337  SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
6338                            ISD::SETGE, ARMcc, DAG, dl);
6339  SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift,
6340                           ARMcc, CCR, CmpHi);
6341
6342  SDValue Ops[2] = { Lo, Hi };
6343  return DAG.getMergeValues(Ops, dl);
6344}
6345
6346/// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
6347/// i32 values and take a 2 x i32 value to shift plus a shift amount.
6348SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
6349                                               SelectionDAG &DAG) const {
6350  assert(Op.getNumOperands() == 3 && "Not a double-shift!");
6351  EVT VT = Op.getValueType();
6352  unsigned VTBits = VT.getSizeInBits();
6353  SDLoc dl(Op);
6354  SDValue ShOpLo = Op.getOperand(0);
6355  SDValue ShOpHi = Op.getOperand(1);
6356  SDValue ShAmt  = Op.getOperand(2);
6357  SDValue ARMcc;
6358  SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
6359
6360  assert(Op.getOpcode() == ISD::SHL_PARTS);
6361  SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
6362                                 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
6363  SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
6364  SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
6365  SDValue HiSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
6366
6367  SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
6368                                   DAG.getConstant(VTBits, dl, MVT::i32));
6369  SDValue HiBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
6370  SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
6371                            ISD::SETGE, ARMcc, DAG, dl);
6372  SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift,
6373                           ARMcc, CCR, CmpHi);
6374
6375  SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
6376                          ISD::SETGE, ARMcc, DAG, dl);
6377  SDValue LoSmallShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
6378  SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift,
6379                           DAG.getConstant(0, dl, VT), ARMcc, CCR, CmpLo);
6380
6381  SDValue Ops[2] = { Lo, Hi };
6382  return DAG.getMergeValues(Ops, dl);
6383}
6384
6385SDValue ARMTargetLowering::LowerGET_ROUNDING(SDValue Op,
6386                                             SelectionDAG &DAG) const {
6387  // The rounding mode is in bits 23:22 of the FPSCR.
6388  // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
6389  // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
6390  // so that the shift + and get folded into a bitfield extract.
6391  SDLoc dl(Op);
6392  SDValue Chain = Op.getOperand(0);
6393  SDValue Ops[] = {Chain,
6394                   DAG.getConstant(Intrinsic::arm_get_fpscr, dl, MVT::i32)};
6395
6396  SDValue FPSCR =
6397      DAG.getNode(ISD::INTRINSIC_W_CHAIN, dl, {MVT::i32, MVT::Other}, Ops);
6398  Chain = FPSCR.getValue(1);
6399  SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
6400                                  DAG.getConstant(1U << 22, dl, MVT::i32));
6401  SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
6402                              DAG.getConstant(22, dl, MVT::i32));
6403  SDValue And = DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
6404                            DAG.getConstant(3, dl, MVT::i32));
6405  return DAG.getMergeValues({And, Chain}, dl);
6406}
6407
6408SDValue ARMTargetLowering::LowerSET_ROUNDING(SDValue Op,
6409                                             SelectionDAG &DAG) const {
6410  SDLoc DL(Op);
6411  SDValue Chain = Op->getOperand(0);
6412  SDValue RMValue = Op->getOperand(1);
6413
6414  // The rounding mode is in bits 23:22 of the FPSCR.
6415  // The llvm.set.rounding argument value to ARM rounding mode value mapping
6416  // is 0->3, 1->0, 2->1, 3->2. The formula we use to implement this is
6417  // ((arg - 1) & 3) << 22).
6418  //
6419  // It is expected that the argument of llvm.set.rounding is within the
6420  // segment [0, 3], so NearestTiesToAway (4) is not handled here. It is
6421  // responsibility of the code generated llvm.set.rounding to ensure this
6422  // condition.
6423
6424  // Calculate new value of FPSCR[23:22].
6425  RMValue = DAG.getNode(ISD::SUB, DL, MVT::i32, RMValue,
6426                        DAG.getConstant(1, DL, MVT::i32));
6427  RMValue = DAG.getNode(ISD::AND, DL, MVT::i32, RMValue,
6428                        DAG.getConstant(0x3, DL, MVT::i32));
6429  RMValue = DAG.getNode(ISD::SHL, DL, MVT::i32, RMValue,
6430                        DAG.getConstant(ARM::RoundingBitsPos, DL, MVT::i32));
6431
6432  // Get current value of FPSCR.
6433  SDValue Ops[] = {Chain,
6434                   DAG.getConstant(Intrinsic::arm_get_fpscr, DL, MVT::i32)};
6435  SDValue FPSCR =
6436      DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL, {MVT::i32, MVT::Other}, Ops);
6437  Chain = FPSCR.getValue(1);
6438  FPSCR = FPSCR.getValue(0);
6439
6440  // Put new rounding mode into FPSCR[23:22].
6441  const unsigned RMMask = ~(ARM::Rounding::rmMask << ARM::RoundingBitsPos);
6442  FPSCR = DAG.getNode(ISD::AND, DL, MVT::i32, FPSCR,
6443                      DAG.getConstant(RMMask, DL, MVT::i32));
6444  FPSCR = DAG.getNode(ISD::OR, DL, MVT::i32, FPSCR, RMValue);
6445  SDValue Ops2[] = {
6446      Chain, DAG.getConstant(Intrinsic::arm_set_fpscr, DL, MVT::i32), FPSCR};
6447  return DAG.getNode(ISD::INTRINSIC_VOID, DL, MVT::Other, Ops2);
6448}
6449
6450SDValue ARMTargetLowering::LowerSET_FPMODE(SDValue Op,
6451                                           SelectionDAG &DAG) const {
6452  SDLoc DL(Op);
6453  SDValue Chain = Op->getOperand(0);
6454  SDValue Mode = Op->getOperand(1);
6455
6456  // Generate nodes to build:
6457  // FPSCR = (FPSCR & FPStatusBits) | (Mode & ~FPStatusBits)
6458  SDValue Ops[] = {Chain,
6459                   DAG.getConstant(Intrinsic::arm_get_fpscr, DL, MVT::i32)};
6460  SDValue FPSCR =
6461      DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL, {MVT::i32, MVT::Other}, Ops);
6462  Chain = FPSCR.getValue(1);
6463  FPSCR = FPSCR.getValue(0);
6464
6465  SDValue FPSCRMasked =
6466      DAG.getNode(ISD::AND, DL, MVT::i32, FPSCR,
6467                  DAG.getConstant(ARM::FPStatusBits, DL, MVT::i32));
6468  SDValue InputMasked =
6469      DAG.getNode(ISD::AND, DL, MVT::i32, Mode,
6470                  DAG.getConstant(~ARM::FPStatusBits, DL, MVT::i32));
6471  FPSCR = DAG.getNode(ISD::OR, DL, MVT::i32, FPSCRMasked, InputMasked);
6472
6473  SDValue Ops2[] = {
6474      Chain, DAG.getConstant(Intrinsic::arm_set_fpscr, DL, MVT::i32), FPSCR};
6475  return DAG.getNode(ISD::INTRINSIC_VOID, DL, MVT::Other, Ops2);
6476}
6477
6478SDValue ARMTargetLowering::LowerRESET_FPMODE(SDValue Op,
6479                                             SelectionDAG &DAG) const {
6480  SDLoc DL(Op);
6481  SDValue Chain = Op->getOperand(0);
6482
6483  // To get the default FP mode all control bits are cleared:
6484  // FPSCR = FPSCR & (FPStatusBits | FPReservedBits)
6485  SDValue Ops[] = {Chain,
6486                   DAG.getConstant(Intrinsic::arm_get_fpscr, DL, MVT::i32)};
6487  SDValue FPSCR =
6488      DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL, {MVT::i32, MVT::Other}, Ops);
6489  Chain = FPSCR.getValue(1);
6490  FPSCR = FPSCR.getValue(0);
6491
6492  SDValue FPSCRMasked = DAG.getNode(
6493      ISD::AND, DL, MVT::i32, FPSCR,
6494      DAG.getConstant(ARM::FPStatusBits | ARM::FPReservedBits, DL, MVT::i32));
6495  SDValue Ops2[] = {Chain,
6496                    DAG.getConstant(Intrinsic::arm_set_fpscr, DL, MVT::i32),
6497                    FPSCRMasked};
6498  return DAG.getNode(ISD::INTRINSIC_VOID, DL, MVT::Other, Ops2);
6499}
6500
6501static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
6502                         const ARMSubtarget *ST) {
6503  SDLoc dl(N);
6504  EVT VT = N->getValueType(0);
6505  if (VT.isVector() && ST->hasNEON()) {
6506
6507    // Compute the least significant set bit: LSB = X & -X
6508    SDValue X = N->getOperand(0);
6509    SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X);
6510    SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX);
6511
6512    EVT ElemTy = VT.getVectorElementType();
6513
6514    if (ElemTy == MVT::i8) {
6515      // Compute with: cttz(x) = ctpop(lsb - 1)
6516      SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
6517                                DAG.getTargetConstant(1, dl, ElemTy));
6518      SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
6519      return DAG.getNode(ISD::CTPOP, dl, VT, Bits);
6520    }
6521
6522    if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) &&
6523        (N->getOpcode() == ISD::CTTZ_ZERO_UNDEF)) {
6524      // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0
6525      unsigned NumBits = ElemTy.getSizeInBits();
6526      SDValue WidthMinus1 =
6527          DAG.getNode(ARMISD::VMOVIMM, dl, VT,
6528                      DAG.getTargetConstant(NumBits - 1, dl, ElemTy));
6529      SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB);
6530      return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ);
6531    }
6532
6533    // Compute with: cttz(x) = ctpop(lsb - 1)
6534
6535    // Compute LSB - 1.
6536    SDValue Bits;
6537    if (ElemTy == MVT::i64) {
6538      // Load constant 0xffff'ffff'ffff'ffff to register.
6539      SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
6540                               DAG.getTargetConstant(0x1eff, dl, MVT::i32));
6541      Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF);
6542    } else {
6543      SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
6544                                DAG.getTargetConstant(1, dl, ElemTy));
6545      Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
6546    }
6547    return DAG.getNode(ISD::CTPOP, dl, VT, Bits);
6548  }
6549
6550  if (!ST->hasV6T2Ops())
6551    return SDValue();
6552
6553  SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, VT, N->getOperand(0));
6554  return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
6555}
6556
6557static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
6558                          const ARMSubtarget *ST) {
6559  EVT VT = N->getValueType(0);
6560  SDLoc DL(N);
6561
6562  assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
6563  assert((VT == MVT::v1i64 || VT == MVT::v2i64 || VT == MVT::v2i32 ||
6564          VT == MVT::v4i32 || VT == MVT::v4i16 || VT == MVT::v8i16) &&
6565         "Unexpected type for custom ctpop lowering");
6566
6567  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6568  EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
6569  SDValue Res = DAG.getBitcast(VT8Bit, N->getOperand(0));
6570  Res = DAG.getNode(ISD::CTPOP, DL, VT8Bit, Res);
6571
6572  // Widen v8i8/v16i8 CTPOP result to VT by repeatedly widening pairwise adds.
6573  unsigned EltSize = 8;
6574  unsigned NumElts = VT.is64BitVector() ? 8 : 16;
6575  while (EltSize != VT.getScalarSizeInBits()) {
6576    SmallVector<SDValue, 8> Ops;
6577    Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddlu, DL,
6578                                  TLI.getPointerTy(DAG.getDataLayout())));
6579    Ops.push_back(Res);
6580
6581    EltSize *= 2;
6582    NumElts /= 2;
6583    MVT WidenVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize), NumElts);
6584    Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, WidenVT, Ops);
6585  }
6586
6587  return Res;
6588}
6589
6590/// Getvshiftimm - Check if this is a valid build_vector for the immediate
6591/// operand of a vector shift operation, where all the elements of the
6592/// build_vector must have the same constant integer value.
6593static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
6594  // Ignore bit_converts.
6595  while (Op.getOpcode() == ISD::BITCAST)
6596    Op = Op.getOperand(0);
6597  BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
6598  APInt SplatBits, SplatUndef;
6599  unsigned SplatBitSize;
6600  bool HasAnyUndefs;
6601  if (!BVN ||
6602      !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs,
6603                            ElementBits) ||
6604      SplatBitSize > ElementBits)
6605    return false;
6606  Cnt = SplatBits.getSExtValue();
6607  return true;
6608}
6609
6610/// isVShiftLImm - Check if this is a valid build_vector for the immediate
6611/// operand of a vector shift left operation.  That value must be in the range:
6612///   0 <= Value < ElementBits for a left shift; or
6613///   0 <= Value <= ElementBits for a long left shift.
6614static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
6615  assert(VT.isVector() && "vector shift count is not a vector type");
6616  int64_t ElementBits = VT.getScalarSizeInBits();
6617  if (!getVShiftImm(Op, ElementBits, Cnt))
6618    return false;
6619  return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
6620}
6621
6622/// isVShiftRImm - Check if this is a valid build_vector for the immediate
6623/// operand of a vector shift right operation.  For a shift opcode, the value
6624/// is positive, but for an intrinsic the value count must be negative. The
6625/// absolute value must be in the range:
6626///   1 <= |Value| <= ElementBits for a right shift; or
6627///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
6628static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
6629                         int64_t &Cnt) {
6630  assert(VT.isVector() && "vector shift count is not a vector type");
6631  int64_t ElementBits = VT.getScalarSizeInBits();
6632  if (!getVShiftImm(Op, ElementBits, Cnt))
6633    return false;
6634  if (!isIntrinsic)
6635    return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
6636  if (Cnt >= -(isNarrow ? ElementBits / 2 : ElementBits) && Cnt <= -1) {
6637    Cnt = -Cnt;
6638    return true;
6639  }
6640  return false;
6641}
6642
6643static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
6644                          const ARMSubtarget *ST) {
6645  EVT VT = N->getValueType(0);
6646  SDLoc dl(N);
6647  int64_t Cnt;
6648
6649  if (!VT.isVector())
6650    return SDValue();
6651
6652  // We essentially have two forms here. Shift by an immediate and shift by a
6653  // vector register (there are also shift by a gpr, but that is just handled
6654  // with a tablegen pattern). We cannot easily match shift by an immediate in
6655  // tablegen so we do that here and generate a VSHLIMM/VSHRsIMM/VSHRuIMM.
6656  // For shifting by a vector, we don't have VSHR, only VSHL (which can be
6657  // signed or unsigned, and a negative shift indicates a shift right).
6658  if (N->getOpcode() == ISD::SHL) {
6659    if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
6660      return DAG.getNode(ARMISD::VSHLIMM, dl, VT, N->getOperand(0),
6661                         DAG.getConstant(Cnt, dl, MVT::i32));
6662    return DAG.getNode(ARMISD::VSHLu, dl, VT, N->getOperand(0),
6663                       N->getOperand(1));
6664  }
6665
6666  assert((N->getOpcode() == ISD::SRA || N->getOpcode() == ISD::SRL) &&
6667         "unexpected vector shift opcode");
6668
6669  if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
6670    unsigned VShiftOpc =
6671        (N->getOpcode() == ISD::SRA ? ARMISD::VSHRsIMM : ARMISD::VSHRuIMM);
6672    return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0),
6673                       DAG.getConstant(Cnt, dl, MVT::i32));
6674  }
6675
6676  // Other right shifts we don't have operations for (we use a shift left by a
6677  // negative number).
6678  EVT ShiftVT = N->getOperand(1).getValueType();
6679  SDValue NegatedCount = DAG.getNode(
6680      ISD::SUB, dl, ShiftVT, getZeroVector(ShiftVT, DAG, dl), N->getOperand(1));
6681  unsigned VShiftOpc =
6682      (N->getOpcode() == ISD::SRA ? ARMISD::VSHLs : ARMISD::VSHLu);
6683  return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0), NegatedCount);
6684}
6685
6686static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
6687                                const ARMSubtarget *ST) {
6688  EVT VT = N->getValueType(0);
6689  SDLoc dl(N);
6690
6691  // We can get here for a node like i32 = ISD::SHL i32, i64
6692  if (VT != MVT::i64)
6693    return SDValue();
6694
6695  assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA ||
6696          N->getOpcode() == ISD::SHL) &&
6697         "Unknown shift to lower!");
6698
6699  unsigned ShOpc = N->getOpcode();
6700  if (ST->hasMVEIntegerOps()) {
6701    SDValue ShAmt = N->getOperand(1);
6702    unsigned ShPartsOpc = ARMISD::LSLL;
6703    ConstantSDNode *Con = dyn_cast<ConstantSDNode>(ShAmt);
6704
6705    // If the shift amount is greater than 32 or has a greater bitwidth than 64
6706    // then do the default optimisation
6707    if (ShAmt->getValueType(0).getSizeInBits() > 64 ||
6708        (Con && (Con->getZExtValue() == 0 || Con->getZExtValue() >= 32)))
6709      return SDValue();
6710
6711    // Extract the lower 32 bits of the shift amount if it's not an i32
6712    if (ShAmt->getValueType(0) != MVT::i32)
6713      ShAmt = DAG.getZExtOrTrunc(ShAmt, dl, MVT::i32);
6714
6715    if (ShOpc == ISD::SRL) {
6716      if (!Con)
6717        // There is no t2LSRLr instruction so negate and perform an lsll if the
6718        // shift amount is in a register, emulating a right shift.
6719        ShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
6720                            DAG.getConstant(0, dl, MVT::i32), ShAmt);
6721      else
6722        // Else generate an lsrl on the immediate shift amount
6723        ShPartsOpc = ARMISD::LSRL;
6724    } else if (ShOpc == ISD::SRA)
6725      ShPartsOpc = ARMISD::ASRL;
6726
6727    // Split Lower/Upper 32 bits of the destination/source
6728    SDValue Lo, Hi;
6729    std::tie(Lo, Hi) =
6730        DAG.SplitScalar(N->getOperand(0), dl, MVT::i32, MVT::i32);
6731    // Generate the shift operation as computed above
6732    Lo = DAG.getNode(ShPartsOpc, dl, DAG.getVTList(MVT::i32, MVT::i32), Lo, Hi,
6733                     ShAmt);
6734    // The upper 32 bits come from the second return value of lsll
6735    Hi = SDValue(Lo.getNode(), 1);
6736    return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
6737  }
6738
6739  // We only lower SRA, SRL of 1 here, all others use generic lowering.
6740  if (!isOneConstant(N->getOperand(1)) || N->getOpcode() == ISD::SHL)
6741    return SDValue();
6742
6743  // If we are in thumb mode, we don't have RRX.
6744  if (ST->isThumb1Only())
6745    return SDValue();
6746
6747  // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
6748  SDValue Lo, Hi;
6749  std::tie(Lo, Hi) = DAG.SplitScalar(N->getOperand(0), dl, MVT::i32, MVT::i32);
6750
6751  // First, build a SRA_GLUE/SRL_GLUE op, which shifts the top part by one and
6752  // captures the result into a carry flag.
6753  unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_GLUE:ARMISD::SRA_GLUE;
6754  Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
6755
6756  // The low part is an ARMISD::RRX operand, which shifts the carry in.
6757  Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
6758
6759  // Merge the pieces into a single i64 value.
6760 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
6761}
6762
6763static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG,
6764                           const ARMSubtarget *ST) {
6765  bool Invert = false;
6766  bool Swap = false;
6767  unsigned Opc = ARMCC::AL;
6768
6769  SDValue Op0 = Op.getOperand(0);
6770  SDValue Op1 = Op.getOperand(1);
6771  SDValue CC = Op.getOperand(2);
6772  EVT VT = Op.getValueType();
6773  ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
6774  SDLoc dl(Op);
6775
6776  EVT CmpVT;
6777  if (ST->hasNEON())
6778    CmpVT = Op0.getValueType().changeVectorElementTypeToInteger();
6779  else {
6780    assert(ST->hasMVEIntegerOps() &&
6781           "No hardware support for integer vector comparison!");
6782
6783    if (Op.getValueType().getVectorElementType() != MVT::i1)
6784      return SDValue();
6785
6786    // Make sure we expand floating point setcc to scalar if we do not have
6787    // mve.fp, so that we can handle them from there.
6788    if (Op0.getValueType().isFloatingPoint() && !ST->hasMVEFloatOps())
6789      return SDValue();
6790
6791    CmpVT = VT;
6792  }
6793
6794  if (Op0.getValueType().getVectorElementType() == MVT::i64 &&
6795      (SetCCOpcode == ISD::SETEQ || SetCCOpcode == ISD::SETNE)) {
6796    // Special-case integer 64-bit equality comparisons. They aren't legal,
6797    // but they can be lowered with a few vector instructions.
6798    unsigned CmpElements = CmpVT.getVectorNumElements() * 2;
6799    EVT SplitVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, CmpElements);
6800    SDValue CastOp0 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op0);
6801    SDValue CastOp1 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op1);
6802    SDValue Cmp = DAG.getNode(ISD::SETCC, dl, SplitVT, CastOp0, CastOp1,
6803                              DAG.getCondCode(ISD::SETEQ));
6804    SDValue Reversed = DAG.getNode(ARMISD::VREV64, dl, SplitVT, Cmp);
6805    SDValue Merged = DAG.getNode(ISD::AND, dl, SplitVT, Cmp, Reversed);
6806    Merged = DAG.getNode(ISD::BITCAST, dl, CmpVT, Merged);
6807    if (SetCCOpcode == ISD::SETNE)
6808      Merged = DAG.getNOT(dl, Merged, CmpVT);
6809    Merged = DAG.getSExtOrTrunc(Merged, dl, VT);
6810    return Merged;
6811  }
6812
6813  if (CmpVT.getVectorElementType() == MVT::i64)
6814    // 64-bit comparisons are not legal in general.
6815    return SDValue();
6816
6817  if (Op1.getValueType().isFloatingPoint()) {
6818    switch (SetCCOpcode) {
6819    default: llvm_unreachable("Illegal FP comparison");
6820    case ISD::SETUNE:
6821    case ISD::SETNE:
6822      if (ST->hasMVEFloatOps()) {
6823        Opc = ARMCC::NE; break;
6824      } else {
6825        Invert = true; [[fallthrough]];
6826      }
6827    case ISD::SETOEQ:
6828    case ISD::SETEQ:  Opc = ARMCC::EQ; break;
6829    case ISD::SETOLT:
6830    case ISD::SETLT: Swap = true; [[fallthrough]];
6831    case ISD::SETOGT:
6832    case ISD::SETGT:  Opc = ARMCC::GT; break;
6833    case ISD::SETOLE:
6834    case ISD::SETLE:  Swap = true; [[fallthrough]];
6835    case ISD::SETOGE:
6836    case ISD::SETGE: Opc = ARMCC::GE; break;
6837    case ISD::SETUGE: Swap = true; [[fallthrough]];
6838    case ISD::SETULE: Invert = true; Opc = ARMCC::GT; break;
6839    case ISD::SETUGT: Swap = true; [[fallthrough]];
6840    case ISD::SETULT: Invert = true; Opc = ARMCC::GE; break;
6841    case ISD::SETUEQ: Invert = true; [[fallthrough]];
6842    case ISD::SETONE: {
6843      // Expand this to (OLT | OGT).
6844      SDValue TmpOp0 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op1, Op0,
6845                                   DAG.getConstant(ARMCC::GT, dl, MVT::i32));
6846      SDValue TmpOp1 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op0, Op1,
6847                                   DAG.getConstant(ARMCC::GT, dl, MVT::i32));
6848      SDValue Result = DAG.getNode(ISD::OR, dl, CmpVT, TmpOp0, TmpOp1);
6849      if (Invert)
6850        Result = DAG.getNOT(dl, Result, VT);
6851      return Result;
6852    }
6853    case ISD::SETUO: Invert = true; [[fallthrough]];
6854    case ISD::SETO: {
6855      // Expand this to (OLT | OGE).
6856      SDValue TmpOp0 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op1, Op0,
6857                                   DAG.getConstant(ARMCC::GT, dl, MVT::i32));
6858      SDValue TmpOp1 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op0, Op1,
6859                                   DAG.getConstant(ARMCC::GE, dl, MVT::i32));
6860      SDValue Result = DAG.getNode(ISD::OR, dl, CmpVT, TmpOp0, TmpOp1);
6861      if (Invert)
6862        Result = DAG.getNOT(dl, Result, VT);
6863      return Result;
6864    }
6865    }
6866  } else {
6867    // Integer comparisons.
6868    switch (SetCCOpcode) {
6869    default: llvm_unreachable("Illegal integer comparison");
6870    case ISD::SETNE:
6871      if (ST->hasMVEIntegerOps()) {
6872        Opc = ARMCC::NE; break;
6873      } else {
6874        Invert = true; [[fallthrough]];
6875      }
6876    case ISD::SETEQ:  Opc = ARMCC::EQ; break;
6877    case ISD::SETLT:  Swap = true; [[fallthrough]];
6878    case ISD::SETGT:  Opc = ARMCC::GT; break;
6879    case ISD::SETLE:  Swap = true; [[fallthrough]];
6880    case ISD::SETGE:  Opc = ARMCC::GE; break;
6881    case ISD::SETULT: Swap = true; [[fallthrough]];
6882    case ISD::SETUGT: Opc = ARMCC::HI; break;
6883    case ISD::SETULE: Swap = true; [[fallthrough]];
6884    case ISD::SETUGE: Opc = ARMCC::HS; break;
6885    }
6886
6887    // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
6888    if (ST->hasNEON() && Opc == ARMCC::EQ) {
6889      SDValue AndOp;
6890      if (ISD::isBuildVectorAllZeros(Op1.getNode()))
6891        AndOp = Op0;
6892      else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
6893        AndOp = Op1;
6894
6895      // Ignore bitconvert.
6896      if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
6897        AndOp = AndOp.getOperand(0);
6898
6899      if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
6900        Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0));
6901        Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1));
6902        SDValue Result = DAG.getNode(ARMISD::VTST, dl, CmpVT, Op0, Op1);
6903        if (!Invert)
6904          Result = DAG.getNOT(dl, Result, VT);
6905        return Result;
6906      }
6907    }
6908  }
6909
6910  if (Swap)
6911    std::swap(Op0, Op1);
6912
6913  // If one of the operands is a constant vector zero, attempt to fold the
6914  // comparison to a specialized compare-against-zero form.
6915  if (ISD::isBuildVectorAllZeros(Op0.getNode()) &&
6916      (Opc == ARMCC::GE || Opc == ARMCC::GT || Opc == ARMCC::EQ ||
6917       Opc == ARMCC::NE)) {
6918    if (Opc == ARMCC::GE)
6919      Opc = ARMCC::LE;
6920    else if (Opc == ARMCC::GT)
6921      Opc = ARMCC::LT;
6922    std::swap(Op0, Op1);
6923  }
6924
6925  SDValue Result;
6926  if (ISD::isBuildVectorAllZeros(Op1.getNode()) &&
6927      (Opc == ARMCC::GE || Opc == ARMCC::GT || Opc == ARMCC::LE ||
6928       Opc == ARMCC::LT || Opc == ARMCC::NE || Opc == ARMCC::EQ))
6929    Result = DAG.getNode(ARMISD::VCMPZ, dl, CmpVT, Op0,
6930                         DAG.getConstant(Opc, dl, MVT::i32));
6931  else
6932    Result = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op0, Op1,
6933                         DAG.getConstant(Opc, dl, MVT::i32));
6934
6935  Result = DAG.getSExtOrTrunc(Result, dl, VT);
6936
6937  if (Invert)
6938    Result = DAG.getNOT(dl, Result, VT);
6939
6940  return Result;
6941}
6942
6943static SDValue LowerSETCCCARRY(SDValue Op, SelectionDAG &DAG) {
6944  SDValue LHS = Op.getOperand(0);
6945  SDValue RHS = Op.getOperand(1);
6946  SDValue Carry = Op.getOperand(2);
6947  SDValue Cond = Op.getOperand(3);
6948  SDLoc DL(Op);
6949
6950  assert(LHS.getSimpleValueType().isInteger() && "SETCCCARRY is integer only.");
6951
6952  // ARMISD::SUBE expects a carry not a borrow like ISD::USUBO_CARRY so we
6953  // have to invert the carry first.
6954  Carry = DAG.getNode(ISD::SUB, DL, MVT::i32,
6955                      DAG.getConstant(1, DL, MVT::i32), Carry);
6956  // This converts the boolean value carry into the carry flag.
6957  Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG);
6958
6959  SDVTList VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
6960  SDValue Cmp = DAG.getNode(ARMISD::SUBE, DL, VTs, LHS, RHS, Carry);
6961
6962  SDValue FVal = DAG.getConstant(0, DL, MVT::i32);
6963  SDValue TVal = DAG.getConstant(1, DL, MVT::i32);
6964  SDValue ARMcc = DAG.getConstant(
6965      IntCCToARMCC(cast<CondCodeSDNode>(Cond)->get()), DL, MVT::i32);
6966  SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
6967  SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), DL, ARM::CPSR,
6968                                   Cmp.getValue(1), SDValue());
6969  return DAG.getNode(ARMISD::CMOV, DL, Op.getValueType(), FVal, TVal, ARMcc,
6970                     CCR, Chain.getValue(1));
6971}
6972
6973/// isVMOVModifiedImm - Check if the specified splat value corresponds to a
6974/// valid vector constant for a NEON or MVE instruction with a "modified
6975/// immediate" operand (e.g., VMOV).  If so, return the encoded value.
6976static SDValue isVMOVModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
6977                                 unsigned SplatBitSize, SelectionDAG &DAG,
6978                                 const SDLoc &dl, EVT &VT, EVT VectorVT,
6979                                 VMOVModImmType type) {
6980  unsigned OpCmode, Imm;
6981  bool is128Bits = VectorVT.is128BitVector();
6982
6983  // SplatBitSize is set to the smallest size that splats the vector, so a
6984  // zero vector will always have SplatBitSize == 8.  However, NEON modified
6985  // immediate instructions others than VMOV do not support the 8-bit encoding
6986  // of a zero vector, and the default encoding of zero is supposed to be the
6987  // 32-bit version.
6988  if (SplatBits == 0)
6989    SplatBitSize = 32;
6990
6991  switch (SplatBitSize) {
6992  case 8:
6993    if (type != VMOVModImm)
6994      return SDValue();
6995    // Any 1-byte value is OK.  Op=0, Cmode=1110.
6996    assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
6997    OpCmode = 0xe;
6998    Imm = SplatBits;
6999    VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
7000    break;
7001
7002  case 16:
7003    // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
7004    VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
7005    if ((SplatBits & ~0xff) == 0) {
7006      // Value = 0x00nn: Op=x, Cmode=100x.
7007      OpCmode = 0x8;
7008      Imm = SplatBits;
7009      break;
7010    }
7011    if ((SplatBits & ~0xff00) == 0) {
7012      // Value = 0xnn00: Op=x, Cmode=101x.
7013      OpCmode = 0xa;
7014      Imm = SplatBits >> 8;
7015      break;
7016    }
7017    return SDValue();
7018
7019  case 32:
7020    // NEON's 32-bit VMOV supports splat values where:
7021    // * only one byte is nonzero, or
7022    // * the least significant byte is 0xff and the second byte is nonzero, or
7023    // * the least significant 2 bytes are 0xff and the third is nonzero.
7024    VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
7025    if ((SplatBits & ~0xff) == 0) {
7026      // Value = 0x000000nn: Op=x, Cmode=000x.
7027      OpCmode = 0;
7028      Imm = SplatBits;
7029      break;
7030    }
7031    if ((SplatBits & ~0xff00) == 0) {
7032      // Value = 0x0000nn00: Op=x, Cmode=001x.
7033      OpCmode = 0x2;
7034      Imm = SplatBits >> 8;
7035      break;
7036    }
7037    if ((SplatBits & ~0xff0000) == 0) {
7038      // Value = 0x00nn0000: Op=x, Cmode=010x.
7039      OpCmode = 0x4;
7040      Imm = SplatBits >> 16;
7041      break;
7042    }
7043    if ((SplatBits & ~0xff000000) == 0) {
7044      // Value = 0xnn000000: Op=x, Cmode=011x.
7045      OpCmode = 0x6;
7046      Imm = SplatBits >> 24;
7047      break;
7048    }
7049
7050    // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
7051    if (type == OtherModImm) return SDValue();
7052
7053    if ((SplatBits & ~0xffff) == 0 &&
7054        ((SplatBits | SplatUndef) & 0xff) == 0xff) {
7055      // Value = 0x0000nnff: Op=x, Cmode=1100.
7056      OpCmode = 0xc;
7057      Imm = SplatBits >> 8;
7058      break;
7059    }
7060
7061    // cmode == 0b1101 is not supported for MVE VMVN
7062    if (type == MVEVMVNModImm)
7063      return SDValue();
7064
7065    if ((SplatBits & ~0xffffff) == 0 &&
7066        ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
7067      // Value = 0x00nnffff: Op=x, Cmode=1101.
7068      OpCmode = 0xd;
7069      Imm = SplatBits >> 16;
7070      break;
7071    }
7072
7073    // Note: there are a few 32-bit splat values (specifically: 00ffff00,
7074    // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
7075    // VMOV.I32.  A (very) minor optimization would be to replicate the value
7076    // and fall through here to test for a valid 64-bit splat.  But, then the
7077    // caller would also need to check and handle the change in size.
7078    return SDValue();
7079
7080  case 64: {
7081    if (type != VMOVModImm)
7082      return SDValue();
7083    // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
7084    uint64_t BitMask = 0xff;
7085    unsigned ImmMask = 1;
7086    Imm = 0;
7087    for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
7088      if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
7089        Imm |= ImmMask;
7090      } else if ((SplatBits & BitMask) != 0) {
7091        return SDValue();
7092      }
7093      BitMask <<= 8;
7094      ImmMask <<= 1;
7095    }
7096
7097    if (DAG.getDataLayout().isBigEndian()) {
7098      // Reverse the order of elements within the vector.
7099      unsigned BytesPerElem = VectorVT.getScalarSizeInBits() / 8;
7100      unsigned Mask = (1 << BytesPerElem) - 1;
7101      unsigned NumElems = 8 / BytesPerElem;
7102      unsigned NewImm = 0;
7103      for (unsigned ElemNum = 0; ElemNum < NumElems; ++ElemNum) {
7104        unsigned Elem = ((Imm >> ElemNum * BytesPerElem) & Mask);
7105        NewImm |= Elem << (NumElems - ElemNum - 1) * BytesPerElem;
7106      }
7107      Imm = NewImm;
7108    }
7109
7110    // Op=1, Cmode=1110.
7111    OpCmode = 0x1e;
7112    VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
7113    break;
7114  }
7115
7116  default:
7117    llvm_unreachable("unexpected size for isVMOVModifiedImm");
7118  }
7119
7120  unsigned EncodedVal = ARM_AM::createVMOVModImm(OpCmode, Imm);
7121  return DAG.getTargetConstant(EncodedVal, dl, MVT::i32);
7122}
7123
7124SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
7125                                           const ARMSubtarget *ST) const {
7126  EVT VT = Op.getValueType();
7127  bool IsDouble = (VT == MVT::f64);
7128  ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
7129  const APFloat &FPVal = CFP->getValueAPF();
7130
7131  // Prevent floating-point constants from using literal loads
7132  // when execute-only is enabled.
7133  if (ST->genExecuteOnly()) {
7134    // We shouldn't trigger this for v6m execute-only
7135    assert((!ST->isThumb1Only() || ST->hasV8MBaselineOps()) &&
7136           "Unexpected architecture");
7137
7138    // If we can represent the constant as an immediate, don't lower it
7139    if (isFPImmLegal(FPVal, VT))
7140      return Op;
7141    // Otherwise, construct as integer, and move to float register
7142    APInt INTVal = FPVal.bitcastToAPInt();
7143    SDLoc DL(CFP);
7144    switch (VT.getSimpleVT().SimpleTy) {
7145      default:
7146        llvm_unreachable("Unknown floating point type!");
7147        break;
7148      case MVT::f64: {
7149        SDValue Lo = DAG.getConstant(INTVal.trunc(32), DL, MVT::i32);
7150        SDValue Hi = DAG.getConstant(INTVal.lshr(32).trunc(32), DL, MVT::i32);
7151        return DAG.getNode(ARMISD::VMOVDRR, DL, MVT::f64, Lo, Hi);
7152      }
7153      case MVT::f32:
7154          return DAG.getNode(ARMISD::VMOVSR, DL, VT,
7155              DAG.getConstant(INTVal, DL, MVT::i32));
7156    }
7157  }
7158
7159  if (!ST->hasVFP3Base())
7160    return SDValue();
7161
7162  // Use the default (constant pool) lowering for double constants when we have
7163  // an SP-only FPU
7164  if (IsDouble && !Subtarget->hasFP64())
7165    return SDValue();
7166
7167  // Try splatting with a VMOV.f32...
7168  int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
7169
7170  if (ImmVal != -1) {
7171    if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
7172      // We have code in place to select a valid ConstantFP already, no need to
7173      // do any mangling.
7174      return Op;
7175    }
7176
7177    // It's a float and we are trying to use NEON operations where
7178    // possible. Lower it to a splat followed by an extract.
7179    SDLoc DL(Op);
7180    SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32);
7181    SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
7182                                      NewVal);
7183    return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
7184                       DAG.getConstant(0, DL, MVT::i32));
7185  }
7186
7187  // The rest of our options are NEON only, make sure that's allowed before
7188  // proceeding..
7189  if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
7190    return SDValue();
7191
7192  EVT VMovVT;
7193  uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
7194
7195  // It wouldn't really be worth bothering for doubles except for one very
7196  // important value, which does happen to match: 0.0. So make sure we don't do
7197  // anything stupid.
7198  if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
7199    return SDValue();
7200
7201  // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
7202  SDValue NewVal = isVMOVModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op),
7203                                     VMovVT, VT, VMOVModImm);
7204  if (NewVal != SDValue()) {
7205    SDLoc DL(Op);
7206    SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
7207                                      NewVal);
7208    if (IsDouble)
7209      return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
7210
7211    // It's a float: cast and extract a vector element.
7212    SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
7213                                       VecConstant);
7214    return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
7215                       DAG.getConstant(0, DL, MVT::i32));
7216  }
7217
7218  // Finally, try a VMVN.i32
7219  NewVal = isVMOVModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT,
7220                             VT, VMVNModImm);
7221  if (NewVal != SDValue()) {
7222    SDLoc DL(Op);
7223    SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
7224
7225    if (IsDouble)
7226      return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
7227
7228    // It's a float: cast and extract a vector element.
7229    SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
7230                                       VecConstant);
7231    return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
7232                       DAG.getConstant(0, DL, MVT::i32));
7233  }
7234
7235  return SDValue();
7236}
7237
7238// check if an VEXT instruction can handle the shuffle mask when the
7239// vector sources of the shuffle are the same.
7240static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
7241  unsigned NumElts = VT.getVectorNumElements();
7242
7243  // Assume that the first shuffle index is not UNDEF.  Fail if it is.
7244  if (M[0] < 0)
7245    return false;
7246
7247  Imm = M[0];
7248
7249  // If this is a VEXT shuffle, the immediate value is the index of the first
7250  // element.  The other shuffle indices must be the successive elements after
7251  // the first one.
7252  unsigned ExpectedElt = Imm;
7253  for (unsigned i = 1; i < NumElts; ++i) {
7254    // Increment the expected index.  If it wraps around, just follow it
7255    // back to index zero and keep going.
7256    ++ExpectedElt;
7257    if (ExpectedElt == NumElts)
7258      ExpectedElt = 0;
7259
7260    if (M[i] < 0) continue; // ignore UNDEF indices
7261    if (ExpectedElt != static_cast<unsigned>(M[i]))
7262      return false;
7263  }
7264
7265  return true;
7266}
7267
7268static bool isVEXTMask(ArrayRef<int> M, EVT VT,
7269                       bool &ReverseVEXT, unsigned &Imm) {
7270  unsigned NumElts = VT.getVectorNumElements();
7271  ReverseVEXT = false;
7272
7273  // Assume that the first shuffle index is not UNDEF.  Fail if it is.
7274  if (M[0] < 0)
7275    return false;
7276
7277  Imm = M[0];
7278
7279  // If this is a VEXT shuffle, the immediate value is the index of the first
7280  // element.  The other shuffle indices must be the successive elements after
7281  // the first one.
7282  unsigned ExpectedElt = Imm;
7283  for (unsigned i = 1; i < NumElts; ++i) {
7284    // Increment the expected index.  If it wraps around, it may still be
7285    // a VEXT but the source vectors must be swapped.
7286    ExpectedElt += 1;
7287    if (ExpectedElt == NumElts * 2) {
7288      ExpectedElt = 0;
7289      ReverseVEXT = true;
7290    }
7291
7292    if (M[i] < 0) continue; // ignore UNDEF indices
7293    if (ExpectedElt != static_cast<unsigned>(M[i]))
7294      return false;
7295  }
7296
7297  // Adjust the index value if the source operands will be swapped.
7298  if (ReverseVEXT)
7299    Imm -= NumElts;
7300
7301  return true;
7302}
7303
7304static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
7305  // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
7306  // range, then 0 is placed into the resulting vector. So pretty much any mask
7307  // of 8 elements can work here.
7308  return VT == MVT::v8i8 && M.size() == 8;
7309}
7310
7311static unsigned SelectPairHalf(unsigned Elements, ArrayRef<int> Mask,
7312                               unsigned Index) {
7313  if (Mask.size() == Elements * 2)
7314    return Index / Elements;
7315  return Mask[Index] == 0 ? 0 : 1;
7316}
7317
7318// Checks whether the shuffle mask represents a vector transpose (VTRN) by
7319// checking that pairs of elements in the shuffle mask represent the same index
7320// in each vector, incrementing the expected index by 2 at each step.
7321// e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 2, 6]
7322//  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,c,g}
7323//  v2={e,f,g,h}
7324// WhichResult gives the offset for each element in the mask based on which
7325// of the two results it belongs to.
7326//
7327// The transpose can be represented either as:
7328// result1 = shufflevector v1, v2, result1_shuffle_mask
7329// result2 = shufflevector v1, v2, result2_shuffle_mask
7330// where v1/v2 and the shuffle masks have the same number of elements
7331// (here WhichResult (see below) indicates which result is being checked)
7332//
7333// or as:
7334// results = shufflevector v1, v2, shuffle_mask
7335// where both results are returned in one vector and the shuffle mask has twice
7336// as many elements as v1/v2 (here WhichResult will always be 0 if true) here we
7337// want to check the low half and high half of the shuffle mask as if it were
7338// the other case
7339static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
7340  unsigned EltSz = VT.getScalarSizeInBits();
7341  if (EltSz == 64)
7342    return false;
7343
7344  unsigned NumElts = VT.getVectorNumElements();
7345  if (M.size() != NumElts && M.size() != NumElts*2)
7346    return false;
7347
7348  // If the mask is twice as long as the input vector then we need to check the
7349  // upper and lower parts of the mask with a matching value for WhichResult
7350  // FIXME: A mask with only even values will be rejected in case the first
7351  // element is undefined, e.g. [-1, 4, 2, 6] will be rejected, because only
7352  // M[0] is used to determine WhichResult
7353  for (unsigned i = 0; i < M.size(); i += NumElts) {
7354    WhichResult = SelectPairHalf(NumElts, M, i);
7355    for (unsigned j = 0; j < NumElts; j += 2) {
7356      if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
7357          (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + NumElts + WhichResult))
7358        return false;
7359    }
7360  }
7361
7362  if (M.size() == NumElts*2)
7363    WhichResult = 0;
7364
7365  return true;
7366}
7367
7368/// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
7369/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
7370/// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
7371static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
7372  unsigned EltSz = VT.getScalarSizeInBits();
7373  if (EltSz == 64)
7374    return false;
7375
7376  unsigned NumElts = VT.getVectorNumElements();
7377  if (M.size() != NumElts && M.size() != NumElts*2)
7378    return false;
7379
7380  for (unsigned i = 0; i < M.size(); i += NumElts) {
7381    WhichResult = SelectPairHalf(NumElts, M, i);
7382    for (unsigned j = 0; j < NumElts; j += 2) {
7383      if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
7384          (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + WhichResult))
7385        return false;
7386    }
7387  }
7388
7389  if (M.size() == NumElts*2)
7390    WhichResult = 0;
7391
7392  return true;
7393}
7394
7395// Checks whether the shuffle mask represents a vector unzip (VUZP) by checking
7396// that the mask elements are either all even and in steps of size 2 or all odd
7397// and in steps of size 2.
7398// e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 2, 4, 6]
7399//  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,c,e,g}
7400//  v2={e,f,g,h}
7401// Requires similar checks to that of isVTRNMask with
7402// respect the how results are returned.
7403static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
7404  unsigned EltSz = VT.getScalarSizeInBits();
7405  if (EltSz == 64)
7406    return false;
7407
7408  unsigned NumElts = VT.getVectorNumElements();
7409  if (M.size() != NumElts && M.size() != NumElts*2)
7410    return false;
7411
7412  for (unsigned i = 0; i < M.size(); i += NumElts) {
7413    WhichResult = SelectPairHalf(NumElts, M, i);
7414    for (unsigned j = 0; j < NumElts; ++j) {
7415      if (M[i+j] >= 0 && (unsigned) M[i+j] != 2 * j + WhichResult)
7416        return false;
7417    }
7418  }
7419
7420  if (M.size() == NumElts*2)
7421    WhichResult = 0;
7422
7423  // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
7424  if (VT.is64BitVector() && EltSz == 32)
7425    return false;
7426
7427  return true;
7428}
7429
7430/// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
7431/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
7432/// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
7433static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
7434  unsigned EltSz = VT.getScalarSizeInBits();
7435  if (EltSz == 64)
7436    return false;
7437
7438  unsigned NumElts = VT.getVectorNumElements();
7439  if (M.size() != NumElts && M.size() != NumElts*2)
7440    return false;
7441
7442  unsigned Half = NumElts / 2;
7443  for (unsigned i = 0; i < M.size(); i += NumElts) {
7444    WhichResult = SelectPairHalf(NumElts, M, i);
7445    for (unsigned j = 0; j < NumElts; j += Half) {
7446      unsigned Idx = WhichResult;
7447      for (unsigned k = 0; k < Half; ++k) {
7448        int MIdx = M[i + j + k];
7449        if (MIdx >= 0 && (unsigned) MIdx != Idx)
7450          return false;
7451        Idx += 2;
7452      }
7453    }
7454  }
7455
7456  if (M.size() == NumElts*2)
7457    WhichResult = 0;
7458
7459  // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
7460  if (VT.is64BitVector() && EltSz == 32)
7461    return false;
7462
7463  return true;
7464}
7465
7466// Checks whether the shuffle mask represents a vector zip (VZIP) by checking
7467// that pairs of elements of the shufflemask represent the same index in each
7468// vector incrementing sequentially through the vectors.
7469// e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 1, 5]
7470//  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,b,f}
7471//  v2={e,f,g,h}
7472// Requires similar checks to that of isVTRNMask with respect the how results
7473// are returned.
7474static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
7475  unsigned EltSz = VT.getScalarSizeInBits();
7476  if (EltSz == 64)
7477    return false;
7478
7479  unsigned NumElts = VT.getVectorNumElements();
7480  if (M.size() != NumElts && M.size() != NumElts*2)
7481    return false;
7482
7483  for (unsigned i = 0; i < M.size(); i += NumElts) {
7484    WhichResult = SelectPairHalf(NumElts, M, i);
7485    unsigned Idx = WhichResult * NumElts / 2;
7486    for (unsigned j = 0; j < NumElts; j += 2) {
7487      if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
7488          (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx + NumElts))
7489        return false;
7490      Idx += 1;
7491    }
7492  }
7493
7494  if (M.size() == NumElts*2)
7495    WhichResult = 0;
7496
7497  // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
7498  if (VT.is64BitVector() && EltSz == 32)
7499    return false;
7500
7501  return true;
7502}
7503
7504/// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
7505/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
7506/// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
7507static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
7508  unsigned EltSz = VT.getScalarSizeInBits();
7509  if (EltSz == 64)
7510    return false;
7511
7512  unsigned NumElts = VT.getVectorNumElements();
7513  if (M.size() != NumElts && M.size() != NumElts*2)
7514    return false;
7515
7516  for (unsigned i = 0; i < M.size(); i += NumElts) {
7517    WhichResult = SelectPairHalf(NumElts, M, i);
7518    unsigned Idx = WhichResult * NumElts / 2;
7519    for (unsigned j = 0; j < NumElts; j += 2) {
7520      if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
7521          (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx))
7522        return false;
7523      Idx += 1;
7524    }
7525  }
7526
7527  if (M.size() == NumElts*2)
7528    WhichResult = 0;
7529
7530  // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
7531  if (VT.is64BitVector() && EltSz == 32)
7532    return false;
7533
7534  return true;
7535}
7536
7537/// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN),
7538/// and return the corresponding ARMISD opcode if it is, or 0 if it isn't.
7539static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT,
7540                                           unsigned &WhichResult,
7541                                           bool &isV_UNDEF) {
7542  isV_UNDEF = false;
7543  if (isVTRNMask(ShuffleMask, VT, WhichResult))
7544    return ARMISD::VTRN;
7545  if (isVUZPMask(ShuffleMask, VT, WhichResult))
7546    return ARMISD::VUZP;
7547  if (isVZIPMask(ShuffleMask, VT, WhichResult))
7548    return ARMISD::VZIP;
7549
7550  isV_UNDEF = true;
7551  if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
7552    return ARMISD::VTRN;
7553  if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
7554    return ARMISD::VUZP;
7555  if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
7556    return ARMISD::VZIP;
7557
7558  return 0;
7559}
7560
7561/// \return true if this is a reverse operation on an vector.
7562static bool isReverseMask(ArrayRef<int> M, EVT VT) {
7563  unsigned NumElts = VT.getVectorNumElements();
7564  // Make sure the mask has the right size.
7565  if (NumElts != M.size())
7566      return false;
7567
7568  // Look for <15, ..., 3, -1, 1, 0>.
7569  for (unsigned i = 0; i != NumElts; ++i)
7570    if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
7571      return false;
7572
7573  return true;
7574}
7575
7576static bool isTruncMask(ArrayRef<int> M, EVT VT, bool Top, bool SingleSource) {
7577  unsigned NumElts = VT.getVectorNumElements();
7578  // Make sure the mask has the right size.
7579  if (NumElts != M.size() || (VT != MVT::v8i16 && VT != MVT::v16i8))
7580    return false;
7581
7582  // Half-width truncation patterns (e.g. v4i32 -> v8i16):
7583  // !Top &&  SingleSource: <0, 2, 4, 6, 0, 2, 4, 6>
7584  // !Top && !SingleSource: <0, 2, 4, 6, 8, 10, 12, 14>
7585  //  Top &&  SingleSource: <1, 3, 5, 7, 1, 3, 5, 7>
7586  //  Top && !SingleSource: <1, 3, 5, 7, 9, 11, 13, 15>
7587  int Ofs = Top ? 1 : 0;
7588  int Upper = SingleSource ? 0 : NumElts;
7589  for (int i = 0, e = NumElts / 2; i != e; ++i) {
7590    if (M[i] >= 0 && M[i] != (i * 2) + Ofs)
7591      return false;
7592    if (M[i + e] >= 0 && M[i + e] != (i * 2) + Ofs + Upper)
7593      return false;
7594  }
7595  return true;
7596}
7597
7598static bool isVMOVNMask(ArrayRef<int> M, EVT VT, bool Top, bool SingleSource) {
7599  unsigned NumElts = VT.getVectorNumElements();
7600  // Make sure the mask has the right size.
7601  if (NumElts != M.size() || (VT != MVT::v8i16 && VT != MVT::v16i8))
7602    return false;
7603
7604  // If Top
7605  //   Look for <0, N, 2, N+2, 4, N+4, ..>.
7606  //   This inserts Input2 into Input1
7607  // else if not Top
7608  //   Look for <0, N+1, 2, N+3, 4, N+5, ..>
7609  //   This inserts Input1 into Input2
7610  unsigned Offset = Top ? 0 : 1;
7611  unsigned N = SingleSource ? 0 : NumElts;
7612  for (unsigned i = 0; i < NumElts; i += 2) {
7613    if (M[i] >= 0 && M[i] != (int)i)
7614      return false;
7615    if (M[i + 1] >= 0 && M[i + 1] != (int)(N + i + Offset))
7616      return false;
7617  }
7618
7619  return true;
7620}
7621
7622static bool isVMOVNTruncMask(ArrayRef<int> M, EVT ToVT, bool rev) {
7623  unsigned NumElts = ToVT.getVectorNumElements();
7624  if (NumElts != M.size())
7625    return false;
7626
7627  // Test if the Trunc can be convertable to a VMOVN with this shuffle. We are
7628  // looking for patterns of:
7629  // !rev: 0 N/2 1 N/2+1 2 N/2+2 ...
7630  //  rev: N/2 0 N/2+1 1 N/2+2 2 ...
7631
7632  unsigned Off0 = rev ? NumElts / 2 : 0;
7633  unsigned Off1 = rev ? 0 : NumElts / 2;
7634  for (unsigned i = 0; i < NumElts; i += 2) {
7635    if (M[i] >= 0 && M[i] != (int)(Off0 + i / 2))
7636      return false;
7637    if (M[i + 1] >= 0 && M[i + 1] != (int)(Off1 + i / 2))
7638      return false;
7639  }
7640
7641  return true;
7642}
7643
7644// Reconstruct an MVE VCVT from a BuildVector of scalar fptrunc, all extracted
7645// from a pair of inputs. For example:
7646// BUILDVECTOR(FP_ROUND(EXTRACT_ELT(X, 0),
7647//             FP_ROUND(EXTRACT_ELT(Y, 0),
7648//             FP_ROUND(EXTRACT_ELT(X, 1),
7649//             FP_ROUND(EXTRACT_ELT(Y, 1), ...)
7650static SDValue LowerBuildVectorOfFPTrunc(SDValue BV, SelectionDAG &DAG,
7651                                         const ARMSubtarget *ST) {
7652  assert(BV.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
7653  if (!ST->hasMVEFloatOps())
7654    return SDValue();
7655
7656  SDLoc dl(BV);
7657  EVT VT = BV.getValueType();
7658  if (VT != MVT::v8f16)
7659    return SDValue();
7660
7661  // We are looking for a buildvector of fptrunc elements, where all the
7662  // elements are interleavingly extracted from two sources. Check the first two
7663  // items are valid enough and extract some info from them (they are checked
7664  // properly in the loop below).
7665  if (BV.getOperand(0).getOpcode() != ISD::FP_ROUND ||
7666      BV.getOperand(0).getOperand(0).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
7667      BV.getOperand(0).getOperand(0).getConstantOperandVal(1) != 0)
7668    return SDValue();
7669  if (BV.getOperand(1).getOpcode() != ISD::FP_ROUND ||
7670      BV.getOperand(1).getOperand(0).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
7671      BV.getOperand(1).getOperand(0).getConstantOperandVal(1) != 0)
7672    return SDValue();
7673  SDValue Op0 = BV.getOperand(0).getOperand(0).getOperand(0);
7674  SDValue Op1 = BV.getOperand(1).getOperand(0).getOperand(0);
7675  if (Op0.getValueType() != MVT::v4f32 || Op1.getValueType() != MVT::v4f32)
7676    return SDValue();
7677
7678  // Check all the values in the BuildVector line up with our expectations.
7679  for (unsigned i = 1; i < 4; i++) {
7680    auto Check = [](SDValue Trunc, SDValue Op, unsigned Idx) {
7681      return Trunc.getOpcode() == ISD::FP_ROUND &&
7682             Trunc.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7683             Trunc.getOperand(0).getOperand(0) == Op &&
7684             Trunc.getOperand(0).getConstantOperandVal(1) == Idx;
7685    };
7686    if (!Check(BV.getOperand(i * 2 + 0), Op0, i))
7687      return SDValue();
7688    if (!Check(BV.getOperand(i * 2 + 1), Op1, i))
7689      return SDValue();
7690  }
7691
7692  SDValue N1 = DAG.getNode(ARMISD::VCVTN, dl, VT, DAG.getUNDEF(VT), Op0,
7693                           DAG.getConstant(0, dl, MVT::i32));
7694  return DAG.getNode(ARMISD::VCVTN, dl, VT, N1, Op1,
7695                     DAG.getConstant(1, dl, MVT::i32));
7696}
7697
7698// Reconstruct an MVE VCVT from a BuildVector of scalar fpext, all extracted
7699// from a single input on alternating lanes. For example:
7700// BUILDVECTOR(FP_ROUND(EXTRACT_ELT(X, 0),
7701//             FP_ROUND(EXTRACT_ELT(X, 2),
7702//             FP_ROUND(EXTRACT_ELT(X, 4), ...)
7703static SDValue LowerBuildVectorOfFPExt(SDValue BV, SelectionDAG &DAG,
7704                                       const ARMSubtarget *ST) {
7705  assert(BV.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
7706  if (!ST->hasMVEFloatOps())
7707    return SDValue();
7708
7709  SDLoc dl(BV);
7710  EVT VT = BV.getValueType();
7711  if (VT != MVT::v4f32)
7712    return SDValue();
7713
7714  // We are looking for a buildvector of fptext elements, where all the
7715  // elements are alternating lanes from a single source. For example <0,2,4,6>
7716  // or <1,3,5,7>. Check the first two items are valid enough and extract some
7717  // info from them (they are checked properly in the loop below).
7718  if (BV.getOperand(0).getOpcode() != ISD::FP_EXTEND ||
7719      BV.getOperand(0).getOperand(0).getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7720    return SDValue();
7721  SDValue Op0 = BV.getOperand(0).getOperand(0).getOperand(0);
7722  int Offset = BV.getOperand(0).getOperand(0).getConstantOperandVal(1);
7723  if (Op0.getValueType() != MVT::v8f16 || (Offset != 0 && Offset != 1))
7724    return SDValue();
7725
7726  // Check all the values in the BuildVector line up with our expectations.
7727  for (unsigned i = 1; i < 4; i++) {
7728    auto Check = [](SDValue Trunc, SDValue Op, unsigned Idx) {
7729      return Trunc.getOpcode() == ISD::FP_EXTEND &&
7730             Trunc.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7731             Trunc.getOperand(0).getOperand(0) == Op &&
7732             Trunc.getOperand(0).getConstantOperandVal(1) == Idx;
7733    };
7734    if (!Check(BV.getOperand(i), Op0, 2 * i + Offset))
7735      return SDValue();
7736  }
7737
7738  return DAG.getNode(ARMISD::VCVTL, dl, VT, Op0,
7739                     DAG.getConstant(Offset, dl, MVT::i32));
7740}
7741
7742// If N is an integer constant that can be moved into a register in one
7743// instruction, return an SDValue of such a constant (will become a MOV
7744// instruction).  Otherwise return null.
7745static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
7746                                     const ARMSubtarget *ST, const SDLoc &dl) {
7747  uint64_t Val;
7748  if (!isa<ConstantSDNode>(N))
7749    return SDValue();
7750  Val = N->getAsZExtVal();
7751
7752  if (ST->isThumb1Only()) {
7753    if (Val <= 255 || ~Val <= 255)
7754      return DAG.getConstant(Val, dl, MVT::i32);
7755  } else {
7756    if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
7757      return DAG.getConstant(Val, dl, MVT::i32);
7758  }
7759  return SDValue();
7760}
7761
7762static SDValue LowerBUILD_VECTOR_i1(SDValue Op, SelectionDAG &DAG,
7763                                    const ARMSubtarget *ST) {
7764  SDLoc dl(Op);
7765  EVT VT = Op.getValueType();
7766
7767  assert(ST->hasMVEIntegerOps() && "LowerBUILD_VECTOR_i1 called without MVE!");
7768
7769  unsigned NumElts = VT.getVectorNumElements();
7770  unsigned BoolMask;
7771  unsigned BitsPerBool;
7772  if (NumElts == 2) {
7773    BitsPerBool = 8;
7774    BoolMask = 0xff;
7775  } else if (NumElts == 4) {
7776    BitsPerBool = 4;
7777    BoolMask = 0xf;
7778  } else if (NumElts == 8) {
7779    BitsPerBool = 2;
7780    BoolMask = 0x3;
7781  } else if (NumElts == 16) {
7782    BitsPerBool = 1;
7783    BoolMask = 0x1;
7784  } else
7785    return SDValue();
7786
7787  // If this is a single value copied into all lanes (a splat), we can just sign
7788  // extend that single value
7789  SDValue FirstOp = Op.getOperand(0);
7790  if (!isa<ConstantSDNode>(FirstOp) &&
7791      llvm::all_of(llvm::drop_begin(Op->ops()), [&FirstOp](const SDUse &U) {
7792        return U.get().isUndef() || U.get() == FirstOp;
7793      })) {
7794    SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::i32, FirstOp,
7795                              DAG.getValueType(MVT::i1));
7796    return DAG.getNode(ARMISD::PREDICATE_CAST, dl, Op.getValueType(), Ext);
7797  }
7798
7799  // First create base with bits set where known
7800  unsigned Bits32 = 0;
7801  for (unsigned i = 0; i < NumElts; ++i) {
7802    SDValue V = Op.getOperand(i);
7803    if (!isa<ConstantSDNode>(V) && !V.isUndef())
7804      continue;
7805    bool BitSet = V.isUndef() ? false : V->getAsZExtVal();
7806    if (BitSet)
7807      Bits32 |= BoolMask << (i * BitsPerBool);
7808  }
7809
7810  // Add in unknown nodes
7811  SDValue Base = DAG.getNode(ARMISD::PREDICATE_CAST, dl, VT,
7812                             DAG.getConstant(Bits32, dl, MVT::i32));
7813  for (unsigned i = 0; i < NumElts; ++i) {
7814    SDValue V = Op.getOperand(i);
7815    if (isa<ConstantSDNode>(V) || V.isUndef())
7816      continue;
7817    Base = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Base, V,
7818                       DAG.getConstant(i, dl, MVT::i32));
7819  }
7820
7821  return Base;
7822}
7823
7824static SDValue LowerBUILD_VECTORToVIDUP(SDValue Op, SelectionDAG &DAG,
7825                                        const ARMSubtarget *ST) {
7826  if (!ST->hasMVEIntegerOps())
7827    return SDValue();
7828
7829  // We are looking for a buildvector where each element is Op[0] + i*N
7830  EVT VT = Op.getValueType();
7831  SDValue Op0 = Op.getOperand(0);
7832  unsigned NumElts = VT.getVectorNumElements();
7833
7834  // Get the increment value from operand 1
7835  SDValue Op1 = Op.getOperand(1);
7836  if (Op1.getOpcode() != ISD::ADD || Op1.getOperand(0) != Op0 ||
7837      !isa<ConstantSDNode>(Op1.getOperand(1)))
7838    return SDValue();
7839  unsigned N = Op1.getConstantOperandVal(1);
7840  if (N != 1 && N != 2 && N != 4 && N != 8)
7841    return SDValue();
7842
7843  // Check that each other operand matches
7844  for (unsigned I = 2; I < NumElts; I++) {
7845    SDValue OpI = Op.getOperand(I);
7846    if (OpI.getOpcode() != ISD::ADD || OpI.getOperand(0) != Op0 ||
7847        !isa<ConstantSDNode>(OpI.getOperand(1)) ||
7848        OpI.getConstantOperandVal(1) != I * N)
7849      return SDValue();
7850  }
7851
7852  SDLoc DL(Op);
7853  return DAG.getNode(ARMISD::VIDUP, DL, DAG.getVTList(VT, MVT::i32), Op0,
7854                     DAG.getConstant(N, DL, MVT::i32));
7855}
7856
7857// Returns true if the operation N can be treated as qr instruction variant at
7858// operand Op.
7859static bool IsQRMVEInstruction(const SDNode *N, const SDNode *Op) {
7860  switch (N->getOpcode()) {
7861  case ISD::ADD:
7862  case ISD::MUL:
7863  case ISD::SADDSAT:
7864  case ISD::UADDSAT:
7865    return true;
7866  case ISD::SUB:
7867  case ISD::SSUBSAT:
7868  case ISD::USUBSAT:
7869    return N->getOperand(1).getNode() == Op;
7870  case ISD::INTRINSIC_WO_CHAIN:
7871    switch (N->getConstantOperandVal(0)) {
7872    case Intrinsic::arm_mve_add_predicated:
7873    case Intrinsic::arm_mve_mul_predicated:
7874    case Intrinsic::arm_mve_qadd_predicated:
7875    case Intrinsic::arm_mve_vhadd:
7876    case Intrinsic::arm_mve_hadd_predicated:
7877    case Intrinsic::arm_mve_vqdmulh:
7878    case Intrinsic::arm_mve_qdmulh_predicated:
7879    case Intrinsic::arm_mve_vqrdmulh:
7880    case Intrinsic::arm_mve_qrdmulh_predicated:
7881    case Intrinsic::arm_mve_vqdmull:
7882    case Intrinsic::arm_mve_vqdmull_predicated:
7883      return true;
7884    case Intrinsic::arm_mve_sub_predicated:
7885    case Intrinsic::arm_mve_qsub_predicated:
7886    case Intrinsic::arm_mve_vhsub:
7887    case Intrinsic::arm_mve_hsub_predicated:
7888      return N->getOperand(2).getNode() == Op;
7889    default:
7890      return false;
7891    }
7892  default:
7893    return false;
7894  }
7895}
7896
7897// If this is a case we can't handle, return null and let the default
7898// expansion code take care of it.
7899SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
7900                                             const ARMSubtarget *ST) const {
7901  BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
7902  SDLoc dl(Op);
7903  EVT VT = Op.getValueType();
7904
7905  if (ST->hasMVEIntegerOps() && VT.getScalarSizeInBits() == 1)
7906    return LowerBUILD_VECTOR_i1(Op, DAG, ST);
7907
7908  if (SDValue R = LowerBUILD_VECTORToVIDUP(Op, DAG, ST))
7909    return R;
7910
7911  APInt SplatBits, SplatUndef;
7912  unsigned SplatBitSize;
7913  bool HasAnyUndefs;
7914  if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
7915    if (SplatUndef.isAllOnes())
7916      return DAG.getUNDEF(VT);
7917
7918    // If all the users of this constant splat are qr instruction variants,
7919    // generate a vdup of the constant.
7920    if (ST->hasMVEIntegerOps() && VT.getScalarSizeInBits() == SplatBitSize &&
7921        (SplatBitSize == 8 || SplatBitSize == 16 || SplatBitSize == 32) &&
7922        all_of(BVN->uses(),
7923               [BVN](const SDNode *U) { return IsQRMVEInstruction(U, BVN); })) {
7924      EVT DupVT = SplatBitSize == 32   ? MVT::v4i32
7925                  : SplatBitSize == 16 ? MVT::v8i16
7926                                       : MVT::v16i8;
7927      SDValue Const = DAG.getConstant(SplatBits.getZExtValue(), dl, MVT::i32);
7928      SDValue VDup = DAG.getNode(ARMISD::VDUP, dl, DupVT, Const);
7929      return DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, VT, VDup);
7930    }
7931
7932    if ((ST->hasNEON() && SplatBitSize <= 64) ||
7933        (ST->hasMVEIntegerOps() && SplatBitSize <= 64)) {
7934      // Check if an immediate VMOV works.
7935      EVT VmovVT;
7936      SDValue Val =
7937          isVMOVModifiedImm(SplatBits.getZExtValue(), SplatUndef.getZExtValue(),
7938                            SplatBitSize, DAG, dl, VmovVT, VT, VMOVModImm);
7939
7940      if (Val.getNode()) {
7941        SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
7942        return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
7943      }
7944
7945      // Try an immediate VMVN.
7946      uint64_t NegatedImm = (~SplatBits).getZExtValue();
7947      Val = isVMOVModifiedImm(
7948          NegatedImm, SplatUndef.getZExtValue(), SplatBitSize, DAG, dl, VmovVT,
7949          VT, ST->hasMVEIntegerOps() ? MVEVMVNModImm : VMVNModImm);
7950      if (Val.getNode()) {
7951        SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
7952        return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
7953      }
7954
7955      // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
7956      if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
7957        int ImmVal = ARM_AM::getFP32Imm(SplatBits);
7958        if (ImmVal != -1) {
7959          SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32);
7960          return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
7961        }
7962      }
7963
7964      // If we are under MVE, generate a VDUP(constant), bitcast to the original
7965      // type.
7966      if (ST->hasMVEIntegerOps() &&
7967          (SplatBitSize == 8 || SplatBitSize == 16 || SplatBitSize == 32)) {
7968        EVT DupVT = SplatBitSize == 32   ? MVT::v4i32
7969                    : SplatBitSize == 16 ? MVT::v8i16
7970                                         : MVT::v16i8;
7971        SDValue Const = DAG.getConstant(SplatBits.getZExtValue(), dl, MVT::i32);
7972        SDValue VDup = DAG.getNode(ARMISD::VDUP, dl, DupVT, Const);
7973        return DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, VT, VDup);
7974      }
7975    }
7976  }
7977
7978  // Scan through the operands to see if only one value is used.
7979  //
7980  // As an optimisation, even if more than one value is used it may be more
7981  // profitable to splat with one value then change some lanes.
7982  //
7983  // Heuristically we decide to do this if the vector has a "dominant" value,
7984  // defined as splatted to more than half of the lanes.
7985  unsigned NumElts = VT.getVectorNumElements();
7986  bool isOnlyLowElement = true;
7987  bool usesOnlyOneValue = true;
7988  bool hasDominantValue = false;
7989  bool isConstant = true;
7990
7991  // Map of the number of times a particular SDValue appears in the
7992  // element list.
7993  DenseMap<SDValue, unsigned> ValueCounts;
7994  SDValue Value;
7995  for (unsigned i = 0; i < NumElts; ++i) {
7996    SDValue V = Op.getOperand(i);
7997    if (V.isUndef())
7998      continue;
7999    if (i > 0)
8000      isOnlyLowElement = false;
8001    if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
8002      isConstant = false;
8003
8004    ValueCounts.insert(std::make_pair(V, 0));
8005    unsigned &Count = ValueCounts[V];
8006
8007    // Is this value dominant? (takes up more than half of the lanes)
8008    if (++Count > (NumElts / 2)) {
8009      hasDominantValue = true;
8010      Value = V;
8011    }
8012  }
8013  if (ValueCounts.size() != 1)
8014    usesOnlyOneValue = false;
8015  if (!Value.getNode() && !ValueCounts.empty())
8016    Value = ValueCounts.begin()->first;
8017
8018  if (ValueCounts.empty())
8019    return DAG.getUNDEF(VT);
8020
8021  // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
8022  // Keep going if we are hitting this case.
8023  if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
8024    return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
8025
8026  unsigned EltSize = VT.getScalarSizeInBits();
8027
8028  // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
8029  // i32 and try again.
8030  if (hasDominantValue && EltSize <= 32) {
8031    if (!isConstant) {
8032      SDValue N;
8033
8034      // If we are VDUPing a value that comes directly from a vector, that will
8035      // cause an unnecessary move to and from a GPR, where instead we could
8036      // just use VDUPLANE. We can only do this if the lane being extracted
8037      // is at a constant index, as the VDUP from lane instructions only have
8038      // constant-index forms.
8039      ConstantSDNode *constIndex;
8040      if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
8041          (constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1)))) {
8042        // We need to create a new undef vector to use for the VDUPLANE if the
8043        // size of the vector from which we get the value is different than the
8044        // size of the vector that we need to create. We will insert the element
8045        // such that the register coalescer will remove unnecessary copies.
8046        if (VT != Value->getOperand(0).getValueType()) {
8047          unsigned index = constIndex->getAPIntValue().getLimitedValue() %
8048                             VT.getVectorNumElements();
8049          N =  DAG.getNode(ARMISD::VDUPLANE, dl, VT,
8050                 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
8051                        Value, DAG.getConstant(index, dl, MVT::i32)),
8052                           DAG.getConstant(index, dl, MVT::i32));
8053        } else
8054          N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
8055                        Value->getOperand(0), Value->getOperand(1));
8056      } else
8057        N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
8058
8059      if (!usesOnlyOneValue) {
8060        // The dominant value was splatted as 'N', but we now have to insert
8061        // all differing elements.
8062        for (unsigned I = 0; I < NumElts; ++I) {
8063          if (Op.getOperand(I) == Value)
8064            continue;
8065          SmallVector<SDValue, 3> Ops;
8066          Ops.push_back(N);
8067          Ops.push_back(Op.getOperand(I));
8068          Ops.push_back(DAG.getConstant(I, dl, MVT::i32));
8069          N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
8070        }
8071      }
8072      return N;
8073    }
8074    if (VT.getVectorElementType().isFloatingPoint()) {
8075      SmallVector<SDValue, 8> Ops;
8076      MVT FVT = VT.getVectorElementType().getSimpleVT();
8077      assert(FVT == MVT::f32 || FVT == MVT::f16);
8078      MVT IVT = (FVT == MVT::f32) ? MVT::i32 : MVT::i16;
8079      for (unsigned i = 0; i < NumElts; ++i)
8080        Ops.push_back(DAG.getNode(ISD::BITCAST, dl, IVT,
8081                                  Op.getOperand(i)));
8082      EVT VecVT = EVT::getVectorVT(*DAG.getContext(), IVT, NumElts);
8083      SDValue Val = DAG.getBuildVector(VecVT, dl, Ops);
8084      Val = LowerBUILD_VECTOR(Val, DAG, ST);
8085      if (Val.getNode())
8086        return DAG.getNode(ISD::BITCAST, dl, VT, Val);
8087    }
8088    if (usesOnlyOneValue) {
8089      SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
8090      if (isConstant && Val.getNode())
8091        return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
8092    }
8093  }
8094
8095  // If all elements are constants and the case above didn't get hit, fall back
8096  // to the default expansion, which will generate a load from the constant
8097  // pool.
8098  if (isConstant)
8099    return SDValue();
8100
8101  // Reconstruct the BUILDVECTOR to one of the legal shuffles (such as vext and
8102  // vmovn). Empirical tests suggest this is rarely worth it for vectors of
8103  // length <= 2.
8104  if (NumElts >= 4)
8105    if (SDValue shuffle = ReconstructShuffle(Op, DAG))
8106      return shuffle;
8107
8108  // Attempt to turn a buildvector of scalar fptrunc's or fpext's back into
8109  // VCVT's
8110  if (SDValue VCVT = LowerBuildVectorOfFPTrunc(Op, DAG, Subtarget))
8111    return VCVT;
8112  if (SDValue VCVT = LowerBuildVectorOfFPExt(Op, DAG, Subtarget))
8113    return VCVT;
8114
8115  if (ST->hasNEON() && VT.is128BitVector() && VT != MVT::v2f64 && VT != MVT::v4f32) {
8116    // If we haven't found an efficient lowering, try splitting a 128-bit vector
8117    // into two 64-bit vectors; we might discover a better way to lower it.
8118    SmallVector<SDValue, 64> Ops(Op->op_begin(), Op->op_begin() + NumElts);
8119    EVT ExtVT = VT.getVectorElementType();
8120    EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElts / 2);
8121    SDValue Lower = DAG.getBuildVector(HVT, dl, ArrayRef(&Ops[0], NumElts / 2));
8122    if (Lower.getOpcode() == ISD::BUILD_VECTOR)
8123      Lower = LowerBUILD_VECTOR(Lower, DAG, ST);
8124    SDValue Upper =
8125        DAG.getBuildVector(HVT, dl, ArrayRef(&Ops[NumElts / 2], NumElts / 2));
8126    if (Upper.getOpcode() == ISD::BUILD_VECTOR)
8127      Upper = LowerBUILD_VECTOR(Upper, DAG, ST);
8128    if (Lower && Upper)
8129      return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lower, Upper);
8130  }
8131
8132  // Vectors with 32- or 64-bit elements can be built by directly assigning
8133  // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
8134  // will be legalized.
8135  if (EltSize >= 32) {
8136    // Do the expansion with floating-point types, since that is what the VFP
8137    // registers are defined to use, and since i64 is not legal.
8138    EVT EltVT = EVT::getFloatingPointVT(EltSize);
8139    EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
8140    SmallVector<SDValue, 8> Ops;
8141    for (unsigned i = 0; i < NumElts; ++i)
8142      Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
8143    SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
8144    return DAG.getNode(ISD::BITCAST, dl, VT, Val);
8145  }
8146
8147  // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
8148  // know the default expansion would otherwise fall back on something even
8149  // worse. For a vector with one or two non-undef values, that's
8150  // scalar_to_vector for the elements followed by a shuffle (provided the
8151  // shuffle is valid for the target) and materialization element by element
8152  // on the stack followed by a load for everything else.
8153  if (!isConstant && !usesOnlyOneValue) {
8154    SDValue Vec = DAG.getUNDEF(VT);
8155    for (unsigned i = 0 ; i < NumElts; ++i) {
8156      SDValue V = Op.getOperand(i);
8157      if (V.isUndef())
8158        continue;
8159      SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32);
8160      Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
8161    }
8162    return Vec;
8163  }
8164
8165  return SDValue();
8166}
8167
8168// Gather data to see if the operation can be modelled as a
8169// shuffle in combination with VEXTs.
8170SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
8171                                              SelectionDAG &DAG) const {
8172  assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
8173  SDLoc dl(Op);
8174  EVT VT = Op.getValueType();
8175  unsigned NumElts = VT.getVectorNumElements();
8176
8177  struct ShuffleSourceInfo {
8178    SDValue Vec;
8179    unsigned MinElt = std::numeric_limits<unsigned>::max();
8180    unsigned MaxElt = 0;
8181
8182    // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
8183    // be compatible with the shuffle we intend to construct. As a result
8184    // ShuffleVec will be some sliding window into the original Vec.
8185    SDValue ShuffleVec;
8186
8187    // Code should guarantee that element i in Vec starts at element "WindowBase
8188    // + i * WindowScale in ShuffleVec".
8189    int WindowBase = 0;
8190    int WindowScale = 1;
8191
8192    ShuffleSourceInfo(SDValue Vec) : Vec(Vec), ShuffleVec(Vec) {}
8193
8194    bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
8195  };
8196
8197  // First gather all vectors used as an immediate source for this BUILD_VECTOR
8198  // node.
8199  SmallVector<ShuffleSourceInfo, 2> Sources;
8200  for (unsigned i = 0; i < NumElts; ++i) {
8201    SDValue V = Op.getOperand(i);
8202    if (V.isUndef())
8203      continue;
8204    else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
8205      // A shuffle can only come from building a vector from various
8206      // elements of other vectors.
8207      return SDValue();
8208    } else if (!isa<ConstantSDNode>(V.getOperand(1))) {
8209      // Furthermore, shuffles require a constant mask, whereas extractelts
8210      // accept variable indices.
8211      return SDValue();
8212    }
8213
8214    // Add this element source to the list if it's not already there.
8215    SDValue SourceVec = V.getOperand(0);
8216    auto Source = llvm::find(Sources, SourceVec);
8217    if (Source == Sources.end())
8218      Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
8219
8220    // Update the minimum and maximum lane number seen.
8221    unsigned EltNo = V.getConstantOperandVal(1);
8222    Source->MinElt = std::min(Source->MinElt, EltNo);
8223    Source->MaxElt = std::max(Source->MaxElt, EltNo);
8224  }
8225
8226  // Currently only do something sane when at most two source vectors
8227  // are involved.
8228  if (Sources.size() > 2)
8229    return SDValue();
8230
8231  // Find out the smallest element size among result and two sources, and use
8232  // it as element size to build the shuffle_vector.
8233  EVT SmallestEltTy = VT.getVectorElementType();
8234  for (auto &Source : Sources) {
8235    EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
8236    if (SrcEltTy.bitsLT(SmallestEltTy))
8237      SmallestEltTy = SrcEltTy;
8238  }
8239  unsigned ResMultiplier =
8240      VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits();
8241  NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
8242  EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
8243
8244  // If the source vector is too wide or too narrow, we may nevertheless be able
8245  // to construct a compatible shuffle either by concatenating it with UNDEF or
8246  // extracting a suitable range of elements.
8247  for (auto &Src : Sources) {
8248    EVT SrcVT = Src.ShuffleVec.getValueType();
8249
8250    uint64_t SrcVTSize = SrcVT.getFixedSizeInBits();
8251    uint64_t VTSize = VT.getFixedSizeInBits();
8252    if (SrcVTSize == VTSize)
8253      continue;
8254
8255    // This stage of the search produces a source with the same element type as
8256    // the original, but with a total width matching the BUILD_VECTOR output.
8257    EVT EltVT = SrcVT.getVectorElementType();
8258    unsigned NumSrcElts = VTSize / EltVT.getFixedSizeInBits();
8259    EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
8260
8261    if (SrcVTSize < VTSize) {
8262      if (2 * SrcVTSize != VTSize)
8263        return SDValue();
8264      // We can pad out the smaller vector for free, so if it's part of a
8265      // shuffle...
8266      Src.ShuffleVec =
8267          DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
8268                      DAG.getUNDEF(Src.ShuffleVec.getValueType()));
8269      continue;
8270    }
8271
8272    if (SrcVTSize != 2 * VTSize)
8273      return SDValue();
8274
8275    if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
8276      // Span too large for a VEXT to cope
8277      return SDValue();
8278    }
8279
8280    if (Src.MinElt >= NumSrcElts) {
8281      // The extraction can just take the second half
8282      Src.ShuffleVec =
8283          DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
8284                      DAG.getConstant(NumSrcElts, dl, MVT::i32));
8285      Src.WindowBase = -NumSrcElts;
8286    } else if (Src.MaxElt < NumSrcElts) {
8287      // The extraction can just take the first half
8288      Src.ShuffleVec =
8289          DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
8290                      DAG.getConstant(0, dl, MVT::i32));
8291    } else {
8292      // An actual VEXT is needed
8293      SDValue VEXTSrc1 =
8294          DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
8295                      DAG.getConstant(0, dl, MVT::i32));
8296      SDValue VEXTSrc2 =
8297          DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
8298                      DAG.getConstant(NumSrcElts, dl, MVT::i32));
8299
8300      Src.ShuffleVec = DAG.getNode(ARMISD::VEXT, dl, DestVT, VEXTSrc1,
8301                                   VEXTSrc2,
8302                                   DAG.getConstant(Src.MinElt, dl, MVT::i32));
8303      Src.WindowBase = -Src.MinElt;
8304    }
8305  }
8306
8307  // Another possible incompatibility occurs from the vector element types. We
8308  // can fix this by bitcasting the source vectors to the same type we intend
8309  // for the shuffle.
8310  for (auto &Src : Sources) {
8311    EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
8312    if (SrcEltTy == SmallestEltTy)
8313      continue;
8314    assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
8315    Src.ShuffleVec = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, ShuffleVT, Src.ShuffleVec);
8316    Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
8317    Src.WindowBase *= Src.WindowScale;
8318  }
8319
8320  // Final check before we try to actually produce a shuffle.
8321  LLVM_DEBUG(for (auto Src
8322                  : Sources)
8323                 assert(Src.ShuffleVec.getValueType() == ShuffleVT););
8324
8325  // The stars all align, our next step is to produce the mask for the shuffle.
8326  SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
8327  int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits();
8328  for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
8329    SDValue Entry = Op.getOperand(i);
8330    if (Entry.isUndef())
8331      continue;
8332
8333    auto Src = llvm::find(Sources, Entry.getOperand(0));
8334    int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
8335
8336    // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
8337    // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
8338    // segment.
8339    EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
8340    int BitsDefined = std::min(OrigEltTy.getScalarSizeInBits(),
8341                               VT.getScalarSizeInBits());
8342    int LanesDefined = BitsDefined / BitsPerShuffleLane;
8343
8344    // This source is expected to fill ResMultiplier lanes of the final shuffle,
8345    // starting at the appropriate offset.
8346    int *LaneMask = &Mask[i * ResMultiplier];
8347
8348    int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
8349    ExtractBase += NumElts * (Src - Sources.begin());
8350    for (int j = 0; j < LanesDefined; ++j)
8351      LaneMask[j] = ExtractBase + j;
8352  }
8353
8354
8355  // We can't handle more than two sources. This should have already
8356  // been checked before this point.
8357  assert(Sources.size() <= 2 && "Too many sources!");
8358
8359  SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
8360  for (unsigned i = 0; i < Sources.size(); ++i)
8361    ShuffleOps[i] = Sources[i].ShuffleVec;
8362
8363  SDValue Shuffle = buildLegalVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
8364                                            ShuffleOps[1], Mask, DAG);
8365  if (!Shuffle)
8366    return SDValue();
8367  return DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, VT, Shuffle);
8368}
8369
8370enum ShuffleOpCodes {
8371  OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
8372  OP_VREV,
8373  OP_VDUP0,
8374  OP_VDUP1,
8375  OP_VDUP2,
8376  OP_VDUP3,
8377  OP_VEXT1,
8378  OP_VEXT2,
8379  OP_VEXT3,
8380  OP_VUZPL, // VUZP, left result
8381  OP_VUZPR, // VUZP, right result
8382  OP_VZIPL, // VZIP, left result
8383  OP_VZIPR, // VZIP, right result
8384  OP_VTRNL, // VTRN, left result
8385  OP_VTRNR  // VTRN, right result
8386};
8387
8388static bool isLegalMVEShuffleOp(unsigned PFEntry) {
8389  unsigned OpNum = (PFEntry >> 26) & 0x0F;
8390  switch (OpNum) {
8391  case OP_COPY:
8392  case OP_VREV:
8393  case OP_VDUP0:
8394  case OP_VDUP1:
8395  case OP_VDUP2:
8396  case OP_VDUP3:
8397    return true;
8398  }
8399  return false;
8400}
8401
8402/// isShuffleMaskLegal - Targets can use this to indicate that they only
8403/// support *some* VECTOR_SHUFFLE operations, those with specific masks.
8404/// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
8405/// are assumed to be legal.
8406bool ARMTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
8407  if (VT.getVectorNumElements() == 4 &&
8408      (VT.is128BitVector() || VT.is64BitVector())) {
8409    unsigned PFIndexes[4];
8410    for (unsigned i = 0; i != 4; ++i) {
8411      if (M[i] < 0)
8412        PFIndexes[i] = 8;
8413      else
8414        PFIndexes[i] = M[i];
8415    }
8416
8417    // Compute the index in the perfect shuffle table.
8418    unsigned PFTableIndex =
8419      PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
8420    unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
8421    unsigned Cost = (PFEntry >> 30);
8422
8423    if (Cost <= 4 && (Subtarget->hasNEON() || isLegalMVEShuffleOp(PFEntry)))
8424      return true;
8425  }
8426
8427  bool ReverseVEXT, isV_UNDEF;
8428  unsigned Imm, WhichResult;
8429
8430  unsigned EltSize = VT.getScalarSizeInBits();
8431  if (EltSize >= 32 ||
8432      ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
8433      ShuffleVectorInst::isIdentityMask(M, M.size()) ||
8434      isVREVMask(M, VT, 64) ||
8435      isVREVMask(M, VT, 32) ||
8436      isVREVMask(M, VT, 16))
8437    return true;
8438  else if (Subtarget->hasNEON() &&
8439           (isVEXTMask(M, VT, ReverseVEXT, Imm) ||
8440            isVTBLMask(M, VT) ||
8441            isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF)))
8442    return true;
8443  else if ((VT == MVT::v8i16 || VT == MVT::v8f16 || VT == MVT::v16i8) &&
8444           isReverseMask(M, VT))
8445    return true;
8446  else if (Subtarget->hasMVEIntegerOps() &&
8447           (isVMOVNMask(M, VT, true, false) ||
8448            isVMOVNMask(M, VT, false, false) || isVMOVNMask(M, VT, true, true)))
8449    return true;
8450  else if (Subtarget->hasMVEIntegerOps() &&
8451           (isTruncMask(M, VT, false, false) ||
8452            isTruncMask(M, VT, false, true) ||
8453            isTruncMask(M, VT, true, false) || isTruncMask(M, VT, true, true)))
8454    return true;
8455  else
8456    return false;
8457}
8458
8459/// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
8460/// the specified operations to build the shuffle.
8461static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
8462                                      SDValue RHS, SelectionDAG &DAG,
8463                                      const SDLoc &dl) {
8464  unsigned OpNum = (PFEntry >> 26) & 0x0F;
8465  unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
8466  unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
8467
8468  if (OpNum == OP_COPY) {
8469    if (LHSID == (1*9+2)*9+3) return LHS;
8470    assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
8471    return RHS;
8472  }
8473
8474  SDValue OpLHS, OpRHS;
8475  OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
8476  OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
8477  EVT VT = OpLHS.getValueType();
8478
8479  switch (OpNum) {
8480  default: llvm_unreachable("Unknown shuffle opcode!");
8481  case OP_VREV:
8482    // VREV divides the vector in half and swaps within the half.
8483    if (VT.getScalarSizeInBits() == 32)
8484      return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
8485    // vrev <4 x i16> -> VREV32
8486    if (VT.getScalarSizeInBits() == 16)
8487      return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
8488    // vrev <4 x i8> -> VREV16
8489    assert(VT.getScalarSizeInBits() == 8);
8490    return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
8491  case OP_VDUP0:
8492  case OP_VDUP1:
8493  case OP_VDUP2:
8494  case OP_VDUP3:
8495    return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
8496                       OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32));
8497  case OP_VEXT1:
8498  case OP_VEXT2:
8499  case OP_VEXT3:
8500    return DAG.getNode(ARMISD::VEXT, dl, VT,
8501                       OpLHS, OpRHS,
8502                       DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32));
8503  case OP_VUZPL:
8504  case OP_VUZPR:
8505    return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
8506                       OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
8507  case OP_VZIPL:
8508  case OP_VZIPR:
8509    return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
8510                       OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
8511  case OP_VTRNL:
8512  case OP_VTRNR:
8513    return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
8514                       OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
8515  }
8516}
8517
8518static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
8519                                       ArrayRef<int> ShuffleMask,
8520                                       SelectionDAG &DAG) {
8521  // Check to see if we can use the VTBL instruction.
8522  SDValue V1 = Op.getOperand(0);
8523  SDValue V2 = Op.getOperand(1);
8524  SDLoc DL(Op);
8525
8526  SmallVector<SDValue, 8> VTBLMask;
8527  for (int I : ShuffleMask)
8528    VTBLMask.push_back(DAG.getConstant(I, DL, MVT::i32));
8529
8530  if (V2.getNode()->isUndef())
8531    return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
8532                       DAG.getBuildVector(MVT::v8i8, DL, VTBLMask));
8533
8534  return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
8535                     DAG.getBuildVector(MVT::v8i8, DL, VTBLMask));
8536}
8537
8538static SDValue LowerReverse_VECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
8539  SDLoc DL(Op);
8540  EVT VT = Op.getValueType();
8541
8542  assert((VT == MVT::v8i16 || VT == MVT::v8f16 || VT == MVT::v16i8) &&
8543         "Expect an v8i16/v16i8 type");
8544  SDValue OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, Op.getOperand(0));
8545  // For a v16i8 type: After the VREV, we have got <7, ..., 0, 15, ..., 8>. Now,
8546  // extract the first 8 bytes into the top double word and the last 8 bytes
8547  // into the bottom double word, through a new vector shuffle that will be
8548  // turned into a VEXT on Neon, or a couple of VMOVDs on MVE.
8549  std::vector<int> NewMask;
8550  for (unsigned i = 0; i < VT.getVectorNumElements() / 2; i++)
8551    NewMask.push_back(VT.getVectorNumElements() / 2 + i);
8552  for (unsigned i = 0; i < VT.getVectorNumElements() / 2; i++)
8553    NewMask.push_back(i);
8554  return DAG.getVectorShuffle(VT, DL, OpLHS, OpLHS, NewMask);
8555}
8556
8557static EVT getVectorTyFromPredicateVector(EVT VT) {
8558  switch (VT.getSimpleVT().SimpleTy) {
8559  case MVT::v2i1:
8560    return MVT::v2f64;
8561  case MVT::v4i1:
8562    return MVT::v4i32;
8563  case MVT::v8i1:
8564    return MVT::v8i16;
8565  case MVT::v16i1:
8566    return MVT::v16i8;
8567  default:
8568    llvm_unreachable("Unexpected vector predicate type");
8569  }
8570}
8571
8572static SDValue PromoteMVEPredVector(SDLoc dl, SDValue Pred, EVT VT,
8573                                    SelectionDAG &DAG) {
8574  // Converting from boolean predicates to integers involves creating a vector
8575  // of all ones or all zeroes and selecting the lanes based upon the real
8576  // predicate.
8577  SDValue AllOnes =
8578      DAG.getTargetConstant(ARM_AM::createVMOVModImm(0xe, 0xff), dl, MVT::i32);
8579  AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v16i8, AllOnes);
8580
8581  SDValue AllZeroes =
8582      DAG.getTargetConstant(ARM_AM::createVMOVModImm(0xe, 0x0), dl, MVT::i32);
8583  AllZeroes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v16i8, AllZeroes);
8584
8585  // Get full vector type from predicate type
8586  EVT NewVT = getVectorTyFromPredicateVector(VT);
8587
8588  SDValue RecastV1;
8589  // If the real predicate is an v8i1 or v4i1 (not v16i1) then we need to recast
8590  // this to a v16i1. This cannot be done with an ordinary bitcast because the
8591  // sizes are not the same. We have to use a MVE specific PREDICATE_CAST node,
8592  // since we know in hardware the sizes are really the same.
8593  if (VT != MVT::v16i1)
8594    RecastV1 = DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::v16i1, Pred);
8595  else
8596    RecastV1 = Pred;
8597
8598  // Select either all ones or zeroes depending upon the real predicate bits.
8599  SDValue PredAsVector =
8600      DAG.getNode(ISD::VSELECT, dl, MVT::v16i8, RecastV1, AllOnes, AllZeroes);
8601
8602  // Recast our new predicate-as-integer v16i8 vector into something
8603  // appropriate for the shuffle, i.e. v4i32 for a real v4i1 predicate.
8604  return DAG.getNode(ISD::BITCAST, dl, NewVT, PredAsVector);
8605}
8606
8607static SDValue LowerVECTOR_SHUFFLE_i1(SDValue Op, SelectionDAG &DAG,
8608                                      const ARMSubtarget *ST) {
8609  EVT VT = Op.getValueType();
8610  ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
8611  ArrayRef<int> ShuffleMask = SVN->getMask();
8612
8613  assert(ST->hasMVEIntegerOps() &&
8614         "No support for vector shuffle of boolean predicates");
8615
8616  SDValue V1 = Op.getOperand(0);
8617  SDValue V2 = Op.getOperand(1);
8618  SDLoc dl(Op);
8619  if (isReverseMask(ShuffleMask, VT)) {
8620    SDValue cast = DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, V1);
8621    SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, MVT::i32, cast);
8622    SDValue srl = DAG.getNode(ISD::SRL, dl, MVT::i32, rbit,
8623                              DAG.getConstant(16, dl, MVT::i32));
8624    return DAG.getNode(ARMISD::PREDICATE_CAST, dl, VT, srl);
8625  }
8626
8627  // Until we can come up with optimised cases for every single vector
8628  // shuffle in existence we have chosen the least painful strategy. This is
8629  // to essentially promote the boolean predicate to a 8-bit integer, where
8630  // each predicate represents a byte. Then we fall back on a normal integer
8631  // vector shuffle and convert the result back into a predicate vector. In
8632  // many cases the generated code might be even better than scalar code
8633  // operating on bits. Just imagine trying to shuffle 8 arbitrary 2-bit
8634  // fields in a register into 8 other arbitrary 2-bit fields!
8635  SDValue PredAsVector1 = PromoteMVEPredVector(dl, V1, VT, DAG);
8636  EVT NewVT = PredAsVector1.getValueType();
8637  SDValue PredAsVector2 = V2.isUndef() ? DAG.getUNDEF(NewVT)
8638                                       : PromoteMVEPredVector(dl, V2, VT, DAG);
8639  assert(PredAsVector2.getValueType() == NewVT &&
8640         "Expected identical vector type in expanded i1 shuffle!");
8641
8642  // Do the shuffle!
8643  SDValue Shuffled = DAG.getVectorShuffle(NewVT, dl, PredAsVector1,
8644                                          PredAsVector2, ShuffleMask);
8645
8646  // Now return the result of comparing the shuffled vector with zero,
8647  // which will generate a real predicate, i.e. v4i1, v8i1 or v16i1. For a v2i1
8648  // we convert to a v4i1 compare to fill in the two halves of the i64 as i32s.
8649  if (VT == MVT::v2i1) {
8650    SDValue BC = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, MVT::v4i32, Shuffled);
8651    SDValue Cmp = DAG.getNode(ARMISD::VCMPZ, dl, MVT::v4i1, BC,
8652                              DAG.getConstant(ARMCC::NE, dl, MVT::i32));
8653    return DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::v2i1, Cmp);
8654  }
8655  return DAG.getNode(ARMISD::VCMPZ, dl, VT, Shuffled,
8656                     DAG.getConstant(ARMCC::NE, dl, MVT::i32));
8657}
8658
8659static SDValue LowerVECTOR_SHUFFLEUsingMovs(SDValue Op,
8660                                            ArrayRef<int> ShuffleMask,
8661                                            SelectionDAG &DAG) {
8662  // Attempt to lower the vector shuffle using as many whole register movs as
8663  // possible. This is useful for types smaller than 32bits, which would
8664  // often otherwise become a series for grp movs.
8665  SDLoc dl(Op);
8666  EVT VT = Op.getValueType();
8667  if (VT.getScalarSizeInBits() >= 32)
8668    return SDValue();
8669
8670  assert((VT == MVT::v8i16 || VT == MVT::v8f16 || VT == MVT::v16i8) &&
8671         "Unexpected vector type");
8672  int NumElts = VT.getVectorNumElements();
8673  int QuarterSize = NumElts / 4;
8674  // The four final parts of the vector, as i32's
8675  SDValue Parts[4];
8676
8677  // Look for full lane vmovs like <0,1,2,3> or <u,5,6,7> etc, (but not
8678  // <u,u,u,u>), returning the vmov lane index
8679  auto getMovIdx = [](ArrayRef<int> ShuffleMask, int Start, int Length) {
8680    // Detect which mov lane this would be from the first non-undef element.
8681    int MovIdx = -1;
8682    for (int i = 0; i < Length; i++) {
8683      if (ShuffleMask[Start + i] >= 0) {
8684        if (ShuffleMask[Start + i] % Length != i)
8685          return -1;
8686        MovIdx = ShuffleMask[Start + i] / Length;
8687        break;
8688      }
8689    }
8690    // If all items are undef, leave this for other combines
8691    if (MovIdx == -1)
8692      return -1;
8693    // Check the remaining values are the correct part of the same mov
8694    for (int i = 1; i < Length; i++) {
8695      if (ShuffleMask[Start + i] >= 0 &&
8696          (ShuffleMask[Start + i] / Length != MovIdx ||
8697           ShuffleMask[Start + i] % Length != i))
8698        return -1;
8699    }
8700    return MovIdx;
8701  };
8702
8703  for (int Part = 0; Part < 4; ++Part) {
8704    // Does this part look like a mov
8705    int Elt = getMovIdx(ShuffleMask, Part * QuarterSize, QuarterSize);
8706    if (Elt != -1) {
8707      SDValue Input = Op->getOperand(0);
8708      if (Elt >= 4) {
8709        Input = Op->getOperand(1);
8710        Elt -= 4;
8711      }
8712      SDValue BitCast = DAG.getBitcast(MVT::v4f32, Input);
8713      Parts[Part] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, BitCast,
8714                                DAG.getConstant(Elt, dl, MVT::i32));
8715    }
8716  }
8717
8718  // Nothing interesting found, just return
8719  if (!Parts[0] && !Parts[1] && !Parts[2] && !Parts[3])
8720    return SDValue();
8721
8722  // The other parts need to be built with the old shuffle vector, cast to a
8723  // v4i32 and extract_vector_elts
8724  if (!Parts[0] || !Parts[1] || !Parts[2] || !Parts[3]) {
8725    SmallVector<int, 16> NewShuffleMask;
8726    for (int Part = 0; Part < 4; ++Part)
8727      for (int i = 0; i < QuarterSize; i++)
8728        NewShuffleMask.push_back(
8729            Parts[Part] ? -1 : ShuffleMask[Part * QuarterSize + i]);
8730    SDValue NewShuffle = DAG.getVectorShuffle(
8731        VT, dl, Op->getOperand(0), Op->getOperand(1), NewShuffleMask);
8732    SDValue BitCast = DAG.getBitcast(MVT::v4f32, NewShuffle);
8733
8734    for (int Part = 0; Part < 4; ++Part)
8735      if (!Parts[Part])
8736        Parts[Part] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32,
8737                                  BitCast, DAG.getConstant(Part, dl, MVT::i32));
8738  }
8739  // Build a vector out of the various parts and bitcast it back to the original
8740  // type.
8741  SDValue NewVec = DAG.getNode(ARMISD::BUILD_VECTOR, dl, MVT::v4f32, Parts);
8742  return DAG.getBitcast(VT, NewVec);
8743}
8744
8745static SDValue LowerVECTOR_SHUFFLEUsingOneOff(SDValue Op,
8746                                              ArrayRef<int> ShuffleMask,
8747                                              SelectionDAG &DAG) {
8748  SDValue V1 = Op.getOperand(0);
8749  SDValue V2 = Op.getOperand(1);
8750  EVT VT = Op.getValueType();
8751  unsigned NumElts = VT.getVectorNumElements();
8752
8753  // An One-Off Identity mask is one that is mostly an identity mask from as
8754  // single source but contains a single element out-of-place, either from a
8755  // different vector or from another position in the same vector. As opposed to
8756  // lowering this via a ARMISD::BUILD_VECTOR we can generate an extract/insert
8757  // pair directly.
8758  auto isOneOffIdentityMask = [](ArrayRef<int> Mask, EVT VT, int BaseOffset,
8759                                 int &OffElement) {
8760    OffElement = -1;
8761    int NonUndef = 0;
8762    for (int i = 0, NumMaskElts = Mask.size(); i < NumMaskElts; ++i) {
8763      if (Mask[i] == -1)
8764        continue;
8765      NonUndef++;
8766      if (Mask[i] != i + BaseOffset) {
8767        if (OffElement == -1)
8768          OffElement = i;
8769        else
8770          return false;
8771      }
8772    }
8773    return NonUndef > 2 && OffElement != -1;
8774  };
8775  int OffElement;
8776  SDValue VInput;
8777  if (isOneOffIdentityMask(ShuffleMask, VT, 0, OffElement))
8778    VInput = V1;
8779  else if (isOneOffIdentityMask(ShuffleMask, VT, NumElts, OffElement))
8780    VInput = V2;
8781  else
8782    return SDValue();
8783
8784  SDLoc dl(Op);
8785  EVT SVT = VT.getScalarType() == MVT::i8 || VT.getScalarType() == MVT::i16
8786                ? MVT::i32
8787                : VT.getScalarType();
8788  SDValue Elt = DAG.getNode(
8789      ISD::EXTRACT_VECTOR_ELT, dl, SVT,
8790      ShuffleMask[OffElement] < (int)NumElts ? V1 : V2,
8791      DAG.getVectorIdxConstant(ShuffleMask[OffElement] % NumElts, dl));
8792  return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, VInput, Elt,
8793                     DAG.getVectorIdxConstant(OffElement % NumElts, dl));
8794}
8795
8796static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG,
8797                                   const ARMSubtarget *ST) {
8798  SDValue V1 = Op.getOperand(0);
8799  SDValue V2 = Op.getOperand(1);
8800  SDLoc dl(Op);
8801  EVT VT = Op.getValueType();
8802  ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
8803  unsigned EltSize = VT.getScalarSizeInBits();
8804
8805  if (ST->hasMVEIntegerOps() && EltSize == 1)
8806    return LowerVECTOR_SHUFFLE_i1(Op, DAG, ST);
8807
8808  // Convert shuffles that are directly supported on NEON to target-specific
8809  // DAG nodes, instead of keeping them as shuffles and matching them again
8810  // during code selection.  This is more efficient and avoids the possibility
8811  // of inconsistencies between legalization and selection.
8812  // FIXME: floating-point vectors should be canonicalized to integer vectors
8813  // of the same time so that they get CSEd properly.
8814  ArrayRef<int> ShuffleMask = SVN->getMask();
8815
8816  if (EltSize <= 32) {
8817    if (SVN->isSplat()) {
8818      int Lane = SVN->getSplatIndex();
8819      // If this is undef splat, generate it via "just" vdup, if possible.
8820      if (Lane == -1) Lane = 0;
8821
8822      // Test if V1 is a SCALAR_TO_VECTOR.
8823      if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
8824        return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
8825      }
8826      // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
8827      // (and probably will turn into a SCALAR_TO_VECTOR once legalization
8828      // reaches it).
8829      if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
8830          !isa<ConstantSDNode>(V1.getOperand(0))) {
8831        bool IsScalarToVector = true;
8832        for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
8833          if (!V1.getOperand(i).isUndef()) {
8834            IsScalarToVector = false;
8835            break;
8836          }
8837        if (IsScalarToVector)
8838          return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
8839      }
8840      return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
8841                         DAG.getConstant(Lane, dl, MVT::i32));
8842    }
8843
8844    bool ReverseVEXT = false;
8845    unsigned Imm = 0;
8846    if (ST->hasNEON() && isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
8847      if (ReverseVEXT)
8848        std::swap(V1, V2);
8849      return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
8850                         DAG.getConstant(Imm, dl, MVT::i32));
8851    }
8852
8853    if (isVREVMask(ShuffleMask, VT, 64))
8854      return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
8855    if (isVREVMask(ShuffleMask, VT, 32))
8856      return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
8857    if (isVREVMask(ShuffleMask, VT, 16))
8858      return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
8859
8860    if (ST->hasNEON() && V2->isUndef() && isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
8861      return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
8862                         DAG.getConstant(Imm, dl, MVT::i32));
8863    }
8864
8865    // Check for Neon shuffles that modify both input vectors in place.
8866    // If both results are used, i.e., if there are two shuffles with the same
8867    // source operands and with masks corresponding to both results of one of
8868    // these operations, DAG memoization will ensure that a single node is
8869    // used for both shuffles.
8870    unsigned WhichResult = 0;
8871    bool isV_UNDEF = false;
8872    if (ST->hasNEON()) {
8873      if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
8874              ShuffleMask, VT, WhichResult, isV_UNDEF)) {
8875        if (isV_UNDEF)
8876          V2 = V1;
8877        return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2)
8878            .getValue(WhichResult);
8879      }
8880    }
8881    if (ST->hasMVEIntegerOps()) {
8882      if (isVMOVNMask(ShuffleMask, VT, false, false))
8883        return DAG.getNode(ARMISD::VMOVN, dl, VT, V2, V1,
8884                           DAG.getConstant(0, dl, MVT::i32));
8885      if (isVMOVNMask(ShuffleMask, VT, true, false))
8886        return DAG.getNode(ARMISD::VMOVN, dl, VT, V1, V2,
8887                           DAG.getConstant(1, dl, MVT::i32));
8888      if (isVMOVNMask(ShuffleMask, VT, true, true))
8889        return DAG.getNode(ARMISD::VMOVN, dl, VT, V1, V1,
8890                           DAG.getConstant(1, dl, MVT::i32));
8891    }
8892
8893    // Also check for these shuffles through CONCAT_VECTORS: we canonicalize
8894    // shuffles that produce a result larger than their operands with:
8895    //   shuffle(concat(v1, undef), concat(v2, undef))
8896    // ->
8897    //   shuffle(concat(v1, v2), undef)
8898    // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine).
8899    //
8900    // This is useful in the general case, but there are special cases where
8901    // native shuffles produce larger results: the two-result ops.
8902    //
8903    // Look through the concat when lowering them:
8904    //   shuffle(concat(v1, v2), undef)
8905    // ->
8906    //   concat(VZIP(v1, v2):0, :1)
8907    //
8908    if (ST->hasNEON() && V1->getOpcode() == ISD::CONCAT_VECTORS && V2->isUndef()) {
8909      SDValue SubV1 = V1->getOperand(0);
8910      SDValue SubV2 = V1->getOperand(1);
8911      EVT SubVT = SubV1.getValueType();
8912
8913      // We expect these to have been canonicalized to -1.
8914      assert(llvm::all_of(ShuffleMask, [&](int i) {
8915        return i < (int)VT.getVectorNumElements();
8916      }) && "Unexpected shuffle index into UNDEF operand!");
8917
8918      if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
8919              ShuffleMask, SubVT, WhichResult, isV_UNDEF)) {
8920        if (isV_UNDEF)
8921          SubV2 = SubV1;
8922        assert((WhichResult == 0) &&
8923               "In-place shuffle of concat can only have one result!");
8924        SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT),
8925                                  SubV1, SubV2);
8926        return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0),
8927                           Res.getValue(1));
8928      }
8929    }
8930  }
8931
8932  if (ST->hasMVEIntegerOps() && EltSize <= 32) {
8933    if (SDValue V = LowerVECTOR_SHUFFLEUsingOneOff(Op, ShuffleMask, DAG))
8934      return V;
8935
8936    for (bool Top : {false, true}) {
8937      for (bool SingleSource : {false, true}) {
8938        if (isTruncMask(ShuffleMask, VT, Top, SingleSource)) {
8939          MVT FromSVT = MVT::getIntegerVT(EltSize * 2);
8940          MVT FromVT = MVT::getVectorVT(FromSVT, ShuffleMask.size() / 2);
8941          SDValue Lo = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, FromVT, V1);
8942          SDValue Hi = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, FromVT,
8943                                   SingleSource ? V1 : V2);
8944          if (Top) {
8945            SDValue Amt = DAG.getConstant(EltSize, dl, FromVT);
8946            Lo = DAG.getNode(ISD::SRL, dl, FromVT, Lo, Amt);
8947            Hi = DAG.getNode(ISD::SRL, dl, FromVT, Hi, Amt);
8948          }
8949          return DAG.getNode(ARMISD::MVETRUNC, dl, VT, Lo, Hi);
8950        }
8951      }
8952    }
8953  }
8954
8955  // If the shuffle is not directly supported and it has 4 elements, use
8956  // the PerfectShuffle-generated table to synthesize it from other shuffles.
8957  unsigned NumElts = VT.getVectorNumElements();
8958  if (NumElts == 4) {
8959    unsigned PFIndexes[4];
8960    for (unsigned i = 0; i != 4; ++i) {
8961      if (ShuffleMask[i] < 0)
8962        PFIndexes[i] = 8;
8963      else
8964        PFIndexes[i] = ShuffleMask[i];
8965    }
8966
8967    // Compute the index in the perfect shuffle table.
8968    unsigned PFTableIndex =
8969      PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
8970    unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
8971    unsigned Cost = (PFEntry >> 30);
8972
8973    if (Cost <= 4) {
8974      if (ST->hasNEON())
8975        return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
8976      else if (isLegalMVEShuffleOp(PFEntry)) {
8977        unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
8978        unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
8979        unsigned PFEntryLHS = PerfectShuffleTable[LHSID];
8980        unsigned PFEntryRHS = PerfectShuffleTable[RHSID];
8981        if (isLegalMVEShuffleOp(PFEntryLHS) && isLegalMVEShuffleOp(PFEntryRHS))
8982          return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
8983      }
8984    }
8985  }
8986
8987  // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
8988  if (EltSize >= 32) {
8989    // Do the expansion with floating-point types, since that is what the VFP
8990    // registers are defined to use, and since i64 is not legal.
8991    EVT EltVT = EVT::getFloatingPointVT(EltSize);
8992    EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
8993    V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
8994    V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
8995    SmallVector<SDValue, 8> Ops;
8996    for (unsigned i = 0; i < NumElts; ++i) {
8997      if (ShuffleMask[i] < 0)
8998        Ops.push_back(DAG.getUNDEF(EltVT));
8999      else
9000        Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
9001                                  ShuffleMask[i] < (int)NumElts ? V1 : V2,
9002                                  DAG.getConstant(ShuffleMask[i] & (NumElts-1),
9003                                                  dl, MVT::i32)));
9004    }
9005    SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
9006    return DAG.getNode(ISD::BITCAST, dl, VT, Val);
9007  }
9008
9009  if ((VT == MVT::v8i16 || VT == MVT::v8f16 || VT == MVT::v16i8) &&
9010      isReverseMask(ShuffleMask, VT))
9011    return LowerReverse_VECTOR_SHUFFLE(Op, DAG);
9012
9013  if (ST->hasNEON() && VT == MVT::v8i8)
9014    if (SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG))
9015      return NewOp;
9016
9017  if (ST->hasMVEIntegerOps())
9018    if (SDValue NewOp = LowerVECTOR_SHUFFLEUsingMovs(Op, ShuffleMask, DAG))
9019      return NewOp;
9020
9021  return SDValue();
9022}
9023
9024static SDValue LowerINSERT_VECTOR_ELT_i1(SDValue Op, SelectionDAG &DAG,
9025                                         const ARMSubtarget *ST) {
9026  EVT VecVT = Op.getOperand(0).getValueType();
9027  SDLoc dl(Op);
9028
9029  assert(ST->hasMVEIntegerOps() &&
9030         "LowerINSERT_VECTOR_ELT_i1 called without MVE!");
9031
9032  SDValue Conv =
9033      DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, Op->getOperand(0));
9034  unsigned Lane = Op.getConstantOperandVal(2);
9035  unsigned LaneWidth =
9036      getVectorTyFromPredicateVector(VecVT).getScalarSizeInBits() / 8;
9037  unsigned Mask = ((1 << LaneWidth) - 1) << Lane * LaneWidth;
9038  SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::i32,
9039                            Op.getOperand(1), DAG.getValueType(MVT::i1));
9040  SDValue BFI = DAG.getNode(ARMISD::BFI, dl, MVT::i32, Conv, Ext,
9041                            DAG.getConstant(~Mask, dl, MVT::i32));
9042  return DAG.getNode(ARMISD::PREDICATE_CAST, dl, Op.getValueType(), BFI);
9043}
9044
9045SDValue ARMTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
9046                                                  SelectionDAG &DAG) const {
9047  // INSERT_VECTOR_ELT is legal only for immediate indexes.
9048  SDValue Lane = Op.getOperand(2);
9049  if (!isa<ConstantSDNode>(Lane))
9050    return SDValue();
9051
9052  SDValue Elt = Op.getOperand(1);
9053  EVT EltVT = Elt.getValueType();
9054
9055  if (Subtarget->hasMVEIntegerOps() &&
9056      Op.getValueType().getScalarSizeInBits() == 1)
9057    return LowerINSERT_VECTOR_ELT_i1(Op, DAG, Subtarget);
9058
9059  if (getTypeAction(*DAG.getContext(), EltVT) ==
9060      TargetLowering::TypePromoteFloat) {
9061    // INSERT_VECTOR_ELT doesn't want f16 operands promoting to f32,
9062    // but the type system will try to do that if we don't intervene.
9063    // Reinterpret any such vector-element insertion as one with the
9064    // corresponding integer types.
9065
9066    SDLoc dl(Op);
9067
9068    EVT IEltVT = MVT::getIntegerVT(EltVT.getScalarSizeInBits());
9069    assert(getTypeAction(*DAG.getContext(), IEltVT) !=
9070           TargetLowering::TypePromoteFloat);
9071
9072    SDValue VecIn = Op.getOperand(0);
9073    EVT VecVT = VecIn.getValueType();
9074    EVT IVecVT = EVT::getVectorVT(*DAG.getContext(), IEltVT,
9075                                  VecVT.getVectorNumElements());
9076
9077    SDValue IElt = DAG.getNode(ISD::BITCAST, dl, IEltVT, Elt);
9078    SDValue IVecIn = DAG.getNode(ISD::BITCAST, dl, IVecVT, VecIn);
9079    SDValue IVecOut = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, IVecVT,
9080                                  IVecIn, IElt, Lane);
9081    return DAG.getNode(ISD::BITCAST, dl, VecVT, IVecOut);
9082  }
9083
9084  return Op;
9085}
9086
9087static SDValue LowerEXTRACT_VECTOR_ELT_i1(SDValue Op, SelectionDAG &DAG,
9088                                          const ARMSubtarget *ST) {
9089  EVT VecVT = Op.getOperand(0).getValueType();
9090  SDLoc dl(Op);
9091
9092  assert(ST->hasMVEIntegerOps() &&
9093         "LowerINSERT_VECTOR_ELT_i1 called without MVE!");
9094
9095  SDValue Conv =
9096      DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, Op->getOperand(0));
9097  unsigned Lane = Op.getConstantOperandVal(1);
9098  unsigned LaneWidth =
9099      getVectorTyFromPredicateVector(VecVT).getScalarSizeInBits() / 8;
9100  SDValue Shift = DAG.getNode(ISD::SRL, dl, MVT::i32, Conv,
9101                              DAG.getConstant(Lane * LaneWidth, dl, MVT::i32));
9102  return Shift;
9103}
9104
9105static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG,
9106                                       const ARMSubtarget *ST) {
9107  // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
9108  SDValue Lane = Op.getOperand(1);
9109  if (!isa<ConstantSDNode>(Lane))
9110    return SDValue();
9111
9112  SDValue Vec = Op.getOperand(0);
9113  EVT VT = Vec.getValueType();
9114
9115  if (ST->hasMVEIntegerOps() && VT.getScalarSizeInBits() == 1)
9116    return LowerEXTRACT_VECTOR_ELT_i1(Op, DAG, ST);
9117
9118  if (Op.getValueType() == MVT::i32 && Vec.getScalarValueSizeInBits() < 32) {
9119    SDLoc dl(Op);
9120    return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
9121  }
9122
9123  return Op;
9124}
9125
9126static SDValue LowerCONCAT_VECTORS_i1(SDValue Op, SelectionDAG &DAG,
9127                                      const ARMSubtarget *ST) {
9128  SDLoc dl(Op);
9129  assert(Op.getValueType().getScalarSizeInBits() == 1 &&
9130         "Unexpected custom CONCAT_VECTORS lowering");
9131  assert(isPowerOf2_32(Op.getNumOperands()) &&
9132         "Unexpected custom CONCAT_VECTORS lowering");
9133  assert(ST->hasMVEIntegerOps() &&
9134         "CONCAT_VECTORS lowering only supported for MVE");
9135
9136  auto ConcatPair = [&](SDValue V1, SDValue V2) {
9137    EVT Op1VT = V1.getValueType();
9138    EVT Op2VT = V2.getValueType();
9139    assert(Op1VT == Op2VT && "Operand types don't match!");
9140    assert((Op1VT == MVT::v2i1 || Op1VT == MVT::v4i1 || Op1VT == MVT::v8i1) &&
9141           "Unexpected i1 concat operations!");
9142    EVT VT = Op1VT.getDoubleNumVectorElementsVT(*DAG.getContext());
9143
9144    SDValue NewV1 = PromoteMVEPredVector(dl, V1, Op1VT, DAG);
9145    SDValue NewV2 = PromoteMVEPredVector(dl, V2, Op2VT, DAG);
9146
9147    // We now have Op1 + Op2 promoted to vectors of integers, where v8i1 gets
9148    // promoted to v8i16, etc.
9149    MVT ElType =
9150        getVectorTyFromPredicateVector(VT).getScalarType().getSimpleVT();
9151    unsigned NumElts = 2 * Op1VT.getVectorNumElements();
9152
9153    EVT ConcatVT = MVT::getVectorVT(ElType, NumElts);
9154    if (Op1VT == MVT::v4i1 || Op1VT == MVT::v8i1) {
9155      // Use MVETRUNC to truncate the combined NewV1::NewV2 into the smaller
9156      // ConcatVT.
9157      SDValue ConVec =
9158          DAG.getNode(ARMISD::MVETRUNC, dl, ConcatVT, NewV1, NewV2);
9159      return DAG.getNode(ARMISD::VCMPZ, dl, VT, ConVec,
9160                         DAG.getConstant(ARMCC::NE, dl, MVT::i32));
9161    }
9162
9163    // Extract the vector elements from Op1 and Op2 one by one and truncate them
9164    // to be the right size for the destination. For example, if Op1 is v4i1
9165    // then the promoted vector is v4i32. The result of concatenation gives a
9166    // v8i1, which when promoted is v8i16. That means each i32 element from Op1
9167    // needs truncating to i16 and inserting in the result.
9168    auto ExtractInto = [&DAG, &dl](SDValue NewV, SDValue ConVec, unsigned &j) {
9169      EVT NewVT = NewV.getValueType();
9170      EVT ConcatVT = ConVec.getValueType();
9171      unsigned ExtScale = 1;
9172      if (NewVT == MVT::v2f64) {
9173        NewV = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, MVT::v4i32, NewV);
9174        ExtScale = 2;
9175      }
9176      for (unsigned i = 0, e = NewVT.getVectorNumElements(); i < e; i++, j++) {
9177        SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, NewV,
9178                                  DAG.getIntPtrConstant(i * ExtScale, dl));
9179        ConVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ConcatVT, ConVec, Elt,
9180                             DAG.getConstant(j, dl, MVT::i32));
9181      }
9182      return ConVec;
9183    };
9184    unsigned j = 0;
9185    SDValue ConVec = DAG.getNode(ISD::UNDEF, dl, ConcatVT);
9186    ConVec = ExtractInto(NewV1, ConVec, j);
9187    ConVec = ExtractInto(NewV2, ConVec, j);
9188
9189    // Now return the result of comparing the subvector with zero, which will
9190    // generate a real predicate, i.e. v4i1, v8i1 or v16i1.
9191    return DAG.getNode(ARMISD::VCMPZ, dl, VT, ConVec,
9192                       DAG.getConstant(ARMCC::NE, dl, MVT::i32));
9193  };
9194
9195  // Concat each pair of subvectors and pack into the lower half of the array.
9196  SmallVector<SDValue> ConcatOps(Op->op_begin(), Op->op_end());
9197  while (ConcatOps.size() > 1) {
9198    for (unsigned I = 0, E = ConcatOps.size(); I != E; I += 2) {
9199      SDValue V1 = ConcatOps[I];
9200      SDValue V2 = ConcatOps[I + 1];
9201      ConcatOps[I / 2] = ConcatPair(V1, V2);
9202    }
9203    ConcatOps.resize(ConcatOps.size() / 2);
9204  }
9205  return ConcatOps[0];
9206}
9207
9208static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG,
9209                                   const ARMSubtarget *ST) {
9210  EVT VT = Op->getValueType(0);
9211  if (ST->hasMVEIntegerOps() && VT.getScalarSizeInBits() == 1)
9212    return LowerCONCAT_VECTORS_i1(Op, DAG, ST);
9213
9214  // The only time a CONCAT_VECTORS operation can have legal types is when
9215  // two 64-bit vectors are concatenated to a 128-bit vector.
9216  assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
9217         "unexpected CONCAT_VECTORS");
9218  SDLoc dl(Op);
9219  SDValue Val = DAG.getUNDEF(MVT::v2f64);
9220  SDValue Op0 = Op.getOperand(0);
9221  SDValue Op1 = Op.getOperand(1);
9222  if (!Op0.isUndef())
9223    Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
9224                      DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
9225                      DAG.getIntPtrConstant(0, dl));
9226  if (!Op1.isUndef())
9227    Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
9228                      DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
9229                      DAG.getIntPtrConstant(1, dl));
9230  return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
9231}
9232
9233static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG,
9234                                      const ARMSubtarget *ST) {
9235  SDValue V1 = Op.getOperand(0);
9236  SDValue V2 = Op.getOperand(1);
9237  SDLoc dl(Op);
9238  EVT VT = Op.getValueType();
9239  EVT Op1VT = V1.getValueType();
9240  unsigned NumElts = VT.getVectorNumElements();
9241  unsigned Index = V2->getAsZExtVal();
9242
9243  assert(VT.getScalarSizeInBits() == 1 &&
9244         "Unexpected custom EXTRACT_SUBVECTOR lowering");
9245  assert(ST->hasMVEIntegerOps() &&
9246         "EXTRACT_SUBVECTOR lowering only supported for MVE");
9247
9248  SDValue NewV1 = PromoteMVEPredVector(dl, V1, Op1VT, DAG);
9249
9250  // We now have Op1 promoted to a vector of integers, where v8i1 gets
9251  // promoted to v8i16, etc.
9252
9253  MVT ElType = getVectorTyFromPredicateVector(VT).getScalarType().getSimpleVT();
9254
9255  if (NumElts == 2) {
9256    EVT SubVT = MVT::v4i32;
9257    SDValue SubVec = DAG.getNode(ISD::UNDEF, dl, SubVT);
9258    for (unsigned i = Index, j = 0; i < (Index + NumElts); i++, j += 2) {
9259      SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, NewV1,
9260                                DAG.getIntPtrConstant(i, dl));
9261      SubVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, SubVT, SubVec, Elt,
9262                           DAG.getConstant(j, dl, MVT::i32));
9263      SubVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, SubVT, SubVec, Elt,
9264                           DAG.getConstant(j + 1, dl, MVT::i32));
9265    }
9266    SDValue Cmp = DAG.getNode(ARMISD::VCMPZ, dl, MVT::v4i1, SubVec,
9267                              DAG.getConstant(ARMCC::NE, dl, MVT::i32));
9268    return DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::v2i1, Cmp);
9269  }
9270
9271  EVT SubVT = MVT::getVectorVT(ElType, NumElts);
9272  SDValue SubVec = DAG.getNode(ISD::UNDEF, dl, SubVT);
9273  for (unsigned i = Index, j = 0; i < (Index + NumElts); i++, j++) {
9274    SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, NewV1,
9275                              DAG.getIntPtrConstant(i, dl));
9276    SubVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, SubVT, SubVec, Elt,
9277                         DAG.getConstant(j, dl, MVT::i32));
9278  }
9279
9280  // Now return the result of comparing the subvector with zero,
9281  // which will generate a real predicate, i.e. v4i1, v8i1 or v16i1.
9282  return DAG.getNode(ARMISD::VCMPZ, dl, VT, SubVec,
9283                     DAG.getConstant(ARMCC::NE, dl, MVT::i32));
9284}
9285
9286// Turn a truncate into a predicate (an i1 vector) into icmp(and(x, 1), 0).
9287static SDValue LowerTruncatei1(SDNode *N, SelectionDAG &DAG,
9288                               const ARMSubtarget *ST) {
9289  assert(ST->hasMVEIntegerOps() && "Expected MVE!");
9290  EVT VT = N->getValueType(0);
9291  assert((VT == MVT::v16i1 || VT == MVT::v8i1 || VT == MVT::v4i1) &&
9292         "Expected a vector i1 type!");
9293  SDValue Op = N->getOperand(0);
9294  EVT FromVT = Op.getValueType();
9295  SDLoc DL(N);
9296
9297  SDValue And =
9298      DAG.getNode(ISD::AND, DL, FromVT, Op, DAG.getConstant(1, DL, FromVT));
9299  return DAG.getNode(ISD::SETCC, DL, VT, And, DAG.getConstant(0, DL, FromVT),
9300                     DAG.getCondCode(ISD::SETNE));
9301}
9302
9303static SDValue LowerTruncate(SDNode *N, SelectionDAG &DAG,
9304                             const ARMSubtarget *Subtarget) {
9305  if (!Subtarget->hasMVEIntegerOps())
9306    return SDValue();
9307
9308  EVT ToVT = N->getValueType(0);
9309  if (ToVT.getScalarType() == MVT::i1)
9310    return LowerTruncatei1(N, DAG, Subtarget);
9311
9312  // MVE does not have a single instruction to perform the truncation of a v4i32
9313  // into the lower half of a v8i16, in the same way that a NEON vmovn would.
9314  // Most of the instructions in MVE follow the 'Beats' system, where moving
9315  // values from different lanes is usually something that the instructions
9316  // avoid.
9317  //
9318  // Instead it has top/bottom instructions such as VMOVLT/B and VMOVNT/B,
9319  // which take a the top/bottom half of a larger lane and extend it (or do the
9320  // opposite, truncating into the top/bottom lane from a larger lane). Note
9321  // that because of the way we widen lanes, a v4i16 is really a v4i32 using the
9322  // bottom 16bits from each vector lane. This works really well with T/B
9323  // instructions, but that doesn't extend to v8i32->v8i16 where the lanes need
9324  // to move order.
9325  //
9326  // But truncates and sext/zext are always going to be fairly common from llvm.
9327  // We have several options for how to deal with them:
9328  // - Wherever possible combine them into an instruction that makes them
9329  //   "free". This includes loads/stores, which can perform the trunc as part
9330  //   of the memory operation. Or certain shuffles that can be turned into
9331  //   VMOVN/VMOVL.
9332  // - Lane Interleaving to transform blocks surrounded by ext/trunc. So
9333  //   trunc(mul(sext(a), sext(b))) may become
9334  //   VMOVNT(VMUL(VMOVLB(a), VMOVLB(b)), VMUL(VMOVLT(a), VMOVLT(b))). (Which in
9335  //   this case can use VMULL). This is performed in the
9336  //   MVELaneInterleavingPass.
9337  // - Otherwise we have an option. By default we would expand the
9338  //   zext/sext/trunc into a series of lane extract/inserts going via GPR
9339  //   registers. One for each vector lane in the vector. This can obviously be
9340  //   very expensive.
9341  // - The other option is to use the fact that loads/store can extend/truncate
9342  //   to turn a trunc into two truncating stack stores and a stack reload. This
9343  //   becomes 3 back-to-back memory operations, but at least that is less than
9344  //   all the insert/extracts.
9345  //
9346  // In order to do the last, we convert certain trunc's into MVETRUNC, which
9347  // are either optimized where they can be, or eventually lowered into stack
9348  // stores/loads. This prevents us from splitting a v8i16 trunc into two stores
9349  // two early, where other instructions would be better, and stops us from
9350  // having to reconstruct multiple buildvector shuffles into loads/stores.
9351  if (ToVT != MVT::v8i16 && ToVT != MVT::v16i8)
9352    return SDValue();
9353  EVT FromVT = N->getOperand(0).getValueType();
9354  if (FromVT != MVT::v8i32 && FromVT != MVT::v16i16)
9355    return SDValue();
9356
9357  SDValue Lo, Hi;
9358  std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 0);
9359  SDLoc DL(N);
9360  return DAG.getNode(ARMISD::MVETRUNC, DL, ToVT, Lo, Hi);
9361}
9362
9363static SDValue LowerVectorExtend(SDNode *N, SelectionDAG &DAG,
9364                                 const ARMSubtarget *Subtarget) {
9365  if (!Subtarget->hasMVEIntegerOps())
9366    return SDValue();
9367
9368  // See LowerTruncate above for an explanation of MVEEXT/MVETRUNC.
9369
9370  EVT ToVT = N->getValueType(0);
9371  if (ToVT != MVT::v16i32 && ToVT != MVT::v8i32 && ToVT != MVT::v16i16)
9372    return SDValue();
9373  SDValue Op = N->getOperand(0);
9374  EVT FromVT = Op.getValueType();
9375  if (FromVT != MVT::v8i16 && FromVT != MVT::v16i8)
9376    return SDValue();
9377
9378  SDLoc DL(N);
9379  EVT ExtVT = ToVT.getHalfNumVectorElementsVT(*DAG.getContext());
9380  if (ToVT.getScalarType() == MVT::i32 && FromVT.getScalarType() == MVT::i8)
9381    ExtVT = MVT::v8i16;
9382
9383  unsigned Opcode =
9384      N->getOpcode() == ISD::SIGN_EXTEND ? ARMISD::MVESEXT : ARMISD::MVEZEXT;
9385  SDValue Ext = DAG.getNode(Opcode, DL, DAG.getVTList(ExtVT, ExtVT), Op);
9386  SDValue Ext1 = Ext.getValue(1);
9387
9388  if (ToVT.getScalarType() == MVT::i32 && FromVT.getScalarType() == MVT::i8) {
9389    Ext = DAG.getNode(N->getOpcode(), DL, MVT::v8i32, Ext);
9390    Ext1 = DAG.getNode(N->getOpcode(), DL, MVT::v8i32, Ext1);
9391  }
9392
9393  return DAG.getNode(ISD::CONCAT_VECTORS, DL, ToVT, Ext, Ext1);
9394}
9395
9396/// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
9397/// element has been zero/sign-extended, depending on the isSigned parameter,
9398/// from an integer type half its size.
9399static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
9400                                   bool isSigned) {
9401  // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
9402  EVT VT = N->getValueType(0);
9403  if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
9404    SDNode *BVN = N->getOperand(0).getNode();
9405    if (BVN->getValueType(0) != MVT::v4i32 ||
9406        BVN->getOpcode() != ISD::BUILD_VECTOR)
9407      return false;
9408    unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
9409    unsigned HiElt = 1 - LoElt;
9410    ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
9411    ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
9412    ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
9413    ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
9414    if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
9415      return false;
9416    if (isSigned) {
9417      if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
9418          Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
9419        return true;
9420    } else {
9421      if (Hi0->isZero() && Hi1->isZero())
9422        return true;
9423    }
9424    return false;
9425  }
9426
9427  if (N->getOpcode() != ISD::BUILD_VECTOR)
9428    return false;
9429
9430  for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
9431    SDNode *Elt = N->getOperand(i).getNode();
9432    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
9433      unsigned EltSize = VT.getScalarSizeInBits();
9434      unsigned HalfSize = EltSize / 2;
9435      if (isSigned) {
9436        if (!isIntN(HalfSize, C->getSExtValue()))
9437          return false;
9438      } else {
9439        if (!isUIntN(HalfSize, C->getZExtValue()))
9440          return false;
9441      }
9442      continue;
9443    }
9444    return false;
9445  }
9446
9447  return true;
9448}
9449
9450/// isSignExtended - Check if a node is a vector value that is sign-extended
9451/// or a constant BUILD_VECTOR with sign-extended elements.
9452static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
9453  if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
9454    return true;
9455  if (isExtendedBUILD_VECTOR(N, DAG, true))
9456    return true;
9457  return false;
9458}
9459
9460/// isZeroExtended - Check if a node is a vector value that is zero-extended (or
9461/// any-extended) or a constant BUILD_VECTOR with zero-extended elements.
9462static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
9463  if (N->getOpcode() == ISD::ZERO_EXTEND || N->getOpcode() == ISD::ANY_EXTEND ||
9464      ISD::isZEXTLoad(N))
9465    return true;
9466  if (isExtendedBUILD_VECTOR(N, DAG, false))
9467    return true;
9468  return false;
9469}
9470
9471static EVT getExtensionTo64Bits(const EVT &OrigVT) {
9472  if (OrigVT.getSizeInBits() >= 64)
9473    return OrigVT;
9474
9475  assert(OrigVT.isSimple() && "Expecting a simple value type");
9476
9477  MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
9478  switch (OrigSimpleTy) {
9479  default: llvm_unreachable("Unexpected Vector Type");
9480  case MVT::v2i8:
9481  case MVT::v2i16:
9482     return MVT::v2i32;
9483  case MVT::v4i8:
9484    return  MVT::v4i16;
9485  }
9486}
9487
9488/// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
9489/// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
9490/// We insert the required extension here to get the vector to fill a D register.
9491static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
9492                                            const EVT &OrigTy,
9493                                            const EVT &ExtTy,
9494                                            unsigned ExtOpcode) {
9495  // The vector originally had a size of OrigTy. It was then extended to ExtTy.
9496  // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
9497  // 64-bits we need to insert a new extension so that it will be 64-bits.
9498  assert(ExtTy.is128BitVector() && "Unexpected extension size");
9499  if (OrigTy.getSizeInBits() >= 64)
9500    return N;
9501
9502  // Must extend size to at least 64 bits to be used as an operand for VMULL.
9503  EVT NewVT = getExtensionTo64Bits(OrigTy);
9504
9505  return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
9506}
9507
9508/// SkipLoadExtensionForVMULL - return a load of the original vector size that
9509/// does not do any sign/zero extension. If the original vector is less
9510/// than 64 bits, an appropriate extension will be added after the load to
9511/// reach a total size of 64 bits. We have to add the extension separately
9512/// because ARM does not have a sign/zero extending load for vectors.
9513static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
9514  EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
9515
9516  // The load already has the right type.
9517  if (ExtendedTy == LD->getMemoryVT())
9518    return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
9519                       LD->getBasePtr(), LD->getPointerInfo(), LD->getAlign(),
9520                       LD->getMemOperand()->getFlags());
9521
9522  // We need to create a zextload/sextload. We cannot just create a load
9523  // followed by a zext/zext node because LowerMUL is also run during normal
9524  // operation legalization where we can't create illegal types.
9525  return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
9526                        LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
9527                        LD->getMemoryVT(), LD->getAlign(),
9528                        LD->getMemOperand()->getFlags());
9529}
9530
9531/// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
9532/// ANY_EXTEND, extending load, or BUILD_VECTOR with extended elements, return
9533/// the unextended value. The unextended vector should be 64 bits so that it can
9534/// be used as an operand to a VMULL instruction. If the original vector size
9535/// before extension is less than 64 bits we add a an extension to resize
9536/// the vector to 64 bits.
9537static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
9538  if (N->getOpcode() == ISD::SIGN_EXTEND ||
9539      N->getOpcode() == ISD::ZERO_EXTEND || N->getOpcode() == ISD::ANY_EXTEND)
9540    return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
9541                                        N->getOperand(0)->getValueType(0),
9542                                        N->getValueType(0),
9543                                        N->getOpcode());
9544
9545  if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9546    assert((ISD::isSEXTLoad(LD) || ISD::isZEXTLoad(LD)) &&
9547           "Expected extending load");
9548
9549    SDValue newLoad = SkipLoadExtensionForVMULL(LD, DAG);
9550    DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), newLoad.getValue(1));
9551    unsigned Opcode = ISD::isSEXTLoad(LD) ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
9552    SDValue extLoad =
9553        DAG.getNode(Opcode, SDLoc(newLoad), LD->getValueType(0), newLoad);
9554    DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 0), extLoad);
9555
9556    return newLoad;
9557  }
9558
9559  // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
9560  // have been legalized as a BITCAST from v4i32.
9561  if (N->getOpcode() == ISD::BITCAST) {
9562    SDNode *BVN = N->getOperand(0).getNode();
9563    assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
9564           BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
9565    unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
9566    return DAG.getBuildVector(
9567        MVT::v2i32, SDLoc(N),
9568        {BVN->getOperand(LowElt), BVN->getOperand(LowElt + 2)});
9569  }
9570  // Construct a new BUILD_VECTOR with elements truncated to half the size.
9571  assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
9572  EVT VT = N->getValueType(0);
9573  unsigned EltSize = VT.getScalarSizeInBits() / 2;
9574  unsigned NumElts = VT.getVectorNumElements();
9575  MVT TruncVT = MVT::getIntegerVT(EltSize);
9576  SmallVector<SDValue, 8> Ops;
9577  SDLoc dl(N);
9578  for (unsigned i = 0; i != NumElts; ++i) {
9579    const APInt &CInt = N->getConstantOperandAPInt(i);
9580    // Element types smaller than 32 bits are not legal, so use i32 elements.
9581    // The values are implicitly truncated so sext vs. zext doesn't matter.
9582    Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
9583  }
9584  return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops);
9585}
9586
9587static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
9588  unsigned Opcode = N->getOpcode();
9589  if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
9590    SDNode *N0 = N->getOperand(0).getNode();
9591    SDNode *N1 = N->getOperand(1).getNode();
9592    return N0->hasOneUse() && N1->hasOneUse() &&
9593      isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
9594  }
9595  return false;
9596}
9597
9598static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
9599  unsigned Opcode = N->getOpcode();
9600  if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
9601    SDNode *N0 = N->getOperand(0).getNode();
9602    SDNode *N1 = N->getOperand(1).getNode();
9603    return N0->hasOneUse() && N1->hasOneUse() &&
9604      isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
9605  }
9606  return false;
9607}
9608
9609static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
9610  // Multiplications are only custom-lowered for 128-bit vectors so that
9611  // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
9612  EVT VT = Op.getValueType();
9613  assert(VT.is128BitVector() && VT.isInteger() &&
9614         "unexpected type for custom-lowering ISD::MUL");
9615  SDNode *N0 = Op.getOperand(0).getNode();
9616  SDNode *N1 = Op.getOperand(1).getNode();
9617  unsigned NewOpc = 0;
9618  bool isMLA = false;
9619  bool isN0SExt = isSignExtended(N0, DAG);
9620  bool isN1SExt = isSignExtended(N1, DAG);
9621  if (isN0SExt && isN1SExt)
9622    NewOpc = ARMISD::VMULLs;
9623  else {
9624    bool isN0ZExt = isZeroExtended(N0, DAG);
9625    bool isN1ZExt = isZeroExtended(N1, DAG);
9626    if (isN0ZExt && isN1ZExt)
9627      NewOpc = ARMISD::VMULLu;
9628    else if (isN1SExt || isN1ZExt) {
9629      // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
9630      // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
9631      if (isN1SExt && isAddSubSExt(N0, DAG)) {
9632        NewOpc = ARMISD::VMULLs;
9633        isMLA = true;
9634      } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
9635        NewOpc = ARMISD::VMULLu;
9636        isMLA = true;
9637      } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
9638        std::swap(N0, N1);
9639        NewOpc = ARMISD::VMULLu;
9640        isMLA = true;
9641      }
9642    }
9643
9644    if (!NewOpc) {
9645      if (VT == MVT::v2i64)
9646        // Fall through to expand this.  It is not legal.
9647        return SDValue();
9648      else
9649        // Other vector multiplications are legal.
9650        return Op;
9651    }
9652  }
9653
9654  // Legalize to a VMULL instruction.
9655  SDLoc DL(Op);
9656  SDValue Op0;
9657  SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
9658  if (!isMLA) {
9659    Op0 = SkipExtensionForVMULL(N0, DAG);
9660    assert(Op0.getValueType().is64BitVector() &&
9661           Op1.getValueType().is64BitVector() &&
9662           "unexpected types for extended operands to VMULL");
9663    return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
9664  }
9665
9666  // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
9667  // isel lowering to take advantage of no-stall back to back vmul + vmla.
9668  //   vmull q0, d4, d6
9669  //   vmlal q0, d5, d6
9670  // is faster than
9671  //   vaddl q0, d4, d5
9672  //   vmovl q1, d6
9673  //   vmul  q0, q0, q1
9674  SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
9675  SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
9676  EVT Op1VT = Op1.getValueType();
9677  return DAG.getNode(N0->getOpcode(), DL, VT,
9678                     DAG.getNode(NewOpc, DL, VT,
9679                               DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
9680                     DAG.getNode(NewOpc, DL, VT,
9681                               DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
9682}
9683
9684static SDValue LowerSDIV_v4i8(SDValue X, SDValue Y, const SDLoc &dl,
9685                              SelectionDAG &DAG) {
9686  // TODO: Should this propagate fast-math-flags?
9687
9688  // Convert to float
9689  // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
9690  // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
9691  X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
9692  Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
9693  X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
9694  Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
9695  // Get reciprocal estimate.
9696  // float4 recip = vrecpeq_f32(yf);
9697  Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
9698                   DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
9699                   Y);
9700  // Because char has a smaller range than uchar, we can actually get away
9701  // without any newton steps.  This requires that we use a weird bias
9702  // of 0xb000, however (again, this has been exhaustively tested).
9703  // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
9704  X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
9705  X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
9706  Y = DAG.getConstant(0xb000, dl, MVT::v4i32);
9707  X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
9708  X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
9709  // Convert back to short.
9710  X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
9711  X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
9712  return X;
9713}
9714
9715static SDValue LowerSDIV_v4i16(SDValue N0, SDValue N1, const SDLoc &dl,
9716                               SelectionDAG &DAG) {
9717  // TODO: Should this propagate fast-math-flags?
9718
9719  SDValue N2;
9720  // Convert to float.
9721  // float4 yf = vcvt_f32_s32(vmovl_s16(y));
9722  // float4 xf = vcvt_f32_s32(vmovl_s16(x));
9723  N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
9724  N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
9725  N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
9726  N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
9727
9728  // Use reciprocal estimate and one refinement step.
9729  // float4 recip = vrecpeq_f32(yf);
9730  // recip *= vrecpsq_f32(yf, recip);
9731  N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
9732                   DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
9733                   N1);
9734  N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
9735                   DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
9736                   N1, N2);
9737  N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
9738  // Because short has a smaller range than ushort, we can actually get away
9739  // with only a single newton step.  This requires that we use a weird bias
9740  // of 89, however (again, this has been exhaustively tested).
9741  // float4 result = as_float4(as_int4(xf*recip) + 0x89);
9742  N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
9743  N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
9744  N1 = DAG.getConstant(0x89, dl, MVT::v4i32);
9745  N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
9746  N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
9747  // Convert back to integer and return.
9748  // return vmovn_s32(vcvt_s32_f32(result));
9749  N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
9750  N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
9751  return N0;
9752}
9753
9754static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG,
9755                         const ARMSubtarget *ST) {
9756  EVT VT = Op.getValueType();
9757  assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
9758         "unexpected type for custom-lowering ISD::SDIV");
9759
9760  SDLoc dl(Op);
9761  SDValue N0 = Op.getOperand(0);
9762  SDValue N1 = Op.getOperand(1);
9763  SDValue N2, N3;
9764
9765  if (VT == MVT::v8i8) {
9766    N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
9767    N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
9768
9769    N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
9770                     DAG.getIntPtrConstant(4, dl));
9771    N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
9772                     DAG.getIntPtrConstant(4, dl));
9773    N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
9774                     DAG.getIntPtrConstant(0, dl));
9775    N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
9776                     DAG.getIntPtrConstant(0, dl));
9777
9778    N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
9779    N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
9780
9781    N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
9782    N0 = LowerCONCAT_VECTORS(N0, DAG, ST);
9783
9784    N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
9785    return N0;
9786  }
9787  return LowerSDIV_v4i16(N0, N1, dl, DAG);
9788}
9789
9790static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG,
9791                         const ARMSubtarget *ST) {
9792  // TODO: Should this propagate fast-math-flags?
9793  EVT VT = Op.getValueType();
9794  assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
9795         "unexpected type for custom-lowering ISD::UDIV");
9796
9797  SDLoc dl(Op);
9798  SDValue N0 = Op.getOperand(0);
9799  SDValue N1 = Op.getOperand(1);
9800  SDValue N2, N3;
9801
9802  if (VT == MVT::v8i8) {
9803    N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
9804    N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
9805
9806    N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
9807                     DAG.getIntPtrConstant(4, dl));
9808    N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
9809                     DAG.getIntPtrConstant(4, dl));
9810    N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
9811                     DAG.getIntPtrConstant(0, dl));
9812    N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
9813                     DAG.getIntPtrConstant(0, dl));
9814
9815    N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
9816    N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
9817
9818    N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
9819    N0 = LowerCONCAT_VECTORS(N0, DAG, ST);
9820
9821    N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
9822                     DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl,
9823                                     MVT::i32),
9824                     N0);
9825    return N0;
9826  }
9827
9828  // v4i16 sdiv ... Convert to float.
9829  // float4 yf = vcvt_f32_s32(vmovl_u16(y));
9830  // float4 xf = vcvt_f32_s32(vmovl_u16(x));
9831  N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
9832  N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
9833  N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
9834  SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
9835
9836  // Use reciprocal estimate and two refinement steps.
9837  // float4 recip = vrecpeq_f32(yf);
9838  // recip *= vrecpsq_f32(yf, recip);
9839  // recip *= vrecpsq_f32(yf, recip);
9840  N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
9841                   DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
9842                   BN1);
9843  N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
9844                   DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
9845                   BN1, N2);
9846  N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
9847  N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
9848                   DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
9849                   BN1, N2);
9850  N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
9851  // Simply multiplying by the reciprocal estimate can leave us a few ulps
9852  // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
9853  // and that it will never cause us to return an answer too large).
9854  // float4 result = as_float4(as_int4(xf*recip) + 2);
9855  N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
9856  N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
9857  N1 = DAG.getConstant(2, dl, MVT::v4i32);
9858  N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
9859  N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
9860  // Convert back to integer and return.
9861  // return vmovn_u32(vcvt_s32_f32(result));
9862  N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
9863  N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
9864  return N0;
9865}
9866
9867static SDValue LowerUADDSUBO_CARRY(SDValue Op, SelectionDAG &DAG) {
9868  SDNode *N = Op.getNode();
9869  EVT VT = N->getValueType(0);
9870  SDVTList VTs = DAG.getVTList(VT, MVT::i32);
9871
9872  SDValue Carry = Op.getOperand(2);
9873
9874  SDLoc DL(Op);
9875
9876  SDValue Result;
9877  if (Op.getOpcode() == ISD::UADDO_CARRY) {
9878    // This converts the boolean value carry into the carry flag.
9879    Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG);
9880
9881    // Do the addition proper using the carry flag we wanted.
9882    Result = DAG.getNode(ARMISD::ADDE, DL, VTs, Op.getOperand(0),
9883                         Op.getOperand(1), Carry);
9884
9885    // Now convert the carry flag into a boolean value.
9886    Carry = ConvertCarryFlagToBooleanCarry(Result.getValue(1), VT, DAG);
9887  } else {
9888    // ARMISD::SUBE expects a carry not a borrow like ISD::USUBO_CARRY so we
9889    // have to invert the carry first.
9890    Carry = DAG.getNode(ISD::SUB, DL, MVT::i32,
9891                        DAG.getConstant(1, DL, MVT::i32), Carry);
9892    // This converts the boolean value carry into the carry flag.
9893    Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG);
9894
9895    // Do the subtraction proper using the carry flag we wanted.
9896    Result = DAG.getNode(ARMISD::SUBE, DL, VTs, Op.getOperand(0),
9897                         Op.getOperand(1), Carry);
9898
9899    // Now convert the carry flag into a boolean value.
9900    Carry = ConvertCarryFlagToBooleanCarry(Result.getValue(1), VT, DAG);
9901    // But the carry returned by ARMISD::SUBE is not a borrow as expected
9902    // by ISD::USUBO_CARRY, so compute 1 - C.
9903    Carry = DAG.getNode(ISD::SUB, DL, MVT::i32,
9904                        DAG.getConstant(1, DL, MVT::i32), Carry);
9905  }
9906
9907  // Return both values.
9908  return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Result, Carry);
9909}
9910
9911SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
9912  assert(Subtarget->isTargetDarwin());
9913
9914  // For iOS, we want to call an alternative entry point: __sincos_stret,
9915  // return values are passed via sret.
9916  SDLoc dl(Op);
9917  SDValue Arg = Op.getOperand(0);
9918  EVT ArgVT = Arg.getValueType();
9919  Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
9920  auto PtrVT = getPointerTy(DAG.getDataLayout());
9921
9922  MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
9923  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9924
9925  // Pair of floats / doubles used to pass the result.
9926  Type *RetTy = StructType::get(ArgTy, ArgTy);
9927  auto &DL = DAG.getDataLayout();
9928
9929  ArgListTy Args;
9930  bool ShouldUseSRet = Subtarget->isAPCS_ABI();
9931  SDValue SRet;
9932  if (ShouldUseSRet) {
9933    // Create stack object for sret.
9934    const uint64_t ByteSize = DL.getTypeAllocSize(RetTy);
9935    const Align StackAlign = DL.getPrefTypeAlign(RetTy);
9936    int FrameIdx = MFI.CreateStackObject(ByteSize, StackAlign, false);
9937    SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy(DL));
9938
9939    ArgListEntry Entry;
9940    Entry.Node = SRet;
9941    Entry.Ty = PointerType::getUnqual(RetTy->getContext());
9942    Entry.IsSExt = false;
9943    Entry.IsZExt = false;
9944    Entry.IsSRet = true;
9945    Args.push_back(Entry);
9946    RetTy = Type::getVoidTy(*DAG.getContext());
9947  }
9948
9949  ArgListEntry Entry;
9950  Entry.Node = Arg;
9951  Entry.Ty = ArgTy;
9952  Entry.IsSExt = false;
9953  Entry.IsZExt = false;
9954  Args.push_back(Entry);
9955
9956  RTLIB::Libcall LC =
9957      (ArgVT == MVT::f64) ? RTLIB::SINCOS_STRET_F64 : RTLIB::SINCOS_STRET_F32;
9958  const char *LibcallName = getLibcallName(LC);
9959  CallingConv::ID CC = getLibcallCallingConv(LC);
9960  SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DL));
9961
9962  TargetLowering::CallLoweringInfo CLI(DAG);
9963  CLI.setDebugLoc(dl)
9964      .setChain(DAG.getEntryNode())
9965      .setCallee(CC, RetTy, Callee, std::move(Args))
9966      .setDiscardResult(ShouldUseSRet);
9967  std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
9968
9969  if (!ShouldUseSRet)
9970    return CallResult.first;
9971
9972  SDValue LoadSin =
9973      DAG.getLoad(ArgVT, dl, CallResult.second, SRet, MachinePointerInfo());
9974
9975  // Address of cos field.
9976  SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, SRet,
9977                            DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl));
9978  SDValue LoadCos =
9979      DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add, MachinePointerInfo());
9980
9981  SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
9982  return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
9983                     LoadSin.getValue(0), LoadCos.getValue(0));
9984}
9985
9986SDValue ARMTargetLowering::LowerWindowsDIVLibCall(SDValue Op, SelectionDAG &DAG,
9987                                                  bool Signed,
9988                                                  SDValue &Chain) const {
9989  EVT VT = Op.getValueType();
9990  assert((VT == MVT::i32 || VT == MVT::i64) &&
9991         "unexpected type for custom lowering DIV");
9992  SDLoc dl(Op);
9993
9994  const auto &DL = DAG.getDataLayout();
9995  const auto &TLI = DAG.getTargetLoweringInfo();
9996
9997  const char *Name = nullptr;
9998  if (Signed)
9999    Name = (VT == MVT::i32) ? "__rt_sdiv" : "__rt_sdiv64";
10000  else
10001    Name = (VT == MVT::i32) ? "__rt_udiv" : "__rt_udiv64";
10002
10003  SDValue ES = DAG.getExternalSymbol(Name, TLI.getPointerTy(DL));
10004
10005  ARMTargetLowering::ArgListTy Args;
10006
10007  for (auto AI : {1, 0}) {
10008    ArgListEntry Arg;
10009    Arg.Node = Op.getOperand(AI);
10010    Arg.Ty = Arg.Node.getValueType().getTypeForEVT(*DAG.getContext());
10011    Args.push_back(Arg);
10012  }
10013
10014  CallLoweringInfo CLI(DAG);
10015  CLI.setDebugLoc(dl)
10016    .setChain(Chain)
10017    .setCallee(CallingConv::ARM_AAPCS_VFP, VT.getTypeForEVT(*DAG.getContext()),
10018               ES, std::move(Args));
10019
10020  return LowerCallTo(CLI).first;
10021}
10022
10023// This is a code size optimisation: return the original SDIV node to
10024// DAGCombiner when we don't want to expand SDIV into a sequence of
10025// instructions, and an empty node otherwise which will cause the
10026// SDIV to be expanded in DAGCombine.
10027SDValue
10028ARMTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
10029                                 SelectionDAG &DAG,
10030                                 SmallVectorImpl<SDNode *> &Created) const {
10031  // TODO: Support SREM
10032  if (N->getOpcode() != ISD::SDIV)
10033    return SDValue();
10034
10035  const auto &ST = DAG.getSubtarget<ARMSubtarget>();
10036  const bool MinSize = ST.hasMinSize();
10037  const bool HasDivide = ST.isThumb() ? ST.hasDivideInThumbMode()
10038                                      : ST.hasDivideInARMMode();
10039
10040  // Don't touch vector types; rewriting this may lead to scalarizing
10041  // the int divs.
10042  if (N->getOperand(0).getValueType().isVector())
10043    return SDValue();
10044
10045  // Bail if MinSize is not set, and also for both ARM and Thumb mode we need
10046  // hwdiv support for this to be really profitable.
10047  if (!(MinSize && HasDivide))
10048    return SDValue();
10049
10050  // ARM mode is a bit simpler than Thumb: we can handle large power
10051  // of 2 immediates with 1 mov instruction; no further checks required,
10052  // just return the sdiv node.
10053  if (!ST.isThumb())
10054    return SDValue(N, 0);
10055
10056  // In Thumb mode, immediates larger than 128 need a wide 4-byte MOV,
10057  // and thus lose the code size benefits of a MOVS that requires only 2.
10058  // TargetTransformInfo and 'getIntImmCodeSizeCost' could be helpful here,
10059  // but as it's doing exactly this, it's not worth the trouble to get TTI.
10060  if (Divisor.sgt(128))
10061    return SDValue();
10062
10063  return SDValue(N, 0);
10064}
10065
10066SDValue ARMTargetLowering::LowerDIV_Windows(SDValue Op, SelectionDAG &DAG,
10067                                            bool Signed) const {
10068  assert(Op.getValueType() == MVT::i32 &&
10069         "unexpected type for custom lowering DIV");
10070  SDLoc dl(Op);
10071
10072  SDValue DBZCHK = DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other,
10073                               DAG.getEntryNode(), Op.getOperand(1));
10074
10075  return LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
10076}
10077
10078static SDValue WinDBZCheckDenominator(SelectionDAG &DAG, SDNode *N, SDValue InChain) {
10079  SDLoc DL(N);
10080  SDValue Op = N->getOperand(1);
10081  if (N->getValueType(0) == MVT::i32)
10082    return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain, Op);
10083  SDValue Lo, Hi;
10084  std::tie(Lo, Hi) = DAG.SplitScalar(Op, DL, MVT::i32, MVT::i32);
10085  return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain,
10086                     DAG.getNode(ISD::OR, DL, MVT::i32, Lo, Hi));
10087}
10088
10089void ARMTargetLowering::ExpandDIV_Windows(
10090    SDValue Op, SelectionDAG &DAG, bool Signed,
10091    SmallVectorImpl<SDValue> &Results) const {
10092  const auto &DL = DAG.getDataLayout();
10093  const auto &TLI = DAG.getTargetLoweringInfo();
10094
10095  assert(Op.getValueType() == MVT::i64 &&
10096         "unexpected type for custom lowering DIV");
10097  SDLoc dl(Op);
10098
10099  SDValue DBZCHK = WinDBZCheckDenominator(DAG, Op.getNode(), DAG.getEntryNode());
10100
10101  SDValue Result = LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
10102
10103  SDValue Lower = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Result);
10104  SDValue Upper = DAG.getNode(ISD::SRL, dl, MVT::i64, Result,
10105                              DAG.getConstant(32, dl, TLI.getPointerTy(DL)));
10106  Upper = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Upper);
10107
10108  Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lower, Upper));
10109}
10110
10111static SDValue LowerPredicateLoad(SDValue Op, SelectionDAG &DAG) {
10112  LoadSDNode *LD = cast<LoadSDNode>(Op.getNode());
10113  EVT MemVT = LD->getMemoryVT();
10114  assert((MemVT == MVT::v2i1 || MemVT == MVT::v4i1 || MemVT == MVT::v8i1 ||
10115          MemVT == MVT::v16i1) &&
10116         "Expected a predicate type!");
10117  assert(MemVT == Op.getValueType());
10118  assert(LD->getExtensionType() == ISD::NON_EXTLOAD &&
10119         "Expected a non-extending load");
10120  assert(LD->isUnindexed() && "Expected a unindexed load");
10121
10122  // The basic MVE VLDR on a v2i1/v4i1/v8i1 actually loads the entire 16bit
10123  // predicate, with the "v4i1" bits spread out over the 16 bits loaded. We
10124  // need to make sure that 8/4/2 bits are actually loaded into the correct
10125  // place, which means loading the value and then shuffling the values into
10126  // the bottom bits of the predicate.
10127  // Equally, VLDR for an v16i1 will actually load 32bits (so will be incorrect
10128  // for BE).
10129  // Speaking of BE, apparently the rest of llvm will assume a reverse order to
10130  // a natural VMSR(load), so needs to be reversed.
10131
10132  SDLoc dl(Op);
10133  SDValue Load = DAG.getExtLoad(
10134      ISD::EXTLOAD, dl, MVT::i32, LD->getChain(), LD->getBasePtr(),
10135      EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits()),
10136      LD->getMemOperand());
10137  SDValue Val = Load;
10138  if (DAG.getDataLayout().isBigEndian())
10139    Val = DAG.getNode(ISD::SRL, dl, MVT::i32,
10140                      DAG.getNode(ISD::BITREVERSE, dl, MVT::i32, Load),
10141                      DAG.getConstant(32 - MemVT.getSizeInBits(), dl, MVT::i32));
10142  SDValue Pred = DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::v16i1, Val);
10143  if (MemVT != MVT::v16i1)
10144    Pred = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MemVT, Pred,
10145                       DAG.getConstant(0, dl, MVT::i32));
10146  return DAG.getMergeValues({Pred, Load.getValue(1)}, dl);
10147}
10148
10149void ARMTargetLowering::LowerLOAD(SDNode *N, SmallVectorImpl<SDValue> &Results,
10150                                  SelectionDAG &DAG) const {
10151  LoadSDNode *LD = cast<LoadSDNode>(N);
10152  EVT MemVT = LD->getMemoryVT();
10153  assert(LD->isUnindexed() && "Loads should be unindexed at this point.");
10154
10155  if (MemVT == MVT::i64 && Subtarget->hasV5TEOps() &&
10156      !Subtarget->isThumb1Only() && LD->isVolatile() &&
10157      LD->getAlign() >= Subtarget->getDualLoadStoreAlignment()) {
10158    SDLoc dl(N);
10159    SDValue Result = DAG.getMemIntrinsicNode(
10160        ARMISD::LDRD, dl, DAG.getVTList({MVT::i32, MVT::i32, MVT::Other}),
10161        {LD->getChain(), LD->getBasePtr()}, MemVT, LD->getMemOperand());
10162    SDValue Lo = Result.getValue(DAG.getDataLayout().isLittleEndian() ? 0 : 1);
10163    SDValue Hi = Result.getValue(DAG.getDataLayout().isLittleEndian() ? 1 : 0);
10164    SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
10165    Results.append({Pair, Result.getValue(2)});
10166  }
10167}
10168
10169static SDValue LowerPredicateStore(SDValue Op, SelectionDAG &DAG) {
10170  StoreSDNode *ST = cast<StoreSDNode>(Op.getNode());
10171  EVT MemVT = ST->getMemoryVT();
10172  assert((MemVT == MVT::v2i1 || MemVT == MVT::v4i1 || MemVT == MVT::v8i1 ||
10173          MemVT == MVT::v16i1) &&
10174         "Expected a predicate type!");
10175  assert(MemVT == ST->getValue().getValueType());
10176  assert(!ST->isTruncatingStore() && "Expected a non-extending store");
10177  assert(ST->isUnindexed() && "Expected a unindexed store");
10178
10179  // Only store the v2i1 or v4i1 or v8i1 worth of bits, via a buildvector with
10180  // top bits unset and a scalar store.
10181  SDLoc dl(Op);
10182  SDValue Build = ST->getValue();
10183  if (MemVT != MVT::v16i1) {
10184    SmallVector<SDValue, 16> Ops;
10185    for (unsigned I = 0; I < MemVT.getVectorNumElements(); I++) {
10186      unsigned Elt = DAG.getDataLayout().isBigEndian()
10187                         ? MemVT.getVectorNumElements() - I - 1
10188                         : I;
10189      Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, Build,
10190                                DAG.getConstant(Elt, dl, MVT::i32)));
10191    }
10192    for (unsigned I = MemVT.getVectorNumElements(); I < 16; I++)
10193      Ops.push_back(DAG.getUNDEF(MVT::i32));
10194    Build = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i1, Ops);
10195  }
10196  SDValue GRP = DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, Build);
10197  if (MemVT == MVT::v16i1 && DAG.getDataLayout().isBigEndian())
10198    GRP = DAG.getNode(ISD::SRL, dl, MVT::i32,
10199                      DAG.getNode(ISD::BITREVERSE, dl, MVT::i32, GRP),
10200                      DAG.getConstant(16, dl, MVT::i32));
10201  return DAG.getTruncStore(
10202      ST->getChain(), dl, GRP, ST->getBasePtr(),
10203      EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits()),
10204      ST->getMemOperand());
10205}
10206
10207static SDValue LowerSTORE(SDValue Op, SelectionDAG &DAG,
10208                          const ARMSubtarget *Subtarget) {
10209  StoreSDNode *ST = cast<StoreSDNode>(Op.getNode());
10210  EVT MemVT = ST->getMemoryVT();
10211  assert(ST->isUnindexed() && "Stores should be unindexed at this point.");
10212
10213  if (MemVT == MVT::i64 && Subtarget->hasV5TEOps() &&
10214      !Subtarget->isThumb1Only() && ST->isVolatile() &&
10215      ST->getAlign() >= Subtarget->getDualLoadStoreAlignment()) {
10216    SDNode *N = Op.getNode();
10217    SDLoc dl(N);
10218
10219    SDValue Lo = DAG.getNode(
10220        ISD::EXTRACT_ELEMENT, dl, MVT::i32, ST->getValue(),
10221        DAG.getTargetConstant(DAG.getDataLayout().isLittleEndian() ? 0 : 1, dl,
10222                              MVT::i32));
10223    SDValue Hi = DAG.getNode(
10224        ISD::EXTRACT_ELEMENT, dl, MVT::i32, ST->getValue(),
10225        DAG.getTargetConstant(DAG.getDataLayout().isLittleEndian() ? 1 : 0, dl,
10226                              MVT::i32));
10227
10228    return DAG.getMemIntrinsicNode(ARMISD::STRD, dl, DAG.getVTList(MVT::Other),
10229                                   {ST->getChain(), Lo, Hi, ST->getBasePtr()},
10230                                   MemVT, ST->getMemOperand());
10231  } else if (Subtarget->hasMVEIntegerOps() &&
10232             ((MemVT == MVT::v2i1 || MemVT == MVT::v4i1 || MemVT == MVT::v8i1 ||
10233               MemVT == MVT::v16i1))) {
10234    return LowerPredicateStore(Op, DAG);
10235  }
10236
10237  return SDValue();
10238}
10239
10240static bool isZeroVector(SDValue N) {
10241  return (ISD::isBuildVectorAllZeros(N.getNode()) ||
10242          (N->getOpcode() == ARMISD::VMOVIMM &&
10243           isNullConstant(N->getOperand(0))));
10244}
10245
10246static SDValue LowerMLOAD(SDValue Op, SelectionDAG &DAG) {
10247  MaskedLoadSDNode *N = cast<MaskedLoadSDNode>(Op.getNode());
10248  MVT VT = Op.getSimpleValueType();
10249  SDValue Mask = N->getMask();
10250  SDValue PassThru = N->getPassThru();
10251  SDLoc dl(Op);
10252
10253  if (isZeroVector(PassThru))
10254    return Op;
10255
10256  // MVE Masked loads use zero as the passthru value. Here we convert undef to
10257  // zero too, and other values are lowered to a select.
10258  SDValue ZeroVec = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
10259                                DAG.getTargetConstant(0, dl, MVT::i32));
10260  SDValue NewLoad = DAG.getMaskedLoad(
10261      VT, dl, N->getChain(), N->getBasePtr(), N->getOffset(), Mask, ZeroVec,
10262      N->getMemoryVT(), N->getMemOperand(), N->getAddressingMode(),
10263      N->getExtensionType(), N->isExpandingLoad());
10264  SDValue Combo = NewLoad;
10265  bool PassThruIsCastZero = (PassThru.getOpcode() == ISD::BITCAST ||
10266                             PassThru.getOpcode() == ARMISD::VECTOR_REG_CAST) &&
10267                            isZeroVector(PassThru->getOperand(0));
10268  if (!PassThru.isUndef() && !PassThruIsCastZero)
10269    Combo = DAG.getNode(ISD::VSELECT, dl, VT, Mask, NewLoad, PassThru);
10270  return DAG.getMergeValues({Combo, NewLoad.getValue(1)}, dl);
10271}
10272
10273static SDValue LowerVecReduce(SDValue Op, SelectionDAG &DAG,
10274                              const ARMSubtarget *ST) {
10275  if (!ST->hasMVEIntegerOps())
10276    return SDValue();
10277
10278  SDLoc dl(Op);
10279  unsigned BaseOpcode = 0;
10280  switch (Op->getOpcode()) {
10281  default: llvm_unreachable("Expected VECREDUCE opcode");
10282  case ISD::VECREDUCE_FADD: BaseOpcode = ISD::FADD; break;
10283  case ISD::VECREDUCE_FMUL: BaseOpcode = ISD::FMUL; break;
10284  case ISD::VECREDUCE_MUL:  BaseOpcode = ISD::MUL; break;
10285  case ISD::VECREDUCE_AND:  BaseOpcode = ISD::AND; break;
10286  case ISD::VECREDUCE_OR:   BaseOpcode = ISD::OR; break;
10287  case ISD::VECREDUCE_XOR:  BaseOpcode = ISD::XOR; break;
10288  case ISD::VECREDUCE_FMAX: BaseOpcode = ISD::FMAXNUM; break;
10289  case ISD::VECREDUCE_FMIN: BaseOpcode = ISD::FMINNUM; break;
10290  }
10291
10292  SDValue Op0 = Op->getOperand(0);
10293  EVT VT = Op0.getValueType();
10294  EVT EltVT = VT.getVectorElementType();
10295  unsigned NumElts = VT.getVectorNumElements();
10296  unsigned NumActiveLanes = NumElts;
10297
10298  assert((NumActiveLanes == 16 || NumActiveLanes == 8 || NumActiveLanes == 4 ||
10299          NumActiveLanes == 2) &&
10300         "Only expected a power 2 vector size");
10301
10302  // Use Mul(X, Rev(X)) until 4 items remain. Going down to 4 vector elements
10303  // allows us to easily extract vector elements from the lanes.
10304  while (NumActiveLanes > 4) {
10305    unsigned RevOpcode = NumActiveLanes == 16 ? ARMISD::VREV16 : ARMISD::VREV32;
10306    SDValue Rev = DAG.getNode(RevOpcode, dl, VT, Op0);
10307    Op0 = DAG.getNode(BaseOpcode, dl, VT, Op0, Rev);
10308    NumActiveLanes /= 2;
10309  }
10310
10311  SDValue Res;
10312  if (NumActiveLanes == 4) {
10313    // The remaining 4 elements are summed sequentially
10314    SDValue Ext0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op0,
10315                              DAG.getConstant(0 * NumElts / 4, dl, MVT::i32));
10316    SDValue Ext1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op0,
10317                              DAG.getConstant(1 * NumElts / 4, dl, MVT::i32));
10318    SDValue Ext2 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op0,
10319                              DAG.getConstant(2 * NumElts / 4, dl, MVT::i32));
10320    SDValue Ext3 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op0,
10321                              DAG.getConstant(3 * NumElts / 4, dl, MVT::i32));
10322    SDValue Res0 = DAG.getNode(BaseOpcode, dl, EltVT, Ext0, Ext1, Op->getFlags());
10323    SDValue Res1 = DAG.getNode(BaseOpcode, dl, EltVT, Ext2, Ext3, Op->getFlags());
10324    Res = DAG.getNode(BaseOpcode, dl, EltVT, Res0, Res1, Op->getFlags());
10325  } else {
10326    SDValue Ext0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op0,
10327                              DAG.getConstant(0, dl, MVT::i32));
10328    SDValue Ext1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op0,
10329                              DAG.getConstant(1, dl, MVT::i32));
10330    Res = DAG.getNode(BaseOpcode, dl, EltVT, Ext0, Ext1, Op->getFlags());
10331  }
10332
10333  // Result type may be wider than element type.
10334  if (EltVT != Op->getValueType(0))
10335    Res = DAG.getNode(ISD::ANY_EXTEND, dl, Op->getValueType(0), Res);
10336  return Res;
10337}
10338
10339static SDValue LowerVecReduceF(SDValue Op, SelectionDAG &DAG,
10340                               const ARMSubtarget *ST) {
10341  if (!ST->hasMVEFloatOps())
10342    return SDValue();
10343  return LowerVecReduce(Op, DAG, ST);
10344}
10345
10346static SDValue LowerVecReduceMinMax(SDValue Op, SelectionDAG &DAG,
10347                                    const ARMSubtarget *ST) {
10348  if (!ST->hasNEON())
10349    return SDValue();
10350
10351  SDLoc dl(Op);
10352  SDValue Op0 = Op->getOperand(0);
10353  EVT VT = Op0.getValueType();
10354  EVT EltVT = VT.getVectorElementType();
10355
10356  unsigned PairwiseIntrinsic = 0;
10357  switch (Op->getOpcode()) {
10358  default:
10359    llvm_unreachable("Expected VECREDUCE opcode");
10360  case ISD::VECREDUCE_UMIN:
10361    PairwiseIntrinsic = Intrinsic::arm_neon_vpminu;
10362    break;
10363  case ISD::VECREDUCE_UMAX:
10364    PairwiseIntrinsic = Intrinsic::arm_neon_vpmaxu;
10365    break;
10366  case ISD::VECREDUCE_SMIN:
10367    PairwiseIntrinsic = Intrinsic::arm_neon_vpmins;
10368    break;
10369  case ISD::VECREDUCE_SMAX:
10370    PairwiseIntrinsic = Intrinsic::arm_neon_vpmaxs;
10371    break;
10372  }
10373  SDValue PairwiseOp = DAG.getConstant(PairwiseIntrinsic, dl, MVT::i32);
10374
10375  unsigned NumElts = VT.getVectorNumElements();
10376  unsigned NumActiveLanes = NumElts;
10377
10378  assert((NumActiveLanes == 16 || NumActiveLanes == 8 || NumActiveLanes == 4 ||
10379          NumActiveLanes == 2) &&
10380         "Only expected a power 2 vector size");
10381
10382  // Split 128-bit vectors, since vpmin/max takes 2 64-bit vectors.
10383  if (VT.is128BitVector()) {
10384    SDValue Lo, Hi;
10385    std::tie(Lo, Hi) = DAG.SplitVector(Op0, dl);
10386    VT = Lo.getValueType();
10387    Op0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, {PairwiseOp, Lo, Hi});
10388    NumActiveLanes /= 2;
10389  }
10390
10391  // Use pairwise reductions until one lane remains
10392  while (NumActiveLanes > 1) {
10393    Op0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, {PairwiseOp, Op0, Op0});
10394    NumActiveLanes /= 2;
10395  }
10396
10397  SDValue Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op0,
10398                            DAG.getConstant(0, dl, MVT::i32));
10399
10400  // Result type may be wider than element type.
10401  if (EltVT != Op.getValueType()) {
10402    unsigned Extend = 0;
10403    switch (Op->getOpcode()) {
10404    default:
10405      llvm_unreachable("Expected VECREDUCE opcode");
10406    case ISD::VECREDUCE_UMIN:
10407    case ISD::VECREDUCE_UMAX:
10408      Extend = ISD::ZERO_EXTEND;
10409      break;
10410    case ISD::VECREDUCE_SMIN:
10411    case ISD::VECREDUCE_SMAX:
10412      Extend = ISD::SIGN_EXTEND;
10413      break;
10414    }
10415    Res = DAG.getNode(Extend, dl, Op.getValueType(), Res);
10416  }
10417  return Res;
10418}
10419
10420static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
10421  if (isStrongerThanMonotonic(cast<AtomicSDNode>(Op)->getSuccessOrdering()))
10422    // Acquire/Release load/store is not legal for targets without a dmb or
10423    // equivalent available.
10424    return SDValue();
10425
10426  // Monotonic load/store is legal for all targets.
10427  return Op;
10428}
10429
10430static void ReplaceREADCYCLECOUNTER(SDNode *N,
10431                                    SmallVectorImpl<SDValue> &Results,
10432                                    SelectionDAG &DAG,
10433                                    const ARMSubtarget *Subtarget) {
10434  SDLoc DL(N);
10435  // Under Power Management extensions, the cycle-count is:
10436  //    mrc p15, #0, <Rt>, c9, c13, #0
10437  SDValue Ops[] = { N->getOperand(0), // Chain
10438                    DAG.getTargetConstant(Intrinsic::arm_mrc, DL, MVT::i32),
10439                    DAG.getTargetConstant(15, DL, MVT::i32),
10440                    DAG.getTargetConstant(0, DL, MVT::i32),
10441                    DAG.getTargetConstant(9, DL, MVT::i32),
10442                    DAG.getTargetConstant(13, DL, MVT::i32),
10443                    DAG.getTargetConstant(0, DL, MVT::i32)
10444  };
10445
10446  SDValue Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
10447                                 DAG.getVTList(MVT::i32, MVT::Other), Ops);
10448  Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Cycles32,
10449                                DAG.getConstant(0, DL, MVT::i32)));
10450  Results.push_back(Cycles32.getValue(1));
10451}
10452
10453static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) {
10454  SDLoc dl(V.getNode());
10455  auto [VLo, VHi] = DAG.SplitScalar(V, dl, MVT::i32, MVT::i32);
10456  bool isBigEndian = DAG.getDataLayout().isBigEndian();
10457  if (isBigEndian)
10458    std::swap (VLo, VHi);
10459  SDValue RegClass =
10460      DAG.getTargetConstant(ARM::GPRPairRegClassID, dl, MVT::i32);
10461  SDValue SubReg0 = DAG.getTargetConstant(ARM::gsub_0, dl, MVT::i32);
10462  SDValue SubReg1 = DAG.getTargetConstant(ARM::gsub_1, dl, MVT::i32);
10463  const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 };
10464  return SDValue(
10465      DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0);
10466}
10467
10468static void ReplaceCMP_SWAP_64Results(SDNode *N,
10469                                       SmallVectorImpl<SDValue> & Results,
10470                                       SelectionDAG &DAG) {
10471  assert(N->getValueType(0) == MVT::i64 &&
10472         "AtomicCmpSwap on types less than 64 should be legal");
10473  SDValue Ops[] = {N->getOperand(1),
10474                   createGPRPairNode(DAG, N->getOperand(2)),
10475                   createGPRPairNode(DAG, N->getOperand(3)),
10476                   N->getOperand(0)};
10477  SDNode *CmpSwap = DAG.getMachineNode(
10478      ARM::CMP_SWAP_64, SDLoc(N),
10479      DAG.getVTList(MVT::Untyped, MVT::i32, MVT::Other), Ops);
10480
10481  MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand();
10482  DAG.setNodeMemRefs(cast<MachineSDNode>(CmpSwap), {MemOp});
10483
10484  bool isBigEndian = DAG.getDataLayout().isBigEndian();
10485
10486  SDValue Lo =
10487      DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_1 : ARM::gsub_0,
10488                                 SDLoc(N), MVT::i32, SDValue(CmpSwap, 0));
10489  SDValue Hi =
10490      DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_0 : ARM::gsub_1,
10491                                 SDLoc(N), MVT::i32, SDValue(CmpSwap, 0));
10492  Results.push_back(DAG.getNode(ISD::BUILD_PAIR, SDLoc(N), MVT::i64, Lo, Hi));
10493  Results.push_back(SDValue(CmpSwap, 2));
10494}
10495
10496SDValue ARMTargetLowering::LowerFSETCC(SDValue Op, SelectionDAG &DAG) const {
10497  SDLoc dl(Op);
10498  EVT VT = Op.getValueType();
10499  SDValue Chain = Op.getOperand(0);
10500  SDValue LHS = Op.getOperand(1);
10501  SDValue RHS = Op.getOperand(2);
10502  ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(3))->get();
10503  bool IsSignaling = Op.getOpcode() == ISD::STRICT_FSETCCS;
10504
10505  // If we don't have instructions of this float type then soften to a libcall
10506  // and use SETCC instead.
10507  if (isUnsupportedFloatingType(LHS.getValueType())) {
10508    DAG.getTargetLoweringInfo().softenSetCCOperands(
10509      DAG, LHS.getValueType(), LHS, RHS, CC, dl, LHS, RHS, Chain, IsSignaling);
10510    if (!RHS.getNode()) {
10511      RHS = DAG.getConstant(0, dl, LHS.getValueType());
10512      CC = ISD::SETNE;
10513    }
10514    SDValue Result = DAG.getNode(ISD::SETCC, dl, VT, LHS, RHS,
10515                                 DAG.getCondCode(CC));
10516    return DAG.getMergeValues({Result, Chain}, dl);
10517  }
10518
10519  ARMCC::CondCodes CondCode, CondCode2;
10520  FPCCToARMCC(CC, CondCode, CondCode2);
10521
10522  // FIXME: Chain is not handled correctly here. Currently the FPSCR is implicit
10523  // in CMPFP and CMPFPE, but instead it should be made explicit by these
10524  // instructions using a chain instead of glue. This would also fix the problem
10525  // here (and also in LowerSELECT_CC) where we generate two comparisons when
10526  // CondCode2 != AL.
10527  SDValue True = DAG.getConstant(1, dl, VT);
10528  SDValue False =  DAG.getConstant(0, dl, VT);
10529  SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
10530  SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
10531  SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl, IsSignaling);
10532  SDValue Result = getCMOV(dl, VT, False, True, ARMcc, CCR, Cmp, DAG);
10533  if (CondCode2 != ARMCC::AL) {
10534    ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32);
10535    Cmp = getVFPCmp(LHS, RHS, DAG, dl, IsSignaling);
10536    Result = getCMOV(dl, VT, Result, True, ARMcc, CCR, Cmp, DAG);
10537  }
10538  return DAG.getMergeValues({Result, Chain}, dl);
10539}
10540
10541SDValue ARMTargetLowering::LowerSPONENTRY(SDValue Op, SelectionDAG &DAG) const {
10542  MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
10543
10544  EVT VT = getPointerTy(DAG.getDataLayout());
10545  SDLoc DL(Op);
10546  int FI = MFI.CreateFixedObject(4, 0, false);
10547  return DAG.getFrameIndex(FI, VT);
10548}
10549
10550SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
10551  LLVM_DEBUG(dbgs() << "Lowering node: "; Op.dump());
10552  switch (Op.getOpcode()) {
10553  default: llvm_unreachable("Don't know how to custom lower this!");
10554  case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG);
10555  case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
10556  case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
10557  case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
10558  case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
10559  case ISD::SELECT:        return LowerSELECT(Op, DAG);
10560  case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
10561  case ISD::BRCOND:        return LowerBRCOND(Op, DAG);
10562  case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
10563  case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
10564  case ISD::VASTART:       return LowerVASTART(Op, DAG);
10565  case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
10566  case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
10567  case ISD::SINT_TO_FP:
10568  case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
10569  case ISD::STRICT_FP_TO_SINT:
10570  case ISD::STRICT_FP_TO_UINT:
10571  case ISD::FP_TO_SINT:
10572  case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
10573  case ISD::FP_TO_SINT_SAT:
10574  case ISD::FP_TO_UINT_SAT: return LowerFP_TO_INT_SAT(Op, DAG, Subtarget);
10575  case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
10576  case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
10577  case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
10578  case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
10579  case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
10580  case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG);
10581  case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG, Subtarget);
10582  case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
10583                                                               Subtarget);
10584  case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG, Subtarget);
10585  case ISD::SHL:
10586  case ISD::SRL:
10587  case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
10588  case ISD::SREM:          return LowerREM(Op.getNode(), DAG);
10589  case ISD::UREM:          return LowerREM(Op.getNode(), DAG);
10590  case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
10591  case ISD::SRL_PARTS:
10592  case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
10593  case ISD::CTTZ:
10594  case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
10595  case ISD::CTPOP:         return LowerCTPOP(Op.getNode(), DAG, Subtarget);
10596  case ISD::SETCC:         return LowerVSETCC(Op, DAG, Subtarget);
10597  case ISD::SETCCCARRY:    return LowerSETCCCARRY(Op, DAG);
10598  case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
10599  case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
10600  case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG, Subtarget);
10601  case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op, DAG, Subtarget);
10602  case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
10603  case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG, Subtarget);
10604  case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG, Subtarget);
10605  case ISD::TRUNCATE:      return LowerTruncate(Op.getNode(), DAG, Subtarget);
10606  case ISD::SIGN_EXTEND:
10607  case ISD::ZERO_EXTEND:   return LowerVectorExtend(Op.getNode(), DAG, Subtarget);
10608  case ISD::GET_ROUNDING:  return LowerGET_ROUNDING(Op, DAG);
10609  case ISD::SET_ROUNDING:  return LowerSET_ROUNDING(Op, DAG);
10610  case ISD::SET_FPMODE:
10611    return LowerSET_FPMODE(Op, DAG);
10612  case ISD::RESET_FPMODE:
10613    return LowerRESET_FPMODE(Op, DAG);
10614  case ISD::MUL:           return LowerMUL(Op, DAG);
10615  case ISD::SDIV:
10616    if (Subtarget->isTargetWindows() && !Op.getValueType().isVector())
10617      return LowerDIV_Windows(Op, DAG, /* Signed */ true);
10618    return LowerSDIV(Op, DAG, Subtarget);
10619  case ISD::UDIV:
10620    if (Subtarget->isTargetWindows() && !Op.getValueType().isVector())
10621      return LowerDIV_Windows(Op, DAG, /* Signed */ false);
10622    return LowerUDIV(Op, DAG, Subtarget);
10623  case ISD::UADDO_CARRY:
10624  case ISD::USUBO_CARRY:
10625    return LowerUADDSUBO_CARRY(Op, DAG);
10626  case ISD::SADDO:
10627  case ISD::SSUBO:
10628    return LowerSignedALUO(Op, DAG);
10629  case ISD::UADDO:
10630  case ISD::USUBO:
10631    return LowerUnsignedALUO(Op, DAG);
10632  case ISD::SADDSAT:
10633  case ISD::SSUBSAT:
10634  case ISD::UADDSAT:
10635  case ISD::USUBSAT:
10636    return LowerADDSUBSAT(Op, DAG, Subtarget);
10637  case ISD::LOAD:
10638    return LowerPredicateLoad(Op, DAG);
10639  case ISD::STORE:
10640    return LowerSTORE(Op, DAG, Subtarget);
10641  case ISD::MLOAD:
10642    return LowerMLOAD(Op, DAG);
10643  case ISD::VECREDUCE_MUL:
10644  case ISD::VECREDUCE_AND:
10645  case ISD::VECREDUCE_OR:
10646  case ISD::VECREDUCE_XOR:
10647    return LowerVecReduce(Op, DAG, Subtarget);
10648  case ISD::VECREDUCE_FADD:
10649  case ISD::VECREDUCE_FMUL:
10650  case ISD::VECREDUCE_FMIN:
10651  case ISD::VECREDUCE_FMAX:
10652    return LowerVecReduceF(Op, DAG, Subtarget);
10653  case ISD::VECREDUCE_UMIN:
10654  case ISD::VECREDUCE_UMAX:
10655  case ISD::VECREDUCE_SMIN:
10656  case ISD::VECREDUCE_SMAX:
10657    return LowerVecReduceMinMax(Op, DAG, Subtarget);
10658  case ISD::ATOMIC_LOAD:
10659  case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
10660  case ISD::FSINCOS:       return LowerFSINCOS(Op, DAG);
10661  case ISD::SDIVREM:
10662  case ISD::UDIVREM:       return LowerDivRem(Op, DAG);
10663  case ISD::DYNAMIC_STACKALLOC:
10664    if (Subtarget->isTargetWindows())
10665      return LowerDYNAMIC_STACKALLOC(Op, DAG);
10666    llvm_unreachable("Don't know how to custom lower this!");
10667  case ISD::STRICT_FP_ROUND:
10668  case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
10669  case ISD::STRICT_FP_EXTEND:
10670  case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
10671  case ISD::STRICT_FSETCC:
10672  case ISD::STRICT_FSETCCS: return LowerFSETCC(Op, DAG);
10673  case ISD::SPONENTRY:
10674    return LowerSPONENTRY(Op, DAG);
10675  case ARMISD::WIN__DBZCHK: return SDValue();
10676  }
10677}
10678
10679static void ReplaceLongIntrinsic(SDNode *N, SmallVectorImpl<SDValue> &Results,
10680                                 SelectionDAG &DAG) {
10681  unsigned IntNo = N->getConstantOperandVal(0);
10682  unsigned Opc = 0;
10683  if (IntNo == Intrinsic::arm_smlald)
10684    Opc = ARMISD::SMLALD;
10685  else if (IntNo == Intrinsic::arm_smlaldx)
10686    Opc = ARMISD::SMLALDX;
10687  else if (IntNo == Intrinsic::arm_smlsld)
10688    Opc = ARMISD::SMLSLD;
10689  else if (IntNo == Intrinsic::arm_smlsldx)
10690    Opc = ARMISD::SMLSLDX;
10691  else
10692    return;
10693
10694  SDLoc dl(N);
10695  SDValue Lo, Hi;
10696  std::tie(Lo, Hi) = DAG.SplitScalar(N->getOperand(3), dl, MVT::i32, MVT::i32);
10697
10698  SDValue LongMul = DAG.getNode(Opc, dl,
10699                                DAG.getVTList(MVT::i32, MVT::i32),
10700                                N->getOperand(1), N->getOperand(2),
10701                                Lo, Hi);
10702  Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64,
10703                                LongMul.getValue(0), LongMul.getValue(1)));
10704}
10705
10706/// ReplaceNodeResults - Replace the results of node with an illegal result
10707/// type with new values built out of custom code.
10708void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
10709                                           SmallVectorImpl<SDValue> &Results,
10710                                           SelectionDAG &DAG) const {
10711  SDValue Res;
10712  switch (N->getOpcode()) {
10713  default:
10714    llvm_unreachable("Don't know how to custom expand this!");
10715  case ISD::READ_REGISTER:
10716    ExpandREAD_REGISTER(N, Results, DAG);
10717    break;
10718  case ISD::BITCAST:
10719    Res = ExpandBITCAST(N, DAG, Subtarget);
10720    break;
10721  case ISD::SRL:
10722  case ISD::SRA:
10723  case ISD::SHL:
10724    Res = Expand64BitShift(N, DAG, Subtarget);
10725    break;
10726  case ISD::SREM:
10727  case ISD::UREM:
10728    Res = LowerREM(N, DAG);
10729    break;
10730  case ISD::SDIVREM:
10731  case ISD::UDIVREM:
10732    Res = LowerDivRem(SDValue(N, 0), DAG);
10733    assert(Res.getNumOperands() == 2 && "DivRem needs two values");
10734    Results.push_back(Res.getValue(0));
10735    Results.push_back(Res.getValue(1));
10736    return;
10737  case ISD::SADDSAT:
10738  case ISD::SSUBSAT:
10739  case ISD::UADDSAT:
10740  case ISD::USUBSAT:
10741    Res = LowerADDSUBSAT(SDValue(N, 0), DAG, Subtarget);
10742    break;
10743  case ISD::READCYCLECOUNTER:
10744    ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
10745    return;
10746  case ISD::UDIV:
10747  case ISD::SDIV:
10748    assert(Subtarget->isTargetWindows() && "can only expand DIV on Windows");
10749    return ExpandDIV_Windows(SDValue(N, 0), DAG, N->getOpcode() == ISD::SDIV,
10750                             Results);
10751  case ISD::ATOMIC_CMP_SWAP:
10752    ReplaceCMP_SWAP_64Results(N, Results, DAG);
10753    return;
10754  case ISD::INTRINSIC_WO_CHAIN:
10755    return ReplaceLongIntrinsic(N, Results, DAG);
10756  case ISD::LOAD:
10757    LowerLOAD(N, Results, DAG);
10758    break;
10759  case ISD::TRUNCATE:
10760    Res = LowerTruncate(N, DAG, Subtarget);
10761    break;
10762  case ISD::SIGN_EXTEND:
10763  case ISD::ZERO_EXTEND:
10764    Res = LowerVectorExtend(N, DAG, Subtarget);
10765    break;
10766  case ISD::FP_TO_SINT_SAT:
10767  case ISD::FP_TO_UINT_SAT:
10768    Res = LowerFP_TO_INT_SAT(SDValue(N, 0), DAG, Subtarget);
10769    break;
10770  }
10771  if (Res.getNode())
10772    Results.push_back(Res);
10773}
10774
10775//===----------------------------------------------------------------------===//
10776//                           ARM Scheduler Hooks
10777//===----------------------------------------------------------------------===//
10778
10779/// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
10780/// registers the function context.
10781void ARMTargetLowering::SetupEntryBlockForSjLj(MachineInstr &MI,
10782                                               MachineBasicBlock *MBB,
10783                                               MachineBasicBlock *DispatchBB,
10784                                               int FI) const {
10785  assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
10786         "ROPI/RWPI not currently supported with SjLj");
10787  const TargetInstrInfo *TII = Subtarget->getInstrInfo();
10788  DebugLoc dl = MI.getDebugLoc();
10789  MachineFunction *MF = MBB->getParent();
10790  MachineRegisterInfo *MRI = &MF->getRegInfo();
10791  MachineConstantPool *MCP = MF->getConstantPool();
10792  ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
10793  const Function &F = MF->getFunction();
10794
10795  bool isThumb = Subtarget->isThumb();
10796  bool isThumb2 = Subtarget->isThumb2();
10797
10798  unsigned PCLabelId = AFI->createPICLabelUId();
10799  unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
10800  ARMConstantPoolValue *CPV =
10801    ARMConstantPoolMBB::Create(F.getContext(), DispatchBB, PCLabelId, PCAdj);
10802  unsigned CPI = MCP->getConstantPoolIndex(CPV, Align(4));
10803
10804  const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass
10805                                           : &ARM::GPRRegClass;
10806
10807  // Grab constant pool and fixed stack memory operands.
10808  MachineMemOperand *CPMMO =
10809      MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF),
10810                               MachineMemOperand::MOLoad, 4, Align(4));
10811
10812  MachineMemOperand *FIMMOSt =
10813      MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI),
10814                               MachineMemOperand::MOStore, 4, Align(4));
10815
10816  // Load the address of the dispatch MBB into the jump buffer.
10817  if (isThumb2) {
10818    // Incoming value: jbuf
10819    //   ldr.n  r5, LCPI1_1
10820    //   orr    r5, r5, #1
10821    //   add    r5, pc
10822    //   str    r5, [$jbuf, #+4] ; &jbuf[1]
10823    Register NewVReg1 = MRI->createVirtualRegister(TRC);
10824    BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
10825        .addConstantPoolIndex(CPI)
10826        .addMemOperand(CPMMO)
10827        .add(predOps(ARMCC::AL));
10828    // Set the low bit because of thumb mode.
10829    Register NewVReg2 = MRI->createVirtualRegister(TRC);
10830    BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
10831        .addReg(NewVReg1, RegState::Kill)
10832        .addImm(0x01)
10833        .add(predOps(ARMCC::AL))
10834        .add(condCodeOp());
10835    Register NewVReg3 = MRI->createVirtualRegister(TRC);
10836    BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
10837      .addReg(NewVReg2, RegState::Kill)
10838      .addImm(PCLabelId);
10839    BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
10840        .addReg(NewVReg3, RegState::Kill)
10841        .addFrameIndex(FI)
10842        .addImm(36) // &jbuf[1] :: pc
10843        .addMemOperand(FIMMOSt)
10844        .add(predOps(ARMCC::AL));
10845  } else if (isThumb) {
10846    // Incoming value: jbuf
10847    //   ldr.n  r1, LCPI1_4
10848    //   add    r1, pc
10849    //   mov    r2, #1
10850    //   orrs   r1, r2
10851    //   add    r2, $jbuf, #+4 ; &jbuf[1]
10852    //   str    r1, [r2]
10853    Register NewVReg1 = MRI->createVirtualRegister(TRC);
10854    BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
10855        .addConstantPoolIndex(CPI)
10856        .addMemOperand(CPMMO)
10857        .add(predOps(ARMCC::AL));
10858    Register NewVReg2 = MRI->createVirtualRegister(TRC);
10859    BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
10860      .addReg(NewVReg1, RegState::Kill)
10861      .addImm(PCLabelId);
10862    // Set the low bit because of thumb mode.
10863    Register NewVReg3 = MRI->createVirtualRegister(TRC);
10864    BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
10865        .addReg(ARM::CPSR, RegState::Define)
10866        .addImm(1)
10867        .add(predOps(ARMCC::AL));
10868    Register NewVReg4 = MRI->createVirtualRegister(TRC);
10869    BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
10870        .addReg(ARM::CPSR, RegState::Define)
10871        .addReg(NewVReg2, RegState::Kill)
10872        .addReg(NewVReg3, RegState::Kill)
10873        .add(predOps(ARMCC::AL));
10874    Register NewVReg5 = MRI->createVirtualRegister(TRC);
10875    BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5)
10876            .addFrameIndex(FI)
10877            .addImm(36); // &jbuf[1] :: pc
10878    BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
10879        .addReg(NewVReg4, RegState::Kill)
10880        .addReg(NewVReg5, RegState::Kill)
10881        .addImm(0)
10882        .addMemOperand(FIMMOSt)
10883        .add(predOps(ARMCC::AL));
10884  } else {
10885    // Incoming value: jbuf
10886    //   ldr  r1, LCPI1_1
10887    //   add  r1, pc, r1
10888    //   str  r1, [$jbuf, #+4] ; &jbuf[1]
10889    Register NewVReg1 = MRI->createVirtualRegister(TRC);
10890    BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1)
10891        .addConstantPoolIndex(CPI)
10892        .addImm(0)
10893        .addMemOperand(CPMMO)
10894        .add(predOps(ARMCC::AL));
10895    Register NewVReg2 = MRI->createVirtualRegister(TRC);
10896    BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
10897        .addReg(NewVReg1, RegState::Kill)
10898        .addImm(PCLabelId)
10899        .add(predOps(ARMCC::AL));
10900    BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
10901        .addReg(NewVReg2, RegState::Kill)
10902        .addFrameIndex(FI)
10903        .addImm(36) // &jbuf[1] :: pc
10904        .addMemOperand(FIMMOSt)
10905        .add(predOps(ARMCC::AL));
10906  }
10907}
10908
10909void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr &MI,
10910                                              MachineBasicBlock *MBB) const {
10911  const TargetInstrInfo *TII = Subtarget->getInstrInfo();
10912  DebugLoc dl = MI.getDebugLoc();
10913  MachineFunction *MF = MBB->getParent();
10914  MachineRegisterInfo *MRI = &MF->getRegInfo();
10915  MachineFrameInfo &MFI = MF->getFrameInfo();
10916  int FI = MFI.getFunctionContextIndex();
10917
10918  const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass
10919                                                        : &ARM::GPRnopcRegClass;
10920
10921  // Get a mapping of the call site numbers to all of the landing pads they're
10922  // associated with.
10923  DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2>> CallSiteNumToLPad;
10924  unsigned MaxCSNum = 0;
10925  for (MachineBasicBlock &BB : *MF) {
10926    if (!BB.isEHPad())
10927      continue;
10928
10929    // FIXME: We should assert that the EH_LABEL is the first MI in the landing
10930    // pad.
10931    for (MachineInstr &II : BB) {
10932      if (!II.isEHLabel())
10933        continue;
10934
10935      MCSymbol *Sym = II.getOperand(0).getMCSymbol();
10936      if (!MF->hasCallSiteLandingPad(Sym)) continue;
10937
10938      SmallVectorImpl<unsigned> &CallSiteIdxs = MF->getCallSiteLandingPad(Sym);
10939      for (unsigned Idx : CallSiteIdxs) {
10940        CallSiteNumToLPad[Idx].push_back(&BB);
10941        MaxCSNum = std::max(MaxCSNum, Idx);
10942      }
10943      break;
10944    }
10945  }
10946
10947  // Get an ordered list of the machine basic blocks for the jump table.
10948  std::vector<MachineBasicBlock*> LPadList;
10949  SmallPtrSet<MachineBasicBlock*, 32> InvokeBBs;
10950  LPadList.reserve(CallSiteNumToLPad.size());
10951  for (unsigned I = 1; I <= MaxCSNum; ++I) {
10952    SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
10953    for (MachineBasicBlock *MBB : MBBList) {
10954      LPadList.push_back(MBB);
10955      InvokeBBs.insert(MBB->pred_begin(), MBB->pred_end());
10956    }
10957  }
10958
10959  assert(!LPadList.empty() &&
10960         "No landing pad destinations for the dispatch jump table!");
10961
10962  // Create the jump table and associated information.
10963  MachineJumpTableInfo *JTI =
10964    MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
10965  unsigned MJTI = JTI->createJumpTableIndex(LPadList);
10966
10967  // Create the MBBs for the dispatch code.
10968
10969  // Shove the dispatch's address into the return slot in the function context.
10970  MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
10971  DispatchBB->setIsEHPad();
10972
10973  MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
10974  unsigned trap_opcode;
10975  if (Subtarget->isThumb())
10976    trap_opcode = ARM::tTRAP;
10977  else
10978    trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
10979
10980  BuildMI(TrapBB, dl, TII->get(trap_opcode));
10981  DispatchBB->addSuccessor(TrapBB);
10982
10983  MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
10984  DispatchBB->addSuccessor(DispContBB);
10985
10986  // Insert and MBBs.
10987  MF->insert(MF->end(), DispatchBB);
10988  MF->insert(MF->end(), DispContBB);
10989  MF->insert(MF->end(), TrapBB);
10990
10991  // Insert code into the entry block that creates and registers the function
10992  // context.
10993  SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
10994
10995  MachineMemOperand *FIMMOLd = MF->getMachineMemOperand(
10996      MachinePointerInfo::getFixedStack(*MF, FI),
10997      MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile, 4, Align(4));
10998
10999  MachineInstrBuilder MIB;
11000  MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
11001
11002  const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
11003  const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
11004
11005  // Add a register mask with no preserved registers.  This results in all
11006  // registers being marked as clobbered. This can't work if the dispatch block
11007  // is in a Thumb1 function and is linked with ARM code which uses the FP
11008  // registers, as there is no way to preserve the FP registers in Thumb1 mode.
11009  MIB.addRegMask(RI.getSjLjDispatchPreservedMask(*MF));
11010
11011  bool IsPositionIndependent = isPositionIndependent();
11012  unsigned NumLPads = LPadList.size();
11013  if (Subtarget->isThumb2()) {
11014    Register NewVReg1 = MRI->createVirtualRegister(TRC);
11015    BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
11016        .addFrameIndex(FI)
11017        .addImm(4)
11018        .addMemOperand(FIMMOLd)
11019        .add(predOps(ARMCC::AL));
11020
11021    if (NumLPads < 256) {
11022      BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
11023          .addReg(NewVReg1)
11024          .addImm(LPadList.size())
11025          .add(predOps(ARMCC::AL));
11026    } else {
11027      Register VReg1 = MRI->createVirtualRegister(TRC);
11028      BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
11029          .addImm(NumLPads & 0xFFFF)
11030          .add(predOps(ARMCC::AL));
11031
11032      unsigned VReg2 = VReg1;
11033      if ((NumLPads & 0xFFFF0000) != 0) {
11034        VReg2 = MRI->createVirtualRegister(TRC);
11035        BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
11036            .addReg(VReg1)
11037            .addImm(NumLPads >> 16)
11038            .add(predOps(ARMCC::AL));
11039      }
11040
11041      BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
11042          .addReg(NewVReg1)
11043          .addReg(VReg2)
11044          .add(predOps(ARMCC::AL));
11045    }
11046
11047    BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
11048      .addMBB(TrapBB)
11049      .addImm(ARMCC::HI)
11050      .addReg(ARM::CPSR);
11051
11052    Register NewVReg3 = MRI->createVirtualRegister(TRC);
11053    BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT), NewVReg3)
11054        .addJumpTableIndex(MJTI)
11055        .add(predOps(ARMCC::AL));
11056
11057    Register NewVReg4 = MRI->createVirtualRegister(TRC);
11058    BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
11059        .addReg(NewVReg3, RegState::Kill)
11060        .addReg(NewVReg1)
11061        .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))
11062        .add(predOps(ARMCC::AL))
11063        .add(condCodeOp());
11064
11065    BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
11066      .addReg(NewVReg4, RegState::Kill)
11067      .addReg(NewVReg1)
11068      .addJumpTableIndex(MJTI);
11069  } else if (Subtarget->isThumb()) {
11070    Register NewVReg1 = MRI->createVirtualRegister(TRC);
11071    BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
11072        .addFrameIndex(FI)
11073        .addImm(1)
11074        .addMemOperand(FIMMOLd)
11075        .add(predOps(ARMCC::AL));
11076
11077    if (NumLPads < 256) {
11078      BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
11079          .addReg(NewVReg1)
11080          .addImm(NumLPads)
11081          .add(predOps(ARMCC::AL));
11082    } else {
11083      MachineConstantPool *ConstantPool = MF->getConstantPool();
11084      Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext());
11085      const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
11086
11087      // MachineConstantPool wants an explicit alignment.
11088      Align Alignment = MF->getDataLayout().getPrefTypeAlign(Int32Ty);
11089      unsigned Idx = ConstantPool->getConstantPoolIndex(C, Alignment);
11090
11091      Register VReg1 = MRI->createVirtualRegister(TRC);
11092      BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
11093          .addReg(VReg1, RegState::Define)
11094          .addConstantPoolIndex(Idx)
11095          .add(predOps(ARMCC::AL));
11096      BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
11097          .addReg(NewVReg1)
11098          .addReg(VReg1)
11099          .add(predOps(ARMCC::AL));
11100    }
11101
11102    BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
11103      .addMBB(TrapBB)
11104      .addImm(ARMCC::HI)
11105      .addReg(ARM::CPSR);
11106
11107    Register NewVReg2 = MRI->createVirtualRegister(TRC);
11108    BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
11109        .addReg(ARM::CPSR, RegState::Define)
11110        .addReg(NewVReg1)
11111        .addImm(2)
11112        .add(predOps(ARMCC::AL));
11113
11114    Register NewVReg3 = MRI->createVirtualRegister(TRC);
11115    BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
11116        .addJumpTableIndex(MJTI)
11117        .add(predOps(ARMCC::AL));
11118
11119    Register NewVReg4 = MRI->createVirtualRegister(TRC);
11120    BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
11121        .addReg(ARM::CPSR, RegState::Define)
11122        .addReg(NewVReg2, RegState::Kill)
11123        .addReg(NewVReg3)
11124        .add(predOps(ARMCC::AL));
11125
11126    MachineMemOperand *JTMMOLd =
11127        MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(*MF),
11128                                 MachineMemOperand::MOLoad, 4, Align(4));
11129
11130    Register NewVReg5 = MRI->createVirtualRegister(TRC);
11131    BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
11132        .addReg(NewVReg4, RegState::Kill)
11133        .addImm(0)
11134        .addMemOperand(JTMMOLd)
11135        .add(predOps(ARMCC::AL));
11136
11137    unsigned NewVReg6 = NewVReg5;
11138    if (IsPositionIndependent) {
11139      NewVReg6 = MRI->createVirtualRegister(TRC);
11140      BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
11141          .addReg(ARM::CPSR, RegState::Define)
11142          .addReg(NewVReg5, RegState::Kill)
11143          .addReg(NewVReg3)
11144          .add(predOps(ARMCC::AL));
11145    }
11146
11147    BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
11148      .addReg(NewVReg6, RegState::Kill)
11149      .addJumpTableIndex(MJTI);
11150  } else {
11151    Register NewVReg1 = MRI->createVirtualRegister(TRC);
11152    BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
11153        .addFrameIndex(FI)
11154        .addImm(4)
11155        .addMemOperand(FIMMOLd)
11156        .add(predOps(ARMCC::AL));
11157
11158    if (NumLPads < 256) {
11159      BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
11160          .addReg(NewVReg1)
11161          .addImm(NumLPads)
11162          .add(predOps(ARMCC::AL));
11163    } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
11164      Register VReg1 = MRI->createVirtualRegister(TRC);
11165      BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
11166          .addImm(NumLPads & 0xFFFF)
11167          .add(predOps(ARMCC::AL));
11168
11169      unsigned VReg2 = VReg1;
11170      if ((NumLPads & 0xFFFF0000) != 0) {
11171        VReg2 = MRI->createVirtualRegister(TRC);
11172        BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
11173            .addReg(VReg1)
11174            .addImm(NumLPads >> 16)
11175            .add(predOps(ARMCC::AL));
11176      }
11177
11178      BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
11179          .addReg(NewVReg1)
11180          .addReg(VReg2)
11181          .add(predOps(ARMCC::AL));
11182    } else {
11183      MachineConstantPool *ConstantPool = MF->getConstantPool();
11184      Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext());
11185      const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
11186
11187      // MachineConstantPool wants an explicit alignment.
11188      Align Alignment = MF->getDataLayout().getPrefTypeAlign(Int32Ty);
11189      unsigned Idx = ConstantPool->getConstantPoolIndex(C, Alignment);
11190
11191      Register VReg1 = MRI->createVirtualRegister(TRC);
11192      BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
11193          .addReg(VReg1, RegState::Define)
11194          .addConstantPoolIndex(Idx)
11195          .addImm(0)
11196          .add(predOps(ARMCC::AL));
11197      BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
11198          .addReg(NewVReg1)
11199          .addReg(VReg1, RegState::Kill)
11200          .add(predOps(ARMCC::AL));
11201    }
11202
11203    BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
11204      .addMBB(TrapBB)
11205      .addImm(ARMCC::HI)
11206      .addReg(ARM::CPSR);
11207
11208    Register NewVReg3 = MRI->createVirtualRegister(TRC);
11209    BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
11210        .addReg(NewVReg1)
11211        .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))
11212        .add(predOps(ARMCC::AL))
11213        .add(condCodeOp());
11214    Register NewVReg4 = MRI->createVirtualRegister(TRC);
11215    BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
11216        .addJumpTableIndex(MJTI)
11217        .add(predOps(ARMCC::AL));
11218
11219    MachineMemOperand *JTMMOLd =
11220        MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(*MF),
11221                                 MachineMemOperand::MOLoad, 4, Align(4));
11222    Register NewVReg5 = MRI->createVirtualRegister(TRC);
11223    BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
11224        .addReg(NewVReg3, RegState::Kill)
11225        .addReg(NewVReg4)
11226        .addImm(0)
11227        .addMemOperand(JTMMOLd)
11228        .add(predOps(ARMCC::AL));
11229
11230    if (IsPositionIndependent) {
11231      BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
11232        .addReg(NewVReg5, RegState::Kill)
11233        .addReg(NewVReg4)
11234        .addJumpTableIndex(MJTI);
11235    } else {
11236      BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
11237        .addReg(NewVReg5, RegState::Kill)
11238        .addJumpTableIndex(MJTI);
11239    }
11240  }
11241
11242  // Add the jump table entries as successors to the MBB.
11243  SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
11244  for (MachineBasicBlock *CurMBB : LPadList) {
11245    if (SeenMBBs.insert(CurMBB).second)
11246      DispContBB->addSuccessor(CurMBB);
11247  }
11248
11249  // N.B. the order the invoke BBs are processed in doesn't matter here.
11250  const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
11251  SmallVector<MachineBasicBlock*, 64> MBBLPads;
11252  for (MachineBasicBlock *BB : InvokeBBs) {
11253
11254    // Remove the landing pad successor from the invoke block and replace it
11255    // with the new dispatch block.
11256    SmallVector<MachineBasicBlock*, 4> Successors(BB->successors());
11257    while (!Successors.empty()) {
11258      MachineBasicBlock *SMBB = Successors.pop_back_val();
11259      if (SMBB->isEHPad()) {
11260        BB->removeSuccessor(SMBB);
11261        MBBLPads.push_back(SMBB);
11262      }
11263    }
11264
11265    BB->addSuccessor(DispatchBB, BranchProbability::getZero());
11266    BB->normalizeSuccProbs();
11267
11268    // Find the invoke call and mark all of the callee-saved registers as
11269    // 'implicit defined' so that they're spilled. This prevents code from
11270    // moving instructions to before the EH block, where they will never be
11271    // executed.
11272    for (MachineBasicBlock::reverse_iterator
11273           II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
11274      if (!II->isCall()) continue;
11275
11276      DenseMap<unsigned, bool> DefRegs;
11277      for (MachineInstr::mop_iterator
11278             OI = II->operands_begin(), OE = II->operands_end();
11279           OI != OE; ++OI) {
11280        if (!OI->isReg()) continue;
11281        DefRegs[OI->getReg()] = true;
11282      }
11283
11284      MachineInstrBuilder MIB(*MF, &*II);
11285
11286      for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
11287        unsigned Reg = SavedRegs[i];
11288        if (Subtarget->isThumb2() &&
11289            !ARM::tGPRRegClass.contains(Reg) &&
11290            !ARM::hGPRRegClass.contains(Reg))
11291          continue;
11292        if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
11293          continue;
11294        if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
11295          continue;
11296        if (!DefRegs[Reg])
11297          MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
11298      }
11299
11300      break;
11301    }
11302  }
11303
11304  // Mark all former landing pads as non-landing pads. The dispatch is the only
11305  // landing pad now.
11306  for (MachineBasicBlock *MBBLPad : MBBLPads)
11307    MBBLPad->setIsEHPad(false);
11308
11309  // The instruction is gone now.
11310  MI.eraseFromParent();
11311}
11312
11313static
11314MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
11315  for (MachineBasicBlock *S : MBB->successors())
11316    if (S != Succ)
11317      return S;
11318  llvm_unreachable("Expecting a BB with two successors!");
11319}
11320
11321/// Return the load opcode for a given load size. If load size >= 8,
11322/// neon opcode will be returned.
11323static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
11324  if (LdSize >= 8)
11325    return LdSize == 16 ? ARM::VLD1q32wb_fixed
11326                        : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
11327  if (IsThumb1)
11328    return LdSize == 4 ? ARM::tLDRi
11329                       : LdSize == 2 ? ARM::tLDRHi
11330                                     : LdSize == 1 ? ARM::tLDRBi : 0;
11331  if (IsThumb2)
11332    return LdSize == 4 ? ARM::t2LDR_POST
11333                       : LdSize == 2 ? ARM::t2LDRH_POST
11334                                     : LdSize == 1 ? ARM::t2LDRB_POST : 0;
11335  return LdSize == 4 ? ARM::LDR_POST_IMM
11336                     : LdSize == 2 ? ARM::LDRH_POST
11337                                   : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
11338}
11339
11340/// Return the store opcode for a given store size. If store size >= 8,
11341/// neon opcode will be returned.
11342static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
11343  if (StSize >= 8)
11344    return StSize == 16 ? ARM::VST1q32wb_fixed
11345                        : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
11346  if (IsThumb1)
11347    return StSize == 4 ? ARM::tSTRi
11348                       : StSize == 2 ? ARM::tSTRHi
11349                                     : StSize == 1 ? ARM::tSTRBi : 0;
11350  if (IsThumb2)
11351    return StSize == 4 ? ARM::t2STR_POST
11352                       : StSize == 2 ? ARM::t2STRH_POST
11353                                     : StSize == 1 ? ARM::t2STRB_POST : 0;
11354  return StSize == 4 ? ARM::STR_POST_IMM
11355                     : StSize == 2 ? ARM::STRH_POST
11356                                   : StSize == 1 ? ARM::STRB_POST_IMM : 0;
11357}
11358
11359/// Emit a post-increment load operation with given size. The instructions
11360/// will be added to BB at Pos.
11361static void emitPostLd(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos,
11362                       const TargetInstrInfo *TII, const DebugLoc &dl,
11363                       unsigned LdSize, unsigned Data, unsigned AddrIn,
11364                       unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
11365  unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
11366  assert(LdOpc != 0 && "Should have a load opcode");
11367  if (LdSize >= 8) {
11368    BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
11369        .addReg(AddrOut, RegState::Define)
11370        .addReg(AddrIn)
11371        .addImm(0)
11372        .add(predOps(ARMCC::AL));
11373  } else if (IsThumb1) {
11374    // load + update AddrIn
11375    BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
11376        .addReg(AddrIn)
11377        .addImm(0)
11378        .add(predOps(ARMCC::AL));
11379    BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut)
11380        .add(t1CondCodeOp())
11381        .addReg(AddrIn)
11382        .addImm(LdSize)
11383        .add(predOps(ARMCC::AL));
11384  } else if (IsThumb2) {
11385    BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
11386        .addReg(AddrOut, RegState::Define)
11387        .addReg(AddrIn)
11388        .addImm(LdSize)
11389        .add(predOps(ARMCC::AL));
11390  } else { // arm
11391    BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
11392        .addReg(AddrOut, RegState::Define)
11393        .addReg(AddrIn)
11394        .addReg(0)
11395        .addImm(LdSize)
11396        .add(predOps(ARMCC::AL));
11397  }
11398}
11399
11400/// Emit a post-increment store operation with given size. The instructions
11401/// will be added to BB at Pos.
11402static void emitPostSt(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos,
11403                       const TargetInstrInfo *TII, const DebugLoc &dl,
11404                       unsigned StSize, unsigned Data, unsigned AddrIn,
11405                       unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
11406  unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
11407  assert(StOpc != 0 && "Should have a store opcode");
11408  if (StSize >= 8) {
11409    BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
11410        .addReg(AddrIn)
11411        .addImm(0)
11412        .addReg(Data)
11413        .add(predOps(ARMCC::AL));
11414  } else if (IsThumb1) {
11415    // store + update AddrIn
11416    BuildMI(*BB, Pos, dl, TII->get(StOpc))
11417        .addReg(Data)
11418        .addReg(AddrIn)
11419        .addImm(0)
11420        .add(predOps(ARMCC::AL));
11421    BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut)
11422        .add(t1CondCodeOp())
11423        .addReg(AddrIn)
11424        .addImm(StSize)
11425        .add(predOps(ARMCC::AL));
11426  } else if (IsThumb2) {
11427    BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
11428        .addReg(Data)
11429        .addReg(AddrIn)
11430        .addImm(StSize)
11431        .add(predOps(ARMCC::AL));
11432  } else { // arm
11433    BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
11434        .addReg(Data)
11435        .addReg(AddrIn)
11436        .addReg(0)
11437        .addImm(StSize)
11438        .add(predOps(ARMCC::AL));
11439  }
11440}
11441
11442MachineBasicBlock *
11443ARMTargetLowering::EmitStructByval(MachineInstr &MI,
11444                                   MachineBasicBlock *BB) const {
11445  // This pseudo instruction has 3 operands: dst, src, size
11446  // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
11447  // Otherwise, we will generate unrolled scalar copies.
11448  const TargetInstrInfo *TII = Subtarget->getInstrInfo();
11449  const BasicBlock *LLVM_BB = BB->getBasicBlock();
11450  MachineFunction::iterator It = ++BB->getIterator();
11451
11452  Register dest = MI.getOperand(0).getReg();
11453  Register src = MI.getOperand(1).getReg();
11454  unsigned SizeVal = MI.getOperand(2).getImm();
11455  unsigned Alignment = MI.getOperand(3).getImm();
11456  DebugLoc dl = MI.getDebugLoc();
11457
11458  MachineFunction *MF = BB->getParent();
11459  MachineRegisterInfo &MRI = MF->getRegInfo();
11460  unsigned UnitSize = 0;
11461  const TargetRegisterClass *TRC = nullptr;
11462  const TargetRegisterClass *VecTRC = nullptr;
11463
11464  bool IsThumb1 = Subtarget->isThumb1Only();
11465  bool IsThumb2 = Subtarget->isThumb2();
11466  bool IsThumb = Subtarget->isThumb();
11467
11468  if (Alignment & 1) {
11469    UnitSize = 1;
11470  } else if (Alignment & 2) {
11471    UnitSize = 2;
11472  } else {
11473    // Check whether we can use NEON instructions.
11474    if (!MF->getFunction().hasFnAttribute(Attribute::NoImplicitFloat) &&
11475        Subtarget->hasNEON()) {
11476      if ((Alignment % 16 == 0) && SizeVal >= 16)
11477        UnitSize = 16;
11478      else if ((Alignment % 8 == 0) && SizeVal >= 8)
11479        UnitSize = 8;
11480    }
11481    // Can't use NEON instructions.
11482    if (UnitSize == 0)
11483      UnitSize = 4;
11484  }
11485
11486  // Select the correct opcode and register class for unit size load/store
11487  bool IsNeon = UnitSize >= 8;
11488  TRC = IsThumb ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
11489  if (IsNeon)
11490    VecTRC = UnitSize == 16 ? &ARM::DPairRegClass
11491                            : UnitSize == 8 ? &ARM::DPRRegClass
11492                                            : nullptr;
11493
11494  unsigned BytesLeft = SizeVal % UnitSize;
11495  unsigned LoopSize = SizeVal - BytesLeft;
11496
11497  if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
11498    // Use LDR and STR to copy.
11499    // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
11500    // [destOut] = STR_POST(scratch, destIn, UnitSize)
11501    unsigned srcIn = src;
11502    unsigned destIn = dest;
11503    for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
11504      Register srcOut = MRI.createVirtualRegister(TRC);
11505      Register destOut = MRI.createVirtualRegister(TRC);
11506      Register scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
11507      emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
11508                 IsThumb1, IsThumb2);
11509      emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
11510                 IsThumb1, IsThumb2);
11511      srcIn = srcOut;
11512      destIn = destOut;
11513    }
11514
11515    // Handle the leftover bytes with LDRB and STRB.
11516    // [scratch, srcOut] = LDRB_POST(srcIn, 1)
11517    // [destOut] = STRB_POST(scratch, destIn, 1)
11518    for (unsigned i = 0; i < BytesLeft; i++) {
11519      Register srcOut = MRI.createVirtualRegister(TRC);
11520      Register destOut = MRI.createVirtualRegister(TRC);
11521      Register scratch = MRI.createVirtualRegister(TRC);
11522      emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
11523                 IsThumb1, IsThumb2);
11524      emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
11525                 IsThumb1, IsThumb2);
11526      srcIn = srcOut;
11527      destIn = destOut;
11528    }
11529    MI.eraseFromParent(); // The instruction is gone now.
11530    return BB;
11531  }
11532
11533  // Expand the pseudo op to a loop.
11534  // thisMBB:
11535  //   ...
11536  //   movw varEnd, # --> with thumb2
11537  //   movt varEnd, #
11538  //   ldrcp varEnd, idx --> without thumb2
11539  //   fallthrough --> loopMBB
11540  // loopMBB:
11541  //   PHI varPhi, varEnd, varLoop
11542  //   PHI srcPhi, src, srcLoop
11543  //   PHI destPhi, dst, destLoop
11544  //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
11545  //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
11546  //   subs varLoop, varPhi, #UnitSize
11547  //   bne loopMBB
11548  //   fallthrough --> exitMBB
11549  // exitMBB:
11550  //   epilogue to handle left-over bytes
11551  //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
11552  //   [destOut] = STRB_POST(scratch, destLoop, 1)
11553  MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11554  MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11555  MF->insert(It, loopMBB);
11556  MF->insert(It, exitMBB);
11557
11558  // Set the call frame size on entry to the new basic blocks.
11559  unsigned CallFrameSize = TII->getCallFrameSizeAt(MI);
11560  loopMBB->setCallFrameSize(CallFrameSize);
11561  exitMBB->setCallFrameSize(CallFrameSize);
11562
11563  // Transfer the remainder of BB and its successor edges to exitMBB.
11564  exitMBB->splice(exitMBB->begin(), BB,
11565                  std::next(MachineBasicBlock::iterator(MI)), BB->end());
11566  exitMBB->transferSuccessorsAndUpdatePHIs(BB);
11567
11568  // Load an immediate to varEnd.
11569  Register varEnd = MRI.createVirtualRegister(TRC);
11570  if (Subtarget->useMovt()) {
11571    BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVi32imm : ARM::MOVi32imm),
11572            varEnd)
11573        .addImm(LoopSize);
11574  } else if (Subtarget->genExecuteOnly()) {
11575    assert(IsThumb && "Non-thumb expected to have used movt");
11576    BuildMI(BB, dl, TII->get(ARM::tMOVi32imm), varEnd).addImm(LoopSize);
11577  } else {
11578    MachineConstantPool *ConstantPool = MF->getConstantPool();
11579    Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext());
11580    const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
11581
11582    // MachineConstantPool wants an explicit alignment.
11583    Align Alignment = MF->getDataLayout().getPrefTypeAlign(Int32Ty);
11584    unsigned Idx = ConstantPool->getConstantPoolIndex(C, Alignment);
11585    MachineMemOperand *CPMMO =
11586        MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF),
11587                                 MachineMemOperand::MOLoad, 4, Align(4));
11588
11589    if (IsThumb)
11590      BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci))
11591          .addReg(varEnd, RegState::Define)
11592          .addConstantPoolIndex(Idx)
11593          .add(predOps(ARMCC::AL))
11594          .addMemOperand(CPMMO);
11595    else
11596      BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp))
11597          .addReg(varEnd, RegState::Define)
11598          .addConstantPoolIndex(Idx)
11599          .addImm(0)
11600          .add(predOps(ARMCC::AL))
11601          .addMemOperand(CPMMO);
11602  }
11603  BB->addSuccessor(loopMBB);
11604
11605  // Generate the loop body:
11606  //   varPhi = PHI(varLoop, varEnd)
11607  //   srcPhi = PHI(srcLoop, src)
11608  //   destPhi = PHI(destLoop, dst)
11609  MachineBasicBlock *entryBB = BB;
11610  BB = loopMBB;
11611  Register varLoop = MRI.createVirtualRegister(TRC);
11612  Register varPhi = MRI.createVirtualRegister(TRC);
11613  Register srcLoop = MRI.createVirtualRegister(TRC);
11614  Register srcPhi = MRI.createVirtualRegister(TRC);
11615  Register destLoop = MRI.createVirtualRegister(TRC);
11616  Register destPhi = MRI.createVirtualRegister(TRC);
11617
11618  BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
11619    .addReg(varLoop).addMBB(loopMBB)
11620    .addReg(varEnd).addMBB(entryBB);
11621  BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
11622    .addReg(srcLoop).addMBB(loopMBB)
11623    .addReg(src).addMBB(entryBB);
11624  BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
11625    .addReg(destLoop).addMBB(loopMBB)
11626    .addReg(dest).addMBB(entryBB);
11627
11628  //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
11629  //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
11630  Register scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
11631  emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
11632             IsThumb1, IsThumb2);
11633  emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
11634             IsThumb1, IsThumb2);
11635
11636  // Decrement loop variable by UnitSize.
11637  if (IsThumb1) {
11638    BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop)
11639        .add(t1CondCodeOp())
11640        .addReg(varPhi)
11641        .addImm(UnitSize)
11642        .add(predOps(ARMCC::AL));
11643  } else {
11644    MachineInstrBuilder MIB =
11645        BuildMI(*BB, BB->end(), dl,
11646                TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
11647    MIB.addReg(varPhi)
11648        .addImm(UnitSize)
11649        .add(predOps(ARMCC::AL))
11650        .add(condCodeOp());
11651    MIB->getOperand(5).setReg(ARM::CPSR);
11652    MIB->getOperand(5).setIsDef(true);
11653  }
11654  BuildMI(*BB, BB->end(), dl,
11655          TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
11656      .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
11657
11658  // loopMBB can loop back to loopMBB or fall through to exitMBB.
11659  BB->addSuccessor(loopMBB);
11660  BB->addSuccessor(exitMBB);
11661
11662  // Add epilogue to handle BytesLeft.
11663  BB = exitMBB;
11664  auto StartOfExit = exitMBB->begin();
11665
11666  //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
11667  //   [destOut] = STRB_POST(scratch, destLoop, 1)
11668  unsigned srcIn = srcLoop;
11669  unsigned destIn = destLoop;
11670  for (unsigned i = 0; i < BytesLeft; i++) {
11671    Register srcOut = MRI.createVirtualRegister(TRC);
11672    Register destOut = MRI.createVirtualRegister(TRC);
11673    Register scratch = MRI.createVirtualRegister(TRC);
11674    emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
11675               IsThumb1, IsThumb2);
11676    emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
11677               IsThumb1, IsThumb2);
11678    srcIn = srcOut;
11679    destIn = destOut;
11680  }
11681
11682  MI.eraseFromParent(); // The instruction is gone now.
11683  return BB;
11684}
11685
11686MachineBasicBlock *
11687ARMTargetLowering::EmitLowered__chkstk(MachineInstr &MI,
11688                                       MachineBasicBlock *MBB) const {
11689  const TargetMachine &TM = getTargetMachine();
11690  const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
11691  DebugLoc DL = MI.getDebugLoc();
11692
11693  assert(Subtarget->isTargetWindows() &&
11694         "__chkstk is only supported on Windows");
11695  assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
11696
11697  // __chkstk takes the number of words to allocate on the stack in R4, and
11698  // returns the stack adjustment in number of bytes in R4.  This will not
11699  // clober any other registers (other than the obvious lr).
11700  //
11701  // Although, technically, IP should be considered a register which may be
11702  // clobbered, the call itself will not touch it.  Windows on ARM is a pure
11703  // thumb-2 environment, so there is no interworking required.  As a result, we
11704  // do not expect a veneer to be emitted by the linker, clobbering IP.
11705  //
11706  // Each module receives its own copy of __chkstk, so no import thunk is
11707  // required, again, ensuring that IP is not clobbered.
11708  //
11709  // Finally, although some linkers may theoretically provide a trampoline for
11710  // out of range calls (which is quite common due to a 32M range limitation of
11711  // branches for Thumb), we can generate the long-call version via
11712  // -mcmodel=large, alleviating the need for the trampoline which may clobber
11713  // IP.
11714
11715  switch (TM.getCodeModel()) {
11716  case CodeModel::Tiny:
11717    llvm_unreachable("Tiny code model not available on ARM.");
11718  case CodeModel::Small:
11719  case CodeModel::Medium:
11720  case CodeModel::Kernel:
11721    BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
11722        .add(predOps(ARMCC::AL))
11723        .addExternalSymbol("__chkstk")
11724        .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
11725        .addReg(ARM::R4, RegState::Implicit | RegState::Define)
11726        .addReg(ARM::R12,
11727                RegState::Implicit | RegState::Define | RegState::Dead)
11728        .addReg(ARM::CPSR,
11729                RegState::Implicit | RegState::Define | RegState::Dead);
11730    break;
11731  case CodeModel::Large: {
11732    MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
11733    Register Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
11734
11735    BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
11736      .addExternalSymbol("__chkstk");
11737    BuildMI(*MBB, MI, DL, TII.get(gettBLXrOpcode(*MBB->getParent())))
11738        .add(predOps(ARMCC::AL))
11739        .addReg(Reg, RegState::Kill)
11740        .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
11741        .addReg(ARM::R4, RegState::Implicit | RegState::Define)
11742        .addReg(ARM::R12,
11743                RegState::Implicit | RegState::Define | RegState::Dead)
11744        .addReg(ARM::CPSR,
11745                RegState::Implicit | RegState::Define | RegState::Dead);
11746    break;
11747  }
11748  }
11749
11750  BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr), ARM::SP)
11751      .addReg(ARM::SP, RegState::Kill)
11752      .addReg(ARM::R4, RegState::Kill)
11753      .setMIFlags(MachineInstr::FrameSetup)
11754      .add(predOps(ARMCC::AL))
11755      .add(condCodeOp());
11756
11757  MI.eraseFromParent();
11758  return MBB;
11759}
11760
11761MachineBasicBlock *
11762ARMTargetLowering::EmitLowered__dbzchk(MachineInstr &MI,
11763                                       MachineBasicBlock *MBB) const {
11764  DebugLoc DL = MI.getDebugLoc();
11765  MachineFunction *MF = MBB->getParent();
11766  const TargetInstrInfo *TII = Subtarget->getInstrInfo();
11767
11768  MachineBasicBlock *ContBB = MF->CreateMachineBasicBlock();
11769  MF->insert(++MBB->getIterator(), ContBB);
11770  ContBB->splice(ContBB->begin(), MBB,
11771                 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
11772  ContBB->transferSuccessorsAndUpdatePHIs(MBB);
11773  MBB->addSuccessor(ContBB);
11774
11775  MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
11776  BuildMI(TrapBB, DL, TII->get(ARM::t__brkdiv0));
11777  MF->push_back(TrapBB);
11778  MBB->addSuccessor(TrapBB);
11779
11780  BuildMI(*MBB, MI, DL, TII->get(ARM::tCMPi8))
11781      .addReg(MI.getOperand(0).getReg())
11782      .addImm(0)
11783      .add(predOps(ARMCC::AL));
11784  BuildMI(*MBB, MI, DL, TII->get(ARM::t2Bcc))
11785      .addMBB(TrapBB)
11786      .addImm(ARMCC::EQ)
11787      .addReg(ARM::CPSR);
11788
11789  MI.eraseFromParent();
11790  return ContBB;
11791}
11792
11793// The CPSR operand of SelectItr might be missing a kill marker
11794// because there were multiple uses of CPSR, and ISel didn't know
11795// which to mark. Figure out whether SelectItr should have had a
11796// kill marker, and set it if it should. Returns the correct kill
11797// marker value.
11798static bool checkAndUpdateCPSRKill(MachineBasicBlock::iterator SelectItr,
11799                                   MachineBasicBlock* BB,
11800                                   const TargetRegisterInfo* TRI) {
11801  // Scan forward through BB for a use/def of CPSR.
11802  MachineBasicBlock::iterator miI(std::next(SelectItr));
11803  for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
11804    const MachineInstr& mi = *miI;
11805    if (mi.readsRegister(ARM::CPSR))
11806      return false;
11807    if (mi.definesRegister(ARM::CPSR))
11808      break; // Should have kill-flag - update below.
11809  }
11810
11811  // If we hit the end of the block, check whether CPSR is live into a
11812  // successor.
11813  if (miI == BB->end()) {
11814    for (MachineBasicBlock *Succ : BB->successors())
11815      if (Succ->isLiveIn(ARM::CPSR))
11816        return false;
11817  }
11818
11819  // We found a def, or hit the end of the basic block and CPSR wasn't live
11820  // out. SelectMI should have a kill flag on CPSR.
11821  SelectItr->addRegisterKilled(ARM::CPSR, TRI);
11822  return true;
11823}
11824
11825/// Adds logic in loop entry MBB to calculate loop iteration count and adds
11826/// t2WhileLoopSetup and t2WhileLoopStart to generate WLS loop
11827static Register genTPEntry(MachineBasicBlock *TpEntry,
11828                           MachineBasicBlock *TpLoopBody,
11829                           MachineBasicBlock *TpExit, Register OpSizeReg,
11830                           const TargetInstrInfo *TII, DebugLoc Dl,
11831                           MachineRegisterInfo &MRI) {
11832  // Calculates loop iteration count = ceil(n/16) = (n + 15) >> 4.
11833  Register AddDestReg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
11834  BuildMI(TpEntry, Dl, TII->get(ARM::t2ADDri), AddDestReg)
11835      .addUse(OpSizeReg)
11836      .addImm(15)
11837      .add(predOps(ARMCC::AL))
11838      .addReg(0);
11839
11840  Register LsrDestReg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
11841  BuildMI(TpEntry, Dl, TII->get(ARM::t2LSRri), LsrDestReg)
11842      .addUse(AddDestReg, RegState::Kill)
11843      .addImm(4)
11844      .add(predOps(ARMCC::AL))
11845      .addReg(0);
11846
11847  Register TotalIterationsReg = MRI.createVirtualRegister(&ARM::GPRlrRegClass);
11848  BuildMI(TpEntry, Dl, TII->get(ARM::t2WhileLoopSetup), TotalIterationsReg)
11849      .addUse(LsrDestReg, RegState::Kill);
11850
11851  BuildMI(TpEntry, Dl, TII->get(ARM::t2WhileLoopStart))
11852      .addUse(TotalIterationsReg)
11853      .addMBB(TpExit);
11854
11855  BuildMI(TpEntry, Dl, TII->get(ARM::t2B))
11856      .addMBB(TpLoopBody)
11857      .add(predOps(ARMCC::AL));
11858
11859  return TotalIterationsReg;
11860}
11861
11862/// Adds logic in the loopBody MBB to generate MVE_VCTP, t2DoLoopDec and
11863/// t2DoLoopEnd. These are used by later passes to generate tail predicated
11864/// loops.
11865static void genTPLoopBody(MachineBasicBlock *TpLoopBody,
11866                          MachineBasicBlock *TpEntry, MachineBasicBlock *TpExit,
11867                          const TargetInstrInfo *TII, DebugLoc Dl,
11868                          MachineRegisterInfo &MRI, Register OpSrcReg,
11869                          Register OpDestReg, Register ElementCountReg,
11870                          Register TotalIterationsReg, bool IsMemcpy) {
11871  // First insert 4 PHI nodes for: Current pointer to Src (if memcpy), Dest
11872  // array, loop iteration counter, predication counter.
11873
11874  Register SrcPhiReg, CurrSrcReg;
11875  if (IsMemcpy) {
11876    //  Current position in the src array
11877    SrcPhiReg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
11878    CurrSrcReg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
11879    BuildMI(TpLoopBody, Dl, TII->get(ARM::PHI), SrcPhiReg)
11880        .addUse(OpSrcReg)
11881        .addMBB(TpEntry)
11882        .addUse(CurrSrcReg)
11883        .addMBB(TpLoopBody);
11884  }
11885
11886  // Current position in the dest array
11887  Register DestPhiReg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
11888  Register CurrDestReg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
11889  BuildMI(TpLoopBody, Dl, TII->get(ARM::PHI), DestPhiReg)
11890      .addUse(OpDestReg)
11891      .addMBB(TpEntry)
11892      .addUse(CurrDestReg)
11893      .addMBB(TpLoopBody);
11894
11895  // Current loop counter
11896  Register LoopCounterPhiReg = MRI.createVirtualRegister(&ARM::GPRlrRegClass);
11897  Register RemainingLoopIterationsReg =
11898      MRI.createVirtualRegister(&ARM::GPRlrRegClass);
11899  BuildMI(TpLoopBody, Dl, TII->get(ARM::PHI), LoopCounterPhiReg)
11900      .addUse(TotalIterationsReg)
11901      .addMBB(TpEntry)
11902      .addUse(RemainingLoopIterationsReg)
11903      .addMBB(TpLoopBody);
11904
11905  // Predication counter
11906  Register PredCounterPhiReg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
11907  Register RemainingElementsReg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
11908  BuildMI(TpLoopBody, Dl, TII->get(ARM::PHI), PredCounterPhiReg)
11909      .addUse(ElementCountReg)
11910      .addMBB(TpEntry)
11911      .addUse(RemainingElementsReg)
11912      .addMBB(TpLoopBody);
11913
11914  // Pass predication counter to VCTP
11915  Register VccrReg = MRI.createVirtualRegister(&ARM::VCCRRegClass);
11916  BuildMI(TpLoopBody, Dl, TII->get(ARM::MVE_VCTP8), VccrReg)
11917      .addUse(PredCounterPhiReg)
11918      .addImm(ARMVCC::None)
11919      .addReg(0)
11920      .addReg(0);
11921
11922  BuildMI(TpLoopBody, Dl, TII->get(ARM::t2SUBri), RemainingElementsReg)
11923      .addUse(PredCounterPhiReg)
11924      .addImm(16)
11925      .add(predOps(ARMCC::AL))
11926      .addReg(0);
11927
11928  // VLDRB (only if memcpy) and VSTRB instructions, predicated using VPR
11929  Register SrcValueReg;
11930  if (IsMemcpy) {
11931    SrcValueReg = MRI.createVirtualRegister(&ARM::MQPRRegClass);
11932    BuildMI(TpLoopBody, Dl, TII->get(ARM::MVE_VLDRBU8_post))
11933        .addDef(CurrSrcReg)
11934        .addDef(SrcValueReg)
11935        .addReg(SrcPhiReg)
11936        .addImm(16)
11937        .addImm(ARMVCC::Then)
11938        .addUse(VccrReg)
11939        .addReg(0);
11940  } else
11941    SrcValueReg = OpSrcReg;
11942
11943  BuildMI(TpLoopBody, Dl, TII->get(ARM::MVE_VSTRBU8_post))
11944      .addDef(CurrDestReg)
11945      .addUse(SrcValueReg)
11946      .addReg(DestPhiReg)
11947      .addImm(16)
11948      .addImm(ARMVCC::Then)
11949      .addUse(VccrReg)
11950      .addReg(0);
11951
11952  // Add the pseudoInstrs for decrementing the loop counter and marking the
11953  // end:t2DoLoopDec and t2DoLoopEnd
11954  BuildMI(TpLoopBody, Dl, TII->get(ARM::t2LoopDec), RemainingLoopIterationsReg)
11955      .addUse(LoopCounterPhiReg)
11956      .addImm(1);
11957
11958  BuildMI(TpLoopBody, Dl, TII->get(ARM::t2LoopEnd))
11959      .addUse(RemainingLoopIterationsReg)
11960      .addMBB(TpLoopBody);
11961
11962  BuildMI(TpLoopBody, Dl, TII->get(ARM::t2B))
11963      .addMBB(TpExit)
11964      .add(predOps(ARMCC::AL));
11965}
11966
11967MachineBasicBlock *
11968ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
11969                                               MachineBasicBlock *BB) const {
11970  const TargetInstrInfo *TII = Subtarget->getInstrInfo();
11971  DebugLoc dl = MI.getDebugLoc();
11972  bool isThumb2 = Subtarget->isThumb2();
11973  switch (MI.getOpcode()) {
11974  default: {
11975    MI.print(errs());
11976    llvm_unreachable("Unexpected instr type to insert");
11977  }
11978
11979  // Thumb1 post-indexed loads are really just single-register LDMs.
11980  case ARM::tLDR_postidx: {
11981    MachineOperand Def(MI.getOperand(1));
11982    BuildMI(*BB, MI, dl, TII->get(ARM::tLDMIA_UPD))
11983        .add(Def)  // Rn_wb
11984        .add(MI.getOperand(2))  // Rn
11985        .add(MI.getOperand(3))  // PredImm
11986        .add(MI.getOperand(4))  // PredReg
11987        .add(MI.getOperand(0))  // Rt
11988        .cloneMemRefs(MI);
11989    MI.eraseFromParent();
11990    return BB;
11991  }
11992
11993  case ARM::MVE_MEMCPYLOOPINST:
11994  case ARM::MVE_MEMSETLOOPINST: {
11995
11996    // Transformation below expands MVE_MEMCPYLOOPINST/MVE_MEMSETLOOPINST Pseudo
11997    // into a Tail Predicated (TP) Loop. It adds the instructions to calculate
11998    // the iteration count =ceil(size_in_bytes/16)) in the TP entry block and
11999    // adds the relevant instructions in the TP loop Body for generation of a
12000    // WLSTP loop.
12001
12002    // Below is relevant portion of the CFG after the transformation.
12003    // The Machine Basic Blocks are shown along with branch conditions (in
12004    // brackets). Note that TP entry/exit MBBs depict the entry/exit of this
12005    // portion of the CFG and may not necessarily be the entry/exit of the
12006    // function.
12007
12008    //             (Relevant) CFG after transformation:
12009    //               TP entry MBB
12010    //                   |
12011    //          |-----------------|
12012    //       (n <= 0)          (n > 0)
12013    //          |                 |
12014    //          |         TP loop Body MBB<--|
12015    //          |                |           |
12016    //           \               |___________|
12017    //            \             /
12018    //              TP exit MBB
12019
12020    MachineFunction *MF = BB->getParent();
12021    MachineFunctionProperties &Properties = MF->getProperties();
12022    MachineRegisterInfo &MRI = MF->getRegInfo();
12023
12024    Register OpDestReg = MI.getOperand(0).getReg();
12025    Register OpSrcReg = MI.getOperand(1).getReg();
12026    Register OpSizeReg = MI.getOperand(2).getReg();
12027
12028    // Allocate the required MBBs and add to parent function.
12029    MachineBasicBlock *TpEntry = BB;
12030    MachineBasicBlock *TpLoopBody = MF->CreateMachineBasicBlock();
12031    MachineBasicBlock *TpExit;
12032
12033    MF->push_back(TpLoopBody);
12034
12035    // If any instructions are present in the current block after
12036    // MVE_MEMCPYLOOPINST or MVE_MEMSETLOOPINST, split the current block and
12037    // move the instructions into the newly created exit block. If there are no
12038    // instructions add an explicit branch to the FallThrough block and then
12039    // split.
12040    //
12041    // The split is required for two reasons:
12042    // 1) A terminator(t2WhileLoopStart) will be placed at that site.
12043    // 2) Since a TPLoopBody will be added later, any phis in successive blocks
12044    //    need to be updated. splitAt() already handles this.
12045    TpExit = BB->splitAt(MI, false);
12046    if (TpExit == BB) {
12047      assert(BB->canFallThrough() && "Exit Block must be Fallthrough of the "
12048                                     "block containing memcpy/memset Pseudo");
12049      TpExit = BB->getFallThrough();
12050      BuildMI(BB, dl, TII->get(ARM::t2B))
12051          .addMBB(TpExit)
12052          .add(predOps(ARMCC::AL));
12053      TpExit = BB->splitAt(MI, false);
12054    }
12055
12056    // Add logic for iteration count
12057    Register TotalIterationsReg =
12058        genTPEntry(TpEntry, TpLoopBody, TpExit, OpSizeReg, TII, dl, MRI);
12059
12060    // Add the vectorized (and predicated) loads/store instructions
12061    bool IsMemcpy = MI.getOpcode() == ARM::MVE_MEMCPYLOOPINST;
12062    genTPLoopBody(TpLoopBody, TpEntry, TpExit, TII, dl, MRI, OpSrcReg,
12063                  OpDestReg, OpSizeReg, TotalIterationsReg, IsMemcpy);
12064
12065    // Required to avoid conflict with the MachineVerifier during testing.
12066    Properties.reset(MachineFunctionProperties::Property::NoPHIs);
12067
12068    // Connect the blocks
12069    TpEntry->addSuccessor(TpLoopBody);
12070    TpLoopBody->addSuccessor(TpLoopBody);
12071    TpLoopBody->addSuccessor(TpExit);
12072
12073    // Reorder for a more natural layout
12074    TpLoopBody->moveAfter(TpEntry);
12075    TpExit->moveAfter(TpLoopBody);
12076
12077    // Finally, remove the memcpy Pseudo Instruction
12078    MI.eraseFromParent();
12079
12080    // Return the exit block as it may contain other instructions requiring a
12081    // custom inserter
12082    return TpExit;
12083  }
12084
12085  // The Thumb2 pre-indexed stores have the same MI operands, they just
12086  // define them differently in the .td files from the isel patterns, so
12087  // they need pseudos.
12088  case ARM::t2STR_preidx:
12089    MI.setDesc(TII->get(ARM::t2STR_PRE));
12090    return BB;
12091  case ARM::t2STRB_preidx:
12092    MI.setDesc(TII->get(ARM::t2STRB_PRE));
12093    return BB;
12094  case ARM::t2STRH_preidx:
12095    MI.setDesc(TII->get(ARM::t2STRH_PRE));
12096    return BB;
12097
12098  case ARM::STRi_preidx:
12099  case ARM::STRBi_preidx: {
12100    unsigned NewOpc = MI.getOpcode() == ARM::STRi_preidx ? ARM::STR_PRE_IMM
12101                                                         : ARM::STRB_PRE_IMM;
12102    // Decode the offset.
12103    unsigned Offset = MI.getOperand(4).getImm();
12104    bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
12105    Offset = ARM_AM::getAM2Offset(Offset);
12106    if (isSub)
12107      Offset = -Offset;
12108
12109    MachineMemOperand *MMO = *MI.memoperands_begin();
12110    BuildMI(*BB, MI, dl, TII->get(NewOpc))
12111        .add(MI.getOperand(0)) // Rn_wb
12112        .add(MI.getOperand(1)) // Rt
12113        .add(MI.getOperand(2)) // Rn
12114        .addImm(Offset)        // offset (skip GPR==zero_reg)
12115        .add(MI.getOperand(5)) // pred
12116        .add(MI.getOperand(6))
12117        .addMemOperand(MMO);
12118    MI.eraseFromParent();
12119    return BB;
12120  }
12121  case ARM::STRr_preidx:
12122  case ARM::STRBr_preidx:
12123  case ARM::STRH_preidx: {
12124    unsigned NewOpc;
12125    switch (MI.getOpcode()) {
12126    default: llvm_unreachable("unexpected opcode!");
12127    case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
12128    case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
12129    case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
12130    }
12131    MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
12132    for (const MachineOperand &MO : MI.operands())
12133      MIB.add(MO);
12134    MI.eraseFromParent();
12135    return BB;
12136  }
12137
12138  case ARM::tMOVCCr_pseudo: {
12139    // To "insert" a SELECT_CC instruction, we actually have to insert the
12140    // diamond control-flow pattern.  The incoming instruction knows the
12141    // destination vreg to set, the condition code register to branch on, the
12142    // true/false values to select between, and a branch opcode to use.
12143    const BasicBlock *LLVM_BB = BB->getBasicBlock();
12144    MachineFunction::iterator It = ++BB->getIterator();
12145
12146    //  thisMBB:
12147    //  ...
12148    //   TrueVal = ...
12149    //   cmpTY ccX, r1, r2
12150    //   bCC copy1MBB
12151    //   fallthrough --> copy0MBB
12152    MachineBasicBlock *thisMBB  = BB;
12153    MachineFunction *F = BB->getParent();
12154    MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
12155    MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
12156    F->insert(It, copy0MBB);
12157    F->insert(It, sinkMBB);
12158
12159    // Set the call frame size on entry to the new basic blocks.
12160    unsigned CallFrameSize = TII->getCallFrameSizeAt(MI);
12161    copy0MBB->setCallFrameSize(CallFrameSize);
12162    sinkMBB->setCallFrameSize(CallFrameSize);
12163
12164    // Check whether CPSR is live past the tMOVCCr_pseudo.
12165    const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
12166    if (!MI.killsRegister(ARM::CPSR) &&
12167        !checkAndUpdateCPSRKill(MI, thisMBB, TRI)) {
12168      copy0MBB->addLiveIn(ARM::CPSR);
12169      sinkMBB->addLiveIn(ARM::CPSR);
12170    }
12171
12172    // Transfer the remainder of BB and its successor edges to sinkMBB.
12173    sinkMBB->splice(sinkMBB->begin(), BB,
12174                    std::next(MachineBasicBlock::iterator(MI)), BB->end());
12175    sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
12176
12177    BB->addSuccessor(copy0MBB);
12178    BB->addSuccessor(sinkMBB);
12179
12180    BuildMI(BB, dl, TII->get(ARM::tBcc))
12181        .addMBB(sinkMBB)
12182        .addImm(MI.getOperand(3).getImm())
12183        .addReg(MI.getOperand(4).getReg());
12184
12185    //  copy0MBB:
12186    //   %FalseValue = ...
12187    //   # fallthrough to sinkMBB
12188    BB = copy0MBB;
12189
12190    // Update machine-CFG edges
12191    BB->addSuccessor(sinkMBB);
12192
12193    //  sinkMBB:
12194    //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
12195    //  ...
12196    BB = sinkMBB;
12197    BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), MI.getOperand(0).getReg())
12198        .addReg(MI.getOperand(1).getReg())
12199        .addMBB(copy0MBB)
12200        .addReg(MI.getOperand(2).getReg())
12201        .addMBB(thisMBB);
12202
12203    MI.eraseFromParent(); // The pseudo instruction is gone now.
12204    return BB;
12205  }
12206
12207  case ARM::BCCi64:
12208  case ARM::BCCZi64: {
12209    // If there is an unconditional branch to the other successor, remove it.
12210    BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
12211
12212    // Compare both parts that make up the double comparison separately for
12213    // equality.
12214    bool RHSisZero = MI.getOpcode() == ARM::BCCZi64;
12215
12216    Register LHS1 = MI.getOperand(1).getReg();
12217    Register LHS2 = MI.getOperand(2).getReg();
12218    if (RHSisZero) {
12219      BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
12220          .addReg(LHS1)
12221          .addImm(0)
12222          .add(predOps(ARMCC::AL));
12223      BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
12224        .addReg(LHS2).addImm(0)
12225        .addImm(ARMCC::EQ).addReg(ARM::CPSR);
12226    } else {
12227      Register RHS1 = MI.getOperand(3).getReg();
12228      Register RHS2 = MI.getOperand(4).getReg();
12229      BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
12230          .addReg(LHS1)
12231          .addReg(RHS1)
12232          .add(predOps(ARMCC::AL));
12233      BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
12234        .addReg(LHS2).addReg(RHS2)
12235        .addImm(ARMCC::EQ).addReg(ARM::CPSR);
12236    }
12237
12238    MachineBasicBlock *destMBB = MI.getOperand(RHSisZero ? 3 : 5).getMBB();
12239    MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
12240    if (MI.getOperand(0).getImm() == ARMCC::NE)
12241      std::swap(destMBB, exitMBB);
12242
12243    BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
12244      .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
12245    if (isThumb2)
12246      BuildMI(BB, dl, TII->get(ARM::t2B))
12247          .addMBB(exitMBB)
12248          .add(predOps(ARMCC::AL));
12249    else
12250      BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
12251
12252    MI.eraseFromParent(); // The pseudo instruction is gone now.
12253    return BB;
12254  }
12255
12256  case ARM::Int_eh_sjlj_setjmp:
12257  case ARM::Int_eh_sjlj_setjmp_nofp:
12258  case ARM::tInt_eh_sjlj_setjmp:
12259  case ARM::t2Int_eh_sjlj_setjmp:
12260  case ARM::t2Int_eh_sjlj_setjmp_nofp:
12261    return BB;
12262
12263  case ARM::Int_eh_sjlj_setup_dispatch:
12264    EmitSjLjDispatchBlock(MI, BB);
12265    return BB;
12266
12267  case ARM::ABS:
12268  case ARM::t2ABS: {
12269    // To insert an ABS instruction, we have to insert the
12270    // diamond control-flow pattern.  The incoming instruction knows the
12271    // source vreg to test against 0, the destination vreg to set,
12272    // the condition code register to branch on, the
12273    // true/false values to select between, and a branch opcode to use.
12274    // It transforms
12275    //     V1 = ABS V0
12276    // into
12277    //     V2 = MOVS V0
12278    //     BCC                      (branch to SinkBB if V0 >= 0)
12279    //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
12280    //     SinkBB: V1 = PHI(V2, V3)
12281    const BasicBlock *LLVM_BB = BB->getBasicBlock();
12282    MachineFunction::iterator BBI = ++BB->getIterator();
12283    MachineFunction *Fn = BB->getParent();
12284    MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
12285    MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
12286    Fn->insert(BBI, RSBBB);
12287    Fn->insert(BBI, SinkBB);
12288
12289    Register ABSSrcReg = MI.getOperand(1).getReg();
12290    Register ABSDstReg = MI.getOperand(0).getReg();
12291    bool ABSSrcKIll = MI.getOperand(1).isKill();
12292    bool isThumb2 = Subtarget->isThumb2();
12293    MachineRegisterInfo &MRI = Fn->getRegInfo();
12294    // In Thumb mode S must not be specified if source register is the SP or
12295    // PC and if destination register is the SP, so restrict register class
12296    Register NewRsbDstReg = MRI.createVirtualRegister(
12297        isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass);
12298
12299    // Transfer the remainder of BB and its successor edges to sinkMBB.
12300    SinkBB->splice(SinkBB->begin(), BB,
12301                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
12302    SinkBB->transferSuccessorsAndUpdatePHIs(BB);
12303
12304    BB->addSuccessor(RSBBB);
12305    BB->addSuccessor(SinkBB);
12306
12307    // fall through to SinkMBB
12308    RSBBB->addSuccessor(SinkBB);
12309
12310    // insert a cmp at the end of BB
12311    BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
12312        .addReg(ABSSrcReg)
12313        .addImm(0)
12314        .add(predOps(ARMCC::AL));
12315
12316    // insert a bcc with opposite CC to ARMCC::MI at the end of BB
12317    BuildMI(BB, dl,
12318      TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
12319      .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
12320
12321    // insert rsbri in RSBBB
12322    // Note: BCC and rsbri will be converted into predicated rsbmi
12323    // by if-conversion pass
12324    BuildMI(*RSBBB, RSBBB->begin(), dl,
12325            TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
12326        .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0)
12327        .addImm(0)
12328        .add(predOps(ARMCC::AL))
12329        .add(condCodeOp());
12330
12331    // insert PHI in SinkBB,
12332    // reuse ABSDstReg to not change uses of ABS instruction
12333    BuildMI(*SinkBB, SinkBB->begin(), dl,
12334      TII->get(ARM::PHI), ABSDstReg)
12335      .addReg(NewRsbDstReg).addMBB(RSBBB)
12336      .addReg(ABSSrcReg).addMBB(BB);
12337
12338    // remove ABS instruction
12339    MI.eraseFromParent();
12340
12341    // return last added BB
12342    return SinkBB;
12343  }
12344  case ARM::COPY_STRUCT_BYVAL_I32:
12345    ++NumLoopByVals;
12346    return EmitStructByval(MI, BB);
12347  case ARM::WIN__CHKSTK:
12348    return EmitLowered__chkstk(MI, BB);
12349  case ARM::WIN__DBZCHK:
12350    return EmitLowered__dbzchk(MI, BB);
12351  }
12352}
12353
12354/// Attaches vregs to MEMCPY that it will use as scratch registers
12355/// when it is expanded into LDM/STM. This is done as a post-isel lowering
12356/// instead of as a custom inserter because we need the use list from the SDNode.
12357static void attachMEMCPYScratchRegs(const ARMSubtarget *Subtarget,
12358                                    MachineInstr &MI, const SDNode *Node) {
12359  bool isThumb1 = Subtarget->isThumb1Only();
12360
12361  DebugLoc DL = MI.getDebugLoc();
12362  MachineFunction *MF = MI.getParent()->getParent();
12363  MachineRegisterInfo &MRI = MF->getRegInfo();
12364  MachineInstrBuilder MIB(*MF, MI);
12365
12366  // If the new dst/src is unused mark it as dead.
12367  if (!Node->hasAnyUseOfValue(0)) {
12368    MI.getOperand(0).setIsDead(true);
12369  }
12370  if (!Node->hasAnyUseOfValue(1)) {
12371    MI.getOperand(1).setIsDead(true);
12372  }
12373
12374  // The MEMCPY both defines and kills the scratch registers.
12375  for (unsigned I = 0; I != MI.getOperand(4).getImm(); ++I) {
12376    Register TmpReg = MRI.createVirtualRegister(isThumb1 ? &ARM::tGPRRegClass
12377                                                         : &ARM::GPRRegClass);
12378    MIB.addReg(TmpReg, RegState::Define|RegState::Dead);
12379  }
12380}
12381
12382void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
12383                                                      SDNode *Node) const {
12384  if (MI.getOpcode() == ARM::MEMCPY) {
12385    attachMEMCPYScratchRegs(Subtarget, MI, Node);
12386    return;
12387  }
12388
12389  const MCInstrDesc *MCID = &MI.getDesc();
12390  // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
12391  // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
12392  // operand is still set to noreg. If needed, set the optional operand's
12393  // register to CPSR, and remove the redundant implicit def.
12394  //
12395  // e.g. ADCS (..., implicit-def CPSR) -> ADC (... opt:def CPSR).
12396
12397  // Rename pseudo opcodes.
12398  unsigned NewOpc = convertAddSubFlagsOpcode(MI.getOpcode());
12399  unsigned ccOutIdx;
12400  if (NewOpc) {
12401    const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo();
12402    MCID = &TII->get(NewOpc);
12403
12404    assert(MCID->getNumOperands() ==
12405           MI.getDesc().getNumOperands() + 5 - MI.getDesc().getSize()
12406        && "converted opcode should be the same except for cc_out"
12407           " (and, on Thumb1, pred)");
12408
12409    MI.setDesc(*MCID);
12410
12411    // Add the optional cc_out operand
12412    MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
12413
12414    // On Thumb1, move all input operands to the end, then add the predicate
12415    if (Subtarget->isThumb1Only()) {
12416      for (unsigned c = MCID->getNumOperands() - 4; c--;) {
12417        MI.addOperand(MI.getOperand(1));
12418        MI.removeOperand(1);
12419      }
12420
12421      // Restore the ties
12422      for (unsigned i = MI.getNumOperands(); i--;) {
12423        const MachineOperand& op = MI.getOperand(i);
12424        if (op.isReg() && op.isUse()) {
12425          int DefIdx = MCID->getOperandConstraint(i, MCOI::TIED_TO);
12426          if (DefIdx != -1)
12427            MI.tieOperands(DefIdx, i);
12428        }
12429      }
12430
12431      MI.addOperand(MachineOperand::CreateImm(ARMCC::AL));
12432      MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/false));
12433      ccOutIdx = 1;
12434    } else
12435      ccOutIdx = MCID->getNumOperands() - 1;
12436  } else
12437    ccOutIdx = MCID->getNumOperands() - 1;
12438
12439  // Any ARM instruction that sets the 's' bit should specify an optional
12440  // "cc_out" operand in the last operand position.
12441  if (!MI.hasOptionalDef() || !MCID->operands()[ccOutIdx].isOptionalDef()) {
12442    assert(!NewOpc && "Optional cc_out operand required");
12443    return;
12444  }
12445  // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
12446  // since we already have an optional CPSR def.
12447  bool definesCPSR = false;
12448  bool deadCPSR = false;
12449  for (unsigned i = MCID->getNumOperands(), e = MI.getNumOperands(); i != e;
12450       ++i) {
12451    const MachineOperand &MO = MI.getOperand(i);
12452    if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
12453      definesCPSR = true;
12454      if (MO.isDead())
12455        deadCPSR = true;
12456      MI.removeOperand(i);
12457      break;
12458    }
12459  }
12460  if (!definesCPSR) {
12461    assert(!NewOpc && "Optional cc_out operand required");
12462    return;
12463  }
12464  assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
12465  if (deadCPSR) {
12466    assert(!MI.getOperand(ccOutIdx).getReg() &&
12467           "expect uninitialized optional cc_out operand");
12468    // Thumb1 instructions must have the S bit even if the CPSR is dead.
12469    if (!Subtarget->isThumb1Only())
12470      return;
12471  }
12472
12473  // If this instruction was defined with an optional CPSR def and its dag node
12474  // had a live implicit CPSR def, then activate the optional CPSR def.
12475  MachineOperand &MO = MI.getOperand(ccOutIdx);
12476  MO.setReg(ARM::CPSR);
12477  MO.setIsDef(true);
12478}
12479
12480//===----------------------------------------------------------------------===//
12481//                           ARM Optimization Hooks
12482//===----------------------------------------------------------------------===//
12483
12484// Helper function that checks if N is a null or all ones constant.
12485static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
12486  return AllOnes ? isAllOnesConstant(N) : isNullConstant(N);
12487}
12488
12489// Return true if N is conditionally 0 or all ones.
12490// Detects these expressions where cc is an i1 value:
12491//
12492//   (select cc 0, y)   [AllOnes=0]
12493//   (select cc y, 0)   [AllOnes=0]
12494//   (zext cc)          [AllOnes=0]
12495//   (sext cc)          [AllOnes=0/1]
12496//   (select cc -1, y)  [AllOnes=1]
12497//   (select cc y, -1)  [AllOnes=1]
12498//
12499// Invert is set when N is the null/all ones constant when CC is false.
12500// OtherOp is set to the alternative value of N.
12501static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
12502                                       SDValue &CC, bool &Invert,
12503                                       SDValue &OtherOp,
12504                                       SelectionDAG &DAG) {
12505  switch (N->getOpcode()) {
12506  default: return false;
12507  case ISD::SELECT: {
12508    CC = N->getOperand(0);
12509    SDValue N1 = N->getOperand(1);
12510    SDValue N2 = N->getOperand(2);
12511    if (isZeroOrAllOnes(N1, AllOnes)) {
12512      Invert = false;
12513      OtherOp = N2;
12514      return true;
12515    }
12516    if (isZeroOrAllOnes(N2, AllOnes)) {
12517      Invert = true;
12518      OtherOp = N1;
12519      return true;
12520    }
12521    return false;
12522  }
12523  case ISD::ZERO_EXTEND:
12524    // (zext cc) can never be the all ones value.
12525    if (AllOnes)
12526      return false;
12527    [[fallthrough]];
12528  case ISD::SIGN_EXTEND: {
12529    SDLoc dl(N);
12530    EVT VT = N->getValueType(0);
12531    CC = N->getOperand(0);
12532    if (CC.getValueType() != MVT::i1 || CC.getOpcode() != ISD::SETCC)
12533      return false;
12534    Invert = !AllOnes;
12535    if (AllOnes)
12536      // When looking for an AllOnes constant, N is an sext, and the 'other'
12537      // value is 0.
12538      OtherOp = DAG.getConstant(0, dl, VT);
12539    else if (N->getOpcode() == ISD::ZERO_EXTEND)
12540      // When looking for a 0 constant, N can be zext or sext.
12541      OtherOp = DAG.getConstant(1, dl, VT);
12542    else
12543      OtherOp = DAG.getAllOnesConstant(dl, VT);
12544    return true;
12545  }
12546  }
12547}
12548
12549// Combine a constant select operand into its use:
12550//
12551//   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
12552//   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
12553//   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
12554//   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
12555//   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
12556//
12557// The transform is rejected if the select doesn't have a constant operand that
12558// is null, or all ones when AllOnes is set.
12559//
12560// Also recognize sext/zext from i1:
12561//
12562//   (add (zext cc), x) -> (select cc (add x, 1), x)
12563//   (add (sext cc), x) -> (select cc (add x, -1), x)
12564//
12565// These transformations eventually create predicated instructions.
12566//
12567// @param N       The node to transform.
12568// @param Slct    The N operand that is a select.
12569// @param OtherOp The other N operand (x above).
12570// @param DCI     Context.
12571// @param AllOnes Require the select constant to be all ones instead of null.
12572// @returns The new node, or SDValue() on failure.
12573static
12574SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
12575                            TargetLowering::DAGCombinerInfo &DCI,
12576                            bool AllOnes = false) {
12577  SelectionDAG &DAG = DCI.DAG;
12578  EVT VT = N->getValueType(0);
12579  SDValue NonConstantVal;
12580  SDValue CCOp;
12581  bool SwapSelectOps;
12582  if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
12583                                  NonConstantVal, DAG))
12584    return SDValue();
12585
12586  // Slct is now know to be the desired identity constant when CC is true.
12587  SDValue TrueVal = OtherOp;
12588  SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
12589                                 OtherOp, NonConstantVal);
12590  // Unless SwapSelectOps says CC should be false.
12591  if (SwapSelectOps)
12592    std::swap(TrueVal, FalseVal);
12593
12594  return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
12595                     CCOp, TrueVal, FalseVal);
12596}
12597
12598// Attempt combineSelectAndUse on each operand of a commutative operator N.
12599static
12600SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
12601                                       TargetLowering::DAGCombinerInfo &DCI) {
12602  SDValue N0 = N->getOperand(0);
12603  SDValue N1 = N->getOperand(1);
12604  if (N0.getNode()->hasOneUse())
12605    if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes))
12606      return Result;
12607  if (N1.getNode()->hasOneUse())
12608    if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes))
12609      return Result;
12610  return SDValue();
12611}
12612
12613static bool IsVUZPShuffleNode(SDNode *N) {
12614  // VUZP shuffle node.
12615  if (N->getOpcode() == ARMISD::VUZP)
12616    return true;
12617
12618  // "VUZP" on i32 is an alias for VTRN.
12619  if (N->getOpcode() == ARMISD::VTRN && N->getValueType(0) == MVT::v2i32)
12620    return true;
12621
12622  return false;
12623}
12624
12625static SDValue AddCombineToVPADD(SDNode *N, SDValue N0, SDValue N1,
12626                                 TargetLowering::DAGCombinerInfo &DCI,
12627                                 const ARMSubtarget *Subtarget) {
12628  // Look for ADD(VUZP.0, VUZP.1).
12629  if (!IsVUZPShuffleNode(N0.getNode()) || N0.getNode() != N1.getNode() ||
12630      N0 == N1)
12631   return SDValue();
12632
12633  // Make sure the ADD is a 64-bit add; there is no 128-bit VPADD.
12634  if (!N->getValueType(0).is64BitVector())
12635    return SDValue();
12636
12637  // Generate vpadd.
12638  SelectionDAG &DAG = DCI.DAG;
12639  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12640  SDLoc dl(N);
12641  SDNode *Unzip = N0.getNode();
12642  EVT VT = N->getValueType(0);
12643
12644  SmallVector<SDValue, 8> Ops;
12645  Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpadd, dl,
12646                                TLI.getPointerTy(DAG.getDataLayout())));
12647  Ops.push_back(Unzip->getOperand(0));
12648  Ops.push_back(Unzip->getOperand(1));
12649
12650  return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops);
12651}
12652
12653static SDValue AddCombineVUZPToVPADDL(SDNode *N, SDValue N0, SDValue N1,
12654                                      TargetLowering::DAGCombinerInfo &DCI,
12655                                      const ARMSubtarget *Subtarget) {
12656  // Check for two extended operands.
12657  if (!(N0.getOpcode() == ISD::SIGN_EXTEND &&
12658        N1.getOpcode() == ISD::SIGN_EXTEND) &&
12659      !(N0.getOpcode() == ISD::ZERO_EXTEND &&
12660        N1.getOpcode() == ISD::ZERO_EXTEND))
12661    return SDValue();
12662
12663  SDValue N00 = N0.getOperand(0);
12664  SDValue N10 = N1.getOperand(0);
12665
12666  // Look for ADD(SEXT(VUZP.0), SEXT(VUZP.1))
12667  if (!IsVUZPShuffleNode(N00.getNode()) || N00.getNode() != N10.getNode() ||
12668      N00 == N10)
12669    return SDValue();
12670
12671  // We only recognize Q register paddl here; this can't be reached until
12672  // after type legalization.
12673  if (!N00.getValueType().is64BitVector() ||
12674      !N0.getValueType().is128BitVector())
12675    return SDValue();
12676
12677  // Generate vpaddl.
12678  SelectionDAG &DAG = DCI.DAG;
12679  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12680  SDLoc dl(N);
12681  EVT VT = N->getValueType(0);
12682
12683  SmallVector<SDValue, 8> Ops;
12684  // Form vpaddl.sN or vpaddl.uN depending on the kind of extension.
12685  unsigned Opcode;
12686  if (N0.getOpcode() == ISD::SIGN_EXTEND)
12687    Opcode = Intrinsic::arm_neon_vpaddls;
12688  else
12689    Opcode = Intrinsic::arm_neon_vpaddlu;
12690  Ops.push_back(DAG.getConstant(Opcode, dl,
12691                                TLI.getPointerTy(DAG.getDataLayout())));
12692  EVT ElemTy = N00.getValueType().getVectorElementType();
12693  unsigned NumElts = VT.getVectorNumElements();
12694  EVT ConcatVT = EVT::getVectorVT(*DAG.getContext(), ElemTy, NumElts * 2);
12695  SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), ConcatVT,
12696                               N00.getOperand(0), N00.getOperand(1));
12697  Ops.push_back(Concat);
12698
12699  return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops);
12700}
12701
12702// FIXME: This function shouldn't be necessary; if we lower BUILD_VECTOR in
12703// an appropriate manner, we end up with ADD(VUZP(ZEXT(N))), which is
12704// much easier to match.
12705static SDValue
12706AddCombineBUILD_VECTORToVPADDL(SDNode *N, SDValue N0, SDValue N1,
12707                               TargetLowering::DAGCombinerInfo &DCI,
12708                               const ARMSubtarget *Subtarget) {
12709  // Only perform optimization if after legalize, and if NEON is available. We
12710  // also expected both operands to be BUILD_VECTORs.
12711  if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
12712      || N0.getOpcode() != ISD::BUILD_VECTOR
12713      || N1.getOpcode() != ISD::BUILD_VECTOR)
12714    return SDValue();
12715
12716  // Check output type since VPADDL operand elements can only be 8, 16, or 32.
12717  EVT VT = N->getValueType(0);
12718  if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
12719    return SDValue();
12720
12721  // Check that the vector operands are of the right form.
12722  // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
12723  // operands, where N is the size of the formed vector.
12724  // Each EXTRACT_VECTOR should have the same input vector and odd or even
12725  // index such that we have a pair wise add pattern.
12726
12727  // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
12728  if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
12729    return SDValue();
12730  SDValue Vec = N0->getOperand(0)->getOperand(0);
12731  SDNode *V = Vec.getNode();
12732  unsigned nextIndex = 0;
12733
12734  // For each operands to the ADD which are BUILD_VECTORs,
12735  // check to see if each of their operands are an EXTRACT_VECTOR with
12736  // the same vector and appropriate index.
12737  for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
12738    if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
12739        && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
12740
12741      SDValue ExtVec0 = N0->getOperand(i);
12742      SDValue ExtVec1 = N1->getOperand(i);
12743
12744      // First operand is the vector, verify its the same.
12745      if (V != ExtVec0->getOperand(0).getNode() ||
12746          V != ExtVec1->getOperand(0).getNode())
12747        return SDValue();
12748
12749      // Second is the constant, verify its correct.
12750      ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
12751      ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
12752
12753      // For the constant, we want to see all the even or all the odd.
12754      if (!C0 || !C1 || C0->getZExtValue() != nextIndex
12755          || C1->getZExtValue() != nextIndex+1)
12756        return SDValue();
12757
12758      // Increment index.
12759      nextIndex+=2;
12760    } else
12761      return SDValue();
12762  }
12763
12764  // Don't generate vpaddl+vmovn; we'll match it to vpadd later. Also make sure
12765  // we're using the entire input vector, otherwise there's a size/legality
12766  // mismatch somewhere.
12767  if (nextIndex != Vec.getValueType().getVectorNumElements() ||
12768      Vec.getValueType().getVectorElementType() == VT.getVectorElementType())
12769    return SDValue();
12770
12771  // Create VPADDL node.
12772  SelectionDAG &DAG = DCI.DAG;
12773  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12774
12775  SDLoc dl(N);
12776
12777  // Build operand list.
12778  SmallVector<SDValue, 8> Ops;
12779  Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl,
12780                                TLI.getPointerTy(DAG.getDataLayout())));
12781
12782  // Input is the vector.
12783  Ops.push_back(Vec);
12784
12785  // Get widened type and narrowed type.
12786  MVT widenType;
12787  unsigned numElem = VT.getVectorNumElements();
12788
12789  EVT inputLaneType = Vec.getValueType().getVectorElementType();
12790  switch (inputLaneType.getSimpleVT().SimpleTy) {
12791    case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
12792    case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
12793    case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
12794    default:
12795      llvm_unreachable("Invalid vector element type for padd optimization.");
12796  }
12797
12798  SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops);
12799  unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
12800  return DAG.getNode(ExtOp, dl, VT, tmp);
12801}
12802
12803static SDValue findMUL_LOHI(SDValue V) {
12804  if (V->getOpcode() == ISD::UMUL_LOHI ||
12805      V->getOpcode() == ISD::SMUL_LOHI)
12806    return V;
12807  return SDValue();
12808}
12809
12810static SDValue AddCombineTo64BitSMLAL16(SDNode *AddcNode, SDNode *AddeNode,
12811                                        TargetLowering::DAGCombinerInfo &DCI,
12812                                        const ARMSubtarget *Subtarget) {
12813  if (!Subtarget->hasBaseDSP())
12814    return SDValue();
12815
12816  // SMLALBB, SMLALBT, SMLALTB, SMLALTT multiply two 16-bit values and
12817  // accumulates the product into a 64-bit value. The 16-bit values will
12818  // be sign extended somehow or SRA'd into 32-bit values
12819  // (addc (adde (mul 16bit, 16bit), lo), hi)
12820  SDValue Mul = AddcNode->getOperand(0);
12821  SDValue Lo = AddcNode->getOperand(1);
12822  if (Mul.getOpcode() != ISD::MUL) {
12823    Lo = AddcNode->getOperand(0);
12824    Mul = AddcNode->getOperand(1);
12825    if (Mul.getOpcode() != ISD::MUL)
12826      return SDValue();
12827  }
12828
12829  SDValue SRA = AddeNode->getOperand(0);
12830  SDValue Hi = AddeNode->getOperand(1);
12831  if (SRA.getOpcode() != ISD::SRA) {
12832    SRA = AddeNode->getOperand(1);
12833    Hi = AddeNode->getOperand(0);
12834    if (SRA.getOpcode() != ISD::SRA)
12835      return SDValue();
12836  }
12837  if (auto Const = dyn_cast<ConstantSDNode>(SRA.getOperand(1))) {
12838    if (Const->getZExtValue() != 31)
12839      return SDValue();
12840  } else
12841    return SDValue();
12842
12843  if (SRA.getOperand(0) != Mul)
12844    return SDValue();
12845
12846  SelectionDAG &DAG = DCI.DAG;
12847  SDLoc dl(AddcNode);
12848  unsigned Opcode = 0;
12849  SDValue Op0;
12850  SDValue Op1;
12851
12852  if (isS16(Mul.getOperand(0), DAG) && isS16(Mul.getOperand(1), DAG)) {
12853    Opcode = ARMISD::SMLALBB;
12854    Op0 = Mul.getOperand(0);
12855    Op1 = Mul.getOperand(1);
12856  } else if (isS16(Mul.getOperand(0), DAG) && isSRA16(Mul.getOperand(1))) {
12857    Opcode = ARMISD::SMLALBT;
12858    Op0 = Mul.getOperand(0);
12859    Op1 = Mul.getOperand(1).getOperand(0);
12860  } else if (isSRA16(Mul.getOperand(0)) && isS16(Mul.getOperand(1), DAG)) {
12861    Opcode = ARMISD::SMLALTB;
12862    Op0 = Mul.getOperand(0).getOperand(0);
12863    Op1 = Mul.getOperand(1);
12864  } else if (isSRA16(Mul.getOperand(0)) && isSRA16(Mul.getOperand(1))) {
12865    Opcode = ARMISD::SMLALTT;
12866    Op0 = Mul->getOperand(0).getOperand(0);
12867    Op1 = Mul->getOperand(1).getOperand(0);
12868  }
12869
12870  if (!Op0 || !Op1)
12871    return SDValue();
12872
12873  SDValue SMLAL = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
12874                              Op0, Op1, Lo, Hi);
12875  // Replace the ADDs' nodes uses by the MLA node's values.
12876  SDValue HiMLALResult(SMLAL.getNode(), 1);
12877  SDValue LoMLALResult(SMLAL.getNode(), 0);
12878
12879  DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
12880  DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
12881
12882  // Return original node to notify the driver to stop replacing.
12883  SDValue resNode(AddcNode, 0);
12884  return resNode;
12885}
12886
12887static SDValue AddCombineTo64bitMLAL(SDNode *AddeSubeNode,
12888                                     TargetLowering::DAGCombinerInfo &DCI,
12889                                     const ARMSubtarget *Subtarget) {
12890  // Look for multiply add opportunities.
12891  // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
12892  // each add nodes consumes a value from ISD::UMUL_LOHI and there is
12893  // a glue link from the first add to the second add.
12894  // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
12895  // a S/UMLAL instruction.
12896  //                  UMUL_LOHI
12897  //                 / :lo    \ :hi
12898  //                V          \          [no multiline comment]
12899  //    loAdd ->  ADDC         |
12900  //                 \ :carry /
12901  //                  V      V
12902  //                    ADDE   <- hiAdd
12903  //
12904  // In the special case where only the higher part of a signed result is used
12905  // and the add to the low part of the result of ISD::UMUL_LOHI adds or subtracts
12906  // a constant with the exact value of 0x80000000, we recognize we are dealing
12907  // with a "rounded multiply and add" (or subtract) and transform it into
12908  // either a ARMISD::SMMLAR or ARMISD::SMMLSR respectively.
12909
12910  assert((AddeSubeNode->getOpcode() == ARMISD::ADDE ||
12911          AddeSubeNode->getOpcode() == ARMISD::SUBE) &&
12912         "Expect an ADDE or SUBE");
12913
12914  assert(AddeSubeNode->getNumOperands() == 3 &&
12915         AddeSubeNode->getOperand(2).getValueType() == MVT::i32 &&
12916         "ADDE node has the wrong inputs");
12917
12918  // Check that we are chained to the right ADDC or SUBC node.
12919  SDNode *AddcSubcNode = AddeSubeNode->getOperand(2).getNode();
12920  if ((AddeSubeNode->getOpcode() == ARMISD::ADDE &&
12921       AddcSubcNode->getOpcode() != ARMISD::ADDC) ||
12922      (AddeSubeNode->getOpcode() == ARMISD::SUBE &&
12923       AddcSubcNode->getOpcode() != ARMISD::SUBC))
12924    return SDValue();
12925
12926  SDValue AddcSubcOp0 = AddcSubcNode->getOperand(0);
12927  SDValue AddcSubcOp1 = AddcSubcNode->getOperand(1);
12928
12929  // Check if the two operands are from the same mul_lohi node.
12930  if (AddcSubcOp0.getNode() == AddcSubcOp1.getNode())
12931    return SDValue();
12932
12933  assert(AddcSubcNode->getNumValues() == 2 &&
12934         AddcSubcNode->getValueType(0) == MVT::i32 &&
12935         "Expect ADDC with two result values. First: i32");
12936
12937  // Check that the ADDC adds the low result of the S/UMUL_LOHI. If not, it
12938  // maybe a SMLAL which multiplies two 16-bit values.
12939  if (AddeSubeNode->getOpcode() == ARMISD::ADDE &&
12940      AddcSubcOp0->getOpcode() != ISD::UMUL_LOHI &&
12941      AddcSubcOp0->getOpcode() != ISD::SMUL_LOHI &&
12942      AddcSubcOp1->getOpcode() != ISD::UMUL_LOHI &&
12943      AddcSubcOp1->getOpcode() != ISD::SMUL_LOHI)
12944    return AddCombineTo64BitSMLAL16(AddcSubcNode, AddeSubeNode, DCI, Subtarget);
12945
12946  // Check for the triangle shape.
12947  SDValue AddeSubeOp0 = AddeSubeNode->getOperand(0);
12948  SDValue AddeSubeOp1 = AddeSubeNode->getOperand(1);
12949
12950  // Make sure that the ADDE/SUBE operands are not coming from the same node.
12951  if (AddeSubeOp0.getNode() == AddeSubeOp1.getNode())
12952    return SDValue();
12953
12954  // Find the MUL_LOHI node walking up ADDE/SUBE's operands.
12955  bool IsLeftOperandMUL = false;
12956  SDValue MULOp = findMUL_LOHI(AddeSubeOp0);
12957  if (MULOp == SDValue())
12958    MULOp = findMUL_LOHI(AddeSubeOp1);
12959  else
12960    IsLeftOperandMUL = true;
12961  if (MULOp == SDValue())
12962    return SDValue();
12963
12964  // Figure out the right opcode.
12965  unsigned Opc = MULOp->getOpcode();
12966  unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
12967
12968  // Figure out the high and low input values to the MLAL node.
12969  SDValue *HiAddSub = nullptr;
12970  SDValue *LoMul = nullptr;
12971  SDValue *LowAddSub = nullptr;
12972
12973  // Ensure that ADDE/SUBE is from high result of ISD::xMUL_LOHI.
12974  if ((AddeSubeOp0 != MULOp.getValue(1)) && (AddeSubeOp1 != MULOp.getValue(1)))
12975    return SDValue();
12976
12977  if (IsLeftOperandMUL)
12978    HiAddSub = &AddeSubeOp1;
12979  else
12980    HiAddSub = &AddeSubeOp0;
12981
12982  // Ensure that LoMul and LowAddSub are taken from correct ISD::SMUL_LOHI node
12983  // whose low result is fed to the ADDC/SUBC we are checking.
12984
12985  if (AddcSubcOp0 == MULOp.getValue(0)) {
12986    LoMul = &AddcSubcOp0;
12987    LowAddSub = &AddcSubcOp1;
12988  }
12989  if (AddcSubcOp1 == MULOp.getValue(0)) {
12990    LoMul = &AddcSubcOp1;
12991    LowAddSub = &AddcSubcOp0;
12992  }
12993
12994  if (!LoMul)
12995    return SDValue();
12996
12997  // If HiAddSub is the same node as ADDC/SUBC or is a predecessor of ADDC/SUBC
12998  // the replacement below will create a cycle.
12999  if (AddcSubcNode == HiAddSub->getNode() ||
13000      AddcSubcNode->isPredecessorOf(HiAddSub->getNode()))
13001    return SDValue();
13002
13003  // Create the merged node.
13004  SelectionDAG &DAG = DCI.DAG;
13005
13006  // Start building operand list.
13007  SmallVector<SDValue, 8> Ops;
13008  Ops.push_back(LoMul->getOperand(0));
13009  Ops.push_back(LoMul->getOperand(1));
13010
13011  // Check whether we can use SMMLAR, SMMLSR or SMMULR instead.  For this to be
13012  // the case, we must be doing signed multiplication and only use the higher
13013  // part of the result of the MLAL, furthermore the LowAddSub must be a constant
13014  // addition or subtraction with the value of 0x800000.
13015  if (Subtarget->hasV6Ops() && Subtarget->hasDSP() && Subtarget->useMulOps() &&
13016      FinalOpc == ARMISD::SMLAL && !AddeSubeNode->hasAnyUseOfValue(1) &&
13017      LowAddSub->getNode()->getOpcode() == ISD::Constant &&
13018      static_cast<ConstantSDNode *>(LowAddSub->getNode())->getZExtValue() ==
13019          0x80000000) {
13020    Ops.push_back(*HiAddSub);
13021    if (AddcSubcNode->getOpcode() == ARMISD::SUBC) {
13022      FinalOpc = ARMISD::SMMLSR;
13023    } else {
13024      FinalOpc = ARMISD::SMMLAR;
13025    }
13026    SDValue NewNode = DAG.getNode(FinalOpc, SDLoc(AddcSubcNode), MVT::i32, Ops);
13027    DAG.ReplaceAllUsesOfValueWith(SDValue(AddeSubeNode, 0), NewNode);
13028
13029    return SDValue(AddeSubeNode, 0);
13030  } else if (AddcSubcNode->getOpcode() == ARMISD::SUBC)
13031    // SMMLS is generated during instruction selection and the rest of this
13032    // function can not handle the case where AddcSubcNode is a SUBC.
13033    return SDValue();
13034
13035  // Finish building the operand list for {U/S}MLAL
13036  Ops.push_back(*LowAddSub);
13037  Ops.push_back(*HiAddSub);
13038
13039  SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcSubcNode),
13040                                 DAG.getVTList(MVT::i32, MVT::i32), Ops);
13041
13042  // Replace the ADDs' nodes uses by the MLA node's values.
13043  SDValue HiMLALResult(MLALNode.getNode(), 1);
13044  DAG.ReplaceAllUsesOfValueWith(SDValue(AddeSubeNode, 0), HiMLALResult);
13045
13046  SDValue LoMLALResult(MLALNode.getNode(), 0);
13047  DAG.ReplaceAllUsesOfValueWith(SDValue(AddcSubcNode, 0), LoMLALResult);
13048
13049  // Return original node to notify the driver to stop replacing.
13050  return SDValue(AddeSubeNode, 0);
13051}
13052
13053static SDValue AddCombineTo64bitUMAAL(SDNode *AddeNode,
13054                                      TargetLowering::DAGCombinerInfo &DCI,
13055                                      const ARMSubtarget *Subtarget) {
13056  // UMAAL is similar to UMLAL except that it adds two unsigned values.
13057  // While trying to combine for the other MLAL nodes, first search for the
13058  // chance to use UMAAL. Check if Addc uses a node which has already
13059  // been combined into a UMLAL. The other pattern is UMLAL using Addc/Adde
13060  // as the addend, and it's handled in PerformUMLALCombine.
13061
13062  if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP())
13063    return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget);
13064
13065  // Check that we have a glued ADDC node.
13066  SDNode* AddcNode = AddeNode->getOperand(2).getNode();
13067  if (AddcNode->getOpcode() != ARMISD::ADDC)
13068    return SDValue();
13069
13070  // Find the converted UMAAL or quit if it doesn't exist.
13071  SDNode *UmlalNode = nullptr;
13072  SDValue AddHi;
13073  if (AddcNode->getOperand(0).getOpcode() == ARMISD::UMLAL) {
13074    UmlalNode = AddcNode->getOperand(0).getNode();
13075    AddHi = AddcNode->getOperand(1);
13076  } else if (AddcNode->getOperand(1).getOpcode() == ARMISD::UMLAL) {
13077    UmlalNode = AddcNode->getOperand(1).getNode();
13078    AddHi = AddcNode->getOperand(0);
13079  } else {
13080    return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget);
13081  }
13082
13083  // The ADDC should be glued to an ADDE node, which uses the same UMLAL as
13084  // the ADDC as well as Zero.
13085  if (!isNullConstant(UmlalNode->getOperand(3)))
13086    return SDValue();
13087
13088  if ((isNullConstant(AddeNode->getOperand(0)) &&
13089       AddeNode->getOperand(1).getNode() == UmlalNode) ||
13090      (AddeNode->getOperand(0).getNode() == UmlalNode &&
13091       isNullConstant(AddeNode->getOperand(1)))) {
13092    SelectionDAG &DAG = DCI.DAG;
13093    SDValue Ops[] = { UmlalNode->getOperand(0), UmlalNode->getOperand(1),
13094                      UmlalNode->getOperand(2), AddHi };
13095    SDValue UMAAL =  DAG.getNode(ARMISD::UMAAL, SDLoc(AddcNode),
13096                                 DAG.getVTList(MVT::i32, MVT::i32), Ops);
13097
13098    // Replace the ADDs' nodes uses by the UMAAL node's values.
13099    DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), SDValue(UMAAL.getNode(), 1));
13100    DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), SDValue(UMAAL.getNode(), 0));
13101
13102    // Return original node to notify the driver to stop replacing.
13103    return SDValue(AddeNode, 0);
13104  }
13105  return SDValue();
13106}
13107
13108static SDValue PerformUMLALCombine(SDNode *N, SelectionDAG &DAG,
13109                                   const ARMSubtarget *Subtarget) {
13110  if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP())
13111    return SDValue();
13112
13113  // Check that we have a pair of ADDC and ADDE as operands.
13114  // Both addends of the ADDE must be zero.
13115  SDNode* AddcNode = N->getOperand(2).getNode();
13116  SDNode* AddeNode = N->getOperand(3).getNode();
13117  if ((AddcNode->getOpcode() == ARMISD::ADDC) &&
13118      (AddeNode->getOpcode() == ARMISD::ADDE) &&
13119      isNullConstant(AddeNode->getOperand(0)) &&
13120      isNullConstant(AddeNode->getOperand(1)) &&
13121      (AddeNode->getOperand(2).getNode() == AddcNode))
13122    return DAG.getNode(ARMISD::UMAAL, SDLoc(N),
13123                       DAG.getVTList(MVT::i32, MVT::i32),
13124                       {N->getOperand(0), N->getOperand(1),
13125                        AddcNode->getOperand(0), AddcNode->getOperand(1)});
13126  else
13127    return SDValue();
13128}
13129
13130static SDValue PerformAddcSubcCombine(SDNode *N,
13131                                      TargetLowering::DAGCombinerInfo &DCI,
13132                                      const ARMSubtarget *Subtarget) {
13133  SelectionDAG &DAG(DCI.DAG);
13134
13135  if (N->getOpcode() == ARMISD::SUBC && N->hasAnyUseOfValue(1)) {
13136    // (SUBC (ADDE 0, 0, C), 1) -> C
13137    SDValue LHS = N->getOperand(0);
13138    SDValue RHS = N->getOperand(1);
13139    if (LHS->getOpcode() == ARMISD::ADDE &&
13140        isNullConstant(LHS->getOperand(0)) &&
13141        isNullConstant(LHS->getOperand(1)) && isOneConstant(RHS)) {
13142      return DCI.CombineTo(N, SDValue(N, 0), LHS->getOperand(2));
13143    }
13144  }
13145
13146  if (Subtarget->isThumb1Only()) {
13147    SDValue RHS = N->getOperand(1);
13148    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) {
13149      int32_t imm = C->getSExtValue();
13150      if (imm < 0 && imm > std::numeric_limits<int>::min()) {
13151        SDLoc DL(N);
13152        RHS = DAG.getConstant(-imm, DL, MVT::i32);
13153        unsigned Opcode = (N->getOpcode() == ARMISD::ADDC) ? ARMISD::SUBC
13154                                                           : ARMISD::ADDC;
13155        return DAG.getNode(Opcode, DL, N->getVTList(), N->getOperand(0), RHS);
13156      }
13157    }
13158  }
13159
13160  return SDValue();
13161}
13162
13163static SDValue PerformAddeSubeCombine(SDNode *N,
13164                                      TargetLowering::DAGCombinerInfo &DCI,
13165                                      const ARMSubtarget *Subtarget) {
13166  if (Subtarget->isThumb1Only()) {
13167    SelectionDAG &DAG = DCI.DAG;
13168    SDValue RHS = N->getOperand(1);
13169    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) {
13170      int64_t imm = C->getSExtValue();
13171      if (imm < 0) {
13172        SDLoc DL(N);
13173
13174        // The with-carry-in form matches bitwise not instead of the negation.
13175        // Effectively, the inverse interpretation of the carry flag already
13176        // accounts for part of the negation.
13177        RHS = DAG.getConstant(~imm, DL, MVT::i32);
13178
13179        unsigned Opcode = (N->getOpcode() == ARMISD::ADDE) ? ARMISD::SUBE
13180                                                           : ARMISD::ADDE;
13181        return DAG.getNode(Opcode, DL, N->getVTList(),
13182                           N->getOperand(0), RHS, N->getOperand(2));
13183      }
13184    }
13185  } else if (N->getOperand(1)->getOpcode() == ISD::SMUL_LOHI) {
13186    return AddCombineTo64bitMLAL(N, DCI, Subtarget);
13187  }
13188  return SDValue();
13189}
13190
13191static SDValue PerformSELECTCombine(SDNode *N,
13192                                    TargetLowering::DAGCombinerInfo &DCI,
13193                                    const ARMSubtarget *Subtarget) {
13194  if (!Subtarget->hasMVEIntegerOps())
13195    return SDValue();
13196
13197  SDLoc dl(N);
13198  SDValue SetCC;
13199  SDValue LHS;
13200  SDValue RHS;
13201  ISD::CondCode CC;
13202  SDValue TrueVal;
13203  SDValue FalseVal;
13204
13205  if (N->getOpcode() == ISD::SELECT &&
13206      N->getOperand(0)->getOpcode() == ISD::SETCC) {
13207    SetCC = N->getOperand(0);
13208    LHS = SetCC->getOperand(0);
13209    RHS = SetCC->getOperand(1);
13210    CC = cast<CondCodeSDNode>(SetCC->getOperand(2))->get();
13211    TrueVal = N->getOperand(1);
13212    FalseVal = N->getOperand(2);
13213  } else if (N->getOpcode() == ISD::SELECT_CC) {
13214    LHS = N->getOperand(0);
13215    RHS = N->getOperand(1);
13216    CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
13217    TrueVal = N->getOperand(2);
13218    FalseVal = N->getOperand(3);
13219  } else {
13220    return SDValue();
13221  }
13222
13223  unsigned int Opcode = 0;
13224  if ((TrueVal->getOpcode() == ISD::VECREDUCE_UMIN ||
13225       FalseVal->getOpcode() == ISD::VECREDUCE_UMIN) &&
13226      (CC == ISD::SETULT || CC == ISD::SETUGT)) {
13227    Opcode = ARMISD::VMINVu;
13228    if (CC == ISD::SETUGT)
13229      std::swap(TrueVal, FalseVal);
13230  } else if ((TrueVal->getOpcode() == ISD::VECREDUCE_SMIN ||
13231              FalseVal->getOpcode() == ISD::VECREDUCE_SMIN) &&
13232             (CC == ISD::SETLT || CC == ISD::SETGT)) {
13233    Opcode = ARMISD::VMINVs;
13234    if (CC == ISD::SETGT)
13235      std::swap(TrueVal, FalseVal);
13236  } else if ((TrueVal->getOpcode() == ISD::VECREDUCE_UMAX ||
13237              FalseVal->getOpcode() == ISD::VECREDUCE_UMAX) &&
13238             (CC == ISD::SETUGT || CC == ISD::SETULT)) {
13239    Opcode = ARMISD::VMAXVu;
13240    if (CC == ISD::SETULT)
13241      std::swap(TrueVal, FalseVal);
13242  } else if ((TrueVal->getOpcode() == ISD::VECREDUCE_SMAX ||
13243              FalseVal->getOpcode() == ISD::VECREDUCE_SMAX) &&
13244             (CC == ISD::SETGT || CC == ISD::SETLT)) {
13245    Opcode = ARMISD::VMAXVs;
13246    if (CC == ISD::SETLT)
13247      std::swap(TrueVal, FalseVal);
13248  } else
13249    return SDValue();
13250
13251  // Normalise to the right hand side being the vector reduction
13252  switch (TrueVal->getOpcode()) {
13253  case ISD::VECREDUCE_UMIN:
13254  case ISD::VECREDUCE_SMIN:
13255  case ISD::VECREDUCE_UMAX:
13256  case ISD::VECREDUCE_SMAX:
13257    std::swap(LHS, RHS);
13258    std::swap(TrueVal, FalseVal);
13259    break;
13260  }
13261
13262  EVT VectorType = FalseVal->getOperand(0).getValueType();
13263
13264  if (VectorType != MVT::v16i8 && VectorType != MVT::v8i16 &&
13265      VectorType != MVT::v4i32)
13266    return SDValue();
13267
13268  EVT VectorScalarType = VectorType.getVectorElementType();
13269
13270  // The values being selected must also be the ones being compared
13271  if (TrueVal != LHS || FalseVal != RHS)
13272    return SDValue();
13273
13274  EVT LeftType = LHS->getValueType(0);
13275  EVT RightType = RHS->getValueType(0);
13276
13277  // The types must match the reduced type too
13278  if (LeftType != VectorScalarType || RightType != VectorScalarType)
13279    return SDValue();
13280
13281  // Legalise the scalar to an i32
13282  if (VectorScalarType != MVT::i32)
13283    LHS = DCI.DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
13284
13285  // Generate the reduction as an i32 for legalisation purposes
13286  auto Reduction =
13287      DCI.DAG.getNode(Opcode, dl, MVT::i32, LHS, RHS->getOperand(0));
13288
13289  // The result isn't actually an i32 so truncate it back to its original type
13290  if (VectorScalarType != MVT::i32)
13291    Reduction = DCI.DAG.getNode(ISD::TRUNCATE, dl, VectorScalarType, Reduction);
13292
13293  return Reduction;
13294}
13295
13296// A special combine for the vqdmulh family of instructions. This is one of the
13297// potential set of patterns that could patch this instruction. The base pattern
13298// you would expect to be min(max(ashr(mul(mul(sext(x), 2), sext(y)), 16))).
13299// This matches the different min(max(ashr(mul(mul(sext(x), sext(y)), 2), 16))),
13300// which llvm will have optimized to min(ashr(mul(sext(x), sext(y)), 15))) as
13301// the max is unnecessary.
13302static SDValue PerformVQDMULHCombine(SDNode *N, SelectionDAG &DAG) {
13303  EVT VT = N->getValueType(0);
13304  SDValue Shft;
13305  ConstantSDNode *Clamp;
13306
13307  if (!VT.isVector() || VT.getScalarSizeInBits() > 64)
13308    return SDValue();
13309
13310  if (N->getOpcode() == ISD::SMIN) {
13311    Shft = N->getOperand(0);
13312    Clamp = isConstOrConstSplat(N->getOperand(1));
13313  } else if (N->getOpcode() == ISD::VSELECT) {
13314    // Detect a SMIN, which for an i64 node will be a vselect/setcc, not a smin.
13315    SDValue Cmp = N->getOperand(0);
13316    if (Cmp.getOpcode() != ISD::SETCC ||
13317        cast<CondCodeSDNode>(Cmp.getOperand(2))->get() != ISD::SETLT ||
13318        Cmp.getOperand(0) != N->getOperand(1) ||
13319        Cmp.getOperand(1) != N->getOperand(2))
13320      return SDValue();
13321    Shft = N->getOperand(1);
13322    Clamp = isConstOrConstSplat(N->getOperand(2));
13323  } else
13324    return SDValue();
13325
13326  if (!Clamp)
13327    return SDValue();
13328
13329  MVT ScalarType;
13330  int ShftAmt = 0;
13331  switch (Clamp->getSExtValue()) {
13332  case (1 << 7) - 1:
13333    ScalarType = MVT::i8;
13334    ShftAmt = 7;
13335    break;
13336  case (1 << 15) - 1:
13337    ScalarType = MVT::i16;
13338    ShftAmt = 15;
13339    break;
13340  case (1ULL << 31) - 1:
13341    ScalarType = MVT::i32;
13342    ShftAmt = 31;
13343    break;
13344  default:
13345    return SDValue();
13346  }
13347
13348  if (Shft.getOpcode() != ISD::SRA)
13349    return SDValue();
13350  ConstantSDNode *N1 = isConstOrConstSplat(Shft.getOperand(1));
13351  if (!N1 || N1->getSExtValue() != ShftAmt)
13352    return SDValue();
13353
13354  SDValue Mul = Shft.getOperand(0);
13355  if (Mul.getOpcode() != ISD::MUL)
13356    return SDValue();
13357
13358  SDValue Ext0 = Mul.getOperand(0);
13359  SDValue Ext1 = Mul.getOperand(1);
13360  if (Ext0.getOpcode() != ISD::SIGN_EXTEND ||
13361      Ext1.getOpcode() != ISD::SIGN_EXTEND)
13362    return SDValue();
13363  EVT VecVT = Ext0.getOperand(0).getValueType();
13364  if (!VecVT.isPow2VectorType() || VecVT.getVectorNumElements() == 1)
13365    return SDValue();
13366  if (Ext1.getOperand(0).getValueType() != VecVT ||
13367      VecVT.getScalarType() != ScalarType ||
13368      VT.getScalarSizeInBits() < ScalarType.getScalarSizeInBits() * 2)
13369    return SDValue();
13370
13371  SDLoc DL(Mul);
13372  unsigned LegalLanes = 128 / (ShftAmt + 1);
13373  EVT LegalVecVT = MVT::getVectorVT(ScalarType, LegalLanes);
13374  // For types smaller than legal vectors extend to be legal and only use needed
13375  // lanes.
13376  if (VecVT.getSizeInBits() < 128) {
13377    EVT ExtVecVT =
13378        MVT::getVectorVT(MVT::getIntegerVT(128 / VecVT.getVectorNumElements()),
13379                         VecVT.getVectorNumElements());
13380    SDValue Inp0 =
13381        DAG.getNode(ISD::ANY_EXTEND, DL, ExtVecVT, Ext0.getOperand(0));
13382    SDValue Inp1 =
13383        DAG.getNode(ISD::ANY_EXTEND, DL, ExtVecVT, Ext1.getOperand(0));
13384    Inp0 = DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, LegalVecVT, Inp0);
13385    Inp1 = DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, LegalVecVT, Inp1);
13386    SDValue VQDMULH = DAG.getNode(ARMISD::VQDMULH, DL, LegalVecVT, Inp0, Inp1);
13387    SDValue Trunc = DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, ExtVecVT, VQDMULH);
13388    Trunc = DAG.getNode(ISD::TRUNCATE, DL, VecVT, Trunc);
13389    return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Trunc);
13390  }
13391
13392  // For larger types, split into legal sized chunks.
13393  assert(VecVT.getSizeInBits() % 128 == 0 && "Expected a power2 type");
13394  unsigned NumParts = VecVT.getSizeInBits() / 128;
13395  SmallVector<SDValue> Parts;
13396  for (unsigned I = 0; I < NumParts; ++I) {
13397    SDValue Inp0 =
13398        DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, LegalVecVT, Ext0.getOperand(0),
13399                    DAG.getVectorIdxConstant(I * LegalLanes, DL));
13400    SDValue Inp1 =
13401        DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, LegalVecVT, Ext1.getOperand(0),
13402                    DAG.getVectorIdxConstant(I * LegalLanes, DL));
13403    SDValue VQDMULH = DAG.getNode(ARMISD::VQDMULH, DL, LegalVecVT, Inp0, Inp1);
13404    Parts.push_back(VQDMULH);
13405  }
13406  return DAG.getNode(ISD::SIGN_EXTEND, DL, VT,
13407                     DAG.getNode(ISD::CONCAT_VECTORS, DL, VecVT, Parts));
13408}
13409
13410static SDValue PerformVSELECTCombine(SDNode *N,
13411                                     TargetLowering::DAGCombinerInfo &DCI,
13412                                     const ARMSubtarget *Subtarget) {
13413  if (!Subtarget->hasMVEIntegerOps())
13414    return SDValue();
13415
13416  if (SDValue V = PerformVQDMULHCombine(N, DCI.DAG))
13417    return V;
13418
13419  // Transforms vselect(not(cond), lhs, rhs) into vselect(cond, rhs, lhs).
13420  //
13421  // We need to re-implement this optimization here as the implementation in the
13422  // Target-Independent DAGCombiner does not handle the kind of constant we make
13423  // (it calls isConstOrConstSplat with AllowTruncation set to false - and for
13424  // good reason, allowing truncation there would break other targets).
13425  //
13426  // Currently, this is only done for MVE, as it's the only target that benefits
13427  // from this transformation (e.g. VPNOT+VPSEL becomes a single VPSEL).
13428  if (N->getOperand(0).getOpcode() != ISD::XOR)
13429    return SDValue();
13430  SDValue XOR = N->getOperand(0);
13431
13432  // Check if the XOR's RHS is either a 1, or a BUILD_VECTOR of 1s.
13433  // It is important to check with truncation allowed as the BUILD_VECTORs we
13434  // generate in those situations will truncate their operands.
13435  ConstantSDNode *Const =
13436      isConstOrConstSplat(XOR->getOperand(1), /*AllowUndefs*/ false,
13437                          /*AllowTruncation*/ true);
13438  if (!Const || !Const->isOne())
13439    return SDValue();
13440
13441  // Rewrite into vselect(cond, rhs, lhs).
13442  SDValue Cond = XOR->getOperand(0);
13443  SDValue LHS = N->getOperand(1);
13444  SDValue RHS = N->getOperand(2);
13445  EVT Type = N->getValueType(0);
13446  return DCI.DAG.getNode(ISD::VSELECT, SDLoc(N), Type, Cond, RHS, LHS);
13447}
13448
13449// Convert vsetcc([0,1,2,..], splat(n), ult) -> vctp n
13450static SDValue PerformVSetCCToVCTPCombine(SDNode *N,
13451                                          TargetLowering::DAGCombinerInfo &DCI,
13452                                          const ARMSubtarget *Subtarget) {
13453  SDValue Op0 = N->getOperand(0);
13454  SDValue Op1 = N->getOperand(1);
13455  ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
13456  EVT VT = N->getValueType(0);
13457
13458  if (!Subtarget->hasMVEIntegerOps() ||
13459      !DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
13460    return SDValue();
13461
13462  if (CC == ISD::SETUGE) {
13463    std::swap(Op0, Op1);
13464    CC = ISD::SETULT;
13465  }
13466
13467  if (CC != ISD::SETULT || VT.getScalarSizeInBits() != 1 ||
13468      Op0.getOpcode() != ISD::BUILD_VECTOR)
13469    return SDValue();
13470
13471  // Check first operand is BuildVector of 0,1,2,...
13472  for (unsigned I = 0; I < VT.getVectorNumElements(); I++) {
13473    if (!Op0.getOperand(I).isUndef() &&
13474        !(isa<ConstantSDNode>(Op0.getOperand(I)) &&
13475          Op0.getConstantOperandVal(I) == I))
13476      return SDValue();
13477  }
13478
13479  // The second is a Splat of Op1S
13480  SDValue Op1S = DCI.DAG.getSplatValue(Op1);
13481  if (!Op1S)
13482    return SDValue();
13483
13484  unsigned Opc;
13485  switch (VT.getVectorNumElements()) {
13486  case 2:
13487    Opc = Intrinsic::arm_mve_vctp64;
13488    break;
13489  case 4:
13490    Opc = Intrinsic::arm_mve_vctp32;
13491    break;
13492  case 8:
13493    Opc = Intrinsic::arm_mve_vctp16;
13494    break;
13495  case 16:
13496    Opc = Intrinsic::arm_mve_vctp8;
13497    break;
13498  default:
13499    return SDValue();
13500  }
13501
13502  SDLoc DL(N);
13503  return DCI.DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13504                         DCI.DAG.getConstant(Opc, DL, MVT::i32),
13505                         DCI.DAG.getZExtOrTrunc(Op1S, DL, MVT::i32));
13506}
13507
13508static SDValue PerformABSCombine(SDNode *N,
13509                                 TargetLowering::DAGCombinerInfo &DCI,
13510                                 const ARMSubtarget *Subtarget) {
13511  SelectionDAG &DAG = DCI.DAG;
13512  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13513
13514  if (TLI.isOperationLegal(N->getOpcode(), N->getValueType(0)))
13515    return SDValue();
13516
13517  return TLI.expandABS(N, DAG);
13518}
13519
13520/// PerformADDECombine - Target-specific dag combine transform from
13521/// ARMISD::ADDC, ARMISD::ADDE, and ISD::MUL_LOHI to MLAL or
13522/// ARMISD::ADDC, ARMISD::ADDE and ARMISD::UMLAL to ARMISD::UMAAL
13523static SDValue PerformADDECombine(SDNode *N,
13524                                  TargetLowering::DAGCombinerInfo &DCI,
13525                                  const ARMSubtarget *Subtarget) {
13526  // Only ARM and Thumb2 support UMLAL/SMLAL.
13527  if (Subtarget->isThumb1Only())
13528    return PerformAddeSubeCombine(N, DCI, Subtarget);
13529
13530  // Only perform the checks after legalize when the pattern is available.
13531  if (DCI.isBeforeLegalize()) return SDValue();
13532
13533  return AddCombineTo64bitUMAAL(N, DCI, Subtarget);
13534}
13535
13536/// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
13537/// operands N0 and N1.  This is a helper for PerformADDCombine that is
13538/// called with the default operands, and if that fails, with commuted
13539/// operands.
13540static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
13541                                          TargetLowering::DAGCombinerInfo &DCI,
13542                                          const ARMSubtarget *Subtarget){
13543  // Attempt to create vpadd for this add.
13544  if (SDValue Result = AddCombineToVPADD(N, N0, N1, DCI, Subtarget))
13545    return Result;
13546
13547  // Attempt to create vpaddl for this add.
13548  if (SDValue Result = AddCombineVUZPToVPADDL(N, N0, N1, DCI, Subtarget))
13549    return Result;
13550  if (SDValue Result = AddCombineBUILD_VECTORToVPADDL(N, N0, N1, DCI,
13551                                                      Subtarget))
13552    return Result;
13553
13554  // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
13555  if (N0.getNode()->hasOneUse())
13556    if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI))
13557      return Result;
13558  return SDValue();
13559}
13560
13561static SDValue TryDistrubutionADDVecReduce(SDNode *N, SelectionDAG &DAG) {
13562  EVT VT = N->getValueType(0);
13563  SDValue N0 = N->getOperand(0);
13564  SDValue N1 = N->getOperand(1);
13565  SDLoc dl(N);
13566
13567  auto IsVecReduce = [](SDValue Op) {
13568    switch (Op.getOpcode()) {
13569    case ISD::VECREDUCE_ADD:
13570    case ARMISD::VADDVs:
13571    case ARMISD::VADDVu:
13572    case ARMISD::VMLAVs:
13573    case ARMISD::VMLAVu:
13574      return true;
13575    }
13576    return false;
13577  };
13578
13579  auto DistrubuteAddAddVecReduce = [&](SDValue N0, SDValue N1) {
13580    // Distribute add(X, add(vecreduce(Y), vecreduce(Z))) ->
13581    //   add(add(X, vecreduce(Y)), vecreduce(Z))
13582    // to make better use of vaddva style instructions.
13583    if (VT == MVT::i32 && N1.getOpcode() == ISD::ADD && !IsVecReduce(N0) &&
13584        IsVecReduce(N1.getOperand(0)) && IsVecReduce(N1.getOperand(1)) &&
13585        !isa<ConstantSDNode>(N0) && N1->hasOneUse()) {
13586      SDValue Add0 = DAG.getNode(ISD::ADD, dl, VT, N0, N1.getOperand(0));
13587      return DAG.getNode(ISD::ADD, dl, VT, Add0, N1.getOperand(1));
13588    }
13589    // And turn add(add(A, reduce(B)), add(C, reduce(D))) ->
13590    //   add(add(add(A, C), reduce(B)), reduce(D))
13591    if (VT == MVT::i32 && N0.getOpcode() == ISD::ADD &&
13592        N1.getOpcode() == ISD::ADD && N0->hasOneUse() && N1->hasOneUse()) {
13593      unsigned N0RedOp = 0;
13594      if (!IsVecReduce(N0.getOperand(N0RedOp))) {
13595        N0RedOp = 1;
13596        if (!IsVecReduce(N0.getOperand(N0RedOp)))
13597          return SDValue();
13598      }
13599
13600      unsigned N1RedOp = 0;
13601      if (!IsVecReduce(N1.getOperand(N1RedOp)))
13602        N1RedOp = 1;
13603      if (!IsVecReduce(N1.getOperand(N1RedOp)))
13604        return SDValue();
13605
13606      SDValue Add0 = DAG.getNode(ISD::ADD, dl, VT, N0.getOperand(1 - N0RedOp),
13607                                 N1.getOperand(1 - N1RedOp));
13608      SDValue Add1 =
13609          DAG.getNode(ISD::ADD, dl, VT, Add0, N0.getOperand(N0RedOp));
13610      return DAG.getNode(ISD::ADD, dl, VT, Add1, N1.getOperand(N1RedOp));
13611    }
13612    return SDValue();
13613  };
13614  if (SDValue R = DistrubuteAddAddVecReduce(N0, N1))
13615    return R;
13616  if (SDValue R = DistrubuteAddAddVecReduce(N1, N0))
13617    return R;
13618
13619  // Distribute add(vecreduce(load(Y)), vecreduce(load(Z)))
13620  // Or add(add(X, vecreduce(load(Y))), vecreduce(load(Z)))
13621  // by ascending load offsets. This can help cores prefetch if the order of
13622  // loads is more predictable.
13623  auto DistrubuteVecReduceLoad = [&](SDValue N0, SDValue N1, bool IsForward) {
13624    // Check if two reductions are known to load data where one is before/after
13625    // another. Return negative if N0 loads data before N1, positive if N1 is
13626    // before N0 and 0 otherwise if nothing is known.
13627    auto IsKnownOrderedLoad = [&](SDValue N0, SDValue N1) {
13628      // Look through to the first operand of a MUL, for the VMLA case.
13629      // Currently only looks at the first operand, in the hope they are equal.
13630      if (N0.getOpcode() == ISD::MUL)
13631        N0 = N0.getOperand(0);
13632      if (N1.getOpcode() == ISD::MUL)
13633        N1 = N1.getOperand(0);
13634
13635      // Return true if the two operands are loads to the same object and the
13636      // offset of the first is known to be less than the offset of the second.
13637      LoadSDNode *Load0 = dyn_cast<LoadSDNode>(N0);
13638      LoadSDNode *Load1 = dyn_cast<LoadSDNode>(N1);
13639      if (!Load0 || !Load1 || Load0->getChain() != Load1->getChain() ||
13640          !Load0->isSimple() || !Load1->isSimple() || Load0->isIndexed() ||
13641          Load1->isIndexed())
13642        return 0;
13643
13644      auto BaseLocDecomp0 = BaseIndexOffset::match(Load0, DAG);
13645      auto BaseLocDecomp1 = BaseIndexOffset::match(Load1, DAG);
13646
13647      if (!BaseLocDecomp0.getBase() ||
13648          BaseLocDecomp0.getBase() != BaseLocDecomp1.getBase() ||
13649          !BaseLocDecomp0.hasValidOffset() || !BaseLocDecomp1.hasValidOffset())
13650        return 0;
13651      if (BaseLocDecomp0.getOffset() < BaseLocDecomp1.getOffset())
13652        return -1;
13653      if (BaseLocDecomp0.getOffset() > BaseLocDecomp1.getOffset())
13654        return 1;
13655      return 0;
13656    };
13657
13658    SDValue X;
13659    if (N0.getOpcode() == ISD::ADD && N0->hasOneUse()) {
13660      if (IsVecReduce(N0.getOperand(0)) && IsVecReduce(N0.getOperand(1))) {
13661        int IsBefore = IsKnownOrderedLoad(N0.getOperand(0).getOperand(0),
13662                                         N0.getOperand(1).getOperand(0));
13663        if (IsBefore < 0) {
13664          X = N0.getOperand(0);
13665          N0 = N0.getOperand(1);
13666        } else if (IsBefore > 0) {
13667          X = N0.getOperand(1);
13668          N0 = N0.getOperand(0);
13669        } else
13670          return SDValue();
13671      } else if (IsVecReduce(N0.getOperand(0))) {
13672        X = N0.getOperand(1);
13673        N0 = N0.getOperand(0);
13674      } else if (IsVecReduce(N0.getOperand(1))) {
13675        X = N0.getOperand(0);
13676        N0 = N0.getOperand(1);
13677      } else
13678        return SDValue();
13679    } else if (IsForward && IsVecReduce(N0) && IsVecReduce(N1) &&
13680               IsKnownOrderedLoad(N0.getOperand(0), N1.getOperand(0)) < 0) {
13681      // Note this is backward to how you would expect. We create
13682      // add(reduce(load + 16), reduce(load + 0)) so that the
13683      // add(reduce(load+16), X) is combined into VADDVA(X, load+16)), leaving
13684      // the X as VADDV(load + 0)
13685      return DAG.getNode(ISD::ADD, dl, VT, N1, N0);
13686    } else
13687      return SDValue();
13688
13689    if (!IsVecReduce(N0) || !IsVecReduce(N1))
13690      return SDValue();
13691
13692    if (IsKnownOrderedLoad(N1.getOperand(0), N0.getOperand(0)) >= 0)
13693      return SDValue();
13694
13695    // Switch from add(add(X, N0), N1) to add(add(X, N1), N0)
13696    SDValue Add0 = DAG.getNode(ISD::ADD, dl, VT, X, N1);
13697    return DAG.getNode(ISD::ADD, dl, VT, Add0, N0);
13698  };
13699  if (SDValue R = DistrubuteVecReduceLoad(N0, N1, true))
13700    return R;
13701  if (SDValue R = DistrubuteVecReduceLoad(N1, N0, false))
13702    return R;
13703  return SDValue();
13704}
13705
13706static SDValue PerformADDVecReduce(SDNode *N, SelectionDAG &DAG,
13707                                   const ARMSubtarget *Subtarget) {
13708  if (!Subtarget->hasMVEIntegerOps())
13709    return SDValue();
13710
13711  if (SDValue R = TryDistrubutionADDVecReduce(N, DAG))
13712    return R;
13713
13714  EVT VT = N->getValueType(0);
13715  SDValue N0 = N->getOperand(0);
13716  SDValue N1 = N->getOperand(1);
13717  SDLoc dl(N);
13718
13719  if (VT != MVT::i64)
13720    return SDValue();
13721
13722  // We are looking for a i64 add of a VADDLVx. Due to these being i64's, this
13723  // will look like:
13724  //   t1: i32,i32 = ARMISD::VADDLVs x
13725  //   t2: i64 = build_pair t1, t1:1
13726  //   t3: i64 = add t2, y
13727  // Otherwise we try to push the add up above VADDLVAx, to potentially allow
13728  // the add to be simplified seperately.
13729  // We also need to check for sext / zext and commutitive adds.
13730  auto MakeVecReduce = [&](unsigned Opcode, unsigned OpcodeA, SDValue NA,
13731                           SDValue NB) {
13732    if (NB->getOpcode() != ISD::BUILD_PAIR)
13733      return SDValue();
13734    SDValue VecRed = NB->getOperand(0);
13735    if ((VecRed->getOpcode() != Opcode && VecRed->getOpcode() != OpcodeA) ||
13736        VecRed.getResNo() != 0 ||
13737        NB->getOperand(1) != SDValue(VecRed.getNode(), 1))
13738      return SDValue();
13739
13740    if (VecRed->getOpcode() == OpcodeA) {
13741      // add(NA, VADDLVA(Inp), Y) -> VADDLVA(add(NA, Inp), Y)
13742      SDValue Inp = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64,
13743                                VecRed.getOperand(0), VecRed.getOperand(1));
13744      NA = DAG.getNode(ISD::ADD, dl, MVT::i64, Inp, NA);
13745    }
13746
13747    SmallVector<SDValue, 4> Ops(2);
13748    std::tie(Ops[0], Ops[1]) = DAG.SplitScalar(NA, dl, MVT::i32, MVT::i32);
13749
13750    unsigned S = VecRed->getOpcode() == OpcodeA ? 2 : 0;
13751    for (unsigned I = S, E = VecRed.getNumOperands(); I < E; I++)
13752      Ops.push_back(VecRed->getOperand(I));
13753    SDValue Red =
13754        DAG.getNode(OpcodeA, dl, DAG.getVTList({MVT::i32, MVT::i32}), Ops);
13755    return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Red,
13756                       SDValue(Red.getNode(), 1));
13757  };
13758
13759  if (SDValue M = MakeVecReduce(ARMISD::VADDLVs, ARMISD::VADDLVAs, N0, N1))
13760    return M;
13761  if (SDValue M = MakeVecReduce(ARMISD::VADDLVu, ARMISD::VADDLVAu, N0, N1))
13762    return M;
13763  if (SDValue M = MakeVecReduce(ARMISD::VADDLVs, ARMISD::VADDLVAs, N1, N0))
13764    return M;
13765  if (SDValue M = MakeVecReduce(ARMISD::VADDLVu, ARMISD::VADDLVAu, N1, N0))
13766    return M;
13767  if (SDValue M = MakeVecReduce(ARMISD::VADDLVps, ARMISD::VADDLVAps, N0, N1))
13768    return M;
13769  if (SDValue M = MakeVecReduce(ARMISD::VADDLVpu, ARMISD::VADDLVApu, N0, N1))
13770    return M;
13771  if (SDValue M = MakeVecReduce(ARMISD::VADDLVps, ARMISD::VADDLVAps, N1, N0))
13772    return M;
13773  if (SDValue M = MakeVecReduce(ARMISD::VADDLVpu, ARMISD::VADDLVApu, N1, N0))
13774    return M;
13775  if (SDValue M = MakeVecReduce(ARMISD::VMLALVs, ARMISD::VMLALVAs, N0, N1))
13776    return M;
13777  if (SDValue M = MakeVecReduce(ARMISD::VMLALVu, ARMISD::VMLALVAu, N0, N1))
13778    return M;
13779  if (SDValue M = MakeVecReduce(ARMISD::VMLALVs, ARMISD::VMLALVAs, N1, N0))
13780    return M;
13781  if (SDValue M = MakeVecReduce(ARMISD::VMLALVu, ARMISD::VMLALVAu, N1, N0))
13782    return M;
13783  if (SDValue M = MakeVecReduce(ARMISD::VMLALVps, ARMISD::VMLALVAps, N0, N1))
13784    return M;
13785  if (SDValue M = MakeVecReduce(ARMISD::VMLALVpu, ARMISD::VMLALVApu, N0, N1))
13786    return M;
13787  if (SDValue M = MakeVecReduce(ARMISD::VMLALVps, ARMISD::VMLALVAps, N1, N0))
13788    return M;
13789  if (SDValue M = MakeVecReduce(ARMISD::VMLALVpu, ARMISD::VMLALVApu, N1, N0))
13790    return M;
13791  return SDValue();
13792}
13793
13794bool
13795ARMTargetLowering::isDesirableToCommuteWithShift(const SDNode *N,
13796                                                 CombineLevel Level) const {
13797  assert((N->getOpcode() == ISD::SHL || N->getOpcode() == ISD::SRA ||
13798          N->getOpcode() == ISD::SRL) &&
13799         "Expected shift op");
13800
13801  if (Level == BeforeLegalizeTypes)
13802    return true;
13803
13804  if (N->getOpcode() != ISD::SHL)
13805    return true;
13806
13807  if (Subtarget->isThumb1Only()) {
13808    // Avoid making expensive immediates by commuting shifts. (This logic
13809    // only applies to Thumb1 because ARM and Thumb2 immediates can be shifted
13810    // for free.)
13811    if (N->getOpcode() != ISD::SHL)
13812      return true;
13813    SDValue N1 = N->getOperand(0);
13814    if (N1->getOpcode() != ISD::ADD && N1->getOpcode() != ISD::AND &&
13815        N1->getOpcode() != ISD::OR && N1->getOpcode() != ISD::XOR)
13816      return true;
13817    if (auto *Const = dyn_cast<ConstantSDNode>(N1->getOperand(1))) {
13818      if (Const->getAPIntValue().ult(256))
13819        return false;
13820      if (N1->getOpcode() == ISD::ADD && Const->getAPIntValue().slt(0) &&
13821          Const->getAPIntValue().sgt(-256))
13822        return false;
13823    }
13824    return true;
13825  }
13826
13827  // Turn off commute-with-shift transform after legalization, so it doesn't
13828  // conflict with PerformSHLSimplify.  (We could try to detect when
13829  // PerformSHLSimplify would trigger more precisely, but it isn't
13830  // really necessary.)
13831  return false;
13832}
13833
13834bool ARMTargetLowering::isDesirableToCommuteXorWithShift(
13835    const SDNode *N) const {
13836  assert(N->getOpcode() == ISD::XOR &&
13837         (N->getOperand(0).getOpcode() == ISD::SHL ||
13838          N->getOperand(0).getOpcode() == ISD::SRL) &&
13839         "Expected XOR(SHIFT) pattern");
13840
13841  // Only commute if the entire NOT mask is a hidden shifted mask.
13842  auto *XorC = dyn_cast<ConstantSDNode>(N->getOperand(1));
13843  auto *ShiftC = dyn_cast<ConstantSDNode>(N->getOperand(0).getOperand(1));
13844  if (XorC && ShiftC) {
13845    unsigned MaskIdx, MaskLen;
13846    if (XorC->getAPIntValue().isShiftedMask(MaskIdx, MaskLen)) {
13847      unsigned ShiftAmt = ShiftC->getZExtValue();
13848      unsigned BitWidth = N->getValueType(0).getScalarSizeInBits();
13849      if (N->getOperand(0).getOpcode() == ISD::SHL)
13850        return MaskIdx == ShiftAmt && MaskLen == (BitWidth - ShiftAmt);
13851      return MaskIdx == 0 && MaskLen == (BitWidth - ShiftAmt);
13852    }
13853  }
13854
13855  return false;
13856}
13857
13858bool ARMTargetLowering::shouldFoldConstantShiftPairToMask(
13859    const SDNode *N, CombineLevel Level) const {
13860  assert(((N->getOpcode() == ISD::SHL &&
13861           N->getOperand(0).getOpcode() == ISD::SRL) ||
13862          (N->getOpcode() == ISD::SRL &&
13863           N->getOperand(0).getOpcode() == ISD::SHL)) &&
13864         "Expected shift-shift mask");
13865
13866  if (!Subtarget->isThumb1Only())
13867    return true;
13868
13869  if (Level == BeforeLegalizeTypes)
13870    return true;
13871
13872  return false;
13873}
13874
13875bool ARMTargetLowering::shouldFoldSelectWithIdentityConstant(unsigned BinOpcode,
13876                                                             EVT VT) const {
13877  return Subtarget->hasMVEIntegerOps() && isTypeLegal(VT);
13878}
13879
13880bool ARMTargetLowering::preferIncOfAddToSubOfNot(EVT VT) const {
13881  if (!Subtarget->hasNEON()) {
13882    if (Subtarget->isThumb1Only())
13883      return VT.getScalarSizeInBits() <= 32;
13884    return true;
13885  }
13886  return VT.isScalarInteger();
13887}
13888
13889bool ARMTargetLowering::shouldConvertFpToSat(unsigned Op, EVT FPVT,
13890                                             EVT VT) const {
13891  if (!isOperationLegalOrCustom(Op, VT) || !FPVT.isSimple())
13892    return false;
13893
13894  switch (FPVT.getSimpleVT().SimpleTy) {
13895  case MVT::f16:
13896    return Subtarget->hasVFP2Base();
13897  case MVT::f32:
13898    return Subtarget->hasVFP2Base();
13899  case MVT::f64:
13900    return Subtarget->hasFP64();
13901  case MVT::v4f32:
13902  case MVT::v8f16:
13903    return Subtarget->hasMVEFloatOps();
13904  default:
13905    return false;
13906  }
13907}
13908
13909static SDValue PerformSHLSimplify(SDNode *N,
13910                                TargetLowering::DAGCombinerInfo &DCI,
13911                                const ARMSubtarget *ST) {
13912  // Allow the generic combiner to identify potential bswaps.
13913  if (DCI.isBeforeLegalize())
13914    return SDValue();
13915
13916  // DAG combiner will fold:
13917  // (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
13918  // (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2
13919  // Other code patterns that can be also be modified have the following form:
13920  // b + ((a << 1) | 510)
13921  // b + ((a << 1) & 510)
13922  // b + ((a << 1) ^ 510)
13923  // b + ((a << 1) + 510)
13924
13925  // Many instructions can  perform the shift for free, but it requires both
13926  // the operands to be registers. If c1 << c2 is too large, a mov immediate
13927  // instruction will needed. So, unfold back to the original pattern if:
13928  // - if c1 and c2 are small enough that they don't require mov imms.
13929  // - the user(s) of the node can perform an shl
13930
13931  // No shifted operands for 16-bit instructions.
13932  if (ST->isThumb() && ST->isThumb1Only())
13933    return SDValue();
13934
13935  // Check that all the users could perform the shl themselves.
13936  for (auto *U : N->uses()) {
13937    switch(U->getOpcode()) {
13938    default:
13939      return SDValue();
13940    case ISD::SUB:
13941    case ISD::ADD:
13942    case ISD::AND:
13943    case ISD::OR:
13944    case ISD::XOR:
13945    case ISD::SETCC:
13946    case ARMISD::CMP:
13947      // Check that the user isn't already using a constant because there
13948      // aren't any instructions that support an immediate operand and a
13949      // shifted operand.
13950      if (isa<ConstantSDNode>(U->getOperand(0)) ||
13951          isa<ConstantSDNode>(U->getOperand(1)))
13952        return SDValue();
13953
13954      // Check that it's not already using a shift.
13955      if (U->getOperand(0).getOpcode() == ISD::SHL ||
13956          U->getOperand(1).getOpcode() == ISD::SHL)
13957        return SDValue();
13958      break;
13959    }
13960  }
13961
13962  if (N->getOpcode() != ISD::ADD && N->getOpcode() != ISD::OR &&
13963      N->getOpcode() != ISD::XOR && N->getOpcode() != ISD::AND)
13964    return SDValue();
13965
13966  if (N->getOperand(0).getOpcode() != ISD::SHL)
13967    return SDValue();
13968
13969  SDValue SHL = N->getOperand(0);
13970
13971  auto *C1ShlC2 = dyn_cast<ConstantSDNode>(N->getOperand(1));
13972  auto *C2 = dyn_cast<ConstantSDNode>(SHL.getOperand(1));
13973  if (!C1ShlC2 || !C2)
13974    return SDValue();
13975
13976  APInt C2Int = C2->getAPIntValue();
13977  APInt C1Int = C1ShlC2->getAPIntValue();
13978  unsigned C2Width = C2Int.getBitWidth();
13979  if (C2Int.uge(C2Width))
13980    return SDValue();
13981  uint64_t C2Value = C2Int.getZExtValue();
13982
13983  // Check that performing a lshr will not lose any information.
13984  APInt Mask = APInt::getHighBitsSet(C2Width, C2Width - C2Value);
13985  if ((C1Int & Mask) != C1Int)
13986    return SDValue();
13987
13988  // Shift the first constant.
13989  C1Int.lshrInPlace(C2Int);
13990
13991  // The immediates are encoded as an 8-bit value that can be rotated.
13992  auto LargeImm = [](const APInt &Imm) {
13993    unsigned Zeros = Imm.countl_zero() + Imm.countr_zero();
13994    return Imm.getBitWidth() - Zeros > 8;
13995  };
13996
13997  if (LargeImm(C1Int) || LargeImm(C2Int))
13998    return SDValue();
13999
14000  SelectionDAG &DAG = DCI.DAG;
14001  SDLoc dl(N);
14002  SDValue X = SHL.getOperand(0);
14003  SDValue BinOp = DAG.getNode(N->getOpcode(), dl, MVT::i32, X,
14004                              DAG.getConstant(C1Int, dl, MVT::i32));
14005  // Shift left to compensate for the lshr of C1Int.
14006  SDValue Res = DAG.getNode(ISD::SHL, dl, MVT::i32, BinOp, SHL.getOperand(1));
14007
14008  LLVM_DEBUG(dbgs() << "Simplify shl use:\n"; SHL.getOperand(0).dump();
14009             SHL.dump(); N->dump());
14010  LLVM_DEBUG(dbgs() << "Into:\n"; X.dump(); BinOp.dump(); Res.dump());
14011  return Res;
14012}
14013
14014
14015/// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
14016///
14017static SDValue PerformADDCombine(SDNode *N,
14018                                 TargetLowering::DAGCombinerInfo &DCI,
14019                                 const ARMSubtarget *Subtarget) {
14020  SDValue N0 = N->getOperand(0);
14021  SDValue N1 = N->getOperand(1);
14022
14023  // Only works one way, because it needs an immediate operand.
14024  if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
14025    return Result;
14026
14027  if (SDValue Result = PerformADDVecReduce(N, DCI.DAG, Subtarget))
14028    return Result;
14029
14030  // First try with the default operand order.
14031  if (SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget))
14032    return Result;
14033
14034  // If that didn't work, try again with the operands commuted.
14035  return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
14036}
14037
14038// Combine (sub 0, (csinc X, Y, CC)) -> (csinv -X, Y, CC)
14039//   providing -X is as cheap as X (currently, just a constant).
14040static SDValue PerformSubCSINCCombine(SDNode *N, SelectionDAG &DAG) {
14041  if (N->getValueType(0) != MVT::i32 || !isNullConstant(N->getOperand(0)))
14042    return SDValue();
14043  SDValue CSINC = N->getOperand(1);
14044  if (CSINC.getOpcode() != ARMISD::CSINC || !CSINC.hasOneUse())
14045    return SDValue();
14046
14047  ConstantSDNode *X = dyn_cast<ConstantSDNode>(CSINC.getOperand(0));
14048  if (!X)
14049    return SDValue();
14050
14051  return DAG.getNode(ARMISD::CSINV, SDLoc(N), MVT::i32,
14052                     DAG.getNode(ISD::SUB, SDLoc(N), MVT::i32, N->getOperand(0),
14053                                 CSINC.getOperand(0)),
14054                     CSINC.getOperand(1), CSINC.getOperand(2),
14055                     CSINC.getOperand(3));
14056}
14057
14058/// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
14059///
14060static SDValue PerformSUBCombine(SDNode *N,
14061                                 TargetLowering::DAGCombinerInfo &DCI,
14062                                 const ARMSubtarget *Subtarget) {
14063  SDValue N0 = N->getOperand(0);
14064  SDValue N1 = N->getOperand(1);
14065
14066  // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
14067  if (N1.getNode()->hasOneUse())
14068    if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI))
14069      return Result;
14070
14071  if (SDValue R = PerformSubCSINCCombine(N, DCI.DAG))
14072    return R;
14073
14074  if (!Subtarget->hasMVEIntegerOps() || !N->getValueType(0).isVector())
14075    return SDValue();
14076
14077  // Fold (sub (ARMvmovImm 0), (ARMvdup x)) -> (ARMvdup (sub 0, x))
14078  // so that we can readily pattern match more mve instructions which can use
14079  // a scalar operand.
14080  SDValue VDup = N->getOperand(1);
14081  if (VDup->getOpcode() != ARMISD::VDUP)
14082    return SDValue();
14083
14084  SDValue VMov = N->getOperand(0);
14085  if (VMov->getOpcode() == ISD::BITCAST)
14086    VMov = VMov->getOperand(0);
14087
14088  if (VMov->getOpcode() != ARMISD::VMOVIMM || !isZeroVector(VMov))
14089    return SDValue();
14090
14091  SDLoc dl(N);
14092  SDValue Negate = DCI.DAG.getNode(ISD::SUB, dl, MVT::i32,
14093                                   DCI.DAG.getConstant(0, dl, MVT::i32),
14094                                   VDup->getOperand(0));
14095  return DCI.DAG.getNode(ARMISD::VDUP, dl, N->getValueType(0), Negate);
14096}
14097
14098/// PerformVMULCombine
14099/// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
14100/// special multiplier accumulator forwarding.
14101///   vmul d3, d0, d2
14102///   vmla d3, d1, d2
14103/// is faster than
14104///   vadd d3, d0, d1
14105///   vmul d3, d3, d2
14106//  However, for (A + B) * (A + B),
14107//    vadd d2, d0, d1
14108//    vmul d3, d0, d2
14109//    vmla d3, d1, d2
14110//  is slower than
14111//    vadd d2, d0, d1
14112//    vmul d3, d2, d2
14113static SDValue PerformVMULCombine(SDNode *N,
14114                                  TargetLowering::DAGCombinerInfo &DCI,
14115                                  const ARMSubtarget *Subtarget) {
14116  if (!Subtarget->hasVMLxForwarding())
14117    return SDValue();
14118
14119  SelectionDAG &DAG = DCI.DAG;
14120  SDValue N0 = N->getOperand(0);
14121  SDValue N1 = N->getOperand(1);
14122  unsigned Opcode = N0.getOpcode();
14123  if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
14124      Opcode != ISD::FADD && Opcode != ISD::FSUB) {
14125    Opcode = N1.getOpcode();
14126    if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
14127        Opcode != ISD::FADD && Opcode != ISD::FSUB)
14128      return SDValue();
14129    std::swap(N0, N1);
14130  }
14131
14132  if (N0 == N1)
14133    return SDValue();
14134
14135  EVT VT = N->getValueType(0);
14136  SDLoc DL(N);
14137  SDValue N00 = N0->getOperand(0);
14138  SDValue N01 = N0->getOperand(1);
14139  return DAG.getNode(Opcode, DL, VT,
14140                     DAG.getNode(ISD::MUL, DL, VT, N00, N1),
14141                     DAG.getNode(ISD::MUL, DL, VT, N01, N1));
14142}
14143
14144static SDValue PerformMVEVMULLCombine(SDNode *N, SelectionDAG &DAG,
14145                                      const ARMSubtarget *Subtarget) {
14146  EVT VT = N->getValueType(0);
14147  if (VT != MVT::v2i64)
14148    return SDValue();
14149
14150  SDValue N0 = N->getOperand(0);
14151  SDValue N1 = N->getOperand(1);
14152
14153  auto IsSignExt = [&](SDValue Op) {
14154    if (Op->getOpcode() != ISD::SIGN_EXTEND_INREG)
14155      return SDValue();
14156    EVT VT = cast<VTSDNode>(Op->getOperand(1))->getVT();
14157    if (VT.getScalarSizeInBits() == 32)
14158      return Op->getOperand(0);
14159    return SDValue();
14160  };
14161  auto IsZeroExt = [&](SDValue Op) {
14162    // Zero extends are a little more awkward. At the point we are matching
14163    // this, we are looking for an AND with a (-1, 0, -1, 0) buildvector mask.
14164    // That might be before of after a bitcast depending on how the and is
14165    // placed. Because this has to look through bitcasts, it is currently only
14166    // supported on LE.
14167    if (!Subtarget->isLittle())
14168      return SDValue();
14169
14170    SDValue And = Op;
14171    if (And->getOpcode() == ISD::BITCAST)
14172      And = And->getOperand(0);
14173    if (And->getOpcode() != ISD::AND)
14174      return SDValue();
14175    SDValue Mask = And->getOperand(1);
14176    if (Mask->getOpcode() == ISD::BITCAST)
14177      Mask = Mask->getOperand(0);
14178
14179    if (Mask->getOpcode() != ISD::BUILD_VECTOR ||
14180        Mask.getValueType() != MVT::v4i32)
14181      return SDValue();
14182    if (isAllOnesConstant(Mask->getOperand(0)) &&
14183        isNullConstant(Mask->getOperand(1)) &&
14184        isAllOnesConstant(Mask->getOperand(2)) &&
14185        isNullConstant(Mask->getOperand(3)))
14186      return And->getOperand(0);
14187    return SDValue();
14188  };
14189
14190  SDLoc dl(N);
14191  if (SDValue Op0 = IsSignExt(N0)) {
14192    if (SDValue Op1 = IsSignExt(N1)) {
14193      SDValue New0a = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, MVT::v4i32, Op0);
14194      SDValue New1a = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, MVT::v4i32, Op1);
14195      return DAG.getNode(ARMISD::VMULLs, dl, VT, New0a, New1a);
14196    }
14197  }
14198  if (SDValue Op0 = IsZeroExt(N0)) {
14199    if (SDValue Op1 = IsZeroExt(N1)) {
14200      SDValue New0a = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, MVT::v4i32, Op0);
14201      SDValue New1a = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, MVT::v4i32, Op1);
14202      return DAG.getNode(ARMISD::VMULLu, dl, VT, New0a, New1a);
14203    }
14204  }
14205
14206  return SDValue();
14207}
14208
14209static SDValue PerformMULCombine(SDNode *N,
14210                                 TargetLowering::DAGCombinerInfo &DCI,
14211                                 const ARMSubtarget *Subtarget) {
14212  SelectionDAG &DAG = DCI.DAG;
14213
14214  EVT VT = N->getValueType(0);
14215  if (Subtarget->hasMVEIntegerOps() && VT == MVT::v2i64)
14216    return PerformMVEVMULLCombine(N, DAG, Subtarget);
14217
14218  if (Subtarget->isThumb1Only())
14219    return SDValue();
14220
14221  if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
14222    return SDValue();
14223
14224  if (VT.is64BitVector() || VT.is128BitVector())
14225    return PerformVMULCombine(N, DCI, Subtarget);
14226  if (VT != MVT::i32)
14227    return SDValue();
14228
14229  ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
14230  if (!C)
14231    return SDValue();
14232
14233  int64_t MulAmt = C->getSExtValue();
14234  unsigned ShiftAmt = llvm::countr_zero<uint64_t>(MulAmt);
14235
14236  ShiftAmt = ShiftAmt & (32 - 1);
14237  SDValue V = N->getOperand(0);
14238  SDLoc DL(N);
14239
14240  SDValue Res;
14241  MulAmt >>= ShiftAmt;
14242
14243  if (MulAmt >= 0) {
14244    if (llvm::has_single_bit<uint32_t>(MulAmt - 1)) {
14245      // (mul x, 2^N + 1) => (add (shl x, N), x)
14246      Res = DAG.getNode(ISD::ADD, DL, VT,
14247                        V,
14248                        DAG.getNode(ISD::SHL, DL, VT,
14249                                    V,
14250                                    DAG.getConstant(Log2_32(MulAmt - 1), DL,
14251                                                    MVT::i32)));
14252    } else if (llvm::has_single_bit<uint32_t>(MulAmt + 1)) {
14253      // (mul x, 2^N - 1) => (sub (shl x, N), x)
14254      Res = DAG.getNode(ISD::SUB, DL, VT,
14255                        DAG.getNode(ISD::SHL, DL, VT,
14256                                    V,
14257                                    DAG.getConstant(Log2_32(MulAmt + 1), DL,
14258                                                    MVT::i32)),
14259                        V);
14260    } else
14261      return SDValue();
14262  } else {
14263    uint64_t MulAmtAbs = -MulAmt;
14264    if (llvm::has_single_bit<uint32_t>(MulAmtAbs + 1)) {
14265      // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
14266      Res = DAG.getNode(ISD::SUB, DL, VT,
14267                        V,
14268                        DAG.getNode(ISD::SHL, DL, VT,
14269                                    V,
14270                                    DAG.getConstant(Log2_32(MulAmtAbs + 1), DL,
14271                                                    MVT::i32)));
14272    } else if (llvm::has_single_bit<uint32_t>(MulAmtAbs - 1)) {
14273      // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
14274      Res = DAG.getNode(ISD::ADD, DL, VT,
14275                        V,
14276                        DAG.getNode(ISD::SHL, DL, VT,
14277                                    V,
14278                                    DAG.getConstant(Log2_32(MulAmtAbs - 1), DL,
14279                                                    MVT::i32)));
14280      Res = DAG.getNode(ISD::SUB, DL, VT,
14281                        DAG.getConstant(0, DL, MVT::i32), Res);
14282    } else
14283      return SDValue();
14284  }
14285
14286  if (ShiftAmt != 0)
14287    Res = DAG.getNode(ISD::SHL, DL, VT,
14288                      Res, DAG.getConstant(ShiftAmt, DL, MVT::i32));
14289
14290  // Do not add new nodes to DAG combiner worklist.
14291  DCI.CombineTo(N, Res, false);
14292  return SDValue();
14293}
14294
14295static SDValue CombineANDShift(SDNode *N,
14296                               TargetLowering::DAGCombinerInfo &DCI,
14297                               const ARMSubtarget *Subtarget) {
14298  // Allow DAGCombine to pattern-match before we touch the canonical form.
14299  if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
14300    return SDValue();
14301
14302  if (N->getValueType(0) != MVT::i32)
14303    return SDValue();
14304
14305  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1));
14306  if (!N1C)
14307    return SDValue();
14308
14309  uint32_t C1 = (uint32_t)N1C->getZExtValue();
14310  // Don't transform uxtb/uxth.
14311  if (C1 == 255 || C1 == 65535)
14312    return SDValue();
14313
14314  SDNode *N0 = N->getOperand(0).getNode();
14315  if (!N0->hasOneUse())
14316    return SDValue();
14317
14318  if (N0->getOpcode() != ISD::SHL && N0->getOpcode() != ISD::SRL)
14319    return SDValue();
14320
14321  bool LeftShift = N0->getOpcode() == ISD::SHL;
14322
14323  ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0->getOperand(1));
14324  if (!N01C)
14325    return SDValue();
14326
14327  uint32_t C2 = (uint32_t)N01C->getZExtValue();
14328  if (!C2 || C2 >= 32)
14329    return SDValue();
14330
14331  // Clear irrelevant bits in the mask.
14332  if (LeftShift)
14333    C1 &= (-1U << C2);
14334  else
14335    C1 &= (-1U >> C2);
14336
14337  SelectionDAG &DAG = DCI.DAG;
14338  SDLoc DL(N);
14339
14340  // We have a pattern of the form "(and (shl x, c2) c1)" or
14341  // "(and (srl x, c2) c1)", where c1 is a shifted mask. Try to
14342  // transform to a pair of shifts, to save materializing c1.
14343
14344  // First pattern: right shift, then mask off leading bits.
14345  // FIXME: Use demanded bits?
14346  if (!LeftShift && isMask_32(C1)) {
14347    uint32_t C3 = llvm::countl_zero(C1);
14348    if (C2 < C3) {
14349      SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0),
14350                                DAG.getConstant(C3 - C2, DL, MVT::i32));
14351      return DAG.getNode(ISD::SRL, DL, MVT::i32, SHL,
14352                         DAG.getConstant(C3, DL, MVT::i32));
14353    }
14354  }
14355
14356  // First pattern, reversed: left shift, then mask off trailing bits.
14357  if (LeftShift && isMask_32(~C1)) {
14358    uint32_t C3 = llvm::countr_zero(C1);
14359    if (C2 < C3) {
14360      SDValue SHL = DAG.getNode(ISD::SRL, DL, MVT::i32, N0->getOperand(0),
14361                                DAG.getConstant(C3 - C2, DL, MVT::i32));
14362      return DAG.getNode(ISD::SHL, DL, MVT::i32, SHL,
14363                         DAG.getConstant(C3, DL, MVT::i32));
14364    }
14365  }
14366
14367  // Second pattern: left shift, then mask off leading bits.
14368  // FIXME: Use demanded bits?
14369  if (LeftShift && isShiftedMask_32(C1)) {
14370    uint32_t Trailing = llvm::countr_zero(C1);
14371    uint32_t C3 = llvm::countl_zero(C1);
14372    if (Trailing == C2 && C2 + C3 < 32) {
14373      SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0),
14374                                DAG.getConstant(C2 + C3, DL, MVT::i32));
14375      return DAG.getNode(ISD::SRL, DL, MVT::i32, SHL,
14376                        DAG.getConstant(C3, DL, MVT::i32));
14377    }
14378  }
14379
14380  // Second pattern, reversed: right shift, then mask off trailing bits.
14381  // FIXME: Handle other patterns of known/demanded bits.
14382  if (!LeftShift && isShiftedMask_32(C1)) {
14383    uint32_t Leading = llvm::countl_zero(C1);
14384    uint32_t C3 = llvm::countr_zero(C1);
14385    if (Leading == C2 && C2 + C3 < 32) {
14386      SDValue SHL = DAG.getNode(ISD::SRL, DL, MVT::i32, N0->getOperand(0),
14387                                DAG.getConstant(C2 + C3, DL, MVT::i32));
14388      return DAG.getNode(ISD::SHL, DL, MVT::i32, SHL,
14389                         DAG.getConstant(C3, DL, MVT::i32));
14390    }
14391  }
14392
14393  // FIXME: Transform "(and (shl x, c2) c1)" ->
14394  // "(shl (and x, c1>>c2), c2)" if "c1 >> c2" is a cheaper immediate than
14395  // c1.
14396  return SDValue();
14397}
14398
14399static SDValue PerformANDCombine(SDNode *N,
14400                                 TargetLowering::DAGCombinerInfo &DCI,
14401                                 const ARMSubtarget *Subtarget) {
14402  // Attempt to use immediate-form VBIC
14403  BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
14404  SDLoc dl(N);
14405  EVT VT = N->getValueType(0);
14406  SelectionDAG &DAG = DCI.DAG;
14407
14408  if (!DAG.getTargetLoweringInfo().isTypeLegal(VT) || VT == MVT::v2i1 ||
14409      VT == MVT::v4i1 || VT == MVT::v8i1 || VT == MVT::v16i1)
14410    return SDValue();
14411
14412  APInt SplatBits, SplatUndef;
14413  unsigned SplatBitSize;
14414  bool HasAnyUndefs;
14415  if (BVN && (Subtarget->hasNEON() || Subtarget->hasMVEIntegerOps()) &&
14416      BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
14417    if (SplatBitSize == 8 || SplatBitSize == 16 || SplatBitSize == 32 ||
14418        SplatBitSize == 64) {
14419      EVT VbicVT;
14420      SDValue Val = isVMOVModifiedImm((~SplatBits).getZExtValue(),
14421                                      SplatUndef.getZExtValue(), SplatBitSize,
14422                                      DAG, dl, VbicVT, VT, OtherModImm);
14423      if (Val.getNode()) {
14424        SDValue Input =
14425          DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
14426        SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
14427        return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
14428      }
14429    }
14430  }
14431
14432  if (!Subtarget->isThumb1Only()) {
14433    // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
14434    if (SDValue Result = combineSelectAndUseCommutative(N, true, DCI))
14435      return Result;
14436
14437    if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
14438      return Result;
14439  }
14440
14441  if (Subtarget->isThumb1Only())
14442    if (SDValue Result = CombineANDShift(N, DCI, Subtarget))
14443      return Result;
14444
14445  return SDValue();
14446}
14447
14448// Try combining OR nodes to SMULWB, SMULWT.
14449static SDValue PerformORCombineToSMULWBT(SDNode *OR,
14450                                         TargetLowering::DAGCombinerInfo &DCI,
14451                                         const ARMSubtarget *Subtarget) {
14452  if (!Subtarget->hasV6Ops() ||
14453      (Subtarget->isThumb() &&
14454       (!Subtarget->hasThumb2() || !Subtarget->hasDSP())))
14455    return SDValue();
14456
14457  SDValue SRL = OR->getOperand(0);
14458  SDValue SHL = OR->getOperand(1);
14459
14460  if (SRL.getOpcode() != ISD::SRL || SHL.getOpcode() != ISD::SHL) {
14461    SRL = OR->getOperand(1);
14462    SHL = OR->getOperand(0);
14463  }
14464  if (!isSRL16(SRL) || !isSHL16(SHL))
14465    return SDValue();
14466
14467  // The first operands to the shifts need to be the two results from the
14468  // same smul_lohi node.
14469  if ((SRL.getOperand(0).getNode() != SHL.getOperand(0).getNode()) ||
14470       SRL.getOperand(0).getOpcode() != ISD::SMUL_LOHI)
14471    return SDValue();
14472
14473  SDNode *SMULLOHI = SRL.getOperand(0).getNode();
14474  if (SRL.getOperand(0) != SDValue(SMULLOHI, 0) ||
14475      SHL.getOperand(0) != SDValue(SMULLOHI, 1))
14476    return SDValue();
14477
14478  // Now we have:
14479  // (or (srl (smul_lohi ?, ?), 16), (shl (smul_lohi ?, ?), 16)))
14480  // For SMUL[B|T] smul_lohi will take a 32-bit and a 16-bit arguments.
14481  // For SMUWB the 16-bit value will signed extended somehow.
14482  // For SMULWT only the SRA is required.
14483  // Check both sides of SMUL_LOHI
14484  SDValue OpS16 = SMULLOHI->getOperand(0);
14485  SDValue OpS32 = SMULLOHI->getOperand(1);
14486
14487  SelectionDAG &DAG = DCI.DAG;
14488  if (!isS16(OpS16, DAG) && !isSRA16(OpS16)) {
14489    OpS16 = OpS32;
14490    OpS32 = SMULLOHI->getOperand(0);
14491  }
14492
14493  SDLoc dl(OR);
14494  unsigned Opcode = 0;
14495  if (isS16(OpS16, DAG))
14496    Opcode = ARMISD::SMULWB;
14497  else if (isSRA16(OpS16)) {
14498    Opcode = ARMISD::SMULWT;
14499    OpS16 = OpS16->getOperand(0);
14500  }
14501  else
14502    return SDValue();
14503
14504  SDValue Res = DAG.getNode(Opcode, dl, MVT::i32, OpS32, OpS16);
14505  DAG.ReplaceAllUsesOfValueWith(SDValue(OR, 0), Res);
14506  return SDValue(OR, 0);
14507}
14508
14509static SDValue PerformORCombineToBFI(SDNode *N,
14510                                     TargetLowering::DAGCombinerInfo &DCI,
14511                                     const ARMSubtarget *Subtarget) {
14512  // BFI is only available on V6T2+
14513  if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
14514    return SDValue();
14515
14516  EVT VT = N->getValueType(0);
14517  SDValue N0 = N->getOperand(0);
14518  SDValue N1 = N->getOperand(1);
14519  SelectionDAG &DAG = DCI.DAG;
14520  SDLoc DL(N);
14521  // 1) or (and A, mask), val => ARMbfi A, val, mask
14522  //      iff (val & mask) == val
14523  //
14524  // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
14525  //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
14526  //          && mask == ~mask2
14527  //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
14528  //          && ~mask == mask2
14529  //  (i.e., copy a bitfield value into another bitfield of the same width)
14530
14531  if (VT != MVT::i32)
14532    return SDValue();
14533
14534  SDValue N00 = N0.getOperand(0);
14535
14536  // The value and the mask need to be constants so we can verify this is
14537  // actually a bitfield set. If the mask is 0xffff, we can do better
14538  // via a movt instruction, so don't use BFI in that case.
14539  SDValue MaskOp = N0.getOperand(1);
14540  ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
14541  if (!MaskC)
14542    return SDValue();
14543  unsigned Mask = MaskC->getZExtValue();
14544  if (Mask == 0xffff)
14545    return SDValue();
14546  SDValue Res;
14547  // Case (1): or (and A, mask), val => ARMbfi A, val, mask
14548  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
14549  if (N1C) {
14550    unsigned Val = N1C->getZExtValue();
14551    if ((Val & ~Mask) != Val)
14552      return SDValue();
14553
14554    if (ARM::isBitFieldInvertedMask(Mask)) {
14555      Val >>= llvm::countr_zero(~Mask);
14556
14557      Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
14558                        DAG.getConstant(Val, DL, MVT::i32),
14559                        DAG.getConstant(Mask, DL, MVT::i32));
14560
14561      DCI.CombineTo(N, Res, false);
14562      // Return value from the original node to inform the combiner than N is
14563      // now dead.
14564      return SDValue(N, 0);
14565    }
14566  } else if (N1.getOpcode() == ISD::AND) {
14567    // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
14568    ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
14569    if (!N11C)
14570      return SDValue();
14571    unsigned Mask2 = N11C->getZExtValue();
14572
14573    // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
14574    // as is to match.
14575    if (ARM::isBitFieldInvertedMask(Mask) &&
14576        (Mask == ~Mask2)) {
14577      // The pack halfword instruction works better for masks that fit it,
14578      // so use that when it's available.
14579      if (Subtarget->hasDSP() &&
14580          (Mask == 0xffff || Mask == 0xffff0000))
14581        return SDValue();
14582      // 2a
14583      unsigned amt = llvm::countr_zero(Mask2);
14584      Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
14585                        DAG.getConstant(amt, DL, MVT::i32));
14586      Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
14587                        DAG.getConstant(Mask, DL, MVT::i32));
14588      DCI.CombineTo(N, Res, false);
14589      // Return value from the original node to inform the combiner than N is
14590      // now dead.
14591      return SDValue(N, 0);
14592    } else if (ARM::isBitFieldInvertedMask(~Mask) &&
14593               (~Mask == Mask2)) {
14594      // The pack halfword instruction works better for masks that fit it,
14595      // so use that when it's available.
14596      if (Subtarget->hasDSP() &&
14597          (Mask2 == 0xffff || Mask2 == 0xffff0000))
14598        return SDValue();
14599      // 2b
14600      unsigned lsb = llvm::countr_zero(Mask);
14601      Res = DAG.getNode(ISD::SRL, DL, VT, N00,
14602                        DAG.getConstant(lsb, DL, MVT::i32));
14603      Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
14604                        DAG.getConstant(Mask2, DL, MVT::i32));
14605      DCI.CombineTo(N, Res, false);
14606      // Return value from the original node to inform the combiner than N is
14607      // now dead.
14608      return SDValue(N, 0);
14609    }
14610  }
14611
14612  if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
14613      N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
14614      ARM::isBitFieldInvertedMask(~Mask)) {
14615    // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
14616    // where lsb(mask) == #shamt and masked bits of B are known zero.
14617    SDValue ShAmt = N00.getOperand(1);
14618    unsigned ShAmtC = ShAmt->getAsZExtVal();
14619    unsigned LSB = llvm::countr_zero(Mask);
14620    if (ShAmtC != LSB)
14621      return SDValue();
14622
14623    Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
14624                      DAG.getConstant(~Mask, DL, MVT::i32));
14625
14626    DCI.CombineTo(N, Res, false);
14627    // Return value from the original node to inform the combiner than N is
14628    // now dead.
14629    return SDValue(N, 0);
14630  }
14631
14632  return SDValue();
14633}
14634
14635static bool isValidMVECond(unsigned CC, bool IsFloat) {
14636  switch (CC) {
14637  case ARMCC::EQ:
14638  case ARMCC::NE:
14639  case ARMCC::LE:
14640  case ARMCC::GT:
14641  case ARMCC::GE:
14642  case ARMCC::LT:
14643    return true;
14644  case ARMCC::HS:
14645  case ARMCC::HI:
14646    return !IsFloat;
14647  default:
14648    return false;
14649  };
14650}
14651
14652static ARMCC::CondCodes getVCMPCondCode(SDValue N) {
14653  if (N->getOpcode() == ARMISD::VCMP)
14654    return (ARMCC::CondCodes)N->getConstantOperandVal(2);
14655  else if (N->getOpcode() == ARMISD::VCMPZ)
14656    return (ARMCC::CondCodes)N->getConstantOperandVal(1);
14657  else
14658    llvm_unreachable("Not a VCMP/VCMPZ!");
14659}
14660
14661static bool CanInvertMVEVCMP(SDValue N) {
14662  ARMCC::CondCodes CC = ARMCC::getOppositeCondition(getVCMPCondCode(N));
14663  return isValidMVECond(CC, N->getOperand(0).getValueType().isFloatingPoint());
14664}
14665
14666static SDValue PerformORCombine_i1(SDNode *N, SelectionDAG &DAG,
14667                                   const ARMSubtarget *Subtarget) {
14668  // Try to invert "or A, B" -> "and ~A, ~B", as the "and" is easier to chain
14669  // together with predicates
14670  EVT VT = N->getValueType(0);
14671  SDLoc DL(N);
14672  SDValue N0 = N->getOperand(0);
14673  SDValue N1 = N->getOperand(1);
14674
14675  auto IsFreelyInvertable = [&](SDValue V) {
14676    if (V->getOpcode() == ARMISD::VCMP || V->getOpcode() == ARMISD::VCMPZ)
14677      return CanInvertMVEVCMP(V);
14678    return false;
14679  };
14680
14681  // At least one operand must be freely invertable.
14682  if (!(IsFreelyInvertable(N0) || IsFreelyInvertable(N1)))
14683    return SDValue();
14684
14685  SDValue NewN0 = DAG.getLogicalNOT(DL, N0, VT);
14686  SDValue NewN1 = DAG.getLogicalNOT(DL, N1, VT);
14687  SDValue And = DAG.getNode(ISD::AND, DL, VT, NewN0, NewN1);
14688  return DAG.getLogicalNOT(DL, And, VT);
14689}
14690
14691/// PerformORCombine - Target-specific dag combine xforms for ISD::OR
14692static SDValue PerformORCombine(SDNode *N,
14693                                TargetLowering::DAGCombinerInfo &DCI,
14694                                const ARMSubtarget *Subtarget) {
14695  // Attempt to use immediate-form VORR
14696  BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
14697  SDLoc dl(N);
14698  EVT VT = N->getValueType(0);
14699  SelectionDAG &DAG = DCI.DAG;
14700
14701  if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
14702    return SDValue();
14703
14704  if (Subtarget->hasMVEIntegerOps() && (VT == MVT::v2i1 || VT == MVT::v4i1 ||
14705                                        VT == MVT::v8i1 || VT == MVT::v16i1))
14706    return PerformORCombine_i1(N, DAG, Subtarget);
14707
14708  APInt SplatBits, SplatUndef;
14709  unsigned SplatBitSize;
14710  bool HasAnyUndefs;
14711  if (BVN && (Subtarget->hasNEON() || Subtarget->hasMVEIntegerOps()) &&
14712      BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
14713    if (SplatBitSize == 8 || SplatBitSize == 16 || SplatBitSize == 32 ||
14714        SplatBitSize == 64) {
14715      EVT VorrVT;
14716      SDValue Val =
14717          isVMOVModifiedImm(SplatBits.getZExtValue(), SplatUndef.getZExtValue(),
14718                            SplatBitSize, DAG, dl, VorrVT, VT, OtherModImm);
14719      if (Val.getNode()) {
14720        SDValue Input =
14721          DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
14722        SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
14723        return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
14724      }
14725    }
14726  }
14727
14728  if (!Subtarget->isThumb1Only()) {
14729    // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
14730    if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI))
14731      return Result;
14732    if (SDValue Result = PerformORCombineToSMULWBT(N, DCI, Subtarget))
14733      return Result;
14734  }
14735
14736  SDValue N0 = N->getOperand(0);
14737  SDValue N1 = N->getOperand(1);
14738
14739  // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
14740  if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
14741      DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
14742
14743    // The code below optimizes (or (and X, Y), Z).
14744    // The AND operand needs to have a single user to make these optimizations
14745    // profitable.
14746    if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
14747      return SDValue();
14748
14749    APInt SplatUndef;
14750    unsigned SplatBitSize;
14751    bool HasAnyUndefs;
14752
14753    APInt SplatBits0, SplatBits1;
14754    BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
14755    BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
14756    // Ensure that the second operand of both ands are constants
14757    if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
14758                                      HasAnyUndefs) && !HasAnyUndefs) {
14759        if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
14760                                          HasAnyUndefs) && !HasAnyUndefs) {
14761            // Ensure that the bit width of the constants are the same and that
14762            // the splat arguments are logical inverses as per the pattern we
14763            // are trying to simplify.
14764            if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
14765                SplatBits0 == ~SplatBits1) {
14766                // Canonicalize the vector type to make instruction selection
14767                // simpler.
14768                EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
14769                SDValue Result = DAG.getNode(ARMISD::VBSP, dl, CanonicalVT,
14770                                             N0->getOperand(1),
14771                                             N0->getOperand(0),
14772                                             N1->getOperand(0));
14773                return DAG.getNode(ISD::BITCAST, dl, VT, Result);
14774            }
14775        }
14776    }
14777  }
14778
14779  // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
14780  // reasonable.
14781  if (N0.getOpcode() == ISD::AND && N0.hasOneUse()) {
14782    if (SDValue Res = PerformORCombineToBFI(N, DCI, Subtarget))
14783      return Res;
14784  }
14785
14786  if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
14787    return Result;
14788
14789  return SDValue();
14790}
14791
14792static SDValue PerformXORCombine(SDNode *N,
14793                                 TargetLowering::DAGCombinerInfo &DCI,
14794                                 const ARMSubtarget *Subtarget) {
14795  EVT VT = N->getValueType(0);
14796  SelectionDAG &DAG = DCI.DAG;
14797
14798  if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
14799    return SDValue();
14800
14801  if (!Subtarget->isThumb1Only()) {
14802    // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
14803    if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI))
14804      return Result;
14805
14806    if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
14807      return Result;
14808  }
14809
14810  if (Subtarget->hasMVEIntegerOps()) {
14811    // fold (xor(vcmp/z, 1)) into a vcmp with the opposite condition.
14812    SDValue N0 = N->getOperand(0);
14813    SDValue N1 = N->getOperand(1);
14814    const TargetLowering *TLI = Subtarget->getTargetLowering();
14815    if (TLI->isConstTrueVal(N1) &&
14816        (N0->getOpcode() == ARMISD::VCMP || N0->getOpcode() == ARMISD::VCMPZ)) {
14817      if (CanInvertMVEVCMP(N0)) {
14818        SDLoc DL(N0);
14819        ARMCC::CondCodes CC = ARMCC::getOppositeCondition(getVCMPCondCode(N0));
14820
14821        SmallVector<SDValue, 4> Ops;
14822        Ops.push_back(N0->getOperand(0));
14823        if (N0->getOpcode() == ARMISD::VCMP)
14824          Ops.push_back(N0->getOperand(1));
14825        Ops.push_back(DAG.getConstant(CC, DL, MVT::i32));
14826        return DAG.getNode(N0->getOpcode(), DL, N0->getValueType(0), Ops);
14827      }
14828    }
14829  }
14830
14831  return SDValue();
14832}
14833
14834// ParseBFI - given a BFI instruction in N, extract the "from" value (Rn) and return it,
14835// and fill in FromMask and ToMask with (consecutive) bits in "from" to be extracted and
14836// their position in "to" (Rd).
14837static SDValue ParseBFI(SDNode *N, APInt &ToMask, APInt &FromMask) {
14838  assert(N->getOpcode() == ARMISD::BFI);
14839
14840  SDValue From = N->getOperand(1);
14841  ToMask = ~N->getConstantOperandAPInt(2);
14842  FromMask = APInt::getLowBitsSet(ToMask.getBitWidth(), ToMask.popcount());
14843
14844  // If the Base came from a SHR #C, we can deduce that it is really testing bit
14845  // #C in the base of the SHR.
14846  if (From->getOpcode() == ISD::SRL &&
14847      isa<ConstantSDNode>(From->getOperand(1))) {
14848    APInt Shift = From->getConstantOperandAPInt(1);
14849    assert(Shift.getLimitedValue() < 32 && "Shift too large!");
14850    FromMask <<= Shift.getLimitedValue(31);
14851    From = From->getOperand(0);
14852  }
14853
14854  return From;
14855}
14856
14857// If A and B contain one contiguous set of bits, does A | B == A . B?
14858//
14859// Neither A nor B must be zero.
14860static bool BitsProperlyConcatenate(const APInt &A, const APInt &B) {
14861  unsigned LastActiveBitInA = A.countr_zero();
14862  unsigned FirstActiveBitInB = B.getBitWidth() - B.countl_zero() - 1;
14863  return LastActiveBitInA - 1 == FirstActiveBitInB;
14864}
14865
14866static SDValue FindBFIToCombineWith(SDNode *N) {
14867  // We have a BFI in N. Find a BFI it can combine with, if one exists.
14868  APInt ToMask, FromMask;
14869  SDValue From = ParseBFI(N, ToMask, FromMask);
14870  SDValue To = N->getOperand(0);
14871
14872  SDValue V = To;
14873  if (V.getOpcode() != ARMISD::BFI)
14874    return SDValue();
14875
14876  APInt NewToMask, NewFromMask;
14877  SDValue NewFrom = ParseBFI(V.getNode(), NewToMask, NewFromMask);
14878  if (NewFrom != From)
14879    return SDValue();
14880
14881  // Do the written bits conflict with any we've seen so far?
14882  if ((NewToMask & ToMask).getBoolValue())
14883    // Conflicting bits.
14884    return SDValue();
14885
14886  // Are the new bits contiguous when combined with the old bits?
14887  if (BitsProperlyConcatenate(ToMask, NewToMask) &&
14888      BitsProperlyConcatenate(FromMask, NewFromMask))
14889    return V;
14890  if (BitsProperlyConcatenate(NewToMask, ToMask) &&
14891      BitsProperlyConcatenate(NewFromMask, FromMask))
14892    return V;
14893
14894  return SDValue();
14895}
14896
14897static SDValue PerformBFICombine(SDNode *N, SelectionDAG &DAG) {
14898  SDValue N0 = N->getOperand(0);
14899  SDValue N1 = N->getOperand(1);
14900
14901  if (N1.getOpcode() == ISD::AND) {
14902    // (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
14903    // the bits being cleared by the AND are not demanded by the BFI.
14904    ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
14905    if (!N11C)
14906      return SDValue();
14907    unsigned InvMask = N->getConstantOperandVal(2);
14908    unsigned LSB = llvm::countr_zero(~InvMask);
14909    unsigned Width = llvm::bit_width<unsigned>(~InvMask) - LSB;
14910    assert(Width <
14911               static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
14912           "undefined behavior");
14913    unsigned Mask = (1u << Width) - 1;
14914    unsigned Mask2 = N11C->getZExtValue();
14915    if ((Mask & (~Mask2)) == 0)
14916      return DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
14917                         N->getOperand(0), N1.getOperand(0), N->getOperand(2));
14918    return SDValue();
14919  }
14920
14921  // Look for another BFI to combine with.
14922  if (SDValue CombineBFI = FindBFIToCombineWith(N)) {
14923    // We've found a BFI.
14924    APInt ToMask1, FromMask1;
14925    SDValue From1 = ParseBFI(N, ToMask1, FromMask1);
14926
14927    APInt ToMask2, FromMask2;
14928    SDValue From2 = ParseBFI(CombineBFI.getNode(), ToMask2, FromMask2);
14929    assert(From1 == From2);
14930    (void)From2;
14931
14932    // Create a new BFI, combining the two together.
14933    APInt NewFromMask = FromMask1 | FromMask2;
14934    APInt NewToMask = ToMask1 | ToMask2;
14935
14936    EVT VT = N->getValueType(0);
14937    SDLoc dl(N);
14938
14939    if (NewFromMask[0] == 0)
14940      From1 = DAG.getNode(ISD::SRL, dl, VT, From1,
14941                          DAG.getConstant(NewFromMask.countr_zero(), dl, VT));
14942    return DAG.getNode(ARMISD::BFI, dl, VT, CombineBFI.getOperand(0), From1,
14943                       DAG.getConstant(~NewToMask, dl, VT));
14944  }
14945
14946  // Reassociate BFI(BFI (A, B, M1), C, M2) to BFI(BFI (A, C, M2), B, M1) so
14947  // that lower bit insertions are performed first, providing that M1 and M2
14948  // do no overlap. This can allow multiple BFI instructions to be combined
14949  // together by the other folds above.
14950  if (N->getOperand(0).getOpcode() == ARMISD::BFI) {
14951    APInt ToMask1 = ~N->getConstantOperandAPInt(2);
14952    APInt ToMask2 = ~N0.getConstantOperandAPInt(2);
14953
14954    if (!N0.hasOneUse() || (ToMask1 & ToMask2) != 0 ||
14955        ToMask1.countl_zero() < ToMask2.countl_zero())
14956      return SDValue();
14957
14958    EVT VT = N->getValueType(0);
14959    SDLoc dl(N);
14960    SDValue BFI1 = DAG.getNode(ARMISD::BFI, dl, VT, N0.getOperand(0),
14961                               N->getOperand(1), N->getOperand(2));
14962    return DAG.getNode(ARMISD::BFI, dl, VT, BFI1, N0.getOperand(1),
14963                       N0.getOperand(2));
14964  }
14965
14966  return SDValue();
14967}
14968
14969// Check that N is CMPZ(CSINC(0, 0, CC, X)),
14970//              or CMPZ(CMOV(1, 0, CC, $cpsr, X))
14971// return X if valid.
14972static SDValue IsCMPZCSINC(SDNode *Cmp, ARMCC::CondCodes &CC) {
14973  if (Cmp->getOpcode() != ARMISD::CMPZ || !isNullConstant(Cmp->getOperand(1)))
14974    return SDValue();
14975  SDValue CSInc = Cmp->getOperand(0);
14976
14977  // Ignore any `And 1` nodes that may not yet have been removed. We are
14978  // looking for a value that produces 1/0, so these have no effect on the
14979  // code.
14980  while (CSInc.getOpcode() == ISD::AND &&
14981         isa<ConstantSDNode>(CSInc.getOperand(1)) &&
14982         CSInc.getConstantOperandVal(1) == 1 && CSInc->hasOneUse())
14983    CSInc = CSInc.getOperand(0);
14984
14985  if (CSInc.getOpcode() == ARMISD::CSINC &&
14986      isNullConstant(CSInc.getOperand(0)) &&
14987      isNullConstant(CSInc.getOperand(1)) && CSInc->hasOneUse()) {
14988    CC = (ARMCC::CondCodes)CSInc.getConstantOperandVal(2);
14989    return CSInc.getOperand(3);
14990  }
14991  if (CSInc.getOpcode() == ARMISD::CMOV && isOneConstant(CSInc.getOperand(0)) &&
14992      isNullConstant(CSInc.getOperand(1)) && CSInc->hasOneUse()) {
14993    CC = (ARMCC::CondCodes)CSInc.getConstantOperandVal(2);
14994    return CSInc.getOperand(4);
14995  }
14996  if (CSInc.getOpcode() == ARMISD::CMOV && isOneConstant(CSInc.getOperand(1)) &&
14997      isNullConstant(CSInc.getOperand(0)) && CSInc->hasOneUse()) {
14998    CC = ARMCC::getOppositeCondition(
14999        (ARMCC::CondCodes)CSInc.getConstantOperandVal(2));
15000    return CSInc.getOperand(4);
15001  }
15002  return SDValue();
15003}
15004
15005static SDValue PerformCMPZCombine(SDNode *N, SelectionDAG &DAG) {
15006  // Given CMPZ(CSINC(C, 0, 0, EQ), 0), we can just use C directly. As in
15007  //       t92: glue = ARMISD::CMPZ t74, 0
15008  //     t93: i32 = ARMISD::CSINC 0, 0, 1, t92
15009  //   t96: glue = ARMISD::CMPZ t93, 0
15010  // t114: i32 = ARMISD::CSINV 0, 0, 0, t96
15011  ARMCC::CondCodes Cond;
15012  if (SDValue C = IsCMPZCSINC(N, Cond))
15013    if (Cond == ARMCC::EQ)
15014      return C;
15015  return SDValue();
15016}
15017
15018static SDValue PerformCSETCombine(SDNode *N, SelectionDAG &DAG) {
15019  // Fold away an unneccessary CMPZ/CSINC
15020  // CSXYZ A, B, C1 (CMPZ (CSINC 0, 0, C2, D), 0) ->
15021  // if C1==EQ -> CSXYZ A, B, C2, D
15022  // if C1==NE -> CSXYZ A, B, NOT(C2), D
15023  ARMCC::CondCodes Cond;
15024  if (SDValue C = IsCMPZCSINC(N->getOperand(3).getNode(), Cond)) {
15025    if (N->getConstantOperandVal(2) == ARMCC::EQ)
15026      return DAG.getNode(N->getOpcode(), SDLoc(N), MVT::i32, N->getOperand(0),
15027                         N->getOperand(1),
15028                         DAG.getConstant(Cond, SDLoc(N), MVT::i32), C);
15029    if (N->getConstantOperandVal(2) == ARMCC::NE)
15030      return DAG.getNode(
15031          N->getOpcode(), SDLoc(N), MVT::i32, N->getOperand(0),
15032          N->getOperand(1),
15033          DAG.getConstant(ARMCC::getOppositeCondition(Cond), SDLoc(N), MVT::i32), C);
15034  }
15035  return SDValue();
15036}
15037
15038/// PerformVMOVRRDCombine - Target-specific dag combine xforms for
15039/// ARMISD::VMOVRRD.
15040static SDValue PerformVMOVRRDCombine(SDNode *N,
15041                                     TargetLowering::DAGCombinerInfo &DCI,
15042                                     const ARMSubtarget *Subtarget) {
15043  // vmovrrd(vmovdrr x, y) -> x,y
15044  SDValue InDouble = N->getOperand(0);
15045  if (InDouble.getOpcode() == ARMISD::VMOVDRR && Subtarget->hasFP64())
15046    return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
15047
15048  // vmovrrd(load f64) -> (load i32), (load i32)
15049  SDNode *InNode = InDouble.getNode();
15050  if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
15051      InNode->getValueType(0) == MVT::f64 &&
15052      InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
15053      !cast<LoadSDNode>(InNode)->isVolatile()) {
15054    // TODO: Should this be done for non-FrameIndex operands?
15055    LoadSDNode *LD = cast<LoadSDNode>(InNode);
15056
15057    SelectionDAG &DAG = DCI.DAG;
15058    SDLoc DL(LD);
15059    SDValue BasePtr = LD->getBasePtr();
15060    SDValue NewLD1 =
15061        DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr, LD->getPointerInfo(),
15062                    LD->getAlign(), LD->getMemOperand()->getFlags());
15063
15064    SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
15065                                    DAG.getConstant(4, DL, MVT::i32));
15066
15067    SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, LD->getChain(), OffsetPtr,
15068                                 LD->getPointerInfo().getWithOffset(4),
15069                                 commonAlignment(LD->getAlign(), 4),
15070                                 LD->getMemOperand()->getFlags());
15071
15072    DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
15073    if (DCI.DAG.getDataLayout().isBigEndian())
15074      std::swap (NewLD1, NewLD2);
15075    SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
15076    return Result;
15077  }
15078
15079  // VMOVRRD(extract(..(build_vector(a, b, c, d)))) -> a,b or c,d
15080  // VMOVRRD(extract(insert_vector(insert_vector(.., a, l1), b, l2))) -> a,b
15081  if (InDouble.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
15082      isa<ConstantSDNode>(InDouble.getOperand(1))) {
15083    SDValue BV = InDouble.getOperand(0);
15084    // Look up through any nop bitcasts and vector_reg_casts. bitcasts may
15085    // change lane order under big endian.
15086    bool BVSwap = BV.getOpcode() == ISD::BITCAST;
15087    while (
15088        (BV.getOpcode() == ISD::BITCAST ||
15089         BV.getOpcode() == ARMISD::VECTOR_REG_CAST) &&
15090        (BV.getValueType() == MVT::v2f64 || BV.getValueType() == MVT::v2i64)) {
15091      BVSwap = BV.getOpcode() == ISD::BITCAST;
15092      BV = BV.getOperand(0);
15093    }
15094    if (BV.getValueType() != MVT::v4i32)
15095      return SDValue();
15096
15097    // Handle buildvectors, pulling out the correct lane depending on
15098    // endianness.
15099    unsigned Offset = InDouble.getConstantOperandVal(1) == 1 ? 2 : 0;
15100    if (BV.getOpcode() == ISD::BUILD_VECTOR) {
15101      SDValue Op0 = BV.getOperand(Offset);
15102      SDValue Op1 = BV.getOperand(Offset + 1);
15103      if (!Subtarget->isLittle() && BVSwap)
15104        std::swap(Op0, Op1);
15105
15106      return DCI.DAG.getMergeValues({Op0, Op1}, SDLoc(N));
15107    }
15108
15109    // A chain of insert_vectors, grabbing the correct value of the chain of
15110    // inserts.
15111    SDValue Op0, Op1;
15112    while (BV.getOpcode() == ISD::INSERT_VECTOR_ELT) {
15113      if (isa<ConstantSDNode>(BV.getOperand(2))) {
15114        if (BV.getConstantOperandVal(2) == Offset)
15115          Op0 = BV.getOperand(1);
15116        if (BV.getConstantOperandVal(2) == Offset + 1)
15117          Op1 = BV.getOperand(1);
15118      }
15119      BV = BV.getOperand(0);
15120    }
15121    if (!Subtarget->isLittle() && BVSwap)
15122      std::swap(Op0, Op1);
15123    if (Op0 && Op1)
15124      return DCI.DAG.getMergeValues({Op0, Op1}, SDLoc(N));
15125  }
15126
15127  return SDValue();
15128}
15129
15130/// PerformVMOVDRRCombine - Target-specific dag combine xforms for
15131/// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
15132static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
15133  // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
15134  SDValue Op0 = N->getOperand(0);
15135  SDValue Op1 = N->getOperand(1);
15136  if (Op0.getOpcode() == ISD::BITCAST)
15137    Op0 = Op0.getOperand(0);
15138  if (Op1.getOpcode() == ISD::BITCAST)
15139    Op1 = Op1.getOperand(0);
15140  if (Op0.getOpcode() == ARMISD::VMOVRRD &&
15141      Op0.getNode() == Op1.getNode() &&
15142      Op0.getResNo() == 0 && Op1.getResNo() == 1)
15143    return DAG.getNode(ISD::BITCAST, SDLoc(N),
15144                       N->getValueType(0), Op0.getOperand(0));
15145  return SDValue();
15146}
15147
15148static SDValue PerformVMOVhrCombine(SDNode *N,
15149                                    TargetLowering::DAGCombinerInfo &DCI) {
15150  SDValue Op0 = N->getOperand(0);
15151
15152  // VMOVhr (VMOVrh (X)) -> X
15153  if (Op0->getOpcode() == ARMISD::VMOVrh)
15154    return Op0->getOperand(0);
15155
15156  // FullFP16: half values are passed in S-registers, and we don't
15157  // need any of the bitcast and moves:
15158  //
15159  //     t2: f32,ch1,gl1? = CopyFromReg ch, Register:f32 %0, gl?
15160  //   t5: i32 = bitcast t2
15161  // t18: f16 = ARMISD::VMOVhr t5
15162  // =>
15163  // tN: f16,ch2,gl2? = CopyFromReg ch, Register::f32 %0, gl?
15164  if (Op0->getOpcode() == ISD::BITCAST) {
15165    SDValue Copy = Op0->getOperand(0);
15166    if (Copy.getValueType() == MVT::f32 &&
15167        Copy->getOpcode() == ISD::CopyFromReg) {
15168      bool HasGlue = Copy->getNumOperands() == 3;
15169      SDValue Ops[] = {Copy->getOperand(0), Copy->getOperand(1),
15170                       HasGlue ? Copy->getOperand(2) : SDValue()};
15171      EVT OutTys[] = {N->getValueType(0), MVT::Other, MVT::Glue};
15172      SDValue NewCopy =
15173          DCI.DAG.getNode(ISD::CopyFromReg, SDLoc(N),
15174                          DCI.DAG.getVTList(ArrayRef(OutTys, HasGlue ? 3 : 2)),
15175                          ArrayRef(Ops, HasGlue ? 3 : 2));
15176
15177      // Update Users, Chains, and Potential Glue.
15178      DCI.DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), NewCopy.getValue(0));
15179      DCI.DAG.ReplaceAllUsesOfValueWith(Copy.getValue(1), NewCopy.getValue(1));
15180      if (HasGlue)
15181        DCI.DAG.ReplaceAllUsesOfValueWith(Copy.getValue(2),
15182                                          NewCopy.getValue(2));
15183
15184      return NewCopy;
15185    }
15186  }
15187
15188  // fold (VMOVhr (load x)) -> (load (f16*)x)
15189  if (LoadSDNode *LN0 = dyn_cast<LoadSDNode>(Op0)) {
15190    if (LN0->hasOneUse() && LN0->isUnindexed() &&
15191        LN0->getMemoryVT() == MVT::i16) {
15192      SDValue Load =
15193          DCI.DAG.getLoad(N->getValueType(0), SDLoc(N), LN0->getChain(),
15194                          LN0->getBasePtr(), LN0->getMemOperand());
15195      DCI.DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Load.getValue(0));
15196      DCI.DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), Load.getValue(1));
15197      return Load;
15198    }
15199  }
15200
15201  // Only the bottom 16 bits of the source register are used.
15202  APInt DemandedMask = APInt::getLowBitsSet(32, 16);
15203  const TargetLowering &TLI = DCI.DAG.getTargetLoweringInfo();
15204  if (TLI.SimplifyDemandedBits(Op0, DemandedMask, DCI))
15205    return SDValue(N, 0);
15206
15207  return SDValue();
15208}
15209
15210static SDValue PerformVMOVrhCombine(SDNode *N, SelectionDAG &DAG) {
15211  SDValue N0 = N->getOperand(0);
15212  EVT VT = N->getValueType(0);
15213
15214  // fold (VMOVrh (fpconst x)) -> const x
15215  if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N0)) {
15216    APFloat V = C->getValueAPF();
15217    return DAG.getConstant(V.bitcastToAPInt().getZExtValue(), SDLoc(N), VT);
15218  }
15219
15220  // fold (VMOVrh (load x)) -> (zextload (i16*)x)
15221  if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse()) {
15222    LoadSDNode *LN0 = cast<LoadSDNode>(N0);
15223
15224    SDValue Load =
15225        DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT, LN0->getChain(),
15226                       LN0->getBasePtr(), MVT::i16, LN0->getMemOperand());
15227    DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Load.getValue(0));
15228    DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
15229    return Load;
15230  }
15231
15232  // Fold VMOVrh(extract(x, n)) -> vgetlaneu(x, n)
15233  if (N0->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
15234      isa<ConstantSDNode>(N0->getOperand(1)))
15235    return DAG.getNode(ARMISD::VGETLANEu, SDLoc(N), VT, N0->getOperand(0),
15236                       N0->getOperand(1));
15237
15238  return SDValue();
15239}
15240
15241/// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
15242/// are normal, non-volatile loads.  If so, it is profitable to bitcast an
15243/// i64 vector to have f64 elements, since the value can then be loaded
15244/// directly into a VFP register.
15245static bool hasNormalLoadOperand(SDNode *N) {
15246  unsigned NumElts = N->getValueType(0).getVectorNumElements();
15247  for (unsigned i = 0; i < NumElts; ++i) {
15248    SDNode *Elt = N->getOperand(i).getNode();
15249    if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
15250      return true;
15251  }
15252  return false;
15253}
15254
15255/// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
15256/// ISD::BUILD_VECTOR.
15257static SDValue PerformBUILD_VECTORCombine(SDNode *N,
15258                                          TargetLowering::DAGCombinerInfo &DCI,
15259                                          const ARMSubtarget *Subtarget) {
15260  // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
15261  // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
15262  // into a pair of GPRs, which is fine when the value is used as a scalar,
15263  // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
15264  SelectionDAG &DAG = DCI.DAG;
15265  if (N->getNumOperands() == 2)
15266    if (SDValue RV = PerformVMOVDRRCombine(N, DAG))
15267      return RV;
15268
15269  // Load i64 elements as f64 values so that type legalization does not split
15270  // them up into i32 values.
15271  EVT VT = N->getValueType(0);
15272  if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
15273    return SDValue();
15274  SDLoc dl(N);
15275  SmallVector<SDValue, 8> Ops;
15276  unsigned NumElts = VT.getVectorNumElements();
15277  for (unsigned i = 0; i < NumElts; ++i) {
15278    SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
15279    Ops.push_back(V);
15280    // Make the DAGCombiner fold the bitcast.
15281    DCI.AddToWorklist(V.getNode());
15282  }
15283  EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
15284  SDValue BV = DAG.getBuildVector(FloatVT, dl, Ops);
15285  return DAG.getNode(ISD::BITCAST, dl, VT, BV);
15286}
15287
15288/// Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
15289static SDValue
15290PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
15291  // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
15292  // At that time, we may have inserted bitcasts from integer to float.
15293  // If these bitcasts have survived DAGCombine, change the lowering of this
15294  // BUILD_VECTOR in something more vector friendly, i.e., that does not
15295  // force to use floating point types.
15296
15297  // Make sure we can change the type of the vector.
15298  // This is possible iff:
15299  // 1. The vector is only used in a bitcast to a integer type. I.e.,
15300  //    1.1. Vector is used only once.
15301  //    1.2. Use is a bit convert to an integer type.
15302  // 2. The size of its operands are 32-bits (64-bits are not legal).
15303  EVT VT = N->getValueType(0);
15304  EVT EltVT = VT.getVectorElementType();
15305
15306  // Check 1.1. and 2.
15307  if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
15308    return SDValue();
15309
15310  // By construction, the input type must be float.
15311  assert(EltVT == MVT::f32 && "Unexpected type!");
15312
15313  // Check 1.2.
15314  SDNode *Use = *N->use_begin();
15315  if (Use->getOpcode() != ISD::BITCAST ||
15316      Use->getValueType(0).isFloatingPoint())
15317    return SDValue();
15318
15319  // Check profitability.
15320  // Model is, if more than half of the relevant operands are bitcast from
15321  // i32, turn the build_vector into a sequence of insert_vector_elt.
15322  // Relevant operands are everything that is not statically
15323  // (i.e., at compile time) bitcasted.
15324  unsigned NumOfBitCastedElts = 0;
15325  unsigned NumElts = VT.getVectorNumElements();
15326  unsigned NumOfRelevantElts = NumElts;
15327  for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
15328    SDValue Elt = N->getOperand(Idx);
15329    if (Elt->getOpcode() == ISD::BITCAST) {
15330      // Assume only bit cast to i32 will go away.
15331      if (Elt->getOperand(0).getValueType() == MVT::i32)
15332        ++NumOfBitCastedElts;
15333    } else if (Elt.isUndef() || isa<ConstantSDNode>(Elt))
15334      // Constants are statically casted, thus do not count them as
15335      // relevant operands.
15336      --NumOfRelevantElts;
15337  }
15338
15339  // Check if more than half of the elements require a non-free bitcast.
15340  if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
15341    return SDValue();
15342
15343  SelectionDAG &DAG = DCI.DAG;
15344  // Create the new vector type.
15345  EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
15346  // Check if the type is legal.
15347  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15348  if (!TLI.isTypeLegal(VecVT))
15349    return SDValue();
15350
15351  // Combine:
15352  // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
15353  // => BITCAST INSERT_VECTOR_ELT
15354  //                      (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
15355  //                      (BITCAST EN), N.
15356  SDValue Vec = DAG.getUNDEF(VecVT);
15357  SDLoc dl(N);
15358  for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
15359    SDValue V = N->getOperand(Idx);
15360    if (V.isUndef())
15361      continue;
15362    if (V.getOpcode() == ISD::BITCAST &&
15363        V->getOperand(0).getValueType() == MVT::i32)
15364      // Fold obvious case.
15365      V = V.getOperand(0);
15366    else {
15367      V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
15368      // Make the DAGCombiner fold the bitcasts.
15369      DCI.AddToWorklist(V.getNode());
15370    }
15371    SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32);
15372    Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
15373  }
15374  Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
15375  // Make the DAGCombiner fold the bitcasts.
15376  DCI.AddToWorklist(Vec.getNode());
15377  return Vec;
15378}
15379
15380static SDValue
15381PerformPREDICATE_CASTCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
15382  EVT VT = N->getValueType(0);
15383  SDValue Op = N->getOperand(0);
15384  SDLoc dl(N);
15385
15386  // PREDICATE_CAST(PREDICATE_CAST(x)) == PREDICATE_CAST(x)
15387  if (Op->getOpcode() == ARMISD::PREDICATE_CAST) {
15388    // If the valuetypes are the same, we can remove the cast entirely.
15389    if (Op->getOperand(0).getValueType() == VT)
15390      return Op->getOperand(0);
15391    return DCI.DAG.getNode(ARMISD::PREDICATE_CAST, dl, VT, Op->getOperand(0));
15392  }
15393
15394  // Turn pred_cast(xor x, -1) into xor(pred_cast x, -1), in order to produce
15395  // more VPNOT which might get folded as else predicates.
15396  if (Op.getValueType() == MVT::i32 && isBitwiseNot(Op)) {
15397    SDValue X =
15398        DCI.DAG.getNode(ARMISD::PREDICATE_CAST, dl, VT, Op->getOperand(0));
15399    SDValue C = DCI.DAG.getNode(ARMISD::PREDICATE_CAST, dl, VT,
15400                                DCI.DAG.getConstant(65535, dl, MVT::i32));
15401    return DCI.DAG.getNode(ISD::XOR, dl, VT, X, C);
15402  }
15403
15404  // Only the bottom 16 bits of the source register are used.
15405  if (Op.getValueType() == MVT::i32) {
15406    APInt DemandedMask = APInt::getLowBitsSet(32, 16);
15407    const TargetLowering &TLI = DCI.DAG.getTargetLoweringInfo();
15408    if (TLI.SimplifyDemandedBits(Op, DemandedMask, DCI))
15409      return SDValue(N, 0);
15410  }
15411  return SDValue();
15412}
15413
15414static SDValue PerformVECTOR_REG_CASTCombine(SDNode *N, SelectionDAG &DAG,
15415                                             const ARMSubtarget *ST) {
15416  EVT VT = N->getValueType(0);
15417  SDValue Op = N->getOperand(0);
15418  SDLoc dl(N);
15419
15420  // Under Little endian, a VECTOR_REG_CAST is equivalent to a BITCAST
15421  if (ST->isLittle())
15422    return DAG.getNode(ISD::BITCAST, dl, VT, Op);
15423
15424  // VECTOR_REG_CAST undef -> undef
15425  if (Op.isUndef())
15426    return DAG.getUNDEF(VT);
15427
15428  // VECTOR_REG_CAST(VECTOR_REG_CAST(x)) == VECTOR_REG_CAST(x)
15429  if (Op->getOpcode() == ARMISD::VECTOR_REG_CAST) {
15430    // If the valuetypes are the same, we can remove the cast entirely.
15431    if (Op->getOperand(0).getValueType() == VT)
15432      return Op->getOperand(0);
15433    return DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, VT, Op->getOperand(0));
15434  }
15435
15436  return SDValue();
15437}
15438
15439static SDValue PerformVCMPCombine(SDNode *N, SelectionDAG &DAG,
15440                                  const ARMSubtarget *Subtarget) {
15441  if (!Subtarget->hasMVEIntegerOps())
15442    return SDValue();
15443
15444  EVT VT = N->getValueType(0);
15445  SDValue Op0 = N->getOperand(0);
15446  SDValue Op1 = N->getOperand(1);
15447  ARMCC::CondCodes Cond = (ARMCC::CondCodes)N->getConstantOperandVal(2);
15448  SDLoc dl(N);
15449
15450  // vcmp X, 0, cc -> vcmpz X, cc
15451  if (isZeroVector(Op1))
15452    return DAG.getNode(ARMISD::VCMPZ, dl, VT, Op0, N->getOperand(2));
15453
15454  unsigned SwappedCond = getSwappedCondition(Cond);
15455  if (isValidMVECond(SwappedCond, VT.isFloatingPoint())) {
15456    // vcmp 0, X, cc -> vcmpz X, reversed(cc)
15457    if (isZeroVector(Op0))
15458      return DAG.getNode(ARMISD::VCMPZ, dl, VT, Op1,
15459                         DAG.getConstant(SwappedCond, dl, MVT::i32));
15460    // vcmp vdup(Y), X, cc -> vcmp X, vdup(Y), reversed(cc)
15461    if (Op0->getOpcode() == ARMISD::VDUP && Op1->getOpcode() != ARMISD::VDUP)
15462      return DAG.getNode(ARMISD::VCMP, dl, VT, Op1, Op0,
15463                         DAG.getConstant(SwappedCond, dl, MVT::i32));
15464  }
15465
15466  return SDValue();
15467}
15468
15469/// PerformInsertEltCombine - Target-specific dag combine xforms for
15470/// ISD::INSERT_VECTOR_ELT.
15471static SDValue PerformInsertEltCombine(SDNode *N,
15472                                       TargetLowering::DAGCombinerInfo &DCI) {
15473  // Bitcast an i64 load inserted into a vector to f64.
15474  // Otherwise, the i64 value will be legalized to a pair of i32 values.
15475  EVT VT = N->getValueType(0);
15476  SDNode *Elt = N->getOperand(1).getNode();
15477  if (VT.getVectorElementType() != MVT::i64 ||
15478      !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
15479    return SDValue();
15480
15481  SelectionDAG &DAG = DCI.DAG;
15482  SDLoc dl(N);
15483  EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
15484                                 VT.getVectorNumElements());
15485  SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
15486  SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
15487  // Make the DAGCombiner fold the bitcasts.
15488  DCI.AddToWorklist(Vec.getNode());
15489  DCI.AddToWorklist(V.getNode());
15490  SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
15491                               Vec, V, N->getOperand(2));
15492  return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
15493}
15494
15495// Convert a pair of extracts from the same base vector to a VMOVRRD. Either
15496// directly or bitcast to an integer if the original is a float vector.
15497// extract(x, n); extract(x, n+1)  ->  VMOVRRD(extract v2f64 x, n/2)
15498// bitcast(extract(x, n)); bitcast(extract(x, n+1))  ->  VMOVRRD(extract x, n/2)
15499static SDValue
15500PerformExtractEltToVMOVRRD(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
15501  EVT VT = N->getValueType(0);
15502  SDLoc dl(N);
15503
15504  if (!DCI.isAfterLegalizeDAG() || VT != MVT::i32 ||
15505      !DCI.DAG.getTargetLoweringInfo().isTypeLegal(MVT::f64))
15506    return SDValue();
15507
15508  SDValue Ext = SDValue(N, 0);
15509  if (Ext.getOpcode() == ISD::BITCAST &&
15510      Ext.getOperand(0).getValueType() == MVT::f32)
15511    Ext = Ext.getOperand(0);
15512  if (Ext.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
15513      !isa<ConstantSDNode>(Ext.getOperand(1)) ||
15514      Ext.getConstantOperandVal(1) % 2 != 0)
15515    return SDValue();
15516  if (Ext->use_size() == 1 &&
15517      (Ext->use_begin()->getOpcode() == ISD::SINT_TO_FP ||
15518       Ext->use_begin()->getOpcode() == ISD::UINT_TO_FP))
15519    return SDValue();
15520
15521  SDValue Op0 = Ext.getOperand(0);
15522  EVT VecVT = Op0.getValueType();
15523  unsigned ResNo = Op0.getResNo();
15524  unsigned Lane = Ext.getConstantOperandVal(1);
15525  if (VecVT.getVectorNumElements() != 4)
15526    return SDValue();
15527
15528  // Find another extract, of Lane + 1
15529  auto OtherIt = find_if(Op0->uses(), [&](SDNode *V) {
15530    return V->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
15531           isa<ConstantSDNode>(V->getOperand(1)) &&
15532           V->getConstantOperandVal(1) == Lane + 1 &&
15533           V->getOperand(0).getResNo() == ResNo;
15534  });
15535  if (OtherIt == Op0->uses().end())
15536    return SDValue();
15537
15538  // For float extracts, we need to be converting to a i32 for both vector
15539  // lanes.
15540  SDValue OtherExt(*OtherIt, 0);
15541  if (OtherExt.getValueType() != MVT::i32) {
15542    if (OtherExt->use_size() != 1 ||
15543        OtherExt->use_begin()->getOpcode() != ISD::BITCAST ||
15544        OtherExt->use_begin()->getValueType(0) != MVT::i32)
15545      return SDValue();
15546    OtherExt = SDValue(*OtherExt->use_begin(), 0);
15547  }
15548
15549  // Convert the type to a f64 and extract with a VMOVRRD.
15550  SDValue F64 = DCI.DAG.getNode(
15551      ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
15552      DCI.DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, MVT::v2f64, Op0),
15553      DCI.DAG.getConstant(Ext.getConstantOperandVal(1) / 2, dl, MVT::i32));
15554  SDValue VMOVRRD =
15555      DCI.DAG.getNode(ARMISD::VMOVRRD, dl, {MVT::i32, MVT::i32}, F64);
15556
15557  DCI.CombineTo(OtherExt.getNode(), SDValue(VMOVRRD.getNode(), 1));
15558  return VMOVRRD;
15559}
15560
15561static SDValue PerformExtractEltCombine(SDNode *N,
15562                                        TargetLowering::DAGCombinerInfo &DCI,
15563                                        const ARMSubtarget *ST) {
15564  SDValue Op0 = N->getOperand(0);
15565  EVT VT = N->getValueType(0);
15566  SDLoc dl(N);
15567
15568  // extract (vdup x) -> x
15569  if (Op0->getOpcode() == ARMISD::VDUP) {
15570    SDValue X = Op0->getOperand(0);
15571    if (VT == MVT::f16 && X.getValueType() == MVT::i32)
15572      return DCI.DAG.getNode(ARMISD::VMOVhr, dl, VT, X);
15573    if (VT == MVT::i32 && X.getValueType() == MVT::f16)
15574      return DCI.DAG.getNode(ARMISD::VMOVrh, dl, VT, X);
15575    if (VT == MVT::f32 && X.getValueType() == MVT::i32)
15576      return DCI.DAG.getNode(ISD::BITCAST, dl, VT, X);
15577
15578    while (X.getValueType() != VT && X->getOpcode() == ISD::BITCAST)
15579      X = X->getOperand(0);
15580    if (X.getValueType() == VT)
15581      return X;
15582  }
15583
15584  // extract ARM_BUILD_VECTOR -> x
15585  if (Op0->getOpcode() == ARMISD::BUILD_VECTOR &&
15586      isa<ConstantSDNode>(N->getOperand(1)) &&
15587      N->getConstantOperandVal(1) < Op0.getNumOperands()) {
15588    return Op0.getOperand(N->getConstantOperandVal(1));
15589  }
15590
15591  // extract(bitcast(BUILD_VECTOR(VMOVDRR(a, b), ..))) -> a or b
15592  if (Op0.getValueType() == MVT::v4i32 &&
15593      isa<ConstantSDNode>(N->getOperand(1)) &&
15594      Op0.getOpcode() == ISD::BITCAST &&
15595      Op0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
15596      Op0.getOperand(0).getValueType() == MVT::v2f64) {
15597    SDValue BV = Op0.getOperand(0);
15598    unsigned Offset = N->getConstantOperandVal(1);
15599    SDValue MOV = BV.getOperand(Offset < 2 ? 0 : 1);
15600    if (MOV.getOpcode() == ARMISD::VMOVDRR)
15601      return MOV.getOperand(ST->isLittle() ? Offset % 2 : 1 - Offset % 2);
15602  }
15603
15604  // extract x, n; extract x, n+1  ->  VMOVRRD x
15605  if (SDValue R = PerformExtractEltToVMOVRRD(N, DCI))
15606    return R;
15607
15608  // extract (MVETrunc(x)) -> extract x
15609  if (Op0->getOpcode() == ARMISD::MVETRUNC) {
15610    unsigned Idx = N->getConstantOperandVal(1);
15611    unsigned Vec =
15612        Idx / Op0->getOperand(0).getValueType().getVectorNumElements();
15613    unsigned SubIdx =
15614        Idx % Op0->getOperand(0).getValueType().getVectorNumElements();
15615    return DCI.DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Op0.getOperand(Vec),
15616                           DCI.DAG.getConstant(SubIdx, dl, MVT::i32));
15617  }
15618
15619  return SDValue();
15620}
15621
15622static SDValue PerformSignExtendInregCombine(SDNode *N, SelectionDAG &DAG) {
15623  SDValue Op = N->getOperand(0);
15624  EVT VT = N->getValueType(0);
15625
15626  // sext_inreg(VGETLANEu) -> VGETLANEs
15627  if (Op.getOpcode() == ARMISD::VGETLANEu &&
15628      cast<VTSDNode>(N->getOperand(1))->getVT() ==
15629          Op.getOperand(0).getValueType().getScalarType())
15630    return DAG.getNode(ARMISD::VGETLANEs, SDLoc(N), VT, Op.getOperand(0),
15631                       Op.getOperand(1));
15632
15633  return SDValue();
15634}
15635
15636static SDValue
15637PerformInsertSubvectorCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
15638  SDValue Vec = N->getOperand(0);
15639  SDValue SubVec = N->getOperand(1);
15640  uint64_t IdxVal = N->getConstantOperandVal(2);
15641  EVT VecVT = Vec.getValueType();
15642  EVT SubVT = SubVec.getValueType();
15643
15644  // Only do this for legal fixed vector types.
15645  if (!VecVT.isFixedLengthVector() ||
15646      !DCI.DAG.getTargetLoweringInfo().isTypeLegal(VecVT) ||
15647      !DCI.DAG.getTargetLoweringInfo().isTypeLegal(SubVT))
15648    return SDValue();
15649
15650  // Ignore widening patterns.
15651  if (IdxVal == 0 && Vec.isUndef())
15652    return SDValue();
15653
15654  // Subvector must be half the width and an "aligned" insertion.
15655  unsigned NumSubElts = SubVT.getVectorNumElements();
15656  if ((SubVT.getSizeInBits() * 2) != VecVT.getSizeInBits() ||
15657      (IdxVal != 0 && IdxVal != NumSubElts))
15658    return SDValue();
15659
15660  // Fold insert_subvector -> concat_vectors
15661  // insert_subvector(Vec,Sub,lo) -> concat_vectors(Sub,extract(Vec,hi))
15662  // insert_subvector(Vec,Sub,hi) -> concat_vectors(extract(Vec,lo),Sub)
15663  SDLoc DL(N);
15664  SDValue Lo, Hi;
15665  if (IdxVal == 0) {
15666    Lo = SubVec;
15667    Hi = DCI.DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, Vec,
15668                         DCI.DAG.getVectorIdxConstant(NumSubElts, DL));
15669  } else {
15670    Lo = DCI.DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, Vec,
15671                         DCI.DAG.getVectorIdxConstant(0, DL));
15672    Hi = SubVec;
15673  }
15674  return DCI.DAG.getNode(ISD::CONCAT_VECTORS, DL, VecVT, Lo, Hi);
15675}
15676
15677// shuffle(MVETrunc(x, y)) -> VMOVN(x, y)
15678static SDValue PerformShuffleVMOVNCombine(ShuffleVectorSDNode *N,
15679                                          SelectionDAG &DAG) {
15680  SDValue Trunc = N->getOperand(0);
15681  EVT VT = Trunc.getValueType();
15682  if (Trunc.getOpcode() != ARMISD::MVETRUNC || !N->getOperand(1).isUndef())
15683    return SDValue();
15684
15685  SDLoc DL(Trunc);
15686  if (isVMOVNTruncMask(N->getMask(), VT, false))
15687    return DAG.getNode(
15688        ARMISD::VMOVN, DL, VT,
15689        DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, VT, Trunc.getOperand(0)),
15690        DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, VT, Trunc.getOperand(1)),
15691        DAG.getConstant(1, DL, MVT::i32));
15692  else if (isVMOVNTruncMask(N->getMask(), VT, true))
15693    return DAG.getNode(
15694        ARMISD::VMOVN, DL, VT,
15695        DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, VT, Trunc.getOperand(1)),
15696        DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, VT, Trunc.getOperand(0)),
15697        DAG.getConstant(1, DL, MVT::i32));
15698  return SDValue();
15699}
15700
15701/// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
15702/// ISD::VECTOR_SHUFFLE.
15703static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
15704  if (SDValue R = PerformShuffleVMOVNCombine(cast<ShuffleVectorSDNode>(N), DAG))
15705    return R;
15706
15707  // The LLVM shufflevector instruction does not require the shuffle mask
15708  // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
15709  // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
15710  // operands do not match the mask length, they are extended by concatenating
15711  // them with undef vectors.  That is probably the right thing for other
15712  // targets, but for NEON it is better to concatenate two double-register
15713  // size vector operands into a single quad-register size vector.  Do that
15714  // transformation here:
15715  //   shuffle(concat(v1, undef), concat(v2, undef)) ->
15716  //   shuffle(concat(v1, v2), undef)
15717  SDValue Op0 = N->getOperand(0);
15718  SDValue Op1 = N->getOperand(1);
15719  if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
15720      Op1.getOpcode() != ISD::CONCAT_VECTORS ||
15721      Op0.getNumOperands() != 2 ||
15722      Op1.getNumOperands() != 2)
15723    return SDValue();
15724  SDValue Concat0Op1 = Op0.getOperand(1);
15725  SDValue Concat1Op1 = Op1.getOperand(1);
15726  if (!Concat0Op1.isUndef() || !Concat1Op1.isUndef())
15727    return SDValue();
15728  // Skip the transformation if any of the types are illegal.
15729  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15730  EVT VT = N->getValueType(0);
15731  if (!TLI.isTypeLegal(VT) ||
15732      !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
15733      !TLI.isTypeLegal(Concat1Op1.getValueType()))
15734    return SDValue();
15735
15736  SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
15737                                  Op0.getOperand(0), Op1.getOperand(0));
15738  // Translate the shuffle mask.
15739  SmallVector<int, 16> NewMask;
15740  unsigned NumElts = VT.getVectorNumElements();
15741  unsigned HalfElts = NumElts/2;
15742  ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
15743  for (unsigned n = 0; n < NumElts; ++n) {
15744    int MaskElt = SVN->getMaskElt(n);
15745    int NewElt = -1;
15746    if (MaskElt < (int)HalfElts)
15747      NewElt = MaskElt;
15748    else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
15749      NewElt = HalfElts + MaskElt - NumElts;
15750    NewMask.push_back(NewElt);
15751  }
15752  return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
15753                              DAG.getUNDEF(VT), NewMask);
15754}
15755
15756/// Load/store instruction that can be merged with a base address
15757/// update
15758struct BaseUpdateTarget {
15759  SDNode *N;
15760  bool isIntrinsic;
15761  bool isStore;
15762  unsigned AddrOpIdx;
15763};
15764
15765struct BaseUpdateUser {
15766  /// Instruction that updates a pointer
15767  SDNode *N;
15768  /// Pointer increment operand
15769  SDValue Inc;
15770  /// Pointer increment value if it is a constant, or 0 otherwise
15771  unsigned ConstInc;
15772};
15773
15774static bool TryCombineBaseUpdate(struct BaseUpdateTarget &Target,
15775                                 struct BaseUpdateUser &User,
15776                                 bool SimpleConstIncOnly,
15777                                 TargetLowering::DAGCombinerInfo &DCI) {
15778  SelectionDAG &DAG = DCI.DAG;
15779  SDNode *N = Target.N;
15780  MemSDNode *MemN = cast<MemSDNode>(N);
15781  SDLoc dl(N);
15782
15783  // Find the new opcode for the updating load/store.
15784  bool isLoadOp = true;
15785  bool isLaneOp = false;
15786  // Workaround for vst1x and vld1x intrinsics which do not have alignment
15787  // as an operand.
15788  bool hasAlignment = true;
15789  unsigned NewOpc = 0;
15790  unsigned NumVecs = 0;
15791  if (Target.isIntrinsic) {
15792    unsigned IntNo = N->getConstantOperandVal(1);
15793    switch (IntNo) {
15794    default:
15795      llvm_unreachable("unexpected intrinsic for Neon base update");
15796    case Intrinsic::arm_neon_vld1:
15797      NewOpc = ARMISD::VLD1_UPD;
15798      NumVecs = 1;
15799      break;
15800    case Intrinsic::arm_neon_vld2:
15801      NewOpc = ARMISD::VLD2_UPD;
15802      NumVecs = 2;
15803      break;
15804    case Intrinsic::arm_neon_vld3:
15805      NewOpc = ARMISD::VLD3_UPD;
15806      NumVecs = 3;
15807      break;
15808    case Intrinsic::arm_neon_vld4:
15809      NewOpc = ARMISD::VLD4_UPD;
15810      NumVecs = 4;
15811      break;
15812    case Intrinsic::arm_neon_vld1x2:
15813      NewOpc = ARMISD::VLD1x2_UPD;
15814      NumVecs = 2;
15815      hasAlignment = false;
15816      break;
15817    case Intrinsic::arm_neon_vld1x3:
15818      NewOpc = ARMISD::VLD1x3_UPD;
15819      NumVecs = 3;
15820      hasAlignment = false;
15821      break;
15822    case Intrinsic::arm_neon_vld1x4:
15823      NewOpc = ARMISD::VLD1x4_UPD;
15824      NumVecs = 4;
15825      hasAlignment = false;
15826      break;
15827    case Intrinsic::arm_neon_vld2dup:
15828      NewOpc = ARMISD::VLD2DUP_UPD;
15829      NumVecs = 2;
15830      break;
15831    case Intrinsic::arm_neon_vld3dup:
15832      NewOpc = ARMISD::VLD3DUP_UPD;
15833      NumVecs = 3;
15834      break;
15835    case Intrinsic::arm_neon_vld4dup:
15836      NewOpc = ARMISD::VLD4DUP_UPD;
15837      NumVecs = 4;
15838      break;
15839    case Intrinsic::arm_neon_vld2lane:
15840      NewOpc = ARMISD::VLD2LN_UPD;
15841      NumVecs = 2;
15842      isLaneOp = true;
15843      break;
15844    case Intrinsic::arm_neon_vld3lane:
15845      NewOpc = ARMISD::VLD3LN_UPD;
15846      NumVecs = 3;
15847      isLaneOp = true;
15848      break;
15849    case Intrinsic::arm_neon_vld4lane:
15850      NewOpc = ARMISD::VLD4LN_UPD;
15851      NumVecs = 4;
15852      isLaneOp = true;
15853      break;
15854    case Intrinsic::arm_neon_vst1:
15855      NewOpc = ARMISD::VST1_UPD;
15856      NumVecs = 1;
15857      isLoadOp = false;
15858      break;
15859    case Intrinsic::arm_neon_vst2:
15860      NewOpc = ARMISD::VST2_UPD;
15861      NumVecs = 2;
15862      isLoadOp = false;
15863      break;
15864    case Intrinsic::arm_neon_vst3:
15865      NewOpc = ARMISD::VST3_UPD;
15866      NumVecs = 3;
15867      isLoadOp = false;
15868      break;
15869    case Intrinsic::arm_neon_vst4:
15870      NewOpc = ARMISD::VST4_UPD;
15871      NumVecs = 4;
15872      isLoadOp = false;
15873      break;
15874    case Intrinsic::arm_neon_vst2lane:
15875      NewOpc = ARMISD::VST2LN_UPD;
15876      NumVecs = 2;
15877      isLoadOp = false;
15878      isLaneOp = true;
15879      break;
15880    case Intrinsic::arm_neon_vst3lane:
15881      NewOpc = ARMISD::VST3LN_UPD;
15882      NumVecs = 3;
15883      isLoadOp = false;
15884      isLaneOp = true;
15885      break;
15886    case Intrinsic::arm_neon_vst4lane:
15887      NewOpc = ARMISD::VST4LN_UPD;
15888      NumVecs = 4;
15889      isLoadOp = false;
15890      isLaneOp = true;
15891      break;
15892    case Intrinsic::arm_neon_vst1x2:
15893      NewOpc = ARMISD::VST1x2_UPD;
15894      NumVecs = 2;
15895      isLoadOp = false;
15896      hasAlignment = false;
15897      break;
15898    case Intrinsic::arm_neon_vst1x3:
15899      NewOpc = ARMISD::VST1x3_UPD;
15900      NumVecs = 3;
15901      isLoadOp = false;
15902      hasAlignment = false;
15903      break;
15904    case Intrinsic::arm_neon_vst1x4:
15905      NewOpc = ARMISD::VST1x4_UPD;
15906      NumVecs = 4;
15907      isLoadOp = false;
15908      hasAlignment = false;
15909      break;
15910    }
15911  } else {
15912    isLaneOp = true;
15913    switch (N->getOpcode()) {
15914    default:
15915      llvm_unreachable("unexpected opcode for Neon base update");
15916    case ARMISD::VLD1DUP:
15917      NewOpc = ARMISD::VLD1DUP_UPD;
15918      NumVecs = 1;
15919      break;
15920    case ARMISD::VLD2DUP:
15921      NewOpc = ARMISD::VLD2DUP_UPD;
15922      NumVecs = 2;
15923      break;
15924    case ARMISD::VLD3DUP:
15925      NewOpc = ARMISD::VLD3DUP_UPD;
15926      NumVecs = 3;
15927      break;
15928    case ARMISD::VLD4DUP:
15929      NewOpc = ARMISD::VLD4DUP_UPD;
15930      NumVecs = 4;
15931      break;
15932    case ISD::LOAD:
15933      NewOpc = ARMISD::VLD1_UPD;
15934      NumVecs = 1;
15935      isLaneOp = false;
15936      break;
15937    case ISD::STORE:
15938      NewOpc = ARMISD::VST1_UPD;
15939      NumVecs = 1;
15940      isLaneOp = false;
15941      isLoadOp = false;
15942      break;
15943    }
15944  }
15945
15946  // Find the size of memory referenced by the load/store.
15947  EVT VecTy;
15948  if (isLoadOp) {
15949    VecTy = N->getValueType(0);
15950  } else if (Target.isIntrinsic) {
15951    VecTy = N->getOperand(Target.AddrOpIdx + 1).getValueType();
15952  } else {
15953    assert(Target.isStore &&
15954           "Node has to be a load, a store, or an intrinsic!");
15955    VecTy = N->getOperand(1).getValueType();
15956  }
15957
15958  bool isVLDDUPOp =
15959      NewOpc == ARMISD::VLD1DUP_UPD || NewOpc == ARMISD::VLD2DUP_UPD ||
15960      NewOpc == ARMISD::VLD3DUP_UPD || NewOpc == ARMISD::VLD4DUP_UPD;
15961
15962  unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
15963  if (isLaneOp || isVLDDUPOp)
15964    NumBytes /= VecTy.getVectorNumElements();
15965
15966  if (NumBytes >= 3 * 16 && User.ConstInc != NumBytes) {
15967    // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
15968    // separate instructions that make it harder to use a non-constant update.
15969    return false;
15970  }
15971
15972  if (SimpleConstIncOnly && User.ConstInc != NumBytes)
15973    return false;
15974
15975  // OK, we found an ADD we can fold into the base update.
15976  // Now, create a _UPD node, taking care of not breaking alignment.
15977
15978  EVT AlignedVecTy = VecTy;
15979  Align Alignment = MemN->getAlign();
15980
15981  // If this is a less-than-standard-aligned load/store, change the type to
15982  // match the standard alignment.
15983  // The alignment is overlooked when selecting _UPD variants; and it's
15984  // easier to introduce bitcasts here than fix that.
15985  // There are 3 ways to get to this base-update combine:
15986  // - intrinsics: they are assumed to be properly aligned (to the standard
15987  //   alignment of the memory type), so we don't need to do anything.
15988  // - ARMISD::VLDx nodes: they are only generated from the aforementioned
15989  //   intrinsics, so, likewise, there's nothing to do.
15990  // - generic load/store instructions: the alignment is specified as an
15991  //   explicit operand, rather than implicitly as the standard alignment
15992  //   of the memory type (like the intrisics).  We need to change the
15993  //   memory type to match the explicit alignment.  That way, we don't
15994  //   generate non-standard-aligned ARMISD::VLDx nodes.
15995  if (isa<LSBaseSDNode>(N)) {
15996    if (Alignment.value() < VecTy.getScalarSizeInBits() / 8) {
15997      MVT EltTy = MVT::getIntegerVT(Alignment.value() * 8);
15998      assert(NumVecs == 1 && "Unexpected multi-element generic load/store.");
15999      assert(!isLaneOp && "Unexpected generic load/store lane.");
16000      unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8);
16001      AlignedVecTy = MVT::getVectorVT(EltTy, NumElts);
16002    }
16003    // Don't set an explicit alignment on regular load/stores that we want
16004    // to transform to VLD/VST 1_UPD nodes.
16005    // This matches the behavior of regular load/stores, which only get an
16006    // explicit alignment if the MMO alignment is larger than the standard
16007    // alignment of the memory type.
16008    // Intrinsics, however, always get an explicit alignment, set to the
16009    // alignment of the MMO.
16010    Alignment = Align(1);
16011  }
16012
16013  // Create the new updating load/store node.
16014  // First, create an SDVTList for the new updating node's results.
16015  EVT Tys[6];
16016  unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
16017  unsigned n;
16018  for (n = 0; n < NumResultVecs; ++n)
16019    Tys[n] = AlignedVecTy;
16020  Tys[n++] = MVT::i32;
16021  Tys[n] = MVT::Other;
16022  SDVTList SDTys = DAG.getVTList(ArrayRef(Tys, NumResultVecs + 2));
16023
16024  // Then, gather the new node's operands.
16025  SmallVector<SDValue, 8> Ops;
16026  Ops.push_back(N->getOperand(0)); // incoming chain
16027  Ops.push_back(N->getOperand(Target.AddrOpIdx));
16028  Ops.push_back(User.Inc);
16029
16030  if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) {
16031    // Try to match the intrinsic's signature
16032    Ops.push_back(StN->getValue());
16033  } else {
16034    // Loads (and of course intrinsics) match the intrinsics' signature,
16035    // so just add all but the alignment operand.
16036    unsigned LastOperand =
16037        hasAlignment ? N->getNumOperands() - 1 : N->getNumOperands();
16038    for (unsigned i = Target.AddrOpIdx + 1; i < LastOperand; ++i)
16039      Ops.push_back(N->getOperand(i));
16040  }
16041
16042  // For all node types, the alignment operand is always the last one.
16043  Ops.push_back(DAG.getConstant(Alignment.value(), dl, MVT::i32));
16044
16045  // If this is a non-standard-aligned STORE, the penultimate operand is the
16046  // stored value.  Bitcast it to the aligned type.
16047  if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) {
16048    SDValue &StVal = Ops[Ops.size() - 2];
16049    StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal);
16050  }
16051
16052  EVT LoadVT = isLaneOp ? VecTy.getVectorElementType() : AlignedVecTy;
16053  SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys, Ops, LoadVT,
16054                                         MemN->getMemOperand());
16055
16056  // Update the uses.
16057  SmallVector<SDValue, 5> NewResults;
16058  for (unsigned i = 0; i < NumResultVecs; ++i)
16059    NewResults.push_back(SDValue(UpdN.getNode(), i));
16060
16061  // If this is an non-standard-aligned LOAD, the first result is the loaded
16062  // value.  Bitcast it to the expected result type.
16063  if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) {
16064    SDValue &LdVal = NewResults[0];
16065    LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal);
16066  }
16067
16068  NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1)); // chain
16069  DCI.CombineTo(N, NewResults);
16070  DCI.CombineTo(User.N, SDValue(UpdN.getNode(), NumResultVecs));
16071
16072  return true;
16073}
16074
16075// If (opcode ptr inc) is and ADD-like instruction, return the
16076// increment value. Otherwise return 0.
16077static unsigned getPointerConstIncrement(unsigned Opcode, SDValue Ptr,
16078                                         SDValue Inc, const SelectionDAG &DAG) {
16079  ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode());
16080  if (!CInc)
16081    return 0;
16082
16083  switch (Opcode) {
16084  case ARMISD::VLD1_UPD:
16085  case ISD::ADD:
16086    return CInc->getZExtValue();
16087  case ISD::OR: {
16088    if (DAG.haveNoCommonBitsSet(Ptr, Inc)) {
16089      // (OR ptr inc) is the same as (ADD ptr inc)
16090      return CInc->getZExtValue();
16091    }
16092    return 0;
16093  }
16094  default:
16095    return 0;
16096  }
16097}
16098
16099static bool findPointerConstIncrement(SDNode *N, SDValue *Ptr, SDValue *CInc) {
16100  switch (N->getOpcode()) {
16101  case ISD::ADD:
16102  case ISD::OR: {
16103    if (isa<ConstantSDNode>(N->getOperand(1))) {
16104      *Ptr = N->getOperand(0);
16105      *CInc = N->getOperand(1);
16106      return true;
16107    }
16108    return false;
16109  }
16110  case ARMISD::VLD1_UPD: {
16111    if (isa<ConstantSDNode>(N->getOperand(2))) {
16112      *Ptr = N->getOperand(1);
16113      *CInc = N->getOperand(2);
16114      return true;
16115    }
16116    return false;
16117  }
16118  default:
16119    return false;
16120  }
16121}
16122
16123static bool isValidBaseUpdate(SDNode *N, SDNode *User) {
16124  // Check that the add is independent of the load/store.
16125  // Otherwise, folding it would create a cycle. Search through Addr
16126  // as well, since the User may not be a direct user of Addr and
16127  // only share a base pointer.
16128  SmallPtrSet<const SDNode *, 32> Visited;
16129  SmallVector<const SDNode *, 16> Worklist;
16130  Worklist.push_back(N);
16131  Worklist.push_back(User);
16132  if (SDNode::hasPredecessorHelper(N, Visited, Worklist) ||
16133      SDNode::hasPredecessorHelper(User, Visited, Worklist))
16134    return false;
16135  return true;
16136}
16137
16138/// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP,
16139/// NEON load/store intrinsics, and generic vector load/stores, to merge
16140/// base address updates.
16141/// For generic load/stores, the memory type is assumed to be a vector.
16142/// The caller is assumed to have checked legality.
16143static SDValue CombineBaseUpdate(SDNode *N,
16144                                 TargetLowering::DAGCombinerInfo &DCI) {
16145  const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
16146                            N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
16147  const bool isStore = N->getOpcode() == ISD::STORE;
16148  const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1);
16149  BaseUpdateTarget Target = {N, isIntrinsic, isStore, AddrOpIdx};
16150
16151  SDValue Addr = N->getOperand(AddrOpIdx);
16152
16153  SmallVector<BaseUpdateUser, 8> BaseUpdates;
16154
16155  // Search for a use of the address operand that is an increment.
16156  for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
16157         UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
16158    SDNode *User = *UI;
16159    if (UI.getUse().getResNo() != Addr.getResNo() ||
16160        User->getNumOperands() != 2)
16161      continue;
16162
16163    SDValue Inc = User->getOperand(UI.getOperandNo() == 1 ? 0 : 1);
16164    unsigned ConstInc =
16165        getPointerConstIncrement(User->getOpcode(), Addr, Inc, DCI.DAG);
16166
16167    if (ConstInc || User->getOpcode() == ISD::ADD)
16168      BaseUpdates.push_back({User, Inc, ConstInc});
16169  }
16170
16171  // If the address is a constant pointer increment itself, find
16172  // another constant increment that has the same base operand
16173  SDValue Base;
16174  SDValue CInc;
16175  if (findPointerConstIncrement(Addr.getNode(), &Base, &CInc)) {
16176    unsigned Offset =
16177        getPointerConstIncrement(Addr->getOpcode(), Base, CInc, DCI.DAG);
16178    for (SDNode::use_iterator UI = Base->use_begin(), UE = Base->use_end();
16179         UI != UE; ++UI) {
16180
16181      SDNode *User = *UI;
16182      if (UI.getUse().getResNo() != Base.getResNo() || User == Addr.getNode() ||
16183          User->getNumOperands() != 2)
16184        continue;
16185
16186      SDValue UserInc = User->getOperand(UI.getOperandNo() == 0 ? 1 : 0);
16187      unsigned UserOffset =
16188          getPointerConstIncrement(User->getOpcode(), Base, UserInc, DCI.DAG);
16189
16190      if (!UserOffset || UserOffset <= Offset)
16191        continue;
16192
16193      unsigned NewConstInc = UserOffset - Offset;
16194      SDValue NewInc = DCI.DAG.getConstant(NewConstInc, SDLoc(N), MVT::i32);
16195      BaseUpdates.push_back({User, NewInc, NewConstInc});
16196    }
16197  }
16198
16199  // Try to fold the load/store with an update that matches memory
16200  // access size. This should work well for sequential loads.
16201  //
16202  // Filter out invalid updates as well.
16203  unsigned NumValidUpd = BaseUpdates.size();
16204  for (unsigned I = 0; I < NumValidUpd;) {
16205    BaseUpdateUser &User = BaseUpdates[I];
16206    if (!isValidBaseUpdate(N, User.N)) {
16207      --NumValidUpd;
16208      std::swap(BaseUpdates[I], BaseUpdates[NumValidUpd]);
16209      continue;
16210    }
16211
16212    if (TryCombineBaseUpdate(Target, User, /*SimpleConstIncOnly=*/true, DCI))
16213      return SDValue();
16214    ++I;
16215  }
16216  BaseUpdates.resize(NumValidUpd);
16217
16218  // Try to fold with other users. Non-constant updates are considered
16219  // first, and constant updates are sorted to not break a sequence of
16220  // strided accesses (if there is any).
16221  std::stable_sort(BaseUpdates.begin(), BaseUpdates.end(),
16222                   [](const BaseUpdateUser &LHS, const BaseUpdateUser &RHS) {
16223                     return LHS.ConstInc < RHS.ConstInc;
16224                   });
16225  for (BaseUpdateUser &User : BaseUpdates) {
16226    if (TryCombineBaseUpdate(Target, User, /*SimpleConstIncOnly=*/false, DCI))
16227      return SDValue();
16228  }
16229  return SDValue();
16230}
16231
16232static SDValue PerformVLDCombine(SDNode *N,
16233                                 TargetLowering::DAGCombinerInfo &DCI) {
16234  if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
16235    return SDValue();
16236
16237  return CombineBaseUpdate(N, DCI);
16238}
16239
16240static SDValue PerformMVEVLDCombine(SDNode *N,
16241                                    TargetLowering::DAGCombinerInfo &DCI) {
16242  if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
16243    return SDValue();
16244
16245  SelectionDAG &DAG = DCI.DAG;
16246  SDValue Addr = N->getOperand(2);
16247  MemSDNode *MemN = cast<MemSDNode>(N);
16248  SDLoc dl(N);
16249
16250  // For the stores, where there are multiple intrinsics we only actually want
16251  // to post-inc the last of the them.
16252  unsigned IntNo = N->getConstantOperandVal(1);
16253  if (IntNo == Intrinsic::arm_mve_vst2q && N->getConstantOperandVal(5) != 1)
16254    return SDValue();
16255  if (IntNo == Intrinsic::arm_mve_vst4q && N->getConstantOperandVal(7) != 3)
16256    return SDValue();
16257
16258  // Search for a use of the address operand that is an increment.
16259  for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
16260                            UE = Addr.getNode()->use_end();
16261       UI != UE; ++UI) {
16262    SDNode *User = *UI;
16263    if (User->getOpcode() != ISD::ADD ||
16264        UI.getUse().getResNo() != Addr.getResNo())
16265      continue;
16266
16267    // Check that the add is independent of the load/store.  Otherwise, folding
16268    // it would create a cycle. We can avoid searching through Addr as it's a
16269    // predecessor to both.
16270    SmallPtrSet<const SDNode *, 32> Visited;
16271    SmallVector<const SDNode *, 16> Worklist;
16272    Visited.insert(Addr.getNode());
16273    Worklist.push_back(N);
16274    Worklist.push_back(User);
16275    if (SDNode::hasPredecessorHelper(N, Visited, Worklist) ||
16276        SDNode::hasPredecessorHelper(User, Visited, Worklist))
16277      continue;
16278
16279    // Find the new opcode for the updating load/store.
16280    bool isLoadOp = true;
16281    unsigned NewOpc = 0;
16282    unsigned NumVecs = 0;
16283    switch (IntNo) {
16284    default:
16285      llvm_unreachable("unexpected intrinsic for MVE VLDn combine");
16286    case Intrinsic::arm_mve_vld2q:
16287      NewOpc = ARMISD::VLD2_UPD;
16288      NumVecs = 2;
16289      break;
16290    case Intrinsic::arm_mve_vld4q:
16291      NewOpc = ARMISD::VLD4_UPD;
16292      NumVecs = 4;
16293      break;
16294    case Intrinsic::arm_mve_vst2q:
16295      NewOpc = ARMISD::VST2_UPD;
16296      NumVecs = 2;
16297      isLoadOp = false;
16298      break;
16299    case Intrinsic::arm_mve_vst4q:
16300      NewOpc = ARMISD::VST4_UPD;
16301      NumVecs = 4;
16302      isLoadOp = false;
16303      break;
16304    }
16305
16306    // Find the size of memory referenced by the load/store.
16307    EVT VecTy;
16308    if (isLoadOp) {
16309      VecTy = N->getValueType(0);
16310    } else {
16311      VecTy = N->getOperand(3).getValueType();
16312    }
16313
16314    unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
16315
16316    // If the increment is a constant, it must match the memory ref size.
16317    SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
16318    ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode());
16319    if (!CInc || CInc->getZExtValue() != NumBytes)
16320      continue;
16321
16322    // Create the new updating load/store node.
16323    // First, create an SDVTList for the new updating node's results.
16324    EVT Tys[6];
16325    unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
16326    unsigned n;
16327    for (n = 0; n < NumResultVecs; ++n)
16328      Tys[n] = VecTy;
16329    Tys[n++] = MVT::i32;
16330    Tys[n] = MVT::Other;
16331    SDVTList SDTys = DAG.getVTList(ArrayRef(Tys, NumResultVecs + 2));
16332
16333    // Then, gather the new node's operands.
16334    SmallVector<SDValue, 8> Ops;
16335    Ops.push_back(N->getOperand(0)); // incoming chain
16336    Ops.push_back(N->getOperand(2)); // ptr
16337    Ops.push_back(Inc);
16338
16339    for (unsigned i = 3; i < N->getNumOperands(); ++i)
16340      Ops.push_back(N->getOperand(i));
16341
16342    SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys, Ops, VecTy,
16343                                           MemN->getMemOperand());
16344
16345    // Update the uses.
16346    SmallVector<SDValue, 5> NewResults;
16347    for (unsigned i = 0; i < NumResultVecs; ++i)
16348      NewResults.push_back(SDValue(UpdN.getNode(), i));
16349
16350    NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1)); // chain
16351    DCI.CombineTo(N, NewResults);
16352    DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
16353
16354    break;
16355  }
16356
16357  return SDValue();
16358}
16359
16360/// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
16361/// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
16362/// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
16363/// return true.
16364static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
16365  SelectionDAG &DAG = DCI.DAG;
16366  EVT VT = N->getValueType(0);
16367  // vldN-dup instructions only support 64-bit vectors for N > 1.
16368  if (!VT.is64BitVector())
16369    return false;
16370
16371  // Check if the VDUPLANE operand is a vldN-dup intrinsic.
16372  SDNode *VLD = N->getOperand(0).getNode();
16373  if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
16374    return false;
16375  unsigned NumVecs = 0;
16376  unsigned NewOpc = 0;
16377  unsigned IntNo = VLD->getConstantOperandVal(1);
16378  if (IntNo == Intrinsic::arm_neon_vld2lane) {
16379    NumVecs = 2;
16380    NewOpc = ARMISD::VLD2DUP;
16381  } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
16382    NumVecs = 3;
16383    NewOpc = ARMISD::VLD3DUP;
16384  } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
16385    NumVecs = 4;
16386    NewOpc = ARMISD::VLD4DUP;
16387  } else {
16388    return false;
16389  }
16390
16391  // First check that all the vldN-lane uses are VDUPLANEs and that the lane
16392  // numbers match the load.
16393  unsigned VLDLaneNo = VLD->getConstantOperandVal(NumVecs + 3);
16394  for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
16395       UI != UE; ++UI) {
16396    // Ignore uses of the chain result.
16397    if (UI.getUse().getResNo() == NumVecs)
16398      continue;
16399    SDNode *User = *UI;
16400    if (User->getOpcode() != ARMISD::VDUPLANE ||
16401        VLDLaneNo != User->getConstantOperandVal(1))
16402      return false;
16403  }
16404
16405  // Create the vldN-dup node.
16406  EVT Tys[5];
16407  unsigned n;
16408  for (n = 0; n < NumVecs; ++n)
16409    Tys[n] = VT;
16410  Tys[n] = MVT::Other;
16411  SDVTList SDTys = DAG.getVTList(ArrayRef(Tys, NumVecs + 1));
16412  SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
16413  MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
16414  SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
16415                                           Ops, VLDMemInt->getMemoryVT(),
16416                                           VLDMemInt->getMemOperand());
16417
16418  // Update the uses.
16419  for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
16420       UI != UE; ++UI) {
16421    unsigned ResNo = UI.getUse().getResNo();
16422    // Ignore uses of the chain result.
16423    if (ResNo == NumVecs)
16424      continue;
16425    SDNode *User = *UI;
16426    DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
16427  }
16428
16429  // Now the vldN-lane intrinsic is dead except for its chain result.
16430  // Update uses of the chain.
16431  std::vector<SDValue> VLDDupResults;
16432  for (unsigned n = 0; n < NumVecs; ++n)
16433    VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
16434  VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
16435  DCI.CombineTo(VLD, VLDDupResults);
16436
16437  return true;
16438}
16439
16440/// PerformVDUPLANECombine - Target-specific dag combine xforms for
16441/// ARMISD::VDUPLANE.
16442static SDValue PerformVDUPLANECombine(SDNode *N,
16443                                      TargetLowering::DAGCombinerInfo &DCI,
16444                                      const ARMSubtarget *Subtarget) {
16445  SDValue Op = N->getOperand(0);
16446  EVT VT = N->getValueType(0);
16447
16448  // On MVE, we just convert the VDUPLANE to a VDUP with an extract.
16449  if (Subtarget->hasMVEIntegerOps()) {
16450    EVT ExtractVT = VT.getVectorElementType();
16451    // We need to ensure we are creating a legal type.
16452    if (!DCI.DAG.getTargetLoweringInfo().isTypeLegal(ExtractVT))
16453      ExtractVT = MVT::i32;
16454    SDValue Extract = DCI.DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), ExtractVT,
16455                              N->getOperand(0), N->getOperand(1));
16456    return DCI.DAG.getNode(ARMISD::VDUP, SDLoc(N), VT, Extract);
16457  }
16458
16459  // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
16460  // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
16461  if (CombineVLDDUP(N, DCI))
16462    return SDValue(N, 0);
16463
16464  // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
16465  // redundant.  Ignore bit_converts for now; element sizes are checked below.
16466  while (Op.getOpcode() == ISD::BITCAST)
16467    Op = Op.getOperand(0);
16468  if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
16469    return SDValue();
16470
16471  // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
16472  unsigned EltSize = Op.getScalarValueSizeInBits();
16473  // The canonical VMOV for a zero vector uses a 32-bit element size.
16474  unsigned Imm = Op.getConstantOperandVal(0);
16475  unsigned EltBits;
16476  if (ARM_AM::decodeVMOVModImm(Imm, EltBits) == 0)
16477    EltSize = 8;
16478  if (EltSize > VT.getScalarSizeInBits())
16479    return SDValue();
16480
16481  return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
16482}
16483
16484/// PerformVDUPCombine - Target-specific dag combine xforms for ARMISD::VDUP.
16485static SDValue PerformVDUPCombine(SDNode *N, SelectionDAG &DAG,
16486                                  const ARMSubtarget *Subtarget) {
16487  SDValue Op = N->getOperand(0);
16488  SDLoc dl(N);
16489
16490  if (Subtarget->hasMVEIntegerOps()) {
16491    // Convert VDUP f32 -> VDUP BITCAST i32 under MVE, as we know the value will
16492    // need to come from a GPR.
16493    if (Op.getValueType() == MVT::f32)
16494      return DAG.getNode(ARMISD::VDUP, dl, N->getValueType(0),
16495                         DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op));
16496    else if (Op.getValueType() == MVT::f16)
16497      return DAG.getNode(ARMISD::VDUP, dl, N->getValueType(0),
16498                         DAG.getNode(ARMISD::VMOVrh, dl, MVT::i32, Op));
16499  }
16500
16501  if (!Subtarget->hasNEON())
16502    return SDValue();
16503
16504  // Match VDUP(LOAD) -> VLD1DUP.
16505  // We match this pattern here rather than waiting for isel because the
16506  // transform is only legal for unindexed loads.
16507  LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode());
16508  if (LD && Op.hasOneUse() && LD->isUnindexed() &&
16509      LD->getMemoryVT() == N->getValueType(0).getVectorElementType()) {
16510    SDValue Ops[] = {LD->getOperand(0), LD->getOperand(1),
16511                     DAG.getConstant(LD->getAlign().value(), SDLoc(N), MVT::i32)};
16512    SDVTList SDTys = DAG.getVTList(N->getValueType(0), MVT::Other);
16513    SDValue VLDDup =
16514        DAG.getMemIntrinsicNode(ARMISD::VLD1DUP, SDLoc(N), SDTys, Ops,
16515                                LD->getMemoryVT(), LD->getMemOperand());
16516    DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), VLDDup.getValue(1));
16517    return VLDDup;
16518  }
16519
16520  return SDValue();
16521}
16522
16523static SDValue PerformLOADCombine(SDNode *N,
16524                                  TargetLowering::DAGCombinerInfo &DCI,
16525                                  const ARMSubtarget *Subtarget) {
16526  EVT VT = N->getValueType(0);
16527
16528  // If this is a legal vector load, try to combine it into a VLD1_UPD.
16529  if (Subtarget->hasNEON() && ISD::isNormalLoad(N) && VT.isVector() &&
16530      DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
16531    return CombineBaseUpdate(N, DCI);
16532
16533  return SDValue();
16534}
16535
16536// Optimize trunc store (of multiple scalars) to shuffle and store.  First,
16537// pack all of the elements in one place.  Next, store to memory in fewer
16538// chunks.
16539static SDValue PerformTruncatingStoreCombine(StoreSDNode *St,
16540                                             SelectionDAG &DAG) {
16541  SDValue StVal = St->getValue();
16542  EVT VT = StVal.getValueType();
16543  if (!St->isTruncatingStore() || !VT.isVector())
16544    return SDValue();
16545  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16546  EVT StVT = St->getMemoryVT();
16547  unsigned NumElems = VT.getVectorNumElements();
16548  assert(StVT != VT && "Cannot truncate to the same type");
16549  unsigned FromEltSz = VT.getScalarSizeInBits();
16550  unsigned ToEltSz = StVT.getScalarSizeInBits();
16551
16552  // From, To sizes and ElemCount must be pow of two
16553  if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz))
16554    return SDValue();
16555
16556  // We are going to use the original vector elt for storing.
16557  // Accumulated smaller vector elements must be a multiple of the store size.
16558  if (0 != (NumElems * FromEltSz) % ToEltSz)
16559    return SDValue();
16560
16561  unsigned SizeRatio = FromEltSz / ToEltSz;
16562  assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
16563
16564  // Create a type on which we perform the shuffle.
16565  EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
16566                                   NumElems * SizeRatio);
16567  assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
16568
16569  SDLoc DL(St);
16570  SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
16571  SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
16572  for (unsigned i = 0; i < NumElems; ++i)
16573    ShuffleVec[i] = DAG.getDataLayout().isBigEndian() ? (i + 1) * SizeRatio - 1
16574                                                      : i * SizeRatio;
16575
16576  // Can't shuffle using an illegal type.
16577  if (!TLI.isTypeLegal(WideVecVT))
16578    return SDValue();
16579
16580  SDValue Shuff = DAG.getVectorShuffle(
16581      WideVecVT, DL, WideVec, DAG.getUNDEF(WideVec.getValueType()), ShuffleVec);
16582  // At this point all of the data is stored at the bottom of the
16583  // register. We now need to save it to mem.
16584
16585  // Find the largest store unit
16586  MVT StoreType = MVT::i8;
16587  for (MVT Tp : MVT::integer_valuetypes()) {
16588    if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
16589      StoreType = Tp;
16590  }
16591  // Didn't find a legal store type.
16592  if (!TLI.isTypeLegal(StoreType))
16593    return SDValue();
16594
16595  // Bitcast the original vector into a vector of store-size units
16596  EVT StoreVecVT =
16597      EVT::getVectorVT(*DAG.getContext(), StoreType,
16598                       VT.getSizeInBits() / EVT(StoreType).getSizeInBits());
16599  assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
16600  SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
16601  SmallVector<SDValue, 8> Chains;
16602  SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL,
16603                                      TLI.getPointerTy(DAG.getDataLayout()));
16604  SDValue BasePtr = St->getBasePtr();
16605
16606  // Perform one or more big stores into memory.
16607  unsigned E = (ToEltSz * NumElems) / StoreType.getSizeInBits();
16608  for (unsigned I = 0; I < E; I++) {
16609    SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, StoreType,
16610                                 ShuffWide, DAG.getIntPtrConstant(I, DL));
16611    SDValue Ch =
16612        DAG.getStore(St->getChain(), DL, SubVec, BasePtr, St->getPointerInfo(),
16613                     St->getAlign(), St->getMemOperand()->getFlags());
16614    BasePtr =
16615        DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr, Increment);
16616    Chains.push_back(Ch);
16617  }
16618  return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
16619}
16620
16621// Try taking a single vector store from an fpround (which would otherwise turn
16622// into an expensive buildvector) and splitting it into a series of narrowing
16623// stores.
16624static SDValue PerformSplittingToNarrowingStores(StoreSDNode *St,
16625                                                 SelectionDAG &DAG) {
16626  if (!St->isSimple() || St->isTruncatingStore() || !St->isUnindexed())
16627    return SDValue();
16628  SDValue Trunc = St->getValue();
16629  if (Trunc->getOpcode() != ISD::FP_ROUND)
16630    return SDValue();
16631  EVT FromVT = Trunc->getOperand(0).getValueType();
16632  EVT ToVT = Trunc.getValueType();
16633  if (!ToVT.isVector())
16634    return SDValue();
16635  assert(FromVT.getVectorNumElements() == ToVT.getVectorNumElements());
16636  EVT ToEltVT = ToVT.getVectorElementType();
16637  EVT FromEltVT = FromVT.getVectorElementType();
16638
16639  if (FromEltVT != MVT::f32 || ToEltVT != MVT::f16)
16640    return SDValue();
16641
16642  unsigned NumElements = 4;
16643  if (FromVT.getVectorNumElements() % NumElements != 0)
16644    return SDValue();
16645
16646  // Test if the Trunc will be convertable to a VMOVN with a shuffle, and if so
16647  // use the VMOVN over splitting the store. We are looking for patterns of:
16648  // !rev: 0 N 1 N+1 2 N+2 ...
16649  //  rev: N 0 N+1 1 N+2 2 ...
16650  // The shuffle may either be a single source (in which case N = NumElts/2) or
16651  // two inputs extended with concat to the same size (in which case N =
16652  // NumElts).
16653  auto isVMOVNShuffle = [&](ShuffleVectorSDNode *SVN, bool Rev) {
16654    ArrayRef<int> M = SVN->getMask();
16655    unsigned NumElts = ToVT.getVectorNumElements();
16656    if (SVN->getOperand(1).isUndef())
16657      NumElts /= 2;
16658
16659    unsigned Off0 = Rev ? NumElts : 0;
16660    unsigned Off1 = Rev ? 0 : NumElts;
16661
16662    for (unsigned I = 0; I < NumElts; I += 2) {
16663      if (M[I] >= 0 && M[I] != (int)(Off0 + I / 2))
16664        return false;
16665      if (M[I + 1] >= 0 && M[I + 1] != (int)(Off1 + I / 2))
16666        return false;
16667    }
16668
16669    return true;
16670  };
16671
16672  if (auto *Shuffle = dyn_cast<ShuffleVectorSDNode>(Trunc.getOperand(0)))
16673    if (isVMOVNShuffle(Shuffle, false) || isVMOVNShuffle(Shuffle, true))
16674      return SDValue();
16675
16676  LLVMContext &C = *DAG.getContext();
16677  SDLoc DL(St);
16678  // Details about the old store
16679  SDValue Ch = St->getChain();
16680  SDValue BasePtr = St->getBasePtr();
16681  Align Alignment = St->getOriginalAlign();
16682  MachineMemOperand::Flags MMOFlags = St->getMemOperand()->getFlags();
16683  AAMDNodes AAInfo = St->getAAInfo();
16684
16685  // We split the store into slices of NumElements. fp16 trunc stores are vcvt
16686  // and then stored as truncating integer stores.
16687  EVT NewFromVT = EVT::getVectorVT(C, FromEltVT, NumElements);
16688  EVT NewToVT = EVT::getVectorVT(
16689      C, EVT::getIntegerVT(C, ToEltVT.getSizeInBits()), NumElements);
16690
16691  SmallVector<SDValue, 4> Stores;
16692  for (unsigned i = 0; i < FromVT.getVectorNumElements() / NumElements; i++) {
16693    unsigned NewOffset = i * NumElements * ToEltVT.getSizeInBits() / 8;
16694    SDValue NewPtr =
16695        DAG.getObjectPtrOffset(DL, BasePtr, TypeSize::getFixed(NewOffset));
16696
16697    SDValue Extract =
16698        DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, NewFromVT, Trunc.getOperand(0),
16699                    DAG.getConstant(i * NumElements, DL, MVT::i32));
16700
16701    SDValue FPTrunc =
16702        DAG.getNode(ARMISD::VCVTN, DL, MVT::v8f16, DAG.getUNDEF(MVT::v8f16),
16703                    Extract, DAG.getConstant(0, DL, MVT::i32));
16704    Extract = DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, MVT::v4i32, FPTrunc);
16705
16706    SDValue Store = DAG.getTruncStore(
16707        Ch, DL, Extract, NewPtr, St->getPointerInfo().getWithOffset(NewOffset),
16708        NewToVT, Alignment, MMOFlags, AAInfo);
16709    Stores.push_back(Store);
16710  }
16711  return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Stores);
16712}
16713
16714// Try taking a single vector store from an MVETRUNC (which would otherwise turn
16715// into an expensive buildvector) and splitting it into a series of narrowing
16716// stores.
16717static SDValue PerformSplittingMVETruncToNarrowingStores(StoreSDNode *St,
16718                                                         SelectionDAG &DAG) {
16719  if (!St->isSimple() || St->isTruncatingStore() || !St->isUnindexed())
16720    return SDValue();
16721  SDValue Trunc = St->getValue();
16722  if (Trunc->getOpcode() != ARMISD::MVETRUNC)
16723    return SDValue();
16724  EVT FromVT = Trunc->getOperand(0).getValueType();
16725  EVT ToVT = Trunc.getValueType();
16726
16727  LLVMContext &C = *DAG.getContext();
16728  SDLoc DL(St);
16729  // Details about the old store
16730  SDValue Ch = St->getChain();
16731  SDValue BasePtr = St->getBasePtr();
16732  Align Alignment = St->getOriginalAlign();
16733  MachineMemOperand::Flags MMOFlags = St->getMemOperand()->getFlags();
16734  AAMDNodes AAInfo = St->getAAInfo();
16735
16736  EVT NewToVT = EVT::getVectorVT(C, ToVT.getVectorElementType(),
16737                                 FromVT.getVectorNumElements());
16738
16739  SmallVector<SDValue, 4> Stores;
16740  for (unsigned i = 0; i < Trunc.getNumOperands(); i++) {
16741    unsigned NewOffset =
16742        i * FromVT.getVectorNumElements() * ToVT.getScalarSizeInBits() / 8;
16743    SDValue NewPtr =
16744        DAG.getObjectPtrOffset(DL, BasePtr, TypeSize::getFixed(NewOffset));
16745
16746    SDValue Extract = Trunc.getOperand(i);
16747    SDValue Store = DAG.getTruncStore(
16748        Ch, DL, Extract, NewPtr, St->getPointerInfo().getWithOffset(NewOffset),
16749        NewToVT, Alignment, MMOFlags, AAInfo);
16750    Stores.push_back(Store);
16751  }
16752  return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Stores);
16753}
16754
16755// Given a floating point store from an extracted vector, with an integer
16756// VGETLANE that already exists, store the existing VGETLANEu directly. This can
16757// help reduce fp register pressure, doesn't require the fp extract and allows
16758// use of more integer post-inc stores not available with vstr.
16759static SDValue PerformExtractFpToIntStores(StoreSDNode *St, SelectionDAG &DAG) {
16760  if (!St->isSimple() || St->isTruncatingStore() || !St->isUnindexed())
16761    return SDValue();
16762  SDValue Extract = St->getValue();
16763  EVT VT = Extract.getValueType();
16764  // For now only uses f16. This may be useful for f32 too, but that will
16765  // be bitcast(extract), not the VGETLANEu we currently check here.
16766  if (VT != MVT::f16 || Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
16767    return SDValue();
16768
16769  SDNode *GetLane =
16770      DAG.getNodeIfExists(ARMISD::VGETLANEu, DAG.getVTList(MVT::i32),
16771                          {Extract.getOperand(0), Extract.getOperand(1)});
16772  if (!GetLane)
16773    return SDValue();
16774
16775  LLVMContext &C = *DAG.getContext();
16776  SDLoc DL(St);
16777  // Create a new integer store to replace the existing floating point version.
16778  SDValue Ch = St->getChain();
16779  SDValue BasePtr = St->getBasePtr();
16780  Align Alignment = St->getOriginalAlign();
16781  MachineMemOperand::Flags MMOFlags = St->getMemOperand()->getFlags();
16782  AAMDNodes AAInfo = St->getAAInfo();
16783  EVT NewToVT = EVT::getIntegerVT(C, VT.getSizeInBits());
16784  SDValue Store = DAG.getTruncStore(Ch, DL, SDValue(GetLane, 0), BasePtr,
16785                                    St->getPointerInfo(), NewToVT, Alignment,
16786                                    MMOFlags, AAInfo);
16787
16788  return Store;
16789}
16790
16791/// PerformSTORECombine - Target-specific dag combine xforms for
16792/// ISD::STORE.
16793static SDValue PerformSTORECombine(SDNode *N,
16794                                   TargetLowering::DAGCombinerInfo &DCI,
16795                                   const ARMSubtarget *Subtarget) {
16796  StoreSDNode *St = cast<StoreSDNode>(N);
16797  if (St->isVolatile())
16798    return SDValue();
16799  SDValue StVal = St->getValue();
16800  EVT VT = StVal.getValueType();
16801
16802  if (Subtarget->hasNEON())
16803    if (SDValue Store = PerformTruncatingStoreCombine(St, DCI.DAG))
16804      return Store;
16805
16806  if (Subtarget->hasMVEIntegerOps()) {
16807    if (SDValue NewToken = PerformSplittingToNarrowingStores(St, DCI.DAG))
16808      return NewToken;
16809    if (SDValue NewChain = PerformExtractFpToIntStores(St, DCI.DAG))
16810      return NewChain;
16811    if (SDValue NewToken =
16812            PerformSplittingMVETruncToNarrowingStores(St, DCI.DAG))
16813      return NewToken;
16814  }
16815
16816  if (!ISD::isNormalStore(St))
16817    return SDValue();
16818
16819  // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
16820  // ARM stores of arguments in the same cache line.
16821  if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
16822      StVal.getNode()->hasOneUse()) {
16823    SelectionDAG  &DAG = DCI.DAG;
16824    bool isBigEndian = DAG.getDataLayout().isBigEndian();
16825    SDLoc DL(St);
16826    SDValue BasePtr = St->getBasePtr();
16827    SDValue NewST1 = DAG.getStore(
16828        St->getChain(), DL, StVal.getNode()->getOperand(isBigEndian ? 1 : 0),
16829        BasePtr, St->getPointerInfo(), St->getOriginalAlign(),
16830        St->getMemOperand()->getFlags());
16831
16832    SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
16833                                    DAG.getConstant(4, DL, MVT::i32));
16834    return DAG.getStore(NewST1.getValue(0), DL,
16835                        StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
16836                        OffsetPtr, St->getPointerInfo().getWithOffset(4),
16837                        St->getOriginalAlign(),
16838                        St->getMemOperand()->getFlags());
16839  }
16840
16841  if (StVal.getValueType() == MVT::i64 &&
16842      StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
16843
16844    // Bitcast an i64 store extracted from a vector to f64.
16845    // Otherwise, the i64 value will be legalized to a pair of i32 values.
16846    SelectionDAG &DAG = DCI.DAG;
16847    SDLoc dl(StVal);
16848    SDValue IntVec = StVal.getOperand(0);
16849    EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
16850                                   IntVec.getValueType().getVectorNumElements());
16851    SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
16852    SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
16853                                 Vec, StVal.getOperand(1));
16854    dl = SDLoc(N);
16855    SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
16856    // Make the DAGCombiner fold the bitcasts.
16857    DCI.AddToWorklist(Vec.getNode());
16858    DCI.AddToWorklist(ExtElt.getNode());
16859    DCI.AddToWorklist(V.getNode());
16860    return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
16861                        St->getPointerInfo(), St->getAlign(),
16862                        St->getMemOperand()->getFlags(), St->getAAInfo());
16863  }
16864
16865  // If this is a legal vector store, try to combine it into a VST1_UPD.
16866  if (Subtarget->hasNEON() && ISD::isNormalStore(N) && VT.isVector() &&
16867      DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
16868    return CombineBaseUpdate(N, DCI);
16869
16870  return SDValue();
16871}
16872
16873/// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
16874/// can replace combinations of VMUL and VCVT (floating-point to integer)
16875/// when the VMUL has a constant operand that is a power of 2.
16876///
16877/// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
16878///  vmul.f32        d16, d17, d16
16879///  vcvt.s32.f32    d16, d16
16880/// becomes:
16881///  vcvt.s32.f32    d16, d16, #3
16882static SDValue PerformVCVTCombine(SDNode *N, SelectionDAG &DAG,
16883                                  const ARMSubtarget *Subtarget) {
16884  if (!Subtarget->hasNEON())
16885    return SDValue();
16886
16887  SDValue Op = N->getOperand(0);
16888  if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
16889      Op.getOpcode() != ISD::FMUL)
16890    return SDValue();
16891
16892  SDValue ConstVec = Op->getOperand(1);
16893  if (!isa<BuildVectorSDNode>(ConstVec))
16894    return SDValue();
16895
16896  MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
16897  uint32_t FloatBits = FloatTy.getSizeInBits();
16898  MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
16899  uint32_t IntBits = IntTy.getSizeInBits();
16900  unsigned NumLanes = Op.getValueType().getVectorNumElements();
16901  if (FloatBits != 32 || IntBits > 32 || (NumLanes != 4 && NumLanes != 2)) {
16902    // These instructions only exist converting from f32 to i32. We can handle
16903    // smaller integers by generating an extra truncate, but larger ones would
16904    // be lossy. We also can't handle anything other than 2 or 4 lanes, since
16905    // these intructions only support v2i32/v4i32 types.
16906    return SDValue();
16907  }
16908
16909  BitVector UndefElements;
16910  BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
16911  int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33);
16912  if (C == -1 || C == 0 || C > 32)
16913    return SDValue();
16914
16915  SDLoc dl(N);
16916  bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
16917  unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
16918    Intrinsic::arm_neon_vcvtfp2fxu;
16919  SDValue FixConv = DAG.getNode(
16920      ISD::INTRINSIC_WO_CHAIN, dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
16921      DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), Op->getOperand(0),
16922      DAG.getConstant(C, dl, MVT::i32));
16923
16924  if (IntBits < FloatBits)
16925    FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv);
16926
16927  return FixConv;
16928}
16929
16930static SDValue PerformFAddVSelectCombine(SDNode *N, SelectionDAG &DAG,
16931                                         const ARMSubtarget *Subtarget) {
16932  if (!Subtarget->hasMVEFloatOps())
16933    return SDValue();
16934
16935  // Turn (fadd x, (vselect c, y, -0.0)) into (vselect c, (fadd x, y), x)
16936  // The second form can be more easily turned into a predicated vadd, and
16937  // possibly combined into a fma to become a predicated vfma.
16938  SDValue Op0 = N->getOperand(0);
16939  SDValue Op1 = N->getOperand(1);
16940  EVT VT = N->getValueType(0);
16941  SDLoc DL(N);
16942
16943  // The identity element for a fadd is -0.0 or +0.0 when the nsz flag is set,
16944  // which these VMOV's represent.
16945  auto isIdentitySplat = [&](SDValue Op, bool NSZ) {
16946    if (Op.getOpcode() != ISD::BITCAST ||
16947        Op.getOperand(0).getOpcode() != ARMISD::VMOVIMM)
16948      return false;
16949    uint64_t ImmVal = Op.getOperand(0).getConstantOperandVal(0);
16950    if (VT == MVT::v4f32 && (ImmVal == 1664 || (ImmVal == 0 && NSZ)))
16951      return true;
16952    if (VT == MVT::v8f16 && (ImmVal == 2688 || (ImmVal == 0 && NSZ)))
16953      return true;
16954    return false;
16955  };
16956
16957  if (Op0.getOpcode() == ISD::VSELECT && Op1.getOpcode() != ISD::VSELECT)
16958    std::swap(Op0, Op1);
16959
16960  if (Op1.getOpcode() != ISD::VSELECT)
16961    return SDValue();
16962
16963  SDNodeFlags FaddFlags = N->getFlags();
16964  bool NSZ = FaddFlags.hasNoSignedZeros();
16965  if (!isIdentitySplat(Op1.getOperand(2), NSZ))
16966    return SDValue();
16967
16968  SDValue FAdd =
16969      DAG.getNode(ISD::FADD, DL, VT, Op0, Op1.getOperand(1), FaddFlags);
16970  return DAG.getNode(ISD::VSELECT, DL, VT, Op1.getOperand(0), FAdd, Op0, FaddFlags);
16971}
16972
16973static SDValue PerformFADDVCMLACombine(SDNode *N, SelectionDAG &DAG) {
16974  SDValue LHS = N->getOperand(0);
16975  SDValue RHS = N->getOperand(1);
16976  EVT VT = N->getValueType(0);
16977  SDLoc DL(N);
16978
16979  if (!N->getFlags().hasAllowReassociation())
16980    return SDValue();
16981
16982  // Combine fadd(a, vcmla(b, c, d)) -> vcmla(fadd(a, b), b, c)
16983  auto ReassocComplex = [&](SDValue A, SDValue B) {
16984    if (A.getOpcode() != ISD::INTRINSIC_WO_CHAIN)
16985      return SDValue();
16986    unsigned Opc = A.getConstantOperandVal(0);
16987    if (Opc != Intrinsic::arm_mve_vcmlaq)
16988      return SDValue();
16989    SDValue VCMLA = DAG.getNode(
16990        ISD::INTRINSIC_WO_CHAIN, DL, VT, A.getOperand(0), A.getOperand(1),
16991        DAG.getNode(ISD::FADD, DL, VT, A.getOperand(2), B, N->getFlags()),
16992        A.getOperand(3), A.getOperand(4));
16993    VCMLA->setFlags(A->getFlags());
16994    return VCMLA;
16995  };
16996  if (SDValue R = ReassocComplex(LHS, RHS))
16997    return R;
16998  if (SDValue R = ReassocComplex(RHS, LHS))
16999    return R;
17000
17001  return SDValue();
17002}
17003
17004static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
17005                                  const ARMSubtarget *Subtarget) {
17006  if (SDValue S = PerformFAddVSelectCombine(N, DAG, Subtarget))
17007    return S;
17008  if (SDValue S = PerformFADDVCMLACombine(N, DAG))
17009    return S;
17010  return SDValue();
17011}
17012
17013/// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
17014/// can replace combinations of VCVT (integer to floating-point) and VDIV
17015/// when the VDIV has a constant operand that is a power of 2.
17016///
17017/// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
17018///  vcvt.f32.s32    d16, d16
17019///  vdiv.f32        d16, d17, d16
17020/// becomes:
17021///  vcvt.f32.s32    d16, d16, #3
17022static SDValue PerformVDIVCombine(SDNode *N, SelectionDAG &DAG,
17023                                  const ARMSubtarget *Subtarget) {
17024  if (!Subtarget->hasNEON())
17025    return SDValue();
17026
17027  SDValue Op = N->getOperand(0);
17028  unsigned OpOpcode = Op.getNode()->getOpcode();
17029  if (!N->getValueType(0).isVector() || !N->getValueType(0).isSimple() ||
17030      (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
17031    return SDValue();
17032
17033  SDValue ConstVec = N->getOperand(1);
17034  if (!isa<BuildVectorSDNode>(ConstVec))
17035    return SDValue();
17036
17037  MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
17038  uint32_t FloatBits = FloatTy.getSizeInBits();
17039  MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
17040  uint32_t IntBits = IntTy.getSizeInBits();
17041  unsigned NumLanes = Op.getValueType().getVectorNumElements();
17042  if (FloatBits != 32 || IntBits > 32 || (NumLanes != 4 && NumLanes != 2)) {
17043    // These instructions only exist converting from i32 to f32. We can handle
17044    // smaller integers by generating an extra extend, but larger ones would
17045    // be lossy. We also can't handle anything other than 2 or 4 lanes, since
17046    // these intructions only support v2i32/v4i32 types.
17047    return SDValue();
17048  }
17049
17050  BitVector UndefElements;
17051  BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
17052  int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33);
17053  if (C == -1 || C == 0 || C > 32)
17054    return SDValue();
17055
17056  SDLoc dl(N);
17057  bool isSigned = OpOpcode == ISD::SINT_TO_FP;
17058  SDValue ConvInput = Op.getOperand(0);
17059  if (IntBits < FloatBits)
17060    ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
17061                            dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
17062                            ConvInput);
17063
17064  unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
17065    Intrinsic::arm_neon_vcvtfxu2fp;
17066  return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
17067                     Op.getValueType(),
17068                     DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
17069                     ConvInput, DAG.getConstant(C, dl, MVT::i32));
17070}
17071
17072static SDValue PerformVECREDUCE_ADDCombine(SDNode *N, SelectionDAG &DAG,
17073                                           const ARMSubtarget *ST) {
17074  if (!ST->hasMVEIntegerOps())
17075    return SDValue();
17076
17077  assert(N->getOpcode() == ISD::VECREDUCE_ADD);
17078  EVT ResVT = N->getValueType(0);
17079  SDValue N0 = N->getOperand(0);
17080  SDLoc dl(N);
17081
17082  // Try to turn vecreduce_add(add(x, y)) into vecreduce(x) + vecreduce(y)
17083  if (ResVT == MVT::i32 && N0.getOpcode() == ISD::ADD &&
17084      (N0.getValueType() == MVT::v4i32 || N0.getValueType() == MVT::v8i16 ||
17085       N0.getValueType() == MVT::v16i8)) {
17086    SDValue Red0 = DAG.getNode(ISD::VECREDUCE_ADD, dl, ResVT, N0.getOperand(0));
17087    SDValue Red1 = DAG.getNode(ISD::VECREDUCE_ADD, dl, ResVT, N0.getOperand(1));
17088    return DAG.getNode(ISD::ADD, dl, ResVT, Red0, Red1);
17089  }
17090
17091  // We are looking for something that will have illegal types if left alone,
17092  // but that we can convert to a single instruction under MVE. For example
17093  // vecreduce_add(sext(A, v8i32)) => VADDV.s16 A
17094  // or
17095  // vecreduce_add(mul(zext(A, v16i32), zext(B, v16i32))) => VMLADAV.u8 A, B
17096
17097  // The legal cases are:
17098  //   VADDV u/s 8/16/32
17099  //   VMLAV u/s 8/16/32
17100  //   VADDLV u/s 32
17101  //   VMLALV u/s 16/32
17102
17103  // If the input vector is smaller than legal (v4i8/v4i16 for example) we can
17104  // extend it and use v4i32 instead.
17105  auto ExtTypeMatches = [](SDValue A, ArrayRef<MVT> ExtTypes) {
17106    EVT AVT = A.getValueType();
17107    return any_of(ExtTypes, [&](MVT Ty) {
17108      return AVT.getVectorNumElements() == Ty.getVectorNumElements() &&
17109             AVT.bitsLE(Ty);
17110    });
17111  };
17112  auto ExtendIfNeeded = [&](SDValue A, unsigned ExtendCode) {
17113    EVT AVT = A.getValueType();
17114    if (!AVT.is128BitVector())
17115      A = DAG.getNode(ExtendCode, dl,
17116                      AVT.changeVectorElementType(MVT::getIntegerVT(
17117                          128 / AVT.getVectorMinNumElements())),
17118                      A);
17119    return A;
17120  };
17121  auto IsVADDV = [&](MVT RetTy, unsigned ExtendCode, ArrayRef<MVT> ExtTypes) {
17122    if (ResVT != RetTy || N0->getOpcode() != ExtendCode)
17123      return SDValue();
17124    SDValue A = N0->getOperand(0);
17125    if (ExtTypeMatches(A, ExtTypes))
17126      return ExtendIfNeeded(A, ExtendCode);
17127    return SDValue();
17128  };
17129  auto IsPredVADDV = [&](MVT RetTy, unsigned ExtendCode,
17130                         ArrayRef<MVT> ExtTypes, SDValue &Mask) {
17131    if (ResVT != RetTy || N0->getOpcode() != ISD::VSELECT ||
17132        !ISD::isBuildVectorAllZeros(N0->getOperand(2).getNode()))
17133      return SDValue();
17134    Mask = N0->getOperand(0);
17135    SDValue Ext = N0->getOperand(1);
17136    if (Ext->getOpcode() != ExtendCode)
17137      return SDValue();
17138    SDValue A = Ext->getOperand(0);
17139    if (ExtTypeMatches(A, ExtTypes))
17140      return ExtendIfNeeded(A, ExtendCode);
17141    return SDValue();
17142  };
17143  auto IsVMLAV = [&](MVT RetTy, unsigned ExtendCode, ArrayRef<MVT> ExtTypes,
17144                     SDValue &A, SDValue &B) {
17145    // For a vmla we are trying to match a larger pattern:
17146    // ExtA = sext/zext A
17147    // ExtB = sext/zext B
17148    // Mul = mul ExtA, ExtB
17149    // vecreduce.add Mul
17150    // There might also be en extra extend between the mul and the addreduce, so
17151    // long as the bitwidth is high enough to make them equivalent (for example
17152    // original v8i16 might be mul at v8i32 and the reduce happens at v8i64).
17153    if (ResVT != RetTy)
17154      return false;
17155    SDValue Mul = N0;
17156    if (Mul->getOpcode() == ExtendCode &&
17157        Mul->getOperand(0).getScalarValueSizeInBits() * 2 >=
17158            ResVT.getScalarSizeInBits())
17159      Mul = Mul->getOperand(0);
17160    if (Mul->getOpcode() != ISD::MUL)
17161      return false;
17162    SDValue ExtA = Mul->getOperand(0);
17163    SDValue ExtB = Mul->getOperand(1);
17164    if (ExtA->getOpcode() != ExtendCode || ExtB->getOpcode() != ExtendCode)
17165      return false;
17166    A = ExtA->getOperand(0);
17167    B = ExtB->getOperand(0);
17168    if (ExtTypeMatches(A, ExtTypes) && ExtTypeMatches(B, ExtTypes)) {
17169      A = ExtendIfNeeded(A, ExtendCode);
17170      B = ExtendIfNeeded(B, ExtendCode);
17171      return true;
17172    }
17173    return false;
17174  };
17175  auto IsPredVMLAV = [&](MVT RetTy, unsigned ExtendCode, ArrayRef<MVT> ExtTypes,
17176                     SDValue &A, SDValue &B, SDValue &Mask) {
17177    // Same as the pattern above with a select for the zero predicated lanes
17178    // ExtA = sext/zext A
17179    // ExtB = sext/zext B
17180    // Mul = mul ExtA, ExtB
17181    // N0 = select Mask, Mul, 0
17182    // vecreduce.add N0
17183    if (ResVT != RetTy || N0->getOpcode() != ISD::VSELECT ||
17184        !ISD::isBuildVectorAllZeros(N0->getOperand(2).getNode()))
17185      return false;
17186    Mask = N0->getOperand(0);
17187    SDValue Mul = N0->getOperand(1);
17188    if (Mul->getOpcode() == ExtendCode &&
17189        Mul->getOperand(0).getScalarValueSizeInBits() * 2 >=
17190            ResVT.getScalarSizeInBits())
17191      Mul = Mul->getOperand(0);
17192    if (Mul->getOpcode() != ISD::MUL)
17193      return false;
17194    SDValue ExtA = Mul->getOperand(0);
17195    SDValue ExtB = Mul->getOperand(1);
17196    if (ExtA->getOpcode() != ExtendCode || ExtB->getOpcode() != ExtendCode)
17197      return false;
17198    A = ExtA->getOperand(0);
17199    B = ExtB->getOperand(0);
17200    if (ExtTypeMatches(A, ExtTypes) && ExtTypeMatches(B, ExtTypes)) {
17201      A = ExtendIfNeeded(A, ExtendCode);
17202      B = ExtendIfNeeded(B, ExtendCode);
17203      return true;
17204    }
17205    return false;
17206  };
17207  auto Create64bitNode = [&](unsigned Opcode, ArrayRef<SDValue> Ops) {
17208    // Split illegal MVT::v16i8->i64 vector reductions into two legal v8i16->i64
17209    // reductions. The operands are extended with MVEEXT, but as they are
17210    // reductions the lane orders do not matter. MVEEXT may be combined with
17211    // loads to produce two extending loads, or else they will be expanded to
17212    // VREV/VMOVL.
17213    EVT VT = Ops[0].getValueType();
17214    if (VT == MVT::v16i8) {
17215      assert((Opcode == ARMISD::VMLALVs || Opcode == ARMISD::VMLALVu) &&
17216             "Unexpected illegal long reduction opcode");
17217      bool IsUnsigned = Opcode == ARMISD::VMLALVu;
17218
17219      SDValue Ext0 =
17220          DAG.getNode(IsUnsigned ? ARMISD::MVEZEXT : ARMISD::MVESEXT, dl,
17221                      DAG.getVTList(MVT::v8i16, MVT::v8i16), Ops[0]);
17222      SDValue Ext1 =
17223          DAG.getNode(IsUnsigned ? ARMISD::MVEZEXT : ARMISD::MVESEXT, dl,
17224                      DAG.getVTList(MVT::v8i16, MVT::v8i16), Ops[1]);
17225
17226      SDValue MLA0 = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
17227                                 Ext0, Ext1);
17228      SDValue MLA1 =
17229          DAG.getNode(IsUnsigned ? ARMISD::VMLALVAu : ARMISD::VMLALVAs, dl,
17230                      DAG.getVTList(MVT::i32, MVT::i32), MLA0, MLA0.getValue(1),
17231                      Ext0.getValue(1), Ext1.getValue(1));
17232      return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, MLA1, MLA1.getValue(1));
17233    }
17234    SDValue Node = DAG.getNode(Opcode, dl, {MVT::i32, MVT::i32}, Ops);
17235    return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Node,
17236                       SDValue(Node.getNode(), 1));
17237  };
17238
17239  SDValue A, B;
17240  SDValue Mask;
17241  if (IsVMLAV(MVT::i32, ISD::SIGN_EXTEND, {MVT::v8i16, MVT::v16i8}, A, B))
17242    return DAG.getNode(ARMISD::VMLAVs, dl, ResVT, A, B);
17243  if (IsVMLAV(MVT::i32, ISD::ZERO_EXTEND, {MVT::v8i16, MVT::v16i8}, A, B))
17244    return DAG.getNode(ARMISD::VMLAVu, dl, ResVT, A, B);
17245  if (IsVMLAV(MVT::i64, ISD::SIGN_EXTEND, {MVT::v16i8, MVT::v8i16, MVT::v4i32},
17246              A, B))
17247    return Create64bitNode(ARMISD::VMLALVs, {A, B});
17248  if (IsVMLAV(MVT::i64, ISD::ZERO_EXTEND, {MVT::v16i8, MVT::v8i16, MVT::v4i32},
17249              A, B))
17250    return Create64bitNode(ARMISD::VMLALVu, {A, B});
17251  if (IsVMLAV(MVT::i16, ISD::SIGN_EXTEND, {MVT::v16i8}, A, B))
17252    return DAG.getNode(ISD::TRUNCATE, dl, ResVT,
17253                       DAG.getNode(ARMISD::VMLAVs, dl, MVT::i32, A, B));
17254  if (IsVMLAV(MVT::i16, ISD::ZERO_EXTEND, {MVT::v16i8}, A, B))
17255    return DAG.getNode(ISD::TRUNCATE, dl, ResVT,
17256                       DAG.getNode(ARMISD::VMLAVu, dl, MVT::i32, A, B));
17257
17258  if (IsPredVMLAV(MVT::i32, ISD::SIGN_EXTEND, {MVT::v8i16, MVT::v16i8}, A, B,
17259                  Mask))
17260    return DAG.getNode(ARMISD::VMLAVps, dl, ResVT, A, B, Mask);
17261  if (IsPredVMLAV(MVT::i32, ISD::ZERO_EXTEND, {MVT::v8i16, MVT::v16i8}, A, B,
17262                  Mask))
17263    return DAG.getNode(ARMISD::VMLAVpu, dl, ResVT, A, B, Mask);
17264  if (IsPredVMLAV(MVT::i64, ISD::SIGN_EXTEND, {MVT::v8i16, MVT::v4i32}, A, B,
17265                  Mask))
17266    return Create64bitNode(ARMISD::VMLALVps, {A, B, Mask});
17267  if (IsPredVMLAV(MVT::i64, ISD::ZERO_EXTEND, {MVT::v8i16, MVT::v4i32}, A, B,
17268                  Mask))
17269    return Create64bitNode(ARMISD::VMLALVpu, {A, B, Mask});
17270  if (IsPredVMLAV(MVT::i16, ISD::SIGN_EXTEND, {MVT::v16i8}, A, B, Mask))
17271    return DAG.getNode(ISD::TRUNCATE, dl, ResVT,
17272                       DAG.getNode(ARMISD::VMLAVps, dl, MVT::i32, A, B, Mask));
17273  if (IsPredVMLAV(MVT::i16, ISD::ZERO_EXTEND, {MVT::v16i8}, A, B, Mask))
17274    return DAG.getNode(ISD::TRUNCATE, dl, ResVT,
17275                       DAG.getNode(ARMISD::VMLAVpu, dl, MVT::i32, A, B, Mask));
17276
17277  if (SDValue A = IsVADDV(MVT::i32, ISD::SIGN_EXTEND, {MVT::v8i16, MVT::v16i8}))
17278    return DAG.getNode(ARMISD::VADDVs, dl, ResVT, A);
17279  if (SDValue A = IsVADDV(MVT::i32, ISD::ZERO_EXTEND, {MVT::v8i16, MVT::v16i8}))
17280    return DAG.getNode(ARMISD::VADDVu, dl, ResVT, A);
17281  if (SDValue A = IsVADDV(MVT::i64, ISD::SIGN_EXTEND, {MVT::v4i32}))
17282    return Create64bitNode(ARMISD::VADDLVs, {A});
17283  if (SDValue A = IsVADDV(MVT::i64, ISD::ZERO_EXTEND, {MVT::v4i32}))
17284    return Create64bitNode(ARMISD::VADDLVu, {A});
17285  if (SDValue A = IsVADDV(MVT::i16, ISD::SIGN_EXTEND, {MVT::v16i8}))
17286    return DAG.getNode(ISD::TRUNCATE, dl, ResVT,
17287                       DAG.getNode(ARMISD::VADDVs, dl, MVT::i32, A));
17288  if (SDValue A = IsVADDV(MVT::i16, ISD::ZERO_EXTEND, {MVT::v16i8}))
17289    return DAG.getNode(ISD::TRUNCATE, dl, ResVT,
17290                       DAG.getNode(ARMISD::VADDVu, dl, MVT::i32, A));
17291
17292  if (SDValue A = IsPredVADDV(MVT::i32, ISD::SIGN_EXTEND, {MVT::v8i16, MVT::v16i8}, Mask))
17293    return DAG.getNode(ARMISD::VADDVps, dl, ResVT, A, Mask);
17294  if (SDValue A = IsPredVADDV(MVT::i32, ISD::ZERO_EXTEND, {MVT::v8i16, MVT::v16i8}, Mask))
17295    return DAG.getNode(ARMISD::VADDVpu, dl, ResVT, A, Mask);
17296  if (SDValue A = IsPredVADDV(MVT::i64, ISD::SIGN_EXTEND, {MVT::v4i32}, Mask))
17297    return Create64bitNode(ARMISD::VADDLVps, {A, Mask});
17298  if (SDValue A = IsPredVADDV(MVT::i64, ISD::ZERO_EXTEND, {MVT::v4i32}, Mask))
17299    return Create64bitNode(ARMISD::VADDLVpu, {A, Mask});
17300  if (SDValue A = IsPredVADDV(MVT::i16, ISD::SIGN_EXTEND, {MVT::v16i8}, Mask))
17301    return DAG.getNode(ISD::TRUNCATE, dl, ResVT,
17302                       DAG.getNode(ARMISD::VADDVps, dl, MVT::i32, A, Mask));
17303  if (SDValue A = IsPredVADDV(MVT::i16, ISD::ZERO_EXTEND, {MVT::v16i8}, Mask))
17304    return DAG.getNode(ISD::TRUNCATE, dl, ResVT,
17305                       DAG.getNode(ARMISD::VADDVpu, dl, MVT::i32, A, Mask));
17306
17307  // Some complications. We can get a case where the two inputs of the mul are
17308  // the same, then the output sext will have been helpfully converted to a
17309  // zext. Turn it back.
17310  SDValue Op = N0;
17311  if (Op->getOpcode() == ISD::VSELECT)
17312    Op = Op->getOperand(1);
17313  if (Op->getOpcode() == ISD::ZERO_EXTEND &&
17314      Op->getOperand(0)->getOpcode() == ISD::MUL) {
17315    SDValue Mul = Op->getOperand(0);
17316    if (Mul->getOperand(0) == Mul->getOperand(1) &&
17317        Mul->getOperand(0)->getOpcode() == ISD::SIGN_EXTEND) {
17318      SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND, dl, N0->getValueType(0), Mul);
17319      if (Op != N0)
17320        Ext = DAG.getNode(ISD::VSELECT, dl, N0->getValueType(0),
17321                          N0->getOperand(0), Ext, N0->getOperand(2));
17322      return DAG.getNode(ISD::VECREDUCE_ADD, dl, ResVT, Ext);
17323    }
17324  }
17325
17326  return SDValue();
17327}
17328
17329// Looks for vaddv(shuffle) or vmlav(shuffle, shuffle), with a shuffle where all
17330// the lanes are used. Due to the reduction being commutative the shuffle can be
17331// removed.
17332static SDValue PerformReduceShuffleCombine(SDNode *N, SelectionDAG &DAG) {
17333  unsigned VecOp = N->getOperand(0).getValueType().isVector() ? 0 : 2;
17334  auto *Shuf = dyn_cast<ShuffleVectorSDNode>(N->getOperand(VecOp));
17335  if (!Shuf || !Shuf->getOperand(1).isUndef())
17336    return SDValue();
17337
17338  // Check all elements are used once in the mask.
17339  ArrayRef<int> Mask = Shuf->getMask();
17340  APInt SetElts(Mask.size(), 0);
17341  for (int E : Mask) {
17342    if (E < 0 || E >= (int)Mask.size())
17343      return SDValue();
17344    SetElts.setBit(E);
17345  }
17346  if (!SetElts.isAllOnes())
17347    return SDValue();
17348
17349  if (N->getNumOperands() != VecOp + 1) {
17350    auto *Shuf2 = dyn_cast<ShuffleVectorSDNode>(N->getOperand(VecOp + 1));
17351    if (!Shuf2 || !Shuf2->getOperand(1).isUndef() || Shuf2->getMask() != Mask)
17352      return SDValue();
17353  }
17354
17355  SmallVector<SDValue> Ops;
17356  for (SDValue Op : N->ops()) {
17357    if (Op.getValueType().isVector())
17358      Ops.push_back(Op.getOperand(0));
17359    else
17360      Ops.push_back(Op);
17361  }
17362  return DAG.getNode(N->getOpcode(), SDLoc(N), N->getVTList(), Ops);
17363}
17364
17365static SDValue PerformVMOVNCombine(SDNode *N,
17366                                   TargetLowering::DAGCombinerInfo &DCI) {
17367  SDValue Op0 = N->getOperand(0);
17368  SDValue Op1 = N->getOperand(1);
17369  unsigned IsTop = N->getConstantOperandVal(2);
17370
17371  // VMOVNT a undef -> a
17372  // VMOVNB a undef -> a
17373  // VMOVNB undef a -> a
17374  if (Op1->isUndef())
17375    return Op0;
17376  if (Op0->isUndef() && !IsTop)
17377    return Op1;
17378
17379  // VMOVNt(c, VQMOVNb(a, b)) => VQMOVNt(c, b)
17380  // VMOVNb(c, VQMOVNb(a, b)) => VQMOVNb(c, b)
17381  if ((Op1->getOpcode() == ARMISD::VQMOVNs ||
17382       Op1->getOpcode() == ARMISD::VQMOVNu) &&
17383      Op1->getConstantOperandVal(2) == 0)
17384    return DCI.DAG.getNode(Op1->getOpcode(), SDLoc(Op1), N->getValueType(0),
17385                           Op0, Op1->getOperand(1), N->getOperand(2));
17386
17387  // Only the bottom lanes from Qm (Op1) and either the top or bottom lanes from
17388  // Qd (Op0) are demanded from a VMOVN, depending on whether we are inserting
17389  // into the top or bottom lanes.
17390  unsigned NumElts = N->getValueType(0).getVectorNumElements();
17391  APInt Op1DemandedElts = APInt::getSplat(NumElts, APInt::getLowBitsSet(2, 1));
17392  APInt Op0DemandedElts =
17393      IsTop ? Op1DemandedElts
17394            : APInt::getSplat(NumElts, APInt::getHighBitsSet(2, 1));
17395
17396  const TargetLowering &TLI = DCI.DAG.getTargetLoweringInfo();
17397  if (TLI.SimplifyDemandedVectorElts(Op0, Op0DemandedElts, DCI))
17398    return SDValue(N, 0);
17399  if (TLI.SimplifyDemandedVectorElts(Op1, Op1DemandedElts, DCI))
17400    return SDValue(N, 0);
17401
17402  return SDValue();
17403}
17404
17405static SDValue PerformVQMOVNCombine(SDNode *N,
17406                                    TargetLowering::DAGCombinerInfo &DCI) {
17407  SDValue Op0 = N->getOperand(0);
17408  unsigned IsTop = N->getConstantOperandVal(2);
17409
17410  unsigned NumElts = N->getValueType(0).getVectorNumElements();
17411  APInt Op0DemandedElts =
17412      APInt::getSplat(NumElts, IsTop ? APInt::getLowBitsSet(2, 1)
17413                                     : APInt::getHighBitsSet(2, 1));
17414
17415  const TargetLowering &TLI = DCI.DAG.getTargetLoweringInfo();
17416  if (TLI.SimplifyDemandedVectorElts(Op0, Op0DemandedElts, DCI))
17417    return SDValue(N, 0);
17418  return SDValue();
17419}
17420
17421static SDValue PerformVQDMULHCombine(SDNode *N,
17422                                     TargetLowering::DAGCombinerInfo &DCI) {
17423  EVT VT = N->getValueType(0);
17424  SDValue LHS = N->getOperand(0);
17425  SDValue RHS = N->getOperand(1);
17426
17427  auto *Shuf0 = dyn_cast<ShuffleVectorSDNode>(LHS);
17428  auto *Shuf1 = dyn_cast<ShuffleVectorSDNode>(RHS);
17429  // Turn VQDMULH(shuffle, shuffle) -> shuffle(VQDMULH)
17430  if (Shuf0 && Shuf1 && Shuf0->getMask().equals(Shuf1->getMask()) &&
17431      LHS.getOperand(1).isUndef() && RHS.getOperand(1).isUndef() &&
17432      (LHS.hasOneUse() || RHS.hasOneUse() || LHS == RHS)) {
17433    SDLoc DL(N);
17434    SDValue NewBinOp = DCI.DAG.getNode(N->getOpcode(), DL, VT,
17435                                       LHS.getOperand(0), RHS.getOperand(0));
17436    SDValue UndefV = LHS.getOperand(1);
17437    return DCI.DAG.getVectorShuffle(VT, DL, NewBinOp, UndefV, Shuf0->getMask());
17438  }
17439  return SDValue();
17440}
17441
17442static SDValue PerformLongShiftCombine(SDNode *N, SelectionDAG &DAG) {
17443  SDLoc DL(N);
17444  SDValue Op0 = N->getOperand(0);
17445  SDValue Op1 = N->getOperand(1);
17446
17447  // Turn X << -C -> X >> C and viceversa. The negative shifts can come up from
17448  // uses of the intrinsics.
17449  if (auto C = dyn_cast<ConstantSDNode>(N->getOperand(2))) {
17450    int ShiftAmt = C->getSExtValue();
17451    if (ShiftAmt == 0) {
17452      SDValue Merge = DAG.getMergeValues({Op0, Op1}, DL);
17453      DAG.ReplaceAllUsesWith(N, Merge.getNode());
17454      return SDValue();
17455    }
17456
17457    if (ShiftAmt >= -32 && ShiftAmt < 0) {
17458      unsigned NewOpcode =
17459          N->getOpcode() == ARMISD::LSLL ? ARMISD::LSRL : ARMISD::LSLL;
17460      SDValue NewShift = DAG.getNode(NewOpcode, DL, N->getVTList(), Op0, Op1,
17461                                     DAG.getConstant(-ShiftAmt, DL, MVT::i32));
17462      DAG.ReplaceAllUsesWith(N, NewShift.getNode());
17463      return NewShift;
17464    }
17465  }
17466
17467  return SDValue();
17468}
17469
17470/// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
17471SDValue ARMTargetLowering::PerformIntrinsicCombine(SDNode *N,
17472                                                   DAGCombinerInfo &DCI) const {
17473  SelectionDAG &DAG = DCI.DAG;
17474  unsigned IntNo = N->getConstantOperandVal(0);
17475  switch (IntNo) {
17476  default:
17477    // Don't do anything for most intrinsics.
17478    break;
17479
17480  // Vector shifts: check for immediate versions and lower them.
17481  // Note: This is done during DAG combining instead of DAG legalizing because
17482  // the build_vectors for 64-bit vector element shift counts are generally
17483  // not legal, and it is hard to see their values after they get legalized to
17484  // loads from a constant pool.
17485  case Intrinsic::arm_neon_vshifts:
17486  case Intrinsic::arm_neon_vshiftu:
17487  case Intrinsic::arm_neon_vrshifts:
17488  case Intrinsic::arm_neon_vrshiftu:
17489  case Intrinsic::arm_neon_vrshiftn:
17490  case Intrinsic::arm_neon_vqshifts:
17491  case Intrinsic::arm_neon_vqshiftu:
17492  case Intrinsic::arm_neon_vqshiftsu:
17493  case Intrinsic::arm_neon_vqshiftns:
17494  case Intrinsic::arm_neon_vqshiftnu:
17495  case Intrinsic::arm_neon_vqshiftnsu:
17496  case Intrinsic::arm_neon_vqrshiftns:
17497  case Intrinsic::arm_neon_vqrshiftnu:
17498  case Intrinsic::arm_neon_vqrshiftnsu: {
17499    EVT VT = N->getOperand(1).getValueType();
17500    int64_t Cnt;
17501    unsigned VShiftOpc = 0;
17502
17503    switch (IntNo) {
17504    case Intrinsic::arm_neon_vshifts:
17505    case Intrinsic::arm_neon_vshiftu:
17506      if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
17507        VShiftOpc = ARMISD::VSHLIMM;
17508        break;
17509      }
17510      if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
17511        VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ? ARMISD::VSHRsIMM
17512                                                          : ARMISD::VSHRuIMM);
17513        break;
17514      }
17515      return SDValue();
17516
17517    case Intrinsic::arm_neon_vrshifts:
17518    case Intrinsic::arm_neon_vrshiftu:
17519      if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
17520        break;
17521      return SDValue();
17522
17523    case Intrinsic::arm_neon_vqshifts:
17524    case Intrinsic::arm_neon_vqshiftu:
17525      if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
17526        break;
17527      return SDValue();
17528
17529    case Intrinsic::arm_neon_vqshiftsu:
17530      if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
17531        break;
17532      llvm_unreachable("invalid shift count for vqshlu intrinsic");
17533
17534    case Intrinsic::arm_neon_vrshiftn:
17535    case Intrinsic::arm_neon_vqshiftns:
17536    case Intrinsic::arm_neon_vqshiftnu:
17537    case Intrinsic::arm_neon_vqshiftnsu:
17538    case Intrinsic::arm_neon_vqrshiftns:
17539    case Intrinsic::arm_neon_vqrshiftnu:
17540    case Intrinsic::arm_neon_vqrshiftnsu:
17541      // Narrowing shifts require an immediate right shift.
17542      if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
17543        break;
17544      llvm_unreachable("invalid shift count for narrowing vector shift "
17545                       "intrinsic");
17546
17547    default:
17548      llvm_unreachable("unhandled vector shift");
17549    }
17550
17551    switch (IntNo) {
17552    case Intrinsic::arm_neon_vshifts:
17553    case Intrinsic::arm_neon_vshiftu:
17554      // Opcode already set above.
17555      break;
17556    case Intrinsic::arm_neon_vrshifts:
17557      VShiftOpc = ARMISD::VRSHRsIMM;
17558      break;
17559    case Intrinsic::arm_neon_vrshiftu:
17560      VShiftOpc = ARMISD::VRSHRuIMM;
17561      break;
17562    case Intrinsic::arm_neon_vrshiftn:
17563      VShiftOpc = ARMISD::VRSHRNIMM;
17564      break;
17565    case Intrinsic::arm_neon_vqshifts:
17566      VShiftOpc = ARMISD::VQSHLsIMM;
17567      break;
17568    case Intrinsic::arm_neon_vqshiftu:
17569      VShiftOpc = ARMISD::VQSHLuIMM;
17570      break;
17571    case Intrinsic::arm_neon_vqshiftsu:
17572      VShiftOpc = ARMISD::VQSHLsuIMM;
17573      break;
17574    case Intrinsic::arm_neon_vqshiftns:
17575      VShiftOpc = ARMISD::VQSHRNsIMM;
17576      break;
17577    case Intrinsic::arm_neon_vqshiftnu:
17578      VShiftOpc = ARMISD::VQSHRNuIMM;
17579      break;
17580    case Intrinsic::arm_neon_vqshiftnsu:
17581      VShiftOpc = ARMISD::VQSHRNsuIMM;
17582      break;
17583    case Intrinsic::arm_neon_vqrshiftns:
17584      VShiftOpc = ARMISD::VQRSHRNsIMM;
17585      break;
17586    case Intrinsic::arm_neon_vqrshiftnu:
17587      VShiftOpc = ARMISD::VQRSHRNuIMM;
17588      break;
17589    case Intrinsic::arm_neon_vqrshiftnsu:
17590      VShiftOpc = ARMISD::VQRSHRNsuIMM;
17591      break;
17592    }
17593
17594    SDLoc dl(N);
17595    return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
17596                       N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32));
17597  }
17598
17599  case Intrinsic::arm_neon_vshiftins: {
17600    EVT VT = N->getOperand(1).getValueType();
17601    int64_t Cnt;
17602    unsigned VShiftOpc = 0;
17603
17604    if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
17605      VShiftOpc = ARMISD::VSLIIMM;
17606    else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
17607      VShiftOpc = ARMISD::VSRIIMM;
17608    else {
17609      llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
17610    }
17611
17612    SDLoc dl(N);
17613    return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
17614                       N->getOperand(1), N->getOperand(2),
17615                       DAG.getConstant(Cnt, dl, MVT::i32));
17616  }
17617
17618  case Intrinsic::arm_neon_vqrshifts:
17619  case Intrinsic::arm_neon_vqrshiftu:
17620    // No immediate versions of these to check for.
17621    break;
17622
17623  case Intrinsic::arm_mve_vqdmlah:
17624  case Intrinsic::arm_mve_vqdmlash:
17625  case Intrinsic::arm_mve_vqrdmlah:
17626  case Intrinsic::arm_mve_vqrdmlash:
17627  case Intrinsic::arm_mve_vmla_n_predicated:
17628  case Intrinsic::arm_mve_vmlas_n_predicated:
17629  case Intrinsic::arm_mve_vqdmlah_predicated:
17630  case Intrinsic::arm_mve_vqdmlash_predicated:
17631  case Intrinsic::arm_mve_vqrdmlah_predicated:
17632  case Intrinsic::arm_mve_vqrdmlash_predicated: {
17633    // These intrinsics all take an i32 scalar operand which is narrowed to the
17634    // size of a single lane of the vector type they return. So we don't need
17635    // any bits of that operand above that point, which allows us to eliminate
17636    // uxth/sxth.
17637    unsigned BitWidth = N->getValueType(0).getScalarSizeInBits();
17638    APInt DemandedMask = APInt::getLowBitsSet(32, BitWidth);
17639    if (SimplifyDemandedBits(N->getOperand(3), DemandedMask, DCI))
17640      return SDValue();
17641    break;
17642  }
17643
17644  case Intrinsic::arm_mve_minv:
17645  case Intrinsic::arm_mve_maxv:
17646  case Intrinsic::arm_mve_minav:
17647  case Intrinsic::arm_mve_maxav:
17648  case Intrinsic::arm_mve_minv_predicated:
17649  case Intrinsic::arm_mve_maxv_predicated:
17650  case Intrinsic::arm_mve_minav_predicated:
17651  case Intrinsic::arm_mve_maxav_predicated: {
17652    // These intrinsics all take an i32 scalar operand which is narrowed to the
17653    // size of a single lane of the vector type they take as the other input.
17654    unsigned BitWidth = N->getOperand(2)->getValueType(0).getScalarSizeInBits();
17655    APInt DemandedMask = APInt::getLowBitsSet(32, BitWidth);
17656    if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))
17657      return SDValue();
17658    break;
17659  }
17660
17661  case Intrinsic::arm_mve_addv: {
17662    // Turn this intrinsic straight into the appropriate ARMISD::VADDV node,
17663    // which allow PerformADDVecReduce to turn it into VADDLV when possible.
17664    bool Unsigned = N->getConstantOperandVal(2);
17665    unsigned Opc = Unsigned ? ARMISD::VADDVu : ARMISD::VADDVs;
17666    return DAG.getNode(Opc, SDLoc(N), N->getVTList(), N->getOperand(1));
17667  }
17668
17669  case Intrinsic::arm_mve_addlv:
17670  case Intrinsic::arm_mve_addlv_predicated: {
17671    // Same for these, but ARMISD::VADDLV has to be followed by a BUILD_PAIR
17672    // which recombines the two outputs into an i64
17673    bool Unsigned = N->getConstantOperandVal(2);
17674    unsigned Opc = IntNo == Intrinsic::arm_mve_addlv ?
17675                    (Unsigned ? ARMISD::VADDLVu : ARMISD::VADDLVs) :
17676                    (Unsigned ? ARMISD::VADDLVpu : ARMISD::VADDLVps);
17677
17678    SmallVector<SDValue, 4> Ops;
17679    for (unsigned i = 1, e = N->getNumOperands(); i < e; i++)
17680      if (i != 2)                      // skip the unsigned flag
17681        Ops.push_back(N->getOperand(i));
17682
17683    SDLoc dl(N);
17684    SDValue val = DAG.getNode(Opc, dl, {MVT::i32, MVT::i32}, Ops);
17685    return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, val.getValue(0),
17686                       val.getValue(1));
17687  }
17688  }
17689
17690  return SDValue();
17691}
17692
17693/// PerformShiftCombine - Checks for immediate versions of vector shifts and
17694/// lowers them.  As with the vector shift intrinsics, this is done during DAG
17695/// combining instead of DAG legalizing because the build_vectors for 64-bit
17696/// vector element shift counts are generally not legal, and it is hard to see
17697/// their values after they get legalized to loads from a constant pool.
17698static SDValue PerformShiftCombine(SDNode *N,
17699                                   TargetLowering::DAGCombinerInfo &DCI,
17700                                   const ARMSubtarget *ST) {
17701  SelectionDAG &DAG = DCI.DAG;
17702  EVT VT = N->getValueType(0);
17703
17704  if (ST->isThumb1Only() && N->getOpcode() == ISD::SHL && VT == MVT::i32 &&
17705      N->getOperand(0)->getOpcode() == ISD::AND &&
17706      N->getOperand(0)->hasOneUse()) {
17707    if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
17708      return SDValue();
17709    // Look for the pattern (shl (and x, AndMask), ShiftAmt). This doesn't
17710    // usually show up because instcombine prefers to canonicalize it to
17711    // (and (shl x, ShiftAmt) (shl AndMask, ShiftAmt)), but the shift can come
17712    // out of GEP lowering in some cases.
17713    SDValue N0 = N->getOperand(0);
17714    ConstantSDNode *ShiftAmtNode = dyn_cast<ConstantSDNode>(N->getOperand(1));
17715    if (!ShiftAmtNode)
17716      return SDValue();
17717    uint32_t ShiftAmt = static_cast<uint32_t>(ShiftAmtNode->getZExtValue());
17718    ConstantSDNode *AndMaskNode = dyn_cast<ConstantSDNode>(N0->getOperand(1));
17719    if (!AndMaskNode)
17720      return SDValue();
17721    uint32_t AndMask = static_cast<uint32_t>(AndMaskNode->getZExtValue());
17722    // Don't transform uxtb/uxth.
17723    if (AndMask == 255 || AndMask == 65535)
17724      return SDValue();
17725    if (isMask_32(AndMask)) {
17726      uint32_t MaskedBits = llvm::countl_zero(AndMask);
17727      if (MaskedBits > ShiftAmt) {
17728        SDLoc DL(N);
17729        SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0),
17730                                  DAG.getConstant(MaskedBits, DL, MVT::i32));
17731        return DAG.getNode(
17732            ISD::SRL, DL, MVT::i32, SHL,
17733            DAG.getConstant(MaskedBits - ShiftAmt, DL, MVT::i32));
17734      }
17735    }
17736  }
17737
17738  // Nothing to be done for scalar shifts.
17739  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17740  if (!VT.isVector() || !TLI.isTypeLegal(VT))
17741    return SDValue();
17742  if (ST->hasMVEIntegerOps())
17743    return SDValue();
17744
17745  int64_t Cnt;
17746
17747  switch (N->getOpcode()) {
17748  default: llvm_unreachable("unexpected shift opcode");
17749
17750  case ISD::SHL:
17751    if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) {
17752      SDLoc dl(N);
17753      return DAG.getNode(ARMISD::VSHLIMM, dl, VT, N->getOperand(0),
17754                         DAG.getConstant(Cnt, dl, MVT::i32));
17755    }
17756    break;
17757
17758  case ISD::SRA:
17759  case ISD::SRL:
17760    if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
17761      unsigned VShiftOpc =
17762          (N->getOpcode() == ISD::SRA ? ARMISD::VSHRsIMM : ARMISD::VSHRuIMM);
17763      SDLoc dl(N);
17764      return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0),
17765                         DAG.getConstant(Cnt, dl, MVT::i32));
17766    }
17767  }
17768  return SDValue();
17769}
17770
17771// Look for a sign/zero/fpextend extend of a larger than legal load. This can be
17772// split into multiple extending loads, which are simpler to deal with than an
17773// arbitrary extend. For fp extends we use an integer extending load and a VCVTL
17774// to convert the type to an f32.
17775static SDValue PerformSplittingToWideningLoad(SDNode *N, SelectionDAG &DAG) {
17776  SDValue N0 = N->getOperand(0);
17777  if (N0.getOpcode() != ISD::LOAD)
17778    return SDValue();
17779  LoadSDNode *LD = cast<LoadSDNode>(N0.getNode());
17780  if (!LD->isSimple() || !N0.hasOneUse() || LD->isIndexed() ||
17781      LD->getExtensionType() != ISD::NON_EXTLOAD)
17782    return SDValue();
17783  EVT FromVT = LD->getValueType(0);
17784  EVT ToVT = N->getValueType(0);
17785  if (!ToVT.isVector())
17786    return SDValue();
17787  assert(FromVT.getVectorNumElements() == ToVT.getVectorNumElements());
17788  EVT ToEltVT = ToVT.getVectorElementType();
17789  EVT FromEltVT = FromVT.getVectorElementType();
17790
17791  unsigned NumElements = 0;
17792  if (ToEltVT == MVT::i32 && FromEltVT == MVT::i8)
17793    NumElements = 4;
17794  if (ToEltVT == MVT::f32 && FromEltVT == MVT::f16)
17795    NumElements = 4;
17796  if (NumElements == 0 ||
17797      (FromEltVT != MVT::f16 && FromVT.getVectorNumElements() == NumElements) ||
17798      FromVT.getVectorNumElements() % NumElements != 0 ||
17799      !isPowerOf2_32(NumElements))
17800    return SDValue();
17801
17802  LLVMContext &C = *DAG.getContext();
17803  SDLoc DL(LD);
17804  // Details about the old load
17805  SDValue Ch = LD->getChain();
17806  SDValue BasePtr = LD->getBasePtr();
17807  Align Alignment = LD->getOriginalAlign();
17808  MachineMemOperand::Flags MMOFlags = LD->getMemOperand()->getFlags();
17809  AAMDNodes AAInfo = LD->getAAInfo();
17810
17811  ISD::LoadExtType NewExtType =
17812      N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
17813  SDValue Offset = DAG.getUNDEF(BasePtr.getValueType());
17814  EVT NewFromVT = EVT::getVectorVT(
17815      C, EVT::getIntegerVT(C, FromEltVT.getScalarSizeInBits()), NumElements);
17816  EVT NewToVT = EVT::getVectorVT(
17817      C, EVT::getIntegerVT(C, ToEltVT.getScalarSizeInBits()), NumElements);
17818
17819  SmallVector<SDValue, 4> Loads;
17820  SmallVector<SDValue, 4> Chains;
17821  for (unsigned i = 0; i < FromVT.getVectorNumElements() / NumElements; i++) {
17822    unsigned NewOffset = (i * NewFromVT.getSizeInBits()) / 8;
17823    SDValue NewPtr =
17824        DAG.getObjectPtrOffset(DL, BasePtr, TypeSize::getFixed(NewOffset));
17825
17826    SDValue NewLoad =
17827        DAG.getLoad(ISD::UNINDEXED, NewExtType, NewToVT, DL, Ch, NewPtr, Offset,
17828                    LD->getPointerInfo().getWithOffset(NewOffset), NewFromVT,
17829                    Alignment, MMOFlags, AAInfo);
17830    Loads.push_back(NewLoad);
17831    Chains.push_back(SDValue(NewLoad.getNode(), 1));
17832  }
17833
17834  // Float truncs need to extended with VCVTB's into their floating point types.
17835  if (FromEltVT == MVT::f16) {
17836    SmallVector<SDValue, 4> Extends;
17837
17838    for (unsigned i = 0; i < Loads.size(); i++) {
17839      SDValue LoadBC =
17840          DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, MVT::v8f16, Loads[i]);
17841      SDValue FPExt = DAG.getNode(ARMISD::VCVTL, DL, MVT::v4f32, LoadBC,
17842                                  DAG.getConstant(0, DL, MVT::i32));
17843      Extends.push_back(FPExt);
17844    }
17845
17846    Loads = Extends;
17847  }
17848
17849  SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
17850  DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewChain);
17851  return DAG.getNode(ISD::CONCAT_VECTORS, DL, ToVT, Loads);
17852}
17853
17854/// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
17855/// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
17856static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
17857                                    const ARMSubtarget *ST) {
17858  SDValue N0 = N->getOperand(0);
17859
17860  // Check for sign- and zero-extensions of vector extract operations of 8- and
17861  // 16-bit vector elements. NEON and MVE support these directly. They are
17862  // handled during DAG combining because type legalization will promote them
17863  // to 32-bit types and it is messy to recognize the operations after that.
17864  if ((ST->hasNEON() || ST->hasMVEIntegerOps()) &&
17865      N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
17866    SDValue Vec = N0.getOperand(0);
17867    SDValue Lane = N0.getOperand(1);
17868    EVT VT = N->getValueType(0);
17869    EVT EltVT = N0.getValueType();
17870    const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17871
17872    if (VT == MVT::i32 &&
17873        (EltVT == MVT::i8 || EltVT == MVT::i16) &&
17874        TLI.isTypeLegal(Vec.getValueType()) &&
17875        isa<ConstantSDNode>(Lane)) {
17876
17877      unsigned Opc = 0;
17878      switch (N->getOpcode()) {
17879      default: llvm_unreachable("unexpected opcode");
17880      case ISD::SIGN_EXTEND:
17881        Opc = ARMISD::VGETLANEs;
17882        break;
17883      case ISD::ZERO_EXTEND:
17884      case ISD::ANY_EXTEND:
17885        Opc = ARMISD::VGETLANEu;
17886        break;
17887      }
17888      return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
17889    }
17890  }
17891
17892  if (ST->hasMVEIntegerOps())
17893    if (SDValue NewLoad = PerformSplittingToWideningLoad(N, DAG))
17894      return NewLoad;
17895
17896  return SDValue();
17897}
17898
17899static SDValue PerformFPExtendCombine(SDNode *N, SelectionDAG &DAG,
17900                                      const ARMSubtarget *ST) {
17901  if (ST->hasMVEFloatOps())
17902    if (SDValue NewLoad = PerformSplittingToWideningLoad(N, DAG))
17903      return NewLoad;
17904
17905  return SDValue();
17906}
17907
17908// Lower smin(smax(x, C1), C2) to ssat or usat, if they have saturating
17909// constant bounds.
17910static SDValue PerformMinMaxToSatCombine(SDValue Op, SelectionDAG &DAG,
17911                                         const ARMSubtarget *Subtarget) {
17912  if ((Subtarget->isThumb() || !Subtarget->hasV6Ops()) &&
17913      !Subtarget->isThumb2())
17914    return SDValue();
17915
17916  EVT VT = Op.getValueType();
17917  SDValue Op0 = Op.getOperand(0);
17918
17919  if (VT != MVT::i32 ||
17920      (Op0.getOpcode() != ISD::SMIN && Op0.getOpcode() != ISD::SMAX) ||
17921      !isa<ConstantSDNode>(Op.getOperand(1)) ||
17922      !isa<ConstantSDNode>(Op0.getOperand(1)))
17923    return SDValue();
17924
17925  SDValue Min = Op;
17926  SDValue Max = Op0;
17927  SDValue Input = Op0.getOperand(0);
17928  if (Min.getOpcode() == ISD::SMAX)
17929    std::swap(Min, Max);
17930
17931  APInt MinC = Min.getConstantOperandAPInt(1);
17932  APInt MaxC = Max.getConstantOperandAPInt(1);
17933
17934  if (Min.getOpcode() != ISD::SMIN || Max.getOpcode() != ISD::SMAX ||
17935      !(MinC + 1).isPowerOf2())
17936    return SDValue();
17937
17938  SDLoc DL(Op);
17939  if (MinC == ~MaxC)
17940    return DAG.getNode(ARMISD::SSAT, DL, VT, Input,
17941                       DAG.getConstant(MinC.countr_one(), DL, VT));
17942  if (MaxC == 0)
17943    return DAG.getNode(ARMISD::USAT, DL, VT, Input,
17944                       DAG.getConstant(MinC.countr_one(), DL, VT));
17945
17946  return SDValue();
17947}
17948
17949/// PerformMinMaxCombine - Target-specific DAG combining for creating truncating
17950/// saturates.
17951static SDValue PerformMinMaxCombine(SDNode *N, SelectionDAG &DAG,
17952                                    const ARMSubtarget *ST) {
17953  EVT VT = N->getValueType(0);
17954  SDValue N0 = N->getOperand(0);
17955
17956  if (VT == MVT::i32)
17957    return PerformMinMaxToSatCombine(SDValue(N, 0), DAG, ST);
17958
17959  if (!ST->hasMVEIntegerOps())
17960    return SDValue();
17961
17962  if (SDValue V = PerformVQDMULHCombine(N, DAG))
17963    return V;
17964
17965  if (VT != MVT::v4i32 && VT != MVT::v8i16)
17966    return SDValue();
17967
17968  auto IsSignedSaturate = [&](SDNode *Min, SDNode *Max) {
17969    // Check one is a smin and the other is a smax
17970    if (Min->getOpcode() != ISD::SMIN)
17971      std::swap(Min, Max);
17972    if (Min->getOpcode() != ISD::SMIN || Max->getOpcode() != ISD::SMAX)
17973      return false;
17974
17975    APInt SaturateC;
17976    if (VT == MVT::v4i32)
17977      SaturateC = APInt(32, (1 << 15) - 1, true);
17978    else //if (VT == MVT::v8i16)
17979      SaturateC = APInt(16, (1 << 7) - 1, true);
17980
17981    APInt MinC, MaxC;
17982    if (!ISD::isConstantSplatVector(Min->getOperand(1).getNode(), MinC) ||
17983        MinC != SaturateC)
17984      return false;
17985    if (!ISD::isConstantSplatVector(Max->getOperand(1).getNode(), MaxC) ||
17986        MaxC != ~SaturateC)
17987      return false;
17988    return true;
17989  };
17990
17991  if (IsSignedSaturate(N, N0.getNode())) {
17992    SDLoc DL(N);
17993    MVT ExtVT, HalfVT;
17994    if (VT == MVT::v4i32) {
17995      HalfVT = MVT::v8i16;
17996      ExtVT = MVT::v4i16;
17997    } else { // if (VT == MVT::v8i16)
17998      HalfVT = MVT::v16i8;
17999      ExtVT = MVT::v8i8;
18000    }
18001
18002    // Create a VQMOVNB with undef top lanes, then signed extended into the top
18003    // half. That extend will hopefully be removed if only the bottom bits are
18004    // demanded (though a truncating store, for example).
18005    SDValue VQMOVN =
18006        DAG.getNode(ARMISD::VQMOVNs, DL, HalfVT, DAG.getUNDEF(HalfVT),
18007                    N0->getOperand(0), DAG.getConstant(0, DL, MVT::i32));
18008    SDValue Bitcast = DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, VT, VQMOVN);
18009    return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, Bitcast,
18010                       DAG.getValueType(ExtVT));
18011  }
18012
18013  auto IsUnsignedSaturate = [&](SDNode *Min) {
18014    // For unsigned, we just need to check for <= 0xffff
18015    if (Min->getOpcode() != ISD::UMIN)
18016      return false;
18017
18018    APInt SaturateC;
18019    if (VT == MVT::v4i32)
18020      SaturateC = APInt(32, (1 << 16) - 1, true);
18021    else //if (VT == MVT::v8i16)
18022      SaturateC = APInt(16, (1 << 8) - 1, true);
18023
18024    APInt MinC;
18025    if (!ISD::isConstantSplatVector(Min->getOperand(1).getNode(), MinC) ||
18026        MinC != SaturateC)
18027      return false;
18028    return true;
18029  };
18030
18031  if (IsUnsignedSaturate(N)) {
18032    SDLoc DL(N);
18033    MVT HalfVT;
18034    unsigned ExtConst;
18035    if (VT == MVT::v4i32) {
18036      HalfVT = MVT::v8i16;
18037      ExtConst = 0x0000FFFF;
18038    } else { //if (VT == MVT::v8i16)
18039      HalfVT = MVT::v16i8;
18040      ExtConst = 0x00FF;
18041    }
18042
18043    // Create a VQMOVNB with undef top lanes, then ZExt into the top half with
18044    // an AND. That extend will hopefully be removed if only the bottom bits are
18045    // demanded (though a truncating store, for example).
18046    SDValue VQMOVN =
18047        DAG.getNode(ARMISD::VQMOVNu, DL, HalfVT, DAG.getUNDEF(HalfVT), N0,
18048                    DAG.getConstant(0, DL, MVT::i32));
18049    SDValue Bitcast = DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, VT, VQMOVN);
18050    return DAG.getNode(ISD::AND, DL, VT, Bitcast,
18051                       DAG.getConstant(ExtConst, DL, VT));
18052  }
18053
18054  return SDValue();
18055}
18056
18057static const APInt *isPowerOf2Constant(SDValue V) {
18058  ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
18059  if (!C)
18060    return nullptr;
18061  const APInt *CV = &C->getAPIntValue();
18062  return CV->isPowerOf2() ? CV : nullptr;
18063}
18064
18065SDValue ARMTargetLowering::PerformCMOVToBFICombine(SDNode *CMOV, SelectionDAG &DAG) const {
18066  // If we have a CMOV, OR and AND combination such as:
18067  //   if (x & CN)
18068  //     y |= CM;
18069  //
18070  // And:
18071  //   * CN is a single bit;
18072  //   * All bits covered by CM are known zero in y
18073  //
18074  // Then we can convert this into a sequence of BFI instructions. This will
18075  // always be a win if CM is a single bit, will always be no worse than the
18076  // TST&OR sequence if CM is two bits, and for thumb will be no worse if CM is
18077  // three bits (due to the extra IT instruction).
18078
18079  SDValue Op0 = CMOV->getOperand(0);
18080  SDValue Op1 = CMOV->getOperand(1);
18081  auto CC = CMOV->getConstantOperandAPInt(2).getLimitedValue();
18082  SDValue CmpZ = CMOV->getOperand(4);
18083
18084  // The compare must be against zero.
18085  if (!isNullConstant(CmpZ->getOperand(1)))
18086    return SDValue();
18087
18088  assert(CmpZ->getOpcode() == ARMISD::CMPZ);
18089  SDValue And = CmpZ->getOperand(0);
18090  if (And->getOpcode() != ISD::AND)
18091    return SDValue();
18092  const APInt *AndC = isPowerOf2Constant(And->getOperand(1));
18093  if (!AndC)
18094    return SDValue();
18095  SDValue X = And->getOperand(0);
18096
18097  if (CC == ARMCC::EQ) {
18098    // We're performing an "equal to zero" compare. Swap the operands so we
18099    // canonicalize on a "not equal to zero" compare.
18100    std::swap(Op0, Op1);
18101  } else {
18102    assert(CC == ARMCC::NE && "How can a CMPZ node not be EQ or NE?");
18103  }
18104
18105  if (Op1->getOpcode() != ISD::OR)
18106    return SDValue();
18107
18108  ConstantSDNode *OrC = dyn_cast<ConstantSDNode>(Op1->getOperand(1));
18109  if (!OrC)
18110    return SDValue();
18111  SDValue Y = Op1->getOperand(0);
18112
18113  if (Op0 != Y)
18114    return SDValue();
18115
18116  // Now, is it profitable to continue?
18117  APInt OrCI = OrC->getAPIntValue();
18118  unsigned Heuristic = Subtarget->isThumb() ? 3 : 2;
18119  if (OrCI.popcount() > Heuristic)
18120    return SDValue();
18121
18122  // Lastly, can we determine that the bits defined by OrCI
18123  // are zero in Y?
18124  KnownBits Known = DAG.computeKnownBits(Y);
18125  if ((OrCI & Known.Zero) != OrCI)
18126    return SDValue();
18127
18128  // OK, we can do the combine.
18129  SDValue V = Y;
18130  SDLoc dl(X);
18131  EVT VT = X.getValueType();
18132  unsigned BitInX = AndC->logBase2();
18133
18134  if (BitInX != 0) {
18135    // We must shift X first.
18136    X = DAG.getNode(ISD::SRL, dl, VT, X,
18137                    DAG.getConstant(BitInX, dl, VT));
18138  }
18139
18140  for (unsigned BitInY = 0, NumActiveBits = OrCI.getActiveBits();
18141       BitInY < NumActiveBits; ++BitInY) {
18142    if (OrCI[BitInY] == 0)
18143      continue;
18144    APInt Mask(VT.getSizeInBits(), 0);
18145    Mask.setBit(BitInY);
18146    V = DAG.getNode(ARMISD::BFI, dl, VT, V, X,
18147                    // Confusingly, the operand is an *inverted* mask.
18148                    DAG.getConstant(~Mask, dl, VT));
18149  }
18150
18151  return V;
18152}
18153
18154// Given N, the value controlling the conditional branch, search for the loop
18155// intrinsic, returning it, along with how the value is used. We need to handle
18156// patterns such as the following:
18157// (brcond (xor (setcc (loop.decrement), 0, ne), 1), exit)
18158// (brcond (setcc (loop.decrement), 0, eq), exit)
18159// (brcond (setcc (loop.decrement), 0, ne), header)
18160static SDValue SearchLoopIntrinsic(SDValue N, ISD::CondCode &CC, int &Imm,
18161                                   bool &Negate) {
18162  switch (N->getOpcode()) {
18163  default:
18164    break;
18165  case ISD::XOR: {
18166    if (!isa<ConstantSDNode>(N.getOperand(1)))
18167      return SDValue();
18168    if (!cast<ConstantSDNode>(N.getOperand(1))->isOne())
18169      return SDValue();
18170    Negate = !Negate;
18171    return SearchLoopIntrinsic(N.getOperand(0), CC, Imm, Negate);
18172  }
18173  case ISD::SETCC: {
18174    auto *Const = dyn_cast<ConstantSDNode>(N.getOperand(1));
18175    if (!Const)
18176      return SDValue();
18177    if (Const->isZero())
18178      Imm = 0;
18179    else if (Const->isOne())
18180      Imm = 1;
18181    else
18182      return SDValue();
18183    CC = cast<CondCodeSDNode>(N.getOperand(2))->get();
18184    return SearchLoopIntrinsic(N->getOperand(0), CC, Imm, Negate);
18185  }
18186  case ISD::INTRINSIC_W_CHAIN: {
18187    unsigned IntOp = N.getConstantOperandVal(1);
18188    if (IntOp != Intrinsic::test_start_loop_iterations &&
18189        IntOp != Intrinsic::loop_decrement_reg)
18190      return SDValue();
18191    return N;
18192  }
18193  }
18194  return SDValue();
18195}
18196
18197static SDValue PerformHWLoopCombine(SDNode *N,
18198                                    TargetLowering::DAGCombinerInfo &DCI,
18199                                    const ARMSubtarget *ST) {
18200
18201  // The hwloop intrinsics that we're interested are used for control-flow,
18202  // either for entering or exiting the loop:
18203  // - test.start.loop.iterations will test whether its operand is zero. If it
18204  //   is zero, the proceeding branch should not enter the loop.
18205  // - loop.decrement.reg also tests whether its operand is zero. If it is
18206  //   zero, the proceeding branch should not branch back to the beginning of
18207  //   the loop.
18208  // So here, we need to check that how the brcond is using the result of each
18209  // of the intrinsics to ensure that we're branching to the right place at the
18210  // right time.
18211
18212  ISD::CondCode CC;
18213  SDValue Cond;
18214  int Imm = 1;
18215  bool Negate = false;
18216  SDValue Chain = N->getOperand(0);
18217  SDValue Dest;
18218
18219  if (N->getOpcode() == ISD::BRCOND) {
18220    CC = ISD::SETEQ;
18221    Cond = N->getOperand(1);
18222    Dest = N->getOperand(2);
18223  } else {
18224    assert(N->getOpcode() == ISD::BR_CC && "Expected BRCOND or BR_CC!");
18225    CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
18226    Cond = N->getOperand(2);
18227    Dest = N->getOperand(4);
18228    if (auto *Const = dyn_cast<ConstantSDNode>(N->getOperand(3))) {
18229      if (!Const->isOne() && !Const->isZero())
18230        return SDValue();
18231      Imm = Const->getZExtValue();
18232    } else
18233      return SDValue();
18234  }
18235
18236  SDValue Int = SearchLoopIntrinsic(Cond, CC, Imm, Negate);
18237  if (!Int)
18238    return SDValue();
18239
18240  if (Negate)
18241    CC = ISD::getSetCCInverse(CC, /* Integer inverse */ MVT::i32);
18242
18243  auto IsTrueIfZero = [](ISD::CondCode CC, int Imm) {
18244    return (CC == ISD::SETEQ && Imm == 0) ||
18245           (CC == ISD::SETNE && Imm == 1) ||
18246           (CC == ISD::SETLT && Imm == 1) ||
18247           (CC == ISD::SETULT && Imm == 1);
18248  };
18249
18250  auto IsFalseIfZero = [](ISD::CondCode CC, int Imm) {
18251    return (CC == ISD::SETEQ && Imm == 1) ||
18252           (CC == ISD::SETNE && Imm == 0) ||
18253           (CC == ISD::SETGT && Imm == 0) ||
18254           (CC == ISD::SETUGT && Imm == 0) ||
18255           (CC == ISD::SETGE && Imm == 1) ||
18256           (CC == ISD::SETUGE && Imm == 1);
18257  };
18258
18259  assert((IsTrueIfZero(CC, Imm) || IsFalseIfZero(CC, Imm)) &&
18260         "unsupported condition");
18261
18262  SDLoc dl(Int);
18263  SelectionDAG &DAG = DCI.DAG;
18264  SDValue Elements = Int.getOperand(2);
18265  unsigned IntOp = Int->getConstantOperandVal(1);
18266  assert((N->hasOneUse() && N->use_begin()->getOpcode() == ISD::BR)
18267          && "expected single br user");
18268  SDNode *Br = *N->use_begin();
18269  SDValue OtherTarget = Br->getOperand(1);
18270
18271  // Update the unconditional branch to branch to the given Dest.
18272  auto UpdateUncondBr = [](SDNode *Br, SDValue Dest, SelectionDAG &DAG) {
18273    SDValue NewBrOps[] = { Br->getOperand(0), Dest };
18274    SDValue NewBr = DAG.getNode(ISD::BR, SDLoc(Br), MVT::Other, NewBrOps);
18275    DAG.ReplaceAllUsesOfValueWith(SDValue(Br, 0), NewBr);
18276  };
18277
18278  if (IntOp == Intrinsic::test_start_loop_iterations) {
18279    SDValue Res;
18280    SDValue Setup = DAG.getNode(ARMISD::WLSSETUP, dl, MVT::i32, Elements);
18281    // We expect this 'instruction' to branch when the counter is zero.
18282    if (IsTrueIfZero(CC, Imm)) {
18283      SDValue Ops[] = {Chain, Setup, Dest};
18284      Res = DAG.getNode(ARMISD::WLS, dl, MVT::Other, Ops);
18285    } else {
18286      // The logic is the reverse of what we need for WLS, so find the other
18287      // basic block target: the target of the proceeding br.
18288      UpdateUncondBr(Br, Dest, DAG);
18289
18290      SDValue Ops[] = {Chain, Setup, OtherTarget};
18291      Res = DAG.getNode(ARMISD::WLS, dl, MVT::Other, Ops);
18292    }
18293    // Update LR count to the new value
18294    DAG.ReplaceAllUsesOfValueWith(Int.getValue(0), Setup);
18295    // Update chain
18296    DAG.ReplaceAllUsesOfValueWith(Int.getValue(2), Int.getOperand(0));
18297    return Res;
18298  } else {
18299    SDValue Size =
18300        DAG.getTargetConstant(Int.getConstantOperandVal(3), dl, MVT::i32);
18301    SDValue Args[] = { Int.getOperand(0), Elements, Size, };
18302    SDValue LoopDec = DAG.getNode(ARMISD::LOOP_DEC, dl,
18303                                  DAG.getVTList(MVT::i32, MVT::Other), Args);
18304    DAG.ReplaceAllUsesWith(Int.getNode(), LoopDec.getNode());
18305
18306    // We expect this instruction to branch when the count is not zero.
18307    SDValue Target = IsFalseIfZero(CC, Imm) ? Dest : OtherTarget;
18308
18309    // Update the unconditional branch to target the loop preheader if we've
18310    // found the condition has been reversed.
18311    if (Target == OtherTarget)
18312      UpdateUncondBr(Br, Dest, DAG);
18313
18314    Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
18315                        SDValue(LoopDec.getNode(), 1), Chain);
18316
18317    SDValue EndArgs[] = { Chain, SDValue(LoopDec.getNode(), 0), Target };
18318    return DAG.getNode(ARMISD::LE, dl, MVT::Other, EndArgs);
18319  }
18320  return SDValue();
18321}
18322
18323/// PerformBRCONDCombine - Target-specific DAG combining for ARMISD::BRCOND.
18324SDValue
18325ARMTargetLowering::PerformBRCONDCombine(SDNode *N, SelectionDAG &DAG) const {
18326  SDValue Cmp = N->getOperand(4);
18327  if (Cmp.getOpcode() != ARMISD::CMPZ)
18328    // Only looking at NE cases.
18329    return SDValue();
18330
18331  EVT VT = N->getValueType(0);
18332  SDLoc dl(N);
18333  SDValue LHS = Cmp.getOperand(0);
18334  SDValue RHS = Cmp.getOperand(1);
18335  SDValue Chain = N->getOperand(0);
18336  SDValue BB = N->getOperand(1);
18337  SDValue ARMcc = N->getOperand(2);
18338  ARMCC::CondCodes CC = (ARMCC::CondCodes)ARMcc->getAsZExtVal();
18339
18340  // (brcond Chain BB ne CPSR (cmpz (and (cmov 0 1 CC CPSR Cmp) 1) 0))
18341  // -> (brcond Chain BB CC CPSR Cmp)
18342  if (CC == ARMCC::NE && LHS.getOpcode() == ISD::AND && LHS->hasOneUse() &&
18343      LHS->getOperand(0)->getOpcode() == ARMISD::CMOV &&
18344      LHS->getOperand(0)->hasOneUse() &&
18345      isNullConstant(LHS->getOperand(0)->getOperand(0)) &&
18346      isOneConstant(LHS->getOperand(0)->getOperand(1)) &&
18347      isOneConstant(LHS->getOperand(1)) && isNullConstant(RHS)) {
18348    return DAG.getNode(
18349        ARMISD::BRCOND, dl, VT, Chain, BB, LHS->getOperand(0)->getOperand(2),
18350        LHS->getOperand(0)->getOperand(3), LHS->getOperand(0)->getOperand(4));
18351  }
18352
18353  return SDValue();
18354}
18355
18356/// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
18357SDValue
18358ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
18359  SDValue Cmp = N->getOperand(4);
18360  if (Cmp.getOpcode() != ARMISD::CMPZ)
18361    // Only looking at EQ and NE cases.
18362    return SDValue();
18363
18364  EVT VT = N->getValueType(0);
18365  SDLoc dl(N);
18366  SDValue LHS = Cmp.getOperand(0);
18367  SDValue RHS = Cmp.getOperand(1);
18368  SDValue FalseVal = N->getOperand(0);
18369  SDValue TrueVal = N->getOperand(1);
18370  SDValue ARMcc = N->getOperand(2);
18371  ARMCC::CondCodes CC = (ARMCC::CondCodes)ARMcc->getAsZExtVal();
18372
18373  // BFI is only available on V6T2+.
18374  if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) {
18375    SDValue R = PerformCMOVToBFICombine(N, DAG);
18376    if (R)
18377      return R;
18378  }
18379
18380  // Simplify
18381  //   mov     r1, r0
18382  //   cmp     r1, x
18383  //   mov     r0, y
18384  //   moveq   r0, x
18385  // to
18386  //   cmp     r0, x
18387  //   movne   r0, y
18388  //
18389  //   mov     r1, r0
18390  //   cmp     r1, x
18391  //   mov     r0, x
18392  //   movne   r0, y
18393  // to
18394  //   cmp     r0, x
18395  //   movne   r0, y
18396  /// FIXME: Turn this into a target neutral optimization?
18397  SDValue Res;
18398  if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
18399    Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
18400                      N->getOperand(3), Cmp);
18401  } else if (CC == ARMCC::EQ && TrueVal == RHS) {
18402    SDValue ARMcc;
18403    SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
18404    Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
18405                      N->getOperand(3), NewCmp);
18406  }
18407
18408  // (cmov F T ne CPSR (cmpz (cmov 0 1 CC CPSR Cmp) 0))
18409  // -> (cmov F T CC CPSR Cmp)
18410  if (CC == ARMCC::NE && LHS.getOpcode() == ARMISD::CMOV && LHS->hasOneUse() &&
18411      isNullConstant(LHS->getOperand(0)) && isOneConstant(LHS->getOperand(1)) &&
18412      isNullConstant(RHS)) {
18413    return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
18414                       LHS->getOperand(2), LHS->getOperand(3),
18415                       LHS->getOperand(4));
18416  }
18417
18418  if (!VT.isInteger())
18419      return SDValue();
18420
18421  // Fold away an unneccessary CMPZ/CMOV
18422  // CMOV A, B, C1, $cpsr, (CMPZ (CMOV 1, 0, C2, D), 0) ->
18423  // if C1==EQ -> CMOV A, B, C2, $cpsr, D
18424  // if C1==NE -> CMOV A, B, NOT(C2), $cpsr, D
18425  if (N->getConstantOperandVal(2) == ARMCC::EQ ||
18426      N->getConstantOperandVal(2) == ARMCC::NE) {
18427    ARMCC::CondCodes Cond;
18428    if (SDValue C = IsCMPZCSINC(N->getOperand(4).getNode(), Cond)) {
18429      if (N->getConstantOperandVal(2) == ARMCC::NE)
18430        Cond = ARMCC::getOppositeCondition(Cond);
18431      return DAG.getNode(N->getOpcode(), SDLoc(N), MVT::i32, N->getOperand(0),
18432                         N->getOperand(1),
18433                         DAG.getTargetConstant(Cond, SDLoc(N), MVT::i32),
18434                         N->getOperand(3), C);
18435    }
18436  }
18437
18438  // Materialize a boolean comparison for integers so we can avoid branching.
18439  if (isNullConstant(FalseVal)) {
18440    if (CC == ARMCC::EQ && isOneConstant(TrueVal)) {
18441      if (!Subtarget->isThumb1Only() && Subtarget->hasV5TOps()) {
18442        // If x == y then x - y == 0 and ARM's CLZ will return 32, shifting it
18443        // right 5 bits will make that 32 be 1, otherwise it will be 0.
18444        // CMOV 0, 1, ==, (CMPZ x, y) -> SRL (CTLZ (SUB x, y)), 5
18445        SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS);
18446        Res = DAG.getNode(ISD::SRL, dl, VT, DAG.getNode(ISD::CTLZ, dl, VT, Sub),
18447                          DAG.getConstant(5, dl, MVT::i32));
18448      } else {
18449        // CMOV 0, 1, ==, (CMPZ x, y) ->
18450        //     (UADDO_CARRY (SUB x, y), t:0, t:1)
18451        // where t = (USUBO_CARRY 0, (SUB x, y), 0)
18452        //
18453        // The USUBO_CARRY computes 0 - (x - y) and this will give a borrow when
18454        // x != y. In other words, a carry C == 1 when x == y, C == 0
18455        // otherwise.
18456        // The final UADDO_CARRY computes
18457        //     x - y + (0 - (x - y)) + C == C
18458        SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS);
18459        SDVTList VTs = DAG.getVTList(VT, MVT::i32);
18460        SDValue Neg = DAG.getNode(ISD::USUBO, dl, VTs, FalseVal, Sub);
18461        // ISD::USUBO_CARRY returns a borrow but we want the carry here
18462        // actually.
18463        SDValue Carry =
18464            DAG.getNode(ISD::SUB, dl, MVT::i32,
18465                        DAG.getConstant(1, dl, MVT::i32), Neg.getValue(1));
18466        Res = DAG.getNode(ISD::UADDO_CARRY, dl, VTs, Sub, Neg, Carry);
18467      }
18468    } else if (CC == ARMCC::NE && !isNullConstant(RHS) &&
18469               (!Subtarget->isThumb1Only() || isPowerOf2Constant(TrueVal))) {
18470      // This seems pointless but will allow us to combine it further below.
18471      // CMOV 0, z, !=, (CMPZ x, y) -> CMOV (SUBS x, y), z, !=, (SUBS x, y):1
18472      SDValue Sub =
18473          DAG.getNode(ARMISD::SUBS, dl, DAG.getVTList(VT, MVT::i32), LHS, RHS);
18474      SDValue CPSRGlue = DAG.getCopyToReg(DAG.getEntryNode(), dl, ARM::CPSR,
18475                                          Sub.getValue(1), SDValue());
18476      Res = DAG.getNode(ARMISD::CMOV, dl, VT, Sub, TrueVal, ARMcc,
18477                        N->getOperand(3), CPSRGlue.getValue(1));
18478      FalseVal = Sub;
18479    }
18480  } else if (isNullConstant(TrueVal)) {
18481    if (CC == ARMCC::EQ && !isNullConstant(RHS) &&
18482        (!Subtarget->isThumb1Only() || isPowerOf2Constant(FalseVal))) {
18483      // This seems pointless but will allow us to combine it further below
18484      // Note that we change == for != as this is the dual for the case above.
18485      // CMOV z, 0, ==, (CMPZ x, y) -> CMOV (SUBS x, y), z, !=, (SUBS x, y):1
18486      SDValue Sub =
18487          DAG.getNode(ARMISD::SUBS, dl, DAG.getVTList(VT, MVT::i32), LHS, RHS);
18488      SDValue CPSRGlue = DAG.getCopyToReg(DAG.getEntryNode(), dl, ARM::CPSR,
18489                                          Sub.getValue(1), SDValue());
18490      Res = DAG.getNode(ARMISD::CMOV, dl, VT, Sub, FalseVal,
18491                        DAG.getConstant(ARMCC::NE, dl, MVT::i32),
18492                        N->getOperand(3), CPSRGlue.getValue(1));
18493      FalseVal = Sub;
18494    }
18495  }
18496
18497  // On Thumb1, the DAG above may be further combined if z is a power of 2
18498  // (z == 2 ^ K).
18499  // CMOV (SUBS x, y), z, !=, (SUBS x, y):1 ->
18500  // t1 = (USUBO (SUB x, y), 1)
18501  // t2 = (USUBO_CARRY (SUB x, y), t1:0, t1:1)
18502  // Result = if K != 0 then (SHL t2:0, K) else t2:0
18503  //
18504  // This also handles the special case of comparing against zero; it's
18505  // essentially, the same pattern, except there's no SUBS:
18506  // CMOV x, z, !=, (CMPZ x, 0) ->
18507  // t1 = (USUBO x, 1)
18508  // t2 = (USUBO_CARRY x, t1:0, t1:1)
18509  // Result = if K != 0 then (SHL t2:0, K) else t2:0
18510  const APInt *TrueConst;
18511  if (Subtarget->isThumb1Only() && CC == ARMCC::NE &&
18512      ((FalseVal.getOpcode() == ARMISD::SUBS &&
18513        FalseVal.getOperand(0) == LHS && FalseVal.getOperand(1) == RHS) ||
18514       (FalseVal == LHS && isNullConstant(RHS))) &&
18515      (TrueConst = isPowerOf2Constant(TrueVal))) {
18516    SDVTList VTs = DAG.getVTList(VT, MVT::i32);
18517    unsigned ShiftAmount = TrueConst->logBase2();
18518    if (ShiftAmount)
18519      TrueVal = DAG.getConstant(1, dl, VT);
18520    SDValue Subc = DAG.getNode(ISD::USUBO, dl, VTs, FalseVal, TrueVal);
18521    Res = DAG.getNode(ISD::USUBO_CARRY, dl, VTs, FalseVal, Subc,
18522                      Subc.getValue(1));
18523
18524    if (ShiftAmount)
18525      Res = DAG.getNode(ISD::SHL, dl, VT, Res,
18526                        DAG.getConstant(ShiftAmount, dl, MVT::i32));
18527  }
18528
18529  if (Res.getNode()) {
18530    KnownBits Known = DAG.computeKnownBits(SDValue(N,0));
18531    // Capture demanded bits information that would be otherwise lost.
18532    if (Known.Zero == 0xfffffffe)
18533      Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
18534                        DAG.getValueType(MVT::i1));
18535    else if (Known.Zero == 0xffffff00)
18536      Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
18537                        DAG.getValueType(MVT::i8));
18538    else if (Known.Zero == 0xffff0000)
18539      Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
18540                        DAG.getValueType(MVT::i16));
18541  }
18542
18543  return Res;
18544}
18545
18546static SDValue PerformBITCASTCombine(SDNode *N,
18547                                     TargetLowering::DAGCombinerInfo &DCI,
18548                                     const ARMSubtarget *ST) {
18549  SelectionDAG &DAG = DCI.DAG;
18550  SDValue Src = N->getOperand(0);
18551  EVT DstVT = N->getValueType(0);
18552
18553  // Convert v4f32 bitcast (v4i32 vdup (i32)) -> v4f32 vdup (i32) under MVE.
18554  if (ST->hasMVEIntegerOps() && Src.getOpcode() == ARMISD::VDUP) {
18555    EVT SrcVT = Src.getValueType();
18556    if (SrcVT.getScalarSizeInBits() == DstVT.getScalarSizeInBits())
18557      return DAG.getNode(ARMISD::VDUP, SDLoc(N), DstVT, Src.getOperand(0));
18558  }
18559
18560  // We may have a bitcast of something that has already had this bitcast
18561  // combine performed on it, so skip past any VECTOR_REG_CASTs.
18562  while (Src.getOpcode() == ARMISD::VECTOR_REG_CAST)
18563    Src = Src.getOperand(0);
18564
18565  // Bitcast from element-wise VMOV or VMVN doesn't need VREV if the VREV that
18566  // would be generated is at least the width of the element type.
18567  EVT SrcVT = Src.getValueType();
18568  if ((Src.getOpcode() == ARMISD::VMOVIMM ||
18569       Src.getOpcode() == ARMISD::VMVNIMM ||
18570       Src.getOpcode() == ARMISD::VMOVFPIMM) &&
18571      SrcVT.getScalarSizeInBits() <= DstVT.getScalarSizeInBits() &&
18572      DAG.getDataLayout().isBigEndian())
18573    return DAG.getNode(ARMISD::VECTOR_REG_CAST, SDLoc(N), DstVT, Src);
18574
18575  // bitcast(extract(x, n)); bitcast(extract(x, n+1))  ->  VMOVRRD x
18576  if (SDValue R = PerformExtractEltToVMOVRRD(N, DCI))
18577    return R;
18578
18579  return SDValue();
18580}
18581
18582// Some combines for the MVETrunc truncations legalizer helper. Also lowers the
18583// node into stack operations after legalizeOps.
18584SDValue ARMTargetLowering::PerformMVETruncCombine(
18585    SDNode *N, TargetLowering::DAGCombinerInfo &DCI) const {
18586  SelectionDAG &DAG = DCI.DAG;
18587  EVT VT = N->getValueType(0);
18588  SDLoc DL(N);
18589
18590  // MVETrunc(Undef, Undef) -> Undef
18591  if (all_of(N->ops(), [](SDValue Op) { return Op.isUndef(); }))
18592    return DAG.getUNDEF(VT);
18593
18594  // MVETrunc(MVETrunc a b, MVETrunc c, d) -> MVETrunc
18595  if (N->getNumOperands() == 2 &&
18596      N->getOperand(0).getOpcode() == ARMISD::MVETRUNC &&
18597      N->getOperand(1).getOpcode() == ARMISD::MVETRUNC)
18598    return DAG.getNode(ARMISD::MVETRUNC, DL, VT, N->getOperand(0).getOperand(0),
18599                       N->getOperand(0).getOperand(1),
18600                       N->getOperand(1).getOperand(0),
18601                       N->getOperand(1).getOperand(1));
18602
18603  // MVETrunc(shuffle, shuffle) -> VMOVN
18604  if (N->getNumOperands() == 2 &&
18605      N->getOperand(0).getOpcode() == ISD::VECTOR_SHUFFLE &&
18606      N->getOperand(1).getOpcode() == ISD::VECTOR_SHUFFLE) {
18607    auto *S0 = cast<ShuffleVectorSDNode>(N->getOperand(0).getNode());
18608    auto *S1 = cast<ShuffleVectorSDNode>(N->getOperand(1).getNode());
18609
18610    if (S0->getOperand(0) == S1->getOperand(0) &&
18611        S0->getOperand(1) == S1->getOperand(1)) {
18612      // Construct complete shuffle mask
18613      SmallVector<int, 8> Mask(S0->getMask());
18614      Mask.append(S1->getMask().begin(), S1->getMask().end());
18615
18616      if (isVMOVNTruncMask(Mask, VT, false))
18617        return DAG.getNode(
18618            ARMISD::VMOVN, DL, VT,
18619            DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, VT, S0->getOperand(0)),
18620            DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, VT, S0->getOperand(1)),
18621            DAG.getConstant(1, DL, MVT::i32));
18622      if (isVMOVNTruncMask(Mask, VT, true))
18623        return DAG.getNode(
18624            ARMISD::VMOVN, DL, VT,
18625            DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, VT, S0->getOperand(1)),
18626            DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, VT, S0->getOperand(0)),
18627            DAG.getConstant(1, DL, MVT::i32));
18628    }
18629  }
18630
18631  // For MVETrunc of a buildvector or shuffle, it can be beneficial to lower the
18632  // truncate to a buildvector to allow the generic optimisations to kick in.
18633  if (all_of(N->ops(), [](SDValue Op) {
18634        return Op.getOpcode() == ISD::BUILD_VECTOR ||
18635               Op.getOpcode() == ISD::VECTOR_SHUFFLE ||
18636               (Op.getOpcode() == ISD::BITCAST &&
18637                Op.getOperand(0).getOpcode() == ISD::BUILD_VECTOR);
18638      })) {
18639    SmallVector<SDValue, 8> Extracts;
18640    for (unsigned Op = 0; Op < N->getNumOperands(); Op++) {
18641      SDValue O = N->getOperand(Op);
18642      for (unsigned i = 0; i < O.getValueType().getVectorNumElements(); i++) {
18643        SDValue Ext = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, O,
18644                                  DAG.getConstant(i, DL, MVT::i32));
18645        Extracts.push_back(Ext);
18646      }
18647    }
18648    return DAG.getBuildVector(VT, DL, Extracts);
18649  }
18650
18651  // If we are late in the legalization process and nothing has optimised
18652  // the trunc to anything better, lower it to a stack store and reload,
18653  // performing the truncation whilst keeping the lanes in the correct order:
18654  //   VSTRH.32 a, stack; VSTRH.32 b, stack+8; VLDRW.32 stack;
18655  if (!DCI.isAfterLegalizeDAG())
18656    return SDValue();
18657
18658  SDValue StackPtr = DAG.CreateStackTemporary(TypeSize::getFixed(16), Align(4));
18659  int SPFI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
18660  int NumIns = N->getNumOperands();
18661  assert((NumIns == 2 || NumIns == 4) &&
18662         "Expected 2 or 4 inputs to an MVETrunc");
18663  EVT StoreVT = VT.getHalfNumVectorElementsVT(*DAG.getContext());
18664  if (N->getNumOperands() == 4)
18665    StoreVT = StoreVT.getHalfNumVectorElementsVT(*DAG.getContext());
18666
18667  SmallVector<SDValue> Chains;
18668  for (int I = 0; I < NumIns; I++) {
18669    SDValue Ptr = DAG.getNode(
18670        ISD::ADD, DL, StackPtr.getValueType(), StackPtr,
18671        DAG.getConstant(I * 16 / NumIns, DL, StackPtr.getValueType()));
18672    MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(
18673        DAG.getMachineFunction(), SPFI, I * 16 / NumIns);
18674    SDValue Ch = DAG.getTruncStore(DAG.getEntryNode(), DL, N->getOperand(I),
18675                                   Ptr, MPI, StoreVT, Align(4));
18676    Chains.push_back(Ch);
18677  }
18678
18679  SDValue Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
18680  MachinePointerInfo MPI =
18681      MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI, 0);
18682  return DAG.getLoad(VT, DL, Chain, StackPtr, MPI, Align(4));
18683}
18684
18685// Take a MVEEXT(load x) and split that into (extload x, extload x+8)
18686static SDValue PerformSplittingMVEEXTToWideningLoad(SDNode *N,
18687                                                    SelectionDAG &DAG) {
18688  SDValue N0 = N->getOperand(0);
18689  LoadSDNode *LD = dyn_cast<LoadSDNode>(N0.getNode());
18690  if (!LD || !LD->isSimple() || !N0.hasOneUse() || LD->isIndexed())
18691    return SDValue();
18692
18693  EVT FromVT = LD->getMemoryVT();
18694  EVT ToVT = N->getValueType(0);
18695  if (!ToVT.isVector())
18696    return SDValue();
18697  assert(FromVT.getVectorNumElements() == ToVT.getVectorNumElements() * 2);
18698  EVT ToEltVT = ToVT.getVectorElementType();
18699  EVT FromEltVT = FromVT.getVectorElementType();
18700
18701  unsigned NumElements = 0;
18702  if (ToEltVT == MVT::i32 && (FromEltVT == MVT::i16 || FromEltVT == MVT::i8))
18703    NumElements = 4;
18704  if (ToEltVT == MVT::i16 && FromEltVT == MVT::i8)
18705    NumElements = 8;
18706  assert(NumElements != 0);
18707
18708  ISD::LoadExtType NewExtType =
18709      N->getOpcode() == ARMISD::MVESEXT ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
18710  if (LD->getExtensionType() != ISD::NON_EXTLOAD &&
18711      LD->getExtensionType() != ISD::EXTLOAD &&
18712      LD->getExtensionType() != NewExtType)
18713    return SDValue();
18714
18715  LLVMContext &C = *DAG.getContext();
18716  SDLoc DL(LD);
18717  // Details about the old load
18718  SDValue Ch = LD->getChain();
18719  SDValue BasePtr = LD->getBasePtr();
18720  Align Alignment = LD->getOriginalAlign();
18721  MachineMemOperand::Flags MMOFlags = LD->getMemOperand()->getFlags();
18722  AAMDNodes AAInfo = LD->getAAInfo();
18723
18724  SDValue Offset = DAG.getUNDEF(BasePtr.getValueType());
18725  EVT NewFromVT = EVT::getVectorVT(
18726      C, EVT::getIntegerVT(C, FromEltVT.getScalarSizeInBits()), NumElements);
18727  EVT NewToVT = EVT::getVectorVT(
18728      C, EVT::getIntegerVT(C, ToEltVT.getScalarSizeInBits()), NumElements);
18729
18730  SmallVector<SDValue, 4> Loads;
18731  SmallVector<SDValue, 4> Chains;
18732  for (unsigned i = 0; i < FromVT.getVectorNumElements() / NumElements; i++) {
18733    unsigned NewOffset = (i * NewFromVT.getSizeInBits()) / 8;
18734    SDValue NewPtr =
18735        DAG.getObjectPtrOffset(DL, BasePtr, TypeSize::getFixed(NewOffset));
18736
18737    SDValue NewLoad =
18738        DAG.getLoad(ISD::UNINDEXED, NewExtType, NewToVT, DL, Ch, NewPtr, Offset,
18739                    LD->getPointerInfo().getWithOffset(NewOffset), NewFromVT,
18740                    Alignment, MMOFlags, AAInfo);
18741    Loads.push_back(NewLoad);
18742    Chains.push_back(SDValue(NewLoad.getNode(), 1));
18743  }
18744
18745  SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
18746  DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewChain);
18747  return DAG.getMergeValues(Loads, DL);
18748}
18749
18750// Perform combines for MVEEXT. If it has not be optimized to anything better
18751// before lowering, it gets converted to stack store and extloads performing the
18752// extend whilst still keeping the same lane ordering.
18753SDValue ARMTargetLowering::PerformMVEExtCombine(
18754    SDNode *N, TargetLowering::DAGCombinerInfo &DCI) const {
18755  SelectionDAG &DAG = DCI.DAG;
18756  EVT VT = N->getValueType(0);
18757  SDLoc DL(N);
18758  assert(N->getNumValues() == 2 && "Expected MVEEXT with 2 elements");
18759  assert((VT == MVT::v4i32 || VT == MVT::v8i16) && "Unexpected MVEEXT type");
18760
18761  EVT ExtVT = N->getOperand(0).getValueType().getHalfNumVectorElementsVT(
18762      *DAG.getContext());
18763  auto Extend = [&](SDValue V) {
18764    SDValue VVT = DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, VT, V);
18765    return N->getOpcode() == ARMISD::MVESEXT
18766               ? DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, VVT,
18767                             DAG.getValueType(ExtVT))
18768               : DAG.getZeroExtendInReg(VVT, DL, ExtVT);
18769  };
18770
18771  // MVEEXT(VDUP) -> SIGN_EXTEND_INREG(VDUP)
18772  if (N->getOperand(0).getOpcode() == ARMISD::VDUP) {
18773    SDValue Ext = Extend(N->getOperand(0));
18774    return DAG.getMergeValues({Ext, Ext}, DL);
18775  }
18776
18777  // MVEEXT(shuffle) -> SIGN_EXTEND_INREG/ZERO_EXTEND_INREG
18778  if (auto *SVN = dyn_cast<ShuffleVectorSDNode>(N->getOperand(0))) {
18779    ArrayRef<int> Mask = SVN->getMask();
18780    assert(Mask.size() == 2 * VT.getVectorNumElements());
18781    assert(Mask.size() == SVN->getValueType(0).getVectorNumElements());
18782    unsigned Rev = VT == MVT::v4i32 ? ARMISD::VREV32 : ARMISD::VREV16;
18783    SDValue Op0 = SVN->getOperand(0);
18784    SDValue Op1 = SVN->getOperand(1);
18785
18786    auto CheckInregMask = [&](int Start, int Offset) {
18787      for (int Idx = 0, E = VT.getVectorNumElements(); Idx < E; ++Idx)
18788        if (Mask[Start + Idx] >= 0 && Mask[Start + Idx] != Idx * 2 + Offset)
18789          return false;
18790      return true;
18791    };
18792    SDValue V0 = SDValue(N, 0);
18793    SDValue V1 = SDValue(N, 1);
18794    if (CheckInregMask(0, 0))
18795      V0 = Extend(Op0);
18796    else if (CheckInregMask(0, 1))
18797      V0 = Extend(DAG.getNode(Rev, DL, SVN->getValueType(0), Op0));
18798    else if (CheckInregMask(0, Mask.size()))
18799      V0 = Extend(Op1);
18800    else if (CheckInregMask(0, Mask.size() + 1))
18801      V0 = Extend(DAG.getNode(Rev, DL, SVN->getValueType(0), Op1));
18802
18803    if (CheckInregMask(VT.getVectorNumElements(), Mask.size()))
18804      V1 = Extend(Op1);
18805    else if (CheckInregMask(VT.getVectorNumElements(), Mask.size() + 1))
18806      V1 = Extend(DAG.getNode(Rev, DL, SVN->getValueType(0), Op1));
18807    else if (CheckInregMask(VT.getVectorNumElements(), 0))
18808      V1 = Extend(Op0);
18809    else if (CheckInregMask(VT.getVectorNumElements(), 1))
18810      V1 = Extend(DAG.getNode(Rev, DL, SVN->getValueType(0), Op0));
18811
18812    if (V0.getNode() != N || V1.getNode() != N)
18813      return DAG.getMergeValues({V0, V1}, DL);
18814  }
18815
18816  // MVEEXT(load) -> extload, extload
18817  if (N->getOperand(0)->getOpcode() == ISD::LOAD)
18818    if (SDValue L = PerformSplittingMVEEXTToWideningLoad(N, DAG))
18819      return L;
18820
18821  if (!DCI.isAfterLegalizeDAG())
18822    return SDValue();
18823
18824  // Lower to a stack store and reload:
18825  //  VSTRW.32 a, stack; VLDRH.32 stack; VLDRH.32 stack+8;
18826  SDValue StackPtr = DAG.CreateStackTemporary(TypeSize::getFixed(16), Align(4));
18827  int SPFI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
18828  int NumOuts = N->getNumValues();
18829  assert((NumOuts == 2 || NumOuts == 4) &&
18830         "Expected 2 or 4 outputs to an MVEEXT");
18831  EVT LoadVT = N->getOperand(0).getValueType().getHalfNumVectorElementsVT(
18832      *DAG.getContext());
18833  if (N->getNumOperands() == 4)
18834    LoadVT = LoadVT.getHalfNumVectorElementsVT(*DAG.getContext());
18835
18836  MachinePointerInfo MPI =
18837      MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI, 0);
18838  SDValue Chain = DAG.getStore(DAG.getEntryNode(), DL, N->getOperand(0),
18839                               StackPtr, MPI, Align(4));
18840
18841  SmallVector<SDValue> Loads;
18842  for (int I = 0; I < NumOuts; I++) {
18843    SDValue Ptr = DAG.getNode(
18844        ISD::ADD, DL, StackPtr.getValueType(), StackPtr,
18845        DAG.getConstant(I * 16 / NumOuts, DL, StackPtr.getValueType()));
18846    MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(
18847        DAG.getMachineFunction(), SPFI, I * 16 / NumOuts);
18848    SDValue Load = DAG.getExtLoad(
18849        N->getOpcode() == ARMISD::MVESEXT ? ISD::SEXTLOAD : ISD::ZEXTLOAD, DL,
18850        VT, Chain, Ptr, MPI, LoadVT, Align(4));
18851    Loads.push_back(Load);
18852  }
18853
18854  return DAG.getMergeValues(Loads, DL);
18855}
18856
18857SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
18858                                             DAGCombinerInfo &DCI) const {
18859  switch (N->getOpcode()) {
18860  default: break;
18861  case ISD::SELECT_CC:
18862  case ISD::SELECT:     return PerformSELECTCombine(N, DCI, Subtarget);
18863  case ISD::VSELECT:    return PerformVSELECTCombine(N, DCI, Subtarget);
18864  case ISD::SETCC:      return PerformVSetCCToVCTPCombine(N, DCI, Subtarget);
18865  case ISD::ABS:        return PerformABSCombine(N, DCI, Subtarget);
18866  case ARMISD::ADDE:    return PerformADDECombine(N, DCI, Subtarget);
18867  case ARMISD::UMLAL:   return PerformUMLALCombine(N, DCI.DAG, Subtarget);
18868  case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
18869  case ISD::SUB:        return PerformSUBCombine(N, DCI, Subtarget);
18870  case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
18871  case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
18872  case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
18873  case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
18874  case ISD::BRCOND:
18875  case ISD::BR_CC:      return PerformHWLoopCombine(N, DCI, Subtarget);
18876  case ARMISD::ADDC:
18877  case ARMISD::SUBC:    return PerformAddcSubcCombine(N, DCI, Subtarget);
18878  case ARMISD::SUBE:    return PerformAddeSubeCombine(N, DCI, Subtarget);
18879  case ARMISD::BFI:     return PerformBFICombine(N, DCI.DAG);
18880  case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget);
18881  case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
18882  case ARMISD::VMOVhr:  return PerformVMOVhrCombine(N, DCI);
18883  case ARMISD::VMOVrh:  return PerformVMOVrhCombine(N, DCI.DAG);
18884  case ISD::STORE:      return PerformSTORECombine(N, DCI, Subtarget);
18885  case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget);
18886  case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
18887  case ISD::EXTRACT_VECTOR_ELT:
18888    return PerformExtractEltCombine(N, DCI, Subtarget);
18889  case ISD::SIGN_EXTEND_INREG: return PerformSignExtendInregCombine(N, DCI.DAG);
18890  case ISD::INSERT_SUBVECTOR: return PerformInsertSubvectorCombine(N, DCI);
18891  case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
18892  case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI, Subtarget);
18893  case ARMISD::VDUP: return PerformVDUPCombine(N, DCI.DAG, Subtarget);
18894  case ISD::FP_TO_SINT:
18895  case ISD::FP_TO_UINT:
18896    return PerformVCVTCombine(N, DCI.DAG, Subtarget);
18897  case ISD::FADD:
18898    return PerformFADDCombine(N, DCI.DAG, Subtarget);
18899  case ISD::FDIV:
18900    return PerformVDIVCombine(N, DCI.DAG, Subtarget);
18901  case ISD::INTRINSIC_WO_CHAIN:
18902    return PerformIntrinsicCombine(N, DCI);
18903  case ISD::SHL:
18904  case ISD::SRA:
18905  case ISD::SRL:
18906    return PerformShiftCombine(N, DCI, Subtarget);
18907  case ISD::SIGN_EXTEND:
18908  case ISD::ZERO_EXTEND:
18909  case ISD::ANY_EXTEND:
18910    return PerformExtendCombine(N, DCI.DAG, Subtarget);
18911  case ISD::FP_EXTEND:
18912    return PerformFPExtendCombine(N, DCI.DAG, Subtarget);
18913  case ISD::SMIN:
18914  case ISD::UMIN:
18915  case ISD::SMAX:
18916  case ISD::UMAX:
18917    return PerformMinMaxCombine(N, DCI.DAG, Subtarget);
18918  case ARMISD::CMOV:
18919    return PerformCMOVCombine(N, DCI.DAG);
18920  case ARMISD::BRCOND:
18921    return PerformBRCONDCombine(N, DCI.DAG);
18922  case ARMISD::CMPZ:
18923    return PerformCMPZCombine(N, DCI.DAG);
18924  case ARMISD::CSINC:
18925  case ARMISD::CSINV:
18926  case ARMISD::CSNEG:
18927    return PerformCSETCombine(N, DCI.DAG);
18928  case ISD::LOAD:
18929    return PerformLOADCombine(N, DCI, Subtarget);
18930  case ARMISD::VLD1DUP:
18931  case ARMISD::VLD2DUP:
18932  case ARMISD::VLD3DUP:
18933  case ARMISD::VLD4DUP:
18934    return PerformVLDCombine(N, DCI);
18935  case ARMISD::BUILD_VECTOR:
18936    return PerformARMBUILD_VECTORCombine(N, DCI);
18937  case ISD::BITCAST:
18938    return PerformBITCASTCombine(N, DCI, Subtarget);
18939  case ARMISD::PREDICATE_CAST:
18940    return PerformPREDICATE_CASTCombine(N, DCI);
18941  case ARMISD::VECTOR_REG_CAST:
18942    return PerformVECTOR_REG_CASTCombine(N, DCI.DAG, Subtarget);
18943  case ARMISD::MVETRUNC:
18944    return PerformMVETruncCombine(N, DCI);
18945  case ARMISD::MVESEXT:
18946  case ARMISD::MVEZEXT:
18947    return PerformMVEExtCombine(N, DCI);
18948  case ARMISD::VCMP:
18949    return PerformVCMPCombine(N, DCI.DAG, Subtarget);
18950  case ISD::VECREDUCE_ADD:
18951    return PerformVECREDUCE_ADDCombine(N, DCI.DAG, Subtarget);
18952  case ARMISD::VADDVs:
18953  case ARMISD::VADDVu:
18954  case ARMISD::VADDLVs:
18955  case ARMISD::VADDLVu:
18956  case ARMISD::VADDLVAs:
18957  case ARMISD::VADDLVAu:
18958  case ARMISD::VMLAVs:
18959  case ARMISD::VMLAVu:
18960  case ARMISD::VMLALVs:
18961  case ARMISD::VMLALVu:
18962  case ARMISD::VMLALVAs:
18963  case ARMISD::VMLALVAu:
18964    return PerformReduceShuffleCombine(N, DCI.DAG);
18965  case ARMISD::VMOVN:
18966    return PerformVMOVNCombine(N, DCI);
18967  case ARMISD::VQMOVNs:
18968  case ARMISD::VQMOVNu:
18969    return PerformVQMOVNCombine(N, DCI);
18970  case ARMISD::VQDMULH:
18971    return PerformVQDMULHCombine(N, DCI);
18972  case ARMISD::ASRL:
18973  case ARMISD::LSRL:
18974  case ARMISD::LSLL:
18975    return PerformLongShiftCombine(N, DCI.DAG);
18976  case ARMISD::SMULWB: {
18977    unsigned BitWidth = N->getValueType(0).getSizeInBits();
18978    APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16);
18979    if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))
18980      return SDValue();
18981    break;
18982  }
18983  case ARMISD::SMULWT: {
18984    unsigned BitWidth = N->getValueType(0).getSizeInBits();
18985    APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16);
18986    if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))
18987      return SDValue();
18988    break;
18989  }
18990  case ARMISD::SMLALBB:
18991  case ARMISD::QADD16b:
18992  case ARMISD::QSUB16b:
18993  case ARMISD::UQADD16b:
18994  case ARMISD::UQSUB16b: {
18995    unsigned BitWidth = N->getValueType(0).getSizeInBits();
18996    APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16);
18997    if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) ||
18998        (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)))
18999      return SDValue();
19000    break;
19001  }
19002  case ARMISD::SMLALBT: {
19003    unsigned LowWidth = N->getOperand(0).getValueType().getSizeInBits();
19004    APInt LowMask = APInt::getLowBitsSet(LowWidth, 16);
19005    unsigned HighWidth = N->getOperand(1).getValueType().getSizeInBits();
19006    APInt HighMask = APInt::getHighBitsSet(HighWidth, 16);
19007    if ((SimplifyDemandedBits(N->getOperand(0), LowMask, DCI)) ||
19008        (SimplifyDemandedBits(N->getOperand(1), HighMask, DCI)))
19009      return SDValue();
19010    break;
19011  }
19012  case ARMISD::SMLALTB: {
19013    unsigned HighWidth = N->getOperand(0).getValueType().getSizeInBits();
19014    APInt HighMask = APInt::getHighBitsSet(HighWidth, 16);
19015    unsigned LowWidth = N->getOperand(1).getValueType().getSizeInBits();
19016    APInt LowMask = APInt::getLowBitsSet(LowWidth, 16);
19017    if ((SimplifyDemandedBits(N->getOperand(0), HighMask, DCI)) ||
19018        (SimplifyDemandedBits(N->getOperand(1), LowMask, DCI)))
19019      return SDValue();
19020    break;
19021  }
19022  case ARMISD::SMLALTT: {
19023    unsigned BitWidth = N->getValueType(0).getSizeInBits();
19024    APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16);
19025    if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) ||
19026        (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)))
19027      return SDValue();
19028    break;
19029  }
19030  case ARMISD::QADD8b:
19031  case ARMISD::QSUB8b:
19032  case ARMISD::UQADD8b:
19033  case ARMISD::UQSUB8b: {
19034    unsigned BitWidth = N->getValueType(0).getSizeInBits();
19035    APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 8);
19036    if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) ||
19037        (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)))
19038      return SDValue();
19039    break;
19040  }
19041  case ISD::INTRINSIC_VOID:
19042  case ISD::INTRINSIC_W_CHAIN:
19043    switch (N->getConstantOperandVal(1)) {
19044    case Intrinsic::arm_neon_vld1:
19045    case Intrinsic::arm_neon_vld1x2:
19046    case Intrinsic::arm_neon_vld1x3:
19047    case Intrinsic::arm_neon_vld1x4:
19048    case Intrinsic::arm_neon_vld2:
19049    case Intrinsic::arm_neon_vld3:
19050    case Intrinsic::arm_neon_vld4:
19051    case Intrinsic::arm_neon_vld2lane:
19052    case Intrinsic::arm_neon_vld3lane:
19053    case Intrinsic::arm_neon_vld4lane:
19054    case Intrinsic::arm_neon_vld2dup:
19055    case Intrinsic::arm_neon_vld3dup:
19056    case Intrinsic::arm_neon_vld4dup:
19057    case Intrinsic::arm_neon_vst1:
19058    case Intrinsic::arm_neon_vst1x2:
19059    case Intrinsic::arm_neon_vst1x3:
19060    case Intrinsic::arm_neon_vst1x4:
19061    case Intrinsic::arm_neon_vst2:
19062    case Intrinsic::arm_neon_vst3:
19063    case Intrinsic::arm_neon_vst4:
19064    case Intrinsic::arm_neon_vst2lane:
19065    case Intrinsic::arm_neon_vst3lane:
19066    case Intrinsic::arm_neon_vst4lane:
19067      return PerformVLDCombine(N, DCI);
19068    case Intrinsic::arm_mve_vld2q:
19069    case Intrinsic::arm_mve_vld4q:
19070    case Intrinsic::arm_mve_vst2q:
19071    case Intrinsic::arm_mve_vst4q:
19072      return PerformMVEVLDCombine(N, DCI);
19073    default: break;
19074    }
19075    break;
19076  }
19077  return SDValue();
19078}
19079
19080bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
19081                                                          EVT VT) const {
19082  return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
19083}
19084
19085bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, unsigned,
19086                                                       Align Alignment,
19087                                                       MachineMemOperand::Flags,
19088                                                       unsigned *Fast) const {
19089  // Depends what it gets converted into if the type is weird.
19090  if (!VT.isSimple())
19091    return false;
19092
19093  // The AllowsUnaligned flag models the SCTLR.A setting in ARM cpus
19094  bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
19095  auto Ty = VT.getSimpleVT().SimpleTy;
19096
19097  if (Ty == MVT::i8 || Ty == MVT::i16 || Ty == MVT::i32) {
19098    // Unaligned access can use (for example) LRDB, LRDH, LDR
19099    if (AllowsUnaligned) {
19100      if (Fast)
19101        *Fast = Subtarget->hasV7Ops();
19102      return true;
19103    }
19104  }
19105
19106  if (Ty == MVT::f64 || Ty == MVT::v2f64) {
19107    // For any little-endian targets with neon, we can support unaligned ld/st
19108    // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
19109    // A big-endian target may also explicitly support unaligned accesses
19110    if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) {
19111      if (Fast)
19112        *Fast = 1;
19113      return true;
19114    }
19115  }
19116
19117  if (!Subtarget->hasMVEIntegerOps())
19118    return false;
19119
19120  // These are for predicates
19121  if ((Ty == MVT::v16i1 || Ty == MVT::v8i1 || Ty == MVT::v4i1 ||
19122       Ty == MVT::v2i1)) {
19123    if (Fast)
19124      *Fast = 1;
19125    return true;
19126  }
19127
19128  // These are for truncated stores/narrowing loads. They are fine so long as
19129  // the alignment is at least the size of the item being loaded
19130  if ((Ty == MVT::v4i8 || Ty == MVT::v8i8 || Ty == MVT::v4i16) &&
19131      Alignment >= VT.getScalarSizeInBits() / 8) {
19132    if (Fast)
19133      *Fast = true;
19134    return true;
19135  }
19136
19137  // In little-endian MVE, the store instructions VSTRB.U8, VSTRH.U16 and
19138  // VSTRW.U32 all store the vector register in exactly the same format, and
19139  // differ only in the range of their immediate offset field and the required
19140  // alignment. So there is always a store that can be used, regardless of
19141  // actual type.
19142  //
19143  // For big endian, that is not the case. But can still emit a (VSTRB.U8;
19144  // VREV64.8) pair and get the same effect. This will likely be better than
19145  // aligning the vector through the stack.
19146  if (Ty == MVT::v16i8 || Ty == MVT::v8i16 || Ty == MVT::v8f16 ||
19147      Ty == MVT::v4i32 || Ty == MVT::v4f32 || Ty == MVT::v2i64 ||
19148      Ty == MVT::v2f64) {
19149    if (Fast)
19150      *Fast = 1;
19151    return true;
19152  }
19153
19154  return false;
19155}
19156
19157
19158EVT ARMTargetLowering::getOptimalMemOpType(
19159    const MemOp &Op, const AttributeList &FuncAttributes) const {
19160  // See if we can use NEON instructions for this...
19161  if ((Op.isMemcpy() || Op.isZeroMemset()) && Subtarget->hasNEON() &&
19162      !FuncAttributes.hasFnAttr(Attribute::NoImplicitFloat)) {
19163    unsigned Fast;
19164    if (Op.size() >= 16 &&
19165        (Op.isAligned(Align(16)) ||
19166         (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, Align(1),
19167                                         MachineMemOperand::MONone, &Fast) &&
19168          Fast))) {
19169      return MVT::v2f64;
19170    } else if (Op.size() >= 8 &&
19171               (Op.isAligned(Align(8)) ||
19172                (allowsMisalignedMemoryAccesses(
19173                     MVT::f64, 0, Align(1), MachineMemOperand::MONone, &Fast) &&
19174                 Fast))) {
19175      return MVT::f64;
19176    }
19177  }
19178
19179  // Let the target-independent logic figure it out.
19180  return MVT::Other;
19181}
19182
19183// 64-bit integers are split into their high and low parts and held in two
19184// different registers, so the trunc is free since the low register can just
19185// be used.
19186bool ARMTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const {
19187  if (!SrcTy->isIntegerTy() || !DstTy->isIntegerTy())
19188    return false;
19189  unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
19190  unsigned DestBits = DstTy->getPrimitiveSizeInBits();
19191  return (SrcBits == 64 && DestBits == 32);
19192}
19193
19194bool ARMTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const {
19195  if (SrcVT.isVector() || DstVT.isVector() || !SrcVT.isInteger() ||
19196      !DstVT.isInteger())
19197    return false;
19198  unsigned SrcBits = SrcVT.getSizeInBits();
19199  unsigned DestBits = DstVT.getSizeInBits();
19200  return (SrcBits == 64 && DestBits == 32);
19201}
19202
19203bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
19204  if (Val.getOpcode() != ISD::LOAD)
19205    return false;
19206
19207  EVT VT1 = Val.getValueType();
19208  if (!VT1.isSimple() || !VT1.isInteger() ||
19209      !VT2.isSimple() || !VT2.isInteger())
19210    return false;
19211
19212  switch (VT1.getSimpleVT().SimpleTy) {
19213  default: break;
19214  case MVT::i1:
19215  case MVT::i8:
19216  case MVT::i16:
19217    // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
19218    return true;
19219  }
19220
19221  return false;
19222}
19223
19224bool ARMTargetLowering::isFNegFree(EVT VT) const {
19225  if (!VT.isSimple())
19226    return false;
19227
19228  // There are quite a few FP16 instructions (e.g. VNMLA, VNMLS, etc.) that
19229  // negate values directly (fneg is free). So, we don't want to let the DAG
19230  // combiner rewrite fneg into xors and some other instructions.  For f16 and
19231  // FullFP16 argument passing, some bitcast nodes may be introduced,
19232  // triggering this DAG combine rewrite, so we are avoiding that with this.
19233  switch (VT.getSimpleVT().SimpleTy) {
19234  default: break;
19235  case MVT::f16:
19236    return Subtarget->hasFullFP16();
19237  }
19238
19239  return false;
19240}
19241
19242/// Check if Ext1 and Ext2 are extends of the same type, doubling the bitwidth
19243/// of the vector elements.
19244static bool areExtractExts(Value *Ext1, Value *Ext2) {
19245  auto areExtDoubled = [](Instruction *Ext) {
19246    return Ext->getType()->getScalarSizeInBits() ==
19247           2 * Ext->getOperand(0)->getType()->getScalarSizeInBits();
19248  };
19249
19250  if (!match(Ext1, m_ZExtOrSExt(m_Value())) ||
19251      !match(Ext2, m_ZExtOrSExt(m_Value())) ||
19252      !areExtDoubled(cast<Instruction>(Ext1)) ||
19253      !areExtDoubled(cast<Instruction>(Ext2)))
19254    return false;
19255
19256  return true;
19257}
19258
19259/// Check if sinking \p I's operands to I's basic block is profitable, because
19260/// the operands can be folded into a target instruction, e.g.
19261/// sext/zext can be folded into vsubl.
19262bool ARMTargetLowering::shouldSinkOperands(Instruction *I,
19263                                           SmallVectorImpl<Use *> &Ops) const {
19264  if (!I->getType()->isVectorTy())
19265    return false;
19266
19267  if (Subtarget->hasNEON()) {
19268    switch (I->getOpcode()) {
19269    case Instruction::Sub:
19270    case Instruction::Add: {
19271      if (!areExtractExts(I->getOperand(0), I->getOperand(1)))
19272        return false;
19273      Ops.push_back(&I->getOperandUse(0));
19274      Ops.push_back(&I->getOperandUse(1));
19275      return true;
19276    }
19277    default:
19278      return false;
19279    }
19280  }
19281
19282  if (!Subtarget->hasMVEIntegerOps())
19283    return false;
19284
19285  auto IsFMSMul = [&](Instruction *I) {
19286    if (!I->hasOneUse())
19287      return false;
19288    auto *Sub = cast<Instruction>(*I->users().begin());
19289    return Sub->getOpcode() == Instruction::FSub && Sub->getOperand(1) == I;
19290  };
19291  auto IsFMS = [&](Instruction *I) {
19292    if (match(I->getOperand(0), m_FNeg(m_Value())) ||
19293        match(I->getOperand(1), m_FNeg(m_Value())))
19294      return true;
19295    return false;
19296  };
19297
19298  auto IsSinker = [&](Instruction *I, int Operand) {
19299    switch (I->getOpcode()) {
19300    case Instruction::Add:
19301    case Instruction::Mul:
19302    case Instruction::FAdd:
19303    case Instruction::ICmp:
19304    case Instruction::FCmp:
19305      return true;
19306    case Instruction::FMul:
19307      return !IsFMSMul(I);
19308    case Instruction::Sub:
19309    case Instruction::FSub:
19310    case Instruction::Shl:
19311    case Instruction::LShr:
19312    case Instruction::AShr:
19313      return Operand == 1;
19314    case Instruction::Call:
19315      if (auto *II = dyn_cast<IntrinsicInst>(I)) {
19316        switch (II->getIntrinsicID()) {
19317        case Intrinsic::fma:
19318          return !IsFMS(I);
19319        case Intrinsic::sadd_sat:
19320        case Intrinsic::uadd_sat:
19321        case Intrinsic::arm_mve_add_predicated:
19322        case Intrinsic::arm_mve_mul_predicated:
19323        case Intrinsic::arm_mve_qadd_predicated:
19324        case Intrinsic::arm_mve_vhadd:
19325        case Intrinsic::arm_mve_hadd_predicated:
19326        case Intrinsic::arm_mve_vqdmull:
19327        case Intrinsic::arm_mve_vqdmull_predicated:
19328        case Intrinsic::arm_mve_vqdmulh:
19329        case Intrinsic::arm_mve_qdmulh_predicated:
19330        case Intrinsic::arm_mve_vqrdmulh:
19331        case Intrinsic::arm_mve_qrdmulh_predicated:
19332        case Intrinsic::arm_mve_fma_predicated:
19333          return true;
19334        case Intrinsic::ssub_sat:
19335        case Intrinsic::usub_sat:
19336        case Intrinsic::arm_mve_sub_predicated:
19337        case Intrinsic::arm_mve_qsub_predicated:
19338        case Intrinsic::arm_mve_hsub_predicated:
19339        case Intrinsic::arm_mve_vhsub:
19340          return Operand == 1;
19341        default:
19342          return false;
19343        }
19344      }
19345      return false;
19346    default:
19347      return false;
19348    }
19349  };
19350
19351  for (auto OpIdx : enumerate(I->operands())) {
19352    Instruction *Op = dyn_cast<Instruction>(OpIdx.value().get());
19353    // Make sure we are not already sinking this operand
19354    if (!Op || any_of(Ops, [&](Use *U) { return U->get() == Op; }))
19355      continue;
19356
19357    Instruction *Shuffle = Op;
19358    if (Shuffle->getOpcode() == Instruction::BitCast)
19359      Shuffle = dyn_cast<Instruction>(Shuffle->getOperand(0));
19360    // We are looking for a splat that can be sunk.
19361    if (!Shuffle ||
19362        !match(Shuffle, m_Shuffle(
19363                            m_InsertElt(m_Undef(), m_Value(), m_ZeroInt()),
19364                            m_Undef(), m_ZeroMask())))
19365      continue;
19366    if (!IsSinker(I, OpIdx.index()))
19367      continue;
19368
19369    // All uses of the shuffle should be sunk to avoid duplicating it across gpr
19370    // and vector registers
19371    for (Use &U : Op->uses()) {
19372      Instruction *Insn = cast<Instruction>(U.getUser());
19373      if (!IsSinker(Insn, U.getOperandNo()))
19374        return false;
19375    }
19376
19377    Ops.push_back(&Shuffle->getOperandUse(0));
19378    if (Shuffle != Op)
19379      Ops.push_back(&Op->getOperandUse(0));
19380    Ops.push_back(&OpIdx.value());
19381  }
19382  return true;
19383}
19384
19385Type *ARMTargetLowering::shouldConvertSplatType(ShuffleVectorInst *SVI) const {
19386  if (!Subtarget->hasMVEIntegerOps())
19387    return nullptr;
19388  Type *SVIType = SVI->getType();
19389  Type *ScalarType = SVIType->getScalarType();
19390
19391  if (ScalarType->isFloatTy())
19392    return Type::getInt32Ty(SVIType->getContext());
19393  if (ScalarType->isHalfTy())
19394    return Type::getInt16Ty(SVIType->getContext());
19395  return nullptr;
19396}
19397
19398bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
19399  EVT VT = ExtVal.getValueType();
19400
19401  if (!isTypeLegal(VT))
19402    return false;
19403
19404  if (auto *Ld = dyn_cast<MaskedLoadSDNode>(ExtVal.getOperand(0))) {
19405    if (Ld->isExpandingLoad())
19406      return false;
19407  }
19408
19409  if (Subtarget->hasMVEIntegerOps())
19410    return true;
19411
19412  // Don't create a loadext if we can fold the extension into a wide/long
19413  // instruction.
19414  // If there's more than one user instruction, the loadext is desirable no
19415  // matter what.  There can be two uses by the same instruction.
19416  if (ExtVal->use_empty() ||
19417      !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode()))
19418    return true;
19419
19420  SDNode *U = *ExtVal->use_begin();
19421  if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB ||
19422       U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHLIMM))
19423    return false;
19424
19425  return true;
19426}
19427
19428bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
19429  if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
19430    return false;
19431
19432  if (!isTypeLegal(EVT::getEVT(Ty1)))
19433    return false;
19434
19435  assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
19436
19437  // Assuming the caller doesn't have a zeroext or signext return parameter,
19438  // truncation all the way down to i1 is valid.
19439  return true;
19440}
19441
19442/// isFMAFasterThanFMulAndFAdd - Return true if an FMA operation is faster
19443/// than a pair of fmul and fadd instructions. fmuladd intrinsics will be
19444/// expanded to FMAs when this method returns true, otherwise fmuladd is
19445/// expanded to fmul + fadd.
19446///
19447/// ARM supports both fused and unfused multiply-add operations; we already
19448/// lower a pair of fmul and fadd to the latter so it's not clear that there
19449/// would be a gain or that the gain would be worthwhile enough to risk
19450/// correctness bugs.
19451///
19452/// For MVE, we set this to true as it helps simplify the need for some
19453/// patterns (and we don't have the non-fused floating point instruction).
19454bool ARMTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
19455                                                   EVT VT) const {
19456  if (!VT.isSimple())
19457    return false;
19458
19459  switch (VT.getSimpleVT().SimpleTy) {
19460  case MVT::v4f32:
19461  case MVT::v8f16:
19462    return Subtarget->hasMVEFloatOps();
19463  case MVT::f16:
19464    return Subtarget->useFPVFMx16();
19465  case MVT::f32:
19466    return Subtarget->useFPVFMx();
19467  case MVT::f64:
19468    return Subtarget->useFPVFMx64();
19469  default:
19470    break;
19471  }
19472
19473  return false;
19474}
19475
19476static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
19477  if (V < 0)
19478    return false;
19479
19480  unsigned Scale = 1;
19481  switch (VT.getSimpleVT().SimpleTy) {
19482  case MVT::i1:
19483  case MVT::i8:
19484    // Scale == 1;
19485    break;
19486  case MVT::i16:
19487    // Scale == 2;
19488    Scale = 2;
19489    break;
19490  default:
19491    // On thumb1 we load most things (i32, i64, floats, etc) with a LDR
19492    // Scale == 4;
19493    Scale = 4;
19494    break;
19495  }
19496
19497  if ((V & (Scale - 1)) != 0)
19498    return false;
19499  return isUInt<5>(V / Scale);
19500}
19501
19502static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
19503                                      const ARMSubtarget *Subtarget) {
19504  if (!VT.isInteger() && !VT.isFloatingPoint())
19505    return false;
19506  if (VT.isVector() && Subtarget->hasNEON())
19507    return false;
19508  if (VT.isVector() && VT.isFloatingPoint() && Subtarget->hasMVEIntegerOps() &&
19509      !Subtarget->hasMVEFloatOps())
19510    return false;
19511
19512  bool IsNeg = false;
19513  if (V < 0) {
19514    IsNeg = true;
19515    V = -V;
19516  }
19517
19518  unsigned NumBytes = std::max((unsigned)VT.getSizeInBits() / 8, 1U);
19519
19520  // MVE: size * imm7
19521  if (VT.isVector() && Subtarget->hasMVEIntegerOps()) {
19522    switch (VT.getSimpleVT().getVectorElementType().SimpleTy) {
19523    case MVT::i32:
19524    case MVT::f32:
19525      return isShiftedUInt<7,2>(V);
19526    case MVT::i16:
19527    case MVT::f16:
19528      return isShiftedUInt<7,1>(V);
19529    case MVT::i8:
19530      return isUInt<7>(V);
19531    default:
19532      return false;
19533    }
19534  }
19535
19536  // half VLDR: 2 * imm8
19537  if (VT.isFloatingPoint() && NumBytes == 2 && Subtarget->hasFPRegs16())
19538    return isShiftedUInt<8, 1>(V);
19539  // VLDR and LDRD: 4 * imm8
19540  if ((VT.isFloatingPoint() && Subtarget->hasVFP2Base()) || NumBytes == 8)
19541    return isShiftedUInt<8, 2>(V);
19542
19543  if (NumBytes == 1 || NumBytes == 2 || NumBytes == 4) {
19544    // + imm12 or - imm8
19545    if (IsNeg)
19546      return isUInt<8>(V);
19547    return isUInt<12>(V);
19548  }
19549
19550  return false;
19551}
19552
19553/// isLegalAddressImmediate - Return true if the integer value can be used
19554/// as the offset of the target addressing mode for load / store of the
19555/// given type.
19556static bool isLegalAddressImmediate(int64_t V, EVT VT,
19557                                    const ARMSubtarget *Subtarget) {
19558  if (V == 0)
19559    return true;
19560
19561  if (!VT.isSimple())
19562    return false;
19563
19564  if (Subtarget->isThumb1Only())
19565    return isLegalT1AddressImmediate(V, VT);
19566  else if (Subtarget->isThumb2())
19567    return isLegalT2AddressImmediate(V, VT, Subtarget);
19568
19569  // ARM mode.
19570  if (V < 0)
19571    V = - V;
19572  switch (VT.getSimpleVT().SimpleTy) {
19573  default: return false;
19574  case MVT::i1:
19575  case MVT::i8:
19576  case MVT::i32:
19577    // +- imm12
19578    return isUInt<12>(V);
19579  case MVT::i16:
19580    // +- imm8
19581    return isUInt<8>(V);
19582  case MVT::f32:
19583  case MVT::f64:
19584    if (!Subtarget->hasVFP2Base()) // FIXME: NEON?
19585      return false;
19586    return isShiftedUInt<8, 2>(V);
19587  }
19588}
19589
19590bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
19591                                                      EVT VT) const {
19592  int Scale = AM.Scale;
19593  if (Scale < 0)
19594    return false;
19595
19596  switch (VT.getSimpleVT().SimpleTy) {
19597  default: return false;
19598  case MVT::i1:
19599  case MVT::i8:
19600  case MVT::i16:
19601  case MVT::i32:
19602    if (Scale == 1)
19603      return true;
19604    // r + r << imm
19605    Scale = Scale & ~1;
19606    return Scale == 2 || Scale == 4 || Scale == 8;
19607  case MVT::i64:
19608    // FIXME: What are we trying to model here? ldrd doesn't have an r + r
19609    // version in Thumb mode.
19610    // r + r
19611    if (Scale == 1)
19612      return true;
19613    // r * 2 (this can be lowered to r + r).
19614    if (!AM.HasBaseReg && Scale == 2)
19615      return true;
19616    return false;
19617  case MVT::isVoid:
19618    // Note, we allow "void" uses (basically, uses that aren't loads or
19619    // stores), because arm allows folding a scale into many arithmetic
19620    // operations.  This should be made more precise and revisited later.
19621
19622    // Allow r << imm, but the imm has to be a multiple of two.
19623    if (Scale & 1) return false;
19624    return isPowerOf2_32(Scale);
19625  }
19626}
19627
19628bool ARMTargetLowering::isLegalT1ScaledAddressingMode(const AddrMode &AM,
19629                                                      EVT VT) const {
19630  const int Scale = AM.Scale;
19631
19632  // Negative scales are not supported in Thumb1.
19633  if (Scale < 0)
19634    return false;
19635
19636  // Thumb1 addressing modes do not support register scaling excepting the
19637  // following cases:
19638  // 1. Scale == 1 means no scaling.
19639  // 2. Scale == 2 this can be lowered to r + r if there is no base register.
19640  return (Scale == 1) || (!AM.HasBaseReg && Scale == 2);
19641}
19642
19643/// isLegalAddressingMode - Return true if the addressing mode represented
19644/// by AM is legal for this target, for a load/store of the specified type.
19645bool ARMTargetLowering::isLegalAddressingMode(const DataLayout &DL,
19646                                              const AddrMode &AM, Type *Ty,
19647                                              unsigned AS, Instruction *I) const {
19648  EVT VT = getValueType(DL, Ty, true);
19649  if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
19650    return false;
19651
19652  // Can never fold addr of global into load/store.
19653  if (AM.BaseGV)
19654    return false;
19655
19656  switch (AM.Scale) {
19657  case 0:  // no scale reg, must be "r+i" or "r", or "i".
19658    break;
19659  default:
19660    // ARM doesn't support any R+R*scale+imm addr modes.
19661    if (AM.BaseOffs)
19662      return false;
19663
19664    if (!VT.isSimple())
19665      return false;
19666
19667    if (Subtarget->isThumb1Only())
19668      return isLegalT1ScaledAddressingMode(AM, VT);
19669
19670    if (Subtarget->isThumb2())
19671      return isLegalT2ScaledAddressingMode(AM, VT);
19672
19673    int Scale = AM.Scale;
19674    switch (VT.getSimpleVT().SimpleTy) {
19675    default: return false;
19676    case MVT::i1:
19677    case MVT::i8:
19678    case MVT::i32:
19679      if (Scale < 0) Scale = -Scale;
19680      if (Scale == 1)
19681        return true;
19682      // r + r << imm
19683      return isPowerOf2_32(Scale & ~1);
19684    case MVT::i16:
19685    case MVT::i64:
19686      // r +/- r
19687      if (Scale == 1 || (AM.HasBaseReg && Scale == -1))
19688        return true;
19689      // r * 2 (this can be lowered to r + r).
19690      if (!AM.HasBaseReg && Scale == 2)
19691        return true;
19692      return false;
19693
19694    case MVT::isVoid:
19695      // Note, we allow "void" uses (basically, uses that aren't loads or
19696      // stores), because arm allows folding a scale into many arithmetic
19697      // operations.  This should be made more precise and revisited later.
19698
19699      // Allow r << imm, but the imm has to be a multiple of two.
19700      if (Scale & 1) return false;
19701      return isPowerOf2_32(Scale);
19702    }
19703  }
19704  return true;
19705}
19706
19707/// isLegalICmpImmediate - Return true if the specified immediate is legal
19708/// icmp immediate, that is the target has icmp instructions which can compare
19709/// a register against the immediate without having to materialize the
19710/// immediate into a register.
19711bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
19712  // Thumb2 and ARM modes can use cmn for negative immediates.
19713  if (!Subtarget->isThumb())
19714    return ARM_AM::getSOImmVal((uint32_t)Imm) != -1 ||
19715           ARM_AM::getSOImmVal(-(uint32_t)Imm) != -1;
19716  if (Subtarget->isThumb2())
19717    return ARM_AM::getT2SOImmVal((uint32_t)Imm) != -1 ||
19718           ARM_AM::getT2SOImmVal(-(uint32_t)Imm) != -1;
19719  // Thumb1 doesn't have cmn, and only 8-bit immediates.
19720  return Imm >= 0 && Imm <= 255;
19721}
19722
19723/// isLegalAddImmediate - Return true if the specified immediate is a legal add
19724/// *or sub* immediate, that is the target has add or sub instructions which can
19725/// add a register with the immediate without having to materialize the
19726/// immediate into a register.
19727bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
19728  // Same encoding for add/sub, just flip the sign.
19729  int64_t AbsImm = std::abs(Imm);
19730  if (!Subtarget->isThumb())
19731    return ARM_AM::getSOImmVal(AbsImm) != -1;
19732  if (Subtarget->isThumb2())
19733    return ARM_AM::getT2SOImmVal(AbsImm) != -1;
19734  // Thumb1 only has 8-bit unsigned immediate.
19735  return AbsImm >= 0 && AbsImm <= 255;
19736}
19737
19738// Return false to prevent folding
19739// (mul (add r, c0), c1) -> (add (mul r, c1), c0*c1) in DAGCombine,
19740// if the folding leads to worse code.
19741bool ARMTargetLowering::isMulAddWithConstProfitable(SDValue AddNode,
19742                                                    SDValue ConstNode) const {
19743  // Let the DAGCombiner decide for vector types and large types.
19744  const EVT VT = AddNode.getValueType();
19745  if (VT.isVector() || VT.getScalarSizeInBits() > 32)
19746    return true;
19747
19748  // It is worse if c0 is legal add immediate, while c1*c0 is not
19749  // and has to be composed by at least two instructions.
19750  const ConstantSDNode *C0Node = cast<ConstantSDNode>(AddNode.getOperand(1));
19751  const ConstantSDNode *C1Node = cast<ConstantSDNode>(ConstNode);
19752  const int64_t C0 = C0Node->getSExtValue();
19753  APInt CA = C0Node->getAPIntValue() * C1Node->getAPIntValue();
19754  if (!isLegalAddImmediate(C0) || isLegalAddImmediate(CA.getSExtValue()))
19755    return true;
19756  if (ConstantMaterializationCost((unsigned)CA.getZExtValue(), Subtarget) > 1)
19757    return false;
19758
19759  // Default to true and let the DAGCombiner decide.
19760  return true;
19761}
19762
19763static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
19764                                      bool isSEXTLoad, SDValue &Base,
19765                                      SDValue &Offset, bool &isInc,
19766                                      SelectionDAG &DAG) {
19767  if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
19768    return false;
19769
19770  if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
19771    // AddressingMode 3
19772    Base = Ptr->getOperand(0);
19773    if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
19774      int RHSC = (int)RHS->getZExtValue();
19775      if (RHSC < 0 && RHSC > -256) {
19776        assert(Ptr->getOpcode() == ISD::ADD);
19777        isInc = false;
19778        Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
19779        return true;
19780      }
19781    }
19782    isInc = (Ptr->getOpcode() == ISD::ADD);
19783    Offset = Ptr->getOperand(1);
19784    return true;
19785  } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
19786    // AddressingMode 2
19787    if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
19788      int RHSC = (int)RHS->getZExtValue();
19789      if (RHSC < 0 && RHSC > -0x1000) {
19790        assert(Ptr->getOpcode() == ISD::ADD);
19791        isInc = false;
19792        Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
19793        Base = Ptr->getOperand(0);
19794        return true;
19795      }
19796    }
19797
19798    if (Ptr->getOpcode() == ISD::ADD) {
19799      isInc = true;
19800      ARM_AM::ShiftOpc ShOpcVal=
19801        ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
19802      if (ShOpcVal != ARM_AM::no_shift) {
19803        Base = Ptr->getOperand(1);
19804        Offset = Ptr->getOperand(0);
19805      } else {
19806        Base = Ptr->getOperand(0);
19807        Offset = Ptr->getOperand(1);
19808      }
19809      return true;
19810    }
19811
19812    isInc = (Ptr->getOpcode() == ISD::ADD);
19813    Base = Ptr->getOperand(0);
19814    Offset = Ptr->getOperand(1);
19815    return true;
19816  }
19817
19818  // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
19819  return false;
19820}
19821
19822static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
19823                                     bool isSEXTLoad, SDValue &Base,
19824                                     SDValue &Offset, bool &isInc,
19825                                     SelectionDAG &DAG) {
19826  if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
19827    return false;
19828
19829  Base = Ptr->getOperand(0);
19830  if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
19831    int RHSC = (int)RHS->getZExtValue();
19832    if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
19833      assert(Ptr->getOpcode() == ISD::ADD);
19834      isInc = false;
19835      Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
19836      return true;
19837    } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
19838      isInc = Ptr->getOpcode() == ISD::ADD;
19839      Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0));
19840      return true;
19841    }
19842  }
19843
19844  return false;
19845}
19846
19847static bool getMVEIndexedAddressParts(SDNode *Ptr, EVT VT, Align Alignment,
19848                                      bool isSEXTLoad, bool IsMasked, bool isLE,
19849                                      SDValue &Base, SDValue &Offset,
19850                                      bool &isInc, SelectionDAG &DAG) {
19851  if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
19852    return false;
19853  if (!isa<ConstantSDNode>(Ptr->getOperand(1)))
19854    return false;
19855
19856  // We allow LE non-masked loads to change the type (for example use a vldrb.8
19857  // as opposed to a vldrw.32). This can allow extra addressing modes or
19858  // alignments for what is otherwise an equivalent instruction.
19859  bool CanChangeType = isLE && !IsMasked;
19860
19861  ConstantSDNode *RHS = cast<ConstantSDNode>(Ptr->getOperand(1));
19862  int RHSC = (int)RHS->getZExtValue();
19863
19864  auto IsInRange = [&](int RHSC, int Limit, int Scale) {
19865    if (RHSC < 0 && RHSC > -Limit * Scale && RHSC % Scale == 0) {
19866      assert(Ptr->getOpcode() == ISD::ADD);
19867      isInc = false;
19868      Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
19869      return true;
19870    } else if (RHSC > 0 && RHSC < Limit * Scale && RHSC % Scale == 0) {
19871      isInc = Ptr->getOpcode() == ISD::ADD;
19872      Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0));
19873      return true;
19874    }
19875    return false;
19876  };
19877
19878  // Try to find a matching instruction based on s/zext, Alignment, Offset and
19879  // (in BE/masked) type.
19880  Base = Ptr->getOperand(0);
19881  if (VT == MVT::v4i16) {
19882    if (Alignment >= 2 && IsInRange(RHSC, 0x80, 2))
19883      return true;
19884  } else if (VT == MVT::v4i8 || VT == MVT::v8i8) {
19885    if (IsInRange(RHSC, 0x80, 1))
19886      return true;
19887  } else if (Alignment >= 4 &&
19888             (CanChangeType || VT == MVT::v4i32 || VT == MVT::v4f32) &&
19889             IsInRange(RHSC, 0x80, 4))
19890    return true;
19891  else if (Alignment >= 2 &&
19892           (CanChangeType || VT == MVT::v8i16 || VT == MVT::v8f16) &&
19893           IsInRange(RHSC, 0x80, 2))
19894    return true;
19895  else if ((CanChangeType || VT == MVT::v16i8) && IsInRange(RHSC, 0x80, 1))
19896    return true;
19897  return false;
19898}
19899
19900/// getPreIndexedAddressParts - returns true by value, base pointer and
19901/// offset pointer and addressing mode by reference if the node's address
19902/// can be legally represented as pre-indexed load / store address.
19903bool
19904ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
19905                                             SDValue &Offset,
19906                                             ISD::MemIndexedMode &AM,
19907                                             SelectionDAG &DAG) const {
19908  if (Subtarget->isThumb1Only())
19909    return false;
19910
19911  EVT VT;
19912  SDValue Ptr;
19913  Align Alignment;
19914  bool isSEXTLoad = false;
19915  bool IsMasked = false;
19916  if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
19917    Ptr = LD->getBasePtr();
19918    VT = LD->getMemoryVT();
19919    Alignment = LD->getAlign();
19920    isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
19921  } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
19922    Ptr = ST->getBasePtr();
19923    VT = ST->getMemoryVT();
19924    Alignment = ST->getAlign();
19925  } else if (MaskedLoadSDNode *LD = dyn_cast<MaskedLoadSDNode>(N)) {
19926    Ptr = LD->getBasePtr();
19927    VT = LD->getMemoryVT();
19928    Alignment = LD->getAlign();
19929    isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
19930    IsMasked = true;
19931  } else if (MaskedStoreSDNode *ST = dyn_cast<MaskedStoreSDNode>(N)) {
19932    Ptr = ST->getBasePtr();
19933    VT = ST->getMemoryVT();
19934    Alignment = ST->getAlign();
19935    IsMasked = true;
19936  } else
19937    return false;
19938
19939  bool isInc;
19940  bool isLegal = false;
19941  if (VT.isVector())
19942    isLegal = Subtarget->hasMVEIntegerOps() &&
19943              getMVEIndexedAddressParts(
19944                  Ptr.getNode(), VT, Alignment, isSEXTLoad, IsMasked,
19945                  Subtarget->isLittle(), Base, Offset, isInc, DAG);
19946  else {
19947    if (Subtarget->isThumb2())
19948      isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
19949                                         Offset, isInc, DAG);
19950    else
19951      isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
19952                                          Offset, isInc, DAG);
19953  }
19954  if (!isLegal)
19955    return false;
19956
19957  AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
19958  return true;
19959}
19960
19961/// getPostIndexedAddressParts - returns true by value, base pointer and
19962/// offset pointer and addressing mode by reference if this node can be
19963/// combined with a load / store to form a post-indexed load / store.
19964bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
19965                                                   SDValue &Base,
19966                                                   SDValue &Offset,
19967                                                   ISD::MemIndexedMode &AM,
19968                                                   SelectionDAG &DAG) const {
19969  EVT VT;
19970  SDValue Ptr;
19971  Align Alignment;
19972  bool isSEXTLoad = false, isNonExt;
19973  bool IsMasked = false;
19974  if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
19975    VT = LD->getMemoryVT();
19976    Ptr = LD->getBasePtr();
19977    Alignment = LD->getAlign();
19978    isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
19979    isNonExt = LD->getExtensionType() == ISD::NON_EXTLOAD;
19980  } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
19981    VT = ST->getMemoryVT();
19982    Ptr = ST->getBasePtr();
19983    Alignment = ST->getAlign();
19984    isNonExt = !ST->isTruncatingStore();
19985  } else if (MaskedLoadSDNode *LD = dyn_cast<MaskedLoadSDNode>(N)) {
19986    VT = LD->getMemoryVT();
19987    Ptr = LD->getBasePtr();
19988    Alignment = LD->getAlign();
19989    isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
19990    isNonExt = LD->getExtensionType() == ISD::NON_EXTLOAD;
19991    IsMasked = true;
19992  } else if (MaskedStoreSDNode *ST = dyn_cast<MaskedStoreSDNode>(N)) {
19993    VT = ST->getMemoryVT();
19994    Ptr = ST->getBasePtr();
19995    Alignment = ST->getAlign();
19996    isNonExt = !ST->isTruncatingStore();
19997    IsMasked = true;
19998  } else
19999    return false;
20000
20001  if (Subtarget->isThumb1Only()) {
20002    // Thumb-1 can do a limited post-inc load or store as an updating LDM. It
20003    // must be non-extending/truncating, i32, with an offset of 4.
20004    assert(Op->getValueType(0) == MVT::i32 && "Non-i32 post-inc op?!");
20005    if (Op->getOpcode() != ISD::ADD || !isNonExt)
20006      return false;
20007    auto *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1));
20008    if (!RHS || RHS->getZExtValue() != 4)
20009      return false;
20010    if (Alignment < Align(4))
20011      return false;
20012
20013    Offset = Op->getOperand(1);
20014    Base = Op->getOperand(0);
20015    AM = ISD::POST_INC;
20016    return true;
20017  }
20018
20019  bool isInc;
20020  bool isLegal = false;
20021  if (VT.isVector())
20022    isLegal = Subtarget->hasMVEIntegerOps() &&
20023              getMVEIndexedAddressParts(Op, VT, Alignment, isSEXTLoad, IsMasked,
20024                                        Subtarget->isLittle(), Base, Offset,
20025                                        isInc, DAG);
20026  else {
20027    if (Subtarget->isThumb2())
20028      isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
20029                                         isInc, DAG);
20030    else
20031      isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
20032                                          isInc, DAG);
20033  }
20034  if (!isLegal)
20035    return false;
20036
20037  if (Ptr != Base) {
20038    // Swap base ptr and offset to catch more post-index load / store when
20039    // it's legal. In Thumb2 mode, offset must be an immediate.
20040    if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
20041        !Subtarget->isThumb2())
20042      std::swap(Base, Offset);
20043
20044    // Post-indexed load / store update the base pointer.
20045    if (Ptr != Base)
20046      return false;
20047  }
20048
20049  AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
20050  return true;
20051}
20052
20053void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
20054                                                      KnownBits &Known,
20055                                                      const APInt &DemandedElts,
20056                                                      const SelectionDAG &DAG,
20057                                                      unsigned Depth) const {
20058  unsigned BitWidth = Known.getBitWidth();
20059  Known.resetAll();
20060  switch (Op.getOpcode()) {
20061  default: break;
20062  case ARMISD::ADDC:
20063  case ARMISD::ADDE:
20064  case ARMISD::SUBC:
20065  case ARMISD::SUBE:
20066    // Special cases when we convert a carry to a boolean.
20067    if (Op.getResNo() == 0) {
20068      SDValue LHS = Op.getOperand(0);
20069      SDValue RHS = Op.getOperand(1);
20070      // (ADDE 0, 0, C) will give us a single bit.
20071      if (Op->getOpcode() == ARMISD::ADDE && isNullConstant(LHS) &&
20072          isNullConstant(RHS)) {
20073        Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
20074        return;
20075      }
20076    }
20077    break;
20078  case ARMISD::CMOV: {
20079    // Bits are known zero/one if known on the LHS and RHS.
20080    Known = DAG.computeKnownBits(Op.getOperand(0), Depth+1);
20081    if (Known.isUnknown())
20082      return;
20083
20084    KnownBits KnownRHS = DAG.computeKnownBits(Op.getOperand(1), Depth+1);
20085    Known = Known.intersectWith(KnownRHS);
20086    return;
20087  }
20088  case ISD::INTRINSIC_W_CHAIN: {
20089    Intrinsic::ID IntID =
20090        static_cast<Intrinsic::ID>(Op->getConstantOperandVal(1));
20091    switch (IntID) {
20092    default: return;
20093    case Intrinsic::arm_ldaex:
20094    case Intrinsic::arm_ldrex: {
20095      EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
20096      unsigned MemBits = VT.getScalarSizeInBits();
20097      Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
20098      return;
20099    }
20100    }
20101  }
20102  case ARMISD::BFI: {
20103    // Conservatively, we can recurse down the first operand
20104    // and just mask out all affected bits.
20105    Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
20106
20107    // The operand to BFI is already a mask suitable for removing the bits it
20108    // sets.
20109    const APInt &Mask = Op.getConstantOperandAPInt(2);
20110    Known.Zero &= Mask;
20111    Known.One &= Mask;
20112    return;
20113  }
20114  case ARMISD::VGETLANEs:
20115  case ARMISD::VGETLANEu: {
20116    const SDValue &SrcSV = Op.getOperand(0);
20117    EVT VecVT = SrcSV.getValueType();
20118    assert(VecVT.isVector() && "VGETLANE expected a vector type");
20119    const unsigned NumSrcElts = VecVT.getVectorNumElements();
20120    ConstantSDNode *Pos = cast<ConstantSDNode>(Op.getOperand(1).getNode());
20121    assert(Pos->getAPIntValue().ult(NumSrcElts) &&
20122           "VGETLANE index out of bounds");
20123    unsigned Idx = Pos->getZExtValue();
20124    APInt DemandedElt = APInt::getOneBitSet(NumSrcElts, Idx);
20125    Known = DAG.computeKnownBits(SrcSV, DemandedElt, Depth + 1);
20126
20127    EVT VT = Op.getValueType();
20128    const unsigned DstSz = VT.getScalarSizeInBits();
20129    const unsigned SrcSz = VecVT.getVectorElementType().getSizeInBits();
20130    (void)SrcSz;
20131    assert(SrcSz == Known.getBitWidth());
20132    assert(DstSz > SrcSz);
20133    if (Op.getOpcode() == ARMISD::VGETLANEs)
20134      Known = Known.sext(DstSz);
20135    else {
20136      Known = Known.zext(DstSz);
20137    }
20138    assert(DstSz == Known.getBitWidth());
20139    break;
20140  }
20141  case ARMISD::VMOVrh: {
20142    KnownBits KnownOp = DAG.computeKnownBits(Op->getOperand(0), Depth + 1);
20143    assert(KnownOp.getBitWidth() == 16);
20144    Known = KnownOp.zext(32);
20145    break;
20146  }
20147  case ARMISD::CSINC:
20148  case ARMISD::CSINV:
20149  case ARMISD::CSNEG: {
20150    KnownBits KnownOp0 = DAG.computeKnownBits(Op->getOperand(0), Depth + 1);
20151    KnownBits KnownOp1 = DAG.computeKnownBits(Op->getOperand(1), Depth + 1);
20152
20153    // The result is either:
20154    // CSINC: KnownOp0 or KnownOp1 + 1
20155    // CSINV: KnownOp0 or ~KnownOp1
20156    // CSNEG: KnownOp0 or KnownOp1 * -1
20157    if (Op.getOpcode() == ARMISD::CSINC)
20158      KnownOp1 = KnownBits::computeForAddSub(
20159          true, false, KnownOp1, KnownBits::makeConstant(APInt(32, 1)));
20160    else if (Op.getOpcode() == ARMISD::CSINV)
20161      std::swap(KnownOp1.Zero, KnownOp1.One);
20162    else if (Op.getOpcode() == ARMISD::CSNEG)
20163      KnownOp1 = KnownBits::mul(
20164          KnownOp1, KnownBits::makeConstant(APInt(32, -1)));
20165
20166    Known = KnownOp0.intersectWith(KnownOp1);
20167    break;
20168  }
20169  }
20170}
20171
20172bool ARMTargetLowering::targetShrinkDemandedConstant(
20173    SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
20174    TargetLoweringOpt &TLO) const {
20175  // Delay optimization, so we don't have to deal with illegal types, or block
20176  // optimizations.
20177  if (!TLO.LegalOps)
20178    return false;
20179
20180  // Only optimize AND for now.
20181  if (Op.getOpcode() != ISD::AND)
20182    return false;
20183
20184  EVT VT = Op.getValueType();
20185
20186  // Ignore vectors.
20187  if (VT.isVector())
20188    return false;
20189
20190  assert(VT == MVT::i32 && "Unexpected integer type");
20191
20192  // Make sure the RHS really is a constant.
20193  ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
20194  if (!C)
20195    return false;
20196
20197  unsigned Mask = C->getZExtValue();
20198
20199  unsigned Demanded = DemandedBits.getZExtValue();
20200  unsigned ShrunkMask = Mask & Demanded;
20201  unsigned ExpandedMask = Mask | ~Demanded;
20202
20203  // If the mask is all zeros, let the target-independent code replace the
20204  // result with zero.
20205  if (ShrunkMask == 0)
20206    return false;
20207
20208  // If the mask is all ones, erase the AND. (Currently, the target-independent
20209  // code won't do this, so we have to do it explicitly to avoid an infinite
20210  // loop in obscure cases.)
20211  if (ExpandedMask == ~0U)
20212    return TLO.CombineTo(Op, Op.getOperand(0));
20213
20214  auto IsLegalMask = [ShrunkMask, ExpandedMask](unsigned Mask) -> bool {
20215    return (ShrunkMask & Mask) == ShrunkMask && (~ExpandedMask & Mask) == 0;
20216  };
20217  auto UseMask = [Mask, Op, VT, &TLO](unsigned NewMask) -> bool {
20218    if (NewMask == Mask)
20219      return true;
20220    SDLoc DL(Op);
20221    SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT);
20222    SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC);
20223    return TLO.CombineTo(Op, NewOp);
20224  };
20225
20226  // Prefer uxtb mask.
20227  if (IsLegalMask(0xFF))
20228    return UseMask(0xFF);
20229
20230  // Prefer uxth mask.
20231  if (IsLegalMask(0xFFFF))
20232    return UseMask(0xFFFF);
20233
20234  // [1, 255] is Thumb1 movs+ands, legal immediate for ARM/Thumb2.
20235  // FIXME: Prefer a contiguous sequence of bits for other optimizations.
20236  if (ShrunkMask < 256)
20237    return UseMask(ShrunkMask);
20238
20239  // [-256, -2] is Thumb1 movs+bics, legal immediate for ARM/Thumb2.
20240  // FIXME: Prefer a contiguous sequence of bits for other optimizations.
20241  if ((int)ExpandedMask <= -2 && (int)ExpandedMask >= -256)
20242    return UseMask(ExpandedMask);
20243
20244  // Potential improvements:
20245  //
20246  // We could try to recognize lsls+lsrs or lsrs+lsls pairs here.
20247  // We could try to prefer Thumb1 immediates which can be lowered to a
20248  // two-instruction sequence.
20249  // We could try to recognize more legal ARM/Thumb2 immediates here.
20250
20251  return false;
20252}
20253
20254bool ARMTargetLowering::SimplifyDemandedBitsForTargetNode(
20255    SDValue Op, const APInt &OriginalDemandedBits,
20256    const APInt &OriginalDemandedElts, KnownBits &Known, TargetLoweringOpt &TLO,
20257    unsigned Depth) const {
20258  unsigned Opc = Op.getOpcode();
20259
20260  switch (Opc) {
20261  case ARMISD::ASRL:
20262  case ARMISD::LSRL: {
20263    // If this is result 0 and the other result is unused, see if the demand
20264    // bits allow us to shrink this long shift into a standard small shift in
20265    // the opposite direction.
20266    if (Op.getResNo() == 0 && !Op->hasAnyUseOfValue(1) &&
20267        isa<ConstantSDNode>(Op->getOperand(2))) {
20268      unsigned ShAmt = Op->getConstantOperandVal(2);
20269      if (ShAmt < 32 && OriginalDemandedBits.isSubsetOf(APInt::getAllOnes(32)
20270                                                        << (32 - ShAmt)))
20271        return TLO.CombineTo(
20272            Op, TLO.DAG.getNode(
20273                    ISD::SHL, SDLoc(Op), MVT::i32, Op.getOperand(1),
20274                    TLO.DAG.getConstant(32 - ShAmt, SDLoc(Op), MVT::i32)));
20275    }
20276    break;
20277  }
20278  case ARMISD::VBICIMM: {
20279    SDValue Op0 = Op.getOperand(0);
20280    unsigned ModImm = Op.getConstantOperandVal(1);
20281    unsigned EltBits = 0;
20282    uint64_t Mask = ARM_AM::decodeVMOVModImm(ModImm, EltBits);
20283    if ((OriginalDemandedBits & Mask) == 0)
20284      return TLO.CombineTo(Op, Op0);
20285  }
20286  }
20287
20288  return TargetLowering::SimplifyDemandedBitsForTargetNode(
20289      Op, OriginalDemandedBits, OriginalDemandedElts, Known, TLO, Depth);
20290}
20291
20292//===----------------------------------------------------------------------===//
20293//                           ARM Inline Assembly Support
20294//===----------------------------------------------------------------------===//
20295
20296bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
20297  // Looking for "rev" which is V6+.
20298  if (!Subtarget->hasV6Ops())
20299    return false;
20300
20301  InlineAsm *IA = cast<InlineAsm>(CI->getCalledOperand());
20302  StringRef AsmStr = IA->getAsmString();
20303  SmallVector<StringRef, 4> AsmPieces;
20304  SplitString(AsmStr, AsmPieces, ";\n");
20305
20306  switch (AsmPieces.size()) {
20307  default: return false;
20308  case 1:
20309    AsmStr = AsmPieces[0];
20310    AsmPieces.clear();
20311    SplitString(AsmStr, AsmPieces, " \t,");
20312
20313    // rev $0, $1
20314    if (AsmPieces.size() == 3 &&
20315        AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
20316        IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
20317      IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
20318      if (Ty && Ty->getBitWidth() == 32)
20319        return IntrinsicLowering::LowerToByteSwap(CI);
20320    }
20321    break;
20322  }
20323
20324  return false;
20325}
20326
20327const char *ARMTargetLowering::LowerXConstraint(EVT ConstraintVT) const {
20328  // At this point, we have to lower this constraint to something else, so we
20329  // lower it to an "r" or "w". However, by doing this we will force the result
20330  // to be in register, while the X constraint is much more permissive.
20331  //
20332  // Although we are correct (we are free to emit anything, without
20333  // constraints), we might break use cases that would expect us to be more
20334  // efficient and emit something else.
20335  if (!Subtarget->hasVFP2Base())
20336    return "r";
20337  if (ConstraintVT.isFloatingPoint())
20338    return "w";
20339  if (ConstraintVT.isVector() && Subtarget->hasNEON() &&
20340     (ConstraintVT.getSizeInBits() == 64 ||
20341      ConstraintVT.getSizeInBits() == 128))
20342    return "w";
20343
20344  return "r";
20345}
20346
20347/// getConstraintType - Given a constraint letter, return the type of
20348/// constraint it is for this target.
20349ARMTargetLowering::ConstraintType
20350ARMTargetLowering::getConstraintType(StringRef Constraint) const {
20351  unsigned S = Constraint.size();
20352  if (S == 1) {
20353    switch (Constraint[0]) {
20354    default:  break;
20355    case 'l': return C_RegisterClass;
20356    case 'w': return C_RegisterClass;
20357    case 'h': return C_RegisterClass;
20358    case 'x': return C_RegisterClass;
20359    case 't': return C_RegisterClass;
20360    case 'j': return C_Immediate; // Constant for movw.
20361    // An address with a single base register. Due to the way we
20362    // currently handle addresses it is the same as an 'r' memory constraint.
20363    case 'Q': return C_Memory;
20364    }
20365  } else if (S == 2) {
20366    switch (Constraint[0]) {
20367    default: break;
20368    case 'T': return C_RegisterClass;
20369    // All 'U+' constraints are addresses.
20370    case 'U': return C_Memory;
20371    }
20372  }
20373  return TargetLowering::getConstraintType(Constraint);
20374}
20375
20376/// Examine constraint type and operand type and determine a weight value.
20377/// This object must already have been set up with the operand type
20378/// and the current alternative constraint selected.
20379TargetLowering::ConstraintWeight
20380ARMTargetLowering::getSingleConstraintMatchWeight(
20381    AsmOperandInfo &info, const char *constraint) const {
20382  ConstraintWeight weight = CW_Invalid;
20383  Value *CallOperandVal = info.CallOperandVal;
20384    // If we don't have a value, we can't do a match,
20385    // but allow it at the lowest weight.
20386  if (!CallOperandVal)
20387    return CW_Default;
20388  Type *type = CallOperandVal->getType();
20389  // Look at the constraint type.
20390  switch (*constraint) {
20391  default:
20392    weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
20393    break;
20394  case 'l':
20395    if (type->isIntegerTy()) {
20396      if (Subtarget->isThumb())
20397        weight = CW_SpecificReg;
20398      else
20399        weight = CW_Register;
20400    }
20401    break;
20402  case 'w':
20403    if (type->isFloatingPointTy())
20404      weight = CW_Register;
20405    break;
20406  }
20407  return weight;
20408}
20409
20410using RCPair = std::pair<unsigned, const TargetRegisterClass *>;
20411
20412RCPair ARMTargetLowering::getRegForInlineAsmConstraint(
20413    const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
20414  switch (Constraint.size()) {
20415  case 1:
20416    // GCC ARM Constraint Letters
20417    switch (Constraint[0]) {
20418    case 'l': // Low regs or general regs.
20419      if (Subtarget->isThumb())
20420        return RCPair(0U, &ARM::tGPRRegClass);
20421      return RCPair(0U, &ARM::GPRRegClass);
20422    case 'h': // High regs or no regs.
20423      if (Subtarget->isThumb())
20424        return RCPair(0U, &ARM::hGPRRegClass);
20425      break;
20426    case 'r':
20427      if (Subtarget->isThumb1Only())
20428        return RCPair(0U, &ARM::tGPRRegClass);
20429      return RCPair(0U, &ARM::GPRRegClass);
20430    case 'w':
20431      if (VT == MVT::Other)
20432        break;
20433      if (VT == MVT::f32 || VT == MVT::f16 || VT == MVT::bf16)
20434        return RCPair(0U, &ARM::SPRRegClass);
20435      if (VT.getSizeInBits() == 64)
20436        return RCPair(0U, &ARM::DPRRegClass);
20437      if (VT.getSizeInBits() == 128)
20438        return RCPair(0U, &ARM::QPRRegClass);
20439      break;
20440    case 'x':
20441      if (VT == MVT::Other)
20442        break;
20443      if (VT == MVT::f32 || VT == MVT::f16 || VT == MVT::bf16)
20444        return RCPair(0U, &ARM::SPR_8RegClass);
20445      if (VT.getSizeInBits() == 64)
20446        return RCPair(0U, &ARM::DPR_8RegClass);
20447      if (VT.getSizeInBits() == 128)
20448        return RCPair(0U, &ARM::QPR_8RegClass);
20449      break;
20450    case 't':
20451      if (VT == MVT::Other)
20452        break;
20453      if (VT == MVT::f32 || VT == MVT::i32 || VT == MVT::f16 || VT == MVT::bf16)
20454        return RCPair(0U, &ARM::SPRRegClass);
20455      if (VT.getSizeInBits() == 64)
20456        return RCPair(0U, &ARM::DPR_VFP2RegClass);
20457      if (VT.getSizeInBits() == 128)
20458        return RCPair(0U, &ARM::QPR_VFP2RegClass);
20459      break;
20460    }
20461    break;
20462
20463  case 2:
20464    if (Constraint[0] == 'T') {
20465      switch (Constraint[1]) {
20466      default:
20467        break;
20468      case 'e':
20469        return RCPair(0U, &ARM::tGPREvenRegClass);
20470      case 'o':
20471        return RCPair(0U, &ARM::tGPROddRegClass);
20472      }
20473    }
20474    break;
20475
20476  default:
20477    break;
20478  }
20479
20480  if (StringRef("{cc}").equals_insensitive(Constraint))
20481    return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
20482
20483  return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
20484}
20485
20486/// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
20487/// vector.  If it is invalid, don't add anything to Ops.
20488void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
20489                                                     StringRef Constraint,
20490                                                     std::vector<SDValue> &Ops,
20491                                                     SelectionDAG &DAG) const {
20492  SDValue Result;
20493
20494  // Currently only support length 1 constraints.
20495  if (Constraint.size() != 1)
20496    return;
20497
20498  char ConstraintLetter = Constraint[0];
20499  switch (ConstraintLetter) {
20500  default: break;
20501  case 'j':
20502  case 'I': case 'J': case 'K': case 'L':
20503  case 'M': case 'N': case 'O':
20504    ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
20505    if (!C)
20506      return;
20507
20508    int64_t CVal64 = C->getSExtValue();
20509    int CVal = (int) CVal64;
20510    // None of these constraints allow values larger than 32 bits.  Check
20511    // that the value fits in an int.
20512    if (CVal != CVal64)
20513      return;
20514
20515    switch (ConstraintLetter) {
20516      case 'j':
20517        // Constant suitable for movw, must be between 0 and
20518        // 65535.
20519        if (Subtarget->hasV6T2Ops() || (Subtarget->hasV8MBaselineOps()))
20520          if (CVal >= 0 && CVal <= 65535)
20521            break;
20522        return;
20523      case 'I':
20524        if (Subtarget->isThumb1Only()) {
20525          // This must be a constant between 0 and 255, for ADD
20526          // immediates.
20527          if (CVal >= 0 && CVal <= 255)
20528            break;
20529        } else if (Subtarget->isThumb2()) {
20530          // A constant that can be used as an immediate value in a
20531          // data-processing instruction.
20532          if (ARM_AM::getT2SOImmVal(CVal) != -1)
20533            break;
20534        } else {
20535          // A constant that can be used as an immediate value in a
20536          // data-processing instruction.
20537          if (ARM_AM::getSOImmVal(CVal) != -1)
20538            break;
20539        }
20540        return;
20541
20542      case 'J':
20543        if (Subtarget->isThumb1Only()) {
20544          // This must be a constant between -255 and -1, for negated ADD
20545          // immediates. This can be used in GCC with an "n" modifier that
20546          // prints the negated value, for use with SUB instructions. It is
20547          // not useful otherwise but is implemented for compatibility.
20548          if (CVal >= -255 && CVal <= -1)
20549            break;
20550        } else {
20551          // This must be a constant between -4095 and 4095. It is not clear
20552          // what this constraint is intended for. Implemented for
20553          // compatibility with GCC.
20554          if (CVal >= -4095 && CVal <= 4095)
20555            break;
20556        }
20557        return;
20558
20559      case 'K':
20560        if (Subtarget->isThumb1Only()) {
20561          // A 32-bit value where only one byte has a nonzero value. Exclude
20562          // zero to match GCC. This constraint is used by GCC internally for
20563          // constants that can be loaded with a move/shift combination.
20564          // It is not useful otherwise but is implemented for compatibility.
20565          if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
20566            break;
20567        } else if (Subtarget->isThumb2()) {
20568          // A constant whose bitwise inverse can be used as an immediate
20569          // value in a data-processing instruction. This can be used in GCC
20570          // with a "B" modifier that prints the inverted value, for use with
20571          // BIC and MVN instructions. It is not useful otherwise but is
20572          // implemented for compatibility.
20573          if (ARM_AM::getT2SOImmVal(~CVal) != -1)
20574            break;
20575        } else {
20576          // A constant whose bitwise inverse can be used as an immediate
20577          // value in a data-processing instruction. This can be used in GCC
20578          // with a "B" modifier that prints the inverted value, for use with
20579          // BIC and MVN instructions. It is not useful otherwise but is
20580          // implemented for compatibility.
20581          if (ARM_AM::getSOImmVal(~CVal) != -1)
20582            break;
20583        }
20584        return;
20585
20586      case 'L':
20587        if (Subtarget->isThumb1Only()) {
20588          // This must be a constant between -7 and 7,
20589          // for 3-operand ADD/SUB immediate instructions.
20590          if (CVal >= -7 && CVal < 7)
20591            break;
20592        } else if (Subtarget->isThumb2()) {
20593          // A constant whose negation can be used as an immediate value in a
20594          // data-processing instruction. This can be used in GCC with an "n"
20595          // modifier that prints the negated value, for use with SUB
20596          // instructions. It is not useful otherwise but is implemented for
20597          // compatibility.
20598          if (ARM_AM::getT2SOImmVal(-CVal) != -1)
20599            break;
20600        } else {
20601          // A constant whose negation can be used as an immediate value in a
20602          // data-processing instruction. This can be used in GCC with an "n"
20603          // modifier that prints the negated value, for use with SUB
20604          // instructions. It is not useful otherwise but is implemented for
20605          // compatibility.
20606          if (ARM_AM::getSOImmVal(-CVal) != -1)
20607            break;
20608        }
20609        return;
20610
20611      case 'M':
20612        if (Subtarget->isThumb1Only()) {
20613          // This must be a multiple of 4 between 0 and 1020, for
20614          // ADD sp + immediate.
20615          if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
20616            break;
20617        } else {
20618          // A power of two or a constant between 0 and 32.  This is used in
20619          // GCC for the shift amount on shifted register operands, but it is
20620          // useful in general for any shift amounts.
20621          if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
20622            break;
20623        }
20624        return;
20625
20626      case 'N':
20627        if (Subtarget->isThumb1Only()) {
20628          // This must be a constant between 0 and 31, for shift amounts.
20629          if (CVal >= 0 && CVal <= 31)
20630            break;
20631        }
20632        return;
20633
20634      case 'O':
20635        if (Subtarget->isThumb1Only()) {
20636          // This must be a multiple of 4 between -508 and 508, for
20637          // ADD/SUB sp = sp + immediate.
20638          if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
20639            break;
20640        }
20641        return;
20642    }
20643    Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType());
20644    break;
20645  }
20646
20647  if (Result.getNode()) {
20648    Ops.push_back(Result);
20649    return;
20650  }
20651  return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
20652}
20653
20654static RTLIB::Libcall getDivRemLibcall(
20655    const SDNode *N, MVT::SimpleValueType SVT) {
20656  assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
20657          N->getOpcode() == ISD::SREM    || N->getOpcode() == ISD::UREM) &&
20658         "Unhandled Opcode in getDivRemLibcall");
20659  bool isSigned = N->getOpcode() == ISD::SDIVREM ||
20660                  N->getOpcode() == ISD::SREM;
20661  RTLIB::Libcall LC;
20662  switch (SVT) {
20663  default: llvm_unreachable("Unexpected request for libcall!");
20664  case MVT::i8:  LC = isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
20665  case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
20666  case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
20667  case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
20668  }
20669  return LC;
20670}
20671
20672static TargetLowering::ArgListTy getDivRemArgList(
20673    const SDNode *N, LLVMContext *Context, const ARMSubtarget *Subtarget) {
20674  assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
20675          N->getOpcode() == ISD::SREM    || N->getOpcode() == ISD::UREM) &&
20676         "Unhandled Opcode in getDivRemArgList");
20677  bool isSigned = N->getOpcode() == ISD::SDIVREM ||
20678                  N->getOpcode() == ISD::SREM;
20679  TargetLowering::ArgListTy Args;
20680  TargetLowering::ArgListEntry Entry;
20681  for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
20682    EVT ArgVT = N->getOperand(i).getValueType();
20683    Type *ArgTy = ArgVT.getTypeForEVT(*Context);
20684    Entry.Node = N->getOperand(i);
20685    Entry.Ty = ArgTy;
20686    Entry.IsSExt = isSigned;
20687    Entry.IsZExt = !isSigned;
20688    Args.push_back(Entry);
20689  }
20690  if (Subtarget->isTargetWindows() && Args.size() >= 2)
20691    std::swap(Args[0], Args[1]);
20692  return Args;
20693}
20694
20695SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
20696  assert((Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() ||
20697          Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() ||
20698          Subtarget->isTargetWindows()) &&
20699         "Register-based DivRem lowering only");
20700  unsigned Opcode = Op->getOpcode();
20701  assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
20702         "Invalid opcode for Div/Rem lowering");
20703  bool isSigned = (Opcode == ISD::SDIVREM);
20704  EVT VT = Op->getValueType(0);
20705  SDLoc dl(Op);
20706
20707  if (VT == MVT::i64 && isa<ConstantSDNode>(Op.getOperand(1))) {
20708    SmallVector<SDValue> Result;
20709    if (expandDIVREMByConstant(Op.getNode(), Result, MVT::i32, DAG)) {
20710        SDValue Res0 =
20711            DAG.getNode(ISD::BUILD_PAIR, dl, VT, Result[0], Result[1]);
20712        SDValue Res1 =
20713            DAG.getNode(ISD::BUILD_PAIR, dl, VT, Result[2], Result[3]);
20714        return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
20715                           {Res0, Res1});
20716    }
20717  }
20718
20719  Type *Ty = VT.getTypeForEVT(*DAG.getContext());
20720
20721  // If the target has hardware divide, use divide + multiply + subtract:
20722  //     div = a / b
20723  //     rem = a - b * div
20724  //     return {div, rem}
20725  // This should be lowered into UDIV/SDIV + MLS later on.
20726  bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode()
20727                                        : Subtarget->hasDivideInARMMode();
20728  if (hasDivide && Op->getValueType(0).isSimple() &&
20729      Op->getSimpleValueType(0) == MVT::i32) {
20730    unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
20731    const SDValue Dividend = Op->getOperand(0);
20732    const SDValue Divisor = Op->getOperand(1);
20733    SDValue Div = DAG.getNode(DivOpcode, dl, VT, Dividend, Divisor);
20734    SDValue Mul = DAG.getNode(ISD::MUL, dl, VT, Div, Divisor);
20735    SDValue Rem = DAG.getNode(ISD::SUB, dl, VT, Dividend, Mul);
20736
20737    SDValue Values[2] = {Div, Rem};
20738    return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VT, VT), Values);
20739  }
20740
20741  RTLIB::Libcall LC = getDivRemLibcall(Op.getNode(),
20742                                       VT.getSimpleVT().SimpleTy);
20743  SDValue InChain = DAG.getEntryNode();
20744
20745  TargetLowering::ArgListTy Args = getDivRemArgList(Op.getNode(),
20746                                                    DAG.getContext(),
20747                                                    Subtarget);
20748
20749  SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
20750                                         getPointerTy(DAG.getDataLayout()));
20751
20752  Type *RetTy = StructType::get(Ty, Ty);
20753
20754  if (Subtarget->isTargetWindows())
20755    InChain = WinDBZCheckDenominator(DAG, Op.getNode(), InChain);
20756
20757  TargetLowering::CallLoweringInfo CLI(DAG);
20758  CLI.setDebugLoc(dl).setChain(InChain)
20759    .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args))
20760    .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
20761
20762  std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
20763  return CallInfo.first;
20764}
20765
20766// Lowers REM using divmod helpers
20767// see RTABI section 4.2/4.3
20768SDValue ARMTargetLowering::LowerREM(SDNode *N, SelectionDAG &DAG) const {
20769  EVT VT = N->getValueType(0);
20770
20771  if (VT == MVT::i64 && isa<ConstantSDNode>(N->getOperand(1))) {
20772    SmallVector<SDValue> Result;
20773    if (expandDIVREMByConstant(N, Result, MVT::i32, DAG))
20774        return DAG.getNode(ISD::BUILD_PAIR, SDLoc(N), N->getValueType(0),
20775                           Result[0], Result[1]);
20776  }
20777
20778  // Build return types (div and rem)
20779  std::vector<Type*> RetTyParams;
20780  Type *RetTyElement;
20781
20782  switch (VT.getSimpleVT().SimpleTy) {
20783  default: llvm_unreachable("Unexpected request for libcall!");
20784  case MVT::i8:   RetTyElement = Type::getInt8Ty(*DAG.getContext());  break;
20785  case MVT::i16:  RetTyElement = Type::getInt16Ty(*DAG.getContext()); break;
20786  case MVT::i32:  RetTyElement = Type::getInt32Ty(*DAG.getContext()); break;
20787  case MVT::i64:  RetTyElement = Type::getInt64Ty(*DAG.getContext()); break;
20788  }
20789
20790  RetTyParams.push_back(RetTyElement);
20791  RetTyParams.push_back(RetTyElement);
20792  ArrayRef<Type*> ret = ArrayRef<Type*>(RetTyParams);
20793  Type *RetTy = StructType::get(*DAG.getContext(), ret);
20794
20795  RTLIB::Libcall LC = getDivRemLibcall(N, N->getValueType(0).getSimpleVT().
20796                                                             SimpleTy);
20797  SDValue InChain = DAG.getEntryNode();
20798  TargetLowering::ArgListTy Args = getDivRemArgList(N, DAG.getContext(),
20799                                                    Subtarget);
20800  bool isSigned = N->getOpcode() == ISD::SREM;
20801  SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
20802                                         getPointerTy(DAG.getDataLayout()));
20803
20804  if (Subtarget->isTargetWindows())
20805    InChain = WinDBZCheckDenominator(DAG, N, InChain);
20806
20807  // Lower call
20808  CallLoweringInfo CLI(DAG);
20809  CLI.setChain(InChain)
20810     .setCallee(CallingConv::ARM_AAPCS, RetTy, Callee, std::move(Args))
20811     .setSExtResult(isSigned).setZExtResult(!isSigned).setDebugLoc(SDLoc(N));
20812  std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
20813
20814  // Return second (rem) result operand (first contains div)
20815  SDNode *ResNode = CallResult.first.getNode();
20816  assert(ResNode->getNumOperands() == 2 && "divmod should return two operands");
20817  return ResNode->getOperand(1);
20818}
20819
20820SDValue
20821ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
20822  assert(Subtarget->isTargetWindows() && "unsupported target platform");
20823  SDLoc DL(Op);
20824
20825  // Get the inputs.
20826  SDValue Chain = Op.getOperand(0);
20827  SDValue Size  = Op.getOperand(1);
20828
20829  if (DAG.getMachineFunction().getFunction().hasFnAttribute(
20830          "no-stack-arg-probe")) {
20831    MaybeAlign Align =
20832        cast<ConstantSDNode>(Op.getOperand(2))->getMaybeAlignValue();
20833    SDValue SP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
20834    Chain = SP.getValue(1);
20835    SP = DAG.getNode(ISD::SUB, DL, MVT::i32, SP, Size);
20836    if (Align)
20837      SP =
20838          DAG.getNode(ISD::AND, DL, MVT::i32, SP.getValue(0),
20839                      DAG.getConstant(-(uint64_t)Align->value(), DL, MVT::i32));
20840    Chain = DAG.getCopyToReg(Chain, DL, ARM::SP, SP);
20841    SDValue Ops[2] = { SP, Chain };
20842    return DAG.getMergeValues(Ops, DL);
20843  }
20844
20845  SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
20846                              DAG.getConstant(2, DL, MVT::i32));
20847
20848  SDValue Glue;
20849  Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Glue);
20850  Glue = Chain.getValue(1);
20851
20852  SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
20853  Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Glue);
20854
20855  SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
20856  Chain = NewSP.getValue(1);
20857
20858  SDValue Ops[2] = { NewSP, Chain };
20859  return DAG.getMergeValues(Ops, DL);
20860}
20861
20862SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
20863  bool IsStrict = Op->isStrictFPOpcode();
20864  SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0);
20865  const unsigned DstSz = Op.getValueType().getSizeInBits();
20866  const unsigned SrcSz = SrcVal.getValueType().getSizeInBits();
20867  assert(DstSz > SrcSz && DstSz <= 64 && SrcSz >= 16 &&
20868         "Unexpected type for custom-lowering FP_EXTEND");
20869
20870  assert((!Subtarget->hasFP64() || !Subtarget->hasFPARMv8Base()) &&
20871         "With both FP DP and 16, any FP conversion is legal!");
20872
20873  assert(!(DstSz == 32 && Subtarget->hasFP16()) &&
20874         "With FP16, 16 to 32 conversion is legal!");
20875
20876  // Converting from 32 -> 64 is valid if we have FP64.
20877  if (SrcSz == 32 && DstSz == 64 && Subtarget->hasFP64()) {
20878    // FIXME: Remove this when we have strict fp instruction selection patterns
20879    if (IsStrict) {
20880      SDLoc Loc(Op);
20881      SDValue Result = DAG.getNode(ISD::FP_EXTEND,
20882                                   Loc, Op.getValueType(), SrcVal);
20883      return DAG.getMergeValues({Result, Op.getOperand(0)}, Loc);
20884    }
20885    return Op;
20886  }
20887
20888  // Either we are converting from 16 -> 64, without FP16 and/or
20889  // FP.double-precision or without Armv8-fp. So we must do it in two
20890  // steps.
20891  // Or we are converting from 32 -> 64 without fp.double-precision or 16 -> 32
20892  // without FP16. So we must do a function call.
20893  SDLoc Loc(Op);
20894  RTLIB::Libcall LC;
20895  MakeLibCallOptions CallOptions;
20896  SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
20897  for (unsigned Sz = SrcSz; Sz <= 32 && Sz < DstSz; Sz *= 2) {
20898    bool Supported = (Sz == 16 ? Subtarget->hasFP16() : Subtarget->hasFP64());
20899    MVT SrcVT = (Sz == 16 ? MVT::f16 : MVT::f32);
20900    MVT DstVT = (Sz == 16 ? MVT::f32 : MVT::f64);
20901    if (Supported) {
20902      if (IsStrict) {
20903        SrcVal = DAG.getNode(ISD::STRICT_FP_EXTEND, Loc,
20904                             {DstVT, MVT::Other}, {Chain, SrcVal});
20905        Chain = SrcVal.getValue(1);
20906      } else {
20907        SrcVal = DAG.getNode(ISD::FP_EXTEND, Loc, DstVT, SrcVal);
20908      }
20909    } else {
20910      LC = RTLIB::getFPEXT(SrcVT, DstVT);
20911      assert(LC != RTLIB::UNKNOWN_LIBCALL &&
20912             "Unexpected type for custom-lowering FP_EXTEND");
20913      std::tie(SrcVal, Chain) = makeLibCall(DAG, LC, DstVT, SrcVal, CallOptions,
20914                                            Loc, Chain);
20915    }
20916  }
20917
20918  return IsStrict ? DAG.getMergeValues({SrcVal, Chain}, Loc) : SrcVal;
20919}
20920
20921SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
20922  bool IsStrict = Op->isStrictFPOpcode();
20923
20924  SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0);
20925  EVT SrcVT = SrcVal.getValueType();
20926  EVT DstVT = Op.getValueType();
20927  const unsigned DstSz = Op.getValueType().getSizeInBits();
20928  const unsigned SrcSz = SrcVT.getSizeInBits();
20929  (void)DstSz;
20930  assert(DstSz < SrcSz && SrcSz <= 64 && DstSz >= 16 &&
20931         "Unexpected type for custom-lowering FP_ROUND");
20932
20933  assert((!Subtarget->hasFP64() || !Subtarget->hasFPARMv8Base()) &&
20934         "With both FP DP and 16, any FP conversion is legal!");
20935
20936  SDLoc Loc(Op);
20937
20938  // Instruction from 32 -> 16 if hasFP16 is valid
20939  if (SrcSz == 32 && Subtarget->hasFP16())
20940    return Op;
20941
20942  // Lib call from 32 -> 16 / 64 -> [32, 16]
20943  RTLIB::Libcall LC = RTLIB::getFPROUND(SrcVT, DstVT);
20944  assert(LC != RTLIB::UNKNOWN_LIBCALL &&
20945         "Unexpected type for custom-lowering FP_ROUND");
20946  MakeLibCallOptions CallOptions;
20947  SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
20948  SDValue Result;
20949  std::tie(Result, Chain) = makeLibCall(DAG, LC, DstVT, SrcVal, CallOptions,
20950                                        Loc, Chain);
20951  return IsStrict ? DAG.getMergeValues({Result, Chain}, Loc) : Result;
20952}
20953
20954bool
20955ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
20956  // The ARM target isn't yet aware of offsets.
20957  return false;
20958}
20959
20960bool ARM::isBitFieldInvertedMask(unsigned v) {
20961  if (v == 0xffffffff)
20962    return false;
20963
20964  // there can be 1's on either or both "outsides", all the "inside"
20965  // bits must be 0's
20966  return isShiftedMask_32(~v);
20967}
20968
20969/// isFPImmLegal - Returns true if the target can instruction select the
20970/// specified FP immediate natively. If false, the legalizer will
20971/// materialize the FP immediate as a load from a constant pool.
20972bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
20973                                     bool ForCodeSize) const {
20974  if (!Subtarget->hasVFP3Base())
20975    return false;
20976  if (VT == MVT::f16 && Subtarget->hasFullFP16())
20977    return ARM_AM::getFP16Imm(Imm) != -1;
20978  if (VT == MVT::f32 && Subtarget->hasFullFP16() &&
20979      ARM_AM::getFP32FP16Imm(Imm) != -1)
20980    return true;
20981  if (VT == MVT::f32)
20982    return ARM_AM::getFP32Imm(Imm) != -1;
20983  if (VT == MVT::f64 && Subtarget->hasFP64())
20984    return ARM_AM::getFP64Imm(Imm) != -1;
20985  return false;
20986}
20987
20988/// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
20989/// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
20990/// specified in the intrinsic calls.
20991bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
20992                                           const CallInst &I,
20993                                           MachineFunction &MF,
20994                                           unsigned Intrinsic) const {
20995  switch (Intrinsic) {
20996  case Intrinsic::arm_neon_vld1:
20997  case Intrinsic::arm_neon_vld2:
20998  case Intrinsic::arm_neon_vld3:
20999  case Intrinsic::arm_neon_vld4:
21000  case Intrinsic::arm_neon_vld2lane:
21001  case Intrinsic::arm_neon_vld3lane:
21002  case Intrinsic::arm_neon_vld4lane:
21003  case Intrinsic::arm_neon_vld2dup:
21004  case Intrinsic::arm_neon_vld3dup:
21005  case Intrinsic::arm_neon_vld4dup: {
21006    Info.opc = ISD::INTRINSIC_W_CHAIN;
21007    // Conservatively set memVT to the entire set of vectors loaded.
21008    auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
21009    uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
21010    Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
21011    Info.ptrVal = I.getArgOperand(0);
21012    Info.offset = 0;
21013    Value *AlignArg = I.getArgOperand(I.arg_size() - 1);
21014    Info.align = cast<ConstantInt>(AlignArg)->getMaybeAlignValue();
21015    // volatile loads with NEON intrinsics not supported
21016    Info.flags = MachineMemOperand::MOLoad;
21017    return true;
21018  }
21019  case Intrinsic::arm_neon_vld1x2:
21020  case Intrinsic::arm_neon_vld1x3:
21021  case Intrinsic::arm_neon_vld1x4: {
21022    Info.opc = ISD::INTRINSIC_W_CHAIN;
21023    // Conservatively set memVT to the entire set of vectors loaded.
21024    auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
21025    uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
21026    Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
21027    Info.ptrVal = I.getArgOperand(I.arg_size() - 1);
21028    Info.offset = 0;
21029    Info.align.reset();
21030    // volatile loads with NEON intrinsics not supported
21031    Info.flags = MachineMemOperand::MOLoad;
21032    return true;
21033  }
21034  case Intrinsic::arm_neon_vst1:
21035  case Intrinsic::arm_neon_vst2:
21036  case Intrinsic::arm_neon_vst3:
21037  case Intrinsic::arm_neon_vst4:
21038  case Intrinsic::arm_neon_vst2lane:
21039  case Intrinsic::arm_neon_vst3lane:
21040  case Intrinsic::arm_neon_vst4lane: {
21041    Info.opc = ISD::INTRINSIC_VOID;
21042    // Conservatively set memVT to the entire set of vectors stored.
21043    auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
21044    unsigned NumElts = 0;
21045    for (unsigned ArgI = 1, ArgE = I.arg_size(); ArgI < ArgE; ++ArgI) {
21046      Type *ArgTy = I.getArgOperand(ArgI)->getType();
21047      if (!ArgTy->isVectorTy())
21048        break;
21049      NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
21050    }
21051    Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
21052    Info.ptrVal = I.getArgOperand(0);
21053    Info.offset = 0;
21054    Value *AlignArg = I.getArgOperand(I.arg_size() - 1);
21055    Info.align = cast<ConstantInt>(AlignArg)->getMaybeAlignValue();
21056    // volatile stores with NEON intrinsics not supported
21057    Info.flags = MachineMemOperand::MOStore;
21058    return true;
21059  }
21060  case Intrinsic::arm_neon_vst1x2:
21061  case Intrinsic::arm_neon_vst1x3:
21062  case Intrinsic::arm_neon_vst1x4: {
21063    Info.opc = ISD::INTRINSIC_VOID;
21064    // Conservatively set memVT to the entire set of vectors stored.
21065    auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
21066    unsigned NumElts = 0;
21067    for (unsigned ArgI = 1, ArgE = I.arg_size(); ArgI < ArgE; ++ArgI) {
21068      Type *ArgTy = I.getArgOperand(ArgI)->getType();
21069      if (!ArgTy->isVectorTy())
21070        break;
21071      NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
21072    }
21073    Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
21074    Info.ptrVal = I.getArgOperand(0);
21075    Info.offset = 0;
21076    Info.align.reset();
21077    // volatile stores with NEON intrinsics not supported
21078    Info.flags = MachineMemOperand::MOStore;
21079    return true;
21080  }
21081  case Intrinsic::arm_mve_vld2q:
21082  case Intrinsic::arm_mve_vld4q: {
21083    Info.opc = ISD::INTRINSIC_W_CHAIN;
21084    // Conservatively set memVT to the entire set of vectors loaded.
21085    Type *VecTy = cast<StructType>(I.getType())->getElementType(1);
21086    unsigned Factor = Intrinsic == Intrinsic::arm_mve_vld2q ? 2 : 4;
21087    Info.memVT = EVT::getVectorVT(VecTy->getContext(), MVT::i64, Factor * 2);
21088    Info.ptrVal = I.getArgOperand(0);
21089    Info.offset = 0;
21090    Info.align = Align(VecTy->getScalarSizeInBits() / 8);
21091    // volatile loads with MVE intrinsics not supported
21092    Info.flags = MachineMemOperand::MOLoad;
21093    return true;
21094  }
21095  case Intrinsic::arm_mve_vst2q:
21096  case Intrinsic::arm_mve_vst4q: {
21097    Info.opc = ISD::INTRINSIC_VOID;
21098    // Conservatively set memVT to the entire set of vectors stored.
21099    Type *VecTy = I.getArgOperand(1)->getType();
21100    unsigned Factor = Intrinsic == Intrinsic::arm_mve_vst2q ? 2 : 4;
21101    Info.memVT = EVT::getVectorVT(VecTy->getContext(), MVT::i64, Factor * 2);
21102    Info.ptrVal = I.getArgOperand(0);
21103    Info.offset = 0;
21104    Info.align = Align(VecTy->getScalarSizeInBits() / 8);
21105    // volatile stores with MVE intrinsics not supported
21106    Info.flags = MachineMemOperand::MOStore;
21107    return true;
21108  }
21109  case Intrinsic::arm_mve_vldr_gather_base:
21110  case Intrinsic::arm_mve_vldr_gather_base_predicated: {
21111    Info.opc = ISD::INTRINSIC_W_CHAIN;
21112    Info.ptrVal = nullptr;
21113    Info.memVT = MVT::getVT(I.getType());
21114    Info.align = Align(1);
21115    Info.flags |= MachineMemOperand::MOLoad;
21116    return true;
21117  }
21118  case Intrinsic::arm_mve_vldr_gather_base_wb:
21119  case Intrinsic::arm_mve_vldr_gather_base_wb_predicated: {
21120    Info.opc = ISD::INTRINSIC_W_CHAIN;
21121    Info.ptrVal = nullptr;
21122    Info.memVT = MVT::getVT(I.getType()->getContainedType(0));
21123    Info.align = Align(1);
21124    Info.flags |= MachineMemOperand::MOLoad;
21125    return true;
21126  }
21127  case Intrinsic::arm_mve_vldr_gather_offset:
21128  case Intrinsic::arm_mve_vldr_gather_offset_predicated: {
21129    Info.opc = ISD::INTRINSIC_W_CHAIN;
21130    Info.ptrVal = nullptr;
21131    MVT DataVT = MVT::getVT(I.getType());
21132    unsigned MemSize = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue();
21133    Info.memVT = MVT::getVectorVT(MVT::getIntegerVT(MemSize),
21134                                  DataVT.getVectorNumElements());
21135    Info.align = Align(1);
21136    Info.flags |= MachineMemOperand::MOLoad;
21137    return true;
21138  }
21139  case Intrinsic::arm_mve_vstr_scatter_base:
21140  case Intrinsic::arm_mve_vstr_scatter_base_predicated: {
21141    Info.opc = ISD::INTRINSIC_VOID;
21142    Info.ptrVal = nullptr;
21143    Info.memVT = MVT::getVT(I.getArgOperand(2)->getType());
21144    Info.align = Align(1);
21145    Info.flags |= MachineMemOperand::MOStore;
21146    return true;
21147  }
21148  case Intrinsic::arm_mve_vstr_scatter_base_wb:
21149  case Intrinsic::arm_mve_vstr_scatter_base_wb_predicated: {
21150    Info.opc = ISD::INTRINSIC_W_CHAIN;
21151    Info.ptrVal = nullptr;
21152    Info.memVT = MVT::getVT(I.getArgOperand(2)->getType());
21153    Info.align = Align(1);
21154    Info.flags |= MachineMemOperand::MOStore;
21155    return true;
21156  }
21157  case Intrinsic::arm_mve_vstr_scatter_offset:
21158  case Intrinsic::arm_mve_vstr_scatter_offset_predicated: {
21159    Info.opc = ISD::INTRINSIC_VOID;
21160    Info.ptrVal = nullptr;
21161    MVT DataVT = MVT::getVT(I.getArgOperand(2)->getType());
21162    unsigned MemSize = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
21163    Info.memVT = MVT::getVectorVT(MVT::getIntegerVT(MemSize),
21164                                  DataVT.getVectorNumElements());
21165    Info.align = Align(1);
21166    Info.flags |= MachineMemOperand::MOStore;
21167    return true;
21168  }
21169  case Intrinsic::arm_ldaex:
21170  case Intrinsic::arm_ldrex: {
21171    auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
21172    Type *ValTy = I.getParamElementType(0);
21173    Info.opc = ISD::INTRINSIC_W_CHAIN;
21174    Info.memVT = MVT::getVT(ValTy);
21175    Info.ptrVal = I.getArgOperand(0);
21176    Info.offset = 0;
21177    Info.align = DL.getABITypeAlign(ValTy);
21178    Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
21179    return true;
21180  }
21181  case Intrinsic::arm_stlex:
21182  case Intrinsic::arm_strex: {
21183    auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
21184    Type *ValTy = I.getParamElementType(1);
21185    Info.opc = ISD::INTRINSIC_W_CHAIN;
21186    Info.memVT = MVT::getVT(ValTy);
21187    Info.ptrVal = I.getArgOperand(1);
21188    Info.offset = 0;
21189    Info.align = DL.getABITypeAlign(ValTy);
21190    Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
21191    return true;
21192  }
21193  case Intrinsic::arm_stlexd:
21194  case Intrinsic::arm_strexd:
21195    Info.opc = ISD::INTRINSIC_W_CHAIN;
21196    Info.memVT = MVT::i64;
21197    Info.ptrVal = I.getArgOperand(2);
21198    Info.offset = 0;
21199    Info.align = Align(8);
21200    Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
21201    return true;
21202
21203  case Intrinsic::arm_ldaexd:
21204  case Intrinsic::arm_ldrexd:
21205    Info.opc = ISD::INTRINSIC_W_CHAIN;
21206    Info.memVT = MVT::i64;
21207    Info.ptrVal = I.getArgOperand(0);
21208    Info.offset = 0;
21209    Info.align = Align(8);
21210    Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
21211    return true;
21212
21213  default:
21214    break;
21215  }
21216
21217  return false;
21218}
21219
21220/// Returns true if it is beneficial to convert a load of a constant
21221/// to just the constant itself.
21222bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
21223                                                          Type *Ty) const {
21224  assert(Ty->isIntegerTy());
21225
21226  unsigned Bits = Ty->getPrimitiveSizeInBits();
21227  if (Bits == 0 || Bits > 32)
21228    return false;
21229  return true;
21230}
21231
21232bool ARMTargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT,
21233                                                unsigned Index) const {
21234  if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
21235    return false;
21236
21237  return (Index == 0 || Index == ResVT.getVectorNumElements());
21238}
21239
21240Instruction *ARMTargetLowering::makeDMB(IRBuilderBase &Builder,
21241                                        ARM_MB::MemBOpt Domain) const {
21242  Module *M = Builder.GetInsertBlock()->getParent()->getParent();
21243
21244  // First, if the target has no DMB, see what fallback we can use.
21245  if (!Subtarget->hasDataBarrier()) {
21246    // Some ARMv6 cpus can support data barriers with an mcr instruction.
21247    // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
21248    // here.
21249    if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) {
21250      Function *MCR = Intrinsic::getDeclaration(M, Intrinsic::arm_mcr);
21251      Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0),
21252                        Builder.getInt32(0), Builder.getInt32(7),
21253                        Builder.getInt32(10), Builder.getInt32(5)};
21254      return Builder.CreateCall(MCR, args);
21255    } else {
21256      // Instead of using barriers, atomic accesses on these subtargets use
21257      // libcalls.
21258      llvm_unreachable("makeDMB on a target so old that it has no barriers");
21259    }
21260  } else {
21261    Function *DMB = Intrinsic::getDeclaration(M, Intrinsic::arm_dmb);
21262    // Only a full system barrier exists in the M-class architectures.
21263    Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain;
21264    Constant *CDomain = Builder.getInt32(Domain);
21265    return Builder.CreateCall(DMB, CDomain);
21266  }
21267}
21268
21269// Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
21270Instruction *ARMTargetLowering::emitLeadingFence(IRBuilderBase &Builder,
21271                                                 Instruction *Inst,
21272                                                 AtomicOrdering Ord) const {
21273  switch (Ord) {
21274  case AtomicOrdering::NotAtomic:
21275  case AtomicOrdering::Unordered:
21276    llvm_unreachable("Invalid fence: unordered/non-atomic");
21277  case AtomicOrdering::Monotonic:
21278  case AtomicOrdering::Acquire:
21279    return nullptr; // Nothing to do
21280  case AtomicOrdering::SequentiallyConsistent:
21281    if (!Inst->hasAtomicStore())
21282      return nullptr; // Nothing to do
21283    [[fallthrough]];
21284  case AtomicOrdering::Release:
21285  case AtomicOrdering::AcquireRelease:
21286    if (Subtarget->preferISHSTBarriers())
21287      return makeDMB(Builder, ARM_MB::ISHST);
21288    // FIXME: add a comment with a link to documentation justifying this.
21289    else
21290      return makeDMB(Builder, ARM_MB::ISH);
21291  }
21292  llvm_unreachable("Unknown fence ordering in emitLeadingFence");
21293}
21294
21295Instruction *ARMTargetLowering::emitTrailingFence(IRBuilderBase &Builder,
21296                                                  Instruction *Inst,
21297                                                  AtomicOrdering Ord) const {
21298  switch (Ord) {
21299  case AtomicOrdering::NotAtomic:
21300  case AtomicOrdering::Unordered:
21301    llvm_unreachable("Invalid fence: unordered/not-atomic");
21302  case AtomicOrdering::Monotonic:
21303  case AtomicOrdering::Release:
21304    return nullptr; // Nothing to do
21305  case AtomicOrdering::Acquire:
21306  case AtomicOrdering::AcquireRelease:
21307  case AtomicOrdering::SequentiallyConsistent:
21308    return makeDMB(Builder, ARM_MB::ISH);
21309  }
21310  llvm_unreachable("Unknown fence ordering in emitTrailingFence");
21311}
21312
21313// Loads and stores less than 64-bits are already atomic; ones above that
21314// are doomed anyway, so defer to the default libcall and blame the OS when
21315// things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
21316// anything for those.
21317TargetLoweringBase::AtomicExpansionKind
21318ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
21319  bool has64BitAtomicStore;
21320  if (Subtarget->isMClass())
21321    has64BitAtomicStore = false;
21322  else if (Subtarget->isThumb())
21323    has64BitAtomicStore = Subtarget->hasV7Ops();
21324  else
21325    has64BitAtomicStore = Subtarget->hasV6Ops();
21326
21327  unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
21328  return Size == 64 && has64BitAtomicStore ? AtomicExpansionKind::Expand
21329                                           : AtomicExpansionKind::None;
21330}
21331
21332// Loads and stores less than 64-bits are already atomic; ones above that
21333// are doomed anyway, so defer to the default libcall and blame the OS when
21334// things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
21335// anything for those.
21336// FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that
21337// guarantee, see DDI0406C ARM architecture reference manual,
21338// sections A8.8.72-74 LDRD)
21339TargetLowering::AtomicExpansionKind
21340ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
21341  bool has64BitAtomicLoad;
21342  if (Subtarget->isMClass())
21343    has64BitAtomicLoad = false;
21344  else if (Subtarget->isThumb())
21345    has64BitAtomicLoad = Subtarget->hasV7Ops();
21346  else
21347    has64BitAtomicLoad = Subtarget->hasV6Ops();
21348
21349  unsigned Size = LI->getType()->getPrimitiveSizeInBits();
21350  return (Size == 64 && has64BitAtomicLoad) ? AtomicExpansionKind::LLOnly
21351                                            : AtomicExpansionKind::None;
21352}
21353
21354// For the real atomic operations, we have ldrex/strex up to 32 bits,
21355// and up to 64 bits on the non-M profiles
21356TargetLowering::AtomicExpansionKind
21357ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
21358  if (AI->isFloatingPointOperation())
21359    return AtomicExpansionKind::CmpXChg;
21360
21361  unsigned Size = AI->getType()->getPrimitiveSizeInBits();
21362  bool hasAtomicRMW;
21363  if (Subtarget->isMClass())
21364    hasAtomicRMW = Subtarget->hasV8MBaselineOps();
21365  else if (Subtarget->isThumb())
21366    hasAtomicRMW = Subtarget->hasV7Ops();
21367  else
21368    hasAtomicRMW = Subtarget->hasV6Ops();
21369  if (Size <= (Subtarget->isMClass() ? 32U : 64U) && hasAtomicRMW) {
21370    // At -O0, fast-regalloc cannot cope with the live vregs necessary to
21371    // implement atomicrmw without spilling. If the target address is also on
21372    // the stack and close enough to the spill slot, this can lead to a
21373    // situation where the monitor always gets cleared and the atomic operation
21374    // can never succeed. So at -O0 lower this operation to a CAS loop.
21375    if (getTargetMachine().getOptLevel() == CodeGenOptLevel::None)
21376      return AtomicExpansionKind::CmpXChg;
21377    return AtomicExpansionKind::LLSC;
21378  }
21379  return AtomicExpansionKind::None;
21380}
21381
21382// Similar to shouldExpandAtomicRMWInIR, ldrex/strex can be used  up to 32
21383// bits, and up to 64 bits on the non-M profiles.
21384TargetLowering::AtomicExpansionKind
21385ARMTargetLowering::shouldExpandAtomicCmpXchgInIR(AtomicCmpXchgInst *AI) const {
21386  // At -O0, fast-regalloc cannot cope with the live vregs necessary to
21387  // implement cmpxchg without spilling. If the address being exchanged is also
21388  // on the stack and close enough to the spill slot, this can lead to a
21389  // situation where the monitor always gets cleared and the atomic operation
21390  // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead.
21391  unsigned Size = AI->getOperand(1)->getType()->getPrimitiveSizeInBits();
21392  bool HasAtomicCmpXchg;
21393  if (Subtarget->isMClass())
21394    HasAtomicCmpXchg = Subtarget->hasV8MBaselineOps();
21395  else if (Subtarget->isThumb())
21396    HasAtomicCmpXchg = Subtarget->hasV7Ops();
21397  else
21398    HasAtomicCmpXchg = Subtarget->hasV6Ops();
21399  if (getTargetMachine().getOptLevel() != CodeGenOptLevel::None &&
21400      HasAtomicCmpXchg && Size <= (Subtarget->isMClass() ? 32U : 64U))
21401    return AtomicExpansionKind::LLSC;
21402  return AtomicExpansionKind::None;
21403}
21404
21405bool ARMTargetLowering::shouldInsertFencesForAtomic(
21406    const Instruction *I) const {
21407  return InsertFencesForAtomic;
21408}
21409
21410bool ARMTargetLowering::useLoadStackGuardNode() const {
21411  // ROPI/RWPI are not supported currently.
21412  return !Subtarget->isROPI() && !Subtarget->isRWPI();
21413}
21414
21415void ARMTargetLowering::insertSSPDeclarations(Module &M) const {
21416  if (!Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
21417    return TargetLowering::insertSSPDeclarations(M);
21418
21419  // MSVC CRT has a global variable holding security cookie.
21420  M.getOrInsertGlobal("__security_cookie",
21421                      PointerType::getUnqual(M.getContext()));
21422
21423  // MSVC CRT has a function to validate security cookie.
21424  FunctionCallee SecurityCheckCookie = M.getOrInsertFunction(
21425      "__security_check_cookie", Type::getVoidTy(M.getContext()),
21426      PointerType::getUnqual(M.getContext()));
21427  if (Function *F = dyn_cast<Function>(SecurityCheckCookie.getCallee()))
21428    F->addParamAttr(0, Attribute::AttrKind::InReg);
21429}
21430
21431Value *ARMTargetLowering::getSDagStackGuard(const Module &M) const {
21432  // MSVC CRT has a global variable holding security cookie.
21433  if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
21434    return M.getGlobalVariable("__security_cookie");
21435  return TargetLowering::getSDagStackGuard(M);
21436}
21437
21438Function *ARMTargetLowering::getSSPStackGuardCheck(const Module &M) const {
21439  // MSVC CRT has a function to validate security cookie.
21440  if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
21441    return M.getFunction("__security_check_cookie");
21442  return TargetLowering::getSSPStackGuardCheck(M);
21443}
21444
21445bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
21446                                                  unsigned &Cost) const {
21447  // If we do not have NEON, vector types are not natively supported.
21448  if (!Subtarget->hasNEON())
21449    return false;
21450
21451  // Floating point values and vector values map to the same register file.
21452  // Therefore, although we could do a store extract of a vector type, this is
21453  // better to leave at float as we have more freedom in the addressing mode for
21454  // those.
21455  if (VectorTy->isFPOrFPVectorTy())
21456    return false;
21457
21458  // If the index is unknown at compile time, this is very expensive to lower
21459  // and it is not possible to combine the store with the extract.
21460  if (!isa<ConstantInt>(Idx))
21461    return false;
21462
21463  assert(VectorTy->isVectorTy() && "VectorTy is not a vector type");
21464  unsigned BitWidth = VectorTy->getPrimitiveSizeInBits().getFixedValue();
21465  // We can do a store + vector extract on any vector that fits perfectly in a D
21466  // or Q register.
21467  if (BitWidth == 64 || BitWidth == 128) {
21468    Cost = 0;
21469    return true;
21470  }
21471  return false;
21472}
21473
21474bool ARMTargetLowering::isCheapToSpeculateCttz(Type *Ty) const {
21475  return Subtarget->hasV6T2Ops();
21476}
21477
21478bool ARMTargetLowering::isCheapToSpeculateCtlz(Type *Ty) const {
21479  return Subtarget->hasV6T2Ops();
21480}
21481
21482bool ARMTargetLowering::isMaskAndCmp0FoldingBeneficial(
21483    const Instruction &AndI) const {
21484  if (!Subtarget->hasV7Ops())
21485    return false;
21486
21487  // Sink the `and` instruction only if the mask would fit into a modified
21488  // immediate operand.
21489  ConstantInt *Mask = dyn_cast<ConstantInt>(AndI.getOperand(1));
21490  if (!Mask || Mask->getValue().getBitWidth() > 32u)
21491    return false;
21492  auto MaskVal = unsigned(Mask->getValue().getZExtValue());
21493  return (Subtarget->isThumb2() ? ARM_AM::getT2SOImmVal(MaskVal)
21494                                : ARM_AM::getSOImmVal(MaskVal)) != -1;
21495}
21496
21497TargetLowering::ShiftLegalizationStrategy
21498ARMTargetLowering::preferredShiftLegalizationStrategy(
21499    SelectionDAG &DAG, SDNode *N, unsigned ExpansionFactor) const {
21500  if (Subtarget->hasMinSize() && !Subtarget->isTargetWindows())
21501    return ShiftLegalizationStrategy::LowerToLibcall;
21502  return TargetLowering::preferredShiftLegalizationStrategy(DAG, N,
21503                                                            ExpansionFactor);
21504}
21505
21506Value *ARMTargetLowering::emitLoadLinked(IRBuilderBase &Builder, Type *ValueTy,
21507                                         Value *Addr,
21508                                         AtomicOrdering Ord) const {
21509  Module *M = Builder.GetInsertBlock()->getParent()->getParent();
21510  bool IsAcquire = isAcquireOrStronger(Ord);
21511
21512  // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
21513  // intrinsic must return {i32, i32} and we have to recombine them into a
21514  // single i64 here.
21515  if (ValueTy->getPrimitiveSizeInBits() == 64) {
21516    Intrinsic::ID Int =
21517        IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
21518    Function *Ldrex = Intrinsic::getDeclaration(M, Int);
21519
21520    Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
21521
21522    Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
21523    Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
21524    if (!Subtarget->isLittle())
21525      std::swap (Lo, Hi);
21526    Lo = Builder.CreateZExt(Lo, ValueTy, "lo64");
21527    Hi = Builder.CreateZExt(Hi, ValueTy, "hi64");
21528    return Builder.CreateOr(
21529        Lo, Builder.CreateShl(Hi, ConstantInt::get(ValueTy, 32)), "val64");
21530  }
21531
21532  Type *Tys[] = { Addr->getType() };
21533  Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
21534  Function *Ldrex = Intrinsic::getDeclaration(M, Int, Tys);
21535  CallInst *CI = Builder.CreateCall(Ldrex, Addr);
21536
21537  CI->addParamAttr(
21538      0, Attribute::get(M->getContext(), Attribute::ElementType, ValueTy));
21539  return Builder.CreateTruncOrBitCast(CI, ValueTy);
21540}
21541
21542void ARMTargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
21543    IRBuilderBase &Builder) const {
21544  if (!Subtarget->hasV7Ops())
21545    return;
21546  Module *M = Builder.GetInsertBlock()->getParent()->getParent();
21547  Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::arm_clrex));
21548}
21549
21550Value *ARMTargetLowering::emitStoreConditional(IRBuilderBase &Builder,
21551                                               Value *Val, Value *Addr,
21552                                               AtomicOrdering Ord) const {
21553  Module *M = Builder.GetInsertBlock()->getParent()->getParent();
21554  bool IsRelease = isReleaseOrStronger(Ord);
21555
21556  // Since the intrinsics must have legal type, the i64 intrinsics take two
21557  // parameters: "i32, i32". We must marshal Val into the appropriate form
21558  // before the call.
21559  if (Val->getType()->getPrimitiveSizeInBits() == 64) {
21560    Intrinsic::ID Int =
21561        IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
21562    Function *Strex = Intrinsic::getDeclaration(M, Int);
21563    Type *Int32Ty = Type::getInt32Ty(M->getContext());
21564
21565    Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
21566    Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
21567    if (!Subtarget->isLittle())
21568      std::swap(Lo, Hi);
21569    return Builder.CreateCall(Strex, {Lo, Hi, Addr});
21570  }
21571
21572  Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
21573  Type *Tys[] = { Addr->getType() };
21574  Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
21575
21576  CallInst *CI = Builder.CreateCall(
21577      Strex, {Builder.CreateZExtOrBitCast(
21578                  Val, Strex->getFunctionType()->getParamType(0)),
21579              Addr});
21580  CI->addParamAttr(1, Attribute::get(M->getContext(), Attribute::ElementType,
21581                                     Val->getType()));
21582  return CI;
21583}
21584
21585
21586bool ARMTargetLowering::alignLoopsWithOptSize() const {
21587  return Subtarget->isMClass();
21588}
21589
21590/// A helper function for determining the number of interleaved accesses we
21591/// will generate when lowering accesses of the given type.
21592unsigned
21593ARMTargetLowering::getNumInterleavedAccesses(VectorType *VecTy,
21594                                             const DataLayout &DL) const {
21595  return (DL.getTypeSizeInBits(VecTy) + 127) / 128;
21596}
21597
21598bool ARMTargetLowering::isLegalInterleavedAccessType(
21599    unsigned Factor, FixedVectorType *VecTy, Align Alignment,
21600    const DataLayout &DL) const {
21601
21602  unsigned VecSize = DL.getTypeSizeInBits(VecTy);
21603  unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType());
21604
21605  if (!Subtarget->hasNEON() && !Subtarget->hasMVEIntegerOps())
21606    return false;
21607
21608  // Ensure the vector doesn't have f16 elements. Even though we could do an
21609  // i16 vldN, we can't hold the f16 vectors and will end up converting via
21610  // f32.
21611  if (Subtarget->hasNEON() && VecTy->getElementType()->isHalfTy())
21612    return false;
21613  if (Subtarget->hasMVEIntegerOps() && Factor == 3)
21614    return false;
21615
21616  // Ensure the number of vector elements is greater than 1.
21617  if (VecTy->getNumElements() < 2)
21618    return false;
21619
21620  // Ensure the element type is legal.
21621  if (ElSize != 8 && ElSize != 16 && ElSize != 32)
21622    return false;
21623  // And the alignment if high enough under MVE.
21624  if (Subtarget->hasMVEIntegerOps() && Alignment < ElSize / 8)
21625    return false;
21626
21627  // Ensure the total vector size is 64 or a multiple of 128. Types larger than
21628  // 128 will be split into multiple interleaved accesses.
21629  if (Subtarget->hasNEON() && VecSize == 64)
21630    return true;
21631  return VecSize % 128 == 0;
21632}
21633
21634unsigned ARMTargetLowering::getMaxSupportedInterleaveFactor() const {
21635  if (Subtarget->hasNEON())
21636    return 4;
21637  if (Subtarget->hasMVEIntegerOps())
21638    return MVEMaxSupportedInterleaveFactor;
21639  return TargetLoweringBase::getMaxSupportedInterleaveFactor();
21640}
21641
21642/// Lower an interleaved load into a vldN intrinsic.
21643///
21644/// E.g. Lower an interleaved load (Factor = 2):
21645///        %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4
21646///        %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6>  ; Extract even elements
21647///        %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7>  ; Extract odd elements
21648///
21649///      Into:
21650///        %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4)
21651///        %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0
21652///        %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1
21653bool ARMTargetLowering::lowerInterleavedLoad(
21654    LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
21655    ArrayRef<unsigned> Indices, unsigned Factor) const {
21656  assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
21657         "Invalid interleave factor");
21658  assert(!Shuffles.empty() && "Empty shufflevector input");
21659  assert(Shuffles.size() == Indices.size() &&
21660         "Unmatched number of shufflevectors and indices");
21661
21662  auto *VecTy = cast<FixedVectorType>(Shuffles[0]->getType());
21663  Type *EltTy = VecTy->getElementType();
21664
21665  const DataLayout &DL = LI->getModule()->getDataLayout();
21666  Align Alignment = LI->getAlign();
21667
21668  // Skip if we do not have NEON and skip illegal vector types. We can
21669  // "legalize" wide vector types into multiple interleaved accesses as long as
21670  // the vector types are divisible by 128.
21671  if (!isLegalInterleavedAccessType(Factor, VecTy, Alignment, DL))
21672    return false;
21673
21674  unsigned NumLoads = getNumInterleavedAccesses(VecTy, DL);
21675
21676  // A pointer vector can not be the return type of the ldN intrinsics. Need to
21677  // load integer vectors first and then convert to pointer vectors.
21678  if (EltTy->isPointerTy())
21679    VecTy = FixedVectorType::get(DL.getIntPtrType(EltTy), VecTy);
21680
21681  IRBuilder<> Builder(LI);
21682
21683  // The base address of the load.
21684  Value *BaseAddr = LI->getPointerOperand();
21685
21686  if (NumLoads > 1) {
21687    // If we're going to generate more than one load, reset the sub-vector type
21688    // to something legal.
21689    VecTy = FixedVectorType::get(VecTy->getElementType(),
21690                                 VecTy->getNumElements() / NumLoads);
21691  }
21692
21693  assert(isTypeLegal(EVT::getEVT(VecTy)) && "Illegal vldN vector type!");
21694
21695  auto createLoadIntrinsic = [&](Value *BaseAddr) {
21696    if (Subtarget->hasNEON()) {
21697      Type *PtrTy = Builder.getPtrTy(LI->getPointerAddressSpace());
21698      Type *Tys[] = {VecTy, PtrTy};
21699      static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2,
21700                                                Intrinsic::arm_neon_vld3,
21701                                                Intrinsic::arm_neon_vld4};
21702      Function *VldnFunc =
21703          Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
21704
21705      SmallVector<Value *, 2> Ops;
21706      Ops.push_back(BaseAddr);
21707      Ops.push_back(Builder.getInt32(LI->getAlign().value()));
21708
21709      return Builder.CreateCall(VldnFunc, Ops, "vldN");
21710    } else {
21711      assert((Factor == 2 || Factor == 4) &&
21712             "expected interleave factor of 2 or 4 for MVE");
21713      Intrinsic::ID LoadInts =
21714          Factor == 2 ? Intrinsic::arm_mve_vld2q : Intrinsic::arm_mve_vld4q;
21715      Type *PtrTy = Builder.getPtrTy(LI->getPointerAddressSpace());
21716      Type *Tys[] = {VecTy, PtrTy};
21717      Function *VldnFunc =
21718          Intrinsic::getDeclaration(LI->getModule(), LoadInts, Tys);
21719
21720      SmallVector<Value *, 2> Ops;
21721      Ops.push_back(BaseAddr);
21722      return Builder.CreateCall(VldnFunc, Ops, "vldN");
21723    }
21724  };
21725
21726  // Holds sub-vectors extracted from the load intrinsic return values. The
21727  // sub-vectors are associated with the shufflevector instructions they will
21728  // replace.
21729  DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs;
21730
21731  for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) {
21732    // If we're generating more than one load, compute the base address of
21733    // subsequent loads as an offset from the previous.
21734    if (LoadCount > 0)
21735      BaseAddr = Builder.CreateConstGEP1_32(VecTy->getElementType(), BaseAddr,
21736                                            VecTy->getNumElements() * Factor);
21737
21738    CallInst *VldN = createLoadIntrinsic(BaseAddr);
21739
21740    // Replace uses of each shufflevector with the corresponding vector loaded
21741    // by ldN.
21742    for (unsigned i = 0; i < Shuffles.size(); i++) {
21743      ShuffleVectorInst *SV = Shuffles[i];
21744      unsigned Index = Indices[i];
21745
21746      Value *SubVec = Builder.CreateExtractValue(VldN, Index);
21747
21748      // Convert the integer vector to pointer vector if the element is pointer.
21749      if (EltTy->isPointerTy())
21750        SubVec = Builder.CreateIntToPtr(
21751            SubVec,
21752            FixedVectorType::get(SV->getType()->getElementType(), VecTy));
21753
21754      SubVecs[SV].push_back(SubVec);
21755    }
21756  }
21757
21758  // Replace uses of the shufflevector instructions with the sub-vectors
21759  // returned by the load intrinsic. If a shufflevector instruction is
21760  // associated with more than one sub-vector, those sub-vectors will be
21761  // concatenated into a single wide vector.
21762  for (ShuffleVectorInst *SVI : Shuffles) {
21763    auto &SubVec = SubVecs[SVI];
21764    auto *WideVec =
21765        SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0];
21766    SVI->replaceAllUsesWith(WideVec);
21767  }
21768
21769  return true;
21770}
21771
21772/// Lower an interleaved store into a vstN intrinsic.
21773///
21774/// E.g. Lower an interleaved store (Factor = 3):
21775///        %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
21776///                                  <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
21777///        store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4
21778///
21779///      Into:
21780///        %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
21781///        %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
21782///        %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
21783///        call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
21784///
21785/// Note that the new shufflevectors will be removed and we'll only generate one
21786/// vst3 instruction in CodeGen.
21787///
21788/// Example for a more general valid mask (Factor 3). Lower:
21789///        %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1,
21790///                 <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19>
21791///        store <12 x i32> %i.vec, <12 x i32>* %ptr
21792///
21793///      Into:
21794///        %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7>
21795///        %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35>
21796///        %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19>
21797///        call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
21798bool ARMTargetLowering::lowerInterleavedStore(StoreInst *SI,
21799                                              ShuffleVectorInst *SVI,
21800                                              unsigned Factor) const {
21801  assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
21802         "Invalid interleave factor");
21803
21804  auto *VecTy = cast<FixedVectorType>(SVI->getType());
21805  assert(VecTy->getNumElements() % Factor == 0 && "Invalid interleaved store");
21806
21807  unsigned LaneLen = VecTy->getNumElements() / Factor;
21808  Type *EltTy = VecTy->getElementType();
21809  auto *SubVecTy = FixedVectorType::get(EltTy, LaneLen);
21810
21811  const DataLayout &DL = SI->getModule()->getDataLayout();
21812  Align Alignment = SI->getAlign();
21813
21814  // Skip if we do not have NEON and skip illegal vector types. We can
21815  // "legalize" wide vector types into multiple interleaved accesses as long as
21816  // the vector types are divisible by 128.
21817  if (!isLegalInterleavedAccessType(Factor, SubVecTy, Alignment, DL))
21818    return false;
21819
21820  unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL);
21821
21822  Value *Op0 = SVI->getOperand(0);
21823  Value *Op1 = SVI->getOperand(1);
21824  IRBuilder<> Builder(SI);
21825
21826  // StN intrinsics don't support pointer vectors as arguments. Convert pointer
21827  // vectors to integer vectors.
21828  if (EltTy->isPointerTy()) {
21829    Type *IntTy = DL.getIntPtrType(EltTy);
21830
21831    // Convert to the corresponding integer vector.
21832    auto *IntVecTy =
21833        FixedVectorType::get(IntTy, cast<FixedVectorType>(Op0->getType()));
21834    Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
21835    Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
21836
21837    SubVecTy = FixedVectorType::get(IntTy, LaneLen);
21838  }
21839
21840  // The base address of the store.
21841  Value *BaseAddr = SI->getPointerOperand();
21842
21843  if (NumStores > 1) {
21844    // If we're going to generate more than one store, reset the lane length
21845    // and sub-vector type to something legal.
21846    LaneLen /= NumStores;
21847    SubVecTy = FixedVectorType::get(SubVecTy->getElementType(), LaneLen);
21848  }
21849
21850  assert(isTypeLegal(EVT::getEVT(SubVecTy)) && "Illegal vstN vector type!");
21851
21852  auto Mask = SVI->getShuffleMask();
21853
21854  auto createStoreIntrinsic = [&](Value *BaseAddr,
21855                                  SmallVectorImpl<Value *> &Shuffles) {
21856    if (Subtarget->hasNEON()) {
21857      static const Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2,
21858                                                 Intrinsic::arm_neon_vst3,
21859                                                 Intrinsic::arm_neon_vst4};
21860      Type *PtrTy = Builder.getPtrTy(SI->getPointerAddressSpace());
21861      Type *Tys[] = {PtrTy, SubVecTy};
21862
21863      Function *VstNFunc = Intrinsic::getDeclaration(
21864          SI->getModule(), StoreInts[Factor - 2], Tys);
21865
21866      SmallVector<Value *, 6> Ops;
21867      Ops.push_back(BaseAddr);
21868      append_range(Ops, Shuffles);
21869      Ops.push_back(Builder.getInt32(SI->getAlign().value()));
21870      Builder.CreateCall(VstNFunc, Ops);
21871    } else {
21872      assert((Factor == 2 || Factor == 4) &&
21873             "expected interleave factor of 2 or 4 for MVE");
21874      Intrinsic::ID StoreInts =
21875          Factor == 2 ? Intrinsic::arm_mve_vst2q : Intrinsic::arm_mve_vst4q;
21876      Type *PtrTy = Builder.getPtrTy(SI->getPointerAddressSpace());
21877      Type *Tys[] = {PtrTy, SubVecTy};
21878      Function *VstNFunc =
21879          Intrinsic::getDeclaration(SI->getModule(), StoreInts, Tys);
21880
21881      SmallVector<Value *, 6> Ops;
21882      Ops.push_back(BaseAddr);
21883      append_range(Ops, Shuffles);
21884      for (unsigned F = 0; F < Factor; F++) {
21885        Ops.push_back(Builder.getInt32(F));
21886        Builder.CreateCall(VstNFunc, Ops);
21887        Ops.pop_back();
21888      }
21889    }
21890  };
21891
21892  for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) {
21893    // If we generating more than one store, we compute the base address of
21894    // subsequent stores as an offset from the previous.
21895    if (StoreCount > 0)
21896      BaseAddr = Builder.CreateConstGEP1_32(SubVecTy->getElementType(),
21897                                            BaseAddr, LaneLen * Factor);
21898
21899    SmallVector<Value *, 4> Shuffles;
21900
21901    // Split the shufflevector operands into sub vectors for the new vstN call.
21902    for (unsigned i = 0; i < Factor; i++) {
21903      unsigned IdxI = StoreCount * LaneLen * Factor + i;
21904      if (Mask[IdxI] >= 0) {
21905        Shuffles.push_back(Builder.CreateShuffleVector(
21906            Op0, Op1, createSequentialMask(Mask[IdxI], LaneLen, 0)));
21907      } else {
21908        unsigned StartMask = 0;
21909        for (unsigned j = 1; j < LaneLen; j++) {
21910          unsigned IdxJ = StoreCount * LaneLen * Factor + j;
21911          if (Mask[IdxJ * Factor + IdxI] >= 0) {
21912            StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ;
21913            break;
21914          }
21915        }
21916        // Note: If all elements in a chunk are undefs, StartMask=0!
21917        // Note: Filling undef gaps with random elements is ok, since
21918        // those elements were being written anyway (with undefs).
21919        // In the case of all undefs we're defaulting to using elems from 0
21920        // Note: StartMask cannot be negative, it's checked in
21921        // isReInterleaveMask
21922        Shuffles.push_back(Builder.CreateShuffleVector(
21923            Op0, Op1, createSequentialMask(StartMask, LaneLen, 0)));
21924      }
21925    }
21926
21927    createStoreIntrinsic(BaseAddr, Shuffles);
21928  }
21929  return true;
21930}
21931
21932enum HABaseType {
21933  HA_UNKNOWN = 0,
21934  HA_FLOAT,
21935  HA_DOUBLE,
21936  HA_VECT64,
21937  HA_VECT128
21938};
21939
21940static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
21941                                   uint64_t &Members) {
21942  if (auto *ST = dyn_cast<StructType>(Ty)) {
21943    for (unsigned i = 0; i < ST->getNumElements(); ++i) {
21944      uint64_t SubMembers = 0;
21945      if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
21946        return false;
21947      Members += SubMembers;
21948    }
21949  } else if (auto *AT = dyn_cast<ArrayType>(Ty)) {
21950    uint64_t SubMembers = 0;
21951    if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
21952      return false;
21953    Members += SubMembers * AT->getNumElements();
21954  } else if (Ty->isFloatTy()) {
21955    if (Base != HA_UNKNOWN && Base != HA_FLOAT)
21956      return false;
21957    Members = 1;
21958    Base = HA_FLOAT;
21959  } else if (Ty->isDoubleTy()) {
21960    if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
21961      return false;
21962    Members = 1;
21963    Base = HA_DOUBLE;
21964  } else if (auto *VT = dyn_cast<VectorType>(Ty)) {
21965    Members = 1;
21966    switch (Base) {
21967    case HA_FLOAT:
21968    case HA_DOUBLE:
21969      return false;
21970    case HA_VECT64:
21971      return VT->getPrimitiveSizeInBits().getFixedValue() == 64;
21972    case HA_VECT128:
21973      return VT->getPrimitiveSizeInBits().getFixedValue() == 128;
21974    case HA_UNKNOWN:
21975      switch (VT->getPrimitiveSizeInBits().getFixedValue()) {
21976      case 64:
21977        Base = HA_VECT64;
21978        return true;
21979      case 128:
21980        Base = HA_VECT128;
21981        return true;
21982      default:
21983        return false;
21984      }
21985    }
21986  }
21987
21988  return (Members > 0 && Members <= 4);
21989}
21990
21991/// Return the correct alignment for the current calling convention.
21992Align ARMTargetLowering::getABIAlignmentForCallingConv(
21993    Type *ArgTy, const DataLayout &DL) const {
21994  const Align ABITypeAlign = DL.getABITypeAlign(ArgTy);
21995  if (!ArgTy->isVectorTy())
21996    return ABITypeAlign;
21997
21998  // Avoid over-aligning vector parameters. It would require realigning the
21999  // stack and waste space for no real benefit.
22000  return std::min(ABITypeAlign, DL.getStackAlignment());
22001}
22002
22003/// Return true if a type is an AAPCS-VFP homogeneous aggregate or one of
22004/// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when
22005/// passing according to AAPCS rules.
22006bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
22007    Type *Ty, CallingConv::ID CallConv, bool isVarArg,
22008    const DataLayout &DL) const {
22009  if (getEffectiveCallingConv(CallConv, isVarArg) !=
22010      CallingConv::ARM_AAPCS_VFP)
22011    return false;
22012
22013  HABaseType Base = HA_UNKNOWN;
22014  uint64_t Members = 0;
22015  bool IsHA = isHomogeneousAggregate(Ty, Base, Members);
22016  LLVM_DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump());
22017
22018  bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy();
22019  return IsHA || IsIntArray;
22020}
22021
22022Register ARMTargetLowering::getExceptionPointerRegister(
22023    const Constant *PersonalityFn) const {
22024  // Platforms which do not use SjLj EH may return values in these registers
22025  // via the personality function.
22026  return Subtarget->useSjLjEH() ? Register() : ARM::R0;
22027}
22028
22029Register ARMTargetLowering::getExceptionSelectorRegister(
22030    const Constant *PersonalityFn) const {
22031  // Platforms which do not use SjLj EH may return values in these registers
22032  // via the personality function.
22033  return Subtarget->useSjLjEH() ? Register() : ARM::R1;
22034}
22035
22036void ARMTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
22037  // Update IsSplitCSR in ARMFunctionInfo.
22038  ARMFunctionInfo *AFI = Entry->getParent()->getInfo<ARMFunctionInfo>();
22039  AFI->setIsSplitCSR(true);
22040}
22041
22042void ARMTargetLowering::insertCopiesSplitCSR(
22043    MachineBasicBlock *Entry,
22044    const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
22045  const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
22046  const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
22047  if (!IStart)
22048    return;
22049
22050  const TargetInstrInfo *TII = Subtarget->getInstrInfo();
22051  MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
22052  MachineBasicBlock::iterator MBBI = Entry->begin();
22053  for (const MCPhysReg *I = IStart; *I; ++I) {
22054    const TargetRegisterClass *RC = nullptr;
22055    if (ARM::GPRRegClass.contains(*I))
22056      RC = &ARM::GPRRegClass;
22057    else if (ARM::DPRRegClass.contains(*I))
22058      RC = &ARM::DPRRegClass;
22059    else
22060      llvm_unreachable("Unexpected register class in CSRsViaCopy!");
22061
22062    Register NewVR = MRI->createVirtualRegister(RC);
22063    // Create copy from CSR to a virtual register.
22064    // FIXME: this currently does not emit CFI pseudo-instructions, it works
22065    // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
22066    // nounwind. If we want to generalize this later, we may need to emit
22067    // CFI pseudo-instructions.
22068    assert(Entry->getParent()->getFunction().hasFnAttribute(
22069               Attribute::NoUnwind) &&
22070           "Function should be nounwind in insertCopiesSplitCSR!");
22071    Entry->addLiveIn(*I);
22072    BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
22073        .addReg(*I);
22074
22075    // Insert the copy-back instructions right before the terminator.
22076    for (auto *Exit : Exits)
22077      BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
22078              TII->get(TargetOpcode::COPY), *I)
22079          .addReg(NewVR);
22080  }
22081}
22082
22083void ARMTargetLowering::finalizeLowering(MachineFunction &MF) const {
22084  MF.getFrameInfo().computeMaxCallFrameSize(MF);
22085  TargetLoweringBase::finalizeLowering(MF);
22086}
22087
22088bool ARMTargetLowering::isComplexDeinterleavingSupported() const {
22089  return Subtarget->hasMVEIntegerOps();
22090}
22091
22092bool ARMTargetLowering::isComplexDeinterleavingOperationSupported(
22093    ComplexDeinterleavingOperation Operation, Type *Ty) const {
22094  auto *VTy = dyn_cast<FixedVectorType>(Ty);
22095  if (!VTy)
22096    return false;
22097
22098  auto *ScalarTy = VTy->getScalarType();
22099  unsigned NumElements = VTy->getNumElements();
22100
22101  unsigned VTyWidth = VTy->getScalarSizeInBits() * NumElements;
22102  if (VTyWidth < 128 || !llvm::isPowerOf2_32(VTyWidth))
22103    return false;
22104
22105  // Both VCADD and VCMUL/VCMLA support the same types, F16 and F32
22106  if (ScalarTy->isHalfTy() || ScalarTy->isFloatTy())
22107    return Subtarget->hasMVEFloatOps();
22108
22109  if (Operation != ComplexDeinterleavingOperation::CAdd)
22110    return false;
22111
22112  return Subtarget->hasMVEIntegerOps() &&
22113         (ScalarTy->isIntegerTy(8) || ScalarTy->isIntegerTy(16) ||
22114          ScalarTy->isIntegerTy(32));
22115}
22116
22117Value *ARMTargetLowering::createComplexDeinterleavingIR(
22118    IRBuilderBase &B, ComplexDeinterleavingOperation OperationType,
22119    ComplexDeinterleavingRotation Rotation, Value *InputA, Value *InputB,
22120    Value *Accumulator) const {
22121
22122  FixedVectorType *Ty = cast<FixedVectorType>(InputA->getType());
22123
22124  unsigned TyWidth = Ty->getScalarSizeInBits() * Ty->getNumElements();
22125
22126  assert(TyWidth >= 128 && "Width of vector type must be at least 128 bits");
22127
22128  if (TyWidth > 128) {
22129    int Stride = Ty->getNumElements() / 2;
22130    auto SplitSeq = llvm::seq<int>(0, Ty->getNumElements());
22131    auto SplitSeqVec = llvm::to_vector(SplitSeq);
22132    ArrayRef<int> LowerSplitMask(&SplitSeqVec[0], Stride);
22133    ArrayRef<int> UpperSplitMask(&SplitSeqVec[Stride], Stride);
22134
22135    auto *LowerSplitA = B.CreateShuffleVector(InputA, LowerSplitMask);
22136    auto *LowerSplitB = B.CreateShuffleVector(InputB, LowerSplitMask);
22137    auto *UpperSplitA = B.CreateShuffleVector(InputA, UpperSplitMask);
22138    auto *UpperSplitB = B.CreateShuffleVector(InputB, UpperSplitMask);
22139    Value *LowerSplitAcc = nullptr;
22140    Value *UpperSplitAcc = nullptr;
22141
22142    if (Accumulator) {
22143      LowerSplitAcc = B.CreateShuffleVector(Accumulator, LowerSplitMask);
22144      UpperSplitAcc = B.CreateShuffleVector(Accumulator, UpperSplitMask);
22145    }
22146
22147    auto *LowerSplitInt = createComplexDeinterleavingIR(
22148        B, OperationType, Rotation, LowerSplitA, LowerSplitB, LowerSplitAcc);
22149    auto *UpperSplitInt = createComplexDeinterleavingIR(
22150        B, OperationType, Rotation, UpperSplitA, UpperSplitB, UpperSplitAcc);
22151
22152    ArrayRef<int> JoinMask(&SplitSeqVec[0], Ty->getNumElements());
22153    return B.CreateShuffleVector(LowerSplitInt, UpperSplitInt, JoinMask);
22154  }
22155
22156  auto *IntTy = Type::getInt32Ty(B.getContext());
22157
22158  ConstantInt *ConstRotation = nullptr;
22159  if (OperationType == ComplexDeinterleavingOperation::CMulPartial) {
22160    ConstRotation = ConstantInt::get(IntTy, (int)Rotation);
22161
22162    if (Accumulator)
22163      return B.CreateIntrinsic(Intrinsic::arm_mve_vcmlaq, Ty,
22164                               {ConstRotation, Accumulator, InputB, InputA});
22165    return B.CreateIntrinsic(Intrinsic::arm_mve_vcmulq, Ty,
22166                             {ConstRotation, InputB, InputA});
22167  }
22168
22169  if (OperationType == ComplexDeinterleavingOperation::CAdd) {
22170    // 1 means the value is not halved.
22171    auto *ConstHalving = ConstantInt::get(IntTy, 1);
22172
22173    if (Rotation == ComplexDeinterleavingRotation::Rotation_90)
22174      ConstRotation = ConstantInt::get(IntTy, 0);
22175    else if (Rotation == ComplexDeinterleavingRotation::Rotation_270)
22176      ConstRotation = ConstantInt::get(IntTy, 1);
22177
22178    if (!ConstRotation)
22179      return nullptr; // Invalid rotation for arm_mve_vcaddq
22180
22181    return B.CreateIntrinsic(Intrinsic::arm_mve_vcaddq, Ty,
22182                             {ConstHalving, ConstRotation, InputA, InputB});
22183  }
22184
22185  return nullptr;
22186}
22187