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