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