1//===- TargetTransformInfo.h ------------------------------------*- C++ -*-===//
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/// \file
9/// This pass exposes codegen information to IR-level passes. Every
10/// transformation that uses codegen information is broken into three parts:
11/// 1. The IR-level analysis pass.
12/// 2. The IR-level transformation interface which provides the needed
13/// information.
14/// 3. Codegen-level implementation which uses target-specific hooks.
15///
16/// This file defines #2, which is the interface that IR-level transformations
17/// use for querying the codegen.
18///
19//===----------------------------------------------------------------------===//
20
21#ifndef LLVM_ANALYSIS_TARGETTRANSFORMINFO_H
22#define LLVM_ANALYSIS_TARGETTRANSFORMINFO_H
23
24#include "llvm/ADT/SmallBitVector.h"
25#include "llvm/IR/FMF.h"
26#include "llvm/IR/InstrTypes.h"
27#include "llvm/IR/PassManager.h"
28#include "llvm/Pass.h"
29#include "llvm/Support/AtomicOrdering.h"
30#include "llvm/Support/BranchProbability.h"
31#include "llvm/Support/InstructionCost.h"
32#include <functional>
33#include <utility>
34
35namespace llvm {
36
37namespace Intrinsic {
38typedef unsigned ID;
39}
40
41class AssumptionCache;
42class BlockFrequencyInfo;
43class DominatorTree;
44class BranchInst;
45class CallBase;
46class Function;
47class GlobalValue;
48class InstCombiner;
49class OptimizationRemarkEmitter;
50class InterleavedAccessInfo;
51class IntrinsicInst;
52class LoadInst;
53class Loop;
54class LoopInfo;
55class LoopVectorizationLegality;
56class ProfileSummaryInfo;
57class RecurrenceDescriptor;
58class SCEV;
59class ScalarEvolution;
60class StoreInst;
61class SwitchInst;
62class TargetLibraryInfo;
63class Type;
64class User;
65class Value;
66class VPIntrinsic;
67struct KnownBits;
68template <typename T> class Optional;
69
70/// Information about a load/store intrinsic defined by the target.
71struct MemIntrinsicInfo {
72 /// This is the pointer that the intrinsic is loading from or storing to.
73 /// If this is non-null, then analysis/optimization passes can assume that
74 /// this intrinsic is functionally equivalent to a load/store from this
75 /// pointer.
76 Value *PtrVal = nullptr;
77
78 // Ordering for atomic operations.
79 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
80
81 // Same Id is set by the target for corresponding load/store intrinsics.
82 unsigned short MatchingId = 0;
83
84 bool ReadMem = false;
85 bool WriteMem = false;
86 bool IsVolatile = false;
87
88 bool isUnordered() const {
89 return (Ordering == AtomicOrdering::NotAtomic ||
90 Ordering == AtomicOrdering::Unordered) &&
91 !IsVolatile;
92 }
93};
94
95/// Attributes of a target dependent hardware loop.
96struct HardwareLoopInfo {
97 HardwareLoopInfo() = delete;
98 HardwareLoopInfo(Loop *L) : L(L) {}
99 Loop *L = nullptr;
100 BasicBlock *ExitBlock = nullptr;
101 BranchInst *ExitBranch = nullptr;
102 const SCEV *ExitCount = nullptr;
103 IntegerType *CountType = nullptr;
104 Value *LoopDecrement = nullptr; // Decrement the loop counter by this
105 // value in every iteration.
106 bool IsNestingLegal = false; // Can a hardware loop be a parent to
107 // another hardware loop?
108 bool CounterInReg = false; // Should loop counter be updated in
109 // the loop via a phi?
110 bool PerformEntryTest = false; // Generate the intrinsic which also performs
111 // icmp ne zero on the loop counter value and
112 // produces an i1 to guard the loop entry.
113 bool isHardwareLoopCandidate(ScalarEvolution &SE, LoopInfo &LI,
114 DominatorTree &DT, bool ForceNestedLoop = false,
115 bool ForceHardwareLoopPHI = false);
116 bool canAnalyze(LoopInfo &LI);
117};
118
119class IntrinsicCostAttributes {
120 const IntrinsicInst *II = nullptr;
121 Type *RetTy = nullptr;
122 Intrinsic::ID IID;
123 SmallVector<Type *, 4> ParamTys;
124 SmallVector<const Value *, 4> Arguments;
125 FastMathFlags FMF;
126 // If ScalarizationCost is UINT_MAX, the cost of scalarizing the
127 // arguments and the return value will be computed based on types.
128 InstructionCost ScalarizationCost = InstructionCost::getInvalid();
129
130public:
131 IntrinsicCostAttributes(
132 Intrinsic::ID Id, const CallBase &CI,
133 InstructionCost ScalarCost = InstructionCost::getInvalid(),
134 bool TypeBasedOnly = false);
135
136 IntrinsicCostAttributes(
137 Intrinsic::ID Id, Type *RTy, ArrayRef<Type *> Tys,
138 FastMathFlags Flags = FastMathFlags(), const IntrinsicInst *I = nullptr,
139 InstructionCost ScalarCost = InstructionCost::getInvalid());
140
141 IntrinsicCostAttributes(Intrinsic::ID Id, Type *RTy,
142 ArrayRef<const Value *> Args);
143
144 IntrinsicCostAttributes(
145 Intrinsic::ID Id, Type *RTy, ArrayRef<const Value *> Args,
146 ArrayRef<Type *> Tys, FastMathFlags Flags = FastMathFlags(),
147 const IntrinsicInst *I = nullptr,
148 InstructionCost ScalarCost = InstructionCost::getInvalid());
149
150 Intrinsic::ID getID() const { return IID; }
151 const IntrinsicInst *getInst() const { return II; }
152 Type *getReturnType() const { return RetTy; }
153 FastMathFlags getFlags() const { return FMF; }
154 InstructionCost getScalarizationCost() const { return ScalarizationCost; }
155 const SmallVectorImpl<const Value *> &getArgs() const { return Arguments; }
156 const SmallVectorImpl<Type *> &getArgTypes() const { return ParamTys; }
157
158 bool isTypeBasedOnly() const {
159 return Arguments.empty();
160 }
161
162 bool skipScalarizationCost() const { return ScalarizationCost.isValid(); }
163};
164
165enum class PredicationStyle { None, Data, DataAndControlFlow };
166
167class TargetTransformInfo;
168typedef TargetTransformInfo TTI;
169
170/// This pass provides access to the codegen interfaces that are needed
171/// for IR-level transformations.
172class TargetTransformInfo {
173public:
174 /// Construct a TTI object using a type implementing the \c Concept
175 /// API below.
176 ///
177 /// This is used by targets to construct a TTI wrapping their target-specific
178 /// implementation that encodes appropriate costs for their target.
179 template <typename T> TargetTransformInfo(T Impl);
180
181 /// Construct a baseline TTI object using a minimal implementation of
182 /// the \c Concept API below.
183 ///
184 /// The TTI implementation will reflect the information in the DataLayout
185 /// provided if non-null.
186 explicit TargetTransformInfo(const DataLayout &DL);
187
188 // Provide move semantics.
189 TargetTransformInfo(TargetTransformInfo &&Arg);
190 TargetTransformInfo &operator=(TargetTransformInfo &&RHS);
191
192 // We need to define the destructor out-of-line to define our sub-classes
193 // out-of-line.
194 ~TargetTransformInfo();
195
196 /// Handle the invalidation of this information.
197 ///
198 /// When used as a result of \c TargetIRAnalysis this method will be called
199 /// when the function this was computed for changes. When it returns false,
200 /// the information is preserved across those changes.
201 bool invalidate(Function &, const PreservedAnalyses &,
202 FunctionAnalysisManager::Invalidator &) {
203 // FIXME: We should probably in some way ensure that the subtarget
204 // information for a function hasn't changed.
205 return false;
206 }
207
208 /// \name Generic Target Information
209 /// @{
210
211 /// The kind of cost model.
212 ///
213 /// There are several different cost models that can be customized by the
214 /// target. The normalization of each cost model may be target specific.
215 enum TargetCostKind {
216 TCK_RecipThroughput, ///< Reciprocal throughput.
217 TCK_Latency, ///< The latency of instruction.
218 TCK_CodeSize, ///< Instruction code size.
219 TCK_SizeAndLatency ///< The weighted sum of size and latency.
220 };
221
222 /// Query the cost of a specified instruction.
223 ///
224 /// Clients should use this interface to query the cost of an existing
225 /// instruction. The instruction must have a valid parent (basic block).
226 ///
227 /// Note, this method does not cache the cost calculation and it
228 /// can be expensive in some cases.
229 InstructionCost getInstructionCost(const Instruction *I,
230 enum TargetCostKind kind) const {
231 InstructionCost Cost;
232 switch (kind) {
233 case TCK_RecipThroughput:
234 Cost = getInstructionThroughput(I);
235 break;
236 case TCK_Latency:
237 Cost = getInstructionLatency(I);
238 break;
239 case TCK_CodeSize:
240 case TCK_SizeAndLatency:
241 Cost = getUserCost(I, kind);
242 break;
243 }
244 return Cost;
245 }
246
247 /// Underlying constants for 'cost' values in this interface.
248 ///
249 /// Many APIs in this interface return a cost. This enum defines the
250 /// fundamental values that should be used to interpret (and produce) those
251 /// costs. The costs are returned as an int rather than a member of this
252 /// enumeration because it is expected that the cost of one IR instruction
253 /// may have a multiplicative factor to it or otherwise won't fit directly
254 /// into the enum. Moreover, it is common to sum or average costs which works
255 /// better as simple integral values. Thus this enum only provides constants.
256 /// Also note that the returned costs are signed integers to make it natural
257 /// to add, subtract, and test with zero (a common boundary condition). It is
258 /// not expected that 2^32 is a realistic cost to be modeling at any point.
259 ///
260 /// Note that these costs should usually reflect the intersection of code-size
261 /// cost and execution cost. A free instruction is typically one that folds
262 /// into another instruction. For example, reg-to-reg moves can often be
263 /// skipped by renaming the registers in the CPU, but they still are encoded
264 /// and thus wouldn't be considered 'free' here.
265 enum TargetCostConstants {
266 TCC_Free = 0, ///< Expected to fold away in lowering.
267 TCC_Basic = 1, ///< The cost of a typical 'add' instruction.
268 TCC_Expensive = 4 ///< The cost of a 'div' instruction on x86.
269 };
270
271 /// Estimate the cost of a GEP operation when lowered.
272 InstructionCost
273 getGEPCost(Type *PointeeType, const Value *Ptr,
274 ArrayRef<const Value *> Operands,
275 TargetCostKind CostKind = TCK_SizeAndLatency) const;
276
277 /// \returns A value by which our inlining threshold should be multiplied.
278 /// This is primarily used to bump up the inlining threshold wholesale on
279 /// targets where calls are unusually expensive.
280 ///
281 /// TODO: This is a rather blunt instrument. Perhaps altering the costs of
282 /// individual classes of instructions would be better.
283 unsigned getInliningThresholdMultiplier() const;
284
285 /// \returns A value to be added to the inlining threshold.
286 unsigned adjustInliningThreshold(const CallBase *CB) const;
287
288 /// \returns Vector bonus in percent.
289 ///
290 /// Vector bonuses: We want to more aggressively inline vector-dense kernels
291 /// and apply this bonus based on the percentage of vector instructions. A
292 /// bonus is applied if the vector instructions exceed 50% and half that
293 /// amount is applied if it exceeds 10%. Note that these bonuses are some what
294 /// arbitrary and evolved over time by accident as much as because they are
295 /// principled bonuses.
296 /// FIXME: It would be nice to base the bonus values on something more
297 /// scientific. A target may has no bonus on vector instructions.
298 int getInlinerVectorBonusPercent() const;
299
300 /// \return the expected cost of a memcpy, which could e.g. depend on the
301 /// source/destination type and alignment and the number of bytes copied.
302 InstructionCost getMemcpyCost(const Instruction *I) const;
303
304 /// \return The estimated number of case clusters when lowering \p 'SI'.
305 /// \p JTSize Set a jump table size only when \p SI is suitable for a jump
306 /// table.
307 unsigned getEstimatedNumberOfCaseClusters(const SwitchInst &SI,
308 unsigned &JTSize,
309 ProfileSummaryInfo *PSI,
310 BlockFrequencyInfo *BFI) const;
311
312 /// Estimate the cost of a given IR user when lowered.
313 ///
314 /// This can estimate the cost of either a ConstantExpr or Instruction when
315 /// lowered.
316 ///
317 /// \p Operands is a list of operands which can be a result of transformations
318 /// of the current operands. The number of the operands on the list must equal
319 /// to the number of the current operands the IR user has. Their order on the
320 /// list must be the same as the order of the current operands the IR user
321 /// has.
322 ///
323 /// The returned cost is defined in terms of \c TargetCostConstants, see its
324 /// comments for a detailed explanation of the cost values.
325 InstructionCost getUserCost(const User *U, ArrayRef<const Value *> Operands,
326 TargetCostKind CostKind) const;
327
328 /// This is a helper function which calls the two-argument getUserCost
329 /// with \p Operands which are the current operands U has.
330 InstructionCost getUserCost(const User *U, TargetCostKind CostKind) const {
331 SmallVector<const Value *, 4> Operands(U->operand_values());
332 return getUserCost(U, Operands, CostKind);
333 }
334
335 /// If a branch or a select condition is skewed in one direction by more than
336 /// this factor, it is very likely to be predicted correctly.
337 BranchProbability getPredictableBranchThreshold() const;
338
339 /// Return true if branch divergence exists.
340 ///
341 /// Branch divergence has a significantly negative impact on GPU performance
342 /// when threads in the same wavefront take different paths due to conditional
343 /// branches.
344 bool hasBranchDivergence() const;
345
346 /// Return true if the target prefers to use GPU divergence analysis to
347 /// replace the legacy version.
348 bool useGPUDivergenceAnalysis() const;
349
350 /// Returns whether V is a source of divergence.
351 ///
352 /// This function provides the target-dependent information for
353 /// the target-independent LegacyDivergenceAnalysis. LegacyDivergenceAnalysis
354 /// first builds the dependency graph, and then runs the reachability
355 /// algorithm starting with the sources of divergence.
356 bool isSourceOfDivergence(const Value *V) const;
357
358 // Returns true for the target specific
359 // set of operations which produce uniform result
360 // even taking non-uniform arguments
361 bool isAlwaysUniform(const Value *V) const;
362
363 /// Returns the address space ID for a target's 'flat' address space. Note
364 /// this is not necessarily the same as addrspace(0), which LLVM sometimes
365 /// refers to as the generic address space. The flat address space is a
366 /// generic address space that can be used access multiple segments of memory
367 /// with different address spaces. Access of a memory location through a
368 /// pointer with this address space is expected to be legal but slower
369 /// compared to the same memory location accessed through a pointer with a
370 /// different address space.
371 //
372 /// This is for targets with different pointer representations which can
373 /// be converted with the addrspacecast instruction. If a pointer is converted
374 /// to this address space, optimizations should attempt to replace the access
375 /// with the source address space.
376 ///
377 /// \returns ~0u if the target does not have such a flat address space to
378 /// optimize away.
379 unsigned getFlatAddressSpace() const;
380
381 /// Return any intrinsic address operand indexes which may be rewritten if
382 /// they use a flat address space pointer.
383 ///
384 /// \returns true if the intrinsic was handled.
385 bool collectFlatAddressOperands(SmallVectorImpl<int> &OpIndexes,
386 Intrinsic::ID IID) const;
387
388 bool isNoopAddrSpaceCast(unsigned FromAS, unsigned ToAS) const;
389
390 /// Return true if globals in this address space can have initializers other
391 /// than `undef`.
392 bool canHaveNonUndefGlobalInitializerInAddressSpace(unsigned AS) const;
393
394 unsigned getAssumedAddrSpace(const Value *V) const;
395
396 std::pair<const Value *, unsigned>
397 getPredicatedAddrSpace(const Value *V) const;
398
399 /// Rewrite intrinsic call \p II such that \p OldV will be replaced with \p
400 /// NewV, which has a different address space. This should happen for every
401 /// operand index that collectFlatAddressOperands returned for the intrinsic.
402 /// \returns nullptr if the intrinsic was not handled. Otherwise, returns the
403 /// new value (which may be the original \p II with modified operands).
404 Value *rewriteIntrinsicWithAddressSpace(IntrinsicInst *II, Value *OldV,
405 Value *NewV) const;
406
407 /// Test whether calls to a function lower to actual program function
408 /// calls.
409 ///
410 /// The idea is to test whether the program is likely to require a 'call'
411 /// instruction or equivalent in order to call the given function.
412 ///
413 /// FIXME: It's not clear that this is a good or useful query API. Client's
414 /// should probably move to simpler cost metrics using the above.
415 /// Alternatively, we could split the cost interface into distinct code-size
416 /// and execution-speed costs. This would allow modelling the core of this
417 /// query more accurately as a call is a single small instruction, but
418 /// incurs significant execution cost.
419 bool isLoweredToCall(const Function *F) const;
420
421 struct LSRCost {
422 /// TODO: Some of these could be merged. Also, a lexical ordering
423 /// isn't always optimal.
424 unsigned Insns;
425 unsigned NumRegs;
426 unsigned AddRecCost;
427 unsigned NumIVMuls;
428 unsigned NumBaseAdds;
429 unsigned ImmCost;
430 unsigned SetupCost;
431 unsigned ScaleCost;
432 };
433
434 /// Parameters that control the generic loop unrolling transformation.
435 struct UnrollingPreferences {
436 /// The cost threshold for the unrolled loop. Should be relative to the
437 /// getUserCost values returned by this API, and the expectation is that
438 /// the unrolled loop's instructions when run through that interface should
439 /// not exceed this cost. However, this is only an estimate. Also, specific
440 /// loops may be unrolled even with a cost above this threshold if deemed
441 /// profitable. Set this to UINT_MAX to disable the loop body cost
442 /// restriction.
443 unsigned Threshold;
444 /// If complete unrolling will reduce the cost of the loop, we will boost
445 /// the Threshold by a certain percent to allow more aggressive complete
446 /// unrolling. This value provides the maximum boost percentage that we
447 /// can apply to Threshold (The value should be no less than 100).
448 /// BoostedThreshold = Threshold * min(RolledCost / UnrolledCost,
449 /// MaxPercentThresholdBoost / 100)
450 /// E.g. if complete unrolling reduces the loop execution time by 50%
451 /// then we boost the threshold by the factor of 2x. If unrolling is not
452 /// expected to reduce the running time, then we do not increase the
453 /// threshold.
454 unsigned MaxPercentThresholdBoost;
455 /// The cost threshold for the unrolled loop when optimizing for size (set
456 /// to UINT_MAX to disable).
457 unsigned OptSizeThreshold;
458 /// The cost threshold for the unrolled loop, like Threshold, but used
459 /// for partial/runtime unrolling (set to UINT_MAX to disable).
460 unsigned PartialThreshold;
461 /// The cost threshold for the unrolled loop when optimizing for size, like
462 /// OptSizeThreshold, but used for partial/runtime unrolling (set to
463 /// UINT_MAX to disable).
464 unsigned PartialOptSizeThreshold;
465 /// A forced unrolling factor (the number of concatenated bodies of the
466 /// original loop in the unrolled loop body). When set to 0, the unrolling
467 /// transformation will select an unrolling factor based on the current cost
468 /// threshold and other factors.
469 unsigned Count;
470 /// Default unroll count for loops with run-time trip count.
471 unsigned DefaultUnrollRuntimeCount;
472 // Set the maximum unrolling factor. The unrolling factor may be selected
473 // using the appropriate cost threshold, but may not exceed this number
474 // (set to UINT_MAX to disable). This does not apply in cases where the
475 // loop is being fully unrolled.
476 unsigned MaxCount;
477 /// Set the maximum unrolling factor for full unrolling. Like MaxCount, but
478 /// applies even if full unrolling is selected. This allows a target to fall
479 /// back to Partial unrolling if full unrolling is above FullUnrollMaxCount.
480 unsigned FullUnrollMaxCount;
481 // Represents number of instructions optimized when "back edge"
482 // becomes "fall through" in unrolled loop.
483 // For now we count a conditional branch on a backedge and a comparison
484 // feeding it.
485 unsigned BEInsns;
486 /// Allow partial unrolling (unrolling of loops to expand the size of the
487 /// loop body, not only to eliminate small constant-trip-count loops).
488 bool Partial;
489 /// Allow runtime unrolling (unrolling of loops to expand the size of the
490 /// loop body even when the number of loop iterations is not known at
491 /// compile time).
492 bool Runtime;
493 /// Allow generation of a loop remainder (extra iterations after unroll).
494 bool AllowRemainder;
495 /// Allow emitting expensive instructions (such as divisions) when computing
496 /// the trip count of a loop for runtime unrolling.
497 bool AllowExpensiveTripCount;
498 /// Apply loop unroll on any kind of loop
499 /// (mainly to loops that fail runtime unrolling).
500 bool Force;
501 /// Allow using trip count upper bound to unroll loops.
502 bool UpperBound;
503 /// Allow unrolling of all the iterations of the runtime loop remainder.
504 bool UnrollRemainder;
505 /// Allow unroll and jam. Used to enable unroll and jam for the target.
506 bool UnrollAndJam;
507 /// Threshold for unroll and jam, for inner loop size. The 'Threshold'
508 /// value above is used during unroll and jam for the outer loop size.
509 /// This value is used in the same manner to limit the size of the inner
510 /// loop.
511 unsigned UnrollAndJamInnerLoopThreshold;
512 /// Don't allow loop unrolling to simulate more than this number of
513 /// iterations when checking full unroll profitability
514 unsigned MaxIterationsCountToAnalyze;
515 };
516
517 /// Get target-customized preferences for the generic loop unrolling
518 /// transformation. The caller will initialize UP with the current
519 /// target-independent defaults.
520 void getUnrollingPreferences(Loop *L, ScalarEvolution &,
521 UnrollingPreferences &UP,
522 OptimizationRemarkEmitter *ORE) const;
523
524 /// Query the target whether it would be profitable to convert the given loop
525 /// into a hardware loop.
526 bool isHardwareLoopProfitable(Loop *L, ScalarEvolution &SE,
527 AssumptionCache &AC, TargetLibraryInfo *LibInfo,
528 HardwareLoopInfo &HWLoopInfo) const;
529
530 /// Query the target whether it would be prefered to create a predicated
531 /// vector loop, which can avoid the need to emit a scalar epilogue loop.
532 bool preferPredicateOverEpilogue(Loop *L, LoopInfo *LI, ScalarEvolution &SE,
533 AssumptionCache &AC, TargetLibraryInfo *TLI,
534 DominatorTree *DT,
535 LoopVectorizationLegality *LVL,
536 InterleavedAccessInfo *IAI) const;
537
538 /// Query the target whether lowering of the llvm.get.active.lane.mask
539 /// intrinsic is supported and how the mask should be used. A return value
540 /// of PredicationStyle::Data indicates the mask is used as data only,
541 /// whereas PredicationStyle::DataAndControlFlow indicates we should also use
542 /// the mask for control flow in the loop. If unsupported the return value is
543 /// PredicationStyle::None.
544 PredicationStyle emitGetActiveLaneMask() const;
545
546 // Parameters that control the loop peeling transformation
547 struct PeelingPreferences {
548 /// A forced peeling factor (the number of bodied of the original loop
549 /// that should be peeled off before the loop body). When set to 0, the
550 /// a peeling factor based on profile information and other factors.
551 unsigned PeelCount;
552 /// Allow peeling off loop iterations.
553 bool AllowPeeling;
554 /// Allow peeling off loop iterations for loop nests.
555 bool AllowLoopNestsPeeling;
556 /// Allow peeling basing on profile. Uses to enable peeling off all
557 /// iterations basing on provided profile.
558 /// If the value is true the peeling cost model can decide to peel only
559 /// some iterations and in this case it will set this to false.
560 bool PeelProfiledIterations;
561 };
562
563 /// Get target-customized preferences for the generic loop peeling
564 /// transformation. The caller will initialize \p PP with the current
565 /// target-independent defaults with information from \p L and \p SE.
566 void getPeelingPreferences(Loop *L, ScalarEvolution &SE,
567 PeelingPreferences &PP) const;
568
569 /// Targets can implement their own combinations for target-specific
570 /// intrinsics. This function will be called from the InstCombine pass every
571 /// time a target-specific intrinsic is encountered.
572 ///
573 /// \returns None to not do anything target specific or a value that will be
574 /// returned from the InstCombiner. It is possible to return null and stop
575 /// further processing of the intrinsic by returning nullptr.
576 Optional<Instruction *> instCombineIntrinsic(InstCombiner &IC,
577 IntrinsicInst &II) const;
578 /// Can be used to implement target-specific instruction combining.
579 /// \see instCombineIntrinsic
580 Optional<Value *>
581 simplifyDemandedUseBitsIntrinsic(InstCombiner &IC, IntrinsicInst &II,
582 APInt DemandedMask, KnownBits &Known,
583 bool &KnownBitsComputed) const;
584 /// Can be used to implement target-specific instruction combining.
585 /// \see instCombineIntrinsic
586 Optional<Value *> simplifyDemandedVectorEltsIntrinsic(
587 InstCombiner &IC, IntrinsicInst &II, APInt DemandedElts, APInt &UndefElts,
588 APInt &UndefElts2, APInt &UndefElts3,
589 std::function<void(Instruction *, unsigned, APInt, APInt &)>
590 SimplifyAndSetOp) const;
591 /// @}
592
593 /// \name Scalar Target Information
594 /// @{
595
596 /// Flags indicating the kind of support for population count.
597 ///
598 /// Compared to the SW implementation, HW support is supposed to
599 /// significantly boost the performance when the population is dense, and it
600 /// may or may not degrade performance if the population is sparse. A HW
601 /// support is considered as "Fast" if it can outperform, or is on a par
602 /// with, SW implementation when the population is sparse; otherwise, it is
603 /// considered as "Slow".
604 enum PopcntSupportKind { PSK_Software, PSK_SlowHardware, PSK_FastHardware };
605
606 /// Return true if the specified immediate is legal add immediate, that
607 /// is the target has add instructions which can add a register with the
608 /// immediate without having to materialize the immediate into a register.
609 bool isLegalAddImmediate(int64_t Imm) const;
610
611 /// Return true if the specified immediate is legal icmp immediate,
612 /// that is the target has icmp instructions which can compare a register
613 /// against the immediate without having to materialize the immediate into a
614 /// register.
615 bool isLegalICmpImmediate(int64_t Imm) const;
616
617 /// Return true if the addressing mode represented by AM is legal for
618 /// this target, for a load/store of the specified type.
619 /// The type may be VoidTy, in which case only return true if the addressing
620 /// mode is legal for a load/store of any legal type.
621 /// If target returns true in LSRWithInstrQueries(), I may be valid.
622 /// TODO: Handle pre/postinc as well.
623 bool isLegalAddressingMode(Type *Ty, GlobalValue *BaseGV, int64_t BaseOffset,
624 bool HasBaseReg, int64_t Scale,
625 unsigned AddrSpace = 0,
626 Instruction *I = nullptr) const;
627
628 /// Return true if LSR cost of C1 is lower than C1.
629 bool isLSRCostLess(const TargetTransformInfo::LSRCost &C1,
630 const TargetTransformInfo::LSRCost &C2) const;
631
632 /// Return true if LSR major cost is number of registers. Targets which
633 /// implement their own isLSRCostLess and unset number of registers as major
634 /// cost should return false, otherwise return true.
635 bool isNumRegsMajorCostOfLSR() const;
636
637 /// \returns true if LSR should not optimize a chain that includes \p I.
638 bool isProfitableLSRChainElement(Instruction *I) const;
639
640 /// Return true if the target can fuse a compare and branch.
641 /// Loop-strength-reduction (LSR) uses that knowledge to adjust its cost
642 /// calculation for the instructions in a loop.
643 bool canMacroFuseCmp() const;
644
645 /// Return true if the target can save a compare for loop count, for example
646 /// hardware loop saves a compare.
647 bool canSaveCmp(Loop *L, BranchInst **BI, ScalarEvolution *SE, LoopInfo *LI,
648 DominatorTree *DT, AssumptionCache *AC,
649 TargetLibraryInfo *LibInfo) const;
650
651 enum AddressingModeKind {
652 AMK_PreIndexed,
653 AMK_PostIndexed,
654 AMK_None
655 };
656
657 /// Return the preferred addressing mode LSR should make efforts to generate.
658 AddressingModeKind getPreferredAddressingMode(const Loop *L,
659 ScalarEvolution *SE) const;
660
661 /// Return true if the target supports masked store.
662 bool isLegalMaskedStore(Type *DataType, Align Alignment) const;
663 /// Return true if the target supports masked load.
664 bool isLegalMaskedLoad(Type *DataType, Align Alignment) const;
665
666 /// Return true if the target supports nontemporal store.
667 bool isLegalNTStore(Type *DataType, Align Alignment) const;
668 /// Return true if the target supports nontemporal load.
669 bool isLegalNTLoad(Type *DataType, Align Alignment) const;
670
671 /// \Returns true if the target supports broadcasting a load to a vector of
672 /// type <NumElements x ElementTy>.
673 bool isLegalBroadcastLoad(Type *ElementTy, ElementCount NumElements) const;
674
675 /// Return true if the target supports masked scatter.
676 bool isLegalMaskedScatter(Type *DataType, Align Alignment) const;
677 /// Return true if the target supports masked gather.
678 bool isLegalMaskedGather(Type *DataType, Align Alignment) const;
679 /// Return true if the target forces scalarizing of llvm.masked.gather
680 /// intrinsics.
681 bool forceScalarizeMaskedGather(VectorType *Type, Align Alignment) const;
682 /// Return true if the target forces scalarizing of llvm.masked.scatter
683 /// intrinsics.
684 bool forceScalarizeMaskedScatter(VectorType *Type, Align Alignment) const;
685
686 /// Return true if the target supports masked compress store.
687 bool isLegalMaskedCompressStore(Type *DataType) const;
688 /// Return true if the target supports masked expand load.
689 bool isLegalMaskedExpandLoad(Type *DataType) const;
690
691 /// Return true if this is an alternating opcode pattern that can be lowered
692 /// to a single instruction on the target. In X86 this is for the addsub
693 /// instruction which corrsponds to a Shuffle + Fadd + FSub pattern in IR.
694 /// This function expectes two opcodes: \p Opcode1 and \p Opcode2 being
695 /// selected by \p OpcodeMask. The mask contains one bit per lane and is a `0`
696 /// when \p Opcode0 is selected and `1` when Opcode1 is selected.
697 /// \p VecTy is the vector type of the instruction to be generated.
698 bool isLegalAltInstr(VectorType *VecTy, unsigned Opcode0, unsigned Opcode1,
699 const SmallBitVector &OpcodeMask) const;
700
701 /// Return true if we should be enabling ordered reductions for the target.
702 bool enableOrderedReductions() const;
703
704 /// Return true if the target has a unified operation to calculate division
705 /// and remainder. If so, the additional implicit multiplication and
706 /// subtraction required to calculate a remainder from division are free. This
707 /// can enable more aggressive transformations for division and remainder than
708 /// would typically be allowed using throughput or size cost models.
709 bool hasDivRemOp(Type *DataType, bool IsSigned) const;
710
711 /// Return true if the given instruction (assumed to be a memory access
712 /// instruction) has a volatile variant. If that's the case then we can avoid
713 /// addrspacecast to generic AS for volatile loads/stores. Default
714 /// implementation returns false, which prevents address space inference for
715 /// volatile loads/stores.
716 bool hasVolatileVariant(Instruction *I, unsigned AddrSpace) const;
717
718 /// Return true if target doesn't mind addresses in vectors.
719 bool prefersVectorizedAddressing() const;
720
721 /// Return the cost of the scaling factor used in the addressing
722 /// mode represented by AM for this target, for a load/store
723 /// of the specified type.
724 /// If the AM is supported, the return value must be >= 0.
725 /// If the AM is not supported, it returns a negative value.
726 /// TODO: Handle pre/postinc as well.
727 InstructionCost getScalingFactorCost(Type *Ty, GlobalValue *BaseGV,
728 int64_t BaseOffset, bool HasBaseReg,
729 int64_t Scale,
730 unsigned AddrSpace = 0) const;
731
732 /// Return true if the loop strength reduce pass should make
733 /// Instruction* based TTI queries to isLegalAddressingMode(). This is
734 /// needed on SystemZ, where e.g. a memcpy can only have a 12 bit unsigned
735 /// immediate offset and no index register.
736 bool LSRWithInstrQueries() const;
737
738 /// Return true if it's free to truncate a value of type Ty1 to type
739 /// Ty2. e.g. On x86 it's free to truncate a i32 value in register EAX to i16
740 /// by referencing its sub-register AX.
741 bool isTruncateFree(Type *Ty1, Type *Ty2) const;
742
743 /// Return true if it is profitable to hoist instruction in the
744 /// then/else to before if.
745 bool isProfitableToHoist(Instruction *I) const;
746
747 bool useAA() const;
748
749 /// Return true if this type is legal.
750 bool isTypeLegal(Type *Ty) const;
751
752 /// Returns the estimated number of registers required to represent \p Ty.
753 unsigned getRegUsageForType(Type *Ty) const;
754
755 /// Return true if switches should be turned into lookup tables for the
756 /// target.
757 bool shouldBuildLookupTables() const;
758
759 /// Return true if switches should be turned into lookup tables
760 /// containing this constant value for the target.
761 bool shouldBuildLookupTablesForConstant(Constant *C) const;
762
763 /// Return true if lookup tables should be turned into relative lookup tables.
764 bool shouldBuildRelLookupTables() const;
765
766 /// Return true if the input function which is cold at all call sites,
767 /// should use coldcc calling convention.
768 bool useColdCCForColdCall(Function &F) const;
769
770 /// Estimate the overhead of scalarizing an instruction. Insert and Extract
771 /// are set if the demanded result elements need to be inserted and/or
772 /// extracted from vectors.
773 InstructionCost getScalarizationOverhead(VectorType *Ty,
774 const APInt &DemandedElts,
775 bool Insert, bool Extract) const;
776
777 /// Estimate the overhead of scalarizing an instructions unique
778 /// non-constant operands. The (potentially vector) types to use for each of
779 /// argument are passes via Tys.
780 InstructionCost getOperandsScalarizationOverhead(ArrayRef<const Value *> Args,
781 ArrayRef<Type *> Tys) const;
782
783 /// If target has efficient vector element load/store instructions, it can
784 /// return true here so that insertion/extraction costs are not added to
785 /// the scalarization cost of a load/store.
786 bool supportsEfficientVectorElementLoadStore() const;
787
788 /// If the target supports tail calls.
789 bool supportsTailCalls() const;
790
791 /// Don't restrict interleaved unrolling to small loops.
792 bool enableAggressiveInterleaving(bool LoopHasReductions) const;
793
794 /// Returns options for expansion of memcmp. IsZeroCmp is
795 // true if this is the expansion of memcmp(p1, p2, s) == 0.
796 struct MemCmpExpansionOptions {
797 // Return true if memcmp expansion is enabled.
798 operator bool() const { return MaxNumLoads > 0; }
799
800 // Maximum number of load operations.
801 unsigned MaxNumLoads = 0;
802
803 // The list of available load sizes (in bytes), sorted in decreasing order.
804 SmallVector<unsigned, 8> LoadSizes;
805
806 // For memcmp expansion when the memcmp result is only compared equal or
807 // not-equal to 0, allow up to this number of load pairs per block. As an
808 // example, this may allow 'memcmp(a, b, 3) == 0' in a single block:
809 // a0 = load2bytes &a[0]
810 // b0 = load2bytes &b[0]
811 // a2 = load1byte &a[2]
812 // b2 = load1byte &b[2]
813 // r = cmp eq (a0 ^ b0 | a2 ^ b2), 0
814 unsigned NumLoadsPerBlock = 1;
815
816 // Set to true to allow overlapping loads. For example, 7-byte compares can
817 // be done with two 4-byte compares instead of 4+2+1-byte compares. This
818 // requires all loads in LoadSizes to be doable in an unaligned way.
819 bool AllowOverlappingLoads = false;
820 };
821 MemCmpExpansionOptions enableMemCmpExpansion(bool OptSize,
822 bool IsZeroCmp) const;
823
824 /// Enable matching of interleaved access groups.
825 bool enableInterleavedAccessVectorization() const;
826
827 /// Enable matching of interleaved access groups that contain predicated
828 /// accesses or gaps and therefore vectorized using masked
829 /// vector loads/stores.
830 bool enableMaskedInterleavedAccessVectorization() const;
831
832 /// Indicate that it is potentially unsafe to automatically vectorize
833 /// floating-point operations because the semantics of vector and scalar
834 /// floating-point semantics may differ. For example, ARM NEON v7 SIMD math
835 /// does not support IEEE-754 denormal numbers, while depending on the
836 /// platform, scalar floating-point math does.
837 /// This applies to floating-point math operations and calls, not memory
838 /// operations, shuffles, or casts.
839 bool isFPVectorizationPotentiallyUnsafe() const;
840
841 /// Determine if the target supports unaligned memory accesses.
842 bool allowsMisalignedMemoryAccesses(LLVMContext &Context, unsigned BitWidth,
843 unsigned AddressSpace = 0,
844 Align Alignment = Align(1),
845 bool *Fast = nullptr) const;
846
847 /// Return hardware support for population count.
848 PopcntSupportKind getPopcntSupport(unsigned IntTyWidthInBit) const;
849
850 /// Return true if the hardware has a fast square-root instruction.
851 bool haveFastSqrt(Type *Ty) const;
852
853 /// Return true if it is faster to check if a floating-point value is NaN
854 /// (or not-NaN) versus a comparison against a constant FP zero value.
855 /// Targets should override this if materializing a 0.0 for comparison is
856 /// generally as cheap as checking for ordered/unordered.
857 bool isFCmpOrdCheaperThanFCmpZero(Type *Ty) const;
858
859 /// Return the expected cost of supporting the floating point operation
860 /// of the specified type.
861 InstructionCost getFPOpCost(Type *Ty) const;
862
863 /// Return the expected cost of materializing for the given integer
864 /// immediate of the specified type.
865 InstructionCost getIntImmCost(const APInt &Imm, Type *Ty,
866 TargetCostKind CostKind) const;
867
868 /// Return the expected cost of materialization for the given integer
869 /// immediate of the specified type for a given instruction. The cost can be
870 /// zero if the immediate can be folded into the specified instruction.
871 InstructionCost getIntImmCostInst(unsigned Opc, unsigned Idx,
872 const APInt &Imm, Type *Ty,
873 TargetCostKind CostKind,
874 Instruction *Inst = nullptr) const;
875 InstructionCost getIntImmCostIntrin(Intrinsic::ID IID, unsigned Idx,
876 const APInt &Imm, Type *Ty,
877 TargetCostKind CostKind) const;
878
879 /// Return the expected cost for the given integer when optimising
880 /// for size. This is different than the other integer immediate cost
881 /// functions in that it is subtarget agnostic. This is useful when you e.g.
882 /// target one ISA such as Aarch32 but smaller encodings could be possible
883 /// with another such as Thumb. This return value is used as a penalty when
884 /// the total costs for a constant is calculated (the bigger the cost, the
885 /// more beneficial constant hoisting is).
886 InstructionCost getIntImmCodeSizeCost(unsigned Opc, unsigned Idx,
887 const APInt &Imm, Type *Ty) const;
888 /// @}
889
890 /// \name Vector Target Information
891 /// @{
892
893 /// The various kinds of shuffle patterns for vector queries.
894 enum ShuffleKind {
895 SK_Broadcast, ///< Broadcast element 0 to all other elements.
896 SK_Reverse, ///< Reverse the order of the vector.
897 SK_Select, ///< Selects elements from the corresponding lane of
898 ///< either source operand. This is equivalent to a
899 ///< vector select with a constant condition operand.
900 SK_Transpose, ///< Transpose two vectors.
901 SK_InsertSubvector, ///< InsertSubvector. Index indicates start offset.
902 SK_ExtractSubvector, ///< ExtractSubvector Index indicates start offset.
903 SK_PermuteTwoSrc, ///< Merge elements from two source vectors into one
904 ///< with any shuffle mask.
905 SK_PermuteSingleSrc, ///< Shuffle elements of single source vector with any
906 ///< shuffle mask.
907 SK_Splice ///< Concatenates elements from the first input vector
908 ///< with elements of the second input vector. Returning
909 ///< a vector of the same type as the input vectors.
910 };
911
912 /// Additional information about an operand's possible values.
913 enum OperandValueKind {
914 OK_AnyValue, // Operand can have any value.
915 OK_UniformValue, // Operand is uniform (splat of a value).
916 OK_UniformConstantValue, // Operand is uniform constant.
917 OK_NonUniformConstantValue // Operand is a non uniform constant value.
918 };
919
920 /// Additional properties of an operand's values.
921 enum OperandValueProperties { OP_None = 0, OP_PowerOf2 = 1 };
922
923 /// \return the number of registers in the target-provided register class.
924 unsigned getNumberOfRegisters(unsigned ClassID) const;
925
926 /// \return the target-provided register class ID for the provided type,
927 /// accounting for type promotion and other type-legalization techniques that
928 /// the target might apply. However, it specifically does not account for the
929 /// scalarization or splitting of vector types. Should a vector type require
930 /// scalarization or splitting into multiple underlying vector registers, that
931 /// type should be mapped to a register class containing no registers.
932 /// Specifically, this is designed to provide a simple, high-level view of the
933 /// register allocation later performed by the backend. These register classes
934 /// don't necessarily map onto the register classes used by the backend.
935 /// FIXME: It's not currently possible to determine how many registers
936 /// are used by the provided type.
937 unsigned getRegisterClassForType(bool Vector, Type *Ty = nullptr) const;
938
939 /// \return the target-provided register class name
940 const char *getRegisterClassName(unsigned ClassID) const;
941
942 enum RegisterKind { RGK_Scalar, RGK_FixedWidthVector, RGK_ScalableVector };
943
944 /// \return The width of the largest scalar or vector register type.
945 TypeSize getRegisterBitWidth(RegisterKind K) const;
946
947 /// \return The width of the smallest vector register type.
948 unsigned getMinVectorRegisterBitWidth() const;
949
950 /// \return The maximum value of vscale if the target specifies an
951 /// architectural maximum vector length, and None otherwise.
952 Optional<unsigned> getMaxVScale() const;
953
954 /// \return the value of vscale to tune the cost model for.
955 Optional<unsigned> getVScaleForTuning() const;
956
957 /// \return True if the vectorization factor should be chosen to
958 /// make the vector of the smallest element type match the size of a
959 /// vector register. For wider element types, this could result in
960 /// creating vectors that span multiple vector registers.
961 /// If false, the vectorization factor will be chosen based on the
962 /// size of the widest element type.
963 /// \p K Register Kind for vectorization.
964 bool shouldMaximizeVectorBandwidth(TargetTransformInfo::RegisterKind K) const;
965
966 /// \return The minimum vectorization factor for types of given element
967 /// bit width, or 0 if there is no minimum VF. The returned value only
968 /// applies when shouldMaximizeVectorBandwidth returns true.
969 /// If IsScalable is true, the returned ElementCount must be a scalable VF.
970 ElementCount getMinimumVF(unsigned ElemWidth, bool IsScalable) const;
971
972 /// \return The maximum vectorization factor for types of given element
973 /// bit width and opcode, or 0 if there is no maximum VF.
974 /// Currently only used by the SLP vectorizer.
975 unsigned getMaximumVF(unsigned ElemWidth, unsigned Opcode) const;
976
977 /// \return The minimum vectorization factor for the store instruction. Given
978 /// the initial estimation of the minimum vector factor and store value type,
979 /// it tries to find possible lowest VF, which still might be profitable for
980 /// the vectorization.
981 /// \param VF Initial estimation of the minimum vector factor.
982 /// \param ScalarMemTy Scalar memory type of the store operation.
983 /// \param ScalarValTy Scalar type of the stored value.
984 /// Currently only used by the SLP vectorizer.
985 unsigned getStoreMinimumVF(unsigned VF, Type *ScalarMemTy,
986 Type *ScalarValTy) const;
987
988 /// \return True if it should be considered for address type promotion.
989 /// \p AllowPromotionWithoutCommonHeader Set true if promoting \p I is
990 /// profitable without finding other extensions fed by the same input.
991 bool shouldConsiderAddressTypePromotion(
992 const Instruction &I, bool &AllowPromotionWithoutCommonHeader) const;
993
994 /// \return The size of a cache line in bytes.
995 unsigned getCacheLineSize() const;
996
997 /// The possible cache levels
998 enum class CacheLevel {
999 L1D, // The L1 data cache
1000 L2D, // The L2 data cache
1001
1002 // We currently do not model L3 caches, as their sizes differ widely between
1003 // microarchitectures. Also, we currently do not have a use for L3 cache
1004 // size modeling yet.
1005 };
1006
1007 /// \return The size of the cache level in bytes, if available.
1008 Optional<unsigned> getCacheSize(CacheLevel Level) const;
1009
1010 /// \return The associativity of the cache level, if available.
1011 Optional<unsigned> getCacheAssociativity(CacheLevel Level) const;
1012
1013 /// \return How much before a load we should place the prefetch
1014 /// instruction. This is currently measured in number of
1015 /// instructions.
1016 unsigned getPrefetchDistance() const;
1017
1018 /// Some HW prefetchers can handle accesses up to a certain constant stride.
1019 /// Sometimes prefetching is beneficial even below the HW prefetcher limit,
1020 /// and the arguments provided are meant to serve as a basis for deciding this
1021 /// for a particular loop.
1022 ///
1023 /// \param NumMemAccesses Number of memory accesses in the loop.
1024 /// \param NumStridedMemAccesses Number of the memory accesses that
1025 /// ScalarEvolution could find a known stride
1026 /// for.
1027 /// \param NumPrefetches Number of software prefetches that will be
1028 /// emitted as determined by the addresses
1029 /// involved and the cache line size.
1030 /// \param HasCall True if the loop contains a call.
1031 ///
1032 /// \return This is the minimum stride in bytes where it makes sense to start
1033 /// adding SW prefetches. The default is 1, i.e. prefetch with any
1034 /// stride.
1035 unsigned getMinPrefetchStride(unsigned NumMemAccesses,
1036 unsigned NumStridedMemAccesses,
1037 unsigned NumPrefetches, bool HasCall) const;
1038
1039 /// \return The maximum number of iterations to prefetch ahead. If
1040 /// the required number of iterations is more than this number, no
1041 /// prefetching is performed.
1042 unsigned getMaxPrefetchIterationsAhead() const;
1043
1044 /// \return True if prefetching should also be done for writes.
1045 bool enableWritePrefetching() const;
1046
1047 /// \return if target want to issue a prefetch in address space \p AS.
1048 bool shouldPrefetchAddressSpace(unsigned AS) const;
1049
1050 /// \return The maximum interleave factor that any transform should try to
1051 /// perform for this target. This number depends on the level of parallelism
1052 /// and the number of execution units in the CPU.
1053 unsigned getMaxInterleaveFactor(unsigned VF) const;
1054
1055 /// Collect properties of V used in cost analysis, e.g. OP_PowerOf2.
1056 static OperandValueKind getOperandInfo(const Value *V,
1057 OperandValueProperties &OpProps);
1058
1059 /// This is an approximation of reciprocal throughput of a math/logic op.
1060 /// A higher cost indicates less expected throughput.
1061 /// From Agner Fog's guides, reciprocal throughput is "the average number of
1062 /// clock cycles per instruction when the instructions are not part of a
1063 /// limiting dependency chain."
1064 /// Therefore, costs should be scaled to account for multiple execution units
1065 /// on the target that can process this type of instruction. For example, if
1066 /// there are 5 scalar integer units and 2 vector integer units that can
1067 /// calculate an 'add' in a single cycle, this model should indicate that the
1068 /// cost of the vector add instruction is 2.5 times the cost of the scalar
1069 /// add instruction.
1070 /// \p Args is an optional argument which holds the instruction operands
1071 /// values so the TTI can analyze those values searching for special
1072 /// cases or optimizations based on those values.
1073 /// \p CxtI is the optional original context instruction, if one exists, to
1074 /// provide even more information.
1075 InstructionCost getArithmeticInstrCost(
1076 unsigned Opcode, Type *Ty,
1077 TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput,
1078 OperandValueKind Opd1Info = OK_AnyValue,
1079 OperandValueKind Opd2Info = OK_AnyValue,
1080 OperandValueProperties Opd1PropInfo = OP_None,
1081 OperandValueProperties Opd2PropInfo = OP_None,
1082 ArrayRef<const Value *> Args = ArrayRef<const Value *>(),
1083 const Instruction *CxtI = nullptr) const;
1084
1085 /// \return The cost of a shuffle instruction of kind Kind and of type Tp.
1086 /// The exact mask may be passed as Mask, or else the array will be empty.
1087 /// The index and subtype parameters are used by the subvector insertion and
1088 /// extraction shuffle kinds to show the insert/extract point and the type of
1089 /// the subvector being inserted/extracted. The operands of the shuffle can be
1090 /// passed through \p Args, which helps improve the cost estimation in some
1091 /// cases, like in broadcast loads.
1092 /// NOTE: For subvector extractions Tp represents the source type.
1093 InstructionCost getShuffleCost(ShuffleKind Kind, VectorType *Tp,
1094 ArrayRef<int> Mask = None, int Index = 0,
1095 VectorType *SubTp = nullptr,
1096 ArrayRef<const Value *> Args = None) const;
1097
1098 /// Represents a hint about the context in which a cast is used.
1099 ///
1100 /// For zext/sext, the context of the cast is the operand, which must be a
1101 /// load of some kind. For trunc, the context is of the cast is the single
1102 /// user of the instruction, which must be a store of some kind.
1103 ///
1104 /// This enum allows the vectorizer to give getCastInstrCost an idea of the
1105 /// type of cast it's dealing with, as not every cast is equal. For instance,
1106 /// the zext of a load may be free, but the zext of an interleaving load can
1107 //// be (very) expensive!
1108 ///
1109 /// See \c getCastContextHint to compute a CastContextHint from a cast
1110 /// Instruction*. Callers can use it if they don't need to override the
1111 /// context and just want it to be calculated from the instruction.
1112 ///
1113 /// FIXME: This handles the types of load/store that the vectorizer can
1114 /// produce, which are the cases where the context instruction is most
1115 /// likely to be incorrect. There are other situations where that can happen
1116 /// too, which might be handled here but in the long run a more general
1117 /// solution of costing multiple instructions at the same times may be better.
1118 enum class CastContextHint : uint8_t {
1119 None, ///< The cast is not used with a load/store of any kind.
1120 Normal, ///< The cast is used with a normal load/store.
1121 Masked, ///< The cast is used with a masked load/store.
1122 GatherScatter, ///< The cast is used with a gather/scatter.
1123 Interleave, ///< The cast is used with an interleaved load/store.
1124 Reversed, ///< The cast is used with a reversed load/store.
1125 };
1126
1127 /// Calculates a CastContextHint from \p I.
1128 /// This should be used by callers of getCastInstrCost if they wish to
1129 /// determine the context from some instruction.
1130 /// \returns the CastContextHint for ZExt/SExt/Trunc, None if \p I is nullptr,
1131 /// or if it's another type of cast.
1132 static CastContextHint getCastContextHint(const Instruction *I);
1133
1134 /// \return The expected cost of cast instructions, such as bitcast, trunc,
1135 /// zext, etc. If there is an existing instruction that holds Opcode, it
1136 /// may be passed in the 'I' parameter.
1137 InstructionCost
1138 getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src,
1139 TTI::CastContextHint CCH,
1140 TTI::TargetCostKind CostKind = TTI::TCK_SizeAndLatency,
1141 const Instruction *I = nullptr) const;
1142
1143 /// \return The expected cost of a sign- or zero-extended vector extract. Use
1144 /// -1 to indicate that there is no information about the index value.
1145 InstructionCost getExtractWithExtendCost(unsigned Opcode, Type *Dst,
1146 VectorType *VecTy,
1147 unsigned Index = -1) const;
1148
1149 /// \return The expected cost of control-flow related instructions such as
1150 /// Phi, Ret, Br, Switch.
1151 InstructionCost
1152 getCFInstrCost(unsigned Opcode,
1153 TTI::TargetCostKind CostKind = TTI::TCK_SizeAndLatency,
1154 const Instruction *I = nullptr) const;
1155
1156 /// \returns The expected cost of compare and select instructions. If there
1157 /// is an existing instruction that holds Opcode, it may be passed in the
1158 /// 'I' parameter. The \p VecPred parameter can be used to indicate the select
1159 /// is using a compare with the specified predicate as condition. When vector
1160 /// types are passed, \p VecPred must be used for all lanes.
1161 InstructionCost
1162 getCmpSelInstrCost(unsigned Opcode, Type *ValTy, Type *CondTy,
1163 CmpInst::Predicate VecPred,
1164 TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput,
1165 const Instruction *I = nullptr) const;
1166
1167 /// \return The expected cost of vector Insert and Extract.
1168 /// Use -1 to indicate that there is no information on the index value.
1169 /// This is used when the instruction is not available; a typical use
1170 /// case is to provision the cost of vectorization/scalarization in
1171 /// vectorizer passes.
1172 InstructionCost getVectorInstrCost(unsigned Opcode, Type *Val,
1173 unsigned Index = -1) const;
1174
1175 /// \return The expected cost of vector Insert and Extract.
1176 /// This is used when instruction is available, and implementation
1177 /// asserts 'I' is not nullptr.
1178 ///
1179 /// A typical suitable use case is cost estimation when vector instruction
1180 /// exists (e.g., from basic blocks during transformation).
1181 InstructionCost getVectorInstrCost(const Instruction &I, Type *Val,
1182 unsigned Index = -1) const;
1183
1184 /// \return The cost of replication shuffle of \p VF elements typed \p EltTy
1185 /// \p ReplicationFactor times.
1186 ///
1187 /// For example, the mask for \p ReplicationFactor=3 and \p VF=4 is:
1188 /// <0,0,0,1,1,1,2,2,2,3,3,3>
1189 InstructionCost getReplicationShuffleCost(Type *EltTy, int ReplicationFactor,
1190 int VF,
1191 const APInt &DemandedDstElts,
1192 TTI::TargetCostKind CostKind);
1193
1194 /// \return The cost of Load and Store instructions.
1195 InstructionCost
1196 getMemoryOpCost(unsigned Opcode, Type *Src, Align Alignment,
1197 unsigned AddressSpace,
1198 TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput,
1199 const Instruction *I = nullptr) const;
1200
1201 /// \return The cost of VP Load and Store instructions.
1202 InstructionCost
1203 getVPMemoryOpCost(unsigned Opcode, Type *Src, Align Alignment,
1204 unsigned AddressSpace,
1205 TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput,
1206 const Instruction *I = nullptr) const;
1207
1208 /// \return The cost of masked Load and Store instructions.
1209 InstructionCost getMaskedMemoryOpCost(
1210 unsigned Opcode, Type *Src, Align Alignment, unsigned AddressSpace,
1211 TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput) const;
1212
1213 /// \return The cost of Gather or Scatter operation
1214 /// \p Opcode - is a type of memory access Load or Store
1215 /// \p DataTy - a vector type of the data to be loaded or stored
1216 /// \p Ptr - pointer [or vector of pointers] - address[es] in memory
1217 /// \p VariableMask - true when the memory access is predicated with a mask
1218 /// that is not a compile-time constant
1219 /// \p Alignment - alignment of single element
1220 /// \p I - the optional original context instruction, if one exists, e.g. the
1221 /// load/store to transform or the call to the gather/scatter intrinsic
1222 InstructionCost getGatherScatterOpCost(
1223 unsigned Opcode, Type *DataTy, const Value *Ptr, bool VariableMask,
1224 Align Alignment, TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput,
1225 const Instruction *I = nullptr) const;
1226
1227 /// \return The cost of the interleaved memory operation.
1228 /// \p Opcode is the memory operation code
1229 /// \p VecTy is the vector type of the interleaved access.
1230 /// \p Factor is the interleave factor
1231 /// \p Indices is the indices for interleaved load members (as interleaved
1232 /// load allows gaps)
1233 /// \p Alignment is the alignment of the memory operation
1234 /// \p AddressSpace is address space of the pointer.
1235 /// \p UseMaskForCond indicates if the memory access is predicated.
1236 /// \p UseMaskForGaps indicates if gaps should be masked.
1237 InstructionCost getInterleavedMemoryOpCost(
1238 unsigned Opcode, Type *VecTy, unsigned Factor, ArrayRef<unsigned> Indices,
1239 Align Alignment, unsigned AddressSpace,
1240 TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput,
1241 bool UseMaskForCond = false, bool UseMaskForGaps = false) const;
1242
1243 /// A helper function to determine the type of reduction algorithm used
1244 /// for a given \p Opcode and set of FastMathFlags \p FMF.
1245 static bool requiresOrderedReduction(Optional<FastMathFlags> FMF) {
1246 return FMF != None && !(*FMF).allowReassoc();
1247 }
1248
1249 /// Calculate the cost of vector reduction intrinsics.
1250 ///
1251 /// This is the cost of reducing the vector value of type \p Ty to a scalar
1252 /// value using the operation denoted by \p Opcode. The FastMathFlags
1253 /// parameter \p FMF indicates what type of reduction we are performing:
1254 /// 1. Tree-wise. This is the typical 'fast' reduction performed that
1255 /// involves successively splitting a vector into half and doing the
1256 /// operation on the pair of halves until you have a scalar value. For
1257 /// example:
1258 /// (v0, v1, v2, v3)
1259 /// ((v0+v2), (v1+v3), undef, undef)
1260 /// ((v0+v2+v1+v3), undef, undef, undef)
1261 /// This is the default behaviour for integer operations, whereas for
1262 /// floating point we only do this if \p FMF indicates that
1263 /// reassociation is allowed.
1264 /// 2. Ordered. For a vector with N elements this involves performing N
1265 /// operations in lane order, starting with an initial scalar value, i.e.
1266 /// result = InitVal + v0
1267 /// result = result + v1
1268 /// result = result + v2
1269 /// result = result + v3
1270 /// This is only the case for FP operations and when reassociation is not
1271 /// allowed.
1272 ///
1273 InstructionCost getArithmeticReductionCost(
1274 unsigned Opcode, VectorType *Ty, Optional<FastMathFlags> FMF,
1275 TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput) const;
1276
1277 InstructionCost getMinMaxReductionCost(
1278 VectorType *Ty, VectorType *CondTy, bool IsUnsigned,
1279 TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput) const;
1280
1281 /// Calculate the cost of an extended reduction pattern, similar to
1282 /// getArithmeticReductionCost of an Add reduction with multiply and optional
1283 /// extensions. This is the cost of as:
1284 /// ResTy vecreduce.add(mul (A, B)).
1285 /// ResTy vecreduce.add(mul(ext(Ty A), ext(Ty B)).
1286 InstructionCost getMulAccReductionCost(
1287 bool IsUnsigned, Type *ResTy, VectorType *Ty,
1288 TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput) const;
1289
1290 /// Calculate the cost of an extended reduction pattern, similar to
1291 /// getArithmeticReductionCost of a reduction with an extension.
1292 /// This is the cost of as:
1293 /// ResTy vecreduce(ext(Ty A)).
1294 InstructionCost getExtendedReductionCost(
1295 unsigned Opcode, bool IsUnsigned, Type *ResTy, VectorType *Ty,
1296 Optional<FastMathFlags> FMF,
1297 TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput) const;
1298
1299 /// \returns The cost of Intrinsic instructions. Analyses the real arguments.
1300 /// Three cases are handled: 1. scalar instruction 2. vector instruction
1301 /// 3. scalar instruction which is to be vectorized.
1302 InstructionCost getIntrinsicInstrCost(const IntrinsicCostAttributes &ICA,
1303 TTI::TargetCostKind CostKind) const;
1304
1305 /// \returns The cost of Call instructions.
1306 InstructionCost getCallInstrCost(
1307 Function *F, Type *RetTy, ArrayRef<Type *> Tys,
1308 TTI::TargetCostKind CostKind = TTI::TCK_SizeAndLatency) const;
1309
1310 /// \returns The number of pieces into which the provided type must be
1311 /// split during legalization. Zero is returned when the answer is unknown.
1312 unsigned getNumberOfParts(Type *Tp) const;
1313
1314 /// \returns The cost of the address computation. For most targets this can be
1315 /// merged into the instruction indexing mode. Some targets might want to
1316 /// distinguish between address computation for memory operations on vector
1317 /// types and scalar types. Such targets should override this function.
1318 /// The 'SE' parameter holds pointer for the scalar evolution object which
1319 /// is used in order to get the Ptr step value in case of constant stride.
1320 /// The 'Ptr' parameter holds SCEV of the access pointer.
1321 InstructionCost getAddressComputationCost(Type *Ty,
1322 ScalarEvolution *SE = nullptr,
1323 const SCEV *Ptr = nullptr) const;
1324
1325 /// \returns The cost, if any, of keeping values of the given types alive
1326 /// over a callsite.
1327 ///
1328 /// Some types may require the use of register classes that do not have
1329 /// any callee-saved registers, so would require a spill and fill.
1330 InstructionCost getCostOfKeepingLiveOverCall(ArrayRef<Type *> Tys) const;
1331
1332 /// \returns True if the intrinsic is a supported memory intrinsic. Info
1333 /// will contain additional information - whether the intrinsic may write
1334 /// or read to memory, volatility and the pointer. Info is undefined
1335 /// if false is returned.
1336 bool getTgtMemIntrinsic(IntrinsicInst *Inst, MemIntrinsicInfo &Info) const;
1337
1338 /// \returns The maximum element size, in bytes, for an element
1339 /// unordered-atomic memory intrinsic.
1340 unsigned getAtomicMemIntrinsicMaxElementSize() const;
1341
1342 /// \returns A value which is the result of the given memory intrinsic. New
1343 /// instructions may be created to extract the result from the given intrinsic
1344 /// memory operation. Returns nullptr if the target cannot create a result
1345 /// from the given intrinsic.
1346 Value *getOrCreateResultFromMemIntrinsic(IntrinsicInst *Inst,
1347 Type *ExpectedType) const;
1348
1349 /// \returns The type to use in a loop expansion of a memcpy call.
1350 Type *
1351 getMemcpyLoopLoweringType(LLVMContext &Context, Value *Length,
1352 unsigned SrcAddrSpace, unsigned DestAddrSpace,
1353 unsigned SrcAlign, unsigned DestAlign,
1354 Optional<uint32_t> AtomicElementSize = None) const;
1355
1356 /// \param[out] OpsOut The operand types to copy RemainingBytes of memory.
1357 /// \param RemainingBytes The number of bytes to copy.
1358 ///
1359 /// Calculates the operand types to use when copying \p RemainingBytes of
1360 /// memory, where source and destination alignments are \p SrcAlign and
1361 /// \p DestAlign respectively.
1362 void getMemcpyLoopResidualLoweringType(
1363 SmallVectorImpl<Type *> &OpsOut, LLVMContext &Context,
1364 unsigned RemainingBytes, unsigned SrcAddrSpace, unsigned DestAddrSpace,
1365 unsigned SrcAlign, unsigned DestAlign,
1366 Optional<uint32_t> AtomicCpySize = None) const;
1367
1368 /// \returns True if the two functions have compatible attributes for inlining
1369 /// purposes.
1370 bool areInlineCompatible(const Function *Caller,
1371 const Function *Callee) const;
1372
1373 /// \returns True if the caller and callee agree on how \p Types will be
1374 /// passed to or returned from the callee.
1375 /// to the callee.
1376 /// \param Types List of types to check.
1377 bool areTypesABICompatible(const Function *Caller, const Function *Callee,
1378 const ArrayRef<Type *> &Types) const;
1379
1380 /// The type of load/store indexing.
1381 enum MemIndexedMode {
1382 MIM_Unindexed, ///< No indexing.
1383 MIM_PreInc, ///< Pre-incrementing.
1384 MIM_PreDec, ///< Pre-decrementing.
1385 MIM_PostInc, ///< Post-incrementing.
1386 MIM_PostDec ///< Post-decrementing.
1387 };
1388
1389 /// \returns True if the specified indexed load for the given type is legal.
1390 bool isIndexedLoadLegal(enum MemIndexedMode Mode, Type *Ty) const;
1391
1392 /// \returns True if the specified indexed store for the given type is legal.
1393 bool isIndexedStoreLegal(enum MemIndexedMode Mode, Type *Ty) const;
1394
1395 /// \returns The bitwidth of the largest vector type that should be used to
1396 /// load/store in the given address space.
1397 unsigned getLoadStoreVecRegBitWidth(unsigned AddrSpace) const;
1398
1399 /// \returns True if the load instruction is legal to vectorize.
1400 bool isLegalToVectorizeLoad(LoadInst *LI) const;
1401
1402 /// \returns True if the store instruction is legal to vectorize.
1403 bool isLegalToVectorizeStore(StoreInst *SI) const;
1404
1405 /// \returns True if it is legal to vectorize the given load chain.
1406 bool isLegalToVectorizeLoadChain(unsigned ChainSizeInBytes, Align Alignment,
1407 unsigned AddrSpace) const;
1408
1409 /// \returns True if it is legal to vectorize the given store chain.
1410 bool isLegalToVectorizeStoreChain(unsigned ChainSizeInBytes, Align Alignment,
1411 unsigned AddrSpace) const;
1412
1413 /// \returns True if it is legal to vectorize the given reduction kind.
1414 bool isLegalToVectorizeReduction(const RecurrenceDescriptor &RdxDesc,
1415 ElementCount VF) const;
1416
1417 /// \returns True if the given type is supported for scalable vectors
1418 bool isElementTypeLegalForScalableVector(Type *Ty) const;
1419
1420 /// \returns The new vector factor value if the target doesn't support \p
1421 /// SizeInBytes loads or has a better vector factor.
1422 unsigned getLoadVectorFactor(unsigned VF, unsigned LoadSize,
1423 unsigned ChainSizeInBytes,
1424 VectorType *VecTy) const;
1425
1426 /// \returns The new vector factor value if the target doesn't support \p
1427 /// SizeInBytes stores or has a better vector factor.
1428 unsigned getStoreVectorFactor(unsigned VF, unsigned StoreSize,
1429 unsigned ChainSizeInBytes,
1430 VectorType *VecTy) const;
1431
1432 /// Flags describing the kind of vector reduction.
1433 struct ReductionFlags {
1434 ReductionFlags() = default;
1435 bool IsMaxOp =
1436 false; ///< If the op a min/max kind, true if it's a max operation.
1437 bool IsSigned = false; ///< Whether the operation is a signed int reduction.
1438 bool NoNaN =
1439 false; ///< If op is an fp min/max, whether NaNs may be present.
1440 };
1441
1442 /// \returns True if the target prefers reductions in loop.
1443 bool preferInLoopReduction(unsigned Opcode, Type *Ty,
1444 ReductionFlags Flags) const;
1445
1446 /// \returns True if the target prefers reductions select kept in the loop
1447 /// when tail folding. i.e.
1448 /// loop:
1449 /// p = phi (0, s)
1450 /// a = add (p, x)
1451 /// s = select (mask, a, p)
1452 /// vecreduce.add(s)
1453 ///
1454 /// As opposed to the normal scheme of p = phi (0, a) which allows the select
1455 /// to be pulled out of the loop. If the select(.., add, ..) can be predicated
1456 /// by the target, this can lead to cleaner code generation.
1457 bool preferPredicatedReductionSelect(unsigned Opcode, Type *Ty,
1458 ReductionFlags Flags) const;
1459
1460 /// \returns True if the target wants to expand the given reduction intrinsic
1461 /// into a shuffle sequence.
1462 bool shouldExpandReduction(const IntrinsicInst *II) const;
1463
1464 /// \returns the size cost of rematerializing a GlobalValue address relative
1465 /// to a stack reload.
1466 unsigned getGISelRematGlobalCost() const;
1467
1468 /// \returns the lower bound of a trip count to decide on vectorization
1469 /// while tail-folding.
1470 unsigned getMinTripCountTailFoldingThreshold() const;
1471
1472 /// \returns True if the target supports scalable vectors.
1473 bool supportsScalableVectors() const;
1474
1475 /// \return true when scalable vectorization is preferred.
1476 bool enableScalableVectorization() const;
1477
1478 /// \name Vector Predication Information
1479 /// @{
1480 /// Whether the target supports the %evl parameter of VP intrinsic efficiently
1481 /// in hardware, for the given opcode and type/alignment. (see LLVM Language
1482 /// Reference - "Vector Predication Intrinsics").
1483 /// Use of %evl is discouraged when that is not the case.
1484 bool hasActiveVectorLength(unsigned Opcode, Type *DataType,
1485 Align Alignment) const;
1486
1487 struct VPLegalization {
1488 enum VPTransform {
1489 // keep the predicating parameter
1490 Legal = 0,
1491 // where legal, discard the predicate parameter
1492 Discard = 1,
1493 // transform into something else that is also predicating
1494 Convert = 2
1495 };
1496
1497 // How to transform the EVL parameter.
1498 // Legal: keep the EVL parameter as it is.
1499 // Discard: Ignore the EVL parameter where it is safe to do so.
1500 // Convert: Fold the EVL into the mask parameter.
1501 VPTransform EVLParamStrategy;
1502
1503 // How to transform the operator.
1504 // Legal: The target supports this operator.
1505 // Convert: Convert this to a non-VP operation.
1506 // The 'Discard' strategy is invalid.
1507 VPTransform OpStrategy;
1508
1509 bool shouldDoNothing() const {
1510 return (EVLParamStrategy == Legal) && (OpStrategy == Legal);
1511 }
1512 VPLegalization(VPTransform EVLParamStrategy, VPTransform OpStrategy)
1513 : EVLParamStrategy(EVLParamStrategy), OpStrategy(OpStrategy) {}
1514 };
1515
1516 /// \returns How the target needs this vector-predicated operation to be
1517 /// transformed.
1518 VPLegalization getVPLegalizationStrategy(const VPIntrinsic &PI) const;
1519 /// @}
1520
1521 /// @}
1522
1523private:
1524 /// Estimate the latency of specified instruction.
1525 /// Returns 1 as the default value.
1526 InstructionCost getInstructionLatency(const Instruction *I) const;
1527
1528 /// Returns the expected throughput cost of the instruction.
1529 /// Returns -1 if the cost is unknown.
1530 InstructionCost getInstructionThroughput(const Instruction *I) const;
1531
1532 /// The abstract base class used to type erase specific TTI
1533 /// implementations.
1534 class Concept;
1535
1536 /// The template model for the base class which wraps a concrete
1537 /// implementation in a type erased interface.
1538 template <typename T> class Model;
1539
1540 std::unique_ptr<Concept> TTIImpl;
1541};
1542
1543class TargetTransformInfo::Concept {
1544public:
1545 virtual ~Concept() = 0;
1546 virtual const DataLayout &getDataLayout() const = 0;
1547 virtual InstructionCost getGEPCost(Type *PointeeType, const Value *Ptr,
1548 ArrayRef<const Value *> Operands,
1549 TTI::TargetCostKind CostKind) = 0;
1550 virtual unsigned getInliningThresholdMultiplier() = 0;
1551 virtual unsigned adjustInliningThreshold(const CallBase *CB) = 0;
1552 virtual int getInlinerVectorBonusPercent() = 0;
1553 virtual InstructionCost getMemcpyCost(const Instruction *I) = 0;
1554 virtual unsigned
1555 getEstimatedNumberOfCaseClusters(const SwitchInst &SI, unsigned &JTSize,
1556 ProfileSummaryInfo *PSI,
1557 BlockFrequencyInfo *BFI) = 0;
1558 virtual InstructionCost getUserCost(const User *U,
1559 ArrayRef<const Value *> Operands,
1560 TargetCostKind CostKind) = 0;
1561 virtual BranchProbability getPredictableBranchThreshold() = 0;
1562 virtual bool hasBranchDivergence() = 0;
1563 virtual bool useGPUDivergenceAnalysis() = 0;
1564 virtual bool isSourceOfDivergence(const Value *V) = 0;
1565 virtual bool isAlwaysUniform(const Value *V) = 0;
1566 virtual unsigned getFlatAddressSpace() = 0;
1567 virtual bool collectFlatAddressOperands(SmallVectorImpl<int> &OpIndexes,
1568 Intrinsic::ID IID) const = 0;
1569 virtual bool isNoopAddrSpaceCast(unsigned FromAS, unsigned ToAS) const = 0;
1570 virtual bool
1571 canHaveNonUndefGlobalInitializerInAddressSpace(unsigned AS) const = 0;
1572 virtual unsigned getAssumedAddrSpace(const Value *V) const = 0;
1573 virtual std::pair<const Value *, unsigned>
1574 getPredicatedAddrSpace(const Value *V) const = 0;
1575 virtual Value *rewriteIntrinsicWithAddressSpace(IntrinsicInst *II,
1576 Value *OldV,
1577 Value *NewV) const = 0;
1578 virtual bool isLoweredToCall(const Function *F) = 0;
1579 virtual void getUnrollingPreferences(Loop *L, ScalarEvolution &,
1580 UnrollingPreferences &UP,
1581 OptimizationRemarkEmitter *ORE) = 0;
1582 virtual void getPeelingPreferences(Loop *L, ScalarEvolution &SE,
1583 PeelingPreferences &PP) = 0;
1584 virtual bool isHardwareLoopProfitable(Loop *L, ScalarEvolution &SE,
1585 AssumptionCache &AC,
1586 TargetLibraryInfo *LibInfo,
1587 HardwareLoopInfo &HWLoopInfo) = 0;
1588 virtual bool
1589 preferPredicateOverEpilogue(Loop *L, LoopInfo *LI, ScalarEvolution &SE,
1590 AssumptionCache &AC, TargetLibraryInfo *TLI,
1591 DominatorTree *DT, LoopVectorizationLegality *LVL,
1592 InterleavedAccessInfo *IAI) = 0;
1593 virtual PredicationStyle emitGetActiveLaneMask() = 0;
1594 virtual Optional<Instruction *> instCombineIntrinsic(InstCombiner &IC,
1595 IntrinsicInst &II) = 0;
1596 virtual Optional<Value *>
1597 simplifyDemandedUseBitsIntrinsic(InstCombiner &IC, IntrinsicInst &II,
1598 APInt DemandedMask, KnownBits &Known,
1599 bool &KnownBitsComputed) = 0;
1600 virtual Optional<Value *> simplifyDemandedVectorEltsIntrinsic(
1601 InstCombiner &IC, IntrinsicInst &II, APInt DemandedElts, APInt &UndefElts,
1602 APInt &UndefElts2, APInt &UndefElts3,
1603 std::function<void(Instruction *, unsigned, APInt, APInt &)>
1604 SimplifyAndSetOp) = 0;
1605 virtual bool isLegalAddImmediate(int64_t Imm) = 0;
1606 virtual bool isLegalICmpImmediate(int64_t Imm) = 0;
1607 virtual bool isLegalAddressingMode(Type *Ty, GlobalValue *BaseGV,
1608 int64_t BaseOffset, bool HasBaseReg,
1609 int64_t Scale, unsigned AddrSpace,
1610 Instruction *I) = 0;
1611 virtual bool isLSRCostLess(const TargetTransformInfo::LSRCost &C1,
1612 const TargetTransformInfo::LSRCost &C2) = 0;
1613 virtual bool isNumRegsMajorCostOfLSR() = 0;
1614 virtual bool isProfitableLSRChainElement(Instruction *I) = 0;
1615 virtual bool canMacroFuseCmp() = 0;
1616 virtual bool canSaveCmp(Loop *L, BranchInst **BI, ScalarEvolution *SE,
1617 LoopInfo *LI, DominatorTree *DT, AssumptionCache *AC,
1618 TargetLibraryInfo *LibInfo) = 0;
1619 virtual AddressingModeKind
1620 getPreferredAddressingMode(const Loop *L, ScalarEvolution *SE) const = 0;
1621 virtual bool isLegalMaskedStore(Type *DataType, Align Alignment) = 0;
1622 virtual bool isLegalMaskedLoad(Type *DataType, Align Alignment) = 0;
1623 virtual bool isLegalNTStore(Type *DataType, Align Alignment) = 0;
1624 virtual bool isLegalNTLoad(Type *DataType, Align Alignment) = 0;
1625 virtual bool isLegalBroadcastLoad(Type *ElementTy,
1626 ElementCount NumElements) const = 0;
1627 virtual bool isLegalMaskedScatter(Type *DataType, Align Alignment) = 0;
1628 virtual bool isLegalMaskedGather(Type *DataType, Align Alignment) = 0;
1629 virtual bool forceScalarizeMaskedGather(VectorType *DataType,
1630 Align Alignment) = 0;
1631 virtual bool forceScalarizeMaskedScatter(VectorType *DataType,
1632 Align Alignment) = 0;
1633 virtual bool isLegalMaskedCompressStore(Type *DataType) = 0;
1634 virtual bool isLegalMaskedExpandLoad(Type *DataType) = 0;
1635 virtual bool isLegalAltInstr(VectorType *VecTy, unsigned Opcode0,
1636 unsigned Opcode1,
1637 const SmallBitVector &OpcodeMask) const = 0;
1638 virtual bool enableOrderedReductions() = 0;
1639 virtual bool hasDivRemOp(Type *DataType, bool IsSigned) = 0;
1640 virtual bool hasVolatileVariant(Instruction *I, unsigned AddrSpace) = 0;
1641 virtual bool prefersVectorizedAddressing() = 0;
1642 virtual InstructionCost getScalingFactorCost(Type *Ty, GlobalValue *BaseGV,
1643 int64_t BaseOffset,
1644 bool HasBaseReg, int64_t Scale,
1645 unsigned AddrSpace) = 0;
1646 virtual bool LSRWithInstrQueries() = 0;
1647 virtual bool isTruncateFree(Type *Ty1, Type *Ty2) = 0;
1648 virtual bool isProfitableToHoist(Instruction *I) = 0;
1649 virtual bool useAA() = 0;
1650 virtual bool isTypeLegal(Type *Ty) = 0;
1651 virtual unsigned getRegUsageForType(Type *Ty) = 0;
1652 virtual bool shouldBuildLookupTables() = 0;
1653 virtual bool shouldBuildLookupTablesForConstant(Constant *C) = 0;
1654 virtual bool shouldBuildRelLookupTables() = 0;
1655 virtual bool useColdCCForColdCall(Function &F) = 0;
1656 virtual InstructionCost getScalarizationOverhead(VectorType *Ty,
1657 const APInt &DemandedElts,
1658 bool Insert,
1659 bool Extract) = 0;
1660 virtual InstructionCost
1661 getOperandsScalarizationOverhead(ArrayRef<const Value *> Args,
1662 ArrayRef<Type *> Tys) = 0;
1663 virtual bool supportsEfficientVectorElementLoadStore() = 0;
1664 virtual bool supportsTailCalls() = 0;
1665 virtual bool enableAggressiveInterleaving(bool LoopHasReductions) = 0;
1666 virtual MemCmpExpansionOptions
1667 enableMemCmpExpansion(bool OptSize, bool IsZeroCmp) const = 0;
1668 virtual bool enableInterleavedAccessVectorization() = 0;
1669 virtual bool enableMaskedInterleavedAccessVectorization() = 0;
1670 virtual bool isFPVectorizationPotentiallyUnsafe() = 0;
1671 virtual bool allowsMisalignedMemoryAccesses(LLVMContext &Context,
1672 unsigned BitWidth,
1673 unsigned AddressSpace,
1674 Align Alignment,
1675 bool *Fast) = 0;
1676 virtual PopcntSupportKind getPopcntSupport(unsigned IntTyWidthInBit) = 0;
1677 virtual bool haveFastSqrt(Type *Ty) = 0;
1678 virtual bool isFCmpOrdCheaperThanFCmpZero(Type *Ty) = 0;
1679 virtual InstructionCost getFPOpCost(Type *Ty) = 0;
1680 virtual InstructionCost getIntImmCodeSizeCost(unsigned Opc, unsigned Idx,
1681 const APInt &Imm, Type *Ty) = 0;
1682 virtual InstructionCost getIntImmCost(const APInt &Imm, Type *Ty,
1683 TargetCostKind CostKind) = 0;
1684 virtual InstructionCost getIntImmCostInst(unsigned Opc, unsigned Idx,
1685 const APInt &Imm, Type *Ty,
1686 TargetCostKind CostKind,
1687 Instruction *Inst = nullptr) = 0;
1688 virtual InstructionCost getIntImmCostIntrin(Intrinsic::ID IID, unsigned Idx,
1689 const APInt &Imm, Type *Ty,
1690 TargetCostKind CostKind) = 0;
1691 virtual unsigned getNumberOfRegisters(unsigned ClassID) const = 0;
1692 virtual unsigned getRegisterClassForType(bool Vector,
1693 Type *Ty = nullptr) const = 0;
1694 virtual const char *getRegisterClassName(unsigned ClassID) const = 0;
1695 virtual TypeSize getRegisterBitWidth(RegisterKind K) const = 0;
1696 virtual unsigned getMinVectorRegisterBitWidth() const = 0;
1697 virtual Optional<unsigned> getMaxVScale() const = 0;
1698 virtual Optional<unsigned> getVScaleForTuning() const = 0;
1699 virtual bool
1700 shouldMaximizeVectorBandwidth(TargetTransformInfo::RegisterKind K) const = 0;
1701 virtual ElementCount getMinimumVF(unsigned ElemWidth,
1702 bool IsScalable) const = 0;
1703 virtual unsigned getMaximumVF(unsigned ElemWidth, unsigned Opcode) const = 0;
1704 virtual unsigned getStoreMinimumVF(unsigned VF, Type *ScalarMemTy,
1705 Type *ScalarValTy) const = 0;
1706 virtual bool shouldConsiderAddressTypePromotion(
1707 const Instruction &I, bool &AllowPromotionWithoutCommonHeader) = 0;
1708 virtual unsigned getCacheLineSize() const = 0;
1709 virtual Optional<unsigned> getCacheSize(CacheLevel Level) const = 0;
1710 virtual Optional<unsigned> getCacheAssociativity(CacheLevel Level) const = 0;
1711
1712 /// \return How much before a load we should place the prefetch
1713 /// instruction. This is currently measured in number of
1714 /// instructions.
1715 virtual unsigned getPrefetchDistance() const = 0;
1716
1717 /// \return Some HW prefetchers can handle accesses up to a certain
1718 /// constant stride. This is the minimum stride in bytes where it
1719 /// makes sense to start adding SW prefetches. The default is 1,
1720 /// i.e. prefetch with any stride. Sometimes prefetching is beneficial
1721 /// even below the HW prefetcher limit, and the arguments provided are
1722 /// meant to serve as a basis for deciding this for a particular loop.
1723 virtual unsigned getMinPrefetchStride(unsigned NumMemAccesses,
1724 unsigned NumStridedMemAccesses,
1725 unsigned NumPrefetches,
1726 bool HasCall) const = 0;
1727
1728 /// \return The maximum number of iterations to prefetch ahead. If
1729 /// the required number of iterations is more than this number, no
1730 /// prefetching is performed.
1731 virtual unsigned getMaxPrefetchIterationsAhead() const = 0;
1732
1733 /// \return True if prefetching should also be done for writes.
1734 virtual bool enableWritePrefetching() const = 0;
1735
1736 /// \return if target want to issue a prefetch in address space \p AS.
1737 virtual bool shouldPrefetchAddressSpace(unsigned AS) const = 0;
1738
1739 virtual unsigned getMaxInterleaveFactor(unsigned VF) = 0;
1740 virtual InstructionCost getArithmeticInstrCost(
1741 unsigned Opcode, Type *Ty, TTI::TargetCostKind CostKind,
1742 OperandValueKind Opd1Info, OperandValueKind Opd2Info,
1743 OperandValueProperties Opd1PropInfo, OperandValueProperties Opd2PropInfo,
1744 ArrayRef<const Value *> Args, const Instruction *CxtI = nullptr) = 0;
1745 virtual InstructionCost getShuffleCost(ShuffleKind Kind, VectorType *Tp,
1746 ArrayRef<int> Mask, int Index,
1747 VectorType *SubTp,
1748 ArrayRef<const Value *> Args) = 0;
1749 virtual InstructionCost getCastInstrCost(unsigned Opcode, Type *Dst,
1750 Type *Src, CastContextHint CCH,
1751 TTI::TargetCostKind CostKind,
1752 const Instruction *I) = 0;
1753 virtual InstructionCost getExtractWithExtendCost(unsigned Opcode, Type *Dst,
1754 VectorType *VecTy,
1755 unsigned Index) = 0;
1756 virtual InstructionCost getCFInstrCost(unsigned Opcode,
1757 TTI::TargetCostKind CostKind,
1758 const Instruction *I = nullptr) = 0;
1759 virtual InstructionCost getCmpSelInstrCost(unsigned Opcode, Type *ValTy,
1760 Type *CondTy,
1761 CmpInst::Predicate VecPred,
1762 TTI::TargetCostKind CostKind,
1763 const Instruction *I) = 0;
1764 virtual InstructionCost getVectorInstrCost(unsigned Opcode, Type *Val,
1765 unsigned Index) = 0;
1766 virtual InstructionCost getVectorInstrCost(const Instruction &I, Type *Val,
1767 unsigned Index) = 0;
1768
1769 virtual InstructionCost
1770 getReplicationShuffleCost(Type *EltTy, int ReplicationFactor, int VF,
1771 const APInt &DemandedDstElts,
1772 TTI::TargetCostKind CostKind) = 0;
1773
1774 virtual InstructionCost getMemoryOpCost(unsigned Opcode, Type *Src,
1775 Align Alignment,
1776 unsigned AddressSpace,
1777 TTI::TargetCostKind CostKind,
1778 const Instruction *I) = 0;
1779 virtual InstructionCost getVPMemoryOpCost(unsigned Opcode, Type *Src,
1780 Align Alignment,
1781 unsigned AddressSpace,
1782 TTI::TargetCostKind CostKind,
1783 const Instruction *I) = 0;
1784 virtual InstructionCost
1785 getMaskedMemoryOpCost(unsigned Opcode, Type *Src, Align Alignment,
1786 unsigned AddressSpace,
1787 TTI::TargetCostKind CostKind) = 0;
1788 virtual InstructionCost
1789 getGatherScatterOpCost(unsigned Opcode, Type *DataTy, const Value *Ptr,
1790 bool VariableMask, Align Alignment,
1791 TTI::TargetCostKind CostKind,
1792 const Instruction *I = nullptr) = 0;
1793
1794 virtual InstructionCost getInterleavedMemoryOpCost(
1795 unsigned Opcode, Type *VecTy, unsigned Factor, ArrayRef<unsigned> Indices,
1796 Align Alignment, unsigned AddressSpace, TTI::TargetCostKind CostKind,
1797 bool UseMaskForCond = false, bool UseMaskForGaps = false) = 0;
1798 virtual InstructionCost
1799 getArithmeticReductionCost(unsigned Opcode, VectorType *Ty,
1800 Optional<FastMathFlags> FMF,
1801 TTI::TargetCostKind CostKind) = 0;
1802 virtual InstructionCost
1803 getMinMaxReductionCost(VectorType *Ty, VectorType *CondTy, bool IsUnsigned,
1804 TTI::TargetCostKind CostKind) = 0;
1805 virtual InstructionCost getExtendedReductionCost(
1806 unsigned Opcode, bool IsUnsigned, Type *ResTy, VectorType *Ty,
1807 Optional<FastMathFlags> FMF,
1808 TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput) = 0;
1809 virtual InstructionCost getMulAccReductionCost(
1810 bool IsUnsigned, Type *ResTy, VectorType *Ty,
1811 TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput) = 0;
1812 virtual InstructionCost
1813 getIntrinsicInstrCost(const IntrinsicCostAttributes &ICA,
1814 TTI::TargetCostKind CostKind) = 0;
1815 virtual InstructionCost getCallInstrCost(Function *F, Type *RetTy,
1816 ArrayRef<Type *> Tys,
1817 TTI::TargetCostKind CostKind) = 0;
1818 virtual unsigned getNumberOfParts(Type *Tp) = 0;
1819 virtual InstructionCost
1820 getAddressComputationCost(Type *Ty, ScalarEvolution *SE, const SCEV *Ptr) = 0;
1821 virtual InstructionCost
1822 getCostOfKeepingLiveOverCall(ArrayRef<Type *> Tys) = 0;
1823 virtual bool getTgtMemIntrinsic(IntrinsicInst *Inst,
1824 MemIntrinsicInfo &Info) = 0;
1825 virtual unsigned getAtomicMemIntrinsicMaxElementSize() const = 0;
1826 virtual Value *getOrCreateResultFromMemIntrinsic(IntrinsicInst *Inst,
1827 Type *ExpectedType) = 0;
1828 virtual Type *
1829 getMemcpyLoopLoweringType(LLVMContext &Context, Value *Length,
1830 unsigned SrcAddrSpace, unsigned DestAddrSpace,
1831 unsigned SrcAlign, unsigned DestAlign,
1832 Optional<uint32_t> AtomicElementSize) const = 0;
1833
1834 virtual void getMemcpyLoopResidualLoweringType(
1835 SmallVectorImpl<Type *> &OpsOut, LLVMContext &Context,
1836 unsigned RemainingBytes, unsigned SrcAddrSpace, unsigned DestAddrSpace,
1837 unsigned SrcAlign, unsigned DestAlign,
1838 Optional<uint32_t> AtomicCpySize) const = 0;
1839 virtual bool areInlineCompatible(const Function *Caller,
1840 const Function *Callee) const = 0;
1841 virtual bool areTypesABICompatible(const Function *Caller,
1842 const Function *Callee,
1843 const ArrayRef<Type *> &Types) const = 0;
1844 virtual bool isIndexedLoadLegal(MemIndexedMode Mode, Type *Ty) const = 0;
1845 virtual bool isIndexedStoreLegal(MemIndexedMode Mode, Type *Ty) const = 0;
1846 virtual unsigned getLoadStoreVecRegBitWidth(unsigned AddrSpace) const = 0;
1847 virtual bool isLegalToVectorizeLoad(LoadInst *LI) const = 0;
1848 virtual bool isLegalToVectorizeStore(StoreInst *SI) const = 0;
1849 virtual bool isLegalToVectorizeLoadChain(unsigned ChainSizeInBytes,
1850 Align Alignment,
1851 unsigned AddrSpace) const = 0;
1852 virtual bool isLegalToVectorizeStoreChain(unsigned ChainSizeInBytes,
1853 Align Alignment,
1854 unsigned AddrSpace) const = 0;
1855 virtual bool isLegalToVectorizeReduction(const RecurrenceDescriptor &RdxDesc,
1856 ElementCount VF) const = 0;
1857 virtual bool isElementTypeLegalForScalableVector(Type *Ty) const = 0;
1858 virtual unsigned getLoadVectorFactor(unsigned VF, unsigned LoadSize,
1859 unsigned ChainSizeInBytes,
1860 VectorType *VecTy) const = 0;
1861 virtual unsigned getStoreVectorFactor(unsigned VF, unsigned StoreSize,
1862 unsigned ChainSizeInBytes,
1863 VectorType *VecTy) const = 0;
1864 virtual bool preferInLoopReduction(unsigned Opcode, Type *Ty,
1865 ReductionFlags) const = 0;
1866 virtual bool preferPredicatedReductionSelect(unsigned Opcode, Type *Ty,
1867 ReductionFlags) const = 0;
1868 virtual bool shouldExpandReduction(const IntrinsicInst *II) const = 0;
1869 virtual unsigned getGISelRematGlobalCost() const = 0;
1870 virtual unsigned getMinTripCountTailFoldingThreshold() const = 0;
1871 virtual bool enableScalableVectorization() const = 0;
1872 virtual bool supportsScalableVectors() const = 0;
1873 virtual bool hasActiveVectorLength(unsigned Opcode, Type *DataType,
1874 Align Alignment) const = 0;
1875 virtual InstructionCost getInstructionLatency(const Instruction *I) = 0;
1876 virtual VPLegalization
1877 getVPLegalizationStrategy(const VPIntrinsic &PI) const = 0;
1878};
1879
1880template <typename T>
1881class TargetTransformInfo::Model final : public TargetTransformInfo::Concept {
1882 T Impl;
1883
1884public:
1885 Model(T Impl) : Impl(std::move(Impl)) {}
1886 ~Model() override = default;
1887
1888 const DataLayout &getDataLayout() const override {
1889 return Impl.getDataLayout();
1890 }
1891
1892 InstructionCost
1893 getGEPCost(Type *PointeeType, const Value *Ptr,
1894 ArrayRef<const Value *> Operands,
1895 TargetTransformInfo::TargetCostKind CostKind) override {
1896 return Impl.getGEPCost(PointeeType, Ptr, Operands, CostKind);
1897 }
1898 unsigned getInliningThresholdMultiplier() override {
1899 return Impl.getInliningThresholdMultiplier();
1900 }
1901 unsigned adjustInliningThreshold(const CallBase *CB) override {
1902 return Impl.adjustInliningThreshold(CB);
1903 }
1904 int getInlinerVectorBonusPercent() override {
1905 return Impl.getInlinerVectorBonusPercent();
1906 }
1907 InstructionCost getMemcpyCost(const Instruction *I) override {
1908 return Impl.getMemcpyCost(I);
1909 }
1910 InstructionCost getUserCost(const User *U, ArrayRef<const Value *> Operands,
1911 TargetCostKind CostKind) override {
1912 return Impl.getUserCost(U, Operands, CostKind);
1913 }
1914 BranchProbability getPredictableBranchThreshold() override {
1915 return Impl.getPredictableBranchThreshold();
1916 }
1917 bool hasBranchDivergence() override { return Impl.hasBranchDivergence(); }
1918 bool useGPUDivergenceAnalysis() override {
1919 return Impl.useGPUDivergenceAnalysis();
1920 }
1921 bool isSourceOfDivergence(const Value *V) override {
1922 return Impl.isSourceOfDivergence(V);
1923 }
1924
1925 bool isAlwaysUniform(const Value *V) override {
1926 return Impl.isAlwaysUniform(V);
1927 }
1928
1929 unsigned getFlatAddressSpace() override { return Impl.getFlatAddressSpace(); }
1930
1931 bool collectFlatAddressOperands(SmallVectorImpl<int> &OpIndexes,
1932 Intrinsic::ID IID) const override {
1933 return Impl.collectFlatAddressOperands(OpIndexes, IID);
1934 }
1935
1936 bool isNoopAddrSpaceCast(unsigned FromAS, unsigned ToAS) const override {
1937 return Impl.isNoopAddrSpaceCast(FromAS, ToAS);
1938 }
1939
1940 bool
1941 canHaveNonUndefGlobalInitializerInAddressSpace(unsigned AS) const override {
1942 return Impl.canHaveNonUndefGlobalInitializerInAddressSpace(AS);
1943 }
1944
1945 unsigned getAssumedAddrSpace(const Value *V) const override {
1946 return Impl.getAssumedAddrSpace(V);
1947 }
1948
1949 std::pair<const Value *, unsigned>
1950 getPredicatedAddrSpace(const Value *V) const override {
1951 return Impl.getPredicatedAddrSpace(V);
1952 }
1953
1954 Value *rewriteIntrinsicWithAddressSpace(IntrinsicInst *II, Value *OldV,
1955 Value *NewV) const override {
1956 return Impl.rewriteIntrinsicWithAddressSpace(II, OldV, NewV);
1957 }
1958
1959 bool isLoweredToCall(const Function *F) override {
1960 return Impl.isLoweredToCall(F);
1961 }
1962 void getUnrollingPreferences(Loop *L, ScalarEvolution &SE,
1963 UnrollingPreferences &UP,
1964 OptimizationRemarkEmitter *ORE) override {
1965 return Impl.getUnrollingPreferences(L, SE, UP, ORE);
1966 }
1967 void getPeelingPreferences(Loop *L, ScalarEvolution &SE,
1968 PeelingPreferences &PP) override {
1969 return Impl.getPeelingPreferences(L, SE, PP);
1970 }
1971 bool isHardwareLoopProfitable(Loop *L, ScalarEvolution &SE,
1972 AssumptionCache &AC, TargetLibraryInfo *LibInfo,
1973 HardwareLoopInfo &HWLoopInfo) override {
1974 return Impl.isHardwareLoopProfitable(L, SE, AC, LibInfo, HWLoopInfo);
1975 }
1976 bool preferPredicateOverEpilogue(Loop *L, LoopInfo *LI, ScalarEvolution &SE,
1977 AssumptionCache &AC, TargetLibraryInfo *TLI,
1978 DominatorTree *DT,
1979 LoopVectorizationLegality *LVL,
1980 InterleavedAccessInfo *IAI) override {
1981 return Impl.preferPredicateOverEpilogue(L, LI, SE, AC, TLI, DT, LVL, IAI);
1982 }
1983 PredicationStyle emitGetActiveLaneMask() override {
1984 return Impl.emitGetActiveLaneMask();
1985 }
1986 Optional<Instruction *> instCombineIntrinsic(InstCombiner &IC,
1987 IntrinsicInst &II) override {
1988 return Impl.instCombineIntrinsic(IC, II);
1989 }
1990 Optional<Value *>
1991 simplifyDemandedUseBitsIntrinsic(InstCombiner &IC, IntrinsicInst &II,
1992 APInt DemandedMask, KnownBits &Known,
1993 bool &KnownBitsComputed) override {
1994 return Impl.simplifyDemandedUseBitsIntrinsic(IC, II, DemandedMask, Known,
1995 KnownBitsComputed);
1996 }
1997 Optional<Value *> simplifyDemandedVectorEltsIntrinsic(
1998 InstCombiner &IC, IntrinsicInst &II, APInt DemandedElts, APInt &UndefElts,
1999 APInt &UndefElts2, APInt &UndefElts3,
2000 std::function<void(Instruction *, unsigned, APInt, APInt &)>
2001 SimplifyAndSetOp) override {
2002 return Impl.simplifyDemandedVectorEltsIntrinsic(
2003 IC, II, DemandedElts, UndefElts, UndefElts2, UndefElts3,
2004 SimplifyAndSetOp);
2005 }
2006 bool isLegalAddImmediate(int64_t Imm) override {
2007 return Impl.isLegalAddImmediate(Imm);
2008 }
2009 bool isLegalICmpImmediate(int64_t Imm) override {
2010 return Impl.isLegalICmpImmediate(Imm);
2011 }
2012 bool isLegalAddressingMode(Type *Ty, GlobalValue *BaseGV, int64_t BaseOffset,
2013 bool HasBaseReg, int64_t Scale, unsigned AddrSpace,
2014 Instruction *I) override {
2015 return Impl.isLegalAddressingMode(Ty, BaseGV, BaseOffset, HasBaseReg, Scale,
2016 AddrSpace, I);
2017 }
2018 bool isLSRCostLess(const TargetTransformInfo::LSRCost &C1,
2019 const TargetTransformInfo::LSRCost &C2) override {
2020 return Impl.isLSRCostLess(C1, C2);
2021 }
2022 bool isNumRegsMajorCostOfLSR() override {
2023 return Impl.isNumRegsMajorCostOfLSR();
2024 }
2025 bool isProfitableLSRChainElement(Instruction *I) override {
2026 return Impl.isProfitableLSRChainElement(I);
2027 }
2028 bool canMacroFuseCmp() override { return Impl.canMacroFuseCmp(); }
2029 bool canSaveCmp(Loop *L, BranchInst **BI, ScalarEvolution *SE, LoopInfo *LI,
2030 DominatorTree *DT, AssumptionCache *AC,
2031 TargetLibraryInfo *LibInfo) override {
2032 return Impl.canSaveCmp(L, BI, SE, LI, DT, AC, LibInfo);
2033 }
2034 AddressingModeKind
2035 getPreferredAddressingMode(const Loop *L,
2036 ScalarEvolution *SE) const override {
2037 return Impl.getPreferredAddressingMode(L, SE);
2038 }
2039 bool isLegalMaskedStore(Type *DataType, Align Alignment) override {
2040 return Impl.isLegalMaskedStore(DataType, Alignment);
2041 }
2042 bool isLegalMaskedLoad(Type *DataType, Align Alignment) override {
2043 return Impl.isLegalMaskedLoad(DataType, Alignment);
2044 }
2045 bool isLegalNTStore(Type *DataType, Align Alignment) override {
2046 return Impl.isLegalNTStore(DataType, Alignment);
2047 }
2048 bool isLegalNTLoad(Type *DataType, Align Alignment) override {
2049 return Impl.isLegalNTLoad(DataType, Alignment);
2050 }
2051 bool isLegalBroadcastLoad(Type *ElementTy,
2052 ElementCount NumElements) const override {
2053 return Impl.isLegalBroadcastLoad(ElementTy, NumElements);
2054 }
2055 bool isLegalMaskedScatter(Type *DataType, Align Alignment) override {
2056 return Impl.isLegalMaskedScatter(DataType, Alignment);
2057 }
2058 bool isLegalMaskedGather(Type *DataType, Align Alignment) override {
2059 return Impl.isLegalMaskedGather(DataType, Alignment);
2060 }
2061 bool forceScalarizeMaskedGather(VectorType *DataType,
2062 Align Alignment) override {
2063 return Impl.forceScalarizeMaskedGather(DataType, Alignment);
2064 }
2065 bool forceScalarizeMaskedScatter(VectorType *DataType,
2066 Align Alignment) override {
2067 return Impl.forceScalarizeMaskedScatter(DataType, Alignment);
2068 }
2069 bool isLegalMaskedCompressStore(Type *DataType) override {
2070 return Impl.isLegalMaskedCompressStore(DataType);
2071 }
2072 bool isLegalMaskedExpandLoad(Type *DataType) override {
2073 return Impl.isLegalMaskedExpandLoad(DataType);
2074 }
2075 bool isLegalAltInstr(VectorType *VecTy, unsigned Opcode0, unsigned Opcode1,
2076 const SmallBitVector &OpcodeMask) const override {
2077 return Impl.isLegalAltInstr(VecTy, Opcode0, Opcode1, OpcodeMask);
2078 }
2079 bool enableOrderedReductions() override {
2080 return Impl.enableOrderedReductions();
2081 }
2082 bool hasDivRemOp(Type *DataType, bool IsSigned) override {
2083 return Impl.hasDivRemOp(DataType, IsSigned);
2084 }
2085 bool hasVolatileVariant(Instruction *I, unsigned AddrSpace) override {
2086 return Impl.hasVolatileVariant(I, AddrSpace);
2087 }
2088 bool prefersVectorizedAddressing() override {
2089 return Impl.prefersVectorizedAddressing();
2090 }
2091 InstructionCost getScalingFactorCost(Type *Ty, GlobalValue *BaseGV,
2092 int64_t BaseOffset, bool HasBaseReg,
2093 int64_t Scale,
2094 unsigned AddrSpace) override {
2095 return Impl.getScalingFactorCost(Ty, BaseGV, BaseOffset, HasBaseReg, Scale,
2096 AddrSpace);
2097 }
2098 bool LSRWithInstrQueries() override { return Impl.LSRWithInstrQueries(); }
2099 bool isTruncateFree(Type *Ty1, Type *Ty2) override {
2100 return Impl.isTruncateFree(Ty1, Ty2);
2101 }
2102 bool isProfitableToHoist(Instruction *I) override {
2103 return Impl.isProfitableToHoist(I);
2104 }
2105 bool useAA() override { return Impl.useAA(); }
2106 bool isTypeLegal(Type *Ty) override { return Impl.isTypeLegal(Ty); }
2107 unsigned getRegUsageForType(Type *Ty) override {
2108 return Impl.getRegUsageForType(Ty);
2109 }
2110 bool shouldBuildLookupTables() override {
2111 return Impl.shouldBuildLookupTables();
2112 }
2113 bool shouldBuildLookupTablesForConstant(Constant *C) override {
2114 return Impl.shouldBuildLookupTablesForConstant(C);
2115 }
2116 bool shouldBuildRelLookupTables() override {
2117 return Impl.shouldBuildRelLookupTables();
2118 }
2119 bool useColdCCForColdCall(Function &F) override {
2120 return Impl.useColdCCForColdCall(F);
2121 }
2122
2123 InstructionCost getScalarizationOverhead(VectorType *Ty,
2124 const APInt &DemandedElts,
2125 bool Insert, bool Extract) override {
2126 return Impl.getScalarizationOverhead(Ty, DemandedElts, Insert, Extract);
2127 }
2128 InstructionCost
2129 getOperandsScalarizationOverhead(ArrayRef<const Value *> Args,
2130 ArrayRef<Type *> Tys) override {
2131 return Impl.getOperandsScalarizationOverhead(Args, Tys);
2132 }
2133
2134 bool supportsEfficientVectorElementLoadStore() override {
2135 return Impl.supportsEfficientVectorElementLoadStore();
2136 }
2137
2138 bool supportsTailCalls() override { return Impl.supportsTailCalls(); }
2139
2140 bool enableAggressiveInterleaving(bool LoopHasReductions) override {
2141 return Impl.enableAggressiveInterleaving(LoopHasReductions);
2142 }
2143 MemCmpExpansionOptions enableMemCmpExpansion(bool OptSize,
2144 bool IsZeroCmp) const override {
2145 return Impl.enableMemCmpExpansion(OptSize, IsZeroCmp);
2146 }
2147 bool enableInterleavedAccessVectorization() override {
2148 return Impl.enableInterleavedAccessVectorization();
2149 }
2150 bool enableMaskedInterleavedAccessVectorization() override {
2151 return Impl.enableMaskedInterleavedAccessVectorization();
2152 }
2153 bool isFPVectorizationPotentiallyUnsafe() override {
2154 return Impl.isFPVectorizationPotentiallyUnsafe();
2155 }
2156 bool allowsMisalignedMemoryAccesses(LLVMContext &Context, unsigned BitWidth,
2157 unsigned AddressSpace, Align Alignment,
2158 bool *Fast) override {
2159 return Impl.allowsMisalignedMemoryAccesses(Context, BitWidth, AddressSpace,
2160 Alignment, Fast);
2161 }
2162 PopcntSupportKind getPopcntSupport(unsigned IntTyWidthInBit) override {
2163 return Impl.getPopcntSupport(IntTyWidthInBit);
2164 }
2165 bool haveFastSqrt(Type *Ty) override { return Impl.haveFastSqrt(Ty); }
2166
2167 bool isFCmpOrdCheaperThanFCmpZero(Type *Ty) override {
2168 return Impl.isFCmpOrdCheaperThanFCmpZero(Ty);
2169 }
2170
2171 InstructionCost getFPOpCost(Type *Ty) override {
2172 return Impl.getFPOpCost(Ty);
2173 }
2174
2175 InstructionCost getIntImmCodeSizeCost(unsigned Opc, unsigned Idx,
2176 const APInt &Imm, Type *Ty) override {
2177 return Impl.getIntImmCodeSizeCost(Opc, Idx, Imm, Ty);
2178 }
2179 InstructionCost getIntImmCost(const APInt &Imm, Type *Ty,
2180 TargetCostKind CostKind) override {
2181 return Impl.getIntImmCost(Imm, Ty, CostKind);
2182 }
2183 InstructionCost getIntImmCostInst(unsigned Opc, unsigned Idx,
2184 const APInt &Imm, Type *Ty,
2185 TargetCostKind CostKind,
2186 Instruction *Inst = nullptr) override {
2187 return Impl.getIntImmCostInst(Opc, Idx, Imm, Ty, CostKind, Inst);
2188 }
2189 InstructionCost getIntImmCostIntrin(Intrinsic::ID IID, unsigned Idx,
2190 const APInt &Imm, Type *Ty,
2191 TargetCostKind CostKind) override {
2192 return Impl.getIntImmCostIntrin(IID, Idx, Imm, Ty, CostKind);
2193 }
2194 unsigned getNumberOfRegisters(unsigned ClassID) const override {
2195 return Impl.getNumberOfRegisters(ClassID);
2196 }
2197 unsigned getRegisterClassForType(bool Vector,
2198 Type *Ty = nullptr) const override {
2199 return Impl.getRegisterClassForType(Vector, Ty);
2200 }
2201 const char *getRegisterClassName(unsigned ClassID) const override {
2202 return Impl.getRegisterClassName(ClassID);
2203 }
2204 TypeSize getRegisterBitWidth(RegisterKind K) const override {
2205 return Impl.getRegisterBitWidth(K);
2206 }
2207 unsigned getMinVectorRegisterBitWidth() const override {
2208 return Impl.getMinVectorRegisterBitWidth();
2209 }
2210 Optional<unsigned> getMaxVScale() const override {
2211 return Impl.getMaxVScale();
2212 }
2213 Optional<unsigned> getVScaleForTuning() const override {
2214 return Impl.getVScaleForTuning();
2215 }
2216 bool shouldMaximizeVectorBandwidth(
2217 TargetTransformInfo::RegisterKind K) const override {
2218 return Impl.shouldMaximizeVectorBandwidth(K);
2219 }
2220 ElementCount getMinimumVF(unsigned ElemWidth,
2221 bool IsScalable) const override {
2222 return Impl.getMinimumVF(ElemWidth, IsScalable);
2223 }
2224 unsigned getMaximumVF(unsigned ElemWidth, unsigned Opcode) const override {
2225 return Impl.getMaximumVF(ElemWidth, Opcode);
2226 }
2227 unsigned getStoreMinimumVF(unsigned VF, Type *ScalarMemTy,
2228 Type *ScalarValTy) const override {
2229 return Impl.getStoreMinimumVF(VF, ScalarMemTy, ScalarValTy);
2230 }
2231 bool shouldConsiderAddressTypePromotion(
2232 const Instruction &I, bool &AllowPromotionWithoutCommonHeader) override {
2233 return Impl.shouldConsiderAddressTypePromotion(
2234 I, AllowPromotionWithoutCommonHeader);
2235 }
2236 unsigned getCacheLineSize() const override { return Impl.getCacheLineSize(); }
2237 Optional<unsigned> getCacheSize(CacheLevel Level) const override {
2238 return Impl.getCacheSize(Level);
2239 }
2240 Optional<unsigned> getCacheAssociativity(CacheLevel Level) const override {
2241 return Impl.getCacheAssociativity(Level);
2242 }
2243
2244 /// Return the preferred prefetch distance in terms of instructions.
2245 ///
2246 unsigned getPrefetchDistance() const override {
2247 return Impl.getPrefetchDistance();
2248 }
2249
2250 /// Return the minimum stride necessary to trigger software
2251 /// prefetching.
2252 ///
2253 unsigned getMinPrefetchStride(unsigned NumMemAccesses,
2254 unsigned NumStridedMemAccesses,
2255 unsigned NumPrefetches,
2256 bool HasCall) const override {
2257 return Impl.getMinPrefetchStride(NumMemAccesses, NumStridedMemAccesses,
2258 NumPrefetches, HasCall);
2259 }
2260
2261 /// Return the maximum prefetch distance in terms of loop
2262 /// iterations.
2263 ///
2264 unsigned getMaxPrefetchIterationsAhead() const override {
2265 return Impl.getMaxPrefetchIterationsAhead();
2266 }
2267
2268 /// \return True if prefetching should also be done for writes.
2269 bool enableWritePrefetching() const override {
2270 return Impl.enableWritePrefetching();
2271 }
2272
2273 /// \return if target want to issue a prefetch in address space \p AS.
2274 bool shouldPrefetchAddressSpace(unsigned AS) const override {
2275 return Impl.shouldPrefetchAddressSpace(AS);
2276 }
2277
2278 unsigned getMaxInterleaveFactor(unsigned VF) override {
2279 return Impl.getMaxInterleaveFactor(VF);
2280 }
2281 unsigned getEstimatedNumberOfCaseClusters(const SwitchInst &SI,
2282 unsigned &JTSize,
2283 ProfileSummaryInfo *PSI,
2284 BlockFrequencyInfo *BFI) override {
2285 return Impl.getEstimatedNumberOfCaseClusters(SI, JTSize, PSI, BFI);
2286 }
2287 InstructionCost getArithmeticInstrCost(
2288 unsigned Opcode, Type *Ty, TTI::TargetCostKind CostKind,
2289 OperandValueKind Opd1Info, OperandValueKind Opd2Info,
2290 OperandValueProperties Opd1PropInfo, OperandValueProperties Opd2PropInfo,
2291 ArrayRef<const Value *> Args,
2292 const Instruction *CxtI = nullptr) override {
2293 return Impl.getArithmeticInstrCost(Opcode, Ty, CostKind, Opd1Info, Opd2Info,
2294 Opd1PropInfo, Opd2PropInfo, Args, CxtI);
2295 }
2296 InstructionCost getShuffleCost(ShuffleKind Kind, VectorType *Tp,
2297 ArrayRef<int> Mask, int Index,
2298 VectorType *SubTp,
2299 ArrayRef<const Value *> Args) override {
2300 return Impl.getShuffleCost(Kind, Tp, Mask, Index, SubTp, Args);
2301 }
2302 InstructionCost getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src,
2303 CastContextHint CCH,
2304 TTI::TargetCostKind CostKind,
2305 const Instruction *I) override {
2306 return Impl.getCastInstrCost(Opcode, Dst, Src, CCH, CostKind, I);
2307 }
2308 InstructionCost getExtractWithExtendCost(unsigned Opcode, Type *Dst,
2309 VectorType *VecTy,
2310 unsigned Index) override {
2311 return Impl.getExtractWithExtendCost(Opcode, Dst, VecTy, Index);
2312 }
2313 InstructionCost getCFInstrCost(unsigned Opcode, TTI::TargetCostKind CostKind,
2314 const Instruction *I = nullptr) override {
2315 return Impl.getCFInstrCost(Opcode, CostKind, I);
2316 }
2317 InstructionCost getCmpSelInstrCost(unsigned Opcode, Type *ValTy, Type *CondTy,
2318 CmpInst::Predicate VecPred,
2319 TTI::TargetCostKind CostKind,
2320 const Instruction *I) override {
2321 return Impl.getCmpSelInstrCost(Opcode, ValTy, CondTy, VecPred, CostKind, I);
2322 }
2323 InstructionCost getVectorInstrCost(unsigned Opcode, Type *Val,
2324 unsigned Index) override {
2325 return Impl.getVectorInstrCost(Opcode, Val, Index);
2326 }
2327 InstructionCost getVectorInstrCost(const Instruction &I, Type *Val,
2328 unsigned Index) override {
2329 return Impl.getVectorInstrCost(I, Val, Index);
2330 }
2331 InstructionCost
2332 getReplicationShuffleCost(Type *EltTy, int ReplicationFactor, int VF,
2333 const APInt &DemandedDstElts,
2334 TTI::TargetCostKind CostKind) override {
2335 return Impl.getReplicationShuffleCost(EltTy, ReplicationFactor, VF,
2336 DemandedDstElts, CostKind);
2337 }
2338 InstructionCost getMemoryOpCost(unsigned Opcode, Type *Src, Align Alignment,
2339 unsigned AddressSpace,
2340 TTI::TargetCostKind CostKind,
2341 const Instruction *I) override {
2342 return Impl.getMemoryOpCost(Opcode, Src, Alignment, AddressSpace,
2343 CostKind, I);
2344 }
2345 InstructionCost getVPMemoryOpCost(unsigned Opcode, Type *Src, Align Alignment,
2346 unsigned AddressSpace,
2347 TTI::TargetCostKind CostKind,
2348 const Instruction *I) override {
2349 return Impl.getVPMemoryOpCost(Opcode, Src, Alignment, AddressSpace,
2350 CostKind, I);
2351 }
2352 InstructionCost getMaskedMemoryOpCost(unsigned Opcode, Type *Src,
2353 Align Alignment, unsigned AddressSpace,
2354 TTI::TargetCostKind CostKind) override {
2355 return Impl.getMaskedMemoryOpCost(Opcode, Src, Alignment, AddressSpace,
2356 CostKind);
2357 }
2358 InstructionCost
2359 getGatherScatterOpCost(unsigned Opcode, Type *DataTy, const Value *Ptr,
2360 bool VariableMask, Align Alignment,
2361 TTI::TargetCostKind CostKind,
2362 const Instruction *I = nullptr) override {
2363 return Impl.getGatherScatterOpCost(Opcode, DataTy, Ptr, VariableMask,
2364 Alignment, CostKind, I);
2365 }
2366 InstructionCost getInterleavedMemoryOpCost(
2367 unsigned Opcode, Type *VecTy, unsigned Factor, ArrayRef<unsigned> Indices,
2368 Align Alignment, unsigned AddressSpace, TTI::TargetCostKind CostKind,
2369 bool UseMaskForCond, bool UseMaskForGaps) override {
2370 return Impl.getInterleavedMemoryOpCost(Opcode, VecTy, Factor, Indices,
2371 Alignment, AddressSpace, CostKind,
2372 UseMaskForCond, UseMaskForGaps);
2373 }
2374 InstructionCost
2375 getArithmeticReductionCost(unsigned Opcode, VectorType *Ty,
2376 Optional<FastMathFlags> FMF,
2377 TTI::TargetCostKind CostKind) override {
2378 return Impl.getArithmeticReductionCost(Opcode, Ty, FMF, CostKind);
2379 }
2380 InstructionCost
2381 getMinMaxReductionCost(VectorType *Ty, VectorType *CondTy, bool IsUnsigned,
2382 TTI::TargetCostKind CostKind) override {
2383 return Impl.getMinMaxReductionCost(Ty, CondTy, IsUnsigned, CostKind);
2384 }
2385 InstructionCost getExtendedReductionCost(
2386 unsigned Opcode, bool IsUnsigned, Type *ResTy, VectorType *Ty,
2387 Optional<FastMathFlags> FMF,
2388 TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput) override {
2389 return Impl.getExtendedReductionCost(Opcode, IsUnsigned, ResTy, Ty, FMF,
2390 CostKind);
2391 }
2392 InstructionCost getMulAccReductionCost(
2393 bool IsUnsigned, Type *ResTy, VectorType *Ty,
2394 TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput) override {
2395 return Impl.getMulAccReductionCost(IsUnsigned, ResTy, Ty, CostKind);
2396 }
2397 InstructionCost getIntrinsicInstrCost(const IntrinsicCostAttributes &ICA,
2398 TTI::TargetCostKind CostKind) override {
2399 return Impl.getIntrinsicInstrCost(ICA, CostKind);
2400 }
2401 InstructionCost getCallInstrCost(Function *F, Type *RetTy,
2402 ArrayRef<Type *> Tys,
2403 TTI::TargetCostKind CostKind) override {
2404 return Impl.getCallInstrCost(F, RetTy, Tys, CostKind);
2405 }
2406 unsigned getNumberOfParts(Type *Tp) override {
2407 return Impl.getNumberOfParts(Tp);
2408 }
2409 InstructionCost getAddressComputationCost(Type *Ty, ScalarEvolution *SE,
2410 const SCEV *Ptr) override {
2411 return Impl.getAddressComputationCost(Ty, SE, Ptr);
2412 }
2413 InstructionCost getCostOfKeepingLiveOverCall(ArrayRef<Type *> Tys) override {
2414 return Impl.getCostOfKeepingLiveOverCall(Tys);
2415 }
2416 bool getTgtMemIntrinsic(IntrinsicInst *Inst,
2417 MemIntrinsicInfo &Info) override {
2418 return Impl.getTgtMemIntrinsic(Inst, Info);
2419 }
2420 unsigned getAtomicMemIntrinsicMaxElementSize() const override {
2421 return Impl.getAtomicMemIntrinsicMaxElementSize();
2422 }
2423 Value *getOrCreateResultFromMemIntrinsic(IntrinsicInst *Inst,
2424 Type *ExpectedType) override {
2425 return Impl.getOrCreateResultFromMemIntrinsic(Inst, ExpectedType);
2426 }
2427 Type *getMemcpyLoopLoweringType(
2428 LLVMContext &Context, Value *Length, unsigned SrcAddrSpace,
2429 unsigned DestAddrSpace, unsigned SrcAlign, unsigned DestAlign,
2430 Optional<uint32_t> AtomicElementSize) const override {
2431 return Impl.getMemcpyLoopLoweringType(Context, Length, SrcAddrSpace,
2432 DestAddrSpace, SrcAlign, DestAlign,
2433 AtomicElementSize);
2434 }
2435 void getMemcpyLoopResidualLoweringType(
2436 SmallVectorImpl<Type *> &OpsOut, LLVMContext &Context,
2437 unsigned RemainingBytes, unsigned SrcAddrSpace, unsigned DestAddrSpace,
2438 unsigned SrcAlign, unsigned DestAlign,
2439 Optional<uint32_t> AtomicCpySize) const override {
2440 Impl.getMemcpyLoopResidualLoweringType(OpsOut, Context, RemainingBytes,
2441 SrcAddrSpace, DestAddrSpace,
2442 SrcAlign, DestAlign, AtomicCpySize);
2443 }
2444 bool areInlineCompatible(const Function *Caller,
2445 const Function *Callee) const override {
2446 return Impl.areInlineCompatible(Caller, Callee);
2447 }
2448 bool areTypesABICompatible(const Function *Caller, const Function *Callee,
2449 const ArrayRef<Type *> &Types) const override {
2450 return Impl.areTypesABICompatible(Caller, Callee, Types);
2451 }
2452 bool isIndexedLoadLegal(MemIndexedMode Mode, Type *Ty) const override {
2453 return Impl.isIndexedLoadLegal(Mode, Ty, getDataLayout());
2454 }
2455 bool isIndexedStoreLegal(MemIndexedMode Mode, Type *Ty) const override {
2456 return Impl.isIndexedStoreLegal(Mode, Ty, getDataLayout());
2457 }
2458 unsigned getLoadStoreVecRegBitWidth(unsigned AddrSpace) const override {
2459 return Impl.getLoadStoreVecRegBitWidth(AddrSpace);
2460 }
2461 bool isLegalToVectorizeLoad(LoadInst *LI) const override {
2462 return Impl.isLegalToVectorizeLoad(LI);
2463 }
2464 bool isLegalToVectorizeStore(StoreInst *SI) const override {
2465 return Impl.isLegalToVectorizeStore(SI);
2466 }
2467 bool isLegalToVectorizeLoadChain(unsigned ChainSizeInBytes, Align Alignment,
2468 unsigned AddrSpace) const override {
2469 return Impl.isLegalToVectorizeLoadChain(ChainSizeInBytes, Alignment,
2470 AddrSpace);
2471 }
2472 bool isLegalToVectorizeStoreChain(unsigned ChainSizeInBytes, Align Alignment,
2473 unsigned AddrSpace) const override {
2474 return Impl.isLegalToVectorizeStoreChain(ChainSizeInBytes, Alignment,
2475 AddrSpace);
2476 }
2477 bool isLegalToVectorizeReduction(const RecurrenceDescriptor &RdxDesc,
2478 ElementCount VF) const override {
2479 return Impl.isLegalToVectorizeReduction(RdxDesc, VF);
2480 }
2481 bool isElementTypeLegalForScalableVector(Type *Ty) const override {
2482 return Impl.isElementTypeLegalForScalableVector(Ty);
2483 }
2484 unsigned getLoadVectorFactor(unsigned VF, unsigned LoadSize,
2485 unsigned ChainSizeInBytes,
2486 VectorType *VecTy) const override {
2487 return Impl.getLoadVectorFactor(VF, LoadSize, ChainSizeInBytes, VecTy);
2488 }
2489 unsigned getStoreVectorFactor(unsigned VF, unsigned StoreSize,
2490 unsigned ChainSizeInBytes,
2491 VectorType *VecTy) const override {
2492 return Impl.getStoreVectorFactor(VF, StoreSize, ChainSizeInBytes, VecTy);
2493 }
2494 bool preferInLoopReduction(unsigned Opcode, Type *Ty,
2495 ReductionFlags Flags) const override {
2496 return Impl.preferInLoopReduction(Opcode, Ty, Flags);
2497 }
2498 bool preferPredicatedReductionSelect(unsigned Opcode, Type *Ty,
2499 ReductionFlags Flags) const override {
2500 return Impl.preferPredicatedReductionSelect(Opcode, Ty, Flags);
2501 }
2502 bool shouldExpandReduction(const IntrinsicInst *II) const override {
2503 return Impl.shouldExpandReduction(II);
2504 }
2505
2506 unsigned getGISelRematGlobalCost() const override {
2507 return Impl.getGISelRematGlobalCost();
2508 }
2509
2510 unsigned getMinTripCountTailFoldingThreshold() const override {
2511 return Impl.getMinTripCountTailFoldingThreshold();
2512 }
2513
2514 bool supportsScalableVectors() const override {
2515 return Impl.supportsScalableVectors();
2516 }
2517
2518 bool enableScalableVectorization() const override {
2519 return Impl.enableScalableVectorization();
2520 }
2521
2522 bool hasActiveVectorLength(unsigned Opcode, Type *DataType,
2523 Align Alignment) const override {
2524 return Impl.hasActiveVectorLength(Opcode, DataType, Alignment);
2525 }
2526
2527 InstructionCost getInstructionLatency(const Instruction *I) override {
2528 return Impl.getInstructionLatency(I);
2529 }
2530
2531 VPLegalization
2532 getVPLegalizationStrategy(const VPIntrinsic &PI) const override {
2533 return Impl.getVPLegalizationStrategy(PI);
2534 }
2535};
2536
2537template <typename T>
2538TargetTransformInfo::TargetTransformInfo(T Impl)
2539 : TTIImpl(new Model<T>(Impl)) {}
2540
2541/// Analysis pass providing the \c TargetTransformInfo.
2542///
2543/// The core idea of the TargetIRAnalysis is to expose an interface through
2544/// which LLVM targets can analyze and provide information about the middle
2545/// end's target-independent IR. This supports use cases such as target-aware
2546/// cost modeling of IR constructs.
2547///
2548/// This is a function analysis because much of the cost modeling for targets
2549/// is done in a subtarget specific way and LLVM supports compiling different
2550/// functions targeting different subtargets in order to support runtime
2551/// dispatch according to the observed subtarget.
2552class TargetIRAnalysis : public AnalysisInfoMixin<TargetIRAnalysis> {
2553public:
2554 typedef TargetTransformInfo Result;
2555
2556 /// Default construct a target IR analysis.
2557 ///
2558 /// This will use the module's datalayout to construct a baseline
2559 /// conservative TTI result.
2560 TargetIRAnalysis();
2561
2562 /// Construct an IR analysis pass around a target-provide callback.
2563 ///
2564 /// The callback will be called with a particular function for which the TTI
2565 /// is needed and must return a TTI object for that function.
2566 TargetIRAnalysis(std::function<Result(const Function &)> TTICallback);
2567
2568 // Value semantics. We spell out the constructors for MSVC.
2569 TargetIRAnalysis(const TargetIRAnalysis &Arg)
2570 : TTICallback(Arg.TTICallback) {}
2571 TargetIRAnalysis(TargetIRAnalysis &&Arg)
2572 : TTICallback(std::move(Arg.TTICallback)) {}
2573 TargetIRAnalysis &operator=(const TargetIRAnalysis &RHS) {
2574 TTICallback = RHS.TTICallback;
2575 return *this;
2576 }
2577 TargetIRAnalysis &operator=(TargetIRAnalysis &&RHS) {
2578 TTICallback = std::move(RHS.TTICallback);
2579 return *this;
2580 }
2581
2582 Result run(const Function &F, FunctionAnalysisManager &);
2583
2584private:
2585 friend AnalysisInfoMixin<TargetIRAnalysis>;
2586 static AnalysisKey Key;
2587
2588 /// The callback used to produce a result.
2589 ///
2590 /// We use a completely opaque callback so that targets can provide whatever
2591 /// mechanism they desire for constructing the TTI for a given function.
2592 ///
2593 /// FIXME: Should we really use std::function? It's relatively inefficient.
2594 /// It might be possible to arrange for even stateful callbacks to outlive
2595 /// the analysis and thus use a function_ref which would be lighter weight.
2596 /// This may also be less error prone as the callback is likely to reference
2597 /// the external TargetMachine, and that reference needs to never dangle.
2598 std::function<Result(const Function &)> TTICallback;
2599
2600 /// Helper function used as the callback in the default constructor.
2601 static Result getDefaultTTI(const Function &F);
2602};
2603
2604/// Wrapper pass for TargetTransformInfo.
2605///
2606/// This pass can be constructed from a TTI object which it stores internally
2607/// and is queried by passes.
2608class TargetTransformInfoWrapperPass : public ImmutablePass {
2609 TargetIRAnalysis TIRA;
2610 Optional<TargetTransformInfo> TTI;
2611
2612 virtual void anchor();
2613
2614public:
2615 static char ID;
2616
2617 /// We must provide a default constructor for the pass but it should
2618 /// never be used.
2619 ///
2620 /// Use the constructor below or call one of the creation routines.
2621 TargetTransformInfoWrapperPass();
2622
2623 explicit TargetTransformInfoWrapperPass(TargetIRAnalysis TIRA);
2624
2625 TargetTransformInfo &getTTI(const Function &F);
2626};
2627
2628/// Create an analysis pass wrapper around a TTI object.
2629///
2630/// This analysis pass just holds the TTI instance and makes it available to
2631/// clients.
2632ImmutablePass *createTargetTransformInfoWrapperPass(TargetIRAnalysis TIRA);
2633
2634} // namespace llvm
2635
2636#endif
2637

source code of llvm/include/llvm/Analysis/TargetTransformInfo.h