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