LLVM 22.0.0git
TargetTransformInfo.h
Go to the documentation of this file.
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/APInt.h"
25#include "llvm/ADT/ArrayRef.h"
28#include "llvm/IR/FMF.h"
29#include "llvm/IR/InstrTypes.h"
30#include "llvm/IR/PassManager.h"
31#include "llvm/Pass.h"
36#include <functional>
37#include <optional>
38#include <utility>
39
40namespace llvm {
41
42namespace Intrinsic {
43typedef unsigned ID;
44}
45
46class AllocaInst;
47class AssumptionCache;
49class DominatorTree;
50class BranchInst;
51class Function;
52class GlobalValue;
53class InstCombiner;
56class IntrinsicInst;
57class LoadInst;
58class Loop;
59class LoopInfo;
63class SCEV;
64class ScalarEvolution;
65class SmallBitVector;
66class StoreInst;
67class SwitchInst;
69class Type;
70class VPIntrinsic;
71struct KnownBits;
72
73/// Information about a load/store intrinsic defined by the target.
75 /// This is the pointer that the intrinsic is loading from or storing to.
76 /// If this is non-null, then analysis/optimization passes can assume that
77 /// this intrinsic is functionally equivalent to a load/store from this
78 /// pointer.
79 Value *PtrVal = nullptr;
80
81 // Ordering for atomic operations.
83
84 // Same Id is set by the target for corresponding load/store intrinsics.
85 unsigned short MatchingId = 0;
86
87 bool ReadMem = false;
88 bool WriteMem = false;
89 bool IsVolatile = false;
90
96};
97
98/// Attributes of a target dependent hardware loop.
102 Loop *L = nullptr;
105 const SCEV *ExitCount = nullptr;
107 Value *LoopDecrement = nullptr; // Decrement the loop counter by this
108 // value in every iteration.
109 bool IsNestingLegal = false; // Can a hardware loop be a parent to
110 // another hardware loop?
111 bool CounterInReg = false; // Should loop counter be updated in
112 // the loop via a phi?
113 bool PerformEntryTest = false; // Generate the intrinsic which also performs
114 // icmp ne zero on the loop counter value and
115 // produces an i1 to guard the loop entry.
117 DominatorTree &DT,
118 bool ForceNestedLoop = false,
119 bool ForceHardwareLoopPHI = false);
120 LLVM_ABI bool canAnalyze(LoopInfo &LI);
121};
122
124 const IntrinsicInst *II = nullptr;
125 Type *RetTy = nullptr;
126 Intrinsic::ID IID;
127 SmallVector<Type *, 4> ParamTys;
129 FastMathFlags FMF;
130 // If ScalarizationCost is UINT_MAX, the cost of scalarizing the
131 // arguments and the return value will be computed based on types.
132 InstructionCost ScalarizationCost = InstructionCost::getInvalid();
133 TargetLibraryInfo const *LibInfo = nullptr;
134
135public:
137 Intrinsic::ID Id, const CallBase &CI,
139 bool TypeBasedOnly = false, TargetLibraryInfo const *LibInfo = nullptr);
140
142 Intrinsic::ID Id, Type *RTy, ArrayRef<Type *> Tys,
143 FastMathFlags Flags = FastMathFlags(), const IntrinsicInst *I = nullptr,
145
148
152 const IntrinsicInst *I = nullptr,
154 TargetLibraryInfo const *LibInfo = nullptr);
155
156 Intrinsic::ID getID() const { return IID; }
157 const IntrinsicInst *getInst() const { return II; }
158 Type *getReturnType() const { return RetTy; }
159 FastMathFlags getFlags() const { return FMF; }
160 InstructionCost getScalarizationCost() const { return ScalarizationCost; }
161 const SmallVectorImpl<const Value *> &getArgs() const { return Arguments; }
162 const SmallVectorImpl<Type *> &getArgTypes() const { return ParamTys; }
163 const TargetLibraryInfo *getLibInfo() const { return LibInfo; }
164
165 bool isTypeBasedOnly() const {
166 return Arguments.empty();
167 }
168
169 bool skipScalarizationCost() const { return ScalarizationCost.isValid(); }
170};
171
173 /// Don't use tail folding
175 /// Use predicate only to mask operations on data in the loop.
176 /// When the VL is not known to be a power-of-2, this method requires a
177 /// runtime overflow check for the i + VL in the loop because it compares the
178 /// scalar induction variable against the tripcount rounded up by VL which may
179 /// overflow. When the VL is a power-of-2, both the increment and uprounded
180 /// tripcount will overflow to 0, which does not require a runtime check
181 /// since the loop is exited when the loop induction variable equals the
182 /// uprounded trip-count, which are both 0.
184 /// Same as Data, but avoids using the get.active.lane.mask intrinsic to
185 /// calculate the mask and instead implements this with a
186 /// splat/stepvector/cmp.
187 /// FIXME: Can this kind be removed now that SelectionDAGBuilder expands the
188 /// active.lane.mask intrinsic when it is not natively supported?
190 /// Use predicate to control both data and control flow.
191 /// This method always requires a runtime overflow check for the i + VL
192 /// increment inside the loop, because it uses the result direclty in the
193 /// active.lane.mask to calculate the mask for the next iteration. If the
194 /// increment overflows, the mask is no longer correct.
196 /// Use predicate to control both data and control flow, but modify
197 /// the trip count so that a runtime overflow check can be avoided
198 /// and such that the scalar epilogue loop can always be removed.
200 /// Use predicated EVL instructions for tail-folding.
201 /// Indicates that VP intrinsics should be used.
203};
204
213
214class TargetTransformInfo;
217
218/// This pass provides access to the codegen interfaces that are needed
219/// for IR-level transformations.
221public:
223
224 /// Get the kind of extension that an instruction represents.
227
228 /// Construct a TTI object using a type implementing the \c Concept
229 /// API below.
230 ///
231 /// This is used by targets to construct a TTI wrapping their target-specific
232 /// implementation that encodes appropriate costs for their target.
234 std::unique_ptr<const TargetTransformInfoImplBase> Impl);
235
236 /// Construct a baseline TTI object using a minimal implementation of
237 /// the \c Concept API below.
238 ///
239 /// The TTI implementation will reflect the information in the DataLayout
240 /// provided if non-null.
241 LLVM_ABI explicit TargetTransformInfo(const DataLayout &DL);
242
243 // Provide move semantics.
246
247 // We need to define the destructor out-of-line to define our sub-classes
248 // out-of-line.
250
251 /// Handle the invalidation of this information.
252 ///
253 /// When used as a result of \c TargetIRAnalysis this method will be called
254 /// when the function this was computed for changes. When it returns false,
255 /// the information is preserved across those changes.
257 FunctionAnalysisManager::Invalidator &) {
258 // FIXME: We should probably in some way ensure that the subtarget
259 // information for a function hasn't changed.
260 return false;
261 }
262
263 /// \name Generic Target Information
264 /// @{
265
266 /// The kind of cost model.
267 ///
268 /// There are several different cost models that can be customized by the
269 /// target. The normalization of each cost model may be target specific.
270 /// e.g. TCK_SizeAndLatency should be comparable to target thresholds such as
271 /// those derived from MCSchedModel::LoopMicroOpBufferSize etc.
273 TCK_RecipThroughput, ///< Reciprocal throughput.
274 TCK_Latency, ///< The latency of instruction.
275 TCK_CodeSize, ///< Instruction code size.
276 TCK_SizeAndLatency ///< The weighted sum of size and latency.
277 };
278
279 /// Underlying constants for 'cost' values in this interface.
280 ///
281 /// Many APIs in this interface return a cost. This enum defines the
282 /// fundamental values that should be used to interpret (and produce) those
283 /// costs. The costs are returned as an int rather than a member of this
284 /// enumeration because it is expected that the cost of one IR instruction
285 /// may have a multiplicative factor to it or otherwise won't fit directly
286 /// into the enum. Moreover, it is common to sum or average costs which works
287 /// better as simple integral values. Thus this enum only provides constants.
288 /// Also note that the returned costs are signed integers to make it natural
289 /// to add, subtract, and test with zero (a common boundary condition). It is
290 /// not expected that 2^32 is a realistic cost to be modeling at any point.
291 ///
292 /// Note that these costs should usually reflect the intersection of code-size
293 /// cost and execution cost. A free instruction is typically one that folds
294 /// into another instruction. For example, reg-to-reg moves can often be
295 /// skipped by renaming the registers in the CPU, but they still are encoded
296 /// and thus wouldn't be considered 'free' here.
298 TCC_Free = 0, ///< Expected to fold away in lowering.
299 TCC_Basic = 1, ///< The cost of a typical 'add' instruction.
300 TCC_Expensive = 4 ///< The cost of a 'div' instruction on x86.
301 };
302
303 /// Estimate the cost of a GEP operation when lowered.
304 ///
305 /// \p PointeeType is the source element type of the GEP.
306 /// \p Ptr is the base pointer operand.
307 /// \p Operands is the list of indices following the base pointer.
308 ///
309 /// \p AccessType is a hint as to what type of memory might be accessed by
310 /// users of the GEP. getGEPCost will use it to determine if the GEP can be
311 /// folded into the addressing mode of a load/store. If AccessType is null,
312 /// then the resulting target type based off of PointeeType will be used as an
313 /// approximation.
315 getGEPCost(Type *PointeeType, const Value *Ptr,
316 ArrayRef<const Value *> Operands, Type *AccessType = nullptr,
317 TargetCostKind CostKind = TCK_SizeAndLatency) const;
318
319 /// Describe known properties for a set of pointers.
321 /// All the GEPs in a set have same base address.
322 unsigned IsSameBaseAddress : 1;
323 /// These properties only valid if SameBaseAddress is set.
324 /// True if all pointers are separated by a unit stride.
325 unsigned IsUnitStride : 1;
326 /// True if distance between any two neigbouring pointers is a known value.
327 unsigned IsKnownStride : 1;
328 unsigned Reserved : 29;
329
330 bool isSameBase() const { return IsSameBaseAddress; }
331 bool isUnitStride() const { return IsSameBaseAddress && IsUnitStride; }
333
335 return {/*IsSameBaseAddress=*/1, /*IsUnitStride=*/1,
336 /*IsKnownStride=*/1, 0};
337 }
339 return {/*IsSameBaseAddress=*/1, /*IsUnitStride=*/0,
340 /*IsKnownStride=*/1, 0};
341 }
343 return {/*IsSameBaseAddress=*/1, /*IsUnitStride=*/0,
344 /*IsKnownStride=*/0, 0};
345 }
346 };
347 static_assert(sizeof(PointersChainInfo) == 4, "Was size increase justified?");
348
349 /// Estimate the cost of a chain of pointers (typically pointer operands of a
350 /// chain of loads or stores within same block) operations set when lowered.
351 /// \p AccessTy is the type of the loads/stores that will ultimately use the
352 /// \p Ptrs.
355 const PointersChainInfo &Info, Type *AccessTy,
356 TargetCostKind CostKind = TTI::TCK_RecipThroughput) const;
357
358 /// \returns A value by which our inlining threshold should be multiplied.
359 /// This is primarily used to bump up the inlining threshold wholesale on
360 /// targets where calls are unusually expensive.
361 ///
362 /// TODO: This is a rather blunt instrument. Perhaps altering the costs of
363 /// individual classes of instructions would be better.
365
368
369 /// \returns The bonus of inlining the last call to a static function.
371
372 /// \returns A value to be added to the inlining threshold.
373 LLVM_ABI unsigned adjustInliningThreshold(const CallBase *CB) const;
374
375 /// \returns The cost of having an Alloca in the caller if not inlined, to be
376 /// added to the threshold
377 LLVM_ABI unsigned getCallerAllocaCost(const CallBase *CB,
378 const AllocaInst *AI) const;
379
380 /// \returns Vector bonus in percent.
381 ///
382 /// Vector bonuses: We want to more aggressively inline vector-dense kernels
383 /// and apply this bonus based on the percentage of vector instructions. A
384 /// bonus is applied if the vector instructions exceed 50% and half that
385 /// amount is applied if it exceeds 10%. Note that these bonuses are some what
386 /// arbitrary and evolved over time by accident as much as because they are
387 /// principled bonuses.
388 /// FIXME: It would be nice to base the bonus values on something more
389 /// scientific. A target may has no bonus on vector instructions.
391
392 /// \return the expected cost of a memcpy, which could e.g. depend on the
393 /// source/destination type and alignment and the number of bytes copied.
395
396 /// Returns the maximum memset / memcpy size in bytes that still makes it
397 /// profitable to inline the call.
399
400 /// \return The estimated number of case clusters when lowering \p 'SI'.
401 /// \p JTSize Set a jump table size only when \p SI is suitable for a jump
402 /// table.
403 LLVM_ABI unsigned
404 getEstimatedNumberOfCaseClusters(const SwitchInst &SI, unsigned &JTSize,
406 BlockFrequencyInfo *BFI) const;
407
408 /// Estimate the cost of a given IR user when lowered.
409 ///
410 /// This can estimate the cost of either a ConstantExpr or Instruction when
411 /// lowered.
412 ///
413 /// \p Operands is a list of operands which can be a result of transformations
414 /// of the current operands. The number of the operands on the list must equal
415 /// to the number of the current operands the IR user has. Their order on the
416 /// list must be the same as the order of the current operands the IR user
417 /// has.
418 ///
419 /// The returned cost is defined in terms of \c TargetCostConstants, see its
420 /// comments for a detailed explanation of the cost values.
423 TargetCostKind CostKind) const;
424
425 /// This is a helper function which calls the three-argument
426 /// getInstructionCost with \p Operands which are the current operands U has.
432
433 /// If a branch or a select condition is skewed in one direction by more than
434 /// this factor, it is very likely to be predicted correctly.
436
437 /// Returns estimated penalty of a branch misprediction in latency. Indicates
438 /// how aggressive the target wants for eliminating unpredictable branches. A
439 /// zero return value means extra optimization applied to them should be
440 /// minimal.
442
443 /// Return true if branch divergence exists.
444 ///
445 /// Branch divergence has a significantly negative impact on GPU performance
446 /// when threads in the same wavefront take different paths due to conditional
447 /// branches.
448 ///
449 /// If \p F is passed, provides a context function. If \p F is known to only
450 /// execute in a single threaded environment, the target may choose to skip
451 /// uniformity analysis and assume all values are uniform.
452 LLVM_ABI bool hasBranchDivergence(const Function *F = nullptr) const;
453
454 /// Returns whether V is a source of divergence.
455 ///
456 /// This function provides the target-dependent information for
457 /// the target-independent UniformityAnalysis.
458 LLVM_ABI bool isSourceOfDivergence(const Value *V) const;
459
460 // Returns true for the target specific
461 // set of operations which produce uniform result
462 // even taking non-uniform arguments
463 LLVM_ABI bool isAlwaysUniform(const Value *V) const;
464
465 /// Query the target whether the specified address space cast from FromAS to
466 /// ToAS is valid.
467 LLVM_ABI bool isValidAddrSpaceCast(unsigned FromAS, unsigned ToAS) const;
468
469 /// Return false if a \p AS0 address cannot possibly alias a \p AS1 address.
470 LLVM_ABI bool addrspacesMayAlias(unsigned AS0, unsigned AS1) const;
471
472 /// Returns the address space ID for a target's 'flat' address space. Note
473 /// this is not necessarily the same as addrspace(0), which LLVM sometimes
474 /// refers to as the generic address space. The flat address space is a
475 /// generic address space that can be used access multiple segments of memory
476 /// with different address spaces. Access of a memory location through a
477 /// pointer with this address space is expected to be legal but slower
478 /// compared to the same memory location accessed through a pointer with a
479 /// different address space.
480 //
481 /// This is for targets with different pointer representations which can
482 /// be converted with the addrspacecast instruction. If a pointer is converted
483 /// to this address space, optimizations should attempt to replace the access
484 /// with the source address space.
485 ///
486 /// \returns ~0u if the target does not have such a flat address space to
487 /// optimize away.
488 LLVM_ABI unsigned getFlatAddressSpace() const;
489
490 /// Return any intrinsic address operand indexes which may be rewritten if
491 /// they use a flat address space pointer.
492 ///
493 /// \returns true if the intrinsic was handled.
495 Intrinsic::ID IID) const;
496
497 LLVM_ABI bool isNoopAddrSpaceCast(unsigned FromAS, unsigned ToAS) const;
498
499 /// Return true if globals in this address space can have initializers other
500 /// than `undef`.
501 LLVM_ABI bool
503
504 LLVM_ABI unsigned getAssumedAddrSpace(const Value *V) const;
505
506 LLVM_ABI bool isSingleThreaded() const;
507
508 LLVM_ABI std::pair<const Value *, unsigned>
509 getPredicatedAddrSpace(const Value *V) const;
510
511 /// Rewrite intrinsic call \p II such that \p OldV will be replaced with \p
512 /// NewV, which has a different address space. This should happen for every
513 /// operand index that collectFlatAddressOperands returned for the intrinsic.
514 /// \returns nullptr if the intrinsic was not handled. Otherwise, returns the
515 /// new value (which may be the original \p II with modified operands).
517 Value *OldV,
518 Value *NewV) const;
519
520 /// Test whether calls to a function lower to actual program function
521 /// calls.
522 ///
523 /// The idea is to test whether the program is likely to require a 'call'
524 /// instruction or equivalent in order to call the given function.
525 ///
526 /// FIXME: It's not clear that this is a good or useful query API. Client's
527 /// should probably move to simpler cost metrics using the above.
528 /// Alternatively, we could split the cost interface into distinct code-size
529 /// and execution-speed costs. This would allow modelling the core of this
530 /// query more accurately as a call is a single small instruction, but
531 /// incurs significant execution cost.
532 LLVM_ABI bool isLoweredToCall(const Function *F) const;
533
534 struct LSRCost {
535 /// TODO: Some of these could be merged. Also, a lexical ordering
536 /// isn't always optimal.
537 unsigned Insns;
538 unsigned NumRegs;
539 unsigned AddRecCost;
540 unsigned NumIVMuls;
541 unsigned NumBaseAdds;
542 unsigned ImmCost;
543 unsigned SetupCost;
544 unsigned ScaleCost;
545 };
546
547 /// Parameters that control the generic loop unrolling transformation.
549 /// The cost threshold for the unrolled loop. Should be relative to the
550 /// getInstructionCost values returned by this API, and the expectation is
551 /// that the unrolled loop's instructions when run through that interface
552 /// should not exceed this cost. However, this is only an estimate. Also,
553 /// specific loops may be unrolled even with a cost above this threshold if
554 /// deemed profitable. Set this to UINT_MAX to disable the loop body cost
555 /// restriction.
556 unsigned Threshold;
557 /// If complete unrolling will reduce the cost of the loop, we will boost
558 /// the Threshold by a certain percent to allow more aggressive complete
559 /// unrolling. This value provides the maximum boost percentage that we
560 /// can apply to Threshold (The value should be no less than 100).
561 /// BoostedThreshold = Threshold * min(RolledCost / UnrolledCost,
562 /// MaxPercentThresholdBoost / 100)
563 /// E.g. if complete unrolling reduces the loop execution time by 50%
564 /// then we boost the threshold by the factor of 2x. If unrolling is not
565 /// expected to reduce the running time, then we do not increase the
566 /// threshold.
568 /// The cost threshold for the unrolled loop when optimizing for size (set
569 /// to UINT_MAX to disable).
571 /// The cost threshold for the unrolled loop, like Threshold, but used
572 /// for partial/runtime unrolling (set to UINT_MAX to disable).
574 /// The cost threshold for the unrolled loop when optimizing for size, like
575 /// OptSizeThreshold, but used for partial/runtime unrolling (set to
576 /// UINT_MAX to disable).
578 /// A forced unrolling factor (the number of concatenated bodies of the
579 /// original loop in the unrolled loop body). When set to 0, the unrolling
580 /// transformation will select an unrolling factor based on the current cost
581 /// threshold and other factors.
582 unsigned Count;
583 /// Default unroll count for loops with run-time trip count.
585 // Set the maximum unrolling factor. The unrolling factor may be selected
586 // using the appropriate cost threshold, but may not exceed this number
587 // (set to UINT_MAX to disable). This does not apply in cases where the
588 // loop is being fully unrolled.
589 unsigned MaxCount;
590 /// Set the maximum upper bound of trip count. Allowing the MaxUpperBound
591 /// to be overrided by a target gives more flexiblity on certain cases.
592 /// By default, MaxUpperBound uses UnrollMaxUpperBound which value is 8.
594 /// Set the maximum unrolling factor for full unrolling. Like MaxCount, but
595 /// applies even if full unrolling is selected. This allows a target to fall
596 /// back to Partial unrolling if full unrolling is above FullUnrollMaxCount.
598 // Represents number of instructions optimized when "back edge"
599 // becomes "fall through" in unrolled loop.
600 // For now we count a conditional branch on a backedge and a comparison
601 // feeding it.
602 unsigned BEInsns;
603 /// Allow partial unrolling (unrolling of loops to expand the size of the
604 /// loop body, not only to eliminate small constant-trip-count loops).
606 /// Allow runtime unrolling (unrolling of loops to expand the size of the
607 /// loop body even when the number of loop iterations is not known at
608 /// compile time).
610 /// Allow generation of a loop remainder (extra iterations after unroll).
612 /// Allow emitting expensive instructions (such as divisions) when computing
613 /// the trip count of a loop for runtime unrolling.
615 /// Apply loop unroll on any kind of loop
616 /// (mainly to loops that fail runtime unrolling).
617 bool Force;
618 /// Allow using trip count upper bound to unroll loops.
620 /// Allow unrolling of all the iterations of the runtime loop remainder.
622 /// Allow unroll and jam. Used to enable unroll and jam for the target.
624 /// Threshold for unroll and jam, for inner loop size. The 'Threshold'
625 /// value above is used during unroll and jam for the outer loop size.
626 /// This value is used in the same manner to limit the size of the inner
627 /// loop.
629 /// Don't allow loop unrolling to simulate more than this number of
630 /// iterations when checking full unroll profitability
632 /// Don't disable runtime unroll for the loops which were vectorized.
634 /// Don't allow runtime unrolling if expanding the trip count takes more
635 /// than SCEVExpansionBudget.
637 /// Allow runtime unrolling multi-exit loops. Should only be set if the
638 /// target determined that multi-exit unrolling is profitable for the loop.
639 /// Fall back to the generic logic to determine whether multi-exit unrolling
640 /// is profitable if set to false.
642 /// Allow unrolling to add parallel reduction phis.
644 };
645
646 /// Get target-customized preferences for the generic loop unrolling
647 /// transformation. The caller will initialize UP with the current
648 /// target-independent defaults.
651 OptimizationRemarkEmitter *ORE) const;
652
653 /// Query the target whether it would be profitable to convert the given loop
654 /// into a hardware loop.
656 AssumptionCache &AC,
657 TargetLibraryInfo *LibInfo,
658 HardwareLoopInfo &HWLoopInfo) const;
659
660 // Query the target for which minimum vectorization factor epilogue
661 // vectorization should be considered.
663
664 /// Query the target whether it would be prefered to create a predicated
665 /// vector loop, which can avoid the need to emit a scalar epilogue loop.
667
668 /// Query the target what the preferred style of tail folding is.
669 /// \param IVUpdateMayOverflow Tells whether it is known if the IV update
670 /// may (or will never) overflow for the suggested VF/UF in the given loop.
671 /// Targets can use this information to select a more optimal tail folding
672 /// style. The value conservatively defaults to true, such that no assumptions
673 /// are made on overflow.
675 getPreferredTailFoldingStyle(bool IVUpdateMayOverflow = true) const;
676
677 // Parameters that control the loop peeling transformation
679 /// A forced peeling factor (the number of bodied of the original loop
680 /// that should be peeled off before the loop body). When set to 0, the
681 /// a peeling factor based on profile information and other factors.
682 unsigned PeelCount;
683 /// Allow peeling off loop iterations.
685 /// Allow peeling off loop iterations for loop nests.
687 /// Allow peeling basing on profile. Uses to enable peeling off all
688 /// iterations basing on provided profile.
689 /// If the value is true the peeling cost model can decide to peel only
690 /// some iterations and in this case it will set this to false.
692
693 /// Peel off the last PeelCount loop iterations.
695 };
696
697 /// Get target-customized preferences for the generic loop peeling
698 /// transformation. The caller will initialize \p PP with the current
699 /// target-independent defaults with information from \p L and \p SE.
701 PeelingPreferences &PP) const;
702
703 /// Targets can implement their own combinations for target-specific
704 /// intrinsics. This function will be called from the InstCombine pass every
705 /// time a target-specific intrinsic is encountered.
706 ///
707 /// \returns std::nullopt to not do anything target specific or a value that
708 /// will be returned from the InstCombiner. It is possible to return null and
709 /// stop further processing of the intrinsic by returning nullptr.
710 LLVM_ABI std::optional<Instruction *>
712 /// Can be used to implement target-specific instruction combining.
713 /// \see instCombineIntrinsic
714 LLVM_ABI std::optional<Value *>
716 APInt DemandedMask, KnownBits &Known,
717 bool &KnownBitsComputed) const;
718 /// Can be used to implement target-specific instruction combining.
719 /// \see instCombineIntrinsic
720 LLVM_ABI std::optional<Value *> simplifyDemandedVectorEltsIntrinsic(
721 InstCombiner &IC, IntrinsicInst &II, APInt DemandedElts, APInt &UndefElts,
722 APInt &UndefElts2, APInt &UndefElts3,
723 std::function<void(Instruction *, unsigned, APInt, APInt &)>
724 SimplifyAndSetOp) const;
725 /// @}
726
727 /// \name Scalar Target Information
728 /// @{
729
730 /// Flags indicating the kind of support for population count.
731 ///
732 /// Compared to the SW implementation, HW support is supposed to
733 /// significantly boost the performance when the population is dense, and it
734 /// may or may not degrade performance if the population is sparse. A HW
735 /// support is considered as "Fast" if it can outperform, or is on a par
736 /// with, SW implementation when the population is sparse; otherwise, it is
737 /// considered as "Slow".
739
740 /// Return true if the specified immediate is legal add immediate, that
741 /// is the target has add instructions which can add a register with the
742 /// immediate without having to materialize the immediate into a register.
743 LLVM_ABI bool isLegalAddImmediate(int64_t Imm) const;
744
745 /// Return true if adding the specified scalable immediate is legal, that is
746 /// the target has add instructions which can add a register with the
747 /// immediate (multiplied by vscale) without having to materialize the
748 /// immediate into a register.
749 LLVM_ABI bool isLegalAddScalableImmediate(int64_t Imm) const;
750
751 /// Return true if the specified immediate is legal icmp immediate,
752 /// that is the target has icmp instructions which can compare a register
753 /// against the immediate without having to materialize the immediate into a
754 /// register.
755 LLVM_ABI bool isLegalICmpImmediate(int64_t Imm) const;
756
757 /// Return true if the addressing mode represented by AM is legal for
758 /// this target, for a load/store of the specified type.
759 /// The type may be VoidTy, in which case only return true if the addressing
760 /// mode is legal for a load/store of any legal type.
761 /// If target returns true in LSRWithInstrQueries(), I may be valid.
762 /// \param ScalableOffset represents a quantity of bytes multiplied by vscale,
763 /// an invariant value known only at runtime. Most targets should not accept
764 /// a scalable offset.
765 ///
766 /// TODO: Handle pre/postinc as well.
768 int64_t BaseOffset, bool HasBaseReg,
769 int64_t Scale, unsigned AddrSpace = 0,
770 Instruction *I = nullptr,
771 int64_t ScalableOffset = 0) const;
772
773 /// Return true if LSR cost of C1 is lower than C2.
775 const TargetTransformInfo::LSRCost &C2) const;
776
777 /// Return true if LSR major cost is number of registers. Targets which
778 /// implement their own isLSRCostLess and unset number of registers as major
779 /// cost should return false, otherwise return true.
781
782 /// Return true if LSR should drop a found solution if it's calculated to be
783 /// less profitable than the baseline.
785
786 /// \returns true if LSR should not optimize a chain that includes \p I.
788
789 /// Return true if the target can fuse a compare and branch.
790 /// Loop-strength-reduction (LSR) uses that knowledge to adjust its cost
791 /// calculation for the instructions in a loop.
792 LLVM_ABI bool canMacroFuseCmp() const;
793
794 /// Return true if the target can save a compare for loop count, for example
795 /// hardware loop saves a compare.
798 TargetLibraryInfo *LibInfo) const;
799
800 /// Which addressing mode Loop Strength Reduction will try to generate.
802 AMK_None = 0x0, ///< Don't prefer any addressing mode
803 AMK_PreIndexed = 0x1, ///< Prefer pre-indexed addressing mode
804 AMK_PostIndexed = 0x2, ///< Prefer post-indexed addressing mode
805 AMK_All = 0x3, ///< Consider all addressing modes
806 LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/AMK_All)
807 };
808
809 /// Return the preferred addressing mode LSR should make efforts to generate.
812
813 /// Return true if the target supports masked store.
814 LLVM_ABI bool isLegalMaskedStore(Type *DataType, Align Alignment,
815 unsigned AddressSpace) const;
816 /// Return true if the target supports masked load.
817 LLVM_ABI bool isLegalMaskedLoad(Type *DataType, Align Alignment,
818 unsigned AddressSpace) const;
819
820 /// Return true if the target supports nontemporal store.
821 LLVM_ABI bool isLegalNTStore(Type *DataType, Align Alignment) const;
822 /// Return true if the target supports nontemporal load.
823 LLVM_ABI bool isLegalNTLoad(Type *DataType, Align Alignment) const;
824
825 /// \Returns true if the target supports broadcasting a load to a vector of
826 /// type <NumElements x ElementTy>.
827 LLVM_ABI bool isLegalBroadcastLoad(Type *ElementTy,
828 ElementCount NumElements) const;
829
830 /// Return true if the target supports masked scatter.
831 LLVM_ABI bool isLegalMaskedScatter(Type *DataType, Align Alignment) const;
832 /// Return true if the target supports masked gather.
833 LLVM_ABI bool isLegalMaskedGather(Type *DataType, Align Alignment) const;
834 /// Return true if the target forces scalarizing of llvm.masked.gather
835 /// intrinsics.
837 Align Alignment) const;
838 /// Return true if the target forces scalarizing of llvm.masked.scatter
839 /// intrinsics.
841 Align Alignment) const;
842
843 /// Return true if the target supports masked compress store.
845 Align Alignment) const;
846 /// Return true if the target supports masked expand load.
847 LLVM_ABI bool isLegalMaskedExpandLoad(Type *DataType, Align Alignment) const;
848
849 /// Return true if the target supports strided load.
850 LLVM_ABI bool isLegalStridedLoadStore(Type *DataType, Align Alignment) const;
851
852 /// Return true is the target supports interleaved access for the given vector
853 /// type \p VTy, interleave factor \p Factor, alignment \p Alignment and
854 /// address space \p AddrSpace.
855 LLVM_ABI bool isLegalInterleavedAccessType(VectorType *VTy, unsigned Factor,
856 Align Alignment,
857 unsigned AddrSpace) const;
858
859 // Return true if the target supports masked vector histograms.
861 Type *DataType) const;
862
863 /// Return true if this is an alternating opcode pattern that can be lowered
864 /// to a single instruction on the target. In X86 this is for the addsub
865 /// instruction which corrsponds to a Shuffle + Fadd + FSub pattern in IR.
866 /// This function expectes two opcodes: \p Opcode1 and \p Opcode2 being
867 /// selected by \p OpcodeMask. The mask contains one bit per lane and is a `0`
868 /// when \p Opcode0 is selected and `1` when Opcode1 is selected.
869 /// \p VecTy is the vector type of the instruction to be generated.
870 LLVM_ABI bool isLegalAltInstr(VectorType *VecTy, unsigned Opcode0,
871 unsigned Opcode1,
872 const SmallBitVector &OpcodeMask) const;
873
874 /// Return true if we should be enabling ordered reductions for the target.
876
877 /// Return true if the target has a unified operation to calculate division
878 /// and remainder. If so, the additional implicit multiplication and
879 /// subtraction required to calculate a remainder from division are free. This
880 /// can enable more aggressive transformations for division and remainder than
881 /// would typically be allowed using throughput or size cost models.
882 LLVM_ABI bool hasDivRemOp(Type *DataType, bool IsSigned) const;
883
884 /// Return true if the given instruction (assumed to be a memory access
885 /// instruction) has a volatile variant. If that's the case then we can avoid
886 /// addrspacecast to generic AS for volatile loads/stores. Default
887 /// implementation returns false, which prevents address space inference for
888 /// volatile loads/stores.
889 LLVM_ABI bool hasVolatileVariant(Instruction *I, unsigned AddrSpace) const;
890
891 /// Return true if target doesn't mind addresses in vectors.
893
894 /// Return the cost of the scaling factor used in the addressing
895 /// mode represented by AM for this target, for a load/store
896 /// of the specified type.
897 /// If the AM is supported, the return value must be >= 0.
898 /// If the AM is not supported, it returns a negative value.
899 /// TODO: Handle pre/postinc as well.
901 StackOffset BaseOffset,
902 bool HasBaseReg, int64_t Scale,
903 unsigned AddrSpace = 0) const;
904
905 /// Return true if the loop strength reduce pass should make
906 /// Instruction* based TTI queries to isLegalAddressingMode(). This is
907 /// needed on SystemZ, where e.g. a memcpy can only have a 12 bit unsigned
908 /// immediate offset and no index register.
909 LLVM_ABI bool LSRWithInstrQueries() const;
910
911 /// Return true if it's free to truncate a value of type Ty1 to type
912 /// Ty2. e.g. On x86 it's free to truncate a i32 value in register EAX to i16
913 /// by referencing its sub-register AX.
914 LLVM_ABI bool isTruncateFree(Type *Ty1, Type *Ty2) const;
915
916 /// Return true if it is profitable to hoist instruction in the
917 /// then/else to before if.
919
920 LLVM_ABI bool useAA() const;
921
922 /// Return true if this type is legal.
923 LLVM_ABI bool isTypeLegal(Type *Ty) const;
924
925 /// Returns the estimated number of registers required to represent \p Ty.
926 LLVM_ABI unsigned getRegUsageForType(Type *Ty) const;
927
928 /// Return true if switches should be turned into lookup tables for the
929 /// target.
931
932 /// Return true if switches should be turned into lookup tables
933 /// containing this constant value for the target.
935
936 /// Return true if lookup tables should be turned into relative lookup tables.
938
939 /// Return true if the input function which is cold at all call sites,
940 /// should use coldcc calling convention.
942
944
945 /// Identifies if the vector form of the intrinsic has a scalar operand.
947 unsigned ScalarOpdIdx) const;
948
949 /// Identifies if the vector form of the intrinsic is overloaded on the type
950 /// of the operand at index \p OpdIdx, or on the return type if \p OpdIdx is
951 /// -1.
953 int OpdIdx) const;
954
955 /// Identifies if the vector form of the intrinsic that returns a struct is
956 /// overloaded at the struct element index \p RetIdx.
957 LLVM_ABI bool
959 int RetIdx) const;
960
961 /// Estimate the overhead of scalarizing an instruction. Insert and Extract
962 /// are set if the demanded result elements need to be inserted and/or
963 /// extracted from vectors. The involved values may be passed in VL if
964 /// Insert is true.
966 VectorType *Ty, const APInt &DemandedElts, bool Insert, bool Extract,
967 TTI::TargetCostKind CostKind, bool ForPoisonSrc = true,
968 ArrayRef<Value *> VL = {}) const;
969
970 /// Estimate the overhead of scalarizing operands with the given types. The
971 /// (potentially vector) types to use for each of argument are passes via Tys.
974
975 /// If target has efficient vector element load/store instructions, it can
976 /// return true here so that insertion/extraction costs are not added to
977 /// the scalarization cost of a load/store.
979
980 /// If the target supports tail calls.
981 LLVM_ABI bool supportsTailCalls() const;
982
983 /// If target supports tail call on \p CB
984 LLVM_ABI bool supportsTailCallFor(const CallBase *CB) const;
985
986 /// Don't restrict interleaved unrolling to small loops.
987 LLVM_ABI bool enableAggressiveInterleaving(bool LoopHasReductions) const;
988
989 /// Returns options for expansion of memcmp. IsZeroCmp is
990 // true if this is the expansion of memcmp(p1, p2, s) == 0.
992 // Return true if memcmp expansion is enabled.
993 operator bool() const { return MaxNumLoads > 0; }
994
995 // Maximum number of load operations.
996 unsigned MaxNumLoads = 0;
997
998 // The list of available load sizes (in bytes), sorted in decreasing order.
1000
1001 // For memcmp expansion when the memcmp result is only compared equal or
1002 // not-equal to 0, allow up to this number of load pairs per block. As an
1003 // example, this may allow 'memcmp(a, b, 3) == 0' in a single block:
1004 // a0 = load2bytes &a[0]
1005 // b0 = load2bytes &b[0]
1006 // a2 = load1byte &a[2]
1007 // b2 = load1byte &b[2]
1008 // r = cmp eq (a0 ^ b0 | a2 ^ b2), 0
1009 unsigned NumLoadsPerBlock = 1;
1010
1011 // Set to true to allow overlapping loads. For example, 7-byte compares can
1012 // be done with two 4-byte compares instead of 4+2+1-byte compares. This
1013 // requires all loads in LoadSizes to be doable in an unaligned way.
1015
1016 // Sometimes, the amount of data that needs to be compared is smaller than
1017 // the standard register size, but it cannot be loaded with just one load
1018 // instruction. For example, if the size of the memory comparison is 6
1019 // bytes, we can handle it more efficiently by loading all 6 bytes in a
1020 // single block and generating an 8-byte number, instead of generating two
1021 // separate blocks with conditional jumps for 4 and 2 byte loads. This
1022 // approach simplifies the process and produces the comparison result as
1023 // normal. This array lists the allowed sizes of memcmp tails that can be
1024 // merged into one block
1026 };
1028 bool IsZeroCmp) const;
1029
1030 /// Should the Select Optimization pass be enabled and ran.
1031 LLVM_ABI bool enableSelectOptimize() const;
1032
1033 /// Should the Select Optimization pass treat the given instruction like a
1034 /// select, potentially converting it to a conditional branch. This can
1035 /// include select-like instructions like or(zext(c), x) that can be converted
1036 /// to selects.
1038
1039 /// Enable matching of interleaved access groups.
1041
1042 /// Enable matching of interleaved access groups that contain predicated
1043 /// accesses or gaps and therefore vectorized using masked
1044 /// vector loads/stores.
1046
1047 /// Indicate that it is potentially unsafe to automatically vectorize
1048 /// floating-point operations because the semantics of vector and scalar
1049 /// floating-point semantics may differ. For example, ARM NEON v7 SIMD math
1050 /// does not support IEEE-754 denormal numbers, while depending on the
1051 /// platform, scalar floating-point math does.
1052 /// This applies to floating-point math operations and calls, not memory
1053 /// operations, shuffles, or casts.
1055
1056 /// Determine if the target supports unaligned memory accesses.
1058 unsigned BitWidth,
1059 unsigned AddressSpace = 0,
1060 Align Alignment = Align(1),
1061 unsigned *Fast = nullptr) const;
1062
1063 /// Return hardware support for population count.
1064 LLVM_ABI PopcntSupportKind getPopcntSupport(unsigned IntTyWidthInBit) const;
1065
1066 /// Return true if the hardware has a fast square-root instruction.
1067 LLVM_ABI bool haveFastSqrt(Type *Ty) const;
1068
1069 /// Return true if the cost of the instruction is too high to speculatively
1070 /// execute and should be kept behind a branch.
1071 /// This normally just wraps around a getInstructionCost() call, but some
1072 /// targets might report a low TCK_SizeAndLatency value that is incompatible
1073 /// with the fixed TCC_Expensive value.
1074 /// NOTE: This assumes the instruction passes isSafeToSpeculativelyExecute().
1076
1077 /// Return true if it is faster to check if a floating-point value is NaN
1078 /// (or not-NaN) versus a comparison against a constant FP zero value.
1079 /// Targets should override this if materializing a 0.0 for comparison is
1080 /// generally as cheap as checking for ordered/unordered.
1082
1083 /// Return the expected cost of supporting the floating point operation
1084 /// of the specified type.
1086
1087 /// Return the expected cost of materializing for the given integer
1088 /// immediate of the specified type.
1090 TargetCostKind CostKind) const;
1091
1092 /// Return the expected cost of materialization for the given integer
1093 /// immediate of the specified type for a given instruction. The cost can be
1094 /// zero if the immediate can be folded into the specified instruction.
1095 LLVM_ABI InstructionCost getIntImmCostInst(unsigned Opc, unsigned Idx,
1096 const APInt &Imm, Type *Ty,
1098 Instruction *Inst = nullptr) const;
1100 const APInt &Imm, Type *Ty,
1101 TargetCostKind CostKind) const;
1102
1103 /// Return the expected cost for the given integer when optimising
1104 /// for size. This is different than the other integer immediate cost
1105 /// functions in that it is subtarget agnostic. This is useful when you e.g.
1106 /// target one ISA such as Aarch32 but smaller encodings could be possible
1107 /// with another such as Thumb. This return value is used as a penalty when
1108 /// the total costs for a constant is calculated (the bigger the cost, the
1109 /// more beneficial constant hoisting is).
1110 LLVM_ABI InstructionCost getIntImmCodeSizeCost(unsigned Opc, unsigned Idx,
1111 const APInt &Imm,
1112 Type *Ty) const;
1113
1114 /// It can be advantageous to detach complex constants from their uses to make
1115 /// their generation cheaper. This hook allows targets to report when such
1116 /// transformations might negatively effect the code generation of the
1117 /// underlying operation. The motivating example is divides whereby hoisting
1118 /// constants prevents the code generator's ability to transform them into
1119 /// combinations of simpler operations.
1121 const Function &Fn) const;
1122
1123 /// @}
1124
1125 /// \name Vector Target Information
1126 /// @{
1127
1128 /// The various kinds of shuffle patterns for vector queries.
1130 SK_Broadcast, ///< Broadcast element 0 to all other elements.
1131 SK_Reverse, ///< Reverse the order of the vector.
1132 SK_Select, ///< Selects elements from the corresponding lane of
1133 ///< either source operand. This is equivalent to a
1134 ///< vector select with a constant condition operand.
1135 SK_Transpose, ///< Transpose two vectors.
1136 SK_InsertSubvector, ///< InsertSubvector. Index indicates start offset.
1137 SK_ExtractSubvector, ///< ExtractSubvector Index indicates start offset.
1138 SK_PermuteTwoSrc, ///< Merge elements from two source vectors into one
1139 ///< with any shuffle mask.
1140 SK_PermuteSingleSrc, ///< Shuffle elements of single source vector with any
1141 ///< shuffle mask.
1142 SK_Splice ///< Concatenates elements from the first input vector
1143 ///< with elements of the second input vector. Returning
1144 ///< a vector of the same type as the input vectors.
1145 ///< Index indicates start offset in first input vector.
1146 };
1147
1148 /// Additional information about an operand's possible values.
1150 OK_AnyValue, // Operand can have any value.
1151 OK_UniformValue, // Operand is uniform (splat of a value).
1152 OK_UniformConstantValue, // Operand is uniform constant.
1153 OK_NonUniformConstantValue // Operand is a non uniform constant value.
1154 };
1155
1156 /// Additional properties of an operand's values.
1162
1163 // Describe the values an operand can take. We're in the process
1164 // of migrating uses of OperandValueKind and OperandValueProperties
1165 // to use this class, and then will change the internal representation.
1169
1170 bool isConstant() const {
1172 }
1173 bool isUniform() const {
1175 }
1176 bool isPowerOf2() const {
1177 return Properties == OP_PowerOf2;
1178 }
1179 bool isNegatedPowerOf2() const {
1181 }
1182
1184 return {Kind, OP_None};
1185 }
1186 };
1187
1188 /// \return the number of registers in the target-provided register class.
1189 LLVM_ABI unsigned getNumberOfRegisters(unsigned ClassID) const;
1190
1191 /// \return true if the target supports load/store that enables fault
1192 /// suppression of memory operands when the source condition is false.
1193 LLVM_ABI bool hasConditionalLoadStoreForType(Type *Ty, bool IsStore) const;
1194
1195 /// \return the target-provided register class ID for the provided type,
1196 /// accounting for type promotion and other type-legalization techniques that
1197 /// the target might apply. However, it specifically does not account for the
1198 /// scalarization or splitting of vector types. Should a vector type require
1199 /// scalarization or splitting into multiple underlying vector registers, that
1200 /// type should be mapped to a register class containing no registers.
1201 /// Specifically, this is designed to provide a simple, high-level view of the
1202 /// register allocation later performed by the backend. These register classes
1203 /// don't necessarily map onto the register classes used by the backend.
1204 /// FIXME: It's not currently possible to determine how many registers
1205 /// are used by the provided type.
1207 Type *Ty = nullptr) const;
1208
1209 /// \return the target-provided register class name
1210 LLVM_ABI const char *getRegisterClassName(unsigned ClassID) const;
1211
1213
1214 /// \return The width of the largest scalar or vector register type.
1215 LLVM_ABI TypeSize getRegisterBitWidth(RegisterKind K) const;
1216
1217 /// \return The width of the smallest vector register type.
1218 LLVM_ABI unsigned getMinVectorRegisterBitWidth() const;
1219
1220 /// \return The maximum value of vscale if the target specifies an
1221 /// architectural maximum vector length, and std::nullopt otherwise.
1222 LLVM_ABI std::optional<unsigned> getMaxVScale() const;
1223
1224 /// \return the value of vscale to tune the cost model for.
1225 LLVM_ABI std::optional<unsigned> getVScaleForTuning() const;
1226
1227 /// \return true if vscale is known to be a power of 2
1229
1230 /// \return True if the vectorization factor should be chosen to
1231 /// make the vector of the smallest element type match the size of a
1232 /// vector register. For wider element types, this could result in
1233 /// creating vectors that span multiple vector registers.
1234 /// If false, the vectorization factor will be chosen based on the
1235 /// size of the widest element type.
1236 /// \p K Register Kind for vectorization.
1237 LLVM_ABI bool
1239
1240 /// \return The minimum vectorization factor for types of given element
1241 /// bit width, or 0 if there is no minimum VF. The returned value only
1242 /// applies when shouldMaximizeVectorBandwidth returns true.
1243 /// If IsScalable is true, the returned ElementCount must be a scalable VF.
1244 LLVM_ABI ElementCount getMinimumVF(unsigned ElemWidth, bool IsScalable) const;
1245
1246 /// \return The maximum vectorization factor for types of given element
1247 /// bit width and opcode, or 0 if there is no maximum VF.
1248 /// Currently only used by the SLP vectorizer.
1249 LLVM_ABI unsigned getMaximumVF(unsigned ElemWidth, unsigned Opcode) const;
1250
1251 /// \return The minimum vectorization factor for the store instruction. Given
1252 /// the initial estimation of the minimum vector factor and store value type,
1253 /// it tries to find possible lowest VF, which still might be profitable for
1254 /// the vectorization.
1255 /// \param VF Initial estimation of the minimum vector factor.
1256 /// \param ScalarMemTy Scalar memory type of the store operation.
1257 /// \param ScalarValTy Scalar type of the stored value.
1258 /// Currently only used by the SLP vectorizer.
1259 LLVM_ABI unsigned getStoreMinimumVF(unsigned VF, Type *ScalarMemTy,
1260 Type *ScalarValTy) const;
1261
1262 /// \return True if it should be considered for address type promotion.
1263 /// \p AllowPromotionWithoutCommonHeader Set true if promoting \p I is
1264 /// profitable without finding other extensions fed by the same input.
1266 const Instruction &I, bool &AllowPromotionWithoutCommonHeader) const;
1267
1268 /// \return The size of a cache line in bytes.
1269 LLVM_ABI unsigned getCacheLineSize() const;
1270
1271 /// The possible cache levels
1272 enum class CacheLevel {
1273 L1D, // The L1 data cache
1274 L2D, // The L2 data cache
1275
1276 // We currently do not model L3 caches, as their sizes differ widely between
1277 // microarchitectures. Also, we currently do not have a use for L3 cache
1278 // size modeling yet.
1279 };
1280
1281 /// \return The size of the cache level in bytes, if available.
1282 LLVM_ABI std::optional<unsigned> getCacheSize(CacheLevel Level) const;
1283
1284 /// \return The associativity of the cache level, if available.
1285 LLVM_ABI std::optional<unsigned>
1286 getCacheAssociativity(CacheLevel Level) const;
1287
1288 /// \return The minimum architectural page size for the target.
1289 LLVM_ABI std::optional<unsigned> getMinPageSize() const;
1290
1291 /// \return How much before a load we should place the prefetch
1292 /// instruction. This is currently measured in number of
1293 /// instructions.
1294 LLVM_ABI unsigned getPrefetchDistance() const;
1295
1296 /// Some HW prefetchers can handle accesses up to a certain constant stride.
1297 /// Sometimes prefetching is beneficial even below the HW prefetcher limit,
1298 /// and the arguments provided are meant to serve as a basis for deciding this
1299 /// for a particular loop.
1300 ///
1301 /// \param NumMemAccesses Number of memory accesses in the loop.
1302 /// \param NumStridedMemAccesses Number of the memory accesses that
1303 /// ScalarEvolution could find a known stride
1304 /// for.
1305 /// \param NumPrefetches Number of software prefetches that will be
1306 /// emitted as determined by the addresses
1307 /// involved and the cache line size.
1308 /// \param HasCall True if the loop contains a call.
1309 ///
1310 /// \return This is the minimum stride in bytes where it makes sense to start
1311 /// adding SW prefetches. The default is 1, i.e. prefetch with any
1312 /// stride.
1313 LLVM_ABI unsigned getMinPrefetchStride(unsigned NumMemAccesses,
1314 unsigned NumStridedMemAccesses,
1315 unsigned NumPrefetches,
1316 bool HasCall) const;
1317
1318 /// \return The maximum number of iterations to prefetch ahead. If
1319 /// the required number of iterations is more than this number, no
1320 /// prefetching is performed.
1321 LLVM_ABI unsigned getMaxPrefetchIterationsAhead() const;
1322
1323 /// \return True if prefetching should also be done for writes.
1324 LLVM_ABI bool enableWritePrefetching() const;
1325
1326 /// \return if target want to issue a prefetch in address space \p AS.
1327 LLVM_ABI bool shouldPrefetchAddressSpace(unsigned AS) const;
1328
1329 /// \return The cost of a partial reduction, which is a reduction from a
1330 /// vector to another vector with fewer elements of larger size. They are
1331 /// represented by the llvm.vector.partial.reduce.add intrinsic, which
1332 /// takes an accumulator of type \p AccumType and a second vector operand to
1333 /// be accumulated, whose element count is specified by \p VF. The type of
1334 /// reduction is specified by \p Opcode. The second operand passed to the
1335 /// intrinsic could be the result of an extend, such as sext or zext. In
1336 /// this case \p BinOp is nullopt, \p InputTypeA represents the type being
1337 /// extended and \p OpAExtend the operation, i.e. sign- or zero-extend.
1338 /// Also, \p InputTypeB should be nullptr and OpBExtend should be None.
1339 /// Alternatively, the second operand could be the result of a binary
1340 /// operation performed on two extends, i.e.
1341 /// mul(zext i8 %a -> i32, zext i8 %b -> i32).
1342 /// In this case \p BinOp may specify the opcode of the binary operation,
1343 /// \p InputTypeA and \p InputTypeB the types being extended, and
1344 /// \p OpAExtend, \p OpBExtend the form of extensions. An example of an
1345 /// operation that uses a partial reduction is a dot product, which reduces
1346 /// two vectors in binary mul operation to another of 4 times fewer and 4
1347 /// times larger elements.
1349 unsigned Opcode, Type *InputTypeA, Type *InputTypeB, Type *AccumType,
1351 PartialReductionExtendKind OpBExtend, std::optional<unsigned> BinOp,
1353
1354 /// \return The maximum interleave factor that any transform should try to
1355 /// perform for this target. This number depends on the level of parallelism
1356 /// and the number of execution units in the CPU.
1357 LLVM_ABI unsigned getMaxInterleaveFactor(ElementCount VF) const;
1358
1359 /// Collect properties of V used in cost analysis, e.g. OP_PowerOf2.
1360 LLVM_ABI static OperandValueInfo getOperandInfo(const Value *V);
1361
1362 /// This is an approximation of reciprocal throughput of a math/logic op.
1363 /// A higher cost indicates less expected throughput.
1364 /// From Agner Fog's guides, reciprocal throughput is "the average number of
1365 /// clock cycles per instruction when the instructions are not part of a
1366 /// limiting dependency chain."
1367 /// Therefore, costs should be scaled to account for multiple execution units
1368 /// on the target that can process this type of instruction. For example, if
1369 /// there are 5 scalar integer units and 2 vector integer units that can
1370 /// calculate an 'add' in a single cycle, this model should indicate that the
1371 /// cost of the vector add instruction is 2.5 times the cost of the scalar
1372 /// add instruction.
1373 /// \p Args is an optional argument which holds the instruction operands
1374 /// values so the TTI can analyze those values searching for special
1375 /// cases or optimizations based on those values.
1376 /// \p CxtI is the optional original context instruction, if one exists, to
1377 /// provide even more information.
1378 /// \p TLibInfo is used to search for platform specific vector library
1379 /// functions for instructions that might be converted to calls (e.g. frem).
1381 unsigned Opcode, Type *Ty,
1385 ArrayRef<const Value *> Args = {}, const Instruction *CxtI = nullptr,
1386 const TargetLibraryInfo *TLibInfo = nullptr) const;
1387
1388 /// Returns the cost estimation for alternating opcode pattern that can be
1389 /// lowered to a single instruction on the target. In X86 this is for the
1390 /// addsub instruction which corrsponds to a Shuffle + Fadd + FSub pattern in
1391 /// IR. This function expects two opcodes: \p Opcode1 and \p Opcode2 being
1392 /// selected by \p OpcodeMask. The mask contains one bit per lane and is a `0`
1393 /// when \p Opcode0 is selected and `1` when Opcode1 is selected.
1394 /// \p VecTy is the vector type of the instruction to be generated.
1396 VectorType *VecTy, unsigned Opcode0, unsigned Opcode1,
1397 const SmallBitVector &OpcodeMask,
1399
1400 /// \return The cost of a shuffle instruction of kind Kind with inputs of type
1401 /// SrcTy, producing a vector of type DstTy. The exact mask may be passed as
1402 /// Mask, or else the array will be empty. The Index and SubTp parameters
1403 /// are used by the subvector insertions shuffle kinds to show the insert
1404 /// point and the type of the subvector being inserted. The operands of the
1405 /// shuffle can be passed through \p Args, which helps improve the cost
1406 /// estimation in some cases, like in broadcast loads.
1408 ShuffleKind Kind, VectorType *DstTy, VectorType *SrcTy,
1409 ArrayRef<int> Mask = {},
1411 VectorType *SubTp = nullptr, ArrayRef<const Value *> Args = {},
1412 const Instruction *CxtI = nullptr) const;
1413
1414 /// Represents a hint about the context in which a cast is used.
1415 ///
1416 /// For zext/sext, the context of the cast is the operand, which must be a
1417 /// load of some kind. For trunc, the context is of the cast is the single
1418 /// user of the instruction, which must be a store of some kind.
1419 ///
1420 /// This enum allows the vectorizer to give getCastInstrCost an idea of the
1421 /// type of cast it's dealing with, as not every cast is equal. For instance,
1422 /// the zext of a load may be free, but the zext of an interleaving load can
1423 //// be (very) expensive!
1424 ///
1425 /// See \c getCastContextHint to compute a CastContextHint from a cast
1426 /// Instruction*. Callers can use it if they don't need to override the
1427 /// context and just want it to be calculated from the instruction.
1428 ///
1429 /// FIXME: This handles the types of load/store that the vectorizer can
1430 /// produce, which are the cases where the context instruction is most
1431 /// likely to be incorrect. There are other situations where that can happen
1432 /// too, which might be handled here but in the long run a more general
1433 /// solution of costing multiple instructions at the same times may be better.
1435 None, ///< The cast is not used with a load/store of any kind.
1436 Normal, ///< The cast is used with a normal load/store.
1437 Masked, ///< The cast is used with a masked load/store.
1438 GatherScatter, ///< The cast is used with a gather/scatter.
1439 Interleave, ///< The cast is used with an interleaved load/store.
1440 Reversed, ///< The cast is used with a reversed load/store.
1441 };
1442
1443 /// Calculates a CastContextHint from \p I.
1444 /// This should be used by callers of getCastInstrCost if they wish to
1445 /// determine the context from some instruction.
1446 /// \returns the CastContextHint for ZExt/SExt/Trunc, None if \p I is nullptr,
1447 /// or if it's another type of cast.
1449
1450 /// \return The expected cost of cast instructions, such as bitcast, trunc,
1451 /// zext, etc. If there is an existing instruction that holds Opcode, it
1452 /// may be passed in the 'I' parameter.
1454 unsigned Opcode, Type *Dst, Type *Src, TTI::CastContextHint CCH,
1456 const Instruction *I = nullptr) const;
1457
1458 /// \return The expected cost of a sign- or zero-extended vector extract. Use
1459 /// Index = -1 to indicate that there is no information about the index value.
1461 getExtractWithExtendCost(unsigned Opcode, Type *Dst, VectorType *VecTy,
1462 unsigned Index, TTI::TargetCostKind CostKind) const;
1463
1464 /// \return The expected cost of control-flow related instructions such as
1465 /// Phi, Ret, Br, Switch.
1468 const Instruction *I = nullptr) const;
1469
1470 /// \returns The expected cost of compare and select instructions. If there
1471 /// is an existing instruction that holds Opcode, it may be passed in the
1472 /// 'I' parameter. The \p VecPred parameter can be used to indicate the select
1473 /// is using a compare with the specified predicate as condition. When vector
1474 /// types are passed, \p VecPred must be used for all lanes. For a
1475 /// comparison, the two operands are the natural values. For a select, the
1476 /// two operands are the *value* operands, not the condition operand.
1478 unsigned Opcode, Type *ValTy, Type *CondTy, CmpInst::Predicate VecPred,
1480 OperandValueInfo Op1Info = {OK_AnyValue, OP_None},
1481 OperandValueInfo Op2Info = {OK_AnyValue, OP_None},
1482 const Instruction *I = nullptr) const;
1483
1484 /// \return The expected cost of vector Insert and Extract.
1485 /// Use -1 to indicate that there is no information on the index value.
1486 /// This is used when the instruction is not available; a typical use
1487 /// case is to provision the cost of vectorization/scalarization in
1488 /// vectorizer passes.
1489 LLVM_ABI InstructionCost getVectorInstrCost(unsigned Opcode, Type *Val,
1491 unsigned Index = -1,
1492 const Value *Op0 = nullptr,
1493 const Value *Op1 = nullptr) const;
1494
1495 /// \return The expected cost of vector Insert and Extract.
1496 /// Use -1 to indicate that there is no information on the index value.
1497 /// This is used when the instruction is not available; a typical use
1498 /// case is to provision the cost of vectorization/scalarization in
1499 /// vectorizer passes.
1500 /// \param ScalarUserAndIdx encodes the information about extracts from a
1501 /// vector with 'Scalar' being the value being extracted,'User' being the user
1502 /// of the extract(nullptr if user is not known before vectorization) and
1503 /// 'Idx' being the extract lane.
1505 unsigned Opcode, Type *Val, TTI::TargetCostKind CostKind, unsigned Index,
1506 Value *Scalar,
1507 ArrayRef<std::tuple<Value *, User *, int>> ScalarUserAndIdx) const;
1508
1509 /// \return The expected cost of vector Insert and Extract.
1510 /// This is used when instruction is available, and implementation
1511 /// asserts 'I' is not nullptr.
1512 ///
1513 /// A typical suitable use case is cost estimation when vector instruction
1514 /// exists (e.g., from basic blocks during transformation).
1515 LLVM_ABI InstructionCost getVectorInstrCost(const Instruction &I, Type *Val,
1517 unsigned Index = -1) const;
1518
1519 /// \return The expected cost of inserting or extracting a lane that is \p
1520 /// Index elements from the end of a vector, i.e. the mathematical expression
1521 /// for the lane is (VF - 1 - Index). This is required for scalable vectors
1522 /// where the exact lane index is unknown at compile time.
1524 unsigned Opcode, Type *Val, TTI::TargetCostKind CostKind,
1525 unsigned Index) const;
1526
1527 /// \return The expected cost of aggregate inserts and extracts. This is
1528 /// used when the instruction is not available; a typical use case is to
1529 /// provision the cost of vectorization/scalarization in vectorizer passes.
1531 unsigned Opcode, TTI::TargetCostKind CostKind) const;
1532
1533 /// \return The cost of replication shuffle of \p VF elements typed \p EltTy
1534 /// \p ReplicationFactor times.
1535 ///
1536 /// For example, the mask for \p ReplicationFactor=3 and \p VF=4 is:
1537 /// <0,0,0,1,1,1,2,2,2,3,3,3>
1539 Type *EltTy, int ReplicationFactor, int VF, const APInt &DemandedDstElts,
1541
1542 /// \return The cost of Load and Store instructions. The operand info
1543 /// \p OpdInfo should refer to the stored value for stores and the address
1544 /// for loads.
1546 unsigned Opcode, Type *Src, Align Alignment, unsigned AddressSpace,
1549 const Instruction *I = nullptr) const;
1550
1551 /// \return The cost of VP Load and Store instructions.
1553 unsigned Opcode, Type *Src, Align Alignment, unsigned AddressSpace,
1555 const Instruction *I = nullptr) const;
1556
1557 /// \return The cost of masked Load and Store instructions.
1559 unsigned Opcode, Type *Src, Align Alignment, unsigned AddressSpace,
1561
1562 /// \return The cost of Gather or Scatter operation
1563 /// \p Opcode - is a type of memory access Load or Store
1564 /// \p DataTy - a vector type of the data to be loaded or stored
1565 /// \p Ptr - pointer [or vector of pointers] - address[es] in memory
1566 /// \p VariableMask - true when the memory access is predicated with a mask
1567 /// that is not a compile-time constant
1568 /// \p Alignment - alignment of single element
1569 /// \p I - the optional original context instruction, if one exists, e.g. the
1570 /// load/store to transform or the call to the gather/scatter intrinsic
1572 unsigned Opcode, Type *DataTy, const Value *Ptr, bool VariableMask,
1574 const Instruction *I = nullptr) const;
1575
1576 /// \return The cost of Expand Load or Compress Store operation
1577 /// \p Opcode - is a type of memory access Load or Store
1578 /// \p Src - a vector type of the data to be loaded or stored
1579 /// \p VariableMask - true when the memory access is predicated with a mask
1580 /// that is not a compile-time constant
1581 /// \p Alignment - alignment of single element
1582 /// \p I - the optional original context instruction, if one exists, e.g. the
1583 /// load/store to transform or the call to the gather/scatter intrinsic
1585 unsigned Opcode, Type *DataTy, bool VariableMask, Align Alignment,
1587 const Instruction *I = nullptr) const;
1588
1589 /// \return The cost of strided memory operations.
1590 /// \p Opcode - is a type of memory access Load or Store
1591 /// \p DataTy - a vector type of the data to be loaded or stored
1592 /// \p Ptr - pointer [or vector of pointers] - address[es] in memory
1593 /// \p VariableMask - true when the memory access is predicated with a mask
1594 /// that is not a compile-time constant
1595 /// \p Alignment - alignment of single element
1596 /// \p I - the optional original context instruction, if one exists, e.g. the
1597 /// load/store to transform or the call to the gather/scatter intrinsic
1599 unsigned Opcode, Type *DataTy, const Value *Ptr, bool VariableMask,
1601 const Instruction *I = nullptr) const;
1602
1603 /// \return The cost of the interleaved memory operation.
1604 /// \p Opcode is the memory operation code
1605 /// \p VecTy is the vector type of the interleaved access.
1606 /// \p Factor is the interleave factor
1607 /// \p Indices is the indices for interleaved load members (as interleaved
1608 /// load allows gaps)
1609 /// \p Alignment is the alignment of the memory operation
1610 /// \p AddressSpace is address space of the pointer.
1611 /// \p UseMaskForCond indicates if the memory access is predicated.
1612 /// \p UseMaskForGaps indicates if gaps should be masked.
1614 unsigned Opcode, Type *VecTy, unsigned Factor, ArrayRef<unsigned> Indices,
1615 Align Alignment, unsigned AddressSpace,
1617 bool UseMaskForCond = false, bool UseMaskForGaps = false) const;
1618
1619 /// A helper function to determine the type of reduction algorithm used
1620 /// for a given \p Opcode and set of FastMathFlags \p FMF.
1621 static bool requiresOrderedReduction(std::optional<FastMathFlags> FMF) {
1622 return FMF && !(*FMF).allowReassoc();
1623 }
1624
1625 /// Calculate the cost of vector reduction intrinsics.
1626 ///
1627 /// This is the cost of reducing the vector value of type \p Ty to a scalar
1628 /// value using the operation denoted by \p Opcode. The FastMathFlags
1629 /// parameter \p FMF indicates what type of reduction we are performing:
1630 /// 1. Tree-wise. This is the typical 'fast' reduction performed that
1631 /// involves successively splitting a vector into half and doing the
1632 /// operation on the pair of halves until you have a scalar value. For
1633 /// example:
1634 /// (v0, v1, v2, v3)
1635 /// ((v0+v2), (v1+v3), undef, undef)
1636 /// ((v0+v2+v1+v3), undef, undef, undef)
1637 /// This is the default behaviour for integer operations, whereas for
1638 /// floating point we only do this if \p FMF indicates that
1639 /// reassociation is allowed.
1640 /// 2. Ordered. For a vector with N elements this involves performing N
1641 /// operations in lane order, starting with an initial scalar value, i.e.
1642 /// result = InitVal + v0
1643 /// result = result + v1
1644 /// result = result + v2
1645 /// result = result + v3
1646 /// This is only the case for FP operations and when reassociation is not
1647 /// allowed.
1648 ///
1650 unsigned Opcode, VectorType *Ty, std::optional<FastMathFlags> FMF,
1652
1656
1657 /// Calculate the cost of an extended reduction pattern, similar to
1658 /// getArithmeticReductionCost of an Add/Sub reduction with multiply and
1659 /// optional extensions. This is the cost of as:
1660 /// * ResTy vecreduce.add/sub(mul (A, B)) or,
1661 /// * ResTy vecreduce.add/sub(mul(ext(Ty A), ext(Ty B)).
1663 bool IsUnsigned, unsigned RedOpcode, Type *ResTy, VectorType *Ty,
1665
1666 /// Calculate the cost of an extended reduction pattern, similar to
1667 /// getArithmeticReductionCost of a reduction with an extension.
1668 /// This is the cost of as:
1669 /// ResTy vecreduce.opcode(ext(Ty A)).
1671 unsigned Opcode, bool IsUnsigned, Type *ResTy, VectorType *Ty,
1672 std::optional<FastMathFlags> FMF,
1674
1675 /// \returns The cost of Intrinsic instructions. Analyses the real arguments.
1676 /// Three cases are handled: 1. scalar instruction 2. vector instruction
1677 /// 3. scalar instruction which is to be vectorized.
1680
1681 /// \returns The cost of Call instructions.
1683 Function *F, Type *RetTy, ArrayRef<Type *> Tys,
1685
1686 /// \returns The number of pieces into which the provided type must be
1687 /// split during legalization. Zero is returned when the answer is unknown.
1688 LLVM_ABI unsigned getNumberOfParts(Type *Tp) const;
1689
1690 /// \returns The cost of the address computation. For most targets this can be
1691 /// merged into the instruction indexing mode. Some targets might want to
1692 /// distinguish between address computation for memory operations with vector
1693 /// pointer types and scalar pointer types. Such targets should override this
1694 /// function. \p SE holds the pointer for the scalar evolution object which
1695 /// was used in order to get the Ptr step value. \p Ptr holds the SCEV of the
1696 /// access pointer.
1700
1701 /// \returns The cost, if any, of keeping values of the given types alive
1702 /// over a callsite.
1703 ///
1704 /// Some types may require the use of register classes that do not have
1705 /// any callee-saved registers, so would require a spill and fill.
1708
1709 /// \returns True if the intrinsic is a supported memory intrinsic. Info
1710 /// will contain additional information - whether the intrinsic may write
1711 /// or read to memory, volatility and the pointer. Info is undefined
1712 /// if false is returned.
1714 MemIntrinsicInfo &Info) const;
1715
1716 /// \returns The maximum element size, in bytes, for an element
1717 /// unordered-atomic memory intrinsic.
1719
1720 /// \returns A value which is the result of the given memory intrinsic. If \p
1721 /// CanCreate is true, new instructions may be created to extract the result
1722 /// from the given intrinsic memory operation. Returns nullptr if the target
1723 /// cannot create a result from the given intrinsic.
1724 LLVM_ABI Value *
1726 bool CanCreate = true) const;
1727
1728 /// \returns The type to use in a loop expansion of a memcpy call.
1730 LLVMContext &Context, Value *Length, unsigned SrcAddrSpace,
1731 unsigned DestAddrSpace, Align SrcAlign, Align DestAlign,
1732 std::optional<uint32_t> AtomicElementSize = std::nullopt) const;
1733
1734 /// \param[out] OpsOut The operand types to copy RemainingBytes of memory.
1735 /// \param RemainingBytes The number of bytes to copy.
1736 ///
1737 /// Calculates the operand types to use when copying \p RemainingBytes of
1738 /// memory, where source and destination alignments are \p SrcAlign and
1739 /// \p DestAlign respectively.
1741 SmallVectorImpl<Type *> &OpsOut, LLVMContext &Context,
1742 unsigned RemainingBytes, unsigned SrcAddrSpace, unsigned DestAddrSpace,
1743 Align SrcAlign, Align DestAlign,
1744 std::optional<uint32_t> AtomicCpySize = std::nullopt) const;
1745
1746 /// \returns True if the two functions have compatible attributes for inlining
1747 /// purposes.
1748 LLVM_ABI bool areInlineCompatible(const Function *Caller,
1749 const Function *Callee) const;
1750
1751 /// Returns a penalty for invoking call \p Call in \p F.
1752 /// For example, if a function F calls a function G, which in turn calls
1753 /// function H, then getInlineCallPenalty(F, H()) would return the
1754 /// penalty of calling H from F, e.g. after inlining G into F.
1755 /// \p DefaultCallPenalty is passed to give a default penalty that
1756 /// the target can amend or override.
1757 LLVM_ABI unsigned getInlineCallPenalty(const Function *F,
1758 const CallBase &Call,
1759 unsigned DefaultCallPenalty) const;
1760
1761 /// \returns True if the caller and callee agree on how \p Types will be
1762 /// passed to or returned from the callee.
1763 /// to the callee.
1764 /// \param Types List of types to check.
1765 LLVM_ABI bool areTypesABICompatible(const Function *Caller,
1766 const Function *Callee,
1767 const ArrayRef<Type *> &Types) const;
1768
1769 /// The type of load/store indexing.
1771 MIM_Unindexed, ///< No indexing.
1772 MIM_PreInc, ///< Pre-incrementing.
1773 MIM_PreDec, ///< Pre-decrementing.
1774 MIM_PostInc, ///< Post-incrementing.
1775 MIM_PostDec ///< Post-decrementing.
1776 };
1777
1778 /// \returns True if the specified indexed load for the given type is legal.
1779 LLVM_ABI bool isIndexedLoadLegal(enum MemIndexedMode Mode, Type *Ty) const;
1780
1781 /// \returns True if the specified indexed store for the given type is legal.
1782 LLVM_ABI bool isIndexedStoreLegal(enum MemIndexedMode Mode, Type *Ty) const;
1783
1784 /// \returns The bitwidth of the largest vector type that should be used to
1785 /// load/store in the given address space.
1786 LLVM_ABI unsigned getLoadStoreVecRegBitWidth(unsigned AddrSpace) const;
1787
1788 /// \returns True if the load instruction is legal to vectorize.
1790
1791 /// \returns True if the store instruction is legal to vectorize.
1793
1794 /// \returns True if it is legal to vectorize the given load chain.
1795 LLVM_ABI bool isLegalToVectorizeLoadChain(unsigned ChainSizeInBytes,
1796 Align Alignment,
1797 unsigned AddrSpace) const;
1798
1799 /// \returns True if it is legal to vectorize the given store chain.
1800 LLVM_ABI bool isLegalToVectorizeStoreChain(unsigned ChainSizeInBytes,
1801 Align Alignment,
1802 unsigned AddrSpace) const;
1803
1804 /// \returns True if it is legal to vectorize the given reduction kind.
1806 ElementCount VF) const;
1807
1808 /// \returns True if the given type is supported for scalable vectors
1810
1811 /// \returns The new vector factor value if the target doesn't support \p
1812 /// SizeInBytes loads or has a better vector factor.
1813 LLVM_ABI unsigned getLoadVectorFactor(unsigned VF, unsigned LoadSize,
1814 unsigned ChainSizeInBytes,
1815 VectorType *VecTy) const;
1816
1817 /// \returns The new vector factor value if the target doesn't support \p
1818 /// SizeInBytes stores or has a better vector factor.
1819 LLVM_ABI unsigned getStoreVectorFactor(unsigned VF, unsigned StoreSize,
1820 unsigned ChainSizeInBytes,
1821 VectorType *VecTy) const;
1822
1823 /// \returns True if the target prefers fixed width vectorization if the
1824 /// loop vectorizer's cost-model assigns an equal cost to the fixed and
1825 /// scalable version of the vectorized loop.
1826 /// \p IsEpilogue is true if the decision is for the epilogue loop.
1827 LLVM_ABI bool preferFixedOverScalableIfEqualCost(bool IsEpilogue) const;
1828
1829 /// \returns True if target prefers SLP vectorizer with altermate opcode
1830 /// vectorization, false - otherwise.
1832
1833 /// \returns True if the target prefers reductions of \p Kind to be performed
1834 /// in the loop.
1835 LLVM_ABI bool preferInLoopReduction(RecurKind Kind, Type *Ty) const;
1836
1837 /// \returns True if the target prefers reductions select kept in the loop
1838 /// when tail folding. i.e.
1839 /// loop:
1840 /// p = phi (0, s)
1841 /// a = add (p, x)
1842 /// s = select (mask, a, p)
1843 /// vecreduce.add(s)
1844 ///
1845 /// As opposed to the normal scheme of p = phi (0, a) which allows the select
1846 /// to be pulled out of the loop. If the select(.., add, ..) can be predicated
1847 /// by the target, this can lead to cleaner code generation.
1849
1850 /// Return true if the loop vectorizer should consider vectorizing an
1851 /// otherwise scalar epilogue loop.
1853
1854 /// \returns True if the loop vectorizer should discard any VFs where the
1855 /// maximum register pressure exceeds getNumberOfRegisters.
1857
1858 /// \returns True if the target wants to expand the given reduction intrinsic
1859 /// into a shuffle sequence.
1861
1863
1864 /// \returns The shuffle sequence pattern used to expand the given reduction
1865 /// intrinsic.
1868
1869 /// \returns the size cost of rematerializing a GlobalValue address relative
1870 /// to a stack reload.
1871 LLVM_ABI unsigned getGISelRematGlobalCost() const;
1872
1873 /// \returns the lower bound of a trip count to decide on vectorization
1874 /// while tail-folding.
1876
1877 /// \returns True if the target supports scalable vectors.
1878 LLVM_ABI bool supportsScalableVectors() const;
1879
1880 /// \return true when scalable vectorization is preferred.
1882
1883 /// \name Vector Predication Information
1884 /// @{
1885 /// Whether the target supports the %evl parameter of VP intrinsic efficiently
1886 /// in hardware. (see LLVM Language Reference - "Vector Predication
1887 /// Intrinsics"). Use of %evl is discouraged when that is not the case.
1888 LLVM_ABI bool hasActiveVectorLength() const;
1889
1890 /// Return true if sinking I's operands to the same basic block as I is
1891 /// profitable, e.g. because the operands can be folded into a target
1892 /// instruction during instruction selection. After calling the function
1893 /// \p Ops contains the Uses to sink ordered by dominance (dominating users
1894 /// come first).
1897
1898 /// Return true if it's significantly cheaper to shift a vector by a uniform
1899 /// scalar than by an amount which will vary across each lane. On x86 before
1900 /// AVX2 for example, there is a "psllw" instruction for the former case, but
1901 /// no simple instruction for a general "a << b" operation on vectors.
1902 /// This should also apply to lowering for vector funnel shifts (rotates).
1904
1907 // keep the predicating parameter
1909 // where legal, discard the predicate parameter
1911 // transform into something else that is also predicating
1913 };
1914
1915 // How to transform the EVL parameter.
1916 // Legal: keep the EVL parameter as it is.
1917 // Discard: Ignore the EVL parameter where it is safe to do so.
1918 // Convert: Fold the EVL into the mask parameter.
1920
1921 // How to transform the operator.
1922 // Legal: The target supports this operator.
1923 // Convert: Convert this to a non-VP operation.
1924 // The 'Discard' strategy is invalid.
1926
1927 bool shouldDoNothing() const {
1928 return (EVLParamStrategy == Legal) && (OpStrategy == Legal);
1929 }
1932 };
1933
1934 /// \returns How the target needs this vector-predicated operation to be
1935 /// transformed.
1937 getVPLegalizationStrategy(const VPIntrinsic &PI) const;
1938 /// @}
1939
1940 /// \returns Whether a 32-bit branch instruction is available in Arm or Thumb
1941 /// state.
1942 ///
1943 /// Used by the LowerTypeTests pass, which constructs an IR inline assembler
1944 /// node containing a jump table in a format suitable for the target, so it
1945 /// needs to know what format of jump table it can legally use.
1946 ///
1947 /// For non-Arm targets, this function isn't used. It defaults to returning
1948 /// false, but it shouldn't matter what it returns anyway.
1949 LLVM_ABI bool hasArmWideBranch(bool Thumb) const;
1950
1951 /// Returns a bitmask constructed from the target-features or fmv-features
1952 /// metadata of a function.
1953 LLVM_ABI APInt getFeatureMask(const Function &F) const;
1954
1955 /// Returns true if this is an instance of a function with multiple versions.
1956 LLVM_ABI bool isMultiversionedFunction(const Function &F) const;
1957
1958 /// \return The maximum number of function arguments the target supports.
1959 LLVM_ABI unsigned getMaxNumArgs() const;
1960
1961 /// \return For an array of given Size, return alignment boundary to
1962 /// pad to. Default is no padding.
1963 LLVM_ABI unsigned getNumBytesToPadGlobalArray(unsigned Size,
1964 Type *ArrayType) const;
1965
1966 /// @}
1967
1968 /// Collect kernel launch bounds for \p F into \p LB.
1970 const Function &F,
1971 SmallVectorImpl<std::pair<StringRef, int64_t>> &LB) const;
1972
1973 /// Returns true if GEP should not be used to index into vectors for this
1974 /// target.
1976
1977private:
1978 std::unique_ptr<const TargetTransformInfoImplBase> TTIImpl;
1979};
1980
1981/// Analysis pass providing the \c TargetTransformInfo.
1982///
1983/// The core idea of the TargetIRAnalysis is to expose an interface through
1984/// which LLVM targets can analyze and provide information about the middle
1985/// end's target-independent IR. This supports use cases such as target-aware
1986/// cost modeling of IR constructs.
1987///
1988/// This is a function analysis because much of the cost modeling for targets
1989/// is done in a subtarget specific way and LLVM supports compiling different
1990/// functions targeting different subtargets in order to support runtime
1991/// dispatch according to the observed subtarget.
1992class TargetIRAnalysis : public AnalysisInfoMixin<TargetIRAnalysis> {
1993public:
1995
1996 /// Default construct a target IR analysis.
1997 ///
1998 /// This will use the module's datalayout to construct a baseline
1999 /// conservative TTI result.
2001
2002 /// Construct an IR analysis pass around a target-provide callback.
2003 ///
2004 /// The callback will be called with a particular function for which the TTI
2005 /// is needed and must return a TTI object for that function.
2006 LLVM_ABI
2007 TargetIRAnalysis(std::function<Result(const Function &)> TTICallback);
2008
2009 // Value semantics. We spell out the constructors for MSVC.
2011 : TTICallback(Arg.TTICallback) {}
2013 : TTICallback(std::move(Arg.TTICallback)) {}
2015 TTICallback = RHS.TTICallback;
2016 return *this;
2017 }
2019 TTICallback = std::move(RHS.TTICallback);
2020 return *this;
2021 }
2022
2024
2025private:
2027 LLVM_ABI static AnalysisKey Key;
2028
2029 /// The callback used to produce a result.
2030 ///
2031 /// We use a completely opaque callback so that targets can provide whatever
2032 /// mechanism they desire for constructing the TTI for a given function.
2033 ///
2034 /// FIXME: Should we really use std::function? It's relatively inefficient.
2035 /// It might be possible to arrange for even stateful callbacks to outlive
2036 /// the analysis and thus use a function_ref which would be lighter weight.
2037 /// This may also be less error prone as the callback is likely to reference
2038 /// the external TargetMachine, and that reference needs to never dangle.
2039 std::function<Result(const Function &)> TTICallback;
2040
2041 /// Helper function used as the callback in the default constructor.
2042 static Result getDefaultTTI(const Function &F);
2043};
2044
2045/// Wrapper pass for TargetTransformInfo.
2046///
2047/// This pass can be constructed from a TTI object which it stores internally
2048/// and is queried by passes.
2050 TargetIRAnalysis TIRA;
2051 std::optional<TargetTransformInfo> TTI;
2052
2053 virtual void anchor();
2054
2055public:
2056 static char ID;
2057
2058 /// We must provide a default constructor for the pass but it should
2059 /// never be used.
2060 ///
2061 /// Use the constructor below or call one of the creation routines.
2063
2065
2067};
2068
2069/// Create an analysis pass wrapper around a TTI object.
2070///
2071/// This analysis pass just holds the TTI instance and makes it available to
2072/// clients.
2075
2076} // namespace llvm
2077
2078#endif
This file implements a class to represent arbitrary precision integral constant values and operations...
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Atomic ordering constants.
Analysis containing CSE Info
Definition CSEInfo.cpp:27
#define LLVM_ABI
Definition Compiler.h:213
static cl::opt< OutputCostKind > CostKind("cost-kind", cl::desc("Target cost kind"), cl::init(OutputCostKind::RecipThroughput), cl::values(clEnumValN(OutputCostKind::RecipThroughput, "throughput", "Reciprocal throughput"), clEnumValN(OutputCostKind::Latency, "latency", "Instruction latency"), clEnumValN(OutputCostKind::CodeSize, "code-size", "Code size"), clEnumValN(OutputCostKind::SizeAndLatency, "size-latency", "Code size and latency"), clEnumValN(OutputCostKind::All, "all", "Print all cost kinds")))
TargetTransformInfo::VPLegalization VPLegalization
static cl::opt< bool > ForceNestedLoop("force-nested-hardware-loop", cl::Hidden, cl::init(false), cl::desc("Force allowance of nested hardware loops"))
static cl::opt< bool > ForceHardwareLoopPHI("force-hardware-loop-phi", cl::Hidden, cl::init(false), cl::desc("Force hardware loop counter to be updated through a phi"))
This header defines various interfaces for pass management in LLVM.
This file defines an InstructionCost class that is used when calculating the cost of an instruction,...
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
#define F(x, y, z)
Definition MD5.cpp:55
#define I(x, y, z)
Definition MD5.cpp:58
mir Rename Register Operands
uint64_t IntrinsicInst * II
static cl::opt< RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode > Mode("regalloc-enable-advisor", cl::Hidden, cl::init(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default), cl::desc("Enable regalloc advisor mode"), cl::values(clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default, "default", "Default"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Release, "release", "precompiled"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Development, "development", "for training")))
Value * RHS
Class for arbitrary precision integers.
Definition APInt.h:78
an instruction to allocate memory on the stack
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:41
Class to represent array types.
A cache of @llvm.assume calls within a function.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
BlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate IR basic block frequen...
Conditional or Unconditional Branch instruction.
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:678
This is an important base class in LLVM.
Definition Constant.h:43
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:63
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:165
Convenience struct for specifying and reasoning about fast-math flags.
Definition FMF.h:22
ImmutablePass class - This class is used to provide information that does not need to be run.
Definition Pass.h:285
ImmutablePass(char &pid)
Definition Pass.h:287
The core instruction combiner logic.
static InstructionCost getInvalid(CostType Val=0)
Class to represent integer types.
Drive the analysis of interleaved memory accesses in the loop.
const TargetLibraryInfo * getLibInfo() const
const SmallVectorImpl< Type * > & getArgTypes() const
const SmallVectorImpl< const Value * > & getArgs() const
LLVM_ABI IntrinsicCostAttributes(Intrinsic::ID Id, const CallBase &CI, InstructionCost ScalarCost=InstructionCost::getInvalid(), bool TypeBasedOnly=false, TargetLibraryInfo const *LibInfo=nullptr)
InstructionCost getScalarizationCost() const
const IntrinsicInst * getInst() const
A wrapper class for inspecting calls to intrinsic functions.
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:68
An instruction for reading from memory.
LoopVectorizationLegality checks if it is legal to vectorize a loop, and to what vectorization factor...
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
The optimization diagnostic interface.
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
Analysis providing profile information.
The RecurrenceDescriptor is used to identify recurrences variables in a loop.
This class represents an analyzed expression in the program.
The main scalar evolution driver.
This is a 'bitvector' (really, a variable-sized bit array), optimized for the case when the array is ...
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StackOffset holds a fixed and a scalable offset in bytes.
Definition TypeSize.h:31
An instruction for storing to memory.
Multiway switch.
Analysis pass providing the TargetTransformInfo.
TargetIRAnalysis(const TargetIRAnalysis &Arg)
TargetIRAnalysis & operator=(const TargetIRAnalysis &RHS)
LLVM_ABI Result run(const Function &F, FunctionAnalysisManager &)
LLVM_ABI TargetIRAnalysis()
Default construct a target IR analysis.
TargetIRAnalysis & operator=(TargetIRAnalysis &&RHS)
TargetIRAnalysis(TargetIRAnalysis &&Arg)
Provides information about what library functions are available for the current target.
Base class for use as a mix-in that aids implementing a TargetTransformInfo-compatible class.
TargetTransformInfoWrapperPass()
We must provide a default constructor for the pass but it should never be used.
TargetTransformInfo & getTTI(const Function &F)
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
LLVM_ABI bool getTgtMemIntrinsic(IntrinsicInst *Inst, MemIntrinsicInfo &Info) const
LLVM_ABI Value * getOrCreateResultFromMemIntrinsic(IntrinsicInst *Inst, Type *ExpectedType, bool CanCreate=true) const
LLVM_ABI bool isLegalToVectorizeLoad(LoadInst *LI) const
LLVM_ABI std::optional< unsigned > getVScaleForTuning() const
static LLVM_ABI CastContextHint getCastContextHint(const Instruction *I)
Calculates a CastContextHint from I.
LLVM_ABI unsigned getMaxNumArgs() const
LLVM_ABI bool addrspacesMayAlias(unsigned AS0, unsigned AS1) const
Return false if a AS0 address cannot possibly alias a AS1 address.
LLVM_ABI bool isLegalMaskedScatter(Type *DataType, Align Alignment) const
Return true if the target supports masked scatter.
LLVM_ABI InstructionCost getStridedMemoryOpCost(unsigned Opcode, Type *DataTy, const Value *Ptr, bool VariableMask, Align Alignment, TTI::TargetCostKind CostKind=TTI::TCK_RecipThroughput, const Instruction *I=nullptr) const
LLVM_ABI bool shouldBuildLookupTables() const
Return true if switches should be turned into lookup tables for the target.
LLVM_ABI bool isLegalToVectorizeStore(StoreInst *SI) const
LLVM_ABI InstructionCost getVectorInstrCost(unsigned Opcode, Type *Val, TTI::TargetCostKind CostKind, unsigned Index=-1, const Value *Op0=nullptr, const Value *Op1=nullptr) const
LLVM_ABI InstructionCost getMulAccReductionCost(bool IsUnsigned, unsigned RedOpcode, Type *ResTy, VectorType *Ty, TTI::TargetCostKind CostKind=TTI::TCK_RecipThroughput) const
Calculate the cost of an extended reduction pattern, similar to getArithmeticReductionCost of an Add/...
LLVM_ABI bool enableAggressiveInterleaving(bool LoopHasReductions) const
Don't restrict interleaved unrolling to small loops.
LLVM_ABI InstructionCost getScalarizationOverhead(VectorType *Ty, const APInt &DemandedElts, bool Insert, bool Extract, TTI::TargetCostKind CostKind, bool ForPoisonSrc=true, ArrayRef< Value * > VL={}) const
Estimate the overhead of scalarizing an instruction.
LLVM_ABI bool isLegalMaskedLoad(Type *DataType, Align Alignment, unsigned AddressSpace) const
Return true if the target supports masked load.
LLVM_ABI bool isMultiversionedFunction(const Function &F) const
Returns true if this is an instance of a function with multiple versions.
LLVM_ABI bool isFCmpOrdCheaperThanFCmpZero(Type *Ty) const
Return true if it is faster to check if a floating-point value is NaN (or not-NaN) versus a compariso...
LLVM_ABI bool supportsEfficientVectorElementLoadStore() const
If target has efficient vector element load/store instructions, it can return true here so that inser...
LLVM_ABI bool isAlwaysUniform(const Value *V) const
LLVM_ABI unsigned getAssumedAddrSpace(const Value *V) const
LLVM_ABI bool preferAlternateOpcodeVectorization() const
LLVM_ABI bool shouldDropLSRSolutionIfLessProfitable() const
Return true if LSR should drop a found solution if it's calculated to be less profitable than the bas...
LLVM_ABI bool isLSRCostLess(const TargetTransformInfo::LSRCost &C1, const TargetTransformInfo::LSRCost &C2) const
Return true if LSR cost of C1 is lower than C2.
LLVM_ABI unsigned getPrefetchDistance() const
LLVM_ABI Type * getMemcpyLoopLoweringType(LLVMContext &Context, Value *Length, unsigned SrcAddrSpace, unsigned DestAddrSpace, Align SrcAlign, Align DestAlign, std::optional< uint32_t > AtomicElementSize=std::nullopt) const
LLVM_ABI bool isLegalMaskedExpandLoad(Type *DataType, Align Alignment) const
Return true if the target supports masked expand load.
LLVM_ABI bool prefersVectorizedAddressing() const
Return true if target doesn't mind addresses in vectors.
LLVM_ABI InstructionCost getCmpSelInstrCost(unsigned Opcode, Type *ValTy, Type *CondTy, CmpInst::Predicate VecPred, TTI::TargetCostKind CostKind=TTI::TCK_RecipThroughput, OperandValueInfo Op1Info={OK_AnyValue, OP_None}, OperandValueInfo Op2Info={OK_AnyValue, OP_None}, const Instruction *I=nullptr) const
LLVM_ABI bool hasBranchDivergence(const Function *F=nullptr) const
Return true if branch divergence exists.
LLVM_ABI MemCmpExpansionOptions enableMemCmpExpansion(bool OptSize, bool IsZeroCmp) const
bool invalidate(Function &, const PreservedAnalyses &, FunctionAnalysisManager::Invalidator &)
Handle the invalidation of this information.
LLVM_ABI void getUnrollingPreferences(Loop *L, ScalarEvolution &, UnrollingPreferences &UP, OptimizationRemarkEmitter *ORE) const
Get target-customized preferences for the generic loop unrolling transformation.
LLVM_ABI bool shouldBuildLookupTablesForConstant(Constant *C) const
Return true if switches should be turned into lookup tables containing this constant value for the ta...
LLVM_ABI bool supportsTailCallFor(const CallBase *CB) const
If target supports tail call on CB.
LLVM_ABI std::optional< Instruction * > instCombineIntrinsic(InstCombiner &IC, IntrinsicInst &II) const
Targets can implement their own combinations for target-specific intrinsics.
LLVM_ABI bool isProfitableLSRChainElement(Instruction *I) const
LLVM_ABI TypeSize getRegisterBitWidth(RegisterKind K) const
LLVM_ABI unsigned getInlineCallPenalty(const Function *F, const CallBase &Call, unsigned DefaultCallPenalty) const
Returns a penalty for invoking call Call in F.
LLVM_ABI bool hasActiveVectorLength() const
LLVM_ABI bool isExpensiveToSpeculativelyExecute(const Instruction *I) const
Return true if the cost of the instruction is too high to speculatively execute and should be kept be...
LLVM_ABI bool preferFixedOverScalableIfEqualCost(bool IsEpilogue) const
LLVM_ABI bool isLegalMaskedGather(Type *DataType, Align Alignment) const
Return true if the target supports masked gather.
LLVM_ABI InstructionCost getMemoryOpCost(unsigned Opcode, Type *Src, Align Alignment, unsigned AddressSpace, TTI::TargetCostKind CostKind=TTI::TCK_RecipThroughput, OperandValueInfo OpdInfo={OK_AnyValue, OP_None}, const Instruction *I=nullptr) const
LLVM_ABI std::optional< unsigned > getMaxVScale() const
LLVM_ABI InstructionCost getReplicationShuffleCost(Type *EltTy, int ReplicationFactor, int VF, const APInt &DemandedDstElts, TTI::TargetCostKind CostKind) const
LLVM_ABI bool allowVectorElementIndexingUsingGEP() const
Returns true if GEP should not be used to index into vectors for this target.
LLVM_ABI InstructionCost getInterleavedMemoryOpCost(unsigned Opcode, Type *VecTy, unsigned Factor, ArrayRef< unsigned > Indices, Align Alignment, unsigned AddressSpace, TTI::TargetCostKind CostKind=TTI::TCK_RecipThroughput, bool UseMaskForCond=false, bool UseMaskForGaps=false) const
LLVM_ABI bool isSingleThreaded() const
LLVM_ABI std::optional< Value * > simplifyDemandedVectorEltsIntrinsic(InstCombiner &IC, IntrinsicInst &II, APInt DemandedElts, APInt &UndefElts, APInt &UndefElts2, APInt &UndefElts3, std::function< void(Instruction *, unsigned, APInt, APInt &)> SimplifyAndSetOp) const
Can be used to implement target-specific instruction combining.
LLVM_ABI bool enableOrderedReductions() const
Return true if we should be enabling ordered reductions for the target.
InstructionCost getInstructionCost(const User *U, TargetCostKind CostKind) const
This is a helper function which calls the three-argument getInstructionCost with Operands which are t...
LLVM_ABI unsigned getInliningCostBenefitAnalysisProfitableMultiplier() const
LLVM_ABI InstructionCost getShuffleCost(ShuffleKind Kind, VectorType *DstTy, VectorType *SrcTy, ArrayRef< int > Mask={}, TTI::TargetCostKind CostKind=TTI::TCK_RecipThroughput, int Index=0, VectorType *SubTp=nullptr, ArrayRef< const Value * > Args={}, const Instruction *CxtI=nullptr) const
LLVM_ABI InstructionCost getIntrinsicInstrCost(const IntrinsicCostAttributes &ICA, TTI::TargetCostKind CostKind) const
LLVM_ABI InstructionCost getArithmeticReductionCost(unsigned Opcode, VectorType *Ty, std::optional< FastMathFlags > FMF, TTI::TargetCostKind CostKind=TTI::TCK_RecipThroughput) const
Calculate the cost of vector reduction intrinsics.
LLVM_ABI unsigned getAtomicMemIntrinsicMaxElementSize() const
LLVM_ABI InstructionCost getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src, TTI::CastContextHint CCH, TTI::TargetCostKind CostKind=TTI::TCK_SizeAndLatency, const Instruction *I=nullptr) const
LLVM_ABI bool LSRWithInstrQueries() const
Return true if the loop strength reduce pass should make Instruction* based TTI queries to isLegalAdd...
LLVM_ABI unsigned getStoreVectorFactor(unsigned VF, unsigned StoreSize, unsigned ChainSizeInBytes, VectorType *VecTy) const
LLVM_ABI VPLegalization getVPLegalizationStrategy(const VPIntrinsic &PI) const
static LLVM_ABI PartialReductionExtendKind getPartialReductionExtendKind(Instruction *I)
Get the kind of extension that an instruction represents.
LLVM_ABI bool shouldConsiderVectorizationRegPressure() const
LLVM_ABI bool enableWritePrefetching() const
LLVM_ABI bool shouldTreatInstructionLikeSelect(const Instruction *I) const
Should the Select Optimization pass treat the given instruction like a select, potentially converting...
LLVM_ABI bool isNoopAddrSpaceCast(unsigned FromAS, unsigned ToAS) const
LLVM_ABI bool shouldMaximizeVectorBandwidth(TargetTransformInfo::RegisterKind K) const
LLVM_ABI TailFoldingStyle getPreferredTailFoldingStyle(bool IVUpdateMayOverflow=true) const
Query the target what the preferred style of tail folding is.
LLVM_ABI InstructionCost getGEPCost(Type *PointeeType, const Value *Ptr, ArrayRef< const Value * > Operands, Type *AccessType=nullptr, TargetCostKind CostKind=TCK_SizeAndLatency) const
Estimate the cost of a GEP operation when lowered.
LLVM_ABI bool isLegalToVectorizeStoreChain(unsigned ChainSizeInBytes, Align Alignment, unsigned AddrSpace) const
LLVM_ABI bool isLegalInterleavedAccessType(VectorType *VTy, unsigned Factor, Align Alignment, unsigned AddrSpace) const
Return true is the target supports interleaved access for the given vector type VTy,...
LLVM_ABI unsigned getRegUsageForType(Type *Ty) const
Returns the estimated number of registers required to represent Ty.
LLVM_ABI bool isLegalBroadcastLoad(Type *ElementTy, ElementCount NumElements) const
\Returns true if the target supports broadcasting a load to a vector of type <NumElements x ElementTy...
LLVM_ABI bool isIndexedStoreLegal(enum MemIndexedMode Mode, Type *Ty) const
LLVM_ABI std::pair< const Value *, unsigned > getPredicatedAddrSpace(const Value *V) const
LLVM_ABI InstructionCost getExtendedReductionCost(unsigned Opcode, bool IsUnsigned, Type *ResTy, VectorType *Ty, std::optional< FastMathFlags > FMF, TTI::TargetCostKind CostKind=TTI::TCK_RecipThroughput) const
Calculate the cost of an extended reduction pattern, similar to getArithmeticReductionCost of a reduc...
LLVM_ABI unsigned getLoadStoreVecRegBitWidth(unsigned AddrSpace) const
LLVM_ABI ReductionShuffle getPreferredExpandedReductionShuffle(const IntrinsicInst *II) const
static LLVM_ABI OperandValueInfo getOperandInfo(const Value *V)
Collect properties of V used in cost analysis, e.g. OP_PowerOf2.
LLVM_ABI unsigned getRegisterClassForType(bool Vector, Type *Ty=nullptr) const
LLVM_ABI bool isLegalAddressingMode(Type *Ty, GlobalValue *BaseGV, int64_t BaseOffset, bool HasBaseReg, int64_t Scale, unsigned AddrSpace=0, Instruction *I=nullptr, int64_t ScalableOffset=0) const
Return true if the addressing mode represented by AM is legal for this target, for a load/store of th...
LLVM_ABI PopcntSupportKind getPopcntSupport(unsigned IntTyWidthInBit) const
Return hardware support for population count.
LLVM_ABI unsigned getEstimatedNumberOfCaseClusters(const SwitchInst &SI, unsigned &JTSize, ProfileSummaryInfo *PSI, BlockFrequencyInfo *BFI) const
LLVM_ABI bool isElementTypeLegalForScalableVector(Type *Ty) const
LLVM_ABI bool forceScalarizeMaskedGather(VectorType *Type, Align Alignment) const
Return true if the target forces scalarizing of llvm.masked.gather intrinsics.
LLVM_ABI unsigned getMaxPrefetchIterationsAhead() const
LLVM_ABI bool canHaveNonUndefGlobalInitializerInAddressSpace(unsigned AS) const
Return true if globals in this address space can have initializers other than undef.
LLVM_ABI ElementCount getMinimumVF(unsigned ElemWidth, bool IsScalable) const
LLVM_ABI InstructionCost getIntImmCostIntrin(Intrinsic::ID IID, unsigned Idx, const APInt &Imm, Type *Ty, TargetCostKind CostKind) const
LLVM_ABI bool enableMaskedInterleavedAccessVectorization() const
Enable matching of interleaved access groups that contain predicated accesses or gaps and therefore v...
LLVM_ABI InstructionCost getIntImmCostInst(unsigned Opc, unsigned Idx, const APInt &Imm, Type *Ty, TargetCostKind CostKind, Instruction *Inst=nullptr) const
Return the expected cost of materialization for the given integer immediate of the specified type for...
LLVM_ABI bool isLegalStridedLoadStore(Type *DataType, Align Alignment) const
Return true if the target supports strided load.
LLVM_ABI TargetTransformInfo & operator=(TargetTransformInfo &&RHS)
LLVM_ABI InstructionCost getMinMaxReductionCost(Intrinsic::ID IID, VectorType *Ty, FastMathFlags FMF=FastMathFlags(), TTI::TargetCostKind CostKind=TTI::TCK_RecipThroughput) const
TargetCostKind
The kind of cost model.
@ TCK_RecipThroughput
Reciprocal throughput.
@ TCK_CodeSize
Instruction code size.
@ TCK_SizeAndLatency
The weighted sum of size and latency.
@ TCK_Latency
The latency of instruction.
LLVM_ABI InstructionCost getArithmeticInstrCost(unsigned Opcode, Type *Ty, TTI::TargetCostKind CostKind=TTI::TCK_RecipThroughput, TTI::OperandValueInfo Opd1Info={TTI::OK_AnyValue, TTI::OP_None}, TTI::OperandValueInfo Opd2Info={TTI::OK_AnyValue, TTI::OP_None}, ArrayRef< const Value * > Args={}, const Instruction *CxtI=nullptr, const TargetLibraryInfo *TLibInfo=nullptr) const
This is an approximation of reciprocal throughput of a math/logic op.
LLVM_ABI bool areTypesABICompatible(const Function *Caller, const Function *Callee, const ArrayRef< Type * > &Types) const
LLVM_ABI bool enableSelectOptimize() const
Should the Select Optimization pass be enabled and ran.
LLVM_ABI bool collectFlatAddressOperands(SmallVectorImpl< int > &OpIndexes, Intrinsic::ID IID) const
Return any intrinsic address operand indexes which may be rewritten if they use a flat address space ...
OperandValueProperties
Additional properties of an operand's values.
LLVM_ABI int getInliningLastCallToStaticBonus() const
LLVM_ABI InstructionCost getPointersChainCost(ArrayRef< const Value * > Ptrs, const Value *Base, const PointersChainInfo &Info, Type *AccessTy, TargetCostKind CostKind=TTI::TCK_RecipThroughput) const
Estimate the cost of a chain of pointers (typically pointer operands of a chain of loads or stores wi...
LLVM_ABI bool isVScaleKnownToBeAPowerOfTwo() const
LLVM_ABI bool isIndexedLoadLegal(enum MemIndexedMode Mode, Type *Ty) const
LLVM_ABI unsigned getMaximumVF(unsigned ElemWidth, unsigned Opcode) const
LLVM_ABI bool isSourceOfDivergence(const Value *V) const
Returns whether V is a source of divergence.
LLVM_ABI bool isLegalICmpImmediate(int64_t Imm) const
Return true if the specified immediate is legal icmp immediate, that is the target has icmp instructi...
LLVM_ABI bool isTypeLegal(Type *Ty) const
Return true if this type is legal.
static bool requiresOrderedReduction(std::optional< FastMathFlags > FMF)
A helper function to determine the type of reduction algorithm used for a given Opcode and set of Fas...
LLVM_ABI bool isLegalToVectorizeReduction(const RecurrenceDescriptor &RdxDesc, ElementCount VF) const
LLVM_ABI std::optional< unsigned > getCacheAssociativity(CacheLevel Level) const
LLVM_ABI bool isLegalNTLoad(Type *DataType, Align Alignment) const
Return true if the target supports nontemporal load.
LLVM_ABI InstructionCost getMemcpyCost(const Instruction *I) const
LLVM_ABI unsigned adjustInliningThreshold(const CallBase *CB) const
LLVM_ABI bool isLegalAddImmediate(int64_t Imm) const
Return true if the specified immediate is legal add immediate, that is the target has add instruction...
LLVM_ABI bool isTargetIntrinsicWithStructReturnOverloadAtField(Intrinsic::ID ID, int RetIdx) const
Identifies if the vector form of the intrinsic that returns a struct is overloaded at the struct elem...
LLVM_ABI unsigned getLoadVectorFactor(unsigned VF, unsigned LoadSize, unsigned ChainSizeInBytes, VectorType *VecTy) const
LLVM_ABI InstructionCost getMaskedMemoryOpCost(unsigned Opcode, Type *Src, Align Alignment, unsigned AddressSpace, TTI::TargetCostKind CostKind=TTI::TCK_RecipThroughput) const
LLVM_ABI bool canSaveCmp(Loop *L, BranchInst **BI, ScalarEvolution *SE, LoopInfo *LI, DominatorTree *DT, AssumptionCache *AC, TargetLibraryInfo *LibInfo) const
Return true if the target can save a compare for loop count, for example hardware loop saves a compar...
LLVM_ABI bool isTargetIntrinsicTriviallyScalarizable(Intrinsic::ID ID) const
LLVM_ABI Value * rewriteIntrinsicWithAddressSpace(IntrinsicInst *II, Value *OldV, Value *NewV) const
Rewrite intrinsic call II such that OldV will be replaced with NewV, which has a different address sp...
LLVM_ABI InstructionCost getCostOfKeepingLiveOverCall(ArrayRef< Type * > Tys) const
LLVM_ABI unsigned getMinPrefetchStride(unsigned NumMemAccesses, unsigned NumStridedMemAccesses, unsigned NumPrefetches, bool HasCall) const
Some HW prefetchers can handle accesses up to a certain constant stride.
LLVM_ABI bool shouldPrefetchAddressSpace(unsigned AS) const
LLVM_ABI InstructionCost getIntImmCost(const APInt &Imm, Type *Ty, TargetCostKind CostKind) const
Return the expected cost of materializing for the given integer immediate of the specified type.
LLVM_ABI unsigned getMinVectorRegisterBitWidth() const
LLVM_ABI InstructionCost getAddressComputationCost(Type *PtrTy, ScalarEvolution *SE, const SCEV *Ptr, TTI::TargetCostKind CostKind) const
LLVM_ABI bool isLegalNTStore(Type *DataType, Align Alignment) const
Return true if the target supports nontemporal store.
LLVM_ABI InstructionCost getPartialReductionCost(unsigned Opcode, Type *InputTypeA, Type *InputTypeB, Type *AccumType, ElementCount VF, PartialReductionExtendKind OpAExtend, PartialReductionExtendKind OpBExtend, std::optional< unsigned > BinOp, TTI::TargetCostKind CostKind) const
LLVM_ABI unsigned getFlatAddressSpace() const
Returns the address space ID for a target's 'flat' address space.
LLVM_ABI bool preferToKeepConstantsAttached(const Instruction &Inst, const Function &Fn) const
It can be advantageous to detach complex constants from their uses to make their generation cheaper.
LLVM_ABI bool hasArmWideBranch(bool Thumb) const
LLVM_ABI const char * getRegisterClassName(unsigned ClassID) const
LLVM_ABI bool preferEpilogueVectorization() const
Return true if the loop vectorizer should consider vectorizing an otherwise scalar epilogue loop.
LLVM_ABI bool shouldConsiderAddressTypePromotion(const Instruction &I, bool &AllowPromotionWithoutCommonHeader) const
LLVM_ABI BranchProbability getPredictableBranchThreshold() const
If a branch or a select condition is skewed in one direction by more than this factor,...
LLVM_ABI TargetTransformInfo(std::unique_ptr< const TargetTransformInfoImplBase > Impl)
Construct a TTI object using a type implementing the Concept API below.
LLVM_ABI bool preferInLoopReduction(RecurKind Kind, Type *Ty) const
LLVM_ABI unsigned getCallerAllocaCost(const CallBase *CB, const AllocaInst *AI) const
LLVM_ABI bool hasConditionalLoadStoreForType(Type *Ty, bool IsStore) const
LLVM_ABI unsigned getCacheLineSize() const
LLVM_ABI bool allowsMisalignedMemoryAccesses(LLVMContext &Context, unsigned BitWidth, unsigned AddressSpace=0, Align Alignment=Align(1), unsigned *Fast=nullptr) const
Determine if the target supports unaligned memory accesses.
LLVM_ABI InstructionCost getGatherScatterOpCost(unsigned Opcode, Type *DataTy, const Value *Ptr, bool VariableMask, Align Alignment, TTI::TargetCostKind CostKind=TTI::TCK_RecipThroughput, const Instruction *I=nullptr) const
LLVM_ABI int getInlinerVectorBonusPercent() const
LLVM_ABI unsigned getEpilogueVectorizationMinVF() const
LLVM_ABI void collectKernelLaunchBounds(const Function &F, SmallVectorImpl< std::pair< StringRef, int64_t > > &LB) const
Collect kernel launch bounds for F into LB.
PopcntSupportKind
Flags indicating the kind of support for population count.
LLVM_ABI bool preferPredicatedReductionSelect() const
LLVM_ABI InstructionCost getIntImmCodeSizeCost(unsigned Opc, unsigned Idx, const APInt &Imm, Type *Ty) const
Return the expected cost for the given integer when optimising for size.
LLVM_ABI AddressingModeKind getPreferredAddressingMode(const Loop *L, ScalarEvolution *SE) const
Return the preferred addressing mode LSR should make efforts to generate.
LLVM_ABI bool isLoweredToCall(const Function *F) const
Test whether calls to a function lower to actual program function calls.
LLVM_ABI bool isLegalMaskedStore(Type *DataType, Align Alignment, unsigned AddressSpace) const
Return true if the target supports masked store.
LLVM_ABI bool isLegalToVectorizeLoadChain(unsigned ChainSizeInBytes, Align Alignment, unsigned AddrSpace) const
LLVM_ABI bool isHardwareLoopProfitable(Loop *L, ScalarEvolution &SE, AssumptionCache &AC, TargetLibraryInfo *LibInfo, HardwareLoopInfo &HWLoopInfo) const
Query the target whether it would be profitable to convert the given loop into a hardware loop.
LLVM_ABI unsigned getInliningThresholdMultiplier() const
LLVM_ABI InstructionCost getBranchMispredictPenalty() const
Returns estimated penalty of a branch misprediction in latency.
LLVM_ABI unsigned getNumberOfRegisters(unsigned ClassID) const
LLVM_ABI bool isLegalAltInstr(VectorType *VecTy, unsigned Opcode0, unsigned Opcode1, const SmallBitVector &OpcodeMask) const
Return true if this is an alternating opcode pattern that can be lowered to a single instruction on t...
LLVM_ABI bool isProfitableToHoist(Instruction *I) const
Return true if it is profitable to hoist instruction in the then/else to before if.
LLVM_ABI bool supportsScalableVectors() const
LLVM_ABI bool hasVolatileVariant(Instruction *I, unsigned AddrSpace) const
Return true if the given instruction (assumed to be a memory access instruction) has a volatile varia...
LLVM_ABI bool isLegalMaskedCompressStore(Type *DataType, Align Alignment) const
Return true if the target supports masked compress store.
LLVM_ABI std::optional< unsigned > getMinPageSize() const
LLVM_ABI bool isFPVectorizationPotentiallyUnsafe() const
Indicate that it is potentially unsafe to automatically vectorize floating-point operations because t...
LLVM_ABI InstructionCost getInsertExtractValueCost(unsigned Opcode, TTI::TargetCostKind CostKind) const
LLVM_ABI bool shouldBuildRelLookupTables() const
Return true if lookup tables should be turned into relative lookup tables.
LLVM_ABI unsigned getStoreMinimumVF(unsigned VF, Type *ScalarMemTy, Type *ScalarValTy) const
LLVM_ABI std::optional< unsigned > getCacheSize(CacheLevel Level) const
LLVM_ABI std::optional< Value * > simplifyDemandedUseBitsIntrinsic(InstCombiner &IC, IntrinsicInst &II, APInt DemandedMask, KnownBits &Known, bool &KnownBitsComputed) const
Can be used to implement target-specific instruction combining.
LLVM_ABI bool isLegalAddScalableImmediate(int64_t Imm) const
Return true if adding the specified scalable immediate is legal, that is the target has add instructi...
LLVM_ABI bool isTargetIntrinsicWithScalarOpAtArg(Intrinsic::ID ID, unsigned ScalarOpdIdx) const
Identifies if the vector form of the intrinsic has a scalar operand.
LLVM_ABI bool hasDivRemOp(Type *DataType, bool IsSigned) const
Return true if the target has a unified operation to calculate division and remainder.
LLVM_ABI InstructionCost getAltInstrCost(VectorType *VecTy, unsigned Opcode0, unsigned Opcode1, const SmallBitVector &OpcodeMask, TTI::TargetCostKind CostKind=TTI::TCK_RecipThroughput) const
Returns the cost estimation for alternating opcode pattern that can be lowered to a single instructio...
TargetCostConstants
Underlying constants for 'cost' values in this interface.
@ TCC_Expensive
The cost of a 'div' instruction on x86.
@ TCC_Free
Expected to fold away in lowering.
@ TCC_Basic
The cost of a typical 'add' instruction.
LLVM_ABI bool enableInterleavedAccessVectorization() const
Enable matching of interleaved access groups.
LLVM_ABI unsigned getMinTripCountTailFoldingThreshold() const
LLVM_ABI InstructionCost getInstructionCost(const User *U, ArrayRef< const Value * > Operands, TargetCostKind CostKind) const
Estimate the cost of a given IR user when lowered.
LLVM_ABI unsigned getMaxInterleaveFactor(ElementCount VF) const
LLVM_ABI bool enableScalableVectorization() const
LLVM_ABI bool isVectorShiftByScalarCheap(Type *Ty) const
Return true if it's significantly cheaper to shift a vector by a uniform scalar than by an amount whi...
LLVM_ABI bool isNumRegsMajorCostOfLSR() const
Return true if LSR major cost is number of registers.
LLVM_ABI unsigned getInliningCostBenefitAnalysisSavingsMultiplier() const
LLVM_ABI bool isLegalMaskedVectorHistogram(Type *AddrType, Type *DataType) const
LLVM_ABI InstructionCost getExpandCompressMemoryOpCost(unsigned Opcode, Type *DataTy, bool VariableMask, Align Alignment, TTI::TargetCostKind CostKind=TTI::TCK_RecipThroughput, const Instruction *I=nullptr) const
LLVM_ABI unsigned getGISelRematGlobalCost() const
LLVM_ABI unsigned getNumBytesToPadGlobalArray(unsigned Size, Type *ArrayType) const
MemIndexedMode
The type of load/store indexing.
LLVM_ABI InstructionCost getIndexedVectorInstrCostFromEnd(unsigned Opcode, Type *Val, TTI::TargetCostKind CostKind, unsigned Index) const
LLVM_ABI bool areInlineCompatible(const Function *Caller, const Function *Callee) const
LLVM_ABI bool useColdCCForColdCall(Function &F) const
Return true if the input function which is cold at all call sites, should use coldcc calling conventi...
LLVM_ABI InstructionCost getFPOpCost(Type *Ty) const
Return the expected cost of supporting the floating point operation of the specified type.
LLVM_ABI bool supportsTailCalls() const
If the target supports tail calls.
LLVM_ABI bool canMacroFuseCmp() const
Return true if the target can fuse a compare and branch.
LLVM_ABI bool isValidAddrSpaceCast(unsigned FromAS, unsigned ToAS) const
Query the target whether the specified address space cast from FromAS to ToAS is valid.
LLVM_ABI unsigned getNumberOfParts(Type *Tp) const
LLVM_ABI InstructionCost getOperandsScalarizationOverhead(ArrayRef< Type * > Tys, TTI::TargetCostKind CostKind) const
Estimate the overhead of scalarizing operands with the given types.
AddressingModeKind
Which addressing mode Loop Strength Reduction will try to generate.
@ AMK_PostIndexed
Prefer post-indexed addressing mode.
@ AMK_All
Consider all addressing modes.
@ AMK_PreIndexed
Prefer pre-indexed addressing mode.
@ AMK_None
Don't prefer any addressing mode.
LLVM_ABI InstructionCost getVPMemoryOpCost(unsigned Opcode, Type *Src, Align Alignment, unsigned AddressSpace, TTI::TargetCostKind CostKind=TTI::TCK_RecipThroughput, const Instruction *I=nullptr) const
LLVM_ABI InstructionCost getScalingFactorCost(Type *Ty, GlobalValue *BaseGV, StackOffset BaseOffset, bool HasBaseReg, int64_t Scale, unsigned AddrSpace=0) const
Return the cost of the scaling factor used in the addressing mode represented by AM for this target,...
LLVM_ABI bool isTruncateFree(Type *Ty1, Type *Ty2) const
Return true if it's free to truncate a value of type Ty1 to type Ty2.
LLVM_ABI bool isProfitableToSinkOperands(Instruction *I, SmallVectorImpl< Use * > &Ops) const
Return true if sinking I's operands to the same basic block as I is profitable, e....
LLVM_ABI void getMemcpyLoopResidualLoweringType(SmallVectorImpl< Type * > &OpsOut, LLVMContext &Context, unsigned RemainingBytes, unsigned SrcAddrSpace, unsigned DestAddrSpace, Align SrcAlign, Align DestAlign, std::optional< uint32_t > AtomicCpySize=std::nullopt) const
LLVM_ABI bool preferPredicateOverEpilogue(TailFoldingInfo *TFI) const
Query the target whether it would be prefered to create a predicated vector loop, which can avoid the...
LLVM_ABI bool forceScalarizeMaskedScatter(VectorType *Type, Align Alignment) const
Return true if the target forces scalarizing of llvm.masked.scatter intrinsics.
LLVM_ABI bool isTargetIntrinsicWithOverloadTypeAtArg(Intrinsic::ID ID, int OpdIdx) const
Identifies if the vector form of the intrinsic is overloaded on the type of the operand at index OpdI...
LLVM_ABI bool haveFastSqrt(Type *Ty) const
Return true if the hardware has a fast square-root instruction.
LLVM_ABI bool shouldExpandReduction(const IntrinsicInst *II) const
LLVM_ABI uint64_t getMaxMemIntrinsicInlineSizeThreshold() const
Returns the maximum memset / memcpy size in bytes that still makes it profitable to inline the call.
ShuffleKind
The various kinds of shuffle patterns for vector queries.
@ SK_InsertSubvector
InsertSubvector. Index indicates start offset.
@ SK_Select
Selects elements from the corresponding lane of either source operand.
@ SK_PermuteSingleSrc
Shuffle elements of single source vector with any shuffle mask.
@ SK_Transpose
Transpose two vectors.
@ SK_Splice
Concatenates elements from the first input vector with elements of the second input vector.
@ SK_Broadcast
Broadcast element 0 to all other elements.
@ SK_PermuteTwoSrc
Merge elements from two source vectors into one with any shuffle mask.
@ SK_Reverse
Reverse the order of the vector.
@ SK_ExtractSubvector
ExtractSubvector Index indicates start offset.
LLVM_ABI APInt getFeatureMask(const Function &F) const
Returns a bitmask constructed from the target-features or fmv-features metadata of a function.
LLVM_ABI void getPeelingPreferences(Loop *L, ScalarEvolution &SE, PeelingPreferences &PP) const
Get target-customized preferences for the generic loop peeling transformation.
LLVM_ABI InstructionCost getCallInstrCost(Function *F, Type *RetTy, ArrayRef< Type * > Tys, TTI::TargetCostKind CostKind=TTI::TCK_SizeAndLatency) const
LLVM_ABI InstructionCost getCFInstrCost(unsigned Opcode, TTI::TargetCostKind CostKind=TTI::TCK_SizeAndLatency, const Instruction *I=nullptr) const
CastContextHint
Represents a hint about the context in which a cast is used.
@ Reversed
The cast is used with a reversed load/store.
@ Masked
The cast is used with a masked load/store.
@ None
The cast is not used with a load/store of any kind.
@ Normal
The cast is used with a normal load/store.
@ Interleave
The cast is used with an interleaved load/store.
@ GatherScatter
The cast is used with a gather/scatter.
LLVM_ABI InstructionCost getExtractWithExtendCost(unsigned Opcode, Type *Dst, VectorType *VecTy, unsigned Index, TTI::TargetCostKind CostKind) const
OperandValueKind
Additional information about an operand's possible values.
CacheLevel
The possible cache levels.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:45
This is the common base class for vector predication intrinsics.
LLVM Value Representation.
Definition Value.h:75
Base class of all SIMD vector types.
CallInst * Call
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
@ Fast
Attempts to make calls as fast as possible (e.g.
Definition CallingConv.h:41
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
This namespace contains an enum with a value for every intrinsic/builtin function known by LLVM.
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
This is an optimization pass for GlobalISel generic memory operations.
@ Length
Definition DWP.cpp:477
FunctionAddr VTableAddr Value
Definition InstrProf.h:137
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
AtomicOrdering
Atomic ordering for LLVM's memory model.
@ LLVM_MARK_AS_BITMASK_ENUM
Definition ModRef.h:37
TargetTransformInfo TTI
FunctionAddr VTableAddr uintptr_t uintptr_t Data
Definition InstrProf.h:189
LLVM_ABI ImmutablePass * createTargetTransformInfoWrapperPass(TargetIRAnalysis TIRA)
Create an analysis pass wrapper around a TTI object.
RecurKind
These are the kinds of recurrences that we support.
ArrayRef(const T &OneElt) -> ArrayRef< T >
constexpr unsigned BitWidth
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1856
@ DataAndControlFlowWithoutRuntimeCheck
Use predicate to control both data and control flow, but modify the trip count so that a runtime over...
@ DataWithEVL
Use predicated EVL instructions for tail-folding.
@ DataAndControlFlow
Use predicate to control both data and control flow.
@ DataWithoutLaneMask
Same as Data, but avoids using the get.active.lane.mask intrinsic to calculate the mask and instead i...
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:851
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
A CRTP mix-in that provides informational APIs needed for analysis passes.
Definition PassManager.h:93
A special type used by analysis passes to provide an address that identifies that particular analysis...
Definition Analysis.h:29
Attributes of a target dependent hardware loop.
LLVM_ABI bool canAnalyze(LoopInfo &LI)
LLVM_ABI bool isHardwareLoopCandidate(ScalarEvolution &SE, LoopInfo &LI, DominatorTree &DT, bool ForceNestedLoop=false, bool ForceHardwareLoopPHI=false)
Information about a load/store intrinsic defined by the target.
Value * PtrVal
This is the pointer that the intrinsic is loading from or storing to.
InterleavedAccessInfo * IAI
TailFoldingInfo(TargetLibraryInfo *TLI, LoopVectorizationLegality *LVL, InterleavedAccessInfo *IAI)
TargetLibraryInfo * TLI
LoopVectorizationLegality * LVL
unsigned Insns
TODO: Some of these could be merged.
Returns options for expansion of memcmp. IsZeroCmp is.
bool AllowPeeling
Allow peeling off loop iterations.
bool AllowLoopNestsPeeling
Allow peeling off loop iterations for loop nests.
bool PeelLast
Peel off the last PeelCount loop iterations.
bool PeelProfiledIterations
Allow peeling basing on profile.
unsigned PeelCount
A forced peeling factor (the number of bodied of the original loop that should be peeled off before t...
Describe known properties for a set of pointers.
unsigned IsKnownStride
True if distance between any two neigbouring pointers is a known value.
unsigned IsUnitStride
These properties only valid if SameBaseAddress is set.
unsigned IsSameBaseAddress
All the GEPs in a set have same base address.
Parameters that control the generic loop unrolling transformation.
unsigned Count
A forced unrolling factor (the number of concatenated bodies of the original loop in the unrolled loo...
bool UpperBound
Allow using trip count upper bound to unroll loops.
unsigned Threshold
The cost threshold for the unrolled loop.
bool Force
Apply loop unroll on any kind of loop (mainly to loops that fail runtime unrolling).
unsigned PartialOptSizeThreshold
The cost threshold for the unrolled loop when optimizing for size, like OptSizeThreshold,...
bool UnrollVectorizedLoop
Don't disable runtime unroll for the loops which were vectorized.
unsigned DefaultUnrollRuntimeCount
Default unroll count for loops with run-time trip count.
unsigned MaxPercentThresholdBoost
If complete unrolling will reduce the cost of the loop, we will boost the Threshold by a certain perc...
bool RuntimeUnrollMultiExit
Allow runtime unrolling multi-exit loops.
unsigned SCEVExpansionBudget
Don't allow runtime unrolling if expanding the trip count takes more than SCEVExpansionBudget.
bool AddAdditionalAccumulators
Allow unrolling to add parallel reduction phis.
unsigned UnrollAndJamInnerLoopThreshold
Threshold for unroll and jam, for inner loop size.
unsigned MaxIterationsCountToAnalyze
Don't allow loop unrolling to simulate more than this number of iterations when checking full unroll ...
bool AllowRemainder
Allow generation of a loop remainder (extra iterations after unroll).
bool UnrollAndJam
Allow unroll and jam. Used to enable unroll and jam for the target.
bool UnrollRemainder
Allow unrolling of all the iterations of the runtime loop remainder.
unsigned FullUnrollMaxCount
Set the maximum unrolling factor for full unrolling.
unsigned PartialThreshold
The cost threshold for the unrolled loop, like Threshold, but used for partial/runtime unrolling (set...
bool Runtime
Allow runtime unrolling (unrolling of loops to expand the size of the loop body even when the number ...
bool Partial
Allow partial unrolling (unrolling of loops to expand the size of the loop body, not only to eliminat...
unsigned OptSizeThreshold
The cost threshold for the unrolled loop when optimizing for size (set to UINT_MAX to disable).
bool AllowExpensiveTripCount
Allow emitting expensive instructions (such as divisions) when computing the trip count of a loop for...
unsigned MaxUpperBound
Set the maximum upper bound of trip count.
VPLegalization(VPTransform EVLParamStrategy, VPTransform OpStrategy)