LLVM API Documentation

TargetTransformInfo.h
Go to the documentation of this file.
00001 //===- llvm/Analysis/TargetTransformInfo.h ----------------------*- C++ -*-===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This pass exposes codegen information to IR-level passes. Every
00011 // transformation that uses codegen information is broken into three parts:
00012 // 1. The IR-level analysis pass.
00013 // 2. The IR-level transformation interface which provides the needed
00014 //    information.
00015 // 3. Codegen-level implementation which uses target-specific hooks.
00016 //
00017 // This file defines #2, which is the interface that IR-level transformations
00018 // use for querying the codegen.
00019 //
00020 //===----------------------------------------------------------------------===//
00021 
00022 #ifndef LLVM_ANALYSIS_TARGETTRANSFORMINFO_H
00023 #define LLVM_ANALYSIS_TARGETTRANSFORMINFO_H
00024 
00025 #include "llvm/IR/Intrinsics.h"
00026 #include "llvm/Pass.h"
00027 #include "llvm/Support/DataTypes.h"
00028 
00029 namespace llvm {
00030 
00031 class Function;
00032 class GlobalValue;
00033 class Loop;
00034 class Type;
00035 class User;
00036 class Value;
00037 
00038 /// TargetTransformInfo - This pass provides access to the codegen
00039 /// interfaces that are needed for IR-level transformations.
00040 class TargetTransformInfo {
00041 protected:
00042   /// \brief The TTI instance one level down the stack.
00043   ///
00044   /// This is used to implement the default behavior all of the methods which
00045   /// is to delegate up through the stack of TTIs until one can answer the
00046   /// query.
00047   TargetTransformInfo *PrevTTI;
00048 
00049   /// \brief The top of the stack of TTI analyses available.
00050   ///
00051   /// This is a convenience routine maintained as TTI analyses become available
00052   /// that complements the PrevTTI delegation chain. When one part of an
00053   /// analysis pass wants to query another part of the analysis pass it can use
00054   /// this to start back at the top of the stack.
00055   TargetTransformInfo *TopTTI;
00056 
00057   /// All pass subclasses must in their initializePass routine call
00058   /// pushTTIStack with themselves to update the pointers tracking the previous
00059   /// TTI instance in the analysis group's stack, and the top of the analysis
00060   /// group's stack.
00061   void pushTTIStack(Pass *P);
00062 
00063   /// All pass subclasses must call TargetTransformInfo::getAnalysisUsage.
00064   virtual void getAnalysisUsage(AnalysisUsage &AU) const;
00065 
00066 public:
00067   /// This class is intended to be subclassed by real implementations.
00068   virtual ~TargetTransformInfo() = 0;
00069 
00070   /// \name Generic Target Information
00071   /// @{
00072 
00073   /// \brief Underlying constants for 'cost' values in this interface.
00074   ///
00075   /// Many APIs in this interface return a cost. This enum defines the
00076   /// fundamental values that should be used to interpret (and produce) those
00077   /// costs. The costs are returned as an unsigned rather than a member of this
00078   /// enumeration because it is expected that the cost of one IR instruction
00079   /// may have a multiplicative factor to it or otherwise won't fit directly
00080   /// into the enum. Moreover, it is common to sum or average costs which works
00081   /// better as simple integral values. Thus this enum only provides constants.
00082   ///
00083   /// Note that these costs should usually reflect the intersection of code-size
00084   /// cost and execution cost. A free instruction is typically one that folds
00085   /// into another instruction. For example, reg-to-reg moves can often be
00086   /// skipped by renaming the registers in the CPU, but they still are encoded
00087   /// and thus wouldn't be considered 'free' here.
00088   enum TargetCostConstants {
00089     TCC_Free = 0,       ///< Expected to fold away in lowering.
00090     TCC_Basic = 1,      ///< The cost of a typical 'add' instruction.
00091     TCC_Expensive = 4   ///< The cost of a 'div' instruction on x86.
00092   };
00093 
00094   /// \brief Estimate the cost of a specific operation when lowered.
00095   ///
00096   /// Note that this is designed to work on an arbitrary synthetic opcode, and
00097   /// thus work for hypothetical queries before an instruction has even been
00098   /// formed. However, this does *not* work for GEPs, and must not be called
00099   /// for a GEP instruction. Instead, use the dedicated getGEPCost interface as
00100   /// analyzing a GEP's cost required more information.
00101   ///
00102   /// Typically only the result type is required, and the operand type can be
00103   /// omitted. However, if the opcode is one of the cast instructions, the
00104   /// operand type is required.
00105   ///
00106   /// The returned cost is defined in terms of \c TargetCostConstants, see its
00107   /// comments for a detailed explanation of the cost values.
00108   virtual unsigned getOperationCost(unsigned Opcode, Type *Ty,
00109                                     Type *OpTy = nullptr) const;
00110 
00111   /// \brief Estimate the cost of a GEP operation when lowered.
00112   ///
00113   /// The contract for this function is the same as \c getOperationCost except
00114   /// that it supports an interface that provides extra information specific to
00115   /// the GEP operation.
00116   virtual unsigned getGEPCost(const Value *Ptr,
00117                               ArrayRef<const Value *> Operands) const;
00118 
00119   /// \brief Estimate the cost of a function call when lowered.
00120   ///
00121   /// The contract for this is the same as \c getOperationCost except that it
00122   /// supports an interface that provides extra information specific to call
00123   /// instructions.
00124   ///
00125   /// This is the most basic query for estimating call cost: it only knows the
00126   /// function type and (potentially) the number of arguments at the call site.
00127   /// The latter is only interesting for varargs function types.
00128   virtual unsigned getCallCost(FunctionType *FTy, int NumArgs = -1) const;
00129 
00130   /// \brief Estimate the cost of calling a specific function when lowered.
00131   ///
00132   /// This overload adds the ability to reason about the particular function
00133   /// being called in the event it is a library call with special lowering.
00134   virtual unsigned getCallCost(const Function *F, int NumArgs = -1) const;
00135 
00136   /// \brief Estimate the cost of calling a specific function when lowered.
00137   ///
00138   /// This overload allows specifying a set of candidate argument values.
00139   virtual unsigned getCallCost(const Function *F,
00140                                ArrayRef<const Value *> Arguments) const;
00141 
00142   /// \brief Estimate the cost of an intrinsic when lowered.
00143   ///
00144   /// Mirrors the \c getCallCost method but uses an intrinsic identifier.
00145   virtual unsigned getIntrinsicCost(Intrinsic::ID IID, Type *RetTy,
00146                                     ArrayRef<Type *> ParamTys) const;
00147 
00148   /// \brief Estimate the cost of an intrinsic when lowered.
00149   ///
00150   /// Mirrors the \c getCallCost method but uses an intrinsic identifier.
00151   virtual unsigned getIntrinsicCost(Intrinsic::ID IID, Type *RetTy,
00152                                     ArrayRef<const Value *> Arguments) const;
00153 
00154   /// \brief Estimate the cost of a given IR user when lowered.
00155   ///
00156   /// This can estimate the cost of either a ConstantExpr or Instruction when
00157   /// lowered. It has two primary advantages over the \c getOperationCost and
00158   /// \c getGEPCost above, and one significant disadvantage: it can only be
00159   /// used when the IR construct has already been formed.
00160   ///
00161   /// The advantages are that it can inspect the SSA use graph to reason more
00162   /// accurately about the cost. For example, all-constant-GEPs can often be
00163   /// folded into a load or other instruction, but if they are used in some
00164   /// other context they may not be folded. This routine can distinguish such
00165   /// cases.
00166   ///
00167   /// The returned cost is defined in terms of \c TargetCostConstants, see its
00168   /// comments for a detailed explanation of the cost values.
00169   virtual unsigned getUserCost(const User *U) const;
00170 
00171   /// \brief hasBranchDivergence - Return true if branch divergence exists.
00172   /// Branch divergence has a significantly negative impact on GPU performance
00173   /// when threads in the same wavefront take different paths due to conditional
00174   /// branches.
00175   virtual bool hasBranchDivergence() const;
00176 
00177   /// \brief Test whether calls to a function lower to actual program function
00178   /// calls.
00179   ///
00180   /// The idea is to test whether the program is likely to require a 'call'
00181   /// instruction or equivalent in order to call the given function.
00182   ///
00183   /// FIXME: It's not clear that this is a good or useful query API. Client's
00184   /// should probably move to simpler cost metrics using the above.
00185   /// Alternatively, we could split the cost interface into distinct code-size
00186   /// and execution-speed costs. This would allow modelling the core of this
00187   /// query more accurately as a call is a single small instruction, but
00188   /// incurs significant execution cost.
00189   virtual bool isLoweredToCall(const Function *F) const;
00190 
00191   /// Parameters that control the generic loop unrolling transformation.
00192   struct UnrollingPreferences {
00193     /// The cost threshold for the unrolled loop, compared to
00194     /// CodeMetrics.NumInsts aggregated over all basic blocks in the loop body.
00195     /// The unrolling factor is set such that the unrolled loop body does not
00196     /// exceed this cost. Set this to UINT_MAX to disable the loop body cost
00197     /// restriction.
00198     unsigned Threshold;
00199     /// The cost threshold for the unrolled loop when optimizing for size (set
00200     /// to UINT_MAX to disable).
00201     unsigned OptSizeThreshold;
00202     /// The cost threshold for the unrolled loop, like Threshold, but used
00203     /// for partial/runtime unrolling (set to UINT_MAX to disable).
00204     unsigned PartialThreshold;
00205     /// The cost threshold for the unrolled loop when optimizing for size, like
00206     /// OptSizeThreshold, but used for partial/runtime unrolling (set to UINT_MAX
00207     /// to disable).
00208     unsigned PartialOptSizeThreshold;
00209     /// A forced unrolling factor (the number of concatenated bodies of the
00210     /// original loop in the unrolled loop body). When set to 0, the unrolling
00211     /// transformation will select an unrolling factor based on the current cost
00212     /// threshold and other factors.
00213     unsigned Count;
00214     // Set the maximum unrolling factor. The unrolling factor may be selected
00215     // using the appropriate cost threshold, but may not exceed this number
00216     // (set to UINT_MAX to disable). This does not apply in cases where the
00217     // loop is being fully unrolled.
00218     unsigned MaxCount;
00219     /// Allow partial unrolling (unrolling of loops to expand the size of the
00220     /// loop body, not only to eliminate small constant-trip-count loops).
00221     bool     Partial;
00222     /// Allow runtime unrolling (unrolling of loops to expand the size of the
00223     /// loop body even when the number of loop iterations is not known at compile
00224     /// time).
00225     bool     Runtime;
00226   };
00227 
00228   /// \brief Get target-customized preferences for the generic loop unrolling
00229   /// transformation. The caller will initialize UP with the current
00230   /// target-independent defaults.
00231   virtual void getUnrollingPreferences(const Function *F, Loop *L,
00232                                        UnrollingPreferences &UP) const;
00233 
00234   /// @}
00235 
00236   /// \name Scalar Target Information
00237   /// @{
00238 
00239   /// \brief Flags indicating the kind of support for population count.
00240   ///
00241   /// Compared to the SW implementation, HW support is supposed to
00242   /// significantly boost the performance when the population is dense, and it
00243   /// may or may not degrade performance if the population is sparse. A HW
00244   /// support is considered as "Fast" if it can outperform, or is on a par
00245   /// with, SW implementation when the population is sparse; otherwise, it is
00246   /// considered as "Slow".
00247   enum PopcntSupportKind {
00248     PSK_Software,
00249     PSK_SlowHardware,
00250     PSK_FastHardware
00251   };
00252 
00253   /// \brief Return true if the specified immediate is legal add immediate, that
00254   /// is the target has add instructions which can add a register with the
00255   /// immediate without having to materialize the immediate into a register.
00256   virtual bool isLegalAddImmediate(int64_t Imm) const;
00257 
00258   /// \brief Return true if the specified immediate is legal icmp immediate,
00259   /// that is the target has icmp instructions which can compare a register
00260   /// against the immediate without having to materialize the immediate into a
00261   /// register.
00262   virtual bool isLegalICmpImmediate(int64_t Imm) const;
00263 
00264   /// \brief Return true if the addressing mode represented by AM is legal for
00265   /// this target, for a load/store of the specified type.
00266   /// The type may be VoidTy, in which case only return true if the addressing
00267   /// mode is legal for a load/store of any legal type.
00268   /// TODO: Handle pre/postinc as well.
00269   virtual bool isLegalAddressingMode(Type *Ty, GlobalValue *BaseGV,
00270                                      int64_t BaseOffset, bool HasBaseReg,
00271                                      int64_t Scale) const;
00272 
00273   /// \brief Return the cost of the scaling factor used in the addressing
00274   /// mode represented by AM for this target, for a load/store
00275   /// of the specified type.
00276   /// If the AM is supported, the return value must be >= 0.
00277   /// If the AM is not supported, it returns a negative value.
00278   /// TODO: Handle pre/postinc as well.
00279   virtual int getScalingFactorCost(Type *Ty, GlobalValue *BaseGV,
00280                                    int64_t BaseOffset, bool HasBaseReg,
00281                                    int64_t Scale) const;
00282 
00283   /// \brief Return true if it's free to truncate a value of type Ty1 to type
00284   /// Ty2. e.g. On x86 it's free to truncate a i32 value in register EAX to i16
00285   /// by referencing its sub-register AX.
00286   virtual bool isTruncateFree(Type *Ty1, Type *Ty2) const;
00287 
00288   /// \brief Return true if this type is legal.
00289   virtual bool isTypeLegal(Type *Ty) const;
00290 
00291   /// \brief Returns the target's jmp_buf alignment in bytes.
00292   virtual unsigned getJumpBufAlignment() const;
00293 
00294   /// \brief Returns the target's jmp_buf size in bytes.
00295   virtual unsigned getJumpBufSize() const;
00296 
00297   /// \brief Return true if switches should be turned into lookup tables for the
00298   /// target.
00299   virtual bool shouldBuildLookupTables() const;
00300 
00301   /// \brief Return hardware support for population count.
00302   virtual PopcntSupportKind getPopcntSupport(unsigned IntTyWidthInBit) const;
00303 
00304   /// \brief Return true if the hardware has a fast square-root instruction.
00305   virtual bool haveFastSqrt(Type *Ty) const;
00306 
00307   /// \brief Return the expected cost of materializing for the given integer
00308   /// immediate of the specified type.
00309   virtual unsigned getIntImmCost(const APInt &Imm, Type *Ty) const;
00310 
00311   /// \brief Return the expected cost of materialization for the given integer
00312   /// immediate of the specified type for a given instruction. The cost can be
00313   /// zero if the immediate can be folded into the specified instruction.
00314   virtual unsigned getIntImmCost(unsigned Opc, unsigned Idx, const APInt &Imm,
00315                                  Type *Ty) const;
00316   virtual unsigned getIntImmCost(Intrinsic::ID IID, unsigned Idx,
00317                                  const APInt &Imm, Type *Ty) const;
00318   /// @}
00319 
00320   /// \name Vector Target Information
00321   /// @{
00322 
00323   /// \brief The various kinds of shuffle patterns for vector queries.
00324   enum ShuffleKind {
00325     SK_Broadcast,       ///< Broadcast element 0 to all other elements.
00326     SK_Reverse,         ///< Reverse the order of the vector.
00327     SK_Alternate,       ///< Choose alternate elements from vector.
00328     SK_InsertSubvector, ///< InsertSubvector. Index indicates start offset.
00329     SK_ExtractSubvector ///< ExtractSubvector Index indicates start offset.
00330   };
00331 
00332   /// \brief Additional information about an operand's possible values.
00333   enum OperandValueKind {
00334     OK_AnyValue,                 // Operand can have any value.
00335     OK_UniformValue,             // Operand is uniform (splat of a value).
00336     OK_UniformConstantValue,     // Operand is uniform constant.
00337     OK_NonUniformConstantValue   // Operand is a non uniform constant value.
00338   };
00339 
00340   /// \brief Additional properties of an operand's values.
00341   enum OperandValueProperties { OP_None = 0, OP_PowerOf2 = 1 };
00342 
00343   /// \return The number of scalar or vector registers that the target has.
00344   /// If 'Vectors' is true, it returns the number of vector registers. If it is
00345   /// set to false, it returns the number of scalar registers.
00346   virtual unsigned getNumberOfRegisters(bool Vector) const;
00347 
00348   /// \return The width of the largest scalar or vector register type.
00349   virtual unsigned getRegisterBitWidth(bool Vector) const;
00350 
00351   /// \return The maximum interleave factor that any transform should try to
00352   /// perform for this target. This number depends on the level of parallelism
00353   /// and the number of execution units in the CPU.
00354   virtual unsigned getMaxInterleaveFactor() const;
00355 
00356   /// \return The expected cost of arithmetic ops, such as mul, xor, fsub, etc.
00357   virtual unsigned
00358   getArithmeticInstrCost(unsigned Opcode, Type *Ty,
00359                          OperandValueKind Opd1Info = OK_AnyValue,
00360                          OperandValueKind Opd2Info = OK_AnyValue,
00361                          OperandValueProperties Opd1PropInfo = OP_None,
00362                          OperandValueProperties Opd2PropInfo = OP_None) const;
00363 
00364   /// \return The cost of a shuffle instruction of kind Kind and of type Tp.
00365   /// The index and subtype parameters are used by the subvector insertion and
00366   /// extraction shuffle kinds.
00367   virtual unsigned getShuffleCost(ShuffleKind Kind, Type *Tp, int Index = 0,
00368                                   Type *SubTp = nullptr) const;
00369 
00370   /// \return The expected cost of cast instructions, such as bitcast, trunc,
00371   /// zext, etc.
00372   virtual unsigned getCastInstrCost(unsigned Opcode, Type *Dst,
00373                                     Type *Src) const;
00374 
00375   /// \return The expected cost of control-flow related instructions such as
00376   /// Phi, Ret, Br.
00377   virtual unsigned getCFInstrCost(unsigned Opcode) const;
00378 
00379   /// \returns The expected cost of compare and select instructions.
00380   virtual unsigned getCmpSelInstrCost(unsigned Opcode, Type *ValTy,
00381                                       Type *CondTy = nullptr) const;
00382 
00383   /// \return The expected cost of vector Insert and Extract.
00384   /// Use -1 to indicate that there is no information on the index value.
00385   virtual unsigned getVectorInstrCost(unsigned Opcode, Type *Val,
00386                                       unsigned Index = -1) const;
00387 
00388   /// \return The cost of Load and Store instructions.
00389   virtual unsigned getMemoryOpCost(unsigned Opcode, Type *Src,
00390                                    unsigned Alignment,
00391                                    unsigned AddressSpace) const;
00392 
00393   /// \brief Calculate the cost of performing a vector reduction.
00394   ///
00395   /// This is the cost of reducing the vector value of type \p Ty to a scalar
00396   /// value using the operation denoted by \p Opcode. The form of the reduction
00397   /// can either be a pairwise reduction or a reduction that splits the vector
00398   /// at every reduction level.
00399   ///
00400   /// Pairwise:
00401   ///  (v0, v1, v2, v3)
00402   ///  ((v0+v1), (v2, v3), undef, undef)
00403   /// Split:
00404   ///  (v0, v1, v2, v3)
00405   ///  ((v0+v2), (v1+v3), undef, undef)
00406   virtual unsigned getReductionCost(unsigned Opcode, Type *Ty,
00407                                     bool IsPairwiseForm) const;
00408 
00409   /// \returns The cost of Intrinsic instructions.
00410   virtual unsigned getIntrinsicInstrCost(Intrinsic::ID ID, Type *RetTy,
00411                                          ArrayRef<Type *> Tys) const;
00412 
00413   /// \returns The number of pieces into which the provided type must be
00414   /// split during legalization. Zero is returned when the answer is unknown.
00415   virtual unsigned getNumberOfParts(Type *Tp) const;
00416 
00417   /// \returns The cost of the address computation. For most targets this can be
00418   /// merged into the instruction indexing mode. Some targets might want to
00419   /// distinguish between address computation for memory operations on vector
00420   /// types and scalar types. Such targets should override this function.
00421   /// The 'IsComplex' parameter is a hint that the address computation is likely
00422   /// to involve multiple instructions and as such unlikely to be merged into
00423   /// the address indexing mode.
00424   virtual unsigned getAddressComputationCost(Type *Ty,
00425                                              bool IsComplex = false) const;
00426 
00427   /// \returns The cost, if any, of keeping values of the given types alive
00428   /// over a callsite.
00429   ///
00430   /// Some types may require the use of register classes that do not have
00431   /// any callee-saved registers, so would require a spill and fill.
00432   virtual unsigned getCostOfKeepingLiveOverCall(ArrayRef<Type*> Tys) const;
00433 
00434   /// @}
00435 
00436   /// Analysis group identification.
00437   static char ID;
00438 };
00439 
00440 /// \brief Create the base case instance of a pass in the TTI analysis group.
00441 ///
00442 /// This class provides the base case for the stack of TTI analyzes. It doesn't
00443 /// delegate to anything and uses the STTI and VTTI objects passed in to
00444 /// satisfy the queries.
00445 ImmutablePass *createNoTargetTransformInfoPass();
00446 
00447 } // End llvm namespace
00448 
00449 #endif