LLVM 24.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/ADT/Uniformity.h"
31#include "llvm/IR/FMF.h"
32#include "llvm/IR/InstrTypes.h"
33#include "llvm/IR/PassManager.h"
34#include "llvm/Pass.h"
39#include <functional>
40#include <optional>
41#include <utility>
42
43namespace llvm {
44
45namespace Intrinsic {
46typedef unsigned ID;
47}
48
49class AllocaInst;
50class AssumptionCache;
52class DominatorTree;
53class CondBrInst;
54class Function;
55class GlobalValue;
56class InstCombiner;
59class ICmpInst;
60class IntrinsicInst;
61class LoadInst;
62class Loop;
63class LoopInfo;
67class SCEV;
68class ScalarEvolution;
69class SmallBitVector;
70class StoreInst;
71class SwitchInst;
73class Type;
74class VPIntrinsic;
75struct KnownBits;
76
77/// Information about a load/store intrinsic defined by the target.
79 /// This is the pointer that the intrinsic is loading from or storing to.
80 /// If this is non-null, then analysis/optimization passes can assume that
81 /// this intrinsic is functionally equivalent to a load/store from this
82 /// pointer.
83 Value *PtrVal = nullptr;
84
85 // Ordering for atomic operations.
87
88 // Same Id is set by the target for corresponding load/store intrinsics.
89 unsigned short MatchingId = 0;
90
91 bool ReadMem = false;
92 bool WriteMem = false;
93 bool IsVolatile = false;
94
96
97 bool isUnordered() const {
100 !IsVolatile;
101 }
102};
103
104/// Attributes of a target dependent hardware loop.
108 Loop *L = nullptr;
111 const SCEV *ExitCount = nullptr;
113 Value *LoopDecrement = nullptr; // Decrement the loop counter by this
114 // value in every iteration.
115 bool IsNestingLegal = false; // Can a hardware loop be a parent to
116 // another hardware loop?
117 bool CounterInReg = false; // Should loop counter be updated in
118 // the loop via a phi?
119 bool PerformEntryTest = false; // Generate the intrinsic which also performs
120 // icmp ne zero on the loop counter value and
121 // produces an i1 to guard the loop entry.
123 DominatorTree &DT,
124 bool ForceNestedLoop = false,
125 bool ForceHardwareLoopPHI = false);
126 LLVM_ABI bool canAnalyze(LoopInfo &LI);
127};
128
129/// Information for memory intrinsic cost model.
131 /// Optional context instruction, if one exists, e.g. the
132 /// load/store to transform to the intrinsic.
133 const Instruction *I = nullptr;
134
135 /// Address in memory.
136 const Value *Ptr = nullptr;
137
138 /// Vector type of the data to be loaded or stored.
139 Type *DataTy = nullptr;
140
141 /// ID of the memory intrinsic.
142 Intrinsic::ID IID;
143
144 /// True when the memory access is predicated with a mask
145 /// that is not a compile-time constant.
146 bool VariableMask = true;
147
148 /// Address space of the pointer.
149 unsigned AddressSpace = 0;
150
151 /// Alignment of single element.
152 Align Alignment;
153
154 const Value *StrideVal;
155
156public:
158 bool VariableMask, Align Alignment,
159 const Instruction *I = nullptr,
160 const Value *StrideVal = nullptr)
161
162 : I(I), Ptr(Ptr), DataTy(DataTy), IID(Id), VariableMask(VariableMask),
163 Alignment(Alignment), StrideVal(StrideVal) {}
164
166 unsigned AddressSpace = 0,
167 const Value *StrideVal = nullptr)
168 : DataTy(DataTy), IID(Id), AddressSpace(AddressSpace),
169 Alignment(Alignment), StrideVal(StrideVal) {}
170
171 MemIntrinsicCostAttributes(Intrinsic::ID Id, Type *DataTy, bool VariableMask,
172 Align Alignment, const Instruction *I = nullptr,
173 const Value *StrideVal = nullptr)
174
175 : I(I), DataTy(DataTy), IID(Id), VariableMask(VariableMask),
176 Alignment(Alignment), StrideVal(StrideVal) {}
177
178 Intrinsic::ID getID() const { return IID; }
179 const Instruction *getInst() const { return I; }
180 const Value *getPointer() const { return Ptr; }
181 Type *getDataType() const { return DataTy; }
182 bool getVariableMask() const { return VariableMask; }
183 unsigned getAddressSpace() const { return AddressSpace; }
184 Align getAlignment() const { return Alignment; }
185 const Value *getStrideVal() const { return StrideVal; }
186};
187
188/// Represents a hint about the context in which a vector instruction or
189/// intrinsic is used.
190///
191/// On some targets, inserts/extracts can cheaply be folded into loads/stores.
192/// Similarly, vp.merge can also be folded into binary ops on some targets.
193///
194/// This enum allows the vectorizer to give getVectorInstrCost and
195/// getIntrinsicInstrCost an idea of how the values are used.
196///
197/// See \c getVectorInstrContextHint to compute a VectorInstrContext from an
198/// insert/extract Instruction*.
200 None, ///< The instruction is not folded.
201 Load, ///< The value being inserted comes from a load (InsertElement only).
202 Store, ///< The extracted value is stored (ExtractElement only).
203 BinaryOp, ///< One of the operands is a binary op.
204 SplatOpFolded, ///< All of the value's users support splatting the value.
205};
206
208 const IntrinsicInst *II = nullptr;
209 Type *RetTy = nullptr;
210 Intrinsic::ID IID;
211 SmallVector<Type *, 4> ParamTys;
213 FastMathFlags FMF;
214 // If ScalarizationCost is UINT_MAX, the cost of scalarizing the
215 // arguments and the return value will be computed based on types.
216 InstructionCost ScalarizationCost = InstructionCost::getInvalid();
218
219public:
221 Intrinsic::ID Id, const CallBase &CI,
223 bool TypeBasedOnly = false);
224
226 Intrinsic::ID Id, Type *RTy, ArrayRef<Type *> Tys,
227 FastMathFlags Flags = FastMathFlags(), const IntrinsicInst *I = nullptr,
229
232
236 const IntrinsicInst *I = nullptr,
239
240 Intrinsic::ID getID() const { return IID; }
241 const IntrinsicInst *getInst() const { return II; }
242 Type *getReturnType() const { return RetTy; }
243 FastMathFlags getFlags() const { return FMF; }
244 InstructionCost getScalarizationCost() const { return ScalarizationCost; }
246 const SmallVectorImpl<const Value *> &getArgs() const { return Arguments; }
247 const SmallVectorImpl<Type *> &getArgTypes() const { return ParamTys; }
248
249 bool isTypeBasedOnly() const {
250 return Arguments.empty();
251 }
252
253 bool skipScalarizationCost() const { return ScalarizationCost.isValid(); }
254};
255
257 /// Don't use tail folding
259 /// Use predicate only to mask operations on data in the loop.
260 /// When the VL is not known to be a power-of-2, this method requires a
261 /// runtime overflow check for the i + VL in the loop because it compares the
262 /// scalar induction variable against the tripcount rounded up by VL which may
263 /// overflow. When the VL is a power-of-2, both the increment and uprounded
264 /// tripcount will overflow to 0, which does not require a runtime check
265 /// since the loop is exited when the loop induction variable equals the
266 /// uprounded trip-count, which are both 0.
268 /// Same as Data, but avoids using the get.active.lane.mask intrinsic to
269 /// calculate the mask and instead implements this with a
270 /// splat/stepvector/cmp.
271 /// FIXME: Can this kind be removed now that SelectionDAGBuilder expands the
272 /// active.lane.mask intrinsic when it is not natively supported?
274 /// Use predicate to control both data and control flow.
275 /// This method always requires a runtime overflow check for the i + VL
276 /// increment inside the loop, because it uses the result direclty in the
277 /// active.lane.mask to calculate the mask for the next iteration. If the
278 /// increment overflows, the mask is no longer correct.
280 /// Use predicated EVL instructions for tail-folding.
281 /// Indicates that VP intrinsics should be used.
283};
284
293
294class TargetTransformInfo;
297
298/// This pass provides access to the codegen interfaces that are needed
299/// for IR-level transformations.
301public:
308
309 /// Get the kind of extension that an instruction represents.
312 /// Get the kind of extension that a cast opcode represents.
315 /// Get the cast opcode for an extension kind.
318
319 /// Construct a TTI object using a type implementing the \c Concept
320 /// API below.
321 ///
322 /// This is used by targets to construct a TTI wrapping their target-specific
323 /// implementation that encodes appropriate costs for their target.
325 std::unique_ptr<const TargetTransformInfoImplBase> Impl);
326
327 /// Construct a baseline TTI object using a minimal implementation of
328 /// the \c Concept API below.
329 ///
330 /// The TTI implementation will reflect the information in the DataLayout
331 /// provided if non-null.
332 LLVM_ABI explicit TargetTransformInfo(const DataLayout &DL);
333
334 // Provide move semantics.
337
338 // We need to define the destructor out-of-line to define our sub-classes
339 // out-of-line.
341
342 /// Handle the invalidation of this information.
343 ///
344 /// When used as a result of \c TargetIRAnalysis this method will be called
345 /// when the function this was computed for changes. When it returns false,
346 /// the information is preserved across those changes.
348 FunctionAnalysisManager::Invalidator &) {
349 // FIXME: We should probably in some way ensure that the subtarget
350 // information for a function hasn't changed.
351 return false;
352 }
353
354 /// \name Generic Target Information
355 /// @{
356
357 /// The kind of cost model.
358 ///
359 /// There are several different cost models that can be customized by the
360 /// target. The normalization of each cost model may be target specific.
361 /// e.g. TCK_SizeAndLatency should be comparable to target thresholds such as
362 /// those derived from MCSchedModel::LoopMicroOpBufferSize etc.
364 TCK_RecipThroughput, ///< Reciprocal throughput.
365 TCK_Latency, ///< The latency of instruction.
366 TCK_CodeSize, ///< Instruction code size.
367 TCK_SizeAndLatency ///< The weighted sum of size and latency.
368 };
369
370 /// Underlying constants for 'cost' values in this interface.
371 ///
372 /// Many APIs in this interface return a cost. This enum defines the
373 /// fundamental values that should be used to interpret (and produce) those
374 /// costs. The costs are returned as an int rather than a member of this
375 /// enumeration because it is expected that the cost of one IR instruction
376 /// may have a multiplicative factor to it or otherwise won't fit directly
377 /// into the enum. Moreover, it is common to sum or average costs which works
378 /// better as simple integral values. Thus this enum only provides constants.
379 /// Also note that the returned costs are signed integers to make it natural
380 /// to add, subtract, and test with zero (a common boundary condition). It is
381 /// not expected that 2^32 is a realistic cost to be modeling at any point.
382 ///
383 /// Note that these costs should usually reflect the intersection of code-size
384 /// cost and execution cost. A free instruction is typically one that folds
385 /// into another instruction. For example, reg-to-reg moves can often be
386 /// skipped by renaming the registers in the CPU, but they still are encoded
387 /// and thus wouldn't be considered 'free' here.
389 TCC_Free = 0, ///< Expected to fold away in lowering.
390 TCC_Basic = 1, ///< The cost of a typical 'add' instruction.
391 TCC_Expensive = 4 ///< The cost of a 'div' instruction on x86.
392 };
393
394 /// Estimate the cost of a GEP operation when lowered.
395 ///
396 /// \p PointeeType is the source element type of the GEP.
397 /// \p Ptr is the base pointer operand.
398 /// \p Operands is the list of indices following the base pointer.
399 ///
400 /// \p AccessType is a hint as to what type of memory might be accessed by
401 /// users of the GEP. getGEPCost will use it to determine if the GEP can be
402 /// folded into the addressing mode of a load/store. If AccessType is null,
403 /// then the resulting target type based off of PointeeType will be used as an
404 /// approximation.
405 LLVM_ABI InstructionCost getGEPCost(Type *PointeeType, const Value *Ptr,
407 TargetCostKind CostKind,
408 Type *AccessType = nullptr) const;
409
410 /// Describe known properties for a set of pointers.
412 /// All the GEPs in a set have same base address.
413 unsigned IsSameBaseAddress : 1;
414 /// These properties only valid if SameBaseAddress is set.
415 /// True if all pointers are separated by a unit stride.
416 unsigned IsUnitStride : 1;
417 /// True if distance between any two neigbouring pointers is a known value.
418 unsigned IsKnownStride : 1;
419 unsigned Reserved : 29;
420
421 bool isSameBase() const { return IsSameBaseAddress; }
422 bool isUnitStride() const { return IsSameBaseAddress && IsUnitStride; }
424
426 return {/*IsSameBaseAddress=*/1, /*IsUnitStride=*/1,
427 /*IsKnownStride=*/1, 0};
428 }
430 return {/*IsSameBaseAddress=*/1, /*IsUnitStride=*/0,
431 /*IsKnownStride=*/1, 0};
432 }
434 return {/*IsSameBaseAddress=*/1, /*IsUnitStride=*/0,
435 /*IsKnownStride=*/0, 0};
436 }
437 };
438 static_assert(sizeof(PointersChainInfo) == 4, "Was size increase justified?");
439
440 /// Estimate the cost of a chain of pointers (typically pointer operands of a
441 /// chain of loads or stores within same block) operations set when lowered.
442 /// \p AccessTy is the type of the loads/stores that will ultimately use the
443 /// \p Ptrs.
446 const PointersChainInfo &Info, Type *AccessTy,
447 const TargetCostKind CostKind) const;
448
449 /// \returns A value by which our inlining threshold should be multiplied.
450 /// This is primarily used to bump up the inlining threshold wholesale on
451 /// targets where calls are unusually expensive.
452 ///
453 /// TODO: This is a rather blunt instrument. Perhaps altering the costs of
454 /// individual classes of instructions would be better.
456
459
460 /// \returns The bonus of inlining the last call to a static function.
462
463 /// \returns A value to be added to the inlining threshold.
464 LLVM_ABI unsigned adjustInliningThreshold(const CallBase *CB) const;
465
466 /// \returns The cost of having an Alloca in the caller if not inlined, to be
467 /// added to the threshold
468 LLVM_ABI unsigned getCallerAllocaCost(const CallBase *CB,
469 const AllocaInst *AI) const;
470
471 /// \returns Vector bonus in percent.
472 ///
473 /// Vector bonuses: We want to more aggressively inline vector-dense kernels
474 /// and apply this bonus based on the percentage of vector instructions. A
475 /// bonus is applied if the vector instructions exceed 50% and half that
476 /// amount is applied if it exceeds 10%. Note that these bonuses are some what
477 /// arbitrary and evolved over time by accident as much as because they are
478 /// principled bonuses.
479 /// FIXME: It would be nice to base the bonus values on something more
480 /// scientific. A target may has no bonus on vector instructions.
482
483 /// \return the expected cost of a memcpy, which could e.g. depend on the
484 /// source/destination type and alignment and the number of bytes copied.
486
487 /// Returns the maximum memset / memcpy size in bytes that still makes it
488 /// profitable to inline the call.
490
491 /// \return The estimated number of case clusters when lowering \p 'SI'.
492 /// \p JTSize Set a jump table size only when \p SI is suitable for a jump
493 /// table.
494 LLVM_ABI unsigned
495 getEstimatedNumberOfCaseClusters(const SwitchInst &SI, unsigned &JTSize,
497 BlockFrequencyInfo *BFI) const;
498
499 /// Estimate the cost of a given IR user when lowered.
500 ///
501 /// This can estimate the cost of either a ConstantExpr or Instruction when
502 /// lowered.
503 ///
504 /// \p Operands is a list of operands which can be a result of transformations
505 /// of the current operands. The number of the operands on the list must equal
506 /// to the number of the current operands the IR user has. Their order on the
507 /// list must be the same as the order of the current operands the IR user
508 /// has.
509 ///
510 /// The returned cost is defined in terms of \c TargetCostConstants, see its
511 /// comments for a detailed explanation of the cost values.
514 TargetCostKind CostKind) const;
515
516 /// This is a helper function which calls the three-argument
517 /// getInstructionCost with \p Operands which are the current operands U has.
519 TargetCostKind CostKind) const {
520 SmallVector<const Value *, 4> Operands(U->operand_values());
521 return getInstructionCost(U, Operands, CostKind);
522 }
523
524 /// If a branch or a select condition is skewed in one direction by more than
525 /// this factor, it is very likely to be predicted correctly.
527
528 /// Returns estimated penalty of a branch misprediction in latency. Indicates
529 /// how aggressive the target wants for eliminating unpredictable branches. A
530 /// zero return value means extra optimization applied to them should be
531 /// minimal.
533
534 /// Return true if branch divergence exists.
535 ///
536 /// Branch divergence has a significantly negative impact on GPU performance
537 /// when threads in the same wavefront take different paths due to conditional
538 /// branches.
539 ///
540 /// If \p F is passed, provides a context function. If \p F is known to only
541 /// execute in a single threaded environment, the target may choose to skip
542 /// uniformity analysis and assume all values are uniform.
543 LLVM_ABI bool hasBranchDivergence(const Function *F = nullptr) const;
544
545 /// Get target-specific uniformity information for a value.
546 /// This allows targets to provide more fine-grained control over
547 /// uniformity analysis by specifying whether specific values
548 /// should always or never be considered uniform, or require custom
549 /// operand-based analysis.
550 /// \param V The value to query for uniformity information.
551 /// \return ValueUniformity.
553
554 /// Query the target whether the specified address space cast from FromAS to
555 /// ToAS is valid.
556 LLVM_ABI bool isValidAddrSpaceCast(unsigned FromAS, unsigned ToAS) const;
557
558 /// Return false if a \p AS0 address cannot possibly alias a \p AS1 address.
559 LLVM_ABI bool addrspacesMayAlias(unsigned AS0, unsigned AS1) const;
560
561 /// Returns the address space ID for a target's 'flat' address space. Note
562 /// this is not necessarily the same as addrspace(0), which LLVM sometimes
563 /// refers to as the generic address space. The flat address space is a
564 /// generic address space that can be used access multiple segments of memory
565 /// with different address spaces. Access of a memory location through a
566 /// pointer with this address space is expected to be legal but slower
567 /// compared to the same memory location accessed through a pointer with a
568 /// different address space.
569 //
570 /// This is for targets with different pointer representations which can
571 /// be converted with the addrspacecast instruction. If a pointer is converted
572 /// to this address space, optimizations should attempt to replace the access
573 /// with the source address space.
574 ///
575 /// \returns ~0u if the target does not have such a flat address space to
576 /// optimize away.
577 LLVM_ABI unsigned getFlatAddressSpace() const;
578
579 /// Return the most specific common address space containing AS1 and AS2.
580 /// AS1 and AS2 must be distinct, and pointers from both spaces must be
581 /// convertible to the target's flat address space with addrspacecast.
582 /// Pointers from either input space must be convertible to the result with
583 /// addrspacecast. Return getFlatAddressSpace() if no more specific common
584 /// address space is available.
585 LLVM_ABI unsigned getAddressSpaceJoin(unsigned AS1, unsigned AS2) const;
586
587 /// Return any intrinsic address operand indexes which may be rewritten if
588 /// they use a flat address space pointer.
589 ///
590 /// \returns true if the intrinsic was handled.
592 Intrinsic::ID IID) const;
593
594 LLVM_ABI bool isNoopAddrSpaceCast(unsigned FromAS, unsigned ToAS) const;
595
596 // Given an address space cast of the given pointer value, calculate the known
597 // bits of the source pointer in the source addrspace and the destination
598 // pointer in the destination addrspace.
599 LLVM_ABI std::pair<KnownBits, KnownBits>
600 computeKnownBitsAddrSpaceCast(unsigned ToAS, const Value &PtrOp) const;
601
602 // Given an address space cast, calculate the known bits of the resulting ptr
603 // in the destination addrspace using the known bits of the source pointer in
604 // the source addrspace.
606 unsigned FromAS, unsigned ToAS, const KnownBits &FromPtrBits) const;
607
608 /// Returns a mask indicating which bits of a pointer remain unchanged when
609 /// casting between address spaces. The returned APInt has the same bit width
610 /// as the source address space pointer size.
611 ///
612 /// Some targets allow certain bits of a pointer to change (e.g., the low
613 /// bits within a page) while still preserving the address space. This mask
614 /// identifies those bits that are guaranteed to be preserved. If the mask is
615 /// all zeros, no bits are preserved and address space inference cannot be
616 /// performed safely.
617 ///
618 /// For example, given:
619 /// %gp = addrspacecast ptr addrspace(2) %sp to ptr
620 /// %a = ptrtoint ptr %gp to i64
621 /// %b = xor i64 7, %a
622 /// %gp2 = inttoptr i64 %b to ptr
623 /// store i16 0, ptr %gp2, align 2
624 /// if the target preserves the upper bits, `%gp2` can be safely replaced
625 /// with `inttoptr i64 %b to ptr addrspace(2)`.
627 unsigned DstAS) const;
628
629 /// Return true if globals in this address space can have initializers other
630 /// than `undef`.
631 LLVM_ABI bool
633
634 LLVM_ABI unsigned getAssumedAddrSpace(const Value *V) const;
635
636 LLVM_ABI std::pair<const Value *, unsigned>
637 getPredicatedAddrSpace(const Value *V) const;
638
639 /// Rewrite intrinsic call \p II such that \p OldV will be replaced with \p
640 /// NewV, which has a different address space. This should happen for every
641 /// operand index that collectFlatAddressOperands returned for the intrinsic.
642 /// \returns nullptr if the intrinsic was not handled. Otherwise, returns the
643 /// new value (which may be the original \p II with modified operands).
644 /// If a different value is returned, the caller replaces all uses of \p II
645 /// and erases it, including any side effects of the original call.
647 Value *OldV,
648 Value *NewV) const;
649
650 /// Test whether calls to a function lower to actual program function
651 /// calls.
652 ///
653 /// The idea is to test whether the program is likely to require a 'call'
654 /// instruction or equivalent in order to call the given function.
655 ///
656 /// FIXME: It's not clear that this is a good or useful query API. Client's
657 /// should probably move to simpler cost metrics using the above.
658 /// Alternatively, we could split the cost interface into distinct code-size
659 /// and execution-speed costs. This would allow modelling the core of this
660 /// query more accurately as a call is a single small instruction, but
661 /// incurs significant execution cost.
662 LLVM_ABI bool isLoweredToCall(const Function *F) const;
663
664 struct LSRCost {
665 /// TODO: Some of these could be merged. Also, a lexical ordering
666 /// isn't always optimal.
667 unsigned Insns;
668 unsigned NumRegs;
669 unsigned AddRecCost;
670 unsigned NumIVMuls;
671 unsigned NumBaseAdds;
672 unsigned ImmCost;
673 unsigned SetupCost;
674 unsigned ScaleCost;
676 };
677
678 /// Parameters that control the generic loop unrolling transformation.
680 /// The cost threshold for the unrolled loop. Should be relative to the
681 /// getInstructionCost values returned by this API, and the expectation is
682 /// that the unrolled loop's instructions when run through that interface
683 /// should not exceed this cost. However, this is only an estimate. Also,
684 /// specific loops may be unrolled even with a cost above this threshold if
685 /// deemed profitable. Set this to UINT_MAX to disable the loop body cost
686 /// restriction.
687 unsigned Threshold;
688 /// If complete unrolling will reduce the cost of the loop, we will boost
689 /// the Threshold by a certain percent to allow more aggressive complete
690 /// unrolling. This value provides the maximum boost percentage that we
691 /// can apply to Threshold (The value should be no less than 100).
692 /// BoostedThreshold = Threshold * min(RolledCost / UnrolledCost,
693 /// MaxPercentThresholdBoost / 100)
694 /// E.g. if complete unrolling reduces the loop execution time by 50%
695 /// then we boost the threshold by the factor of 2x. If unrolling is not
696 /// expected to reduce the running time, then we do not increase the
697 /// threshold.
699 /// The cost threshold for the unrolled loop when optimizing for size (set
700 /// to UINT_MAX to disable).
702 /// The cost threshold for the unrolled loop, like Threshold, but used
703 /// for partial/runtime unrolling (set to UINT_MAX to disable).
705 /// The cost threshold for the unrolled loop when optimizing for size, like
706 /// OptSizeThreshold, but used for partial/runtime unrolling (set to
707 /// UINT_MAX to disable).
709 /// Default unroll count for loops with run-time trip count.
711 // Set the maximum unrolling factor. The unrolling factor may be selected
712 // using the appropriate cost threshold, but may not exceed this number
713 // (set to UINT_MAX to disable). This does not apply in cases where the
714 // loop is being fully unrolled.
715 unsigned MaxCount;
716 /// Set the maximum upper bound of trip count. Allowing the MaxUpperBound
717 /// to be overrided by a target gives more flexiblity on certain cases.
718 /// By default, MaxUpperBound uses UnrollMaxUpperBound which value is 8.
720 /// Set the maximum unrolling factor for full unrolling. Like MaxCount, but
721 /// applies even if full unrolling is selected. This allows a target to fall
722 /// back to Partial unrolling if full unrolling is above FullUnrollMaxCount.
724 // Represents number of instructions optimized when "back edge"
725 // becomes "fall through" in unrolled loop.
726 // For now we count a conditional branch on a backedge and a comparison
727 // feeding it.
728 unsigned BEInsns;
729 /// Allow partial unrolling (unrolling of loops to expand the size of the
730 /// loop body, not only to eliminate small constant-trip-count loops).
732 /// Allow runtime unrolling (unrolling of loops to expand the size of the
733 /// loop body even when the number of loop iterations is not known at
734 /// compile time).
736 /// Allow generation of a loop remainder (extra iterations after unroll).
738 /// Allow emitting expensive instructions (such as divisions) when computing
739 /// the trip count of a loop for runtime unrolling.
741 /// Apply loop unroll on any kind of loop
742 /// (mainly to loops that fail runtime unrolling).
743 bool Force;
744 /// Allow using trip count upper bound to unroll loops.
746 /// Allow unrolling of all the iterations of the runtime loop remainder.
748 /// Allow unroll and jam. Used to enable unroll and jam for the target.
750 /// Threshold for unroll and jam, for inner loop size. The 'Threshold'
751 /// value above is used during unroll and jam for the outer loop size.
752 /// This value is used in the same manner to limit the size of the inner
753 /// loop.
755 /// Don't allow loop unrolling to simulate more than this number of
756 /// iterations when checking full unroll profitability
758 /// Disable runtime unrolling by default for vectorized loops.
760 /// Don't allow runtime unrolling if expanding the trip count takes more
761 /// than SCEVExpansionBudget.
763 /// Allow runtime unrolling multi-exit loops. Should only be set if the
764 /// target determined that multi-exit unrolling is profitable for the loop.
765 /// Fall back to the generic logic to determine whether multi-exit unrolling
766 /// is profitable if set to false.
768 /// Allow unrolling to add parallel reduction phis.
770 };
771
772 /// Get target-customized preferences for the generic loop unrolling
773 /// transformation. The caller will initialize UP with the current
774 /// target-independent defaults.
777 OptimizationRemarkEmitter *ORE) const;
778
779 /// Query the target whether it would be profitable to convert the given loop
780 /// into a hardware loop.
782 AssumptionCache &AC,
783 TargetLibraryInfo *LibInfo,
784 HardwareLoopInfo &HWLoopInfo) const;
785
786 // Query the target for which minimum vectorization factor epilogue
787 // vectorization should be considered.
789
790 /// Query the target whether it would be preferred to create a tail-folded
791 /// vector loop, which can avoid the need to emit a scalar epilogue loop.
793
794 /// Query the target what the preferred style of tail folding is.
796
797 // Parameters that control the loop peeling transformation
799 /// A forced peeling factor (the number of bodied of the original loop
800 /// that should be peeled off before the loop body). When set to 0, the
801 /// a peeling factor based on profile information and other factors.
802 unsigned PeelCount;
803 /// Allow peeling off loop iterations.
805 /// Allow peeling off loop iterations for loop nests.
807 /// Allow peeling basing on profile. Uses to enable peeling off all
808 /// iterations basing on provided profile.
809 /// If the value is true the peeling cost model can decide to peel only
810 /// some iterations and in this case it will set this to false.
812
813 /// Peel off the last PeelCount loop iterations.
815 };
816
817 /// Get target-customized preferences for the generic loop peeling
818 /// transformation. The caller will initialize \p PP with the current
819 /// target-independent defaults with information from \p L and \p SE.
821 PeelingPreferences &PP) const;
822
823 /// Targets can implement their own combinations for target-specific
824 /// intrinsics. This function will be called from the InstCombine pass every
825 /// time a target-specific intrinsic is encountered.
826 ///
827 /// \returns std::nullopt to not do anything target specific or a value that
828 /// will be returned from the InstCombiner. It is possible to return null and
829 /// stop further processing of the intrinsic by returning nullptr.
830 LLVM_ABI std::optional<Instruction *>
832 /// Can be used to implement target-specific instruction combining.
833 /// \see instCombineIntrinsic
834 LLVM_ABI std::optional<Value *>
836 APInt DemandedMask, KnownBits &Known,
837 bool &KnownBitsComputed) const;
838 /// Can be used to implement target-specific instruction combining.
839 /// \see instCombineIntrinsic
840 LLVM_ABI std::optional<Value *> simplifyDemandedVectorEltsIntrinsic(
841 InstCombiner &IC, IntrinsicInst &II, APInt DemandedElts, APInt &UndefElts,
842 APInt &UndefElts2, APInt &UndefElts3,
843 std::function<void(Instruction *, unsigned, APInt, APInt &)>
844 SimplifyAndSetOp) const;
845 /// @}
846
847 /// \name Scalar Target Information
848 /// @{
849
850 /// Flags indicating the kind of support for population count.
851 ///
852 /// Compared to the SW implementation, HW support is supposed to
853 /// significantly boost the performance when the population is dense, and it
854 /// may or may not degrade performance if the population is sparse. A HW
855 /// support is considered as "Fast" if it can outperform, or is on a par
856 /// with, SW implementation when the population is sparse; otherwise, it is
857 /// considered as "Slow".
859
860 /// Return true if the specified immediate is legal add immediate, that
861 /// is the target has add instructions which can add a register with the
862 /// immediate without having to materialize the immediate into a register.
863 LLVM_ABI bool isLegalAddImmediate(int64_t Imm) const;
864
865 /// Return true if adding the specified scalable immediate is legal, that is
866 /// the target has add instructions which can add a register with the
867 /// immediate (multiplied by vscale) without having to materialize the
868 /// immediate into a register.
869 LLVM_ABI bool isLegalAddScalableImmediate(int64_t Imm) const;
870
871 /// Return true if the specified immediate is legal icmp immediate,
872 /// that is the target has icmp instructions which can compare a register
873 /// against the immediate without having to materialize the immediate into a
874 /// register.
875 LLVM_ABI bool isLegalICmpImmediate(int64_t Imm) const;
876
877 /// Return true if replacing the relational loop exit comparison \p Cond
878 /// with an equality comparison against \p PostIncExitValue is profitable.
879 LLVM_ABI bool
881 const APInt &PostIncExitValue) const;
882
883 /// Return true if the addressing mode represented by AM is legal for
884 /// this target, for a load/store of the specified type.
885 /// The type may be VoidTy, in which case only return true if the addressing
886 /// mode is legal for a load/store of any legal type.
887 /// If target returns true in LSRWithInstrQueries(), I may be valid.
888 /// \param ScalableOffset represents a quantity of bytes multiplied by vscale,
889 /// an invariant value known only at runtime. Most targets should not accept
890 /// a scalable offset.
891 ///
892 /// TODO: Handle pre/postinc as well.
894 int64_t BaseOffset, bool HasBaseReg,
895 int64_t Scale, unsigned AddrSpace = 0,
896 Instruction *I = nullptr,
897 int64_t ScalableOffset = 0) const;
898
899 /// Return true if LSR cost of C1 is lower than C2.
901 const TargetTransformInfo::LSRCost &C2) const;
902
903 /// Return true if LSR major cost is number of registers. Targets which
904 /// implement their own isLSRCostLess and unset number of registers as major
905 /// cost should return false, otherwise return true.
907
908 /// Return true if LSR should drop a found solution if it's calculated to be
909 /// less profitable than the baseline.
911
912 /// \returns true if LSR should not optimize a chain that includes \p I.
914
915 /// Return true if the target can fuse a compare and branch.
916 /// Loop-strength-reduction (LSR) uses that knowledge to adjust its cost
917 /// calculation for the instructions in a loop.
918 LLVM_ABI bool canMacroFuseCmp() const;
919
920 /// Return true if the target can save a compare for loop count, for example
921 /// hardware loop saves a compare.
924 TargetLibraryInfo *LibInfo) const;
925
926 /// Which addressing mode Loop Strength Reduction will try to generate.
928 AMK_None = 0x0, ///< Don't prefer any addressing mode
929 AMK_PreIndexed = 0x1, ///< Prefer pre-indexed addressing mode
930 AMK_PostIndexed = 0x2, ///< Prefer post-indexed addressing mode
931 AMK_All = 0x3, ///< Consider all addressing modes
932 LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/AMK_All)
933 };
934
935 /// Return the preferred addressing mode LSR should make efforts to generate.
938
939 /// Some targets only support masked load/store with a constant mask.
944
945 /// Return true if the target supports masked store.
946 LLVM_ABI bool
947 isLegalMaskedStore(Type *DataType, Align Alignment, unsigned AddressSpace,
949 /// Return true if the target supports masked load.
950 LLVM_ABI bool
951 isLegalMaskedLoad(Type *DataType, Align Alignment, unsigned AddressSpace,
953
954 /// Return true if the target supports speculatively loading \p DataType from
955 /// address space \p AddressSpace, i.e. @llvm.can.load.speculatively can
956 /// return true for the store size of \p DataType.
957 LLVM_ABI bool isLegalSpeculativeLoad(Type *DataType,
958 unsigned AddressSpace) const;
959
960 /// Return true if the target supports nontemporal store.
961 LLVM_ABI bool isLegalNTStore(Type *DataType, Align Alignment) const;
962 /// Return true if the target supports nontemporal load.
963 LLVM_ABI bool isLegalNTLoad(Type *DataType, Align Alignment) const;
964
965 /// \Returns true if the target supports broadcasting a load to a vector of
966 /// type <NumElements x ElementTy>.
967 LLVM_ABI bool isLegalBroadcastLoad(Type *ElementTy,
968 ElementCount NumElements) const;
969
970 /// Return true if the target supports masked scatter.
971 LLVM_ABI bool isLegalMaskedScatter(Type *DataType, Align Alignment) const;
972 /// Return true if the target supports masked gather.
973 LLVM_ABI bool isLegalMaskedGather(Type *DataType, Align Alignment) const;
974 /// Return true if the target forces scalarizing of llvm.masked.gather
975 /// intrinsics.
977 Align Alignment) const;
978 /// Return true if the target forces scalarizing of llvm.masked.scatter
979 /// intrinsics.
981 Align Alignment) const;
982
983 /// Return true if the target supports masked compress store.
985 Align Alignment) const;
986 /// Return true if the target supports masked expand load.
987 LLVM_ABI bool isLegalMaskedExpandLoad(Type *DataType, Align Alignment) const;
988
989 /// Return true if the target supports strided load.
990 LLVM_ABI bool isLegalStridedLoadStore(Type *DataType, Align Alignment) const;
991
992 /// Return true is the target supports interleaved access for the given vector
993 /// type \p VTy, interleave factor \p Factor, alignment \p Alignment and
994 /// address space \p AddrSpace.
995 LLVM_ABI bool isLegalInterleavedAccessType(VectorType *VTy, unsigned Factor,
996 Align Alignment,
997 unsigned AddrSpace) const;
998
999 // Return true if the target supports masked vector histograms.
1001 Type *DataType) const;
1002
1003 /// Return true if this is an alternating opcode pattern that can be lowered
1004 /// to a single instruction on the target. In X86 this is for the addsub
1005 /// instruction which corrsponds to a Shuffle + Fadd + FSub pattern in IR.
1006 /// This function expectes two opcodes: \p Opcode1 and \p Opcode2 being
1007 /// selected by \p OpcodeMask. The mask contains one bit per lane and is a `0`
1008 /// when \p Opcode0 is selected and `1` when Opcode1 is selected.
1009 /// \p VecTy is the vector type of the instruction to be generated.
1010 /// \p Scalars are the scalar instructions of the lanes, if known. The target
1011 /// may use them to find the patterns, which depend on the operands, like
1012 /// the alternating fused multiply-add.
1013 LLVM_ABI bool isLegalAltInstr(VectorType *VecTy, unsigned Opcode0,
1014 unsigned Opcode1,
1015 const SmallBitVector &OpcodeMask,
1016 ArrayRef<const Value *> Scalars = {}) const;
1017
1018 /// Enum describing the source/producer of a mask.
1019 enum class MaskSource {
1020 /// The operation is unmasked.
1022 /// The operation is masked with an arbitrary predicate.
1024 /// The operation is masked with a contiguous active lane mask.
1026 };
1027
1028 /// Return true if the target supports loading or storing \p NumVectors
1029 /// contiguous vectors of type \p VectorTy as a single operation. A null
1030 /// \p VectorTy queries whether the target supports this operation in
1031 /// general.
1032 ///
1033 /// \p CastHint is non-null if a stored value is produced by a cast or a
1034 /// loaded value is consumed by one.
1036 unsigned NumVectors, MaskSource Mask, VectorType *VectorTy = nullptr,
1037 bool IsStore = false,
1038 std::optional<Instruction::CastOps> CastHint = std::nullopt) const;
1039
1040 /// Return true if we should be enabling ordered reductions for the target.
1041 LLVM_ABI bool enableOrderedReductions() const;
1042
1043 /// Return true if the target has a unified operation to calculate division
1044 /// and remainder. If so, the additional implicit multiplication and
1045 /// subtraction required to calculate a remainder from division are free. This
1046 /// can enable more aggressive transformations for division and remainder than
1047 /// would typically be allowed using throughput or size cost models.
1048 LLVM_ABI bool hasDivRemOp(Type *DataType, bool IsSigned) const;
1049
1050 /// Return true if the given instruction (assumed to be a memory access
1051 /// instruction) has a volatile variant. If that's the case then we can avoid
1052 /// addrspacecast to generic AS for volatile loads/stores. Default
1053 /// implementation returns false, which prevents address space inference for
1054 /// volatile loads/stores.
1055 LLVM_ABI bool hasVolatileVariant(Instruction *I, unsigned AddrSpace) const;
1056
1057 /// Return true if target doesn't mind addresses in vectors.
1059
1060 /// Return the cost of the scaling factor used in the addressing
1061 /// mode represented by AM for this target, for a load/store
1062 /// of the specified type.
1063 /// If the AM is supported, the return value must be >= 0.
1064 /// If the AM is not supported, it returns a negative value.
1065 /// TODO: Handle pre/postinc as well.
1067 StackOffset BaseOffset,
1068 bool HasBaseReg, int64_t Scale,
1069 unsigned AddrSpace = 0) const;
1070
1071 /// Return true if the loop strength reduce pass should make
1072 /// Instruction* based TTI queries to isLegalAddressingMode(). This is
1073 /// needed on SystemZ, where e.g. a memcpy can only have a 12 bit unsigned
1074 /// immediate offset and no index register.
1075 LLVM_ABI bool LSRWithInstrQueries() const;
1076
1077 /// Return true if it's free to truncate a value of type Ty1 to type
1078 /// Ty2. e.g. On x86 it's free to truncate a i32 value in register EAX to i16
1079 /// by referencing its sub-register AX.
1080 LLVM_ABI bool isTruncateFree(Type *Ty1, Type *Ty2) const;
1081
1082 /// Return true if it is profitable to hoist instruction in the
1083 /// then/else to before if.
1085
1086 LLVM_ABI bool useAA() const;
1087
1088 /// Return true if this type is legal.
1089 LLVM_ABI bool isTypeLegal(Type *Ty) const;
1090
1091 /// Returns the estimated number of registers required to represent \p Ty.
1092 LLVM_ABI unsigned getRegUsageForType(Type *Ty) const;
1093
1094 /// Return true if switches should be turned into lookup tables for the
1095 /// target.
1096 LLVM_ABI bool shouldBuildLookupTables() const;
1097
1098 /// Return true if switches should be turned into lookup tables
1099 /// containing this constant value for the target.
1101
1102 /// Return the minimum bit width to use for integer switch lookup table
1103 /// elements on this target.
1105
1106 /// Return true if lookup tables should be turned into relative lookup tables.
1108
1109 /// Return true if the input function which is cold at all call sites,
1110 /// should use coldcc calling convention.
1112
1113 /// Return true if the input function is internal, should use fastcc calling
1114 /// convention.
1116
1117 /// Identifies if the vector form of the intrinsic has a scalar operand.
1119 unsigned ScalarOpdIdx) const;
1120
1121 /// Identifies if the vector form of the intrinsic is overloaded on the type
1122 /// of the operand at index \p OpdIdx, or on the return type if \p OpdIdx is
1123 /// -1.
1125 int OpdIdx) const;
1126
1127 /// Identifies if the vector form of the intrinsic that returns a struct is
1128 /// overloaded at the struct element index \p RetIdx.
1129 LLVM_ABI bool
1131 int RetIdx) const;
1132
1134
1135 /// Combines 2 context hints into a single value. If both are equal, keep the
1136 /// shared context, otherwise fall back to no specific context.
1140
1141 /// Stores information about the uses of a build vector
1151
1152 /// Calculates a VectorInstrContext from \p I.
1155
1156 /// Calculates a VectorInstrContext for buildvector-like gather sequences.
1157 ///
1158 /// \p GatherUserOps must collect all users of \p Scalars relevant for
1159 /// determining whether a splat can be folded as a scalar operand. It returns
1160 /// false if those users cannot be gathered in the required form.
1162 ArrayRef<int> Mask, ArrayRef<Value *> Scalars,
1163 function_ref<bool(SmallVectorImpl<BuildVectorUseOp> &)> GatherUseOps)
1164 const;
1165
1166 /// Estimate the overhead of scalarizing an instruction. Insert and Extract
1167 /// are set if the demanded result elements need to be inserted and/or
1168 /// extracted from vectors. The involved values may be passed in VL if
1169 /// Insert is true.
1171 VectorType *Ty, const APInt &DemandedElts, bool Insert, bool Extract,
1172 TTI::TargetCostKind CostKind, bool ForPoisonSrc = true,
1173 ArrayRef<Value *> VL = {},
1175
1176 /// Estimate the overhead of scalarizing operands with the given types. The
1177 /// (potentially vector) types to use for each of argument are passes via Tys.
1181
1182 /// If target has efficient vector element load/store instructions, it can
1183 /// return true here so that insertion/extraction costs are not added to
1184 /// the scalarization cost of a load/store.
1186
1187 /// If the target supports tail calls.
1188 LLVM_ABI bool supportsTailCalls() const;
1189
1190 /// If target supports tail call on \p CB
1191 LLVM_ABI bool supportsTailCallFor(const CallBase *CB) const;
1192
1193 /// Don't restrict interleaved unrolling to small loops.
1194 LLVM_ABI bool enableAggressiveInterleaving(bool LoopHasReductions) const;
1195
1196 /// Returns options for expansion of memcmp. IsZeroCmp is
1197 // true if this is the expansion of memcmp(p1, p2, s) == 0.
1199 // Return true if memcmp expansion is enabled.
1200 operator bool() const { return MaxNumLoads > 0; }
1201
1202 // Maximum number of load operations.
1203 unsigned MaxNumLoads = 0;
1204
1205 // The list of available load sizes (in bytes), sorted in decreasing order.
1207
1208 // For memcmp expansion, allow up to this number of load pairs per block.
1209 // As an example, this may allow 'memcmp(a, b, 3) == 0' in a single block:
1210 // a0 = load2bytes &a[0]
1211 // b0 = load2bytes &b[0]
1212 // a2 = load1byte &a[2]
1213 // b2 = load1byte &b[2]
1214 // r = cmp eq (a0 ^ b0 | a2 ^ b2), 0
1215 // Equality comparisons combine the differences with xor/or. Ordering
1216 // comparisons pack the loads in memory order into a wider integer before
1217 // comparing, without exceeding the target's preferred load width.
1218 unsigned NumLoadsPerBlock = 1;
1219
1220 // Set to true to allow overlapping loads. For example, 7-byte compares can
1221 // be done with two 4-byte compares instead of 4+2+1-byte compares. This
1222 // requires all loads in LoadSizes to be doable in an unaligned way.
1224
1225 // Sometimes, the amount of data that needs to be compared is smaller than
1226 // the standard register size, but it cannot be loaded with just one load
1227 // instruction. For example, if the size of the memory comparison is 6
1228 // bytes, we can handle it more efficiently by loading all 6 bytes in a
1229 // single block and generating an 8-byte number, instead of generating two
1230 // separate blocks with conditional jumps for 4 and 2 byte loads. This
1231 // approach simplifies the process and produces the comparison result as
1232 // normal. This array lists the allowed sizes of memcmp tails that can be
1233 // merged into one block
1235 };
1237 bool IsZeroCmp) const;
1238
1239 /// Should the Select Optimization pass be enabled and ran.
1240 LLVM_ABI bool enableSelectOptimize() const;
1241
1242 /// Should the Select Optimization pass treat the given instruction like a
1243 /// select, potentially converting it to a conditional branch. This can
1244 /// include select-like instructions like or(zext(c), x) that can be converted
1245 /// to selects.
1247
1248 /// Enable matching of interleaved access groups.
1250
1251 /// Enable matching of interleaved access groups that contain predicated
1252 /// accesses or gaps and therefore vectorized using masked
1253 /// vector loads/stores.
1255
1256 /// Indicate that it is potentially unsafe to automatically vectorize
1257 /// floating-point operations because the semantics of vector and scalar
1258 /// floating-point semantics may differ. For example, ARM NEON v7 SIMD math
1259 /// does not support IEEE-754 denormal numbers, while depending on the
1260 /// platform, scalar floating-point math does.
1261 /// This applies to floating-point math operations and calls, not memory
1262 /// operations, shuffles, or casts.
1264
1265 /// Determine if the target supports unaligned memory accesses.
1267 unsigned BitWidth,
1268 unsigned AddressSpace = 0,
1269 Align Alignment = Align(1),
1270 unsigned *Fast = nullptr) const;
1271
1272 /// Return hardware support for population count.
1273 LLVM_ABI PopcntSupportKind getPopcntSupport(unsigned IntTyWidthInBit) const;
1274
1275 /// Return true if the hardware has a fast square-root instruction.
1276 LLVM_ABI bool haveFastSqrt(Type *Ty) const;
1277
1278 /// Return true if the cost of the instruction is too high to speculatively
1279 /// execute and should be kept behind a branch.
1280 /// This normally just wraps around a getInstructionCost() call, but some
1281 /// targets might report a low TCK_SizeAndLatency value that is incompatible
1282 /// with the fixed TCC_Expensive value.
1283 /// NOTE: This assumes the instruction passes isSafeToSpeculativelyExecute().
1285
1286 /// Return true if it is faster to check if a floating-point value is NaN
1287 /// (or not-NaN) versus a comparison against a constant FP zero value.
1288 /// Targets should override this if materializing a 0.0 for comparison is
1289 /// generally as cheap as checking for ordered/unordered.
1291
1292 /// Return the expected cost of supporting the floating point operation
1293 /// of the specified type.
1295
1296 /// Return the expected cost of materializing for the given integer
1297 /// immediate of the specified type.
1299 TargetCostKind CostKind) const;
1300
1301 /// Return the expected cost of materialization for the given integer
1302 /// immediate of the specified type for a given instruction. The cost can be
1303 /// zero if the immediate can be folded into the specified instruction.
1304 LLVM_ABI InstructionCost getIntImmCostInst(unsigned Opc, unsigned Idx,
1305 const APInt &Imm, Type *Ty,
1306 TargetCostKind CostKind,
1307 Instruction *Inst = nullptr) const;
1309 const APInt &Imm, Type *Ty,
1310 TargetCostKind CostKind) const;
1311
1312 /// Return the expected cost for the given integer when optimising
1313 /// for size. This is different than the other integer immediate cost
1314 /// functions in that it is subtarget agnostic. This is useful when you e.g.
1315 /// target one ISA such as Aarch32 but smaller encodings could be possible
1316 /// with another such as Thumb. This return value is used as a penalty when
1317 /// the total costs for a constant is calculated (the bigger the cost, the
1318 /// more beneficial constant hoisting is).
1319 LLVM_ABI InstructionCost getIntImmCodeSizeCost(unsigned Opc, unsigned Idx,
1320 const APInt &Imm,
1321 Type *Ty) const;
1322
1323 /// It can be advantageous to detach complex constants from their uses to make
1324 /// their generation cheaper. This hook allows targets to report when such
1325 /// transformations might negatively effect the code generation of the
1326 /// underlying operation. The motivating example is divides whereby hoisting
1327 /// constants prevents the code generator's ability to transform them into
1328 /// combinations of simpler operations.
1330 const Function &Fn) const;
1331
1332 /// @}
1333
1334 /// \name Vector Target Information
1335 /// @{
1336
1337 /// The various kinds of shuffle patterns for vector queries.
1339 SK_Broadcast, ///< Broadcast element 0 to all other elements.
1340 SK_Reverse, ///< Reverse the order of the vector.
1341 SK_Select, ///< Selects elements from the corresponding lane of
1342 ///< either source operand. This is equivalent to a
1343 ///< vector select with a constant condition operand.
1344 SK_Transpose, ///< Transpose two vectors.
1345 SK_InsertSubvector, ///< InsertSubvector. Index indicates start offset.
1346 SK_ExtractSubvector, ///< ExtractSubvector Index indicates start offset.
1347 SK_PermuteTwoSrc, ///< Merge elements from two source vectors into one
1348 ///< with any shuffle mask.
1349 SK_PermuteSingleSrc, ///< Shuffle elements of single source vector with any
1350 ///< shuffle mask.
1351 SK_Splice ///< Concatenates elements from the first input vector
1352 ///< with elements of the second input vector. Returning
1353 ///< a vector of the same type as the input vectors.
1354 ///< Index indicates start offset in first input vector.
1355 };
1356
1357 /// Additional information about an operand's possible values.
1359 OK_AnyValue, // Operand can have any value.
1360 OK_UniformValue, // Operand is uniform (splat of a value).
1361 OK_UniformConstantValue, // Operand is uniform constant.
1362 OK_NonUniformConstantValue // Operand is a non uniform constant value.
1363 };
1364
1365 /// Additional properties of an operand's values.
1371
1372 // Describe the values an operand can take. We're in the process
1373 // of migrating uses of OperandValueKind and OperandValueProperties
1374 // to use this class, and then will change the internal representation.
1378
1379 bool isConstant() const {
1381 }
1382 bool isUniform() const {
1384 }
1385 bool isPowerOf2() const {
1386 return Properties == OP_PowerOf2;
1387 }
1388 bool isNegatedPowerOf2() const {
1390 }
1391
1393 return {Kind, OP_None};
1394 }
1395
1397 OperandValueKind MergeKind = OK_AnyValue;
1398 if (isConstant() && OpInfoY.isConstant())
1399 MergeKind = OK_NonUniformConstantValue;
1400
1401 OperandValueProperties MergeProp = OP_None;
1402 if (Properties == OpInfoY.Properties)
1403 MergeProp = Properties;
1404 return {MergeKind, MergeProp};
1405 }
1406 };
1407
1408 /// \return the number of registers in the target-provided register class.
1409 LLVM_ABI unsigned getNumberOfRegisters(unsigned ClassID) const;
1410
1411 /// \return true if the target supports load/store that enables fault
1412 /// suppression of memory operands when the source condition is false.
1413 LLVM_ABI bool hasConditionalLoadStoreForType(Type *Ty, bool IsStore) const;
1414
1415 /// \return the target-provided register class ID for the provided type,
1416 /// accounting for type promotion and other type-legalization techniques that
1417 /// the target might apply. However, it specifically does not account for the
1418 /// scalarization or splitting of vector types. Should a vector type require
1419 /// scalarization or splitting into multiple underlying vector registers, that
1420 /// type should be mapped to a register class containing no registers.
1421 /// Specifically, this is designed to provide a simple, high-level view of the
1422 /// register allocation later performed by the backend. These register classes
1423 /// don't necessarily map onto the register classes used by the backend.
1424 /// FIXME: It's not currently possible to determine how many registers
1425 /// are used by the provided type.
1427 Type *Ty = nullptr) const;
1428
1429 /// \return the target-provided register class name
1430 LLVM_ABI const char *getRegisterClassName(unsigned ClassID) const;
1431
1432 /// \return the cost of spilling a register in the target-provided register
1433 /// class to the stack.
1435 getRegisterClassSpillCost(unsigned ClassID, TargetCostKind CostKind) const;
1436
1437 /// \return the cost of reloading a register in the target-provided register
1438 /// class from the stack.
1440 getRegisterClassReloadCost(unsigned ClassID, TargetCostKind CostKind) const;
1441
1443
1444 /// \return The width of the largest scalar or vector register type.
1445 LLVM_ABI TypeSize getRegisterBitWidth(RegisterKind K) const;
1446
1447 /// \return The width of the smallest vector register type.
1448 LLVM_ABI unsigned getMinVectorRegisterBitWidth() const;
1449
1450 /// \return the value of vscale to tune the cost model for.
1451 LLVM_ABI std::optional<unsigned> getVScaleForTuning() const;
1452
1453 /// \return True if the vectorization factor should be chosen to
1454 /// make the vector of the smallest element type match the size of a
1455 /// vector register. For wider element types, this could result in
1456 /// creating vectors that span multiple vector registers.
1457 /// If false, the vectorization factor will be chosen based on the
1458 /// size of the widest element type.
1459 /// \p K Register Kind for vectorization.
1460 LLVM_ABI bool
1462
1463 /// \return The minimum vectorization factor for types of given element
1464 /// bit width, or 0 if there is no minimum VF. The returned value only
1465 /// applies when shouldMaximizeVectorBandwidth returns true.
1466 /// If IsScalable is true, the returned ElementCount must be a scalable VF.
1467 LLVM_ABI ElementCount getMinimumVF(unsigned ElemWidth, bool IsScalable) const;
1468
1469 /// \return The maximum vectorization factor for types of given element
1470 /// bit width and opcode, or 0 if there is no maximum VF.
1471 /// Currently only used by the SLP vectorizer.
1472 LLVM_ABI unsigned getMaximumVF(unsigned ElemWidth, unsigned Opcode) const;
1473
1474 /// \return The minimum vectorization factor for the store instruction. Given
1475 /// the initial estimation of the minimum vector factor and store value type,
1476 /// it tries to find possible lowest VF, which still might be profitable for
1477 /// the vectorization.
1478 /// \param VF Initial estimation of the minimum vector factor.
1479 /// \param ScalarMemTy Scalar memory type of the store operation.
1480 /// \param ScalarValTy Scalar type of the stored value.
1481 /// \param Alignment Alignment of the store
1482 /// \param AddrSpace Address space of the store
1483 /// Currently only used by the SLP vectorizer.
1484 LLVM_ABI unsigned getStoreMinimumVF(unsigned VF, Type *ScalarMemTy,
1485 Type *ScalarValTy, Align Alignment,
1486 unsigned AddrSpace) const;
1487
1488 /// \return True if it should be considered for address type promotion.
1489 /// \p AllowPromotionWithoutCommonHeader Set true if promoting \p I is
1490 /// profitable without finding other extensions fed by the same input.
1492 const Instruction &I, bool &AllowPromotionWithoutCommonHeader) const;
1493
1494 /// \return The size of a cache line in bytes.
1495 LLVM_ABI unsigned getCacheLineSize() const;
1496
1497 /// The possible cache levels
1498 enum class CacheLevel {
1499 L1D, // The L1 data cache
1500 L2D, // The L2 data cache
1501
1502 // We currently do not model L3 caches, as their sizes differ widely between
1503 // microarchitectures. Also, we currently do not have a use for L3 cache
1504 // size modeling yet.
1505 };
1506
1507 /// \return The size of the cache level in bytes, if available.
1508 LLVM_ABI std::optional<unsigned> getCacheSize(CacheLevel Level) const;
1509
1510 /// \return The associativity of the cache level, if available.
1511 LLVM_ABI std::optional<unsigned>
1512 getCacheAssociativity(CacheLevel Level) const;
1513
1514 /// \return The minimum architectural page size for the target.
1515 LLVM_ABI std::optional<unsigned> getMinPageSize() const;
1516
1517 /// \return How much before a load we should place the prefetch
1518 /// instruction. This is currently measured in number of
1519 /// instructions.
1520 LLVM_ABI unsigned getPrefetchDistance() const;
1521
1522 /// Some HW prefetchers can handle accesses up to a certain constant stride.
1523 /// Sometimes prefetching is beneficial even below the HW prefetcher limit,
1524 /// and the arguments provided are meant to serve as a basis for deciding this
1525 /// for a particular loop.
1526 ///
1527 /// \param NumMemAccesses Number of memory accesses in the loop.
1528 /// \param NumStridedMemAccesses Number of the memory accesses that
1529 /// ScalarEvolution could find a known stride
1530 /// for.
1531 /// \param NumPrefetches Number of software prefetches that will be
1532 /// emitted as determined by the addresses
1533 /// involved and the cache line size.
1534 /// \param HasCall True if the loop contains a call.
1535 ///
1536 /// \return This is the minimum stride in bytes where it makes sense to start
1537 /// adding SW prefetches. The default is 1, i.e. prefetch with any
1538 /// stride.
1539 LLVM_ABI unsigned getMinPrefetchStride(unsigned NumMemAccesses,
1540 unsigned NumStridedMemAccesses,
1541 unsigned NumPrefetches,
1542 bool HasCall) const;
1543
1544 /// \return The maximum number of iterations to prefetch ahead. If
1545 /// the required number of iterations is more than this number, no
1546 /// prefetching is performed.
1547 LLVM_ABI unsigned getMaxPrefetchIterationsAhead() const;
1548
1549 /// \return True if prefetching should also be done for writes.
1550 LLVM_ABI bool enableWritePrefetching() const;
1551
1552 /// \return if target want to issue a prefetch in address space \p AS.
1553 LLVM_ABI bool shouldPrefetchAddressSpace(unsigned AS) const;
1554
1555 /// \return The cost of a partial reduction, which is a reduction from a
1556 /// vector to another vector with fewer elements of larger size. They are
1557 /// represented by the llvm.vector.partial.reduce.add and
1558 /// llvm.vector.partial.reduce.fadd intrinsics, which take an accumulator of
1559 /// type \p AccumType and a second vector operand to be accumulated, whose
1560 /// element count is specified by \p VF. The type of reduction is specified by
1561 /// \p Opcode. The second operand passed to the intrinsic could be the result
1562 /// of an extend, such as sext or zext. In this case \p BinOp is nullopt,
1563 /// \p InputTypeA represents the type being extended and \p OpAExtend the
1564 /// operation, i.e. sign- or zero-extend.
1565 /// For floating-point partial reductions, any fast math flags (FMF) should be
1566 /// provided to govern which reductions are valid to perform (depending on
1567 /// reassoc or contract, for example), whereas this must be nullopt for
1568 /// integer partial reductions.
1569 /// Also, \p InputTypeB should be nullptr and OpBExtend should be None.
1570 /// Alternatively, the second operand could be the result of a binary
1571 /// operation performed on two extends, i.e.
1572 /// mul(zext i8 %a -> i32, zext i8 %b -> i32).
1573 /// In this case \p BinOp may specify the opcode of the binary operation,
1574 /// \p InputTypeA and \p InputTypeB the types being extended, and
1575 /// \p OpAExtend, \p OpBExtend the form of extensions. An example of an
1576 /// operation that uses a partial reduction is a dot product, which reduces
1577 /// two vectors in binary mul operation to another of 4 times fewer and 4
1578 /// times larger elements.
1580 unsigned Opcode, Type *InputTypeA, Type *InputTypeB, Type *AccumType,
1582 PartialReductionExtendKind OpBExtend, std::optional<unsigned> BinOp,
1583 TTI::TargetCostKind CostKind, std::optional<FastMathFlags> FMF) const;
1584
1585 /// \return The maximum interleave factor that any transform should try to
1586 /// perform for this target. This number depends on the level of parallelism
1587 /// and the number of execution units in the CPU. HasUnorderedReductions
1588 /// specifies whether (unordered) reductions are present in the loop being
1589 /// vectorized.
1591 bool HasUnorderedReductions) const;
1592
1593 /// Collect properties of V used in cost analysis, e.g. OP_PowerOf2.
1594 LLVM_ABI static OperandValueInfo getOperandInfo(const Value *V);
1595
1596 /// Return information about the vector formed for the specified index
1597 /// of a vector of (the same) instruction.
1598 LLVM_ABI static OperandValueInfo getOperandInfo(ArrayRef<Value *> Ops);
1599
1600 /// Collect common data between two OperandValueInfo inputs
1601 LLVM_ABI static OperandValueInfo commonOperandInfo(const Value *X,
1602 const Value *Y);
1603
1604 /// This is an approximation of reciprocal throughput of a math/logic op.
1605 /// A higher cost indicates less expected throughput.
1606 /// From Agner Fog's guides, reciprocal throughput is "the average number of
1607 /// clock cycles per instruction when the instructions are not part of a
1608 /// limiting dependency chain."
1609 /// Therefore, costs should be scaled to account for multiple execution units
1610 /// on the target that can process this type of instruction. For example, if
1611 /// there are 5 scalar integer units and 2 vector integer units that can
1612 /// calculate an 'add' in a single cycle, this model should indicate that the
1613 /// cost of the vector add instruction is 2.5 times the cost of the scalar
1614 /// add instruction.
1615 /// \p Args is an optional argument which holds the instruction operands
1616 /// values so the TTI can analyze those values searching for special
1617 /// cases or optimizations based on those values.
1618 /// \p CtxI is the optional original context instruction, if one exists, to
1619 /// provide even more information.
1620 /// \p TLibInfo is used to search for platform specific vector library
1621 /// functions for instructions that might be converted to calls (e.g. frem).
1623 unsigned Opcode, Type *Ty, TTI::TargetCostKind CostKind,
1626 ArrayRef<const Value *> Args = {}, const Instruction *CtxI = nullptr,
1627 const TargetLibraryInfo *TLibInfo = nullptr) const;
1628
1629 /// Returns the cost estimation for alternating opcode pattern that can be
1630 /// lowered to a single instruction on the target. In X86 this is for the
1631 /// addsub instruction which corrsponds to a Shuffle + Fadd + FSub pattern in
1632 /// IR. This function expects two opcodes: \p Opcode1 and \p Opcode2 being
1633 /// selected by \p OpcodeMask. The mask contains one bit per lane and is a `0`
1634 /// when \p Opcode0 is selected and `1` when Opcode1 is selected.
1635 /// \p VecTy is the vector type of the instruction to be generated.
1636 /// \p Scalars are the scalar instructions of the lanes, if known. The target
1637 /// may use them to find the patterns, which depend on the operands, like
1638 /// the alternating fused multiply-add.
1640 VectorType *VecTy, unsigned Opcode0, unsigned Opcode1,
1641 const SmallBitVector &OpcodeMask, TTI::TargetCostKind CostKind,
1642 ArrayRef<const Value *> Scalars = {}) const;
1643
1644 /// \return The cost of a shuffle instruction of kind Kind with inputs of type
1645 /// SrcTy, producing a vector of type DstTy. The exact mask may be passed as
1646 /// Mask, or else the array will be empty. The Index and SubTp parameters
1647 /// are used by the subvector insertions shuffle kinds to show the insert
1648 /// point and the type of the subvector being inserted. The operands of the
1649 /// shuffle can be passed through \p Args, which helps improve the cost
1650 /// estimation in some cases, like in broadcast loads.
1652 ShuffleKind Kind, VectorType *DstTy, VectorType *SrcTy,
1653 TTI::TargetCostKind CostKind, ArrayRef<int> Mask = {}, int Index = 0,
1654 VectorType *SubTp = nullptr, ArrayRef<const Value *> Args = {},
1655 const Instruction *CtxI = nullptr,
1657
1658 /// Represents a hint about the context in which a cast is used.
1659 ///
1660 /// For zext/sext, the context of the cast is the operand, which must be a
1661 /// load of some kind. For trunc, the context is of the cast is the single
1662 /// user of the instruction, which must be a store of some kind.
1663 ///
1664 /// This enum allows the vectorizer to give getCastInstrCost an idea of the
1665 /// type of cast it's dealing with, as not every cast is equal. For instance,
1666 /// the zext of a load may be free, but the zext of an interleaving load can
1667 //// be (very) expensive!
1668 ///
1669 /// See \c getCastContextHint to compute a CastContextHint from a cast
1670 /// Instruction*. Callers can use it if they don't need to override the
1671 /// context and just want it to be calculated from the instruction.
1672 ///
1673 /// FIXME: This handles the types of load/store that the vectorizer can
1674 /// produce, which are the cases where the context instruction is most
1675 /// likely to be incorrect. There are other situations where that can happen
1676 /// too, which might be handled here but in the long run a more general
1677 /// solution of costing multiple instructions at the same times may be better.
1679 None, ///< The cast is not used with a load/store of any kind.
1680 Normal, ///< The cast is used with a normal load/store.
1681 Masked, ///< The cast is used with a masked load/store.
1682 GatherScatter, ///< The cast is used with a gather/scatter.
1683 Interleave, ///< The cast is used with an interleaved load/store.
1684 Reversed, ///< The cast is used with a reversed load/store.
1685 };
1686
1687 /// Calculates a CastContextHint from \p I.
1688 /// This should be used by callers of getCastInstrCost if they wish to
1689 /// determine the context from some instruction.
1690 /// \returns the CastContextHint for ZExt/SExt/Trunc, None if \p I is nullptr,
1691 /// or if it's another type of cast.
1693
1694 /// \return The expected cost of cast instructions, such as bitcast, trunc,
1695 /// zext, etc. If there is an existing instruction that holds Opcode, it
1696 /// may be passed in the 'I' parameter.
1698 unsigned Opcode, Type *Dst, Type *Src, TTI::CastContextHint CCH,
1699 TTI::TargetCostKind CostKind, const Instruction *I = nullptr) const;
1700
1701 /// \return The expected cost of a sign- or zero-extended vector extract. Use
1702 /// Index = -1 to indicate that there is no information about the index value.
1704 getExtractWithExtendCost(unsigned Opcode, Type *Dst, VectorType *VecTy,
1705 unsigned Index, TTI::TargetCostKind CostKind) const;
1706
1707 /// \return The expected cost of control-flow related instructions such as
1708 /// Phi, Ret, Br, Switch.
1709 LLVM_ABI InstructionCost getCFInstrCost(unsigned Opcode,
1710 TTI::TargetCostKind CostKind,
1711 const Instruction *I = nullptr) const;
1712
1713 /// \returns The expected cost of compare and select instructions. If there
1714 /// is an existing instruction that holds Opcode, it may be passed in the
1715 /// 'I' parameter. The \p VecPred parameter can be used to indicate the select
1716 /// is using a compare with the specified predicate as condition. When vector
1717 /// types are passed, \p VecPred must be used for all lanes. For a
1718 /// comparison, the two operands are the natural values. For a select, the
1719 /// two operands are the *value* operands, not the condition operand.
1721 getCmpSelInstrCost(unsigned Opcode, Type *ValTy, Type *CondTy,
1722 CmpInst::Predicate VecPred, TTI::TargetCostKind CostKind,
1723 OperandValueInfo Op1Info = {OK_AnyValue, OP_None},
1724 OperandValueInfo Op2Info = {OK_AnyValue, OP_None},
1725 const Instruction *I = nullptr) const;
1726
1727 /// \return The expected cost of vector Insert and Extract.
1728 /// Use -1 to indicate that there is no information on the index value.
1729 /// This is used when the instruction is not available; a typical use
1730 /// case is to provision the cost of vectorization/scalarization in
1731 /// vectorizer passes.
1733 unsigned Opcode, Type *Val, TTI::TargetCostKind CostKind,
1734 unsigned Index = -1, const Value *Op0 = nullptr,
1735 const Value *Op1 = nullptr,
1737
1738 /// \return The expected cost of vector Insert and Extract.
1739 /// Use -1 to indicate that there is no information on the index value.
1740 /// This is used when the instruction is not available; a typical use
1741 /// case is to provision the cost of vectorization/scalarization in
1742 /// vectorizer passes.
1743 /// \param ScalarUserAndIdx encodes the information about extracts from a
1744 /// vector with 'Scalar' being the value being extracted,'User' being the user
1745 /// of the extract(nullptr if user is not known before vectorization) and
1746 /// 'Idx' being the extract lane.
1748 unsigned Opcode, Type *Val, TTI::TargetCostKind CostKind, unsigned Index,
1749 Value *Scalar,
1750 ArrayRef<std::tuple<Value *, User *, int>> ScalarUserAndIdx,
1752
1753 /// \return The expected cost of vector Insert and Extract.
1754 /// This is used when instruction is available, and implementation
1755 /// asserts 'I' is not nullptr.
1756 ///
1757 /// A typical suitable use case is cost estimation when vector instruction
1758 /// exists (e.g., from basic blocks during transformation).
1760 const Instruction &I, Type *Val, TTI::TargetCostKind CostKind,
1761 unsigned Index = -1,
1763
1764 /// \return The expected cost of inserting or extracting a lane that is \p
1765 /// Index elements from the end of a vector, i.e. the mathematical expression
1766 /// for the lane is (VF - 1 - Index). This is required for scalable vectors
1767 /// where the exact lane index is unknown at compile time.
1769 unsigned Opcode, Type *Val, TTI::TargetCostKind CostKind,
1770 unsigned Index) const;
1771
1772 /// \return The expected cost of aggregate inserts and extracts. This is
1773 /// used when the instruction is not available; a typical use case is to
1774 /// provision the cost of vectorization/scalarization in vectorizer passes.
1776 unsigned Opcode, TTI::TargetCostKind CostKind) const;
1777
1778 /// \return The cost of replication shuffle of \p VF elements typed \p EltTy
1779 /// \p ReplicationFactor times.
1780 ///
1781 /// For example, the mask for \p ReplicationFactor=3 and \p VF=4 is:
1782 /// <0,0,0,1,1,1,2,2,2,3,3,3>
1784 Type *EltTy, int ReplicationFactor, int VF, const APInt &DemandedDstElts,
1785 TTI::TargetCostKind CostKind) const;
1786
1787 /// \return The cost of Load and Store instructions. The operand info
1788 /// \p OpdInfo should refer to the stored value for stores and the address
1789 /// for loads.
1791 getMemoryOpCost(unsigned Opcode, Type *Src, Align Alignment,
1792 unsigned AddressSpace, TTI::TargetCostKind CostKind,
1794 const Instruction *I = nullptr) const;
1795
1796 /// \return The cost of the interleaved memory operation.
1797 /// \p Opcode is the memory operation code
1798 /// \p VecTy is the vector type of the interleaved access.
1799 /// \p Factor is the interleave factor
1800 /// \p Indices is the indices for interleaved load members (as interleaved
1801 /// load allows gaps)
1802 /// \p Alignment is the alignment of the memory operation
1803 /// \p AddressSpace is address space of the pointer.
1804 /// \p UseMaskForCond indicates if the memory access is predicated.
1805 /// \p UseMaskForGaps indicates if gaps should be masked.
1807 unsigned Opcode, Type *VecTy, unsigned Factor, ArrayRef<unsigned> Indices,
1808 Align Alignment, unsigned AddressSpace, TTI::TargetCostKind CostKind,
1809 bool UseMaskForCond = false, bool UseMaskForGaps = false) const;
1810
1811 /// A helper function to determine the type of reduction algorithm used
1812 /// for a given \p Opcode and set of FastMathFlags \p FMF.
1813 static bool requiresOrderedReduction(std::optional<FastMathFlags> FMF) {
1814 return FMF && !(*FMF).allowReassoc();
1815 }
1816
1817 /// Calculate the cost of vector reduction intrinsics.
1818 ///
1819 /// This is the cost of reducing the vector value of type \p Ty to a scalar
1820 /// value using the operation denoted by \p Opcode. The FastMathFlags
1821 /// parameter \p FMF indicates what type of reduction we are performing:
1822 /// 1. Tree-wise. This is the typical 'fast' reduction performed that
1823 /// involves successively splitting a vector into half and doing the
1824 /// operation on the pair of halves until you have a scalar value. For
1825 /// example:
1826 /// (v0, v1, v2, v3)
1827 /// ((v0+v2), (v1+v3), undef, undef)
1828 /// ((v0+v2+v1+v3), undef, undef, undef)
1829 /// This is the default behaviour for integer operations, whereas for
1830 /// floating point we only do this if \p FMF indicates that
1831 /// reassociation is allowed.
1832 /// 2. Ordered. For a vector with N elements this involves performing N
1833 /// operations in lane order, starting with an initial scalar value, i.e.
1834 /// result = InitVal + v0
1835 /// result = result + v1
1836 /// result = result + v2
1837 /// result = result + v3
1838 /// This is only the case for FP operations and when reassociation is not
1839 /// allowed.
1840 ///
1842 unsigned Opcode, VectorType *Ty, std::optional<FastMathFlags> FMF,
1843 TTI::TargetCostKind CostKind) const;
1844
1847 TTI::TargetCostKind CostKind) const;
1848
1849 /// Calculate the cost of an extended reduction pattern, similar to
1850 /// getArithmeticReductionCost of an Add/Sub reduction with multiply and
1851 /// optional extensions. This is the cost of as:
1852 /// * ResTy vecreduce.add/sub(mul (A, B)) or,
1853 /// * ResTy vecreduce.add/sub(mul(ext(Ty A), ext(Ty B)).
1855 getMulAccReductionCost(bool IsUnsigned, unsigned RedOpcode, Type *ResTy,
1856 VectorType *Ty, TTI::TargetCostKind CostKind) const;
1857
1858 /// Calculate the cost of an extended reduction pattern, similar to
1859 /// getArithmeticReductionCost of a reduction with an extension.
1860 /// This is the cost of as:
1861 /// ResTy vecreduce.opcode(ext(Ty A)).
1863 unsigned Opcode, bool IsUnsigned, Type *ResTy, VectorType *Ty,
1864 std::optional<FastMathFlags> FMF, TTI::TargetCostKind CostKind) const;
1865
1866 /// \returns The cost of Intrinsic instructions. Analyses the real arguments.
1867 /// Three cases are handled: 1. scalar instruction 2. vector instruction
1868 /// 3. scalar instruction which is to be vectorized.
1870 const IntrinsicCostAttributes &ICA, TTI::TargetCostKind CostKind) const;
1871
1872 /// \returns The cost of memory intrinsic instructions.
1873 /// Used when IntrinsicInst is not materialized.
1876 TTI::TargetCostKind CostKind) const;
1877
1878 /// \returns The cost of Call instructions.
1880 ArrayRef<Type *> Tys,
1881 TTI::TargetCostKind CostKind) const;
1882
1883 /// \returns The number of pieces into which the provided type must be
1884 /// split during legalization. Zero is returned when the answer is unknown.
1885 LLVM_ABI unsigned getNumberOfParts(Type *Tp) const;
1886
1887 /// \returns The cost of the address computation. For most targets this can be
1888 /// merged into the instruction indexing mode. Some targets might want to
1889 /// distinguish between address computation for memory operations with vector
1890 /// pointer types and scalar pointer types. Such targets should override this
1891 /// function. \p SE holds the pointer for the scalar evolution object which
1892 /// was used in order to get the Ptr step value. \p Ptr holds the SCEV of the
1893 /// access pointer.
1895 getAddressComputationCost(Type *PtrTy, ScalarEvolution *SE, const SCEV *Ptr,
1896 TTI::TargetCostKind CostKind) const;
1897
1898 /// \returns The cost, if any, of keeping values of the given types alive
1899 /// over a callsite.
1900 ///
1901 /// Some types may require the use of register classes that do not have
1902 /// any callee-saved registers, so would require a spill and fill.
1905
1906 /// \returns True if the intrinsic is a supported memory intrinsic. Info
1907 /// will contain additional information - whether the intrinsic may write
1908 /// or read to memory, volatility and the pointer. Info is undefined
1909 /// if false is returned.
1911 MemIntrinsicInfo &Info) const;
1912
1913 /// \returns The maximum element size, in bytes, for an element
1914 /// unordered-atomic memory intrinsic.
1916
1917 /// \returns A value which is the result of the given memory intrinsic. If \p
1918 /// CanCreate is true, new instructions may be created to extract the result
1919 /// from the given intrinsic memory operation. Returns nullptr if the target
1920 /// cannot create a result from the given intrinsic.
1921 LLVM_ABI Value *
1923 bool CanCreate = true) const;
1924
1925 /// \returns The type to use in a loop expansion of a memcpy call.
1927 LLVMContext &Context, Value *Length, unsigned SrcAddrSpace,
1928 unsigned DestAddrSpace, Align SrcAlign, Align DestAlign,
1929 std::optional<uint32_t> AtomicElementSize = std::nullopt) const;
1930
1931 /// \param[out] OpsOut The operand types to copy RemainingBytes of memory.
1932 /// \param RemainingBytes The number of bytes to copy.
1933 ///
1934 /// Calculates the operand types to use when copying \p RemainingBytes of
1935 /// memory, where source and destination alignments are \p SrcAlign and
1936 /// \p DestAlign respectively.
1938 SmallVectorImpl<Type *> &OpsOut, LLVMContext &Context,
1939 unsigned RemainingBytes, unsigned SrcAddrSpace, unsigned DestAddrSpace,
1940 Align SrcAlign, Align DestAlign,
1941 std::optional<uint32_t> AtomicCpySize = std::nullopt) const;
1942
1943 /// \returns True if the two functions have compatible attributes for inlining
1944 /// purposes.
1945 LLVM_ABI bool areInlineCompatible(const Function *Caller,
1946 const Function *Callee) const;
1947
1948 /// Returns a penalty for invoking call \p Call in \p F.
1949 /// For example, if a function F calls a function G, which in turn calls
1950 /// function H, then getInlineCallPenalty(F, H()) would return the
1951 /// penalty of calling H from F, e.g. after inlining G into F.
1952 /// \p DefaultCallPenalty is passed to give a default penalty that
1953 /// the target can amend or override.
1954 LLVM_ABI unsigned getInlineCallPenalty(const Function *F,
1955 const CallBase &Call,
1956 unsigned DefaultCallPenalty) const;
1957
1958 /// \returns true if `Caller`'s `Attr` should be added to the new function
1959 /// created by outlining part of `Caller`.
1960 LLVM_ABI bool
1962 const Attribute &Attr) const;
1963
1964 /// \returns True if the caller and callee agree on how \p Types will be
1965 /// passed to or returned from the callee.
1966 /// to the callee.
1967 /// \param Types List of types to check.
1968 LLVM_ABI bool areTypesABICompatible(const Function *Caller,
1969 const Function *Callee,
1970 ArrayRef<Type *> Types) const;
1971
1972 /// The type of load/store indexing.
1974 MIM_Unindexed, ///< No indexing.
1975 MIM_PreInc, ///< Pre-incrementing.
1976 MIM_PreDec, ///< Pre-decrementing.
1977 MIM_PostInc, ///< Post-incrementing.
1978 MIM_PostDec ///< Post-decrementing.
1979 };
1980
1981 /// \returns True if the specified indexed load for the given type is legal.
1982 LLVM_ABI bool isIndexedLoadLegal(enum MemIndexedMode Mode, Type *Ty) const;
1983
1984 /// \returns True if the specified indexed store for the given type is legal.
1985 LLVM_ABI bool isIndexedStoreLegal(enum MemIndexedMode Mode, Type *Ty) const;
1986
1987 /// \returns The bitwidth of the largest vector type that should be used to
1988 /// load/store in the given address space.
1989 LLVM_ABI unsigned getLoadStoreVecRegBitWidth(unsigned AddrSpace) const;
1990
1991 /// \returns True if the load instruction is legal to vectorize.
1993
1994 /// \returns True if the store instruction is legal to vectorize.
1996
1997 /// \returns True if it is legal to vectorize the given load chain.
1998 LLVM_ABI bool isLegalToVectorizeLoadChain(unsigned ChainSizeInBytes,
1999 Align Alignment,
2000 unsigned AddrSpace) const;
2001
2002 /// \returns True if it is legal to vectorize the given store chain.
2003 LLVM_ABI bool isLegalToVectorizeStoreChain(unsigned ChainSizeInBytes,
2004 Align Alignment,
2005 unsigned AddrSpace) const;
2006
2007 /// \returns True if it is legal to vectorize the given reduction kind.
2009 ElementCount VF) const;
2010
2011 /// \returns True if the given type is supported for scalable vectors
2013
2014 /// \returns The new vector factor value if the target doesn't support \p
2015 /// SizeInBytes loads or has a better vector factor.
2016 LLVM_ABI unsigned getLoadVectorFactor(unsigned VF, unsigned LoadSize,
2017 unsigned ChainSizeInBytes,
2018 VectorType *VecTy) const;
2019
2020 /// \returns The new vector factor value if the target doesn't support \p
2021 /// SizeInBytes stores or has a better vector factor.
2022 LLVM_ABI unsigned getStoreVectorFactor(unsigned VF, unsigned StoreSize,
2023 unsigned ChainSizeInBytes,
2024 VectorType *VecTy) const;
2025
2026 /// \returns True if the target prefers fixed width vectorization if the
2027 /// loop vectorizer's cost-model assigns an equal cost to the fixed and
2028 /// scalable version of the vectorized loop.
2030
2031 /// \returns True if target prefers SLP vectorizer with altermate opcode
2032 /// vectorization, false - otherwise.
2034
2035 /// \returns True if the SLP vectorizer should apply the instruction-count
2036 /// check that rejects 2-element vector trees when the vector instruction
2037 /// count exceeds the scalar instruction count, false if the target opts out
2038 /// of this heuristic.
2039 LLVM_ABI bool preferSLPInstCountCheck() const;
2040
2041 /// \returns True if the target prefers reductions of \p Kind to be performed
2042 /// in the loop.
2043 LLVM_ABI bool preferInLoopReduction(RecurKind Kind, Type *Ty) const;
2044
2045 /// \returns True if the target prefers reductions select kept in the loop
2046 /// when tail folding. i.e.
2047 /// loop:
2048 /// p = phi (0, s)
2049 /// a = add (p, x)
2050 /// s = select (mask, a, p)
2051 /// vecreduce.add(s)
2052 ///
2053 /// As opposed to the normal scheme of p = phi (0, a) which allows the select
2054 /// to be pulled out of the loop. If the select(.., add, ..) can be predicated
2055 /// by the target, this can lead to cleaner code generation.
2057
2058 /// Return true if the loop vectorizer should consider vectorizing an
2059 /// otherwise scalar epilogue loop if the loop already has been vectorized
2060 /// processing \p Iters scalar iterations per vector iteration.
2062
2063 /// \returns True if the loop vectorizer should discard any VFs where the
2064 /// maximum register pressure exceeds getNumberOfRegisters.
2066
2067 /// \returns True if the target wants to expand the given reduction intrinsic
2068 /// into a shuffle sequence.
2070
2072
2073 /// \returns The shuffle sequence pattern used to expand the given reduction
2074 /// intrinsic.
2077
2078 /// \returns the size cost of rematerializing a GlobalValue address relative
2079 /// to a stack reload.
2080 LLVM_ABI unsigned getGISelRematGlobalCost() const;
2081
2082 /// \returns the lower bound of a trip count to decide on vectorization
2083 /// while tail-folding.
2085
2086 /// \returns True if the target supports scalable vectors.
2087 LLVM_ABI bool supportsScalableVectors() const;
2088
2089 /// \return true when scalable vectorization is preferred.
2091
2092 /// \name Vector Predication Information
2093 /// @{
2094 /// Whether the target supports the %evl parameter of VP intrinsic efficiently
2095 /// in hardware. (see LLVM Language Reference - "Vector Predication
2096 /// Intrinsics"). Use of %evl is discouraged when that is not the case.
2097 LLVM_ABI bool hasActiveVectorLength() const;
2098
2099 /// Return true if sinking I's operands to the same basic block as I is
2100 /// profitable, e.g. because the operands can be folded into a target
2101 /// instruction during instruction selection. After calling the function
2102 /// \p Ops contains the Uses to sink ordered by dominance (dominating users
2103 /// come first). \p LI, when available, lets targets account for loop
2104 /// boundaries when deciding profitability.
2107 const LoopInfo *LI = nullptr) const;
2108
2109 /// Return true if it's significantly cheaper to shift a vector by a uniform
2110 /// scalar than by an amount which will vary across each lane. On x86 before
2111 /// AVX2 for example, there is a "psllw" instruction for the former case, but
2112 /// no simple instruction for a general "a << b" operation on vectors.
2113 /// This should also apply to lowering for vector funnel shifts (rotates).
2115
2118 // keep the predicating parameter
2120 // where legal, discard the predicate parameter
2122 // transform into something else that is also predicating
2124 };
2125
2126 // How to transform the EVL parameter.
2127 // Legal: keep the EVL parameter as it is.
2128 // Discard: Ignore the EVL parameter where it is safe to do so.
2129 // Convert: Fold the EVL into the mask parameter.
2131
2132 // How to transform the operator.
2133 // Legal: The target supports this operator.
2134 // Convert: Convert this to a non-VP operation.
2135 // The 'Discard' strategy is invalid.
2137
2138 bool shouldDoNothing() const {
2139 return (EVLParamStrategy == Legal) && (OpStrategy == Legal);
2140 }
2143 };
2144
2145 /// \returns How the target needs this vector-predicated operation to be
2146 /// transformed.
2148 getVPLegalizationStrategy(const VPIntrinsic &PI) const;
2149 /// @}
2150
2151 /// \returns Whether a 32-bit branch instruction is available in Arm or Thumb
2152 /// state.
2153 ///
2154 /// Used by the LowerTypeTests pass, which constructs an IR inline assembler
2155 /// node containing a jump table in a format suitable for the target, so it
2156 /// needs to know what format of jump table it can legally use.
2157 ///
2158 /// For non-Arm targets, this function isn't used. It defaults to returning
2159 /// false, but it shouldn't matter what it returns anyway.
2160 LLVM_ABI bool hasArmWideBranch(bool Thumb) const;
2161
2162 /// Returns a bitmask constructed from the target-features or fmv-features
2163 /// metadata of a function corresponding to its Arch Extensions.
2164 LLVM_ABI APInt getFeatureMask(const Function &F) const;
2165
2166 /// Returns a bitmask constructed from the target-features or fmv-features
2167 /// metadata of a function corresponding to its FMV priority.
2168 LLVM_ABI APInt getPriorityMask(const Function &F) const;
2169
2170 /// Returns true if this is an instance of a function with multiple versions.
2171 LLVM_ABI bool isMultiversionedFunction(const Function &F) const;
2172
2173 /// \return The maximum number of function arguments the target supports.
2174 LLVM_ABI unsigned getMaxNumArgs() const;
2175
2176 /// @}
2177
2178 /// Collect kernel launch bounds for \p F into \p LB.
2180 const Function &F,
2181 SmallVectorImpl<std::pair<StringRef, int64_t>> &LB) const;
2182
2183 /// Returns true if GEP should not be used to index into vectors for this
2184 /// target.
2186
2187 /// Determine if an instruction with Custom uniformity can be proven uniform
2188 /// based on which operands are uniform.
2189 ///
2190 /// \param I The instruction to check.
2191 /// \param UniformArgs A bitvector indicating which operands are known to be
2192 /// uniform (bit N corresponds to operand N).
2193 /// \returns true if the instruction result can be proven uniform given the
2194 /// uniform operands, false otherwise.
2195 LLVM_ABI bool isUniform(const Instruction *I,
2196 const SmallBitVector &UniformArgs) const;
2197
2198private:
2199 std::unique_ptr<const TargetTransformInfoImplBase> TTIImpl;
2200};
2201
2202/// Analysis pass providing the \c TargetTransformInfo.
2203///
2204/// The core idea of the TargetIRAnalysis is to expose an interface through
2205/// which LLVM targets can analyze and provide information about the middle
2206/// end's target-independent IR. This supports use cases such as target-aware
2207/// cost modeling of IR constructs.
2208///
2209/// This is a function analysis because much of the cost modeling for targets
2210/// is done in a subtarget specific way and LLVM supports compiling different
2211/// functions targeting different subtargets in order to support runtime
2212/// dispatch according to the observed subtarget.
2213class TargetIRAnalysis : public AnalysisInfoMixin<TargetIRAnalysis> {
2214public:
2216
2217 /// Default construct a target IR analysis.
2218 ///
2219 /// This will use the module's datalayout to construct a baseline
2220 /// conservative TTI result.
2222
2223 /// Construct an IR analysis pass around a target-provide callback.
2224 ///
2225 /// The callback will be called with a particular function for which the TTI
2226 /// is needed and must return a TTI object for that function.
2227 LLVM_ABI
2228 TargetIRAnalysis(std::function<Result(const Function &)> TTICallback);
2229
2230 // Value semantics. We spell out the constructors for MSVC.
2232 : TTICallback(Arg.TTICallback) {}
2234 : TTICallback(std::move(Arg.TTICallback)) {}
2236 TTICallback = RHS.TTICallback;
2237 return *this;
2238 }
2240 TTICallback = std::move(RHS.TTICallback);
2241 return *this;
2242 }
2243
2245
2246private:
2248 LLVM_ABI static AnalysisKey Key;
2249
2250 /// The callback used to produce a result.
2251 ///
2252 /// We use a completely opaque callback so that targets can provide whatever
2253 /// mechanism they desire for constructing the TTI for a given function.
2254 ///
2255 /// FIXME: Should we really use std::function? It's relatively inefficient.
2256 /// It might be possible to arrange for even stateful callbacks to outlive
2257 /// the analysis and thus use a function_ref which would be lighter weight.
2258 /// This may also be less error prone as the callback is likely to reference
2259 /// the external TargetMachine, and that reference needs to never dangle.
2260 std::function<Result(const Function &)> TTICallback;
2261
2262 /// Helper function used as the callback in the default constructor.
2263 static Result getDefaultTTI(const Function &F);
2264};
2265
2266/// Wrapper pass for TargetTransformInfo.
2267///
2268/// This pass can be constructed from a TTI object which it stores internally
2269/// and is queried by passes.
2271 TargetIRAnalysis TIRA;
2272 std::optional<TargetTransformInfo> TTI;
2273
2274 virtual void anchor();
2275
2276public:
2277 static char ID;
2278
2279 /// We must provide a default constructor for the pass but it should
2280 /// never be used.
2281 ///
2282 /// Use the constructor below or call one of the creation routines.
2284
2286
2288};
2289
2290/// Create an analysis pass wrapper around a TTI object.
2291///
2292/// This analysis pass just holds the TTI instance and makes it available to
2293/// clients.
2296
2297} // namespace llvm
2298
2299#endif
uint64_t uint64_t
uint64_t Imm
This file implements a class to represent arbitrary precision integral constant values and operations...
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Atomic ordering constants.
#define X(NUM, ENUM, NAME)
Definition ELF.h:665
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
#define LLVM_ABI
Definition Compiler.h:211
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:54
#define I(x, y, z)
Definition MD5.cpp:57
uint64_t IntrinsicInst * II
SmallVector< MachineOperand, 4 > Cond
int64_t C1
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")))
SI Fold Operands
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
Value * RHS
Class for arbitrary precision integers.
Definition APInt.h:78
an instruction to allocate memory on the stack
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
A cache of @llvm.assume calls within a function.
Functions, function parameters, and return types can have attributes to indicate how they should be t...
Definition Attributes.h:106
LLVM Basic Block Representation.
Definition BasicBlock.h:62
BlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate IR basic block frequen...
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:740
Conditional Branch instruction.
This is an important base class in LLVM.
Definition Constant.h:44
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
Convenience struct for specifying and reasoning about fast-math flags.
Definition FMF.h:23
This instruction compares its operands according to the predicate given to the constructor.
ImmutablePass class - This class is used to provide information that does not need to be run.
Definition Pass.h:283
ImmutablePass(char &pid)
Definition Pass.h:285
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 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)
VectorInstrContext getVectorInstrContext() const
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:76
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
Information for memory intrinsic cost model.
MemIntrinsicCostAttributes(Intrinsic::ID Id, Type *DataTy, const Value *Ptr, bool VariableMask, Align Alignment, const Instruction *I=nullptr, const Value *StrideVal=nullptr)
MemIntrinsicCostAttributes(Intrinsic::ID Id, Type *DataTy, bool VariableMask, Align Alignment, const Instruction *I=nullptr, const Value *StrideVal=nullptr)
MemIntrinsicCostAttributes(Intrinsic::ID Id, Type *DataTy, Align Alignment, unsigned AddressSpace=0, const Value *StrideVal=nullptr)
const Instruction * getInst() const
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 bool shouldBuildLookupTables() const
Return true if switches should be turned into lookup tables for the target.
LLVM_ABI VectorInstrContext getBuildVectorContextHint(ArrayRef< int > Mask, ArrayRef< Value * > Scalars, function_ref< bool(SmallVectorImpl< BuildVectorUseOp > &)> GatherUseOps) const
Calculates a VectorInstrContext for buildvector-like gather sequences.
LLVM_ABI bool isLegalToVectorizeStore(StoreInst *SI) const
LLVM_ABI bool areTypesABICompatible(const Function *Caller, const Function *Callee, ArrayRef< Type * > Types) const
LLVM_ABI bool enableAggressiveInterleaving(bool LoopHasReductions) const
Don't restrict interleaved unrolling to small loops.
LLVM_ABI bool isLegalSpeculativeLoad(Type *DataType, unsigned AddressSpace) const
Return true if the target supports speculatively loading DataType from address space AddressSpace,...
LLVM_ABI bool isMultiversionedFunction(const Function &F) const
Returns true if this is an instance of a function with multiple versions.
LLVM_ABI unsigned getMaxInterleaveFactor(ElementCount VF, bool HasUnorderedReductions) const
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 isLegalMaskedStore(Type *DataType, Align Alignment, unsigned AddressSpace, MaskKind MaskKind=VariableOrConstantMask) const
Return true if the target supports masked store.
LLVM_ABI unsigned getMinimumLookupTableEntryBitWidth() const
Return the minimum bit width to use for integer switch lookup table elements on this target.
LLVM_ABI bool supportsEfficientVectorElementLoadStore() const
If target has efficient vector element load/store instructions, it can return true here so that inser...
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 getCFInstrCost(unsigned Opcode, TTI::TargetCostKind CostKind, const Instruction *I=nullptr) const
LLVM_ABI bool hasBranchDivergence(const Function *F=nullptr) const
Return true if branch divergence exists.
LLVM_ABI bool preferEpilogueVectorization(ElementCount Iters) const
Return true if the loop vectorizer should consider vectorizing an otherwise scalar epilogue loop if t...
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 InstructionCost getGEPCost(Type *PointeeType, const Value *Ptr, ArrayRef< const Value * > Operands, TargetCostKind CostKind, Type *AccessType=nullptr) const
Estimate the cost of a GEP operation when lowered.
LLVM_ABI TailFoldingStyle getPreferredTailFoldingStyle() const
Query the target what the preferred style of tail folding is.
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
MaskKind
Some targets only support masked load/store with a constant mask.
LLVM_ABI unsigned getInlineCallPenalty(const Function *F, const CallBase &Call, unsigned DefaultCallPenalty) const
Returns a penalty for invoking call Call in F.
LLVM_ABI InstructionCost getOperandsScalarizationOverhead(ArrayRef< Type * > Tys, TTI::TargetCostKind CostKind, TTI::VectorInstrContext VIC=TTI::VectorInstrContext::None) const
Estimate the overhead of scalarizing operands with the given types.
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 InstructionCost getMemoryOpCost(unsigned Opcode, Type *Src, Align Alignment, unsigned AddressSpace, TTI::TargetCostKind CostKind, OperandValueInfo OpdInfo={OK_AnyValue, OP_None}, const Instruction *I=nullptr) const
LLVM_ABI bool isLegalMaskedGather(Type *DataType, Align Alignment) const
Return true if the target supports masked gather.
LLVM_ABI ValueUniformity getValueUniformity(const Value *V) const
Get target-specific uniformity information for a value.
static LLVM_ABI OperandValueInfo commonOperandInfo(const Value *X, const Value *Y)
Collect common data between two OperandValueInfo inputs.
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 bool preferTailFoldingOverEpilogue(TailFoldingInfo *TFI) const
Query the target whether it would be preferred to create a tail-folded vector loop,...
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 bool hasMultiVectorLoadStore(unsigned NumVectors, MaskSource Mask, VectorType *VectorTy=nullptr, bool IsStore=false, std::optional< Instruction::CastOps > CastHint=std::nullopt) const
Return true if the target supports loading or storing NumVectors contiguous vectors of type VectorTy ...
LLVM_ABI InstructionCost getIntrinsicInstrCost(const IntrinsicCostAttributes &ICA, TTI::TargetCostKind CostKind) const
LLVM_ABI unsigned getAtomicMemIntrinsicMaxElementSize() const
LLVM_ABI InstructionCost getVectorInstrCost(unsigned Opcode, Type *Val, TTI::TargetCostKind CostKind, unsigned Index=-1, const Value *Op0=nullptr, const Value *Op1=nullptr, TTI::VectorInstrContext VIC=TTI::VectorInstrContext::None) const
LLVM_ABI std::pair< KnownBits, KnownBits > computeKnownBitsAddrSpaceCast(unsigned ToAS, const Value &PtrOp) 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 InstructionCost getCmpSelInstrCost(unsigned Opcode, Type *ValTy, Type *CondTy, CmpInst::Predicate VecPred, TTI::TargetCostKind CostKind, OperandValueInfo Op1Info={OK_AnyValue, OP_None}, OperandValueInfo Op2Info={OK_AnyValue, OP_None}, const Instruction *I=nullptr) const
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 InstructionCost getShuffleCost(ShuffleKind Kind, VectorType *DstTy, VectorType *SrcTy, TTI::TargetCostKind CostKind, ArrayRef< int > Mask={}, int Index=0, VectorType *SubTp=nullptr, ArrayRef< const Value * > Args={}, const Instruction *CtxI=nullptr, TTI::VectorInstrContext VIC=TTI::VectorInstrContext::None) const
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
static LLVM_ABI TargetTransformInfo::VectorInstrContext combineVectorInstrContexts(TargetTransformInfo::VectorInstrContext Ctx1, TargetTransformInfo::VectorInstrContext Ctx2)
Combines 2 context hints into a single value.
LLVM_ABI unsigned getLoadStoreVecRegBitWidth(unsigned AddrSpace) const
LLVM_ABI InstructionCost getRegisterClassReloadCost(unsigned ClassID, TargetCostKind CostKind) 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 InstructionCost getInterleavedMemoryOpCost(unsigned Opcode, Type *VecTy, unsigned Factor, ArrayRef< unsigned > Indices, Align Alignment, unsigned AddressSpace, TTI::TargetCostKind CostKind, bool UseMaskForCond=false, bool UseMaskForGaps=false) const
LLVM_ABI InstructionCost getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src, TTI::CastContextHint CCH, TTI::TargetCostKind CostKind, const Instruction *I=nullptr) const
LLVM_ABI unsigned getAddressSpaceJoin(unsigned AS1, unsigned AS2) const
Return the most specific common address space containing AS1 and AS2.
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 InstructionCost getArithmeticReductionCost(unsigned Opcode, VectorType *Ty, std::optional< FastMathFlags > FMF, TTI::TargetCostKind CostKind) const
Calculate the cost of vector reduction 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 getExtendedReductionCost(unsigned Opcode, bool IsUnsigned, Type *ResTy, VectorType *Ty, std::optional< FastMathFlags > FMF, TTI::TargetCostKind CostKind) const
Calculate the cost of an extended reduction pattern, similar to getArithmeticReductionCost of a reduc...
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 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 bool isIndexedLoadLegal(enum MemIndexedMode Mode, Type *Ty) const
LLVM_ABI InstructionCost getCallInstrCost(Function *F, Type *RetTy, ArrayRef< Type * > Tys, TTI::TargetCostKind CostKind) const
LLVM_ABI unsigned getMaximumVF(unsigned ElemWidth, unsigned Opcode) const
LLVM_ABI unsigned getStoreMinimumVF(unsigned VF, Type *ScalarMemTy, Type *ScalarValTy, Align Alignment, unsigned AddrSpace) const
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 bool isUniform(const Instruction *I, const SmallBitVector &UniformArgs) const
Determine if an instruction with Custom uniformity can be proven uniform based on which operands are ...
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 getMemIntrinsicInstrCost(const MemIntrinsicCostAttributes &MICA, TTI::TargetCostKind CostKind) const
LLVM_ABI InstructionCost getMinMaxReductionCost(Intrinsic::ID IID, VectorType *Ty, FastMathFlags FMF, TTI::TargetCostKind CostKind) 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 bool canSaveCmp(Loop *L, CondBrInst **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 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 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
MaskSource
Enum describing the source/producer of a mask.
@ ArbitraryPredicate
The operation is masked with an arbitrary predicate.
@ ActiveLaneMask
The operation is masked with a contiguous active lane mask.
LLVM_ABI bool shouldConsiderAddressTypePromotion(const Instruction &I, bool &AllowPromotionWithoutCommonHeader) const
LLVM_ABI APInt getPriorityMask(const Function &F) const
Returns a bitmask constructed from the target-features or fmv-features metadata of a function corresp...
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 InstructionCost getMulAccReductionCost(bool IsUnsigned, unsigned RedOpcode, Type *ResTy, VectorType *Ty, TTI::TargetCostKind CostKind) const
Calculate the cost of an extended reduction pattern, similar to getArithmeticReductionCost of an Add/...
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 getAltInstrCost(VectorType *VecTy, unsigned Opcode0, unsigned Opcode1, const SmallBitVector &OpcodeMask, TTI::TargetCostKind CostKind, ArrayRef< const Value * > Scalars={}) const
Returns the cost estimation for alternating opcode pattern that can be lowered to a single instructio...
LLVM_ABI bool shouldCopyAttributeWhenOutliningFrom(const Function *Caller, const Attribute &Attr) const
LLVM_ABI APInt getAddrSpaceCastPreservedPtrMask(unsigned SrcAS, unsigned DstAS) const
Returns a mask indicating which bits of a pointer remain unchanged when casting between address space...
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::VectorInstrContext VectorInstrContext
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 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 preferSLPInstCountCheck() 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 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 InstructionCost getArithmeticInstrCost(unsigned Opcode, Type *Ty, TTI::TargetCostKind CostKind, TTI::OperandValueInfo Opd1Info={TTI::OK_AnyValue, TTI::OP_None}, TTI::OperandValueInfo Opd2Info={TTI::OK_AnyValue, TTI::OP_None}, ArrayRef< const Value * > Args={}, const Instruction *CtxI=nullptr, const TargetLibraryInfo *TLibInfo=nullptr) const
This is an approximation of reciprocal throughput of a math/logic op.
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.
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 getPartialReductionCost(unsigned Opcode, Type *InputTypeA, Type *InputTypeB, Type *AccumType, ElementCount VF, PartialReductionExtendKind OpAExtend, PartialReductionExtendKind OpBExtend, std::optional< unsigned > BinOp, TTI::TargetCostKind CostKind, std::optional< FastMathFlags > FMF) 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 bool enableScalableVectorization() const
LLVM_ABI bool useFastCCForInternalCall(Function &F) const
Return true if the input function is internal, should use fastcc calling convention.
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 unsigned getGISelRematGlobalCost() const
static LLVM_ABI Instruction::CastOps getOpcodeForPartialReductionExtendKind(PartialReductionExtendKind Kind)
Get the cast opcode for an extension kind.
MemIndexedMode
The type of load/store indexing.
LLVM_ABI bool isLegalMaskedLoad(Type *DataType, Align Alignment, unsigned AddressSpace, MaskKind MaskKind=VariableOrConstantMask) const
Return true if the target supports masked load.
LLVM_ABI InstructionCost getIndexedVectorInstrCostFromEnd(unsigned Opcode, Type *Val, TTI::TargetCostKind CostKind, unsigned Index) const
LLVM_ABI bool isProfitableToSinkOperands(Instruction *I, SmallVectorImpl< Use * > &Ops, const LoopInfo *LI=nullptr) const
Return true if sinking I's operands to the same basic block as I is profitable, e....
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
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 bool preferLoopExitWithEqualityComparison(const ICmpInst &Cond, const APInt &PostIncExitValue) const
Return true if replacing the relational loop exit comparison Cond with an equality comparison against...
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 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 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...
static LLVM_ABI VectorInstrContext getVectorInstrContextHint(const Instruction *I)
Calculates a VectorInstrContext from I.
LLVM_ABI InstructionCost getPointersChainCost(ArrayRef< const Value * > Ptrs, const Value *Base, const PointersChainInfo &Info, Type *AccessTy, const TargetCostKind CostKind) const
Estimate the cost of a chain of pointers (typically pointer operands of a chain of loads or stores wi...
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 InstructionCost getScalarizationOverhead(VectorType *Ty, const APInt &DemandedElts, bool Insert, bool Extract, TTI::TargetCostKind CostKind, bool ForPoisonSrc=true, ArrayRef< Value * > VL={}, TTI::VectorInstrContext VIC=TTI::VectorInstrContext::None) const
Estimate the overhead of scalarizing an instruction.
LLVM_ABI uint64_t getMaxMemIntrinsicInlineSizeThreshold() const
Returns the maximum memset / memcpy size in bytes that still makes it profitable to inline the call.
LLVM_ABI bool isLegalAltInstr(VectorType *VecTy, unsigned Opcode0, unsigned Opcode1, const SmallBitVector &OpcodeMask, ArrayRef< const Value * > Scalars={}) const
Return true if this is an alternating opcode pattern that can be lowered to a single instruction on t...
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 corresp...
LLVM_ABI void getPeelingPreferences(Loop *L, ScalarEvolution &SE, PeelingPreferences &PP) const
Get target-customized preferences for the generic loop peeling transformation.
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.
@ 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
LLVM_ABI InstructionCost getRegisterClassSpillCost(unsigned ClassID, TargetCostKind CostKind) const
OperandValueKind
Additional information about an operand's possible values.
CacheLevel
The possible cache levels.
LLVM_ABI bool preferFixedOverScalableIfEqualCost() const
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
This is the common base class for vector predication intrinsics.
LLVM Value Representation.
Definition Value.h:75
Base class of all SIMD vector types.
An efficient, type-erasing, non-owning reference to a callable.
CallInst * Call
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
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:577
@ Known
Known to have no common set bits.
VectorInstrContext
Represents a hint about the context in which a vector instruction or intrinsic is used.
@ None
The instruction is not folded.
@ BinaryOp
One of the operands is a binary op.
@ SplatOpFolded
All of the value's users support splatting the value.
@ Load
The value being inserted comes from a load (InsertElement only).
@ Store
The extracted value is stored (ExtractElement only).
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
AtomicOrdering
Atomic ordering for LLVM's memory model.
TargetTransformInfo TTI
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.
@ Fast
Assign the register banks as fast as possible (default).
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:1933
@ 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.
ValueUniformity
Enum describing how values behave with respect to uniformity and divergence, to answer the question: ...
Definition Uniformity.h:18
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:878
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.
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.
SmallVector< InterestingMemoryOperand, 1 > InterestingOperands
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
BuildVectorUseOp(unsigned Opcode, Intrinsic::ID IntrinsicID, int OperandIndex)
unsigned Insns
TODO: Some of these could be merged.
Returns options for expansion of memcmp. IsZeroCmp is.
OperandValueInfo mergeWith(const OperandValueInfo OpInfoY)
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.
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
Disable runtime unrolling by default for vectorized loops.
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)