1 //===- ARMTargetTransformInfo.cpp - ARM specific TTI ----------------------===//
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 #include "ARMTargetTransformInfo.h"
10 #include "ARMSubtarget.h"
11 #include "MCTargetDesc/ARMAddressingModes.h"
12 #include "llvm/ADT/APInt.h"
13 #include "llvm/ADT/SmallVector.h"
14 #include "llvm/Analysis/LoopInfo.h"
15 #include "llvm/CodeGen/CostTable.h"
16 #include "llvm/CodeGen/ISDOpcodes.h"
17 #include "llvm/CodeGen/ValueTypes.h"
18 #include "llvm/IR/BasicBlock.h"
19 #include "llvm/IR/DataLayout.h"
20 #include "llvm/IR/DerivedTypes.h"
21 #include "llvm/IR/Instruction.h"
22 #include "llvm/IR/Instructions.h"
23 #include "llvm/IR/IntrinsicInst.h"
24 #include "llvm/IR/PatternMatch.h"
25 #include "llvm/IR/Type.h"
26 #include "llvm/MC/SubtargetFeature.h"
27 #include "llvm/Support/Casting.h"
28 #include "llvm/Support/MachineValueType.h"
29 #include "llvm/Target/TargetMachine.h"
30 #include <algorithm>
31 #include <cassert>
32 #include <cstdint>
33 #include <utility>
34 
35 using namespace llvm;
36 
37 #define DEBUG_TYPE "armtti"
38 
39 static cl::opt<bool> EnableMaskedLoadStores(
40   "enable-arm-maskedldst", cl::Hidden, cl::init(true),
41   cl::desc("Enable the generation of masked loads and stores"));
42 
43 static cl::opt<bool> DisableLowOverheadLoops(
44   "disable-arm-loloops", cl::Hidden, cl::init(false),
45   cl::desc("Disable the generation of low-overhead loops"));
46 
47 extern cl::opt<bool> DisableTailPredication;
48 
49 extern cl::opt<bool> EnableMaskedGatherScatters;
50 
51 bool ARMTTIImpl::areInlineCompatible(const Function *Caller,
52                                      const Function *Callee) const {
53   const TargetMachine &TM = getTLI()->getTargetMachine();
54   const FeatureBitset &CallerBits =
55       TM.getSubtargetImpl(*Caller)->getFeatureBits();
56   const FeatureBitset &CalleeBits =
57       TM.getSubtargetImpl(*Callee)->getFeatureBits();
58 
59   // To inline a callee, all features not in the whitelist must match exactly.
60   bool MatchExact = (CallerBits & ~InlineFeatureWhitelist) ==
61                     (CalleeBits & ~InlineFeatureWhitelist);
62   // For features in the whitelist, the callee's features must be a subset of
63   // the callers'.
64   bool MatchSubset = ((CallerBits & CalleeBits) & InlineFeatureWhitelist) ==
65                      (CalleeBits & InlineFeatureWhitelist);
66   return MatchExact && MatchSubset;
67 }
68 
69 bool ARMTTIImpl::shouldFavorBackedgeIndex(const Loop *L) const {
70   if (L->getHeader()->getParent()->hasOptSize())
71     return false;
72   if (ST->hasMVEIntegerOps())
73     return false;
74   return ST->isMClass() && ST->isThumb2() && L->getNumBlocks() == 1;
75 }
76 
77 bool ARMTTIImpl::shouldFavorPostInc() const {
78   if (ST->hasMVEIntegerOps())
79     return true;
80   return false;
81 }
82 
83 int ARMTTIImpl::getIntImmCost(const APInt &Imm, Type *Ty,
84                               TTI::TargetCostKind CostKind) {
85   assert(Ty->isIntegerTy());
86 
87  unsigned Bits = Ty->getPrimitiveSizeInBits();
88  if (Bits == 0 || Imm.getActiveBits() >= 64)
89    return 4;
90 
91   int64_t SImmVal = Imm.getSExtValue();
92   uint64_t ZImmVal = Imm.getZExtValue();
93   if (!ST->isThumb()) {
94     if ((SImmVal >= 0 && SImmVal < 65536) ||
95         (ARM_AM::getSOImmVal(ZImmVal) != -1) ||
96         (ARM_AM::getSOImmVal(~ZImmVal) != -1))
97       return 1;
98     return ST->hasV6T2Ops() ? 2 : 3;
99   }
100   if (ST->isThumb2()) {
101     if ((SImmVal >= 0 && SImmVal < 65536) ||
102         (ARM_AM::getT2SOImmVal(ZImmVal) != -1) ||
103         (ARM_AM::getT2SOImmVal(~ZImmVal) != -1))
104       return 1;
105     return ST->hasV6T2Ops() ? 2 : 3;
106   }
107   // Thumb1, any i8 imm cost 1.
108   if (Bits == 8 || (SImmVal >= 0 && SImmVal < 256))
109     return 1;
110   if ((~SImmVal < 256) || ARM_AM::isThumbImmShiftedVal(ZImmVal))
111     return 2;
112   // Load from constantpool.
113   return 3;
114 }
115 
116 // Constants smaller than 256 fit in the immediate field of
117 // Thumb1 instructions so we return a zero cost and 1 otherwise.
118 int ARMTTIImpl::getIntImmCodeSizeCost(unsigned Opcode, unsigned Idx,
119                                       const APInt &Imm, Type *Ty) {
120   if (Imm.isNonNegative() && Imm.getLimitedValue() < 256)
121     return 0;
122 
123   return 1;
124 }
125 
126 int ARMTTIImpl::getIntImmCostInst(unsigned Opcode, unsigned Idx, const APInt &Imm,
127                                   Type *Ty, TTI::TargetCostKind CostKind) {
128   // Division by a constant can be turned into multiplication, but only if we
129   // know it's constant. So it's not so much that the immediate is cheap (it's
130   // not), but that the alternative is worse.
131   // FIXME: this is probably unneeded with GlobalISel.
132   if ((Opcode == Instruction::SDiv || Opcode == Instruction::UDiv ||
133        Opcode == Instruction::SRem || Opcode == Instruction::URem) &&
134       Idx == 1)
135     return 0;
136 
137   if (Opcode == Instruction::And) {
138     // UXTB/UXTH
139     if (Imm == 255 || Imm == 65535)
140       return 0;
141     // Conversion to BIC is free, and means we can use ~Imm instead.
142     return std::min(getIntImmCost(Imm, Ty, CostKind),
143                     getIntImmCost(~Imm, Ty, CostKind));
144   }
145 
146   if (Opcode == Instruction::Add)
147     // Conversion to SUB is free, and means we can use -Imm instead.
148     return std::min(getIntImmCost(Imm, Ty, CostKind),
149                     getIntImmCost(-Imm, Ty, CostKind));
150 
151   if (Opcode == Instruction::ICmp && Imm.isNegative() &&
152       Ty->getIntegerBitWidth() == 32) {
153     int64_t NegImm = -Imm.getSExtValue();
154     if (ST->isThumb2() && NegImm < 1<<12)
155       // icmp X, #-C -> cmn X, #C
156       return 0;
157     if (ST->isThumb() && NegImm < 1<<8)
158       // icmp X, #-C -> adds X, #C
159       return 0;
160   }
161 
162   // xor a, -1 can always be folded to MVN
163   if (Opcode == Instruction::Xor && Imm.isAllOnesValue())
164     return 0;
165 
166   return getIntImmCost(Imm, Ty, CostKind);
167 }
168 
169 int ARMTTIImpl::getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src,
170                                  TTI::TargetCostKind CostKind,
171                                  const Instruction *I) {
172   int ISD = TLI->InstructionOpcodeToISD(Opcode);
173   assert(ISD && "Invalid opcode");
174 
175   // Single to/from double precision conversions.
176   static const CostTblEntry NEONFltDblTbl[] = {
177     // Vector fptrunc/fpext conversions.
178     { ISD::FP_ROUND,   MVT::v2f64, 2 },
179     { ISD::FP_EXTEND,  MVT::v2f32, 2 },
180     { ISD::FP_EXTEND,  MVT::v4f32, 4 }
181   };
182 
183   if (Src->isVectorTy() && ST->hasNEON() && (ISD == ISD::FP_ROUND ||
184                                           ISD == ISD::FP_EXTEND)) {
185     std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Src);
186     if (const auto *Entry = CostTableLookup(NEONFltDblTbl, ISD, LT.second))
187       return LT.first * Entry->Cost;
188   }
189 
190   EVT SrcTy = TLI->getValueType(DL, Src);
191   EVT DstTy = TLI->getValueType(DL, Dst);
192 
193   if (!SrcTy.isSimple() || !DstTy.isSimple())
194     return BaseT::getCastInstrCost(Opcode, Dst, Src, CostKind);
195 
196   // The extend of a load is free
197   if (I && isa<LoadInst>(I->getOperand(0))) {
198     static const TypeConversionCostTblEntry LoadConversionTbl[] = {
199         {ISD::SIGN_EXTEND, MVT::i32, MVT::i16, 0},
200         {ISD::ZERO_EXTEND, MVT::i32, MVT::i16, 0},
201         {ISD::SIGN_EXTEND, MVT::i32, MVT::i8, 0},
202         {ISD::ZERO_EXTEND, MVT::i32, MVT::i8, 0},
203         {ISD::SIGN_EXTEND, MVT::i16, MVT::i8, 0},
204         {ISD::ZERO_EXTEND, MVT::i16, MVT::i8, 0},
205         {ISD::SIGN_EXTEND, MVT::i64, MVT::i32, 1},
206         {ISD::ZERO_EXTEND, MVT::i64, MVT::i32, 1},
207         {ISD::SIGN_EXTEND, MVT::i64, MVT::i16, 1},
208         {ISD::ZERO_EXTEND, MVT::i64, MVT::i16, 1},
209         {ISD::SIGN_EXTEND, MVT::i64, MVT::i8, 1},
210         {ISD::ZERO_EXTEND, MVT::i64, MVT::i8, 1},
211     };
212     if (const auto *Entry = ConvertCostTableLookup(
213             LoadConversionTbl, ISD, DstTy.getSimpleVT(), SrcTy.getSimpleVT()))
214       return Entry->Cost;
215 
216     static const TypeConversionCostTblEntry MVELoadConversionTbl[] = {
217         {ISD::SIGN_EXTEND, MVT::v4i32, MVT::v4i16, 0},
218         {ISD::ZERO_EXTEND, MVT::v4i32, MVT::v4i16, 0},
219         {ISD::SIGN_EXTEND, MVT::v4i32, MVT::v4i8, 0},
220         {ISD::ZERO_EXTEND, MVT::v4i32, MVT::v4i8, 0},
221         {ISD::SIGN_EXTEND, MVT::v8i16, MVT::v8i8, 0},
222         {ISD::ZERO_EXTEND, MVT::v8i16, MVT::v8i8, 0},
223     };
224     if (SrcTy.isVector() && ST->hasMVEIntegerOps()) {
225       if (const auto *Entry =
226               ConvertCostTableLookup(MVELoadConversionTbl, ISD,
227                                      DstTy.getSimpleVT(), SrcTy.getSimpleVT()))
228         return Entry->Cost;
229     }
230   }
231 
232   // Some arithmetic, load and store operations have specific instructions
233   // to cast up/down their types automatically at no extra cost.
234   // TODO: Get these tables to know at least what the related operations are.
235   static const TypeConversionCostTblEntry NEONVectorConversionTbl[] = {
236     { ISD::SIGN_EXTEND, MVT::v4i32, MVT::v4i16, 0 },
237     { ISD::ZERO_EXTEND, MVT::v4i32, MVT::v4i16, 0 },
238     { ISD::SIGN_EXTEND, MVT::v2i64, MVT::v2i32, 1 },
239     { ISD::ZERO_EXTEND, MVT::v2i64, MVT::v2i32, 1 },
240     { ISD::TRUNCATE,    MVT::v4i32, MVT::v4i64, 0 },
241     { ISD::TRUNCATE,    MVT::v4i16, MVT::v4i32, 1 },
242 
243     // The number of vmovl instructions for the extension.
244     { ISD::SIGN_EXTEND, MVT::v4i64, MVT::v4i16, 3 },
245     { ISD::ZERO_EXTEND, MVT::v4i64, MVT::v4i16, 3 },
246     { ISD::SIGN_EXTEND, MVT::v8i32, MVT::v8i8, 3 },
247     { ISD::ZERO_EXTEND, MVT::v8i32, MVT::v8i8, 3 },
248     { ISD::SIGN_EXTEND, MVT::v8i64, MVT::v8i8, 7 },
249     { ISD::ZERO_EXTEND, MVT::v8i64, MVT::v8i8, 7 },
250     { ISD::SIGN_EXTEND, MVT::v8i64, MVT::v8i16, 6 },
251     { ISD::ZERO_EXTEND, MVT::v8i64, MVT::v8i16, 6 },
252     { ISD::SIGN_EXTEND, MVT::v16i32, MVT::v16i8, 6 },
253     { ISD::ZERO_EXTEND, MVT::v16i32, MVT::v16i8, 6 },
254 
255     // Operations that we legalize using splitting.
256     { ISD::TRUNCATE,    MVT::v16i8, MVT::v16i32, 6 },
257     { ISD::TRUNCATE,    MVT::v8i8, MVT::v8i32, 3 },
258 
259     // Vector float <-> i32 conversions.
260     { ISD::SINT_TO_FP,  MVT::v4f32, MVT::v4i32, 1 },
261     { ISD::UINT_TO_FP,  MVT::v4f32, MVT::v4i32, 1 },
262 
263     { ISD::SINT_TO_FP,  MVT::v2f32, MVT::v2i8, 3 },
264     { ISD::UINT_TO_FP,  MVT::v2f32, MVT::v2i8, 3 },
265     { ISD::SINT_TO_FP,  MVT::v2f32, MVT::v2i16, 2 },
266     { ISD::UINT_TO_FP,  MVT::v2f32, MVT::v2i16, 2 },
267     { ISD::SINT_TO_FP,  MVT::v2f32, MVT::v2i32, 1 },
268     { ISD::UINT_TO_FP,  MVT::v2f32, MVT::v2i32, 1 },
269     { ISD::SINT_TO_FP,  MVT::v4f32, MVT::v4i1, 3 },
270     { ISD::UINT_TO_FP,  MVT::v4f32, MVT::v4i1, 3 },
271     { ISD::SINT_TO_FP,  MVT::v4f32, MVT::v4i8, 3 },
272     { ISD::UINT_TO_FP,  MVT::v4f32, MVT::v4i8, 3 },
273     { ISD::SINT_TO_FP,  MVT::v4f32, MVT::v4i16, 2 },
274     { ISD::UINT_TO_FP,  MVT::v4f32, MVT::v4i16, 2 },
275     { ISD::SINT_TO_FP,  MVT::v8f32, MVT::v8i16, 4 },
276     { ISD::UINT_TO_FP,  MVT::v8f32, MVT::v8i16, 4 },
277     { ISD::SINT_TO_FP,  MVT::v8f32, MVT::v8i32, 2 },
278     { ISD::UINT_TO_FP,  MVT::v8f32, MVT::v8i32, 2 },
279     { ISD::SINT_TO_FP,  MVT::v16f32, MVT::v16i16, 8 },
280     { ISD::UINT_TO_FP,  MVT::v16f32, MVT::v16i16, 8 },
281     { ISD::SINT_TO_FP,  MVT::v16f32, MVT::v16i32, 4 },
282     { ISD::UINT_TO_FP,  MVT::v16f32, MVT::v16i32, 4 },
283 
284     { ISD::FP_TO_SINT,  MVT::v4i32, MVT::v4f32, 1 },
285     { ISD::FP_TO_UINT,  MVT::v4i32, MVT::v4f32, 1 },
286     { ISD::FP_TO_SINT,  MVT::v4i8, MVT::v4f32, 3 },
287     { ISD::FP_TO_UINT,  MVT::v4i8, MVT::v4f32, 3 },
288     { ISD::FP_TO_SINT,  MVT::v4i16, MVT::v4f32, 2 },
289     { ISD::FP_TO_UINT,  MVT::v4i16, MVT::v4f32, 2 },
290 
291     // Vector double <-> i32 conversions.
292     { ISD::SINT_TO_FP,  MVT::v2f64, MVT::v2i32, 2 },
293     { ISD::UINT_TO_FP,  MVT::v2f64, MVT::v2i32, 2 },
294 
295     { ISD::SINT_TO_FP,  MVT::v2f64, MVT::v2i8, 4 },
296     { ISD::UINT_TO_FP,  MVT::v2f64, MVT::v2i8, 4 },
297     { ISD::SINT_TO_FP,  MVT::v2f64, MVT::v2i16, 3 },
298     { ISD::UINT_TO_FP,  MVT::v2f64, MVT::v2i16, 3 },
299     { ISD::SINT_TO_FP,  MVT::v2f64, MVT::v2i32, 2 },
300     { ISD::UINT_TO_FP,  MVT::v2f64, MVT::v2i32, 2 },
301 
302     { ISD::FP_TO_SINT,  MVT::v2i32, MVT::v2f64, 2 },
303     { ISD::FP_TO_UINT,  MVT::v2i32, MVT::v2f64, 2 },
304     { ISD::FP_TO_SINT,  MVT::v8i16, MVT::v8f32, 4 },
305     { ISD::FP_TO_UINT,  MVT::v8i16, MVT::v8f32, 4 },
306     { ISD::FP_TO_SINT,  MVT::v16i16, MVT::v16f32, 8 },
307     { ISD::FP_TO_UINT,  MVT::v16i16, MVT::v16f32, 8 }
308   };
309 
310   if (SrcTy.isVector() && ST->hasNEON()) {
311     if (const auto *Entry = ConvertCostTableLookup(NEONVectorConversionTbl, ISD,
312                                                    DstTy.getSimpleVT(),
313                                                    SrcTy.getSimpleVT()))
314       return Entry->Cost;
315   }
316 
317   // Scalar float to integer conversions.
318   static const TypeConversionCostTblEntry NEONFloatConversionTbl[] = {
319     { ISD::FP_TO_SINT,  MVT::i1, MVT::f32, 2 },
320     { ISD::FP_TO_UINT,  MVT::i1, MVT::f32, 2 },
321     { ISD::FP_TO_SINT,  MVT::i1, MVT::f64, 2 },
322     { ISD::FP_TO_UINT,  MVT::i1, MVT::f64, 2 },
323     { ISD::FP_TO_SINT,  MVT::i8, MVT::f32, 2 },
324     { ISD::FP_TO_UINT,  MVT::i8, MVT::f32, 2 },
325     { ISD::FP_TO_SINT,  MVT::i8, MVT::f64, 2 },
326     { ISD::FP_TO_UINT,  MVT::i8, MVT::f64, 2 },
327     { ISD::FP_TO_SINT,  MVT::i16, MVT::f32, 2 },
328     { ISD::FP_TO_UINT,  MVT::i16, MVT::f32, 2 },
329     { ISD::FP_TO_SINT,  MVT::i16, MVT::f64, 2 },
330     { ISD::FP_TO_UINT,  MVT::i16, MVT::f64, 2 },
331     { ISD::FP_TO_SINT,  MVT::i32, MVT::f32, 2 },
332     { ISD::FP_TO_UINT,  MVT::i32, MVT::f32, 2 },
333     { ISD::FP_TO_SINT,  MVT::i32, MVT::f64, 2 },
334     { ISD::FP_TO_UINT,  MVT::i32, MVT::f64, 2 },
335     { ISD::FP_TO_SINT,  MVT::i64, MVT::f32, 10 },
336     { ISD::FP_TO_UINT,  MVT::i64, MVT::f32, 10 },
337     { ISD::FP_TO_SINT,  MVT::i64, MVT::f64, 10 },
338     { ISD::FP_TO_UINT,  MVT::i64, MVT::f64, 10 }
339   };
340   if (SrcTy.isFloatingPoint() && ST->hasNEON()) {
341     if (const auto *Entry = ConvertCostTableLookup(NEONFloatConversionTbl, ISD,
342                                                    DstTy.getSimpleVT(),
343                                                    SrcTy.getSimpleVT()))
344       return Entry->Cost;
345   }
346 
347   // Scalar integer to float conversions.
348   static const TypeConversionCostTblEntry NEONIntegerConversionTbl[] = {
349     { ISD::SINT_TO_FP,  MVT::f32, MVT::i1, 2 },
350     { ISD::UINT_TO_FP,  MVT::f32, MVT::i1, 2 },
351     { ISD::SINT_TO_FP,  MVT::f64, MVT::i1, 2 },
352     { ISD::UINT_TO_FP,  MVT::f64, MVT::i1, 2 },
353     { ISD::SINT_TO_FP,  MVT::f32, MVT::i8, 2 },
354     { ISD::UINT_TO_FP,  MVT::f32, MVT::i8, 2 },
355     { ISD::SINT_TO_FP,  MVT::f64, MVT::i8, 2 },
356     { ISD::UINT_TO_FP,  MVT::f64, MVT::i8, 2 },
357     { ISD::SINT_TO_FP,  MVT::f32, MVT::i16, 2 },
358     { ISD::UINT_TO_FP,  MVT::f32, MVT::i16, 2 },
359     { ISD::SINT_TO_FP,  MVT::f64, MVT::i16, 2 },
360     { ISD::UINT_TO_FP,  MVT::f64, MVT::i16, 2 },
361     { ISD::SINT_TO_FP,  MVT::f32, MVT::i32, 2 },
362     { ISD::UINT_TO_FP,  MVT::f32, MVT::i32, 2 },
363     { ISD::SINT_TO_FP,  MVT::f64, MVT::i32, 2 },
364     { ISD::UINT_TO_FP,  MVT::f64, MVT::i32, 2 },
365     { ISD::SINT_TO_FP,  MVT::f32, MVT::i64, 10 },
366     { ISD::UINT_TO_FP,  MVT::f32, MVT::i64, 10 },
367     { ISD::SINT_TO_FP,  MVT::f64, MVT::i64, 10 },
368     { ISD::UINT_TO_FP,  MVT::f64, MVT::i64, 10 }
369   };
370 
371   if (SrcTy.isInteger() && ST->hasNEON()) {
372     if (const auto *Entry = ConvertCostTableLookup(NEONIntegerConversionTbl,
373                                                    ISD, DstTy.getSimpleVT(),
374                                                    SrcTy.getSimpleVT()))
375       return Entry->Cost;
376   }
377 
378   // MVE extend costs, taken from codegen tests. i8->i16 or i16->i32 is one
379   // instruction, i8->i32 is two. i64 zexts are an VAND with a constant, sext
380   // are linearised so take more.
381   static const TypeConversionCostTblEntry MVEVectorConversionTbl[] = {
382     { ISD::SIGN_EXTEND, MVT::v8i16, MVT::v8i8, 1 },
383     { ISD::ZERO_EXTEND, MVT::v8i16, MVT::v8i8, 1 },
384     { ISD::SIGN_EXTEND, MVT::v4i32, MVT::v4i8, 2 },
385     { ISD::ZERO_EXTEND, MVT::v4i32, MVT::v4i8, 2 },
386     { ISD::SIGN_EXTEND, MVT::v2i64, MVT::v2i8, 10 },
387     { ISD::ZERO_EXTEND, MVT::v2i64, MVT::v2i8, 2 },
388     { ISD::SIGN_EXTEND, MVT::v4i32, MVT::v4i16, 1 },
389     { ISD::ZERO_EXTEND, MVT::v4i32, MVT::v4i16, 1 },
390     { ISD::SIGN_EXTEND, MVT::v2i64, MVT::v2i16, 10 },
391     { ISD::ZERO_EXTEND, MVT::v2i64, MVT::v2i16, 2 },
392     { ISD::SIGN_EXTEND, MVT::v2i64, MVT::v2i32, 8 },
393     { ISD::ZERO_EXTEND, MVT::v2i64, MVT::v2i32, 2 },
394   };
395 
396   if (SrcTy.isVector() && ST->hasMVEIntegerOps()) {
397     if (const auto *Entry = ConvertCostTableLookup(MVEVectorConversionTbl,
398                                                    ISD, DstTy.getSimpleVT(),
399                                                    SrcTy.getSimpleVT()))
400       return Entry->Cost * ST->getMVEVectorCostFactor();
401   }
402 
403   // Scalar integer conversion costs.
404   static const TypeConversionCostTblEntry ARMIntegerConversionTbl[] = {
405     // i16 -> i64 requires two dependent operations.
406     { ISD::SIGN_EXTEND, MVT::i64, MVT::i16, 2 },
407 
408     // Truncates on i64 are assumed to be free.
409     { ISD::TRUNCATE,    MVT::i32, MVT::i64, 0 },
410     { ISD::TRUNCATE,    MVT::i16, MVT::i64, 0 },
411     { ISD::TRUNCATE,    MVT::i8,  MVT::i64, 0 },
412     { ISD::TRUNCATE,    MVT::i1,  MVT::i64, 0 }
413   };
414 
415   if (SrcTy.isInteger()) {
416     if (const auto *Entry = ConvertCostTableLookup(ARMIntegerConversionTbl, ISD,
417                                                    DstTy.getSimpleVT(),
418                                                    SrcTy.getSimpleVT()))
419       return Entry->Cost;
420   }
421 
422   int BaseCost = ST->hasMVEIntegerOps() && Src->isVectorTy()
423                      ? ST->getMVEVectorCostFactor()
424                      : 1;
425   return BaseCost * BaseT::getCastInstrCost(Opcode, Dst, Src, CostKind);
426 }
427 
428 int ARMTTIImpl::getVectorInstrCost(unsigned Opcode, Type *ValTy,
429                                    unsigned Index) {
430   // Penalize inserting into an D-subregister. We end up with a three times
431   // lower estimated throughput on swift.
432   if (ST->hasSlowLoadDSubregister() && Opcode == Instruction::InsertElement &&
433       ValTy->isVectorTy() && ValTy->getScalarSizeInBits() <= 32)
434     return 3;
435 
436   if (ST->hasNEON() && (Opcode == Instruction::InsertElement ||
437                         Opcode == Instruction::ExtractElement)) {
438     // Cross-class copies are expensive on many microarchitectures,
439     // so assume they are expensive by default.
440     if (cast<VectorType>(ValTy)->getElementType()->isIntegerTy())
441       return 3;
442 
443     // Even if it's not a cross class copy, this likely leads to mixing
444     // of NEON and VFP code and should be therefore penalized.
445     if (ValTy->isVectorTy() &&
446         ValTy->getScalarSizeInBits() <= 32)
447       return std::max(BaseT::getVectorInstrCost(Opcode, ValTy, Index), 2U);
448   }
449 
450   if (ST->hasMVEIntegerOps() && (Opcode == Instruction::InsertElement ||
451                                  Opcode == Instruction::ExtractElement)) {
452     // We say MVE moves costs at least the MVEVectorCostFactor, even though
453     // they are scalar instructions. This helps prevent mixing scalar and
454     // vector, to prevent vectorising where we end up just scalarising the
455     // result anyway.
456     return std::max(BaseT::getVectorInstrCost(Opcode, ValTy, Index),
457                     ST->getMVEVectorCostFactor()) *
458            cast<VectorType>(ValTy)->getNumElements() / 2;
459   }
460 
461   return BaseT::getVectorInstrCost(Opcode, ValTy, Index);
462 }
463 
464 int ARMTTIImpl::getCmpSelInstrCost(unsigned Opcode, Type *ValTy, Type *CondTy,
465                                    TTI::TargetCostKind CostKind,
466                                    const Instruction *I) {
467   int ISD = TLI->InstructionOpcodeToISD(Opcode);
468   // On NEON a vector select gets lowered to vbsl.
469   if (ST->hasNEON() && ValTy->isVectorTy() && ISD == ISD::SELECT) {
470     // Lowering of some vector selects is currently far from perfect.
471     static const TypeConversionCostTblEntry NEONVectorSelectTbl[] = {
472       { ISD::SELECT, MVT::v4i1, MVT::v4i64, 4*4 + 1*2 + 1 },
473       { ISD::SELECT, MVT::v8i1, MVT::v8i64, 50 },
474       { ISD::SELECT, MVT::v16i1, MVT::v16i64, 100 }
475     };
476 
477     EVT SelCondTy = TLI->getValueType(DL, CondTy);
478     EVT SelValTy = TLI->getValueType(DL, ValTy);
479     if (SelCondTy.isSimple() && SelValTy.isSimple()) {
480       if (const auto *Entry = ConvertCostTableLookup(NEONVectorSelectTbl, ISD,
481                                                      SelCondTy.getSimpleVT(),
482                                                      SelValTy.getSimpleVT()))
483         return Entry->Cost;
484     }
485 
486     std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, ValTy);
487     return LT.first;
488   }
489 
490   int BaseCost = ST->hasMVEIntegerOps() && ValTy->isVectorTy()
491                      ? ST->getMVEVectorCostFactor()
492                      : 1;
493   return BaseCost * BaseT::getCmpSelInstrCost(Opcode, ValTy, CondTy, CostKind,
494                                               I);
495 }
496 
497 int ARMTTIImpl::getAddressComputationCost(Type *Ty, ScalarEvolution *SE,
498                                           const SCEV *Ptr) {
499   // Address computations in vectorized code with non-consecutive addresses will
500   // likely result in more instructions compared to scalar code where the
501   // computation can more often be merged into the index mode. The resulting
502   // extra micro-ops can significantly decrease throughput.
503   unsigned NumVectorInstToHideOverhead = 10;
504   int MaxMergeDistance = 64;
505 
506   if (ST->hasNEON()) {
507     if (Ty->isVectorTy() && SE &&
508         !BaseT::isConstantStridedAccessLessThan(SE, Ptr, MaxMergeDistance + 1))
509       return NumVectorInstToHideOverhead;
510 
511     // In many cases the address computation is not merged into the instruction
512     // addressing mode.
513     return 1;
514   }
515   return BaseT::getAddressComputationCost(Ty, SE, Ptr);
516 }
517 
518 bool ARMTTIImpl::isLegalMaskedLoad(Type *DataTy, MaybeAlign Alignment) {
519   if (!EnableMaskedLoadStores || !ST->hasMVEIntegerOps())
520     return false;
521 
522   if (auto *VecTy = dyn_cast<VectorType>(DataTy)) {
523     // Don't support v2i1 yet.
524     if (VecTy->getNumElements() == 2)
525       return false;
526 
527     // We don't support extending fp types.
528      unsigned VecWidth = DataTy->getPrimitiveSizeInBits();
529     if (VecWidth != 128 && VecTy->getElementType()->isFloatingPointTy())
530       return false;
531   }
532 
533   unsigned EltWidth = DataTy->getScalarSizeInBits();
534   return (EltWidth == 32 && (!Alignment || Alignment >= 4)) ||
535          (EltWidth == 16 && (!Alignment || Alignment >= 2)) ||
536          (EltWidth == 8);
537 }
538 
539 bool ARMTTIImpl::isLegalMaskedGather(Type *Ty, MaybeAlign Alignment) {
540   if (!EnableMaskedGatherScatters || !ST->hasMVEIntegerOps())
541     return false;
542 
543   // This method is called in 2 places:
544   //  - from the vectorizer with a scalar type, in which case we need to get
545   //  this as good as we can with the limited info we have (and rely on the cost
546   //  model for the rest).
547   //  - from the masked intrinsic lowering pass with the actual vector type.
548   // For MVE, we have a custom lowering pass that will already have custom
549   // legalised any gathers that we can to MVE intrinsics, and want to expand all
550   // the rest. The pass runs before the masked intrinsic lowering pass, so if we
551   // are here, we know we want to expand.
552   if (isa<VectorType>(Ty))
553     return false;
554 
555   unsigned EltWidth = Ty->getScalarSizeInBits();
556   return ((EltWidth == 32 && (!Alignment || Alignment >= 4)) ||
557           (EltWidth == 16 && (!Alignment || Alignment >= 2)) || EltWidth == 8);
558 }
559 
560 int ARMTTIImpl::getMemcpyCost(const Instruction *I) {
561   const MemCpyInst *MI = dyn_cast<MemCpyInst>(I);
562   assert(MI && "MemcpyInst expected");
563   ConstantInt *C = dyn_cast<ConstantInt>(MI->getLength());
564 
565   // To model the cost of a library call, we assume 1 for the call, and
566   // 3 for the argument setup.
567   const unsigned LibCallCost = 4;
568 
569   // If 'size' is not a constant, a library call will be generated.
570   if (!C)
571     return LibCallCost;
572 
573   const unsigned Size = C->getValue().getZExtValue();
574   const Align DstAlign = *MI->getDestAlign();
575   const Align SrcAlign = *MI->getSourceAlign();
576   const Function *F = I->getParent()->getParent();
577   const unsigned Limit = TLI->getMaxStoresPerMemmove(F->hasMinSize());
578   std::vector<EVT> MemOps;
579 
580   // MemOps will be poplulated with a list of data types that needs to be
581   // loaded and stored. That's why we multiply the number of elements by 2 to
582   // get the cost for this memcpy.
583   if (getTLI()->findOptimalMemOpLowering(
584           MemOps, Limit,
585           MemOp::Copy(Size, /*DstAlignCanChange*/ false, DstAlign, SrcAlign,
586                       /*IsVolatile*/ true),
587           MI->getDestAddressSpace(), MI->getSourceAddressSpace(),
588           F->getAttributes()))
589     return MemOps.size() * 2;
590 
591   // If we can't find an optimal memop lowering, return the default cost
592   return LibCallCost;
593 }
594 
595 int ARMTTIImpl::getShuffleCost(TTI::ShuffleKind Kind, VectorType *Tp,
596                                int Index, VectorType *SubTp) {
597   if (ST->hasNEON()) {
598     if (Kind == TTI::SK_Broadcast) {
599       static const CostTblEntry NEONDupTbl[] = {
600           // VDUP handles these cases.
601           {ISD::VECTOR_SHUFFLE, MVT::v2i32, 1},
602           {ISD::VECTOR_SHUFFLE, MVT::v2f32, 1},
603           {ISD::VECTOR_SHUFFLE, MVT::v2i64, 1},
604           {ISD::VECTOR_SHUFFLE, MVT::v2f64, 1},
605           {ISD::VECTOR_SHUFFLE, MVT::v4i16, 1},
606           {ISD::VECTOR_SHUFFLE, MVT::v8i8, 1},
607 
608           {ISD::VECTOR_SHUFFLE, MVT::v4i32, 1},
609           {ISD::VECTOR_SHUFFLE, MVT::v4f32, 1},
610           {ISD::VECTOR_SHUFFLE, MVT::v8i16, 1},
611           {ISD::VECTOR_SHUFFLE, MVT::v16i8, 1}};
612 
613       std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Tp);
614 
615       if (const auto *Entry =
616               CostTableLookup(NEONDupTbl, ISD::VECTOR_SHUFFLE, LT.second))
617         return LT.first * Entry->Cost;
618     }
619     if (Kind == TTI::SK_Reverse) {
620       static const CostTblEntry NEONShuffleTbl[] = {
621           // Reverse shuffle cost one instruction if we are shuffling within a
622           // double word (vrev) or two if we shuffle a quad word (vrev, vext).
623           {ISD::VECTOR_SHUFFLE, MVT::v2i32, 1},
624           {ISD::VECTOR_SHUFFLE, MVT::v2f32, 1},
625           {ISD::VECTOR_SHUFFLE, MVT::v2i64, 1},
626           {ISD::VECTOR_SHUFFLE, MVT::v2f64, 1},
627           {ISD::VECTOR_SHUFFLE, MVT::v4i16, 1},
628           {ISD::VECTOR_SHUFFLE, MVT::v8i8, 1},
629 
630           {ISD::VECTOR_SHUFFLE, MVT::v4i32, 2},
631           {ISD::VECTOR_SHUFFLE, MVT::v4f32, 2},
632           {ISD::VECTOR_SHUFFLE, MVT::v8i16, 2},
633           {ISD::VECTOR_SHUFFLE, MVT::v16i8, 2}};
634 
635       std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Tp);
636 
637       if (const auto *Entry =
638               CostTableLookup(NEONShuffleTbl, ISD::VECTOR_SHUFFLE, LT.second))
639         return LT.first * Entry->Cost;
640     }
641     if (Kind == TTI::SK_Select) {
642       static const CostTblEntry NEONSelShuffleTbl[] = {
643           // Select shuffle cost table for ARM. Cost is the number of
644           // instructions
645           // required to create the shuffled vector.
646 
647           {ISD::VECTOR_SHUFFLE, MVT::v2f32, 1},
648           {ISD::VECTOR_SHUFFLE, MVT::v2i64, 1},
649           {ISD::VECTOR_SHUFFLE, MVT::v2f64, 1},
650           {ISD::VECTOR_SHUFFLE, MVT::v2i32, 1},
651 
652           {ISD::VECTOR_SHUFFLE, MVT::v4i32, 2},
653           {ISD::VECTOR_SHUFFLE, MVT::v4f32, 2},
654           {ISD::VECTOR_SHUFFLE, MVT::v4i16, 2},
655 
656           {ISD::VECTOR_SHUFFLE, MVT::v8i16, 16},
657 
658           {ISD::VECTOR_SHUFFLE, MVT::v16i8, 32}};
659 
660       std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Tp);
661       if (const auto *Entry = CostTableLookup(NEONSelShuffleTbl,
662                                               ISD::VECTOR_SHUFFLE, LT.second))
663         return LT.first * Entry->Cost;
664     }
665   }
666   if (ST->hasMVEIntegerOps()) {
667     if (Kind == TTI::SK_Broadcast) {
668       static const CostTblEntry MVEDupTbl[] = {
669           // VDUP handles these cases.
670           {ISD::VECTOR_SHUFFLE, MVT::v4i32, 1},
671           {ISD::VECTOR_SHUFFLE, MVT::v8i16, 1},
672           {ISD::VECTOR_SHUFFLE, MVT::v16i8, 1},
673           {ISD::VECTOR_SHUFFLE, MVT::v4f32, 1},
674           {ISD::VECTOR_SHUFFLE, MVT::v8f16, 1}};
675 
676       std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Tp);
677 
678       if (const auto *Entry = CostTableLookup(MVEDupTbl, ISD::VECTOR_SHUFFLE,
679                                               LT.second))
680         return LT.first * Entry->Cost * ST->getMVEVectorCostFactor();
681     }
682   }
683   int BaseCost = ST->hasMVEIntegerOps() && Tp->isVectorTy()
684                      ? ST->getMVEVectorCostFactor()
685                      : 1;
686   return BaseCost * BaseT::getShuffleCost(Kind, Tp, Index, SubTp);
687 }
688 
689 int ARMTTIImpl::getArithmeticInstrCost(unsigned Opcode, Type *Ty,
690                                        TTI::TargetCostKind CostKind,
691                                        TTI::OperandValueKind Op1Info,
692                                        TTI::OperandValueKind Op2Info,
693                                        TTI::OperandValueProperties Opd1PropInfo,
694                                        TTI::OperandValueProperties Opd2PropInfo,
695                                        ArrayRef<const Value *> Args,
696                                        const Instruction *CxtI) {
697   int ISDOpcode = TLI->InstructionOpcodeToISD(Opcode);
698   std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Ty);
699 
700   if (ST->hasNEON()) {
701     const unsigned FunctionCallDivCost = 20;
702     const unsigned ReciprocalDivCost = 10;
703     static const CostTblEntry CostTbl[] = {
704       // Division.
705       // These costs are somewhat random. Choose a cost of 20 to indicate that
706       // vectorizing devision (added function call) is going to be very expensive.
707       // Double registers types.
708       { ISD::SDIV, MVT::v1i64, 1 * FunctionCallDivCost},
709       { ISD::UDIV, MVT::v1i64, 1 * FunctionCallDivCost},
710       { ISD::SREM, MVT::v1i64, 1 * FunctionCallDivCost},
711       { ISD::UREM, MVT::v1i64, 1 * FunctionCallDivCost},
712       { ISD::SDIV, MVT::v2i32, 2 * FunctionCallDivCost},
713       { ISD::UDIV, MVT::v2i32, 2 * FunctionCallDivCost},
714       { ISD::SREM, MVT::v2i32, 2 * FunctionCallDivCost},
715       { ISD::UREM, MVT::v2i32, 2 * FunctionCallDivCost},
716       { ISD::SDIV, MVT::v4i16,     ReciprocalDivCost},
717       { ISD::UDIV, MVT::v4i16,     ReciprocalDivCost},
718       { ISD::SREM, MVT::v4i16, 4 * FunctionCallDivCost},
719       { ISD::UREM, MVT::v4i16, 4 * FunctionCallDivCost},
720       { ISD::SDIV, MVT::v8i8,      ReciprocalDivCost},
721       { ISD::UDIV, MVT::v8i8,      ReciprocalDivCost},
722       { ISD::SREM, MVT::v8i8,  8 * FunctionCallDivCost},
723       { ISD::UREM, MVT::v8i8,  8 * FunctionCallDivCost},
724       // Quad register types.
725       { ISD::SDIV, MVT::v2i64, 2 * FunctionCallDivCost},
726       { ISD::UDIV, MVT::v2i64, 2 * FunctionCallDivCost},
727       { ISD::SREM, MVT::v2i64, 2 * FunctionCallDivCost},
728       { ISD::UREM, MVT::v2i64, 2 * FunctionCallDivCost},
729       { ISD::SDIV, MVT::v4i32, 4 * FunctionCallDivCost},
730       { ISD::UDIV, MVT::v4i32, 4 * FunctionCallDivCost},
731       { ISD::SREM, MVT::v4i32, 4 * FunctionCallDivCost},
732       { ISD::UREM, MVT::v4i32, 4 * FunctionCallDivCost},
733       { ISD::SDIV, MVT::v8i16, 8 * FunctionCallDivCost},
734       { ISD::UDIV, MVT::v8i16, 8 * FunctionCallDivCost},
735       { ISD::SREM, MVT::v8i16, 8 * FunctionCallDivCost},
736       { ISD::UREM, MVT::v8i16, 8 * FunctionCallDivCost},
737       { ISD::SDIV, MVT::v16i8, 16 * FunctionCallDivCost},
738       { ISD::UDIV, MVT::v16i8, 16 * FunctionCallDivCost},
739       { ISD::SREM, MVT::v16i8, 16 * FunctionCallDivCost},
740       { ISD::UREM, MVT::v16i8, 16 * FunctionCallDivCost},
741       // Multiplication.
742     };
743 
744     if (const auto *Entry = CostTableLookup(CostTbl, ISDOpcode, LT.second))
745       return LT.first * Entry->Cost;
746 
747     int Cost = BaseT::getArithmeticInstrCost(Opcode, Ty, CostKind, Op1Info,
748                                              Op2Info,
749                                              Opd1PropInfo, Opd2PropInfo);
750 
751     // This is somewhat of a hack. The problem that we are facing is that SROA
752     // creates a sequence of shift, and, or instructions to construct values.
753     // These sequences are recognized by the ISel and have zero-cost. Not so for
754     // the vectorized code. Because we have support for v2i64 but not i64 those
755     // sequences look particularly beneficial to vectorize.
756     // To work around this we increase the cost of v2i64 operations to make them
757     // seem less beneficial.
758     if (LT.second == MVT::v2i64 &&
759         Op2Info == TargetTransformInfo::OK_UniformConstantValue)
760       Cost += 4;
761 
762     return Cost;
763   }
764 
765   // If this operation is a shift on arm/thumb2, it might well be folded into
766   // the following instruction, hence having a cost of 0.
767   auto LooksLikeAFreeShift = [&]() {
768     if (ST->isThumb1Only() || Ty->isVectorTy())
769       return false;
770 
771     if (!CxtI || !CxtI->hasOneUse() || !CxtI->isShift())
772       return false;
773     if (Op2Info != TargetTransformInfo::OK_UniformConstantValue)
774       return false;
775 
776     // Folded into a ADC/ADD/AND/BIC/CMP/EOR/MVN/ORR/ORN/RSB/SBC/SUB
777     switch (cast<Instruction>(CxtI->user_back())->getOpcode()) {
778     case Instruction::Add:
779     case Instruction::Sub:
780     case Instruction::And:
781     case Instruction::Xor:
782     case Instruction::Or:
783     case Instruction::ICmp:
784       return true;
785     default:
786       return false;
787     }
788   };
789   if (LooksLikeAFreeShift())
790     return 0;
791 
792   int BaseCost = ST->hasMVEIntegerOps() && Ty->isVectorTy()
793                      ? ST->getMVEVectorCostFactor()
794                      : 1;
795 
796   // The rest of this mostly follows what is done in BaseT::getArithmeticInstrCost,
797   // without treating floats as more expensive that scalars or increasing the
798   // costs for custom operations. The results is also multiplied by the
799   // MVEVectorCostFactor where appropriate.
800   if (TLI->isOperationLegalOrCustomOrPromote(ISDOpcode, LT.second))
801     return LT.first * BaseCost;
802 
803   // Else this is expand, assume that we need to scalarize this op.
804   if (auto *VTy = dyn_cast<VectorType>(Ty)) {
805     unsigned Num = VTy->getNumElements();
806     unsigned Cost = getArithmeticInstrCost(Opcode, Ty->getScalarType(),
807                                            CostKind);
808     // Return the cost of multiple scalar invocation plus the cost of
809     // inserting and extracting the values.
810     return BaseT::getScalarizationOverhead(VTy, Args) + Num * Cost;
811   }
812 
813   return BaseCost;
814 }
815 
816 int ARMTTIImpl::getMemoryOpCost(unsigned Opcode, Type *Src,
817                                 MaybeAlign Alignment, unsigned AddressSpace,
818                                 TTI::TargetCostKind CostKind,
819                                 const Instruction *I) {
820   std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Src);
821 
822   if (ST->hasNEON() && Src->isVectorTy() &&
823       (Alignment && *Alignment != Align(16)) &&
824       cast<VectorType>(Src)->getElementType()->isDoubleTy()) {
825     // Unaligned loads/stores are extremely inefficient.
826     // We need 4 uops for vst.1/vld.1 vs 1uop for vldr/vstr.
827     return LT.first * 4;
828   }
829   int BaseCost = ST->hasMVEIntegerOps() && Src->isVectorTy()
830                      ? ST->getMVEVectorCostFactor()
831                      : 1;
832   return BaseCost * LT.first;
833 }
834 
835 int ARMTTIImpl::getInterleavedMemoryOpCost(
836     unsigned Opcode, Type *VecTy, unsigned Factor, ArrayRef<unsigned> Indices,
837     unsigned Alignment, unsigned AddressSpace,
838     TTI::TargetCostKind CostKind,
839     bool UseMaskForCond, bool UseMaskForGaps) {
840   assert(Factor >= 2 && "Invalid interleave factor");
841   assert(isa<VectorType>(VecTy) && "Expect a vector type");
842 
843   // vldN/vstN doesn't support vector types of i64/f64 element.
844   bool EltIs64Bits = DL.getTypeSizeInBits(VecTy->getScalarType()) == 64;
845 
846   if (Factor <= TLI->getMaxSupportedInterleaveFactor() && !EltIs64Bits &&
847       !UseMaskForCond && !UseMaskForGaps) {
848     unsigned NumElts = cast<VectorType>(VecTy)->getNumElements();
849     auto *SubVecTy = VectorType::get(VecTy->getScalarType(), NumElts / Factor);
850 
851     // vldN/vstN only support legal vector types of size 64 or 128 in bits.
852     // Accesses having vector types that are a multiple of 128 bits can be
853     // matched to more than one vldN/vstN instruction.
854     int BaseCost = ST->hasMVEIntegerOps() ? ST->getMVEVectorCostFactor() : 1;
855     if (NumElts % Factor == 0 &&
856         TLI->isLegalInterleavedAccessType(Factor, SubVecTy, DL))
857       return Factor * BaseCost * TLI->getNumInterleavedAccesses(SubVecTy, DL);
858 
859     // Some smaller than legal interleaved patterns are cheap as we can make
860     // use of the vmovn or vrev patterns to interleave a standard load. This is
861     // true for v4i8, v8i8 and v4i16 at least (but not for v4f16 as it is
862     // promoted differently). The cost of 2 here is then a load and vrev or
863     // vmovn.
864     if (ST->hasMVEIntegerOps() && Factor == 2 && NumElts / Factor > 2 &&
865         VecTy->isIntOrIntVectorTy() && DL.getTypeSizeInBits(SubVecTy) <= 64)
866       return 2 * BaseCost;
867   }
868 
869   return BaseT::getInterleavedMemoryOpCost(Opcode, VecTy, Factor, Indices,
870                                            Alignment, AddressSpace, CostKind,
871                                            UseMaskForCond, UseMaskForGaps);
872 }
873 
874 unsigned ARMTTIImpl::getGatherScatterOpCost(unsigned Opcode, Type *DataTy,
875                                             Value *Ptr, bool VariableMask,
876                                             unsigned Alignment,
877                                             TTI::TargetCostKind CostKind,
878                                             const Instruction *I) {
879   using namespace PatternMatch;
880   if (!ST->hasMVEIntegerOps() || !EnableMaskedGatherScatters)
881     return BaseT::getGatherScatterOpCost(Opcode, DataTy, Ptr, VariableMask,
882                                          Alignment, CostKind, I);
883 
884   assert(DataTy->isVectorTy() && "Can't do gather/scatters on scalar!");
885   VectorType *VTy = cast<VectorType>(DataTy);
886 
887   // TODO: Splitting, once we do that.
888 
889   unsigned NumElems = VTy->getNumElements();
890   unsigned EltSize = VTy->getScalarSizeInBits();
891   std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, DataTy);
892 
893   // For now, it is assumed that for the MVE gather instructions the loads are
894   // all effectively serialised. This means the cost is the scalar cost
895   // multiplied by the number of elements being loaded. This is possibly very
896   // conservative, but even so we still end up vectorising loops because the
897   // cost per iteration for many loops is lower than for scalar loops.
898   unsigned VectorCost = NumElems * LT.first;
899   // The scalarization cost should be a lot higher. We use the number of vector
900   // elements plus the scalarization overhead.
901   unsigned ScalarCost =
902       NumElems * LT.first + BaseT::getScalarizationOverhead(VTy, {});
903 
904   if (Alignment < EltSize / 8)
905     return ScalarCost;
906 
907   unsigned ExtSize = EltSize;
908   // Check whether there's a single user that asks for an extended type
909   if (I != nullptr) {
910     // Dependent of the caller of this function, a gather instruction will
911     // either have opcode Instruction::Load or be a call to the masked_gather
912     // intrinsic
913     if ((I->getOpcode() == Instruction::Load ||
914          match(I, m_Intrinsic<Intrinsic::masked_gather>())) &&
915         I->hasOneUse()) {
916       const User *Us = *I->users().begin();
917       if (isa<ZExtInst>(Us) || isa<SExtInst>(Us)) {
918         // only allow valid type combinations
919         unsigned TypeSize =
920             cast<Instruction>(Us)->getType()->getScalarSizeInBits();
921         if (((TypeSize == 32 && (EltSize == 8 || EltSize == 16)) ||
922              (TypeSize == 16 && EltSize == 8)) &&
923             TypeSize * NumElems == 128) {
924           ExtSize = TypeSize;
925         }
926       }
927     }
928     // Check whether the input data needs to be truncated
929     TruncInst *T;
930     if ((I->getOpcode() == Instruction::Store ||
931          match(I, m_Intrinsic<Intrinsic::masked_scatter>())) &&
932         (T = dyn_cast<TruncInst>(I->getOperand(0)))) {
933       // Only allow valid type combinations
934       unsigned TypeSize = T->getOperand(0)->getType()->getScalarSizeInBits();
935       if (((EltSize == 16 && TypeSize == 32) ||
936            (EltSize == 8 && (TypeSize == 32 || TypeSize == 16))) &&
937           TypeSize * NumElems == 128)
938         ExtSize = TypeSize;
939     }
940   }
941 
942   if (ExtSize * NumElems != 128 || NumElems < 4)
943     return ScalarCost;
944 
945   // Any (aligned) i32 gather will not need to be scalarised.
946   if (ExtSize == 32)
947     return VectorCost;
948   // For smaller types, we need to ensure that the gep's inputs are correctly
949   // extended from a small enough value. Other sizes (including i64) are
950   // scalarized for now.
951   if (ExtSize != 8 && ExtSize != 16)
952     return ScalarCost;
953 
954   if (auto BC = dyn_cast<BitCastInst>(Ptr))
955     Ptr = BC->getOperand(0);
956   if (auto *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
957     if (GEP->getNumOperands() != 2)
958       return ScalarCost;
959     unsigned Scale = DL.getTypeAllocSize(GEP->getResultElementType());
960     // Scale needs to be correct (which is only relevant for i16s).
961     if (Scale != 1 && Scale * 8 != ExtSize)
962       return ScalarCost;
963     // And we need to zext (not sext) the indexes from a small enough type.
964     if (auto ZExt = dyn_cast<ZExtInst>(GEP->getOperand(1))) {
965       if (ZExt->getOperand(0)->getType()->getScalarSizeInBits() <= ExtSize)
966         return VectorCost;
967     }
968     return ScalarCost;
969   }
970   return ScalarCost;
971 }
972 
973 bool ARMTTIImpl::isLoweredToCall(const Function *F) {
974   if (!F->isIntrinsic())
975     BaseT::isLoweredToCall(F);
976 
977   // Assume all Arm-specific intrinsics map to an instruction.
978   if (F->getName().startswith("llvm.arm"))
979     return false;
980 
981   switch (F->getIntrinsicID()) {
982   default: break;
983   case Intrinsic::powi:
984   case Intrinsic::sin:
985   case Intrinsic::cos:
986   case Intrinsic::pow:
987   case Intrinsic::log:
988   case Intrinsic::log10:
989   case Intrinsic::log2:
990   case Intrinsic::exp:
991   case Intrinsic::exp2:
992     return true;
993   case Intrinsic::sqrt:
994   case Intrinsic::fabs:
995   case Intrinsic::copysign:
996   case Intrinsic::floor:
997   case Intrinsic::ceil:
998   case Intrinsic::trunc:
999   case Intrinsic::rint:
1000   case Intrinsic::nearbyint:
1001   case Intrinsic::round:
1002   case Intrinsic::canonicalize:
1003   case Intrinsic::lround:
1004   case Intrinsic::llround:
1005   case Intrinsic::lrint:
1006   case Intrinsic::llrint:
1007     if (F->getReturnType()->isDoubleTy() && !ST->hasFP64())
1008       return true;
1009     if (F->getReturnType()->isHalfTy() && !ST->hasFullFP16())
1010       return true;
1011     // Some operations can be handled by vector instructions and assume
1012     // unsupported vectors will be expanded into supported scalar ones.
1013     // TODO Handle scalar operations properly.
1014     return !ST->hasFPARMv8Base() && !ST->hasVFP2Base();
1015   case Intrinsic::masked_store:
1016   case Intrinsic::masked_load:
1017   case Intrinsic::masked_gather:
1018   case Intrinsic::masked_scatter:
1019     return !ST->hasMVEIntegerOps();
1020   case Intrinsic::sadd_with_overflow:
1021   case Intrinsic::uadd_with_overflow:
1022   case Intrinsic::ssub_with_overflow:
1023   case Intrinsic::usub_with_overflow:
1024   case Intrinsic::sadd_sat:
1025   case Intrinsic::uadd_sat:
1026   case Intrinsic::ssub_sat:
1027   case Intrinsic::usub_sat:
1028     return false;
1029   }
1030 
1031   return BaseT::isLoweredToCall(F);
1032 }
1033 
1034 bool ARMTTIImpl::isHardwareLoopProfitable(Loop *L, ScalarEvolution &SE,
1035                                           AssumptionCache &AC,
1036                                           TargetLibraryInfo *LibInfo,
1037                                           HardwareLoopInfo &HWLoopInfo) {
1038   // Low-overhead branches are only supported in the 'low-overhead branch'
1039   // extension of v8.1-m.
1040   if (!ST->hasLOB() || DisableLowOverheadLoops) {
1041     LLVM_DEBUG(dbgs() << "ARMHWLoops: Disabled\n");
1042     return false;
1043   }
1044 
1045   if (!SE.hasLoopInvariantBackedgeTakenCount(L)) {
1046     LLVM_DEBUG(dbgs() << "ARMHWLoops: No BETC\n");
1047     return false;
1048   }
1049 
1050   const SCEV *BackedgeTakenCount = SE.getBackedgeTakenCount(L);
1051   if (isa<SCEVCouldNotCompute>(BackedgeTakenCount)) {
1052     LLVM_DEBUG(dbgs() << "ARMHWLoops: Uncomputable BETC\n");
1053     return false;
1054   }
1055 
1056   const SCEV *TripCountSCEV =
1057     SE.getAddExpr(BackedgeTakenCount,
1058                   SE.getOne(BackedgeTakenCount->getType()));
1059 
1060   // We need to store the trip count in LR, a 32-bit register.
1061   if (SE.getUnsignedRangeMax(TripCountSCEV).getBitWidth() > 32) {
1062     LLVM_DEBUG(dbgs() << "ARMHWLoops: Trip count does not fit into 32bits\n");
1063     return false;
1064   }
1065 
1066   // Making a call will trash LR and clear LO_BRANCH_INFO, so there's little
1067   // point in generating a hardware loop if that's going to happen.
1068   auto MaybeCall = [this](Instruction &I) {
1069     const ARMTargetLowering *TLI = getTLI();
1070     unsigned ISD = TLI->InstructionOpcodeToISD(I.getOpcode());
1071     EVT VT = TLI->getValueType(DL, I.getType(), true);
1072     if (TLI->getOperationAction(ISD, VT) == TargetLowering::LibCall)
1073       return true;
1074 
1075     // Check if an intrinsic will be lowered to a call and assume that any
1076     // other CallInst will generate a bl.
1077     if (auto *Call = dyn_cast<CallInst>(&I)) {
1078       if (isa<IntrinsicInst>(Call)) {
1079         if (const Function *F = Call->getCalledFunction())
1080           return isLoweredToCall(F);
1081       }
1082       return true;
1083     }
1084 
1085     // FPv5 provides conversions between integer, double-precision,
1086     // single-precision, and half-precision formats.
1087     switch (I.getOpcode()) {
1088     default:
1089       break;
1090     case Instruction::FPToSI:
1091     case Instruction::FPToUI:
1092     case Instruction::SIToFP:
1093     case Instruction::UIToFP:
1094     case Instruction::FPTrunc:
1095     case Instruction::FPExt:
1096       return !ST->hasFPARMv8Base();
1097     }
1098 
1099     // FIXME: Unfortunately the approach of checking the Operation Action does
1100     // not catch all cases of Legalization that use library calls. Our
1101     // Legalization step categorizes some transformations into library calls as
1102     // Custom, Expand or even Legal when doing type legalization. So for now
1103     // we have to special case for instance the SDIV of 64bit integers and the
1104     // use of floating point emulation.
1105     if (VT.isInteger() && VT.getSizeInBits() >= 64) {
1106       switch (ISD) {
1107       default:
1108         break;
1109       case ISD::SDIV:
1110       case ISD::UDIV:
1111       case ISD::SREM:
1112       case ISD::UREM:
1113       case ISD::SDIVREM:
1114       case ISD::UDIVREM:
1115         return true;
1116       }
1117     }
1118 
1119     // Assume all other non-float operations are supported.
1120     if (!VT.isFloatingPoint())
1121       return false;
1122 
1123     // We'll need a library call to handle most floats when using soft.
1124     if (TLI->useSoftFloat()) {
1125       switch (I.getOpcode()) {
1126       default:
1127         return true;
1128       case Instruction::Alloca:
1129       case Instruction::Load:
1130       case Instruction::Store:
1131       case Instruction::Select:
1132       case Instruction::PHI:
1133         return false;
1134       }
1135     }
1136 
1137     // We'll need a libcall to perform double precision operations on a single
1138     // precision only FPU.
1139     if (I.getType()->isDoubleTy() && !ST->hasFP64())
1140       return true;
1141 
1142     // Likewise for half precision arithmetic.
1143     if (I.getType()->isHalfTy() && !ST->hasFullFP16())
1144       return true;
1145 
1146     return false;
1147   };
1148 
1149   auto IsHardwareLoopIntrinsic = [](Instruction &I) {
1150     if (auto *Call = dyn_cast<IntrinsicInst>(&I)) {
1151       switch (Call->getIntrinsicID()) {
1152       default:
1153         break;
1154       case Intrinsic::set_loop_iterations:
1155       case Intrinsic::test_set_loop_iterations:
1156       case Intrinsic::loop_decrement:
1157       case Intrinsic::loop_decrement_reg:
1158         return true;
1159       }
1160     }
1161     return false;
1162   };
1163 
1164   // Scan the instructions to see if there's any that we know will turn into a
1165   // call or if this loop is already a low-overhead loop.
1166   auto ScanLoop = [&](Loop *L) {
1167     for (auto *BB : L->getBlocks()) {
1168       for (auto &I : *BB) {
1169         if (MaybeCall(I) || IsHardwareLoopIntrinsic(I)) {
1170           LLVM_DEBUG(dbgs() << "ARMHWLoops: Bad instruction: " << I << "\n");
1171           return false;
1172         }
1173       }
1174     }
1175     return true;
1176   };
1177 
1178   // Visit inner loops.
1179   for (auto Inner : *L)
1180     if (!ScanLoop(Inner))
1181       return false;
1182 
1183   if (!ScanLoop(L))
1184     return false;
1185 
1186   // TODO: Check whether the trip count calculation is expensive. If L is the
1187   // inner loop but we know it has a low trip count, calculating that trip
1188   // count (in the parent loop) may be detrimental.
1189 
1190   LLVMContext &C = L->getHeader()->getContext();
1191   HWLoopInfo.CounterInReg = true;
1192   HWLoopInfo.IsNestingLegal = false;
1193   HWLoopInfo.PerformEntryTest = true;
1194   HWLoopInfo.CountType = Type::getInt32Ty(C);
1195   HWLoopInfo.LoopDecrement = ConstantInt::get(HWLoopInfo.CountType, 1);
1196   return true;
1197 }
1198 
1199 static bool canTailPredicateInstruction(Instruction &I, int &ICmpCount) {
1200   // We don't allow icmp's, and because we only look at single block loops,
1201   // we simply count the icmps, i.e. there should only be 1 for the backedge.
1202   if (isa<ICmpInst>(&I) && ++ICmpCount > 1)
1203     return false;
1204 
1205   if (isa<FCmpInst>(&I))
1206     return false;
1207 
1208   // We could allow extending/narrowing FP loads/stores, but codegen is
1209   // too inefficient so reject this for now.
1210   if (isa<FPExtInst>(&I) || isa<FPTruncInst>(&I))
1211     return false;
1212 
1213   // Extends have to be extending-loads
1214   if (isa<SExtInst>(&I) || isa<ZExtInst>(&I) )
1215     if (!I.getOperand(0)->hasOneUse() || !isa<LoadInst>(I.getOperand(0)))
1216       return false;
1217 
1218   // Truncs have to be narrowing-stores
1219   if (isa<TruncInst>(&I) )
1220     if (!I.hasOneUse() || !isa<StoreInst>(*I.user_begin()))
1221       return false;
1222 
1223   return true;
1224 }
1225 
1226 // To set up a tail-predicated loop, we need to know the total number of
1227 // elements processed by that loop. Thus, we need to determine the element
1228 // size and:
1229 // 1) it should be uniform for all operations in the vector loop, so we
1230 //    e.g. don't want any widening/narrowing operations.
1231 // 2) it should be smaller than i64s because we don't have vector operations
1232 //    that work on i64s.
1233 // 3) we don't want elements to be reversed or shuffled, to make sure the
1234 //    tail-predication masks/predicates the right lanes.
1235 //
1236 static bool canTailPredicateLoop(Loop *L, LoopInfo *LI, ScalarEvolution &SE,
1237                                  const DataLayout &DL,
1238                                  const LoopAccessInfo *LAI) {
1239   PredicatedScalarEvolution PSE = LAI->getPSE();
1240   int ICmpCount = 0;
1241   int Stride = 0;
1242 
1243   LLVM_DEBUG(dbgs() << "tail-predication: checking allowed instructions\n");
1244   SmallVector<Instruction *, 16> LoadStores;
1245   for (BasicBlock *BB : L->blocks()) {
1246     for (Instruction &I : BB->instructionsWithoutDebug()) {
1247       if (isa<PHINode>(&I))
1248         continue;
1249       if (!canTailPredicateInstruction(I, ICmpCount)) {
1250         LLVM_DEBUG(dbgs() << "Instruction not allowed: "; I.dump());
1251         return false;
1252       }
1253 
1254       Type *T  = I.getType();
1255       if (T->isPointerTy())
1256         T = T->getPointerElementType();
1257 
1258       if (T->getScalarSizeInBits() > 32) {
1259         LLVM_DEBUG(dbgs() << "Unsupported Type: "; T->dump());
1260         return false;
1261       }
1262 
1263       if (isa<StoreInst>(I) || isa<LoadInst>(I)) {
1264         Value *Ptr = isa<LoadInst>(I) ? I.getOperand(0) : I.getOperand(1);
1265         int64_t NextStride = getPtrStride(PSE, Ptr, L);
1266         // TODO: for now only allow consecutive strides of 1. We could support
1267         // other strides as long as it is uniform, but let's keep it simple for
1268         // now.
1269         if (Stride == 0 && NextStride == 1) {
1270           Stride = NextStride;
1271           continue;
1272         }
1273         if (Stride != NextStride) {
1274           LLVM_DEBUG(dbgs() << "Different strides found, can't "
1275                                "tail-predicate\n.");
1276           return false;
1277         }
1278       }
1279     }
1280   }
1281 
1282   LLVM_DEBUG(dbgs() << "tail-predication: all instructions allowed!\n");
1283   return true;
1284 }
1285 
1286 bool ARMTTIImpl::preferPredicateOverEpilogue(Loop *L, LoopInfo *LI,
1287                                              ScalarEvolution &SE,
1288                                              AssumptionCache &AC,
1289                                              TargetLibraryInfo *TLI,
1290                                              DominatorTree *DT,
1291                                              const LoopAccessInfo *LAI) {
1292   if (DisableTailPredication)
1293     return false;
1294 
1295   // Creating a predicated vector loop is the first step for generating a
1296   // tail-predicated hardware loop, for which we need the MVE masked
1297   // load/stores instructions:
1298   if (!ST->hasMVEIntegerOps())
1299     return false;
1300 
1301   // For now, restrict this to single block loops.
1302   if (L->getNumBlocks() > 1) {
1303     LLVM_DEBUG(dbgs() << "preferPredicateOverEpilogue: not a single block "
1304                          "loop.\n");
1305     return false;
1306   }
1307 
1308   assert(L->empty() && "preferPredicateOverEpilogue: inner-loop expected");
1309 
1310   HardwareLoopInfo HWLoopInfo(L);
1311   if (!HWLoopInfo.canAnalyze(*LI)) {
1312     LLVM_DEBUG(dbgs() << "preferPredicateOverEpilogue: hardware-loop is not "
1313                          "analyzable.\n");
1314     return false;
1315   }
1316 
1317   // This checks if we have the low-overhead branch architecture
1318   // extension, and if we will create a hardware-loop:
1319   if (!isHardwareLoopProfitable(L, SE, AC, TLI, HWLoopInfo)) {
1320     LLVM_DEBUG(dbgs() << "preferPredicateOverEpilogue: hardware-loop is not "
1321                          "profitable.\n");
1322     return false;
1323   }
1324 
1325   if (!HWLoopInfo.isHardwareLoopCandidate(SE, *LI, *DT)) {
1326     LLVM_DEBUG(dbgs() << "preferPredicateOverEpilogue: hardware-loop is not "
1327                          "a candidate.\n");
1328     return false;
1329   }
1330 
1331   return canTailPredicateLoop(L, LI, SE, DL, LAI);
1332 }
1333 
1334 
1335 void ARMTTIImpl::getUnrollingPreferences(Loop *L, ScalarEvolution &SE,
1336                                          TTI::UnrollingPreferences &UP) {
1337   // Only currently enable these preferences for M-Class cores.
1338   if (!ST->isMClass())
1339     return BasicTTIImplBase::getUnrollingPreferences(L, SE, UP);
1340 
1341   // Disable loop unrolling for Oz and Os.
1342   UP.OptSizeThreshold = 0;
1343   UP.PartialOptSizeThreshold = 0;
1344   if (L->getHeader()->getParent()->hasOptSize())
1345     return;
1346 
1347   // Only enable on Thumb-2 targets.
1348   if (!ST->isThumb2())
1349     return;
1350 
1351   SmallVector<BasicBlock*, 4> ExitingBlocks;
1352   L->getExitingBlocks(ExitingBlocks);
1353   LLVM_DEBUG(dbgs() << "Loop has:\n"
1354                     << "Blocks: " << L->getNumBlocks() << "\n"
1355                     << "Exit blocks: " << ExitingBlocks.size() << "\n");
1356 
1357   // Only allow another exit other than the latch. This acts as an early exit
1358   // as it mirrors the profitability calculation of the runtime unroller.
1359   if (ExitingBlocks.size() > 2)
1360     return;
1361 
1362   // Limit the CFG of the loop body for targets with a branch predictor.
1363   // Allowing 4 blocks permits if-then-else diamonds in the body.
1364   if (ST->hasBranchPredictor() && L->getNumBlocks() > 4)
1365     return;
1366 
1367   // Scan the loop: don't unroll loops with calls as this could prevent
1368   // inlining.
1369   unsigned Cost = 0;
1370   for (auto *BB : L->getBlocks()) {
1371     for (auto &I : *BB) {
1372       // Don't unroll vectorised loop. MVE does not benefit from it as much as
1373       // scalar code.
1374       if (I.getType()->isVectorTy())
1375         return;
1376 
1377       if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
1378         if (const Function *F = cast<CallBase>(I).getCalledFunction()) {
1379           if (!isLoweredToCall(F))
1380             continue;
1381         }
1382         return;
1383       }
1384 
1385       SmallVector<const Value*, 4> Operands(I.value_op_begin(),
1386                                             I.value_op_end());
1387       Cost += getUserCost(&I, Operands, TargetTransformInfo::TCK_CodeSize);
1388     }
1389   }
1390 
1391   LLVM_DEBUG(dbgs() << "Cost of loop: " << Cost << "\n");
1392 
1393   UP.Partial = true;
1394   UP.Runtime = true;
1395   UP.UpperBound = true;
1396   UP.UnrollRemainder = true;
1397   UP.DefaultUnrollRuntimeCount = 4;
1398   UP.UnrollAndJam = true;
1399   UP.UnrollAndJamInnerLoopThreshold = 60;
1400 
1401   // Force unrolling small loops can be very useful because of the branch
1402   // taken cost of the backedge.
1403   if (Cost < 12)
1404     UP.Force = true;
1405 }
1406 
1407 bool ARMTTIImpl::useReductionIntrinsic(unsigned Opcode, Type *Ty,
1408                                        TTI::ReductionFlags Flags) const {
1409   assert(isa<VectorType>(Ty) && "Expected Ty to be a vector type");
1410   unsigned ScalarBits = Ty->getScalarSizeInBits();
1411   if (!ST->hasMVEIntegerOps())
1412     return false;
1413 
1414   switch (Opcode) {
1415   case Instruction::FAdd:
1416   case Instruction::FMul:
1417   case Instruction::And:
1418   case Instruction::Or:
1419   case Instruction::Xor:
1420   case Instruction::Mul:
1421   case Instruction::FCmp:
1422     return false;
1423   case Instruction::ICmp:
1424   case Instruction::Add:
1425     return ScalarBits < 64 &&
1426            (ScalarBits * cast<VectorType>(Ty)->getNumElements()) % 128 == 0;
1427   default:
1428     llvm_unreachable("Unhandled reduction opcode");
1429   }
1430   return false;
1431 }
1432