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