]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/include/llvm/Analysis/TargetTransformInfo.h
Merge llvm, clang, lld, lldb, compiler-rt and libc++ r304149, and update
[FreeBSD/FreeBSD.git] / contrib / llvm / 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/IR/Operator.h"
29 #include "llvm/IR/PassManager.h"
30 #include "llvm/Pass.h"
31 #include "llvm/Support/DataTypes.h"
32 #include <functional>
33
34 namespace llvm {
35
36 class Function;
37 class GlobalValue;
38 class Loop;
39 class ScalarEvolution;
40 class SCEV;
41 class Type;
42 class User;
43 class Value;
44
45 /// \brief Information about a load/store intrinsic defined by the target.
46 struct MemIntrinsicInfo {
47   /// This is the pointer that the intrinsic is loading from or storing to.
48   /// If this is non-null, then analysis/optimization passes can assume that
49   /// this intrinsic is functionally equivalent to a load/store from this
50   /// pointer.
51   Value *PtrVal = nullptr;
52
53   // Ordering for atomic operations.
54   AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
55
56   // Same Id is set by the target for corresponding load/store intrinsics.
57   unsigned short MatchingId = 0;
58
59   bool ReadMem = false;
60   bool WriteMem = false;
61   bool IsVolatile = false;
62
63   bool isUnordered() const {
64     return (Ordering == AtomicOrdering::NotAtomic ||
65             Ordering == AtomicOrdering::Unordered) && !IsVolatile;
66   }
67 };
68
69 /// \brief This pass provides access to the codegen interfaces that are needed
70 /// for IR-level transformations.
71 class TargetTransformInfo {
72 public:
73   /// \brief Construct a TTI object using a type implementing the \c Concept
74   /// API below.
75   ///
76   /// This is used by targets to construct a TTI wrapping their target-specific
77   /// implementaion that encodes appropriate costs for their target.
78   template <typename T> TargetTransformInfo(T Impl);
79
80   /// \brief Construct a baseline TTI object using a minimal implementation of
81   /// the \c Concept API below.
82   ///
83   /// The TTI implementation will reflect the information in the DataLayout
84   /// provided if non-null.
85   explicit TargetTransformInfo(const DataLayout &DL);
86
87   // Provide move semantics.
88   TargetTransformInfo(TargetTransformInfo &&Arg);
89   TargetTransformInfo &operator=(TargetTransformInfo &&RHS);
90
91   // We need to define the destructor out-of-line to define our sub-classes
92   // out-of-line.
93   ~TargetTransformInfo();
94
95   /// \brief Handle the invalidation of this information.
96   ///
97   /// When used as a result of \c TargetIRAnalysis this method will be called
98   /// when the function this was computed for changes. When it returns false,
99   /// the information is preserved across those changes.
100   bool invalidate(Function &, const PreservedAnalyses &,
101                   FunctionAnalysisManager::Invalidator &) {
102     // FIXME: We should probably in some way ensure that the subtarget
103     // information for a function hasn't changed.
104     return false;
105   }
106
107   /// \name Generic Target Information
108   /// @{
109
110   /// \brief Underlying constants for 'cost' values in this interface.
111   ///
112   /// Many APIs in this interface return a cost. This enum defines the
113   /// fundamental values that should be used to interpret (and produce) those
114   /// costs. The costs are returned as an int rather than a member of this
115   /// enumeration because it is expected that the cost of one IR instruction
116   /// may have a multiplicative factor to it or otherwise won't fit directly
117   /// into the enum. Moreover, it is common to sum or average costs which works
118   /// better as simple integral values. Thus this enum only provides constants.
119   /// Also note that the returned costs are signed integers to make it natural
120   /// to add, subtract, and test with zero (a common boundary condition). It is
121   /// not expected that 2^32 is a realistic cost to be modeling at any point.
122   ///
123   /// Note that these costs should usually reflect the intersection of code-size
124   /// cost and execution cost. A free instruction is typically one that folds
125   /// into another instruction. For example, reg-to-reg moves can often be
126   /// skipped by renaming the registers in the CPU, but they still are encoded
127   /// and thus wouldn't be considered 'free' here.
128   enum TargetCostConstants {
129     TCC_Free = 0,     ///< Expected to fold away in lowering.
130     TCC_Basic = 1,    ///< The cost of a typical 'add' instruction.
131     TCC_Expensive = 4 ///< The cost of a 'div' instruction on x86.
132   };
133
134   /// \brief Estimate the cost of a specific operation when lowered.
135   ///
136   /// Note that this is designed to work on an arbitrary synthetic opcode, and
137   /// thus work for hypothetical queries before an instruction has even been
138   /// formed. However, this does *not* work for GEPs, and must not be called
139   /// for a GEP instruction. Instead, use the dedicated getGEPCost interface as
140   /// analyzing a GEP's cost required more information.
141   ///
142   /// Typically only the result type is required, and the operand type can be
143   /// omitted. However, if the opcode is one of the cast instructions, the
144   /// operand type is required.
145   ///
146   /// The returned cost is defined in terms of \c TargetCostConstants, see its
147   /// comments for a detailed explanation of the cost values.
148   int getOperationCost(unsigned Opcode, Type *Ty, Type *OpTy = nullptr) const;
149
150   /// \brief Estimate the cost of a GEP operation when lowered.
151   ///
152   /// The contract for this function is the same as \c getOperationCost except
153   /// that it supports an interface that provides extra information specific to
154   /// the GEP operation.
155   int getGEPCost(Type *PointeeType, const Value *Ptr,
156                  ArrayRef<const Value *> Operands) const;
157
158   /// \brief Estimate the cost of a function call when lowered.
159   ///
160   /// The contract for this is the same as \c getOperationCost except that it
161   /// supports an interface that provides extra information specific to call
162   /// instructions.
163   ///
164   /// This is the most basic query for estimating call cost: it only knows the
165   /// function type and (potentially) the number of arguments at the call site.
166   /// The latter is only interesting for varargs function types.
167   int getCallCost(FunctionType *FTy, int NumArgs = -1) const;
168
169   /// \brief Estimate the cost of calling a specific function when lowered.
170   ///
171   /// This overload adds the ability to reason about the particular function
172   /// being called in the event it is a library call with special lowering.
173   int getCallCost(const Function *F, int NumArgs = -1) const;
174
175   /// \brief Estimate the cost of calling a specific function when lowered.
176   ///
177   /// This overload allows specifying a set of candidate argument values.
178   int getCallCost(const Function *F, ArrayRef<const Value *> Arguments) const;
179
180   /// \returns A value by which our inlining threshold should be multiplied.
181   /// This is primarily used to bump up the inlining threshold wholesale on
182   /// targets where calls are unusually expensive.
183   ///
184   /// TODO: This is a rather blunt instrument.  Perhaps altering the costs of
185   /// individual classes of instructions would be better.
186   unsigned getInliningThresholdMultiplier() const;
187
188   /// \brief Estimate the cost of an intrinsic when lowered.
189   ///
190   /// Mirrors the \c getCallCost method but uses an intrinsic identifier.
191   int getIntrinsicCost(Intrinsic::ID IID, Type *RetTy,
192                        ArrayRef<Type *> ParamTys) const;
193
194   /// \brief Estimate the cost of an intrinsic when lowered.
195   ///
196   /// Mirrors the \c getCallCost method but uses an intrinsic identifier.
197   int getIntrinsicCost(Intrinsic::ID IID, Type *RetTy,
198                        ArrayRef<const Value *> Arguments) const;
199
200   /// \return The estimated number of case clusters when lowering \p 'SI'.
201   /// \p JTSize Set a jump table size only when \p SI is suitable for a jump
202   /// table.
203   unsigned getEstimatedNumberOfCaseClusters(const SwitchInst &SI,
204                                             unsigned &JTSize) const;
205
206   /// \brief Estimate the cost of a given IR user when lowered.
207   ///
208   /// This can estimate the cost of either a ConstantExpr or Instruction when
209   /// lowered. It has two primary advantages over the \c getOperationCost and
210   /// \c getGEPCost above, and one significant disadvantage: it can only be
211   /// used when the IR construct has already been formed.
212   ///
213   /// The advantages are that it can inspect the SSA use graph to reason more
214   /// accurately about the cost. For example, all-constant-GEPs can often be
215   /// folded into a load or other instruction, but if they are used in some
216   /// other context they may not be folded. This routine can distinguish such
217   /// cases.
218   ///
219   /// The returned cost is defined in terms of \c TargetCostConstants, see its
220   /// comments for a detailed explanation of the cost values.
221   int getUserCost(const User *U) const;
222
223   /// \brief Return true if branch divergence exists.
224   ///
225   /// Branch divergence has a significantly negative impact on GPU performance
226   /// when threads in the same wavefront take different paths due to conditional
227   /// branches.
228   bool hasBranchDivergence() const;
229
230   /// \brief Returns whether V is a source of divergence.
231   ///
232   /// This function provides the target-dependent information for
233   /// the target-independent DivergenceAnalysis. DivergenceAnalysis first
234   /// builds the dependency graph, and then runs the reachability algorithm
235   /// starting with the sources of divergence.
236   bool isSourceOfDivergence(const Value *V) const;
237
238   /// Returns the address space ID for a target's 'flat' address space. Note
239   /// this is not necessarily the same as addrspace(0), which LLVM sometimes
240   /// refers to as the generic address space. The flat address space is a
241   /// generic address space that can be used access multiple segments of memory
242   /// with different address spaces. Access of a memory location through a
243   /// pointer with this address space is expected to be legal but slower
244   /// compared to the same memory location accessed through a pointer with a
245   /// different address space.
246   //
247   /// This is for for targets with different pointer representations which can
248   /// be converted with the addrspacecast instruction. If a pointer is converted
249   /// to this address space, optimizations should attempt to replace the access
250   /// with the source address space.
251   ///
252   /// \returns ~0u if the target does not have such a flat address space to
253   /// optimize away.
254   unsigned getFlatAddressSpace() const;
255
256   /// \brief Test whether calls to a function lower to actual program function
257   /// calls.
258   ///
259   /// The idea is to test whether the program is likely to require a 'call'
260   /// instruction or equivalent in order to call the given function.
261   ///
262   /// FIXME: It's not clear that this is a good or useful query API. Client's
263   /// should probably move to simpler cost metrics using the above.
264   /// Alternatively, we could split the cost interface into distinct code-size
265   /// and execution-speed costs. This would allow modelling the core of this
266   /// query more accurately as a call is a single small instruction, but
267   /// incurs significant execution cost.
268   bool isLoweredToCall(const Function *F) const;
269
270   /// Parameters that control the generic loop unrolling transformation.
271   struct UnrollingPreferences {
272     /// The cost threshold for the unrolled loop. Should be relative to the
273     /// getUserCost values returned by this API, and the expectation is that
274     /// the unrolled loop's instructions when run through that interface should
275     /// not exceed this cost. However, this is only an estimate. Also, specific
276     /// loops may be unrolled even with a cost above this threshold if deemed
277     /// profitable. Set this to UINT_MAX to disable the loop body cost
278     /// restriction.
279     unsigned Threshold;
280     /// If complete unrolling will reduce the cost of the loop, we will boost
281     /// the Threshold by a certain percent to allow more aggressive complete
282     /// unrolling. This value provides the maximum boost percentage that we
283     /// can apply to Threshold (The value should be no less than 100).
284     /// BoostedThreshold = Threshold * min(RolledCost / UnrolledCost,
285     ///                                    MaxPercentThresholdBoost / 100)
286     /// E.g. if complete unrolling reduces the loop execution time by 50%
287     /// then we boost the threshold by the factor of 2x. If unrolling is not
288     /// expected to reduce the running time, then we do not increase the
289     /// threshold.
290     unsigned MaxPercentThresholdBoost;
291     /// The cost threshold for the unrolled loop when optimizing for size (set
292     /// to UINT_MAX to disable).
293     unsigned OptSizeThreshold;
294     /// The cost threshold for the unrolled loop, like Threshold, but used
295     /// for partial/runtime unrolling (set to UINT_MAX to disable).
296     unsigned PartialThreshold;
297     /// The cost threshold for the unrolled loop when optimizing for size, like
298     /// OptSizeThreshold, but used for partial/runtime unrolling (set to
299     /// UINT_MAX to disable).
300     unsigned PartialOptSizeThreshold;
301     /// A forced unrolling factor (the number of concatenated bodies of the
302     /// original loop in the unrolled loop body). When set to 0, the unrolling
303     /// transformation will select an unrolling factor based on the current cost
304     /// threshold and other factors.
305     unsigned Count;
306     /// A forced peeling factor (the number of bodied of the original loop
307     /// that should be peeled off before the loop body). When set to 0, the
308     /// unrolling transformation will select a peeling factor based on profile
309     /// information and other factors.
310     unsigned PeelCount;
311     /// Default unroll count for loops with run-time trip count.
312     unsigned DefaultUnrollRuntimeCount;
313     // Set the maximum unrolling factor. The unrolling factor may be selected
314     // using the appropriate cost threshold, but may not exceed this number
315     // (set to UINT_MAX to disable). This does not apply in cases where the
316     // loop is being fully unrolled.
317     unsigned MaxCount;
318     /// Set the maximum unrolling factor for full unrolling. Like MaxCount, but
319     /// applies even if full unrolling is selected. This allows a target to fall
320     /// back to Partial unrolling if full unrolling is above FullUnrollMaxCount.
321     unsigned FullUnrollMaxCount;
322     // Represents number of instructions optimized when "back edge"
323     // becomes "fall through" in unrolled loop.
324     // For now we count a conditional branch on a backedge and a comparison
325     // feeding it.
326     unsigned BEInsns;
327     /// Allow partial unrolling (unrolling of loops to expand the size of the
328     /// loop body, not only to eliminate small constant-trip-count loops).
329     bool Partial;
330     /// Allow runtime unrolling (unrolling of loops to expand the size of the
331     /// loop body even when the number of loop iterations is not known at
332     /// compile time).
333     bool Runtime;
334     /// Allow generation of a loop remainder (extra iterations after unroll).
335     bool AllowRemainder;
336     /// Allow emitting expensive instructions (such as divisions) when computing
337     /// the trip count of a loop for runtime unrolling.
338     bool AllowExpensiveTripCount;
339     /// Apply loop unroll on any kind of loop
340     /// (mainly to loops that fail runtime unrolling).
341     bool Force;
342     /// Allow using trip count upper bound to unroll loops.
343     bool UpperBound;
344     /// Allow peeling off loop iterations for loops with low dynamic tripcount.
345     bool AllowPeeling;
346   };
347
348   /// \brief Get target-customized preferences for the generic loop unrolling
349   /// transformation. The caller will initialize UP with the current
350   /// target-independent defaults.
351   void getUnrollingPreferences(Loop *L, UnrollingPreferences &UP) const;
352
353   /// @}
354
355   /// \name Scalar Target Information
356   /// @{
357
358   /// \brief Flags indicating the kind of support for population count.
359   ///
360   /// Compared to the SW implementation, HW support is supposed to
361   /// significantly boost the performance when the population is dense, and it
362   /// may or may not degrade performance if the population is sparse. A HW
363   /// support is considered as "Fast" if it can outperform, or is on a par
364   /// with, SW implementation when the population is sparse; otherwise, it is
365   /// considered as "Slow".
366   enum PopcntSupportKind { PSK_Software, PSK_SlowHardware, PSK_FastHardware };
367
368   /// \brief Return true if the specified immediate is legal add immediate, that
369   /// is the target has add instructions which can add a register with the
370   /// immediate without having to materialize the immediate into a register.
371   bool isLegalAddImmediate(int64_t Imm) const;
372
373   /// \brief Return true if the specified immediate is legal icmp immediate,
374   /// that is the target has icmp instructions which can compare a register
375   /// against the immediate without having to materialize the immediate into a
376   /// register.
377   bool isLegalICmpImmediate(int64_t Imm) const;
378
379   /// \brief Return true if the addressing mode represented by AM is legal for
380   /// this target, for a load/store of the specified type.
381   /// The type may be VoidTy, in which case only return true if the addressing
382   /// mode is legal for a load/store of any legal type.
383   /// TODO: Handle pre/postinc as well.
384   bool isLegalAddressingMode(Type *Ty, GlobalValue *BaseGV, int64_t BaseOffset,
385                              bool HasBaseReg, int64_t Scale,
386                              unsigned AddrSpace = 0) const;
387
388   /// \brief Return true if the target supports masked load/store
389   /// AVX2 and AVX-512 targets allow masks for consecutive load and store
390   bool isLegalMaskedStore(Type *DataType) const;
391   bool isLegalMaskedLoad(Type *DataType) const;
392
393   /// \brief Return true if the target supports masked gather/scatter
394   /// AVX-512 fully supports gather and scatter for vectors with 32 and 64
395   /// bits scalar type.
396   bool isLegalMaskedScatter(Type *DataType) const;
397   bool isLegalMaskedGather(Type *DataType) const;
398
399   /// Return true if target doesn't mind addresses in vectors.
400   bool prefersVectorizedAddressing() const;
401
402   /// \brief Return the cost of the scaling factor used in the addressing
403   /// mode represented by AM for this target, for a load/store
404   /// of the specified type.
405   /// If the AM is supported, the return value must be >= 0.
406   /// If the AM is not supported, it returns a negative value.
407   /// TODO: Handle pre/postinc as well.
408   int getScalingFactorCost(Type *Ty, GlobalValue *BaseGV, int64_t BaseOffset,
409                            bool HasBaseReg, int64_t Scale,
410                            unsigned AddrSpace = 0) const;
411
412   /// \brief Return true if target supports the load / store
413   /// instruction with the given Offset on the form reg + Offset. It
414   /// may be that Offset is too big for a certain type (register
415   /// class).
416   bool isFoldableMemAccessOffset(Instruction *I, int64_t Offset) const;
417   
418   /// \brief Return true if it's free to truncate a value of type Ty1 to type
419   /// Ty2. e.g. On x86 it's free to truncate a i32 value in register EAX to i16
420   /// by referencing its sub-register AX.
421   bool isTruncateFree(Type *Ty1, Type *Ty2) const;
422
423   /// \brief Return true if it is profitable to hoist instruction in the
424   /// then/else to before if.
425   bool isProfitableToHoist(Instruction *I) const;
426
427   /// \brief Return true if this type is legal.
428   bool isTypeLegal(Type *Ty) const;
429
430   /// \brief Returns the target's jmp_buf alignment in bytes.
431   unsigned getJumpBufAlignment() const;
432
433   /// \brief Returns the target's jmp_buf size in bytes.
434   unsigned getJumpBufSize() const;
435
436   /// \brief Return true if switches should be turned into lookup tables for the
437   /// target.
438   bool shouldBuildLookupTables() const;
439
440   /// \brief Return true if switches should be turned into lookup tables
441   /// containing this constant value for the target.
442   bool shouldBuildLookupTablesForConstant(Constant *C) const;
443
444   unsigned getScalarizationOverhead(Type *Ty, bool Insert, bool Extract) const;
445
446   unsigned getOperandsScalarizationOverhead(ArrayRef<const Value *> Args,
447                                             unsigned VF) const;
448
449   /// If target has efficient vector element load/store instructions, it can
450   /// return true here so that insertion/extraction costs are not added to
451   /// the scalarization cost of a load/store.
452   bool supportsEfficientVectorElementLoadStore() const;
453
454   /// \brief Don't restrict interleaved unrolling to small loops.
455   bool enableAggressiveInterleaving(bool LoopHasReductions) const;
456
457   /// \brief Enable matching of interleaved access groups.
458   bool enableInterleavedAccessVectorization() const;
459
460   /// \brief Indicate that it is potentially unsafe to automatically vectorize
461   /// floating-point operations because the semantics of vector and scalar
462   /// floating-point semantics may differ. For example, ARM NEON v7 SIMD math
463   /// does not support IEEE-754 denormal numbers, while depending on the
464   /// platform, scalar floating-point math does.
465   /// This applies to floating-point math operations and calls, not memory
466   /// operations, shuffles, or casts.
467   bool isFPVectorizationPotentiallyUnsafe() const;
468
469   /// \brief Determine if the target supports unaligned memory accesses.
470   bool allowsMisalignedMemoryAccesses(LLVMContext &Context,
471                                       unsigned BitWidth, unsigned AddressSpace = 0,
472                                       unsigned Alignment = 1,
473                                       bool *Fast = nullptr) const;
474
475   /// \brief Return hardware support for population count.
476   PopcntSupportKind getPopcntSupport(unsigned IntTyWidthInBit) const;
477
478   /// \brief Return true if the hardware has a fast square-root instruction.
479   bool haveFastSqrt(Type *Ty) const;
480
481   /// \brief Return the expected cost of supporting the floating point operation
482   /// of the specified type.
483   int getFPOpCost(Type *Ty) const;
484
485   /// \brief Return the expected cost of materializing for the given integer
486   /// immediate of the specified type.
487   int getIntImmCost(const APInt &Imm, Type *Ty) const;
488
489   /// \brief Return the expected cost of materialization for the given integer
490   /// immediate of the specified type for a given instruction. The cost can be
491   /// zero if the immediate can be folded into the specified instruction.
492   int getIntImmCost(unsigned Opc, unsigned Idx, const APInt &Imm,
493                     Type *Ty) const;
494   int getIntImmCost(Intrinsic::ID IID, unsigned Idx, const APInt &Imm,
495                     Type *Ty) const;
496
497   /// \brief Return the expected cost for the given integer when optimising
498   /// for size. This is different than the other integer immediate cost
499   /// functions in that it is subtarget agnostic. This is useful when you e.g.
500   /// target one ISA such as Aarch32 but smaller encodings could be possible
501   /// with another such as Thumb. This return value is used as a penalty when
502   /// the total costs for a constant is calculated (the bigger the cost, the
503   /// more beneficial constant hoisting is).
504   int getIntImmCodeSizeCost(unsigned Opc, unsigned Idx, const APInt &Imm,
505                             Type *Ty) const;
506   /// @}
507
508   /// \name Vector Target Information
509   /// @{
510
511   /// \brief The various kinds of shuffle patterns for vector queries.
512   enum ShuffleKind {
513     SK_Broadcast,       ///< Broadcast element 0 to all other elements.
514     SK_Reverse,         ///< Reverse the order of the vector.
515     SK_Alternate,       ///< Choose alternate elements from vector.
516     SK_InsertSubvector, ///< InsertSubvector. Index indicates start offset.
517     SK_ExtractSubvector,///< ExtractSubvector Index indicates start offset.
518     SK_PermuteTwoSrc,   ///< Merge elements from two source vectors into one
519                         ///< with any shuffle mask.
520     SK_PermuteSingleSrc ///< Shuffle elements of single source vector with any
521                         ///< shuffle mask.
522   };
523
524   /// \brief Additional information about an operand's possible values.
525   enum OperandValueKind {
526     OK_AnyValue,               // Operand can have any value.
527     OK_UniformValue,           // Operand is uniform (splat of a value).
528     OK_UniformConstantValue,   // Operand is uniform constant.
529     OK_NonUniformConstantValue // Operand is a non uniform constant value.
530   };
531
532   /// \brief Additional properties of an operand's values.
533   enum OperandValueProperties { OP_None = 0, OP_PowerOf2 = 1 };
534
535   /// \return The number of scalar or vector registers that the target has.
536   /// If 'Vectors' is true, it returns the number of vector registers. If it is
537   /// set to false, it returns the number of scalar registers.
538   unsigned getNumberOfRegisters(bool Vector) const;
539
540   /// \return The width of the largest scalar or vector register type.
541   unsigned getRegisterBitWidth(bool Vector) const;
542
543   /// \return The width of the smallest vector register type.
544   unsigned getMinVectorRegisterBitWidth() const;
545
546   /// \return True if it should be considered for address type promotion.
547   /// \p AllowPromotionWithoutCommonHeader Set true if promoting \p I is
548   /// profitable without finding other extensions fed by the same input.
549   bool shouldConsiderAddressTypePromotion(
550       const Instruction &I, bool &AllowPromotionWithoutCommonHeader) const;
551
552   /// \return The size of a cache line in bytes.
553   unsigned getCacheLineSize() const;
554
555   /// \return How much before a load we should place the prefetch instruction.
556   /// This is currently measured in number of instructions.
557   unsigned getPrefetchDistance() const;
558
559   /// \return Some HW prefetchers can handle accesses up to a certain constant
560   /// stride.  This is the minimum stride in bytes where it makes sense to start
561   /// adding SW prefetches.  The default is 1, i.e. prefetch with any stride.
562   unsigned getMinPrefetchStride() const;
563
564   /// \return The maximum number of iterations to prefetch ahead.  If the
565   /// required number of iterations is more than this number, no prefetching is
566   /// performed.
567   unsigned getMaxPrefetchIterationsAhead() const;
568
569   /// \return The maximum interleave factor that any transform should try to
570   /// perform for this target. This number depends on the level of parallelism
571   /// and the number of execution units in the CPU.
572   unsigned getMaxInterleaveFactor(unsigned VF) const;
573
574   /// \return The expected cost of arithmetic ops, such as mul, xor, fsub, etc.
575   /// \p Args is an optional argument which holds the instruction operands  
576   /// values so the TTI can analyize those values searching for special 
577   /// cases\optimizations based on those values.
578   int getArithmeticInstrCost(
579       unsigned Opcode, Type *Ty, OperandValueKind Opd1Info = OK_AnyValue,
580       OperandValueKind Opd2Info = OK_AnyValue,
581       OperandValueProperties Opd1PropInfo = OP_None,
582       OperandValueProperties Opd2PropInfo = OP_None,
583       ArrayRef<const Value *> Args = ArrayRef<const Value *>()) const;
584
585   /// \return The cost of a shuffle instruction of kind Kind and of type Tp.
586   /// The index and subtype parameters are used by the subvector insertion and
587   /// extraction shuffle kinds.
588   int getShuffleCost(ShuffleKind Kind, Type *Tp, int Index = 0,
589                      Type *SubTp = nullptr) const;
590
591   /// \return The expected cost of cast instructions, such as bitcast, trunc,
592   /// zext, etc. If there is an existing instruction that holds Opcode, it
593   /// may be passed in the 'I' parameter.
594   int getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src,
595                        const Instruction *I = nullptr) const;
596
597   /// \return The expected cost of a sign- or zero-extended vector extract. Use
598   /// -1 to indicate that there is no information about the index value.
599   int getExtractWithExtendCost(unsigned Opcode, Type *Dst, VectorType *VecTy,
600                                unsigned Index = -1) const;
601
602   /// \return The expected cost of control-flow related instructions such as
603   /// Phi, Ret, Br.
604   int getCFInstrCost(unsigned Opcode) const;
605
606   /// \returns The expected cost of compare and select instructions. If there
607   /// is an existing instruction that holds Opcode, it may be passed in the
608   /// 'I' parameter.
609   int getCmpSelInstrCost(unsigned Opcode, Type *ValTy,
610                  Type *CondTy = nullptr, const Instruction *I = nullptr) const;
611
612   /// \return The expected cost of vector Insert and Extract.
613   /// Use -1 to indicate that there is no information on the index value.
614   int getVectorInstrCost(unsigned Opcode, Type *Val, unsigned Index = -1) const;
615
616   /// \return The cost of Load and Store instructions.
617   int getMemoryOpCost(unsigned Opcode, Type *Src, unsigned Alignment,
618                       unsigned AddressSpace, const Instruction *I = nullptr) const;
619
620   /// \return The cost of masked Load and Store instructions.
621   int getMaskedMemoryOpCost(unsigned Opcode, Type *Src, unsigned Alignment,
622                             unsigned AddressSpace) const;
623
624   /// \return The cost of Gather or Scatter operation
625   /// \p Opcode - is a type of memory access Load or Store
626   /// \p DataTy - a vector type of the data to be loaded or stored
627   /// \p Ptr - pointer [or vector of pointers] - address[es] in memory
628   /// \p VariableMask - true when the memory access is predicated with a mask
629   ///                   that is not a compile-time constant
630   /// \p Alignment - alignment of single element
631   int getGatherScatterOpCost(unsigned Opcode, Type *DataTy, Value *Ptr,
632                              bool VariableMask, unsigned Alignment) const;
633
634   /// \return The cost of the interleaved memory operation.
635   /// \p Opcode is the memory operation code
636   /// \p VecTy is the vector type of the interleaved access.
637   /// \p Factor is the interleave factor
638   /// \p Indices is the indices for interleaved load members (as interleaved
639   ///    load allows gaps)
640   /// \p Alignment is the alignment of the memory operation
641   /// \p AddressSpace is address space of the pointer.
642   int getInterleavedMemoryOpCost(unsigned Opcode, Type *VecTy, unsigned Factor,
643                                  ArrayRef<unsigned> Indices, unsigned Alignment,
644                                  unsigned AddressSpace) const;
645
646   /// \brief Calculate the cost of performing a vector reduction.
647   ///
648   /// This is the cost of reducing the vector value of type \p Ty to a scalar
649   /// value using the operation denoted by \p Opcode. The form of the reduction
650   /// can either be a pairwise reduction or a reduction that splits the vector
651   /// at every reduction level.
652   ///
653   /// Pairwise:
654   ///  (v0, v1, v2, v3)
655   ///  ((v0+v1), (v2, v3), undef, undef)
656   /// Split:
657   ///  (v0, v1, v2, v3)
658   ///  ((v0+v2), (v1+v3), undef, undef)
659   int getReductionCost(unsigned Opcode, Type *Ty, bool IsPairwiseForm) const;
660
661   /// \returns The cost of Intrinsic instructions. Analyses the real arguments.
662   /// Three cases are handled: 1. scalar instruction 2. vector instruction
663   /// 3. scalar instruction which is to be vectorized with VF.
664   int getIntrinsicInstrCost(Intrinsic::ID ID, Type *RetTy,
665                             ArrayRef<Value *> Args, FastMathFlags FMF,
666                             unsigned VF = 1) const;
667
668   /// \returns The cost of Intrinsic instructions. Types analysis only.
669   /// If ScalarizationCostPassed is UINT_MAX, the cost of scalarizing the
670   /// arguments and the return value will be computed based on types.
671   int getIntrinsicInstrCost(Intrinsic::ID ID, Type *RetTy,
672                             ArrayRef<Type *> Tys, FastMathFlags FMF,
673                             unsigned ScalarizationCostPassed = UINT_MAX) const;
674
675   /// \returns The cost of Call instructions.
676   int getCallInstrCost(Function *F, Type *RetTy, ArrayRef<Type *> Tys) const;
677
678   /// \returns The number of pieces into which the provided type must be
679   /// split during legalization. Zero is returned when the answer is unknown.
680   unsigned getNumberOfParts(Type *Tp) const;
681
682   /// \returns The cost of the address computation. For most targets this can be
683   /// merged into the instruction indexing mode. Some targets might want to
684   /// distinguish between address computation for memory operations on vector
685   /// types and scalar types. Such targets should override this function.
686   /// The 'SE' parameter holds pointer for the scalar evolution object which
687   /// is used in order to get the Ptr step value in case of constant stride.
688   /// The 'Ptr' parameter holds SCEV of the access pointer.
689   int getAddressComputationCost(Type *Ty, ScalarEvolution *SE = nullptr,
690                                 const SCEV *Ptr = nullptr) const;
691
692   /// \returns The cost, if any, of keeping values of the given types alive
693   /// over a callsite.
694   ///
695   /// Some types may require the use of register classes that do not have
696   /// any callee-saved registers, so would require a spill and fill.
697   unsigned getCostOfKeepingLiveOverCall(ArrayRef<Type *> Tys) const;
698
699   /// \returns True if the intrinsic is a supported memory intrinsic.  Info
700   /// will contain additional information - whether the intrinsic may write
701   /// or read to memory, volatility and the pointer.  Info is undefined
702   /// if false is returned.
703   bool getTgtMemIntrinsic(IntrinsicInst *Inst, MemIntrinsicInfo &Info) const;
704
705   /// \returns A value which is the result of the given memory intrinsic.  New
706   /// instructions may be created to extract the result from the given intrinsic
707   /// memory operation.  Returns nullptr if the target cannot create a result
708   /// from the given intrinsic.
709   Value *getOrCreateResultFromMemIntrinsic(IntrinsicInst *Inst,
710                                            Type *ExpectedType) const;
711
712   /// \returns True if the two functions have compatible attributes for inlining
713   /// purposes.
714   bool areInlineCompatible(const Function *Caller,
715                            const Function *Callee) const;
716
717   /// \returns The bitwidth of the largest vector type that should be used to
718   /// load/store in the given address space.
719   unsigned getLoadStoreVecRegBitWidth(unsigned AddrSpace) const;
720
721   /// \returns True if the load instruction is legal to vectorize.
722   bool isLegalToVectorizeLoad(LoadInst *LI) const;
723
724   /// \returns True if the store instruction is legal to vectorize.
725   bool isLegalToVectorizeStore(StoreInst *SI) const;
726
727   /// \returns True if it is legal to vectorize the given load chain.
728   bool isLegalToVectorizeLoadChain(unsigned ChainSizeInBytes,
729                                    unsigned Alignment,
730                                    unsigned AddrSpace) const;
731
732   /// \returns True if it is legal to vectorize the given store chain.
733   bool isLegalToVectorizeStoreChain(unsigned ChainSizeInBytes,
734                                     unsigned Alignment,
735                                     unsigned AddrSpace) const;
736
737   /// \returns The new vector factor value if the target doesn't support \p
738   /// SizeInBytes loads or has a better vector factor.
739   unsigned getLoadVectorFactor(unsigned VF, unsigned LoadSize,
740                                unsigned ChainSizeInBytes,
741                                VectorType *VecTy) const;
742
743   /// \returns The new vector factor value if the target doesn't support \p
744   /// SizeInBytes stores or has a better vector factor.
745   unsigned getStoreVectorFactor(unsigned VF, unsigned StoreSize,
746                                 unsigned ChainSizeInBytes,
747                                 VectorType *VecTy) const;
748
749   /// Flags describing the kind of vector reduction.
750   struct ReductionFlags {
751     ReductionFlags() : IsMaxOp(false), IsSigned(false), NoNaN(false) {}
752     bool IsMaxOp;  ///< If the op a min/max kind, true if it's a max operation.
753     bool IsSigned; ///< Whether the operation is a signed int reduction.
754     bool NoNaN;    ///< If op is an fp min/max, whether NaNs may be present.
755   };
756
757   /// \returns True if the target wants to handle the given reduction idiom in
758   /// the intrinsics form instead of the shuffle form.
759   bool useReductionIntrinsic(unsigned Opcode, Type *Ty,
760                              ReductionFlags Flags) const;
761
762   /// \returns True if the target wants to expand the given reduction intrinsic
763   /// into a shuffle sequence.
764   bool shouldExpandReduction(const IntrinsicInst *II) const;
765   /// @}
766
767 private:
768   /// \brief The abstract base class used to type erase specific TTI
769   /// implementations.
770   class Concept;
771
772   /// \brief The template model for the base class which wraps a concrete
773   /// implementation in a type erased interface.
774   template <typename T> class Model;
775
776   std::unique_ptr<Concept> TTIImpl;
777 };
778
779 class TargetTransformInfo::Concept {
780 public:
781   virtual ~Concept() = 0;
782   virtual const DataLayout &getDataLayout() const = 0;
783   virtual int getOperationCost(unsigned Opcode, Type *Ty, Type *OpTy) = 0;
784   virtual int getGEPCost(Type *PointeeType, const Value *Ptr,
785                          ArrayRef<const Value *> Operands) = 0;
786   virtual int getCallCost(FunctionType *FTy, int NumArgs) = 0;
787   virtual int getCallCost(const Function *F, int NumArgs) = 0;
788   virtual int getCallCost(const Function *F,
789                           ArrayRef<const Value *> Arguments) = 0;
790   virtual unsigned getInliningThresholdMultiplier() = 0;
791   virtual int getIntrinsicCost(Intrinsic::ID IID, Type *RetTy,
792                                ArrayRef<Type *> ParamTys) = 0;
793   virtual int getIntrinsicCost(Intrinsic::ID IID, Type *RetTy,
794                                ArrayRef<const Value *> Arguments) = 0;
795   virtual unsigned getEstimatedNumberOfCaseClusters(const SwitchInst &SI,
796                                                     unsigned &JTSize) = 0;
797   virtual int getUserCost(const User *U) = 0;
798   virtual bool hasBranchDivergence() = 0;
799   virtual bool isSourceOfDivergence(const Value *V) = 0;
800   virtual unsigned getFlatAddressSpace() = 0;
801   virtual bool isLoweredToCall(const Function *F) = 0;
802   virtual void getUnrollingPreferences(Loop *L, UnrollingPreferences &UP) = 0;
803   virtual bool isLegalAddImmediate(int64_t Imm) = 0;
804   virtual bool isLegalICmpImmediate(int64_t Imm) = 0;
805   virtual bool isLegalAddressingMode(Type *Ty, GlobalValue *BaseGV,
806                                      int64_t BaseOffset, bool HasBaseReg,
807                                      int64_t Scale,
808                                      unsigned AddrSpace) = 0;
809   virtual bool isLegalMaskedStore(Type *DataType) = 0;
810   virtual bool isLegalMaskedLoad(Type *DataType) = 0;
811   virtual bool isLegalMaskedScatter(Type *DataType) = 0;
812   virtual bool isLegalMaskedGather(Type *DataType) = 0;
813   virtual bool prefersVectorizedAddressing() = 0;
814   virtual int getScalingFactorCost(Type *Ty, GlobalValue *BaseGV,
815                                    int64_t BaseOffset, bool HasBaseReg,
816                                    int64_t Scale, unsigned AddrSpace) = 0;
817   virtual bool isFoldableMemAccessOffset(Instruction *I, int64_t Offset) = 0;
818   virtual bool isTruncateFree(Type *Ty1, Type *Ty2) = 0;
819   virtual bool isProfitableToHoist(Instruction *I) = 0;
820   virtual bool isTypeLegal(Type *Ty) = 0;
821   virtual unsigned getJumpBufAlignment() = 0;
822   virtual unsigned getJumpBufSize() = 0;
823   virtual bool shouldBuildLookupTables() = 0;
824   virtual bool shouldBuildLookupTablesForConstant(Constant *C) = 0;
825   virtual unsigned
826   getScalarizationOverhead(Type *Ty, bool Insert, bool Extract) = 0;
827   virtual unsigned getOperandsScalarizationOverhead(ArrayRef<const Value *> Args,
828                                                     unsigned VF) = 0;
829   virtual bool supportsEfficientVectorElementLoadStore() = 0;
830   virtual bool enableAggressiveInterleaving(bool LoopHasReductions) = 0;
831   virtual bool enableInterleavedAccessVectorization() = 0;
832   virtual bool isFPVectorizationPotentiallyUnsafe() = 0;
833   virtual bool allowsMisalignedMemoryAccesses(LLVMContext &Context,
834                                               unsigned BitWidth,
835                                               unsigned AddressSpace,
836                                               unsigned Alignment,
837                                               bool *Fast) = 0;
838   virtual PopcntSupportKind getPopcntSupport(unsigned IntTyWidthInBit) = 0;
839   virtual bool haveFastSqrt(Type *Ty) = 0;
840   virtual int getFPOpCost(Type *Ty) = 0;
841   virtual int getIntImmCodeSizeCost(unsigned Opc, unsigned Idx, const APInt &Imm,
842                                     Type *Ty) = 0;
843   virtual int getIntImmCost(const APInt &Imm, Type *Ty) = 0;
844   virtual int getIntImmCost(unsigned Opc, unsigned Idx, const APInt &Imm,
845                             Type *Ty) = 0;
846   virtual int getIntImmCost(Intrinsic::ID IID, unsigned Idx, const APInt &Imm,
847                             Type *Ty) = 0;
848   virtual unsigned getNumberOfRegisters(bool Vector) = 0;
849   virtual unsigned getRegisterBitWidth(bool Vector) = 0;
850   virtual unsigned getMinVectorRegisterBitWidth() = 0;
851   virtual bool shouldConsiderAddressTypePromotion(
852       const Instruction &I, bool &AllowPromotionWithoutCommonHeader) = 0;
853   virtual unsigned getCacheLineSize() = 0;
854   virtual unsigned getPrefetchDistance() = 0;
855   virtual unsigned getMinPrefetchStride() = 0;
856   virtual unsigned getMaxPrefetchIterationsAhead() = 0;
857   virtual unsigned getMaxInterleaveFactor(unsigned VF) = 0;
858   virtual unsigned
859   getArithmeticInstrCost(unsigned Opcode, Type *Ty, OperandValueKind Opd1Info,
860                          OperandValueKind Opd2Info,
861                          OperandValueProperties Opd1PropInfo,
862                          OperandValueProperties Opd2PropInfo,
863                          ArrayRef<const Value *> Args) = 0;
864   virtual int getShuffleCost(ShuffleKind Kind, Type *Tp, int Index,
865                              Type *SubTp) = 0;
866   virtual int getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src,
867                                const Instruction *I) = 0;
868   virtual int getExtractWithExtendCost(unsigned Opcode, Type *Dst,
869                                        VectorType *VecTy, unsigned Index) = 0;
870   virtual int getCFInstrCost(unsigned Opcode) = 0;
871   virtual int getCmpSelInstrCost(unsigned Opcode, Type *ValTy,
872                                 Type *CondTy, const Instruction *I) = 0;
873   virtual int getVectorInstrCost(unsigned Opcode, Type *Val,
874                                  unsigned Index) = 0;
875   virtual int getMemoryOpCost(unsigned Opcode, Type *Src, unsigned Alignment,
876                               unsigned AddressSpace, const Instruction *I) = 0;
877   virtual int getMaskedMemoryOpCost(unsigned Opcode, Type *Src,
878                                     unsigned Alignment,
879                                     unsigned AddressSpace) = 0;
880   virtual int getGatherScatterOpCost(unsigned Opcode, Type *DataTy,
881                                      Value *Ptr, bool VariableMask,
882                                      unsigned Alignment) = 0;
883   virtual int getInterleavedMemoryOpCost(unsigned Opcode, Type *VecTy,
884                                          unsigned Factor,
885                                          ArrayRef<unsigned> Indices,
886                                          unsigned Alignment,
887                                          unsigned AddressSpace) = 0;
888   virtual int getReductionCost(unsigned Opcode, Type *Ty,
889                                bool IsPairwiseForm) = 0;
890   virtual int getIntrinsicInstrCost(Intrinsic::ID ID, Type *RetTy,
891                       ArrayRef<Type *> Tys, FastMathFlags FMF,
892                       unsigned ScalarizationCostPassed) = 0;
893   virtual int getIntrinsicInstrCost(Intrinsic::ID ID, Type *RetTy,
894          ArrayRef<Value *> Args, FastMathFlags FMF, unsigned VF) = 0;
895   virtual int getCallInstrCost(Function *F, Type *RetTy,
896                                ArrayRef<Type *> Tys) = 0;
897   virtual unsigned getNumberOfParts(Type *Tp) = 0;
898   virtual int getAddressComputationCost(Type *Ty, ScalarEvolution *SE,
899                                         const SCEV *Ptr) = 0;
900   virtual unsigned getCostOfKeepingLiveOverCall(ArrayRef<Type *> Tys) = 0;
901   virtual bool getTgtMemIntrinsic(IntrinsicInst *Inst,
902                                   MemIntrinsicInfo &Info) = 0;
903   virtual Value *getOrCreateResultFromMemIntrinsic(IntrinsicInst *Inst,
904                                                    Type *ExpectedType) = 0;
905   virtual bool areInlineCompatible(const Function *Caller,
906                                    const Function *Callee) const = 0;
907   virtual unsigned getLoadStoreVecRegBitWidth(unsigned AddrSpace) const = 0;
908   virtual bool isLegalToVectorizeLoad(LoadInst *LI) const = 0;
909   virtual bool isLegalToVectorizeStore(StoreInst *SI) const = 0;
910   virtual bool isLegalToVectorizeLoadChain(unsigned ChainSizeInBytes,
911                                            unsigned Alignment,
912                                            unsigned AddrSpace) const = 0;
913   virtual bool isLegalToVectorizeStoreChain(unsigned ChainSizeInBytes,
914                                             unsigned Alignment,
915                                             unsigned AddrSpace) const = 0;
916   virtual unsigned getLoadVectorFactor(unsigned VF, unsigned LoadSize,
917                                        unsigned ChainSizeInBytes,
918                                        VectorType *VecTy) const = 0;
919   virtual unsigned getStoreVectorFactor(unsigned VF, unsigned StoreSize,
920                                         unsigned ChainSizeInBytes,
921                                         VectorType *VecTy) const = 0;
922   virtual bool useReductionIntrinsic(unsigned Opcode, Type *Ty,
923                                      ReductionFlags) const = 0;
924   virtual bool shouldExpandReduction(const IntrinsicInst *II) const = 0;
925 };
926
927 template <typename T>
928 class TargetTransformInfo::Model final : public TargetTransformInfo::Concept {
929   T Impl;
930
931 public:
932   Model(T Impl) : Impl(std::move(Impl)) {}
933   ~Model() override {}
934
935   const DataLayout &getDataLayout() const override {
936     return Impl.getDataLayout();
937   }
938
939   int getOperationCost(unsigned Opcode, Type *Ty, Type *OpTy) override {
940     return Impl.getOperationCost(Opcode, Ty, OpTy);
941   }
942   int getGEPCost(Type *PointeeType, const Value *Ptr,
943                  ArrayRef<const Value *> Operands) override {
944     return Impl.getGEPCost(PointeeType, Ptr, Operands);
945   }
946   int getCallCost(FunctionType *FTy, int NumArgs) override {
947     return Impl.getCallCost(FTy, NumArgs);
948   }
949   int getCallCost(const Function *F, int NumArgs) override {
950     return Impl.getCallCost(F, NumArgs);
951   }
952   int getCallCost(const Function *F,
953                   ArrayRef<const Value *> Arguments) override {
954     return Impl.getCallCost(F, Arguments);
955   }
956   unsigned getInliningThresholdMultiplier() override {
957     return Impl.getInliningThresholdMultiplier();
958   }
959   int getIntrinsicCost(Intrinsic::ID IID, Type *RetTy,
960                        ArrayRef<Type *> ParamTys) override {
961     return Impl.getIntrinsicCost(IID, RetTy, ParamTys);
962   }
963   int getIntrinsicCost(Intrinsic::ID IID, Type *RetTy,
964                        ArrayRef<const Value *> Arguments) override {
965     return Impl.getIntrinsicCost(IID, RetTy, Arguments);
966   }
967   int getUserCost(const User *U) override { return Impl.getUserCost(U); }
968   bool hasBranchDivergence() override { return Impl.hasBranchDivergence(); }
969   bool isSourceOfDivergence(const Value *V) override {
970     return Impl.isSourceOfDivergence(V);
971   }
972
973   unsigned getFlatAddressSpace() override {
974     return Impl.getFlatAddressSpace();
975   }
976
977   bool isLoweredToCall(const Function *F) override {
978     return Impl.isLoweredToCall(F);
979   }
980   void getUnrollingPreferences(Loop *L, UnrollingPreferences &UP) override {
981     return Impl.getUnrollingPreferences(L, UP);
982   }
983   bool isLegalAddImmediate(int64_t Imm) override {
984     return Impl.isLegalAddImmediate(Imm);
985   }
986   bool isLegalICmpImmediate(int64_t Imm) override {
987     return Impl.isLegalICmpImmediate(Imm);
988   }
989   bool isLegalAddressingMode(Type *Ty, GlobalValue *BaseGV, int64_t BaseOffset,
990                              bool HasBaseReg, int64_t Scale,
991                              unsigned AddrSpace) override {
992     return Impl.isLegalAddressingMode(Ty, BaseGV, BaseOffset, HasBaseReg,
993                                       Scale, AddrSpace);
994   }
995   bool isLegalMaskedStore(Type *DataType) override {
996     return Impl.isLegalMaskedStore(DataType);
997   }
998   bool isLegalMaskedLoad(Type *DataType) override {
999     return Impl.isLegalMaskedLoad(DataType);
1000   }
1001   bool isLegalMaskedScatter(Type *DataType) override {
1002     return Impl.isLegalMaskedScatter(DataType);
1003   }
1004   bool isLegalMaskedGather(Type *DataType) override {
1005     return Impl.isLegalMaskedGather(DataType);
1006   }
1007   bool prefersVectorizedAddressing() override {
1008     return Impl.prefersVectorizedAddressing();
1009   }
1010   int getScalingFactorCost(Type *Ty, GlobalValue *BaseGV, int64_t BaseOffset,
1011                            bool HasBaseReg, int64_t Scale,
1012                            unsigned AddrSpace) override {
1013     return Impl.getScalingFactorCost(Ty, BaseGV, BaseOffset, HasBaseReg,
1014                                      Scale, AddrSpace);
1015   }
1016   bool isFoldableMemAccessOffset(Instruction *I, int64_t Offset) override {
1017     return Impl.isFoldableMemAccessOffset(I, Offset);
1018   }
1019   bool isTruncateFree(Type *Ty1, Type *Ty2) override {
1020     return Impl.isTruncateFree(Ty1, Ty2);
1021   }
1022   bool isProfitableToHoist(Instruction *I) override {
1023     return Impl.isProfitableToHoist(I);
1024   }
1025   bool isTypeLegal(Type *Ty) override { return Impl.isTypeLegal(Ty); }
1026   unsigned getJumpBufAlignment() override { return Impl.getJumpBufAlignment(); }
1027   unsigned getJumpBufSize() override { return Impl.getJumpBufSize(); }
1028   bool shouldBuildLookupTables() override {
1029     return Impl.shouldBuildLookupTables();
1030   }
1031   bool shouldBuildLookupTablesForConstant(Constant *C) override {
1032     return Impl.shouldBuildLookupTablesForConstant(C);
1033   }
1034   unsigned getScalarizationOverhead(Type *Ty, bool Insert,
1035                                     bool Extract) override {
1036     return Impl.getScalarizationOverhead(Ty, Insert, Extract);
1037   }
1038   unsigned getOperandsScalarizationOverhead(ArrayRef<const Value *> Args,
1039                                             unsigned VF) override {
1040     return Impl.getOperandsScalarizationOverhead(Args, VF);
1041   }
1042
1043   bool supportsEfficientVectorElementLoadStore() override {
1044     return Impl.supportsEfficientVectorElementLoadStore();
1045   }
1046
1047   bool enableAggressiveInterleaving(bool LoopHasReductions) override {
1048     return Impl.enableAggressiveInterleaving(LoopHasReductions);
1049   }
1050   bool enableInterleavedAccessVectorization() override {
1051     return Impl.enableInterleavedAccessVectorization();
1052   }
1053   bool isFPVectorizationPotentiallyUnsafe() override {
1054     return Impl.isFPVectorizationPotentiallyUnsafe();
1055   }
1056   bool allowsMisalignedMemoryAccesses(LLVMContext &Context,
1057                                       unsigned BitWidth, unsigned AddressSpace,
1058                                       unsigned Alignment, bool *Fast) override {
1059     return Impl.allowsMisalignedMemoryAccesses(Context, BitWidth, AddressSpace,
1060                                                Alignment, Fast);
1061   }
1062   PopcntSupportKind getPopcntSupport(unsigned IntTyWidthInBit) override {
1063     return Impl.getPopcntSupport(IntTyWidthInBit);
1064   }
1065   bool haveFastSqrt(Type *Ty) override { return Impl.haveFastSqrt(Ty); }
1066
1067   int getFPOpCost(Type *Ty) override { return Impl.getFPOpCost(Ty); }
1068
1069   int getIntImmCodeSizeCost(unsigned Opc, unsigned Idx, const APInt &Imm,
1070                             Type *Ty) override {
1071     return Impl.getIntImmCodeSizeCost(Opc, Idx, Imm, Ty);
1072   }
1073   int getIntImmCost(const APInt &Imm, Type *Ty) override {
1074     return Impl.getIntImmCost(Imm, Ty);
1075   }
1076   int getIntImmCost(unsigned Opc, unsigned Idx, const APInt &Imm,
1077                     Type *Ty) override {
1078     return Impl.getIntImmCost(Opc, Idx, Imm, Ty);
1079   }
1080   int getIntImmCost(Intrinsic::ID IID, unsigned Idx, const APInt &Imm,
1081                     Type *Ty) override {
1082     return Impl.getIntImmCost(IID, Idx, Imm, Ty);
1083   }
1084   unsigned getNumberOfRegisters(bool Vector) override {
1085     return Impl.getNumberOfRegisters(Vector);
1086   }
1087   unsigned getRegisterBitWidth(bool Vector) override {
1088     return Impl.getRegisterBitWidth(Vector);
1089   }
1090   unsigned getMinVectorRegisterBitWidth() override {
1091     return Impl.getMinVectorRegisterBitWidth();
1092   }
1093   bool shouldConsiderAddressTypePromotion(
1094       const Instruction &I, bool &AllowPromotionWithoutCommonHeader) override {
1095     return Impl.shouldConsiderAddressTypePromotion(
1096         I, AllowPromotionWithoutCommonHeader);
1097   }
1098   unsigned getCacheLineSize() override {
1099     return Impl.getCacheLineSize();
1100   }
1101   unsigned getPrefetchDistance() override { return Impl.getPrefetchDistance(); }
1102   unsigned getMinPrefetchStride() override {
1103     return Impl.getMinPrefetchStride();
1104   }
1105   unsigned getMaxPrefetchIterationsAhead() override {
1106     return Impl.getMaxPrefetchIterationsAhead();
1107   }
1108   unsigned getMaxInterleaveFactor(unsigned VF) override {
1109     return Impl.getMaxInterleaveFactor(VF);
1110   }
1111   unsigned getEstimatedNumberOfCaseClusters(const SwitchInst &SI,
1112                                             unsigned &JTSize) override {
1113     return Impl.getEstimatedNumberOfCaseClusters(SI, JTSize);
1114   }
1115   unsigned
1116   getArithmeticInstrCost(unsigned Opcode, Type *Ty, OperandValueKind Opd1Info,
1117                          OperandValueKind Opd2Info,
1118                          OperandValueProperties Opd1PropInfo,
1119                          OperandValueProperties Opd2PropInfo,
1120                          ArrayRef<const Value *> Args) override {
1121     return Impl.getArithmeticInstrCost(Opcode, Ty, Opd1Info, Opd2Info,
1122                                        Opd1PropInfo, Opd2PropInfo, Args);
1123   }
1124   int getShuffleCost(ShuffleKind Kind, Type *Tp, int Index,
1125                      Type *SubTp) override {
1126     return Impl.getShuffleCost(Kind, Tp, Index, SubTp);
1127   }
1128   int getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src,
1129                        const Instruction *I) override {
1130     return Impl.getCastInstrCost(Opcode, Dst, Src, I);
1131   }
1132   int getExtractWithExtendCost(unsigned Opcode, Type *Dst, VectorType *VecTy,
1133                                unsigned Index) override {
1134     return Impl.getExtractWithExtendCost(Opcode, Dst, VecTy, Index);
1135   }
1136   int getCFInstrCost(unsigned Opcode) override {
1137     return Impl.getCFInstrCost(Opcode);
1138   }
1139   int getCmpSelInstrCost(unsigned Opcode, Type *ValTy, Type *CondTy,
1140                          const Instruction *I) override {
1141     return Impl.getCmpSelInstrCost(Opcode, ValTy, CondTy, I);
1142   }
1143   int getVectorInstrCost(unsigned Opcode, Type *Val, unsigned Index) override {
1144     return Impl.getVectorInstrCost(Opcode, Val, Index);
1145   }
1146   int getMemoryOpCost(unsigned Opcode, Type *Src, unsigned Alignment,
1147                       unsigned AddressSpace, const Instruction *I) override {
1148     return Impl.getMemoryOpCost(Opcode, Src, Alignment, AddressSpace, I);
1149   }
1150   int getMaskedMemoryOpCost(unsigned Opcode, Type *Src, unsigned Alignment,
1151                             unsigned AddressSpace) override {
1152     return Impl.getMaskedMemoryOpCost(Opcode, Src, Alignment, AddressSpace);
1153   }
1154   int getGatherScatterOpCost(unsigned Opcode, Type *DataTy,
1155                              Value *Ptr, bool VariableMask,
1156                              unsigned Alignment) override {
1157     return Impl.getGatherScatterOpCost(Opcode, DataTy, Ptr, VariableMask,
1158                                        Alignment);
1159   }
1160   int getInterleavedMemoryOpCost(unsigned Opcode, Type *VecTy, unsigned Factor,
1161                                  ArrayRef<unsigned> Indices, unsigned Alignment,
1162                                  unsigned AddressSpace) override {
1163     return Impl.getInterleavedMemoryOpCost(Opcode, VecTy, Factor, Indices,
1164                                            Alignment, AddressSpace);
1165   }
1166   int getReductionCost(unsigned Opcode, Type *Ty,
1167                        bool IsPairwiseForm) override {
1168     return Impl.getReductionCost(Opcode, Ty, IsPairwiseForm);
1169   }
1170   int getIntrinsicInstrCost(Intrinsic::ID ID, Type *RetTy, ArrayRef<Type *> Tys,
1171                FastMathFlags FMF, unsigned ScalarizationCostPassed) override {
1172     return Impl.getIntrinsicInstrCost(ID, RetTy, Tys, FMF,
1173                                       ScalarizationCostPassed);
1174   }
1175   int getIntrinsicInstrCost(Intrinsic::ID ID, Type *RetTy,
1176        ArrayRef<Value *> Args, FastMathFlags FMF, unsigned VF) override {
1177     return Impl.getIntrinsicInstrCost(ID, RetTy, Args, FMF, VF);
1178   }
1179   int getCallInstrCost(Function *F, Type *RetTy,
1180                        ArrayRef<Type *> Tys) override {
1181     return Impl.getCallInstrCost(F, RetTy, Tys);
1182   }
1183   unsigned getNumberOfParts(Type *Tp) override {
1184     return Impl.getNumberOfParts(Tp);
1185   }
1186   int getAddressComputationCost(Type *Ty, ScalarEvolution *SE,
1187                                 const SCEV *Ptr) override {
1188     return Impl.getAddressComputationCost(Ty, SE, Ptr);
1189   }
1190   unsigned getCostOfKeepingLiveOverCall(ArrayRef<Type *> Tys) override {
1191     return Impl.getCostOfKeepingLiveOverCall(Tys);
1192   }
1193   bool getTgtMemIntrinsic(IntrinsicInst *Inst,
1194                           MemIntrinsicInfo &Info) override {
1195     return Impl.getTgtMemIntrinsic(Inst, Info);
1196   }
1197   Value *getOrCreateResultFromMemIntrinsic(IntrinsicInst *Inst,
1198                                            Type *ExpectedType) override {
1199     return Impl.getOrCreateResultFromMemIntrinsic(Inst, ExpectedType);
1200   }
1201   bool areInlineCompatible(const Function *Caller,
1202                            const Function *Callee) const override {
1203     return Impl.areInlineCompatible(Caller, Callee);
1204   }
1205   unsigned getLoadStoreVecRegBitWidth(unsigned AddrSpace) const override {
1206     return Impl.getLoadStoreVecRegBitWidth(AddrSpace);
1207   }
1208   bool isLegalToVectorizeLoad(LoadInst *LI) const override {
1209     return Impl.isLegalToVectorizeLoad(LI);
1210   }
1211   bool isLegalToVectorizeStore(StoreInst *SI) const override {
1212     return Impl.isLegalToVectorizeStore(SI);
1213   }
1214   bool isLegalToVectorizeLoadChain(unsigned ChainSizeInBytes,
1215                                    unsigned Alignment,
1216                                    unsigned AddrSpace) const override {
1217     return Impl.isLegalToVectorizeLoadChain(ChainSizeInBytes, Alignment,
1218                                             AddrSpace);
1219   }
1220   bool isLegalToVectorizeStoreChain(unsigned ChainSizeInBytes,
1221                                     unsigned Alignment,
1222                                     unsigned AddrSpace) const override {
1223     return Impl.isLegalToVectorizeStoreChain(ChainSizeInBytes, Alignment,
1224                                              AddrSpace);
1225   }
1226   unsigned getLoadVectorFactor(unsigned VF, unsigned LoadSize,
1227                                unsigned ChainSizeInBytes,
1228                                VectorType *VecTy) const override {
1229     return Impl.getLoadVectorFactor(VF, LoadSize, ChainSizeInBytes, VecTy);
1230   }
1231   unsigned getStoreVectorFactor(unsigned VF, unsigned StoreSize,
1232                                 unsigned ChainSizeInBytes,
1233                                 VectorType *VecTy) const override {
1234     return Impl.getStoreVectorFactor(VF, StoreSize, ChainSizeInBytes, VecTy);
1235   }
1236   bool useReductionIntrinsic(unsigned Opcode, Type *Ty,
1237                              ReductionFlags Flags) const override {
1238     return Impl.useReductionIntrinsic(Opcode, Ty, Flags);
1239   }
1240   bool shouldExpandReduction(const IntrinsicInst *II) const override {
1241     return Impl.shouldExpandReduction(II);
1242   }
1243 };
1244
1245 template <typename T>
1246 TargetTransformInfo::TargetTransformInfo(T Impl)
1247     : TTIImpl(new Model<T>(Impl)) {}
1248
1249 /// \brief Analysis pass providing the \c TargetTransformInfo.
1250 ///
1251 /// The core idea of the TargetIRAnalysis is to expose an interface through
1252 /// which LLVM targets can analyze and provide information about the middle
1253 /// end's target-independent IR. This supports use cases such as target-aware
1254 /// cost modeling of IR constructs.
1255 ///
1256 /// This is a function analysis because much of the cost modeling for targets
1257 /// is done in a subtarget specific way and LLVM supports compiling different
1258 /// functions targeting different subtargets in order to support runtime
1259 /// dispatch according to the observed subtarget.
1260 class TargetIRAnalysis : public AnalysisInfoMixin<TargetIRAnalysis> {
1261 public:
1262   typedef TargetTransformInfo Result;
1263
1264   /// \brief Default construct a target IR analysis.
1265   ///
1266   /// This will use the module's datalayout to construct a baseline
1267   /// conservative TTI result.
1268   TargetIRAnalysis();
1269
1270   /// \brief Construct an IR analysis pass around a target-provide callback.
1271   ///
1272   /// The callback will be called with a particular function for which the TTI
1273   /// is needed and must return a TTI object for that function.
1274   TargetIRAnalysis(std::function<Result(const Function &)> TTICallback);
1275
1276   // Value semantics. We spell out the constructors for MSVC.
1277   TargetIRAnalysis(const TargetIRAnalysis &Arg)
1278       : TTICallback(Arg.TTICallback) {}
1279   TargetIRAnalysis(TargetIRAnalysis &&Arg)
1280       : TTICallback(std::move(Arg.TTICallback)) {}
1281   TargetIRAnalysis &operator=(const TargetIRAnalysis &RHS) {
1282     TTICallback = RHS.TTICallback;
1283     return *this;
1284   }
1285   TargetIRAnalysis &operator=(TargetIRAnalysis &&RHS) {
1286     TTICallback = std::move(RHS.TTICallback);
1287     return *this;
1288   }
1289
1290   Result run(const Function &F, FunctionAnalysisManager &);
1291
1292 private:
1293   friend AnalysisInfoMixin<TargetIRAnalysis>;
1294   static AnalysisKey Key;
1295
1296   /// \brief The callback used to produce a result.
1297   ///
1298   /// We use a completely opaque callback so that targets can provide whatever
1299   /// mechanism they desire for constructing the TTI for a given function.
1300   ///
1301   /// FIXME: Should we really use std::function? It's relatively inefficient.
1302   /// It might be possible to arrange for even stateful callbacks to outlive
1303   /// the analysis and thus use a function_ref which would be lighter weight.
1304   /// This may also be less error prone as the callback is likely to reference
1305   /// the external TargetMachine, and that reference needs to never dangle.
1306   std::function<Result(const Function &)> TTICallback;
1307
1308   /// \brief Helper function used as the callback in the default constructor.
1309   static Result getDefaultTTI(const Function &F);
1310 };
1311
1312 /// \brief Wrapper pass for TargetTransformInfo.
1313 ///
1314 /// This pass can be constructed from a TTI object which it stores internally
1315 /// and is queried by passes.
1316 class TargetTransformInfoWrapperPass : public ImmutablePass {
1317   TargetIRAnalysis TIRA;
1318   Optional<TargetTransformInfo> TTI;
1319
1320   virtual void anchor();
1321
1322 public:
1323   static char ID;
1324
1325   /// \brief We must provide a default constructor for the pass but it should
1326   /// never be used.
1327   ///
1328   /// Use the constructor below or call one of the creation routines.
1329   TargetTransformInfoWrapperPass();
1330
1331   explicit TargetTransformInfoWrapperPass(TargetIRAnalysis TIRA);
1332
1333   TargetTransformInfo &getTTI(const Function &F);
1334 };
1335
1336 /// \brief Create an analysis pass wrapper around a TTI object.
1337 ///
1338 /// This analysis pass just holds the TTI instance and makes it available to
1339 /// clients.
1340 ImmutablePass *createTargetTransformInfoWrapperPass(TargetIRAnalysis TIRA);
1341
1342 } // End llvm namespace
1343
1344 #endif