[PM] Port TTI to the new pass manager, introducing a TargetIRAnalysis to
[oota-llvm.git] / include / llvm / Analysis / TargetTransformInfo.h
1 //===- TargetTransformInfo.h ------------------------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 /// \file
10 /// This pass exposes codegen information to IR-level passes. Every
11 /// transformation that uses codegen information is broken into three parts:
12 /// 1. The IR-level analysis pass.
13 /// 2. The IR-level transformation interface which provides the needed
14 ///    information.
15 /// 3. Codegen-level implementation which uses target-specific hooks.
16 ///
17 /// This file defines #2, which is the interface that IR-level transformations
18 /// use for querying the codegen.
19 ///
20 //===----------------------------------------------------------------------===//
21
22 #ifndef LLVM_ANALYSIS_TARGETTRANSFORMINFO_H
23 #define LLVM_ANALYSIS_TARGETTRANSFORMINFO_H
24
25 #include "llvm/IR/Intrinsics.h"
26 #include "llvm/IR/IntrinsicInst.h"
27 #include "llvm/Pass.h"
28 #include "llvm/Support/DataTypes.h"
29
30 namespace llvm {
31
32 class Function;
33 class GlobalValue;
34 class Loop;
35 class PreservedAnalyses;
36 class Type;
37 class User;
38 class Value;
39
40 /// \brief Information about a load/store intrinsic defined by the target.
41 struct MemIntrinsicInfo {
42   MemIntrinsicInfo()
43       : ReadMem(false), WriteMem(false), Vol(false), MatchingId(0),
44         NumMemRefs(0), PtrVal(nullptr) {}
45   bool ReadMem;
46   bool WriteMem;
47   bool Vol;
48   // Same Id is set by the target for corresponding load/store intrinsics.
49   unsigned short MatchingId;
50   int NumMemRefs;
51   Value *PtrVal;
52 };
53
54 /// \brief This pass provides access to the codegen interfaces that are needed
55 /// for IR-level transformations.
56 class TargetTransformInfo {
57 public:
58   /// \brief Construct a TTI object using a type implementing the \c Concept
59   /// API below.
60   ///
61   /// This is used by targets to construct a TTI wrapping their target-specific
62   /// implementaion that encodes appropriate costs for their target.
63   template <typename T> TargetTransformInfo(T Impl);
64
65   /// \brief Construct a baseline TTI object using a minimal implementation of
66   /// the \c Concept API below.
67   ///
68   /// The TTI implementation will reflect the information in the DataLayout
69   /// provided if non-null.
70   explicit TargetTransformInfo(const DataLayout *DL);
71
72   // Provide move semantics.
73   TargetTransformInfo(TargetTransformInfo &&Arg);
74   TargetTransformInfo &operator=(TargetTransformInfo &&RHS);
75
76   // We need to define the destructor out-of-line to define our sub-classes
77   // out-of-line.
78   ~TargetTransformInfo();
79
80   /// \brief Handle the invalidation of this information.
81   ///
82   /// When used as a result of \c TargetIRAnalysis this method will be called
83   /// when the function this was computed for changes. When it returns false,
84   /// the information is preserved across those changes.
85   bool invalidate(Function &, const PreservedAnalyses &) {
86     // FIXME: We should probably in some way ensure that the subtarget
87     // information for a function hasn't changed.
88     return false;
89   }
90
91   /// \name Generic Target Information
92   /// @{
93
94   /// \brief Underlying constants for 'cost' values in this interface.
95   ///
96   /// Many APIs in this interface return a cost. This enum defines the
97   /// fundamental values that should be used to interpret (and produce) those
98   /// costs. The costs are returned as an unsigned rather than a member of this
99   /// enumeration because it is expected that the cost of one IR instruction
100   /// may have a multiplicative factor to it or otherwise won't fit directly
101   /// into the enum. Moreover, it is common to sum or average costs which works
102   /// better as simple integral values. Thus this enum only provides constants.
103   ///
104   /// Note that these costs should usually reflect the intersection of code-size
105   /// cost and execution cost. A free instruction is typically one that folds
106   /// into another instruction. For example, reg-to-reg moves can often be
107   /// skipped by renaming the registers in the CPU, but they still are encoded
108   /// and thus wouldn't be considered 'free' here.
109   enum TargetCostConstants {
110     TCC_Free = 0,     ///< Expected to fold away in lowering.
111     TCC_Basic = 1,    ///< The cost of a typical 'add' instruction.
112     TCC_Expensive = 4 ///< The cost of a 'div' instruction on x86.
113   };
114
115   /// \brief Estimate the cost of a specific operation when lowered.
116   ///
117   /// Note that this is designed to work on an arbitrary synthetic opcode, and
118   /// thus work for hypothetical queries before an instruction has even been
119   /// formed. However, this does *not* work for GEPs, and must not be called
120   /// for a GEP instruction. Instead, use the dedicated getGEPCost interface as
121   /// analyzing a GEP's cost required more information.
122   ///
123   /// Typically only the result type is required, and the operand type can be
124   /// omitted. However, if the opcode is one of the cast instructions, the
125   /// operand type is required.
126   ///
127   /// The returned cost is defined in terms of \c TargetCostConstants, see its
128   /// comments for a detailed explanation of the cost values.
129   unsigned getOperationCost(unsigned Opcode, Type *Ty,
130                             Type *OpTy = nullptr) const;
131
132   /// \brief Estimate the cost of a GEP operation when lowered.
133   ///
134   /// The contract for this function is the same as \c getOperationCost except
135   /// that it supports an interface that provides extra information specific to
136   /// the GEP operation.
137   unsigned getGEPCost(const Value *Ptr, ArrayRef<const Value *> Operands) const;
138
139   /// \brief Estimate the cost of a function call when lowered.
140   ///
141   /// The contract for this is the same as \c getOperationCost except that it
142   /// supports an interface that provides extra information specific to call
143   /// instructions.
144   ///
145   /// This is the most basic query for estimating call cost: it only knows the
146   /// function type and (potentially) the number of arguments at the call site.
147   /// The latter is only interesting for varargs function types.
148   unsigned getCallCost(FunctionType *FTy, int NumArgs = -1) const;
149
150   /// \brief Estimate the cost of calling a specific function when lowered.
151   ///
152   /// This overload adds the ability to reason about the particular function
153   /// being called in the event it is a library call with special lowering.
154   unsigned getCallCost(const Function *F, int NumArgs = -1) const;
155
156   /// \brief Estimate the cost of calling a specific function when lowered.
157   ///
158   /// This overload allows specifying a set of candidate argument values.
159   unsigned getCallCost(const Function *F,
160                        ArrayRef<const Value *> Arguments) const;
161
162   /// \brief Estimate the cost of an intrinsic when lowered.
163   ///
164   /// Mirrors the \c getCallCost method but uses an intrinsic identifier.
165   unsigned getIntrinsicCost(Intrinsic::ID IID, Type *RetTy,
166                             ArrayRef<Type *> ParamTys) const;
167
168   /// \brief Estimate the cost of an intrinsic when lowered.
169   ///
170   /// Mirrors the \c getCallCost method but uses an intrinsic identifier.
171   unsigned getIntrinsicCost(Intrinsic::ID IID, Type *RetTy,
172                             ArrayRef<const Value *> Arguments) const;
173
174   /// \brief Estimate the cost of a given IR user when lowered.
175   ///
176   /// This can estimate the cost of either a ConstantExpr or Instruction when
177   /// lowered. It has two primary advantages over the \c getOperationCost and
178   /// \c getGEPCost above, and one significant disadvantage: it can only be
179   /// used when the IR construct has already been formed.
180   ///
181   /// The advantages are that it can inspect the SSA use graph to reason more
182   /// accurately about the cost. For example, all-constant-GEPs can often be
183   /// folded into a load or other instruction, but if they are used in some
184   /// other context they may not be folded. This routine can distinguish such
185   /// cases.
186   ///
187   /// The returned cost is defined in terms of \c TargetCostConstants, see its
188   /// comments for a detailed explanation of the cost values.
189   unsigned getUserCost(const User *U) const;
190
191   /// \brief hasBranchDivergence - Return true if branch divergence exists.
192   /// Branch divergence has a significantly negative impact on GPU performance
193   /// when threads in the same wavefront take different paths due to conditional
194   /// branches.
195   bool hasBranchDivergence() const;
196
197   /// \brief Test whether calls to a function lower to actual program function
198   /// calls.
199   ///
200   /// The idea is to test whether the program is likely to require a 'call'
201   /// instruction or equivalent in order to call the given function.
202   ///
203   /// FIXME: It's not clear that this is a good or useful query API. Client's
204   /// should probably move to simpler cost metrics using the above.
205   /// Alternatively, we could split the cost interface into distinct code-size
206   /// and execution-speed costs. This would allow modelling the core of this
207   /// query more accurately as a call is a single small instruction, but
208   /// incurs significant execution cost.
209   bool isLoweredToCall(const Function *F) const;
210
211   /// Parameters that control the generic loop unrolling transformation.
212   struct UnrollingPreferences {
213     /// The cost threshold for the unrolled loop, compared to
214     /// CodeMetrics.NumInsts aggregated over all basic blocks in the loop body.
215     /// The unrolling factor is set such that the unrolled loop body does not
216     /// exceed this cost. Set this to UINT_MAX to disable the loop body cost
217     /// restriction.
218     unsigned Threshold;
219     /// The cost threshold for the unrolled loop when optimizing for size (set
220     /// to UINT_MAX to disable).
221     unsigned OptSizeThreshold;
222     /// The cost threshold for the unrolled loop, like Threshold, but used
223     /// for partial/runtime unrolling (set to UINT_MAX to disable).
224     unsigned PartialThreshold;
225     /// The cost threshold for the unrolled loop when optimizing for size, like
226     /// OptSizeThreshold, but used for partial/runtime unrolling (set to
227     /// UINT_MAX to disable).
228     unsigned PartialOptSizeThreshold;
229     /// A forced unrolling factor (the number of concatenated bodies of the
230     /// original loop in the unrolled loop body). When set to 0, the unrolling
231     /// transformation will select an unrolling factor based on the current cost
232     /// threshold and other factors.
233     unsigned Count;
234     // Set the maximum unrolling factor. The unrolling factor may be selected
235     // using the appropriate cost threshold, but may not exceed this number
236     // (set to UINT_MAX to disable). This does not apply in cases where the
237     // loop is being fully unrolled.
238     unsigned MaxCount;
239     /// Allow partial unrolling (unrolling of loops to expand the size of the
240     /// loop body, not only to eliminate small constant-trip-count loops).
241     bool Partial;
242     /// Allow runtime unrolling (unrolling of loops to expand the size of the
243     /// loop body even when the number of loop iterations is not known at
244     /// compile time).
245     bool Runtime;
246   };
247
248   /// \brief Get target-customized preferences for the generic loop unrolling
249   /// transformation. The caller will initialize UP with the current
250   /// target-independent defaults.
251   void getUnrollingPreferences(const Function *F, Loop *L,
252                                UnrollingPreferences &UP) const;
253
254   /// @}
255
256   /// \name Scalar Target Information
257   /// @{
258
259   /// \brief Flags indicating the kind of support for population count.
260   ///
261   /// Compared to the SW implementation, HW support is supposed to
262   /// significantly boost the performance when the population is dense, and it
263   /// may or may not degrade performance if the population is sparse. A HW
264   /// support is considered as "Fast" if it can outperform, or is on a par
265   /// with, SW implementation when the population is sparse; otherwise, it is
266   /// considered as "Slow".
267   enum PopcntSupportKind { PSK_Software, PSK_SlowHardware, PSK_FastHardware };
268
269   /// \brief Return true if the specified immediate is legal add immediate, that
270   /// is the target has add instructions which can add a register with the
271   /// immediate without having to materialize the immediate into a register.
272   bool isLegalAddImmediate(int64_t Imm) const;
273
274   /// \brief Return true if the specified immediate is legal icmp immediate,
275   /// that is the target has icmp instructions which can compare a register
276   /// against the immediate without having to materialize the immediate into a
277   /// register.
278   bool isLegalICmpImmediate(int64_t Imm) const;
279
280   /// \brief Return true if the addressing mode represented by AM is legal for
281   /// this target, for a load/store of the specified type.
282   /// The type may be VoidTy, in which case only return true if the addressing
283   /// mode is legal for a load/store of any legal type.
284   /// TODO: Handle pre/postinc as well.
285   bool isLegalAddressingMode(Type *Ty, GlobalValue *BaseGV, int64_t BaseOffset,
286                              bool HasBaseReg, int64_t Scale) const;
287
288   /// \brief Return true if the target works with masked instruction
289   /// AVX2 allows masks for consecutive load and store for i32 and i64 elements.
290   /// AVX-512 architecture will also allow masks for non-consecutive memory
291   /// accesses.
292   bool isLegalMaskedStore(Type *DataType, int Consecutive) const;
293   bool isLegalMaskedLoad(Type *DataType, int Consecutive) const;
294
295   /// \brief Return the cost of the scaling factor used in the addressing
296   /// mode represented by AM for this target, for a load/store
297   /// of the specified type.
298   /// If the AM is supported, the return value must be >= 0.
299   /// If the AM is not supported, it returns a negative value.
300   /// TODO: Handle pre/postinc as well.
301   int getScalingFactorCost(Type *Ty, GlobalValue *BaseGV, int64_t BaseOffset,
302                            bool HasBaseReg, int64_t Scale) const;
303
304   /// \brief Return true if it's free to truncate a value of type Ty1 to type
305   /// Ty2. e.g. On x86 it's free to truncate a i32 value in register EAX to i16
306   /// by referencing its sub-register AX.
307   bool isTruncateFree(Type *Ty1, Type *Ty2) const;
308
309   /// \brief Return true if this type is legal.
310   bool isTypeLegal(Type *Ty) const;
311
312   /// \brief Returns the target's jmp_buf alignment in bytes.
313   unsigned getJumpBufAlignment() const;
314
315   /// \brief Returns the target's jmp_buf size in bytes.
316   unsigned getJumpBufSize() const;
317
318   /// \brief Return true if switches should be turned into lookup tables for the
319   /// target.
320   bool shouldBuildLookupTables() const;
321
322   /// \brief Return hardware support for population count.
323   PopcntSupportKind getPopcntSupport(unsigned IntTyWidthInBit) const;
324
325   /// \brief Return true if the hardware has a fast square-root instruction.
326   bool haveFastSqrt(Type *Ty) const;
327
328   /// \brief Return the expected cost of materializing for the given integer
329   /// immediate of the specified type.
330   unsigned getIntImmCost(const APInt &Imm, Type *Ty) const;
331
332   /// \brief Return the expected cost of materialization for the given integer
333   /// immediate of the specified type for a given instruction. The cost can be
334   /// zero if the immediate can be folded into the specified instruction.
335   unsigned getIntImmCost(unsigned Opc, unsigned Idx, const APInt &Imm,
336                          Type *Ty) const;
337   unsigned getIntImmCost(Intrinsic::ID IID, unsigned Idx, const APInt &Imm,
338                          Type *Ty) const;
339   /// @}
340
341   /// \name Vector Target Information
342   /// @{
343
344   /// \brief The various kinds of shuffle patterns for vector queries.
345   enum ShuffleKind {
346     SK_Broadcast,       ///< Broadcast element 0 to all other elements.
347     SK_Reverse,         ///< Reverse the order of the vector.
348     SK_Alternate,       ///< Choose alternate elements from vector.
349     SK_InsertSubvector, ///< InsertSubvector. Index indicates start offset.
350     SK_ExtractSubvector ///< ExtractSubvector Index indicates start offset.
351   };
352
353   /// \brief Additional information about an operand's possible values.
354   enum OperandValueKind {
355     OK_AnyValue,               // Operand can have any value.
356     OK_UniformValue,           // Operand is uniform (splat of a value).
357     OK_UniformConstantValue,   // Operand is uniform constant.
358     OK_NonUniformConstantValue // Operand is a non uniform constant value.
359   };
360
361   /// \brief Additional properties of an operand's values.
362   enum OperandValueProperties { OP_None = 0, OP_PowerOf2 = 1 };
363
364   /// \return The number of scalar or vector registers that the target has.
365   /// If 'Vectors' is true, it returns the number of vector registers. If it is
366   /// set to false, it returns the number of scalar registers.
367   unsigned getNumberOfRegisters(bool Vector) const;
368
369   /// \return The width of the largest scalar or vector register type.
370   unsigned getRegisterBitWidth(bool Vector) const;
371
372   /// \return The maximum interleave factor that any transform should try to
373   /// perform for this target. This number depends on the level of parallelism
374   /// and the number of execution units in the CPU.
375   unsigned getMaxInterleaveFactor() const;
376
377   /// \return The expected cost of arithmetic ops, such as mul, xor, fsub, etc.
378   unsigned
379   getArithmeticInstrCost(unsigned Opcode, Type *Ty,
380                          OperandValueKind Opd1Info = OK_AnyValue,
381                          OperandValueKind Opd2Info = OK_AnyValue,
382                          OperandValueProperties Opd1PropInfo = OP_None,
383                          OperandValueProperties Opd2PropInfo = OP_None) const;
384
385   /// \return The cost of a shuffle instruction of kind Kind and of type Tp.
386   /// The index and subtype parameters are used by the subvector insertion and
387   /// extraction shuffle kinds.
388   unsigned getShuffleCost(ShuffleKind Kind, Type *Tp, int Index = 0,
389                           Type *SubTp = nullptr) const;
390
391   /// \return The expected cost of cast instructions, such as bitcast, trunc,
392   /// zext, etc.
393   unsigned getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src) const;
394
395   /// \return The expected cost of control-flow related instructions such as
396   /// Phi, Ret, Br.
397   unsigned getCFInstrCost(unsigned Opcode) const;
398
399   /// \returns The expected cost of compare and select instructions.
400   unsigned getCmpSelInstrCost(unsigned Opcode, Type *ValTy,
401                               Type *CondTy = nullptr) const;
402
403   /// \return The expected cost of vector Insert and Extract.
404   /// Use -1 to indicate that there is no information on the index value.
405   unsigned getVectorInstrCost(unsigned Opcode, Type *Val,
406                               unsigned Index = -1) const;
407
408   /// \return The cost of Load and Store instructions.
409   unsigned getMemoryOpCost(unsigned Opcode, Type *Src, unsigned Alignment,
410                            unsigned AddressSpace) const;
411
412   /// \return The cost of masked Load and Store instructions.
413   unsigned getMaskedMemoryOpCost(unsigned Opcode, Type *Src, unsigned Alignment,
414                                  unsigned AddressSpace) const;
415
416   /// \brief Calculate the cost of performing a vector reduction.
417   ///
418   /// This is the cost of reducing the vector value of type \p Ty to a scalar
419   /// value using the operation denoted by \p Opcode. The form of the reduction
420   /// can either be a pairwise reduction or a reduction that splits the vector
421   /// at every reduction level.
422   ///
423   /// Pairwise:
424   ///  (v0, v1, v2, v3)
425   ///  ((v0+v1), (v2, v3), undef, undef)
426   /// Split:
427   ///  (v0, v1, v2, v3)
428   ///  ((v0+v2), (v1+v3), undef, undef)
429   unsigned getReductionCost(unsigned Opcode, Type *Ty,
430                             bool IsPairwiseForm) const;
431
432   /// \returns The cost of Intrinsic instructions.
433   unsigned getIntrinsicInstrCost(Intrinsic::ID ID, Type *RetTy,
434                                  ArrayRef<Type *> Tys) const;
435
436   /// \returns The number of pieces into which the provided type must be
437   /// split during legalization. Zero is returned when the answer is unknown.
438   unsigned getNumberOfParts(Type *Tp) const;
439
440   /// \returns The cost of the address computation. For most targets this can be
441   /// merged into the instruction indexing mode. Some targets might want to
442   /// distinguish between address computation for memory operations on vector
443   /// types and scalar types. Such targets should override this function.
444   /// The 'IsComplex' parameter is a hint that the address computation is likely
445   /// to involve multiple instructions and as such unlikely to be merged into
446   /// the address indexing mode.
447   unsigned getAddressComputationCost(Type *Ty, bool IsComplex = false) const;
448
449   /// \returns The cost, if any, of keeping values of the given types alive
450   /// over a callsite.
451   ///
452   /// Some types may require the use of register classes that do not have
453   /// any callee-saved registers, so would require a spill and fill.
454   unsigned getCostOfKeepingLiveOverCall(ArrayRef<Type *> Tys) const;
455
456   /// \returns True if the intrinsic is a supported memory intrinsic.  Info
457   /// will contain additional information - whether the intrinsic may write
458   /// or read to memory, volatility and the pointer.  Info is undefined
459   /// if false is returned.
460   bool getTgtMemIntrinsic(IntrinsicInst *Inst, MemIntrinsicInfo &Info) const;
461
462   /// \returns A value which is the result of the given memory intrinsic.  New
463   /// instructions may be created to extract the result from the given intrinsic
464   /// memory operation.  Returns nullptr if the target cannot create a result
465   /// from the given intrinsic.
466   Value *getOrCreateResultFromMemIntrinsic(IntrinsicInst *Inst,
467                                            Type *ExpectedType) const;
468
469   /// @}
470
471 private:
472   /// \brief The abstract base class used to type erase specific TTI
473   /// implementations.
474   class Concept;
475
476   /// \brief The template model for the base class which wraps a concrete
477   /// implementation in a type erased interface.
478   template <typename T> class Model;
479
480   std::unique_ptr<Concept> TTIImpl;
481 };
482
483 class TargetTransformInfo::Concept {
484 public:
485   virtual ~Concept() = 0;
486
487   virtual unsigned getOperationCost(unsigned Opcode, Type *Ty, Type *OpTy) = 0;
488   virtual unsigned getGEPCost(const Value *Ptr,
489                               ArrayRef<const Value *> Operands) = 0;
490   virtual unsigned getCallCost(FunctionType *FTy, int NumArgs) = 0;
491   virtual unsigned getCallCost(const Function *F, int NumArgs) = 0;
492   virtual unsigned getCallCost(const Function *F,
493                                ArrayRef<const Value *> Arguments) = 0;
494   virtual unsigned getIntrinsicCost(Intrinsic::ID IID, Type *RetTy,
495                                     ArrayRef<Type *> ParamTys) = 0;
496   virtual unsigned getIntrinsicCost(Intrinsic::ID IID, Type *RetTy,
497                                     ArrayRef<const Value *> Arguments) = 0;
498   virtual unsigned getUserCost(const User *U) = 0;
499   virtual bool hasBranchDivergence() = 0;
500   virtual bool isLoweredToCall(const Function *F) = 0;
501   virtual void getUnrollingPreferences(const Function *F, Loop *L,
502                                        UnrollingPreferences &UP) = 0;
503   virtual bool isLegalAddImmediate(int64_t Imm) = 0;
504   virtual bool isLegalICmpImmediate(int64_t Imm) = 0;
505   virtual bool isLegalAddressingMode(Type *Ty, GlobalValue *BaseGV,
506                                      int64_t BaseOffset, bool HasBaseReg,
507                                      int64_t Scale) = 0;
508   virtual bool isLegalMaskedStore(Type *DataType, int Consecutive) = 0;
509   virtual bool isLegalMaskedLoad(Type *DataType, int Consecutive) = 0;
510   virtual int getScalingFactorCost(Type *Ty, GlobalValue *BaseGV,
511                                    int64_t BaseOffset, bool HasBaseReg,
512                                    int64_t Scale) = 0;
513   virtual bool isTruncateFree(Type *Ty1, Type *Ty2) = 0;
514   virtual bool isTypeLegal(Type *Ty) = 0;
515   virtual unsigned getJumpBufAlignment() = 0;
516   virtual unsigned getJumpBufSize() = 0;
517   virtual bool shouldBuildLookupTables() = 0;
518   virtual PopcntSupportKind getPopcntSupport(unsigned IntTyWidthInBit) = 0;
519   virtual bool haveFastSqrt(Type *Ty) = 0;
520   virtual unsigned getIntImmCost(const APInt &Imm, Type *Ty) = 0;
521   virtual unsigned getIntImmCost(unsigned Opc, unsigned Idx, const APInt &Imm,
522                                  Type *Ty) = 0;
523   virtual unsigned getIntImmCost(Intrinsic::ID IID, unsigned Idx,
524                                  const APInt &Imm, Type *Ty) = 0;
525   virtual unsigned getNumberOfRegisters(bool Vector) = 0;
526   virtual unsigned getRegisterBitWidth(bool Vector) = 0;
527   virtual unsigned getMaxInterleaveFactor() = 0;
528   virtual unsigned
529   getArithmeticInstrCost(unsigned Opcode, Type *Ty, OperandValueKind Opd1Info,
530                          OperandValueKind Opd2Info,
531                          OperandValueProperties Opd1PropInfo,
532                          OperandValueProperties Opd2PropInfo) = 0;
533   virtual unsigned getShuffleCost(ShuffleKind Kind, Type *Tp, int Index,
534                                   Type *SubTp) = 0;
535   virtual unsigned getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src) = 0;
536   virtual unsigned getCFInstrCost(unsigned Opcode) = 0;
537   virtual unsigned getCmpSelInstrCost(unsigned Opcode, Type *ValTy,
538                                       Type *CondTy) = 0;
539   virtual unsigned getVectorInstrCost(unsigned Opcode, Type *Val,
540                                       unsigned Index) = 0;
541   virtual unsigned getMemoryOpCost(unsigned Opcode, Type *Src,
542                                    unsigned Alignment,
543                                    unsigned AddressSpace) = 0;
544   virtual unsigned getMaskedMemoryOpCost(unsigned Opcode, Type *Src,
545                                          unsigned Alignment,
546                                          unsigned AddressSpace) = 0;
547   virtual unsigned getReductionCost(unsigned Opcode, Type *Ty,
548                                     bool IsPairwiseForm) = 0;
549   virtual unsigned getIntrinsicInstrCost(Intrinsic::ID ID, Type *RetTy,
550                                          ArrayRef<Type *> Tys) = 0;
551   virtual unsigned getNumberOfParts(Type *Tp) = 0;
552   virtual unsigned getAddressComputationCost(Type *Ty, bool IsComplex) = 0;
553   virtual unsigned getCostOfKeepingLiveOverCall(ArrayRef<Type *> Tys) = 0;
554   virtual bool getTgtMemIntrinsic(IntrinsicInst *Inst,
555                                   MemIntrinsicInfo &Info) = 0;
556   virtual Value *getOrCreateResultFromMemIntrinsic(IntrinsicInst *Inst,
557                                                    Type *ExpectedType) = 0;
558 };
559
560 template <typename T>
561 class TargetTransformInfo::Model final : public TargetTransformInfo::Concept {
562   T Impl;
563
564 public:
565   Model(T Impl) : Impl(std::move(Impl)) {}
566   ~Model() override {}
567
568   unsigned getOperationCost(unsigned Opcode, Type *Ty, Type *OpTy) override {
569     return Impl.getOperationCost(Opcode, Ty, OpTy);
570   }
571   unsigned getGEPCost(const Value *Ptr,
572                       ArrayRef<const Value *> Operands) override {
573     return Impl.getGEPCost(Ptr, Operands);
574   }
575   unsigned getCallCost(FunctionType *FTy, int NumArgs) override {
576     return Impl.getCallCost(FTy, NumArgs);
577   }
578   unsigned getCallCost(const Function *F, int NumArgs) override {
579     return Impl.getCallCost(F, NumArgs);
580   }
581   unsigned getCallCost(const Function *F,
582                        ArrayRef<const Value *> Arguments) override {
583     return Impl.getCallCost(F, Arguments);
584   }
585   unsigned getIntrinsicCost(Intrinsic::ID IID, Type *RetTy,
586                             ArrayRef<Type *> ParamTys) override {
587     return Impl.getIntrinsicCost(IID, RetTy, ParamTys);
588   }
589   unsigned getIntrinsicCost(Intrinsic::ID IID, Type *RetTy,
590                             ArrayRef<const Value *> Arguments) override {
591     return Impl.getIntrinsicCost(IID, RetTy, Arguments);
592   }
593   unsigned getUserCost(const User *U) override { return Impl.getUserCost(U); }
594   bool hasBranchDivergence() override { return Impl.hasBranchDivergence(); }
595   bool isLoweredToCall(const Function *F) override {
596     return Impl.isLoweredToCall(F);
597   }
598   void getUnrollingPreferences(const Function *F, Loop *L,
599                                UnrollingPreferences &UP) override {
600     return Impl.getUnrollingPreferences(F, L, UP);
601   }
602   bool isLegalAddImmediate(int64_t Imm) override {
603     return Impl.isLegalAddImmediate(Imm);
604   }
605   bool isLegalICmpImmediate(int64_t Imm) override {
606     return Impl.isLegalICmpImmediate(Imm);
607   }
608   bool isLegalAddressingMode(Type *Ty, GlobalValue *BaseGV, int64_t BaseOffset,
609                              bool HasBaseReg, int64_t Scale) override {
610     return Impl.isLegalAddressingMode(Ty, BaseGV, BaseOffset, HasBaseReg,
611                                       Scale);
612   }
613   bool isLegalMaskedStore(Type *DataType, int Consecutive) override {
614     return Impl.isLegalMaskedStore(DataType, Consecutive);
615   }
616   bool isLegalMaskedLoad(Type *DataType, int Consecutive) override {
617     return Impl.isLegalMaskedLoad(DataType, Consecutive);
618   }
619   int getScalingFactorCost(Type *Ty, GlobalValue *BaseGV, int64_t BaseOffset,
620                            bool HasBaseReg, int64_t Scale) override {
621     return Impl.getScalingFactorCost(Ty, BaseGV, BaseOffset, HasBaseReg, Scale);
622   }
623   bool isTruncateFree(Type *Ty1, Type *Ty2) override {
624     return Impl.isTruncateFree(Ty1, Ty2);
625   }
626   bool isTypeLegal(Type *Ty) override { return Impl.isTypeLegal(Ty); }
627   unsigned getJumpBufAlignment() override { return Impl.getJumpBufAlignment(); }
628   unsigned getJumpBufSize() override { return Impl.getJumpBufSize(); }
629   bool shouldBuildLookupTables() override {
630     return Impl.shouldBuildLookupTables();
631   }
632   PopcntSupportKind getPopcntSupport(unsigned IntTyWidthInBit) override {
633     return Impl.getPopcntSupport(IntTyWidthInBit);
634   }
635   bool haveFastSqrt(Type *Ty) override { return Impl.haveFastSqrt(Ty); }
636   unsigned getIntImmCost(const APInt &Imm, Type *Ty) override {
637     return Impl.getIntImmCost(Imm, Ty);
638   }
639   unsigned getIntImmCost(unsigned Opc, unsigned Idx, const APInt &Imm,
640                          Type *Ty) override {
641     return Impl.getIntImmCost(Opc, Idx, Imm, Ty);
642   }
643   unsigned getIntImmCost(Intrinsic::ID IID, unsigned Idx, const APInt &Imm,
644                          Type *Ty) override {
645     return Impl.getIntImmCost(IID, Idx, Imm, Ty);
646   }
647   unsigned getNumberOfRegisters(bool Vector) override {
648     return Impl.getNumberOfRegisters(Vector);
649   }
650   unsigned getRegisterBitWidth(bool Vector) override {
651     return Impl.getRegisterBitWidth(Vector);
652   }
653   unsigned getMaxInterleaveFactor() override {
654     return Impl.getMaxInterleaveFactor();
655   }
656   unsigned
657   getArithmeticInstrCost(unsigned Opcode, Type *Ty, OperandValueKind Opd1Info,
658                          OperandValueKind Opd2Info,
659                          OperandValueProperties Opd1PropInfo,
660                          OperandValueProperties Opd2PropInfo) override {
661     return Impl.getArithmeticInstrCost(Opcode, Ty, Opd1Info, Opd2Info,
662                                        Opd1PropInfo, Opd2PropInfo);
663   }
664   unsigned getShuffleCost(ShuffleKind Kind, Type *Tp, int Index,
665                           Type *SubTp) override {
666     return Impl.getShuffleCost(Kind, Tp, Index, SubTp);
667   }
668   unsigned getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src) override {
669     return Impl.getCastInstrCost(Opcode, Dst, Src);
670   }
671   unsigned getCFInstrCost(unsigned Opcode) override {
672     return Impl.getCFInstrCost(Opcode);
673   }
674   unsigned getCmpSelInstrCost(unsigned Opcode, Type *ValTy,
675                               Type *CondTy) override {
676     return Impl.getCmpSelInstrCost(Opcode, ValTy, CondTy);
677   }
678   unsigned getVectorInstrCost(unsigned Opcode, Type *Val,
679                               unsigned Index) override {
680     return Impl.getVectorInstrCost(Opcode, Val, Index);
681   }
682   unsigned getMemoryOpCost(unsigned Opcode, Type *Src, unsigned Alignment,
683                            unsigned AddressSpace) override {
684     return Impl.getMemoryOpCost(Opcode, Src, Alignment, AddressSpace);
685   }
686   unsigned getMaskedMemoryOpCost(unsigned Opcode, Type *Src, unsigned Alignment,
687                                  unsigned AddressSpace) override {
688     return Impl.getMaskedMemoryOpCost(Opcode, Src, Alignment, AddressSpace);
689   }
690   unsigned getReductionCost(unsigned Opcode, Type *Ty,
691                             bool IsPairwiseForm) override {
692     return Impl.getReductionCost(Opcode, Ty, IsPairwiseForm);
693   }
694   unsigned getIntrinsicInstrCost(Intrinsic::ID ID, Type *RetTy,
695                                  ArrayRef<Type *> Tys) override {
696     return Impl.getIntrinsicInstrCost(ID, RetTy, Tys);
697   }
698   unsigned getNumberOfParts(Type *Tp) override {
699     return Impl.getNumberOfParts(Tp);
700   }
701   unsigned getAddressComputationCost(Type *Ty, bool IsComplex) override {
702     return Impl.getAddressComputationCost(Ty, IsComplex);
703   }
704   unsigned getCostOfKeepingLiveOverCall(ArrayRef<Type *> Tys) override {
705     return Impl.getCostOfKeepingLiveOverCall(Tys);
706   }
707   bool getTgtMemIntrinsic(IntrinsicInst *Inst,
708                           MemIntrinsicInfo &Info) override {
709     return Impl.getTgtMemIntrinsic(Inst, Info);
710   }
711   Value *getOrCreateResultFromMemIntrinsic(IntrinsicInst *Inst,
712                                            Type *ExpectedType) override {
713     return Impl.getOrCreateResultFromMemIntrinsic(Inst, ExpectedType);
714   }
715 };
716
717 template <typename T>
718 TargetTransformInfo::TargetTransformInfo(T Impl)
719     : TTIImpl(new Model<T>(Impl)) {}
720
721 /// \brief Analysis pass providing the \c TargetTransformInfo.
722 ///
723 /// The core idea of the TargetIRAnalysis is to expose an interface through
724 /// which LLVM targets can analyze and provide information about the middle
725 /// end's target-independent IR. This supports use cases such as target-aware
726 /// cost modeling of IR constructs.
727 ///
728 /// This is a function analysis because much of the cost modeling for targets
729 /// is done in a subtarget specific way and LLVM supports compiling different
730 /// functions targeting different subtargets in order to support runtime
731 /// dispatch according to the observed subtarget.
732 class TargetIRAnalysis {
733 public:
734   typedef TargetTransformInfo Result;
735
736   /// \brief Opaque, unique identifier for this analysis pass.
737   static void *ID() { return (void *)&PassID; }
738
739   /// \brief Provide access to a name for this pass for debugging purposes.
740   static StringRef name() { return "TargetIRAnalysis"; }
741
742   /// \brief Default construct a target IR analysis.
743   ///
744   /// This will use the module's datalayout to construct a baseline
745   /// conservative TTI result.
746   TargetIRAnalysis();
747
748   /// \brief Construct an IR analysis pass around a target-provide callback.
749   ///
750   /// The callback will be called with a particular function for which the TTI
751   /// is needed and must return a TTI object for that function.
752   TargetIRAnalysis(std::function<Result(Function &)> TTICallback);
753
754   // Value semantics. We spell out the constructors for MSVC.
755   TargetIRAnalysis(const TargetIRAnalysis &Arg)
756       : TTICallback(Arg.TTICallback) {}
757   TargetIRAnalysis(TargetIRAnalysis &&Arg)
758       : TTICallback(std::move(Arg.TTICallback)) {}
759   TargetIRAnalysis &operator=(const TargetIRAnalysis &RHS) {
760     TTICallback = RHS.TTICallback;
761     return *this;
762   }
763   TargetIRAnalysis &operator=(TargetIRAnalysis &&RHS) {
764     TTICallback = std::move(RHS.TTICallback);
765     return *this;
766   }
767
768   Result run(Function &F);
769
770 private:
771   static char PassID;
772
773   /// \brief The callback used to produce a result.
774   ///
775   /// We use a completely opaque callback so that targets can provide whatever
776   /// mechanism they desire for constructing the TTI for a given function.
777   ///
778   /// FIXME: Should we really use std::function? It's relatively inefficient.
779   /// It might be possible to arrange for even stateful callbacks to outlive
780   /// the analysis and thus use a function_ref which would be lighter weight.
781   /// This may also be less error prone as the callback is likely to reference
782   /// the external TargetMachine, and that reference needs to never dangle.
783   std::function<Result(Function &)> TTICallback;
784
785   /// \brief Helper function used as the callback in the default constructor.
786   static Result getDefaultTTI(Function &F);
787 };
788
789 /// \brief Wrapper pass for TargetTransformInfo.
790 ///
791 /// This pass can be constructed from a TTI object which it stores internally
792 /// and is queried by passes.
793 class TargetTransformInfoWrapperPass : public ImmutablePass {
794   TargetTransformInfo TTI;
795
796   virtual void anchor();
797
798 public:
799   static char ID;
800
801   /// \brief We must provide a default constructor for the pass but it should
802   /// never be used.
803   ///
804   /// Use the constructor below or call one of the creation routines.
805   TargetTransformInfoWrapperPass();
806
807   explicit TargetTransformInfoWrapperPass(TargetTransformInfo TTI);
808
809   TargetTransformInfo &getTTI() { return TTI; }
810   const TargetTransformInfo &getTTI() const { return TTI; }
811 };
812
813 /// \brief Create an analysis pass wrapper around a TTI object.
814 ///
815 /// This analysis pass just holds the TTI instance and makes it available to
816 /// clients.
817 ImmutablePass *createTargetTransformInfoWrapperPass(TargetTransformInfo TTI);
818
819 } // End llvm namespace
820
821 #endif