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