OSDN Git Service

ec6815bd11e4afae525d593d33bec46bfc5ea3d4
[android-x86/external-llvm.git] / include / llvm / Analysis / TargetTransformInfo.h
1 //===- TargetTransformInfo.h ------------------------------------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 /// \file
9 /// This pass exposes codegen information to IR-level passes. Every
10 /// transformation that uses codegen information is broken into three parts:
11 /// 1. The IR-level analysis pass.
12 /// 2. The IR-level transformation interface which provides the needed
13 ///    information.
14 /// 3. Codegen-level implementation which uses target-specific hooks.
15 ///
16 /// This file defines #2, which is the interface that IR-level transformations
17 /// use for querying the codegen.
18 ///
19 //===----------------------------------------------------------------------===//
20
21 #ifndef LLVM_ANALYSIS_TARGETTRANSFORMINFO_H
22 #define LLVM_ANALYSIS_TARGETTRANSFORMINFO_H
23
24 #include "llvm/ADT/Optional.h"
25 #include "llvm/IR/Operator.h"
26 #include "llvm/IR/PassManager.h"
27 #include "llvm/Pass.h"
28 #include "llvm/Support/AtomicOrdering.h"
29 #include "llvm/Support/DataTypes.h"
30 #include "llvm/Analysis/LoopInfo.h"
31 #include "llvm/Analysis/ScalarEvolution.h"
32 #include "llvm/IR/Dominators.h"
33 #include "llvm/Analysis/AssumptionCache.h"
34 #include <functional>
35
36 namespace llvm {
37
38 namespace Intrinsic {
39 enum ID : unsigned;
40 }
41
42 class AssumptionCache;
43 class BranchInst;
44 class Function;
45 class GlobalValue;
46 class IntrinsicInst;
47 class LoadInst;
48 class Loop;
49 class SCEV;
50 class ScalarEvolution;
51 class StoreInst;
52 class SwitchInst;
53 class TargetLibraryInfo;
54 class Type;
55 class User;
56 class Value;
57
58 /// Information about a load/store intrinsic defined by the target.
59 struct MemIntrinsicInfo {
60   /// This is the pointer that the intrinsic is loading from or storing to.
61   /// If this is non-null, then analysis/optimization passes can assume that
62   /// this intrinsic is functionally equivalent to a load/store from this
63   /// pointer.
64   Value *PtrVal = nullptr;
65
66   // Ordering for atomic operations.
67   AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
68
69   // Same Id is set by the target for corresponding load/store intrinsics.
70   unsigned short MatchingId = 0;
71
72   bool ReadMem = false;
73   bool WriteMem = false;
74   bool IsVolatile = false;
75
76   bool isUnordered() const {
77     return (Ordering == AtomicOrdering::NotAtomic ||
78             Ordering == AtomicOrdering::Unordered) && !IsVolatile;
79   }
80 };
81
82 /// Attributes of a target dependent hardware loop.
83 struct HardwareLoopInfo {
84   HardwareLoopInfo() = delete;
85   HardwareLoopInfo(Loop *L) : L(L) {}
86   Loop *L = nullptr;
87   BasicBlock *ExitBlock = nullptr;
88   BranchInst *ExitBranch = nullptr;
89   const SCEV *ExitCount = nullptr;
90   IntegerType *CountType = nullptr;
91   Value *LoopDecrement = nullptr; // Decrement the loop counter by this
92                                   // value in every iteration.
93   bool IsNestingLegal = false;    // Can a hardware loop be a parent to
94                                   // another hardware loop?
95   bool CounterInReg = false;      // Should loop counter be updated in
96                                   // the loop via a phi?
97   bool PerformEntryTest = false;  // Generate the intrinsic which also performs
98                                   // icmp ne zero on the loop counter value and
99                                   // produces an i1 to guard the loop entry.
100   bool isHardwareLoopCandidate(ScalarEvolution &SE, LoopInfo &LI,
101                                DominatorTree &DT, bool ForceNestedLoop = false,
102                                bool ForceHardwareLoopPHI = false);
103   bool canAnalyze(LoopInfo &LI);
104 };
105
106 /// This pass provides access to the codegen interfaces that are needed
107 /// for IR-level transformations.
108 class TargetTransformInfo {
109 public:
110   /// Construct a TTI object using a type implementing the \c Concept
111   /// API below.
112   ///
113   /// This is used by targets to construct a TTI wrapping their target-specific
114   /// implementation that encodes appropriate costs for their target.
115   template <typename T> TargetTransformInfo(T Impl);
116
117   /// Construct a baseline TTI object using a minimal implementation of
118   /// the \c Concept API below.
119   ///
120   /// The TTI implementation will reflect the information in the DataLayout
121   /// provided if non-null.
122   explicit TargetTransformInfo(const DataLayout &DL);
123
124   // Provide move semantics.
125   TargetTransformInfo(TargetTransformInfo &&Arg);
126   TargetTransformInfo &operator=(TargetTransformInfo &&RHS);
127
128   // We need to define the destructor out-of-line to define our sub-classes
129   // out-of-line.
130   ~TargetTransformInfo();
131
132   /// Handle the invalidation of this information.
133   ///
134   /// When used as a result of \c TargetIRAnalysis this method will be called
135   /// when the function this was computed for changes. When it returns false,
136   /// the information is preserved across those changes.
137   bool invalidate(Function &, const PreservedAnalyses &,
138                   FunctionAnalysisManager::Invalidator &) {
139     // FIXME: We should probably in some way ensure that the subtarget
140     // information for a function hasn't changed.
141     return false;
142   }
143
144   /// \name Generic Target Information
145   /// @{
146
147   /// The kind of cost model.
148   ///
149   /// There are several different cost models that can be customized by the
150   /// target. The normalization of each cost model may be target specific.
151   enum TargetCostKind {
152     TCK_RecipThroughput, ///< Reciprocal throughput.
153     TCK_Latency,         ///< The latency of instruction.
154     TCK_CodeSize         ///< Instruction code size.
155   };
156
157   /// Query the cost of a specified instruction.
158   ///
159   /// Clients should use this interface to query the cost of an existing
160   /// instruction. The instruction must have a valid parent (basic block).
161   ///
162   /// Note, this method does not cache the cost calculation and it
163   /// can be expensive in some cases.
164   int getInstructionCost(const Instruction *I, enum TargetCostKind kind) const {
165     switch (kind){
166     case TCK_RecipThroughput:
167       return getInstructionThroughput(I);
168
169     case TCK_Latency:
170       return getInstructionLatency(I);
171
172     case TCK_CodeSize:
173       return getUserCost(I);
174     }
175     llvm_unreachable("Unknown instruction cost kind");
176   }
177
178   /// Underlying constants for 'cost' values in this interface.
179   ///
180   /// Many APIs in this interface return a cost. This enum defines the
181   /// fundamental values that should be used to interpret (and produce) those
182   /// costs. The costs are returned as an int rather than a member of this
183   /// enumeration because it is expected that the cost of one IR instruction
184   /// may have a multiplicative factor to it or otherwise won't fit directly
185   /// into the enum. Moreover, it is common to sum or average costs which works
186   /// better as simple integral values. Thus this enum only provides constants.
187   /// Also note that the returned costs are signed integers to make it natural
188   /// to add, subtract, and test with zero (a common boundary condition). It is
189   /// not expected that 2^32 is a realistic cost to be modeling at any point.
190   ///
191   /// Note that these costs should usually reflect the intersection of code-size
192   /// cost and execution cost. A free instruction is typically one that folds
193   /// into another instruction. For example, reg-to-reg moves can often be
194   /// skipped by renaming the registers in the CPU, but they still are encoded
195   /// and thus wouldn't be considered 'free' here.
196   enum TargetCostConstants {
197     TCC_Free = 0,     ///< Expected to fold away in lowering.
198     TCC_Basic = 1,    ///< The cost of a typical 'add' instruction.
199     TCC_Expensive = 4 ///< The cost of a 'div' instruction on x86.
200   };
201
202   /// Estimate the cost of a specific operation when lowered.
203   ///
204   /// Note that this is designed to work on an arbitrary synthetic opcode, and
205   /// thus work for hypothetical queries before an instruction has even been
206   /// formed. However, this does *not* work for GEPs, and must not be called
207   /// for a GEP instruction. Instead, use the dedicated getGEPCost interface as
208   /// analyzing a GEP's cost required more information.
209   ///
210   /// Typically only the result type is required, and the operand type can be
211   /// omitted. However, if the opcode is one of the cast instructions, the
212   /// operand type is required.
213   ///
214   /// The returned cost is defined in terms of \c TargetCostConstants, see its
215   /// comments for a detailed explanation of the cost values.
216   int getOperationCost(unsigned Opcode, Type *Ty, Type *OpTy = nullptr) const;
217
218   /// Estimate the cost of a GEP operation when lowered.
219   ///
220   /// The contract for this function is the same as \c getOperationCost except
221   /// that it supports an interface that provides extra information specific to
222   /// the GEP operation.
223   int getGEPCost(Type *PointeeType, const Value *Ptr,
224                  ArrayRef<const Value *> Operands) const;
225
226   /// Estimate the cost of a EXT operation when lowered.
227   ///
228   /// The contract for this function is the same as \c getOperationCost except
229   /// that it supports an interface that provides extra information specific to
230   /// the EXT operation.
231   int getExtCost(const Instruction *I, const Value *Src) const;
232
233   /// Estimate the cost of a function call when lowered.
234   ///
235   /// The contract for this is the same as \c getOperationCost except that it
236   /// supports an interface that provides extra information specific to call
237   /// instructions.
238   ///
239   /// This is the most basic query for estimating call cost: it only knows the
240   /// function type and (potentially) the number of arguments at the call site.
241   /// The latter is only interesting for varargs function types.
242   int getCallCost(FunctionType *FTy, int NumArgs = -1,
243                   const User *U = nullptr) const;
244
245   /// Estimate the cost of calling a specific function when lowered.
246   ///
247   /// This overload adds the ability to reason about the particular function
248   /// being called in the event it is a library call with special lowering.
249   int getCallCost(const Function *F, int NumArgs = -1,
250                   const User *U = nullptr) const;
251
252   /// Estimate the cost of calling a specific function when lowered.
253   ///
254   /// This overload allows specifying a set of candidate argument values.
255   int getCallCost(const Function *F, ArrayRef<const Value *> Arguments,
256                   const User *U = nullptr) const;
257
258   /// \returns A value by which our inlining threshold should be multiplied.
259   /// This is primarily used to bump up the inlining threshold wholesale on
260   /// targets where calls are unusually expensive.
261   ///
262   /// TODO: This is a rather blunt instrument.  Perhaps altering the costs of
263   /// individual classes of instructions would be better.
264   unsigned getInliningThresholdMultiplier() const;
265
266   /// Estimate the cost of an intrinsic when lowered.
267   ///
268   /// Mirrors the \c getCallCost method but uses an intrinsic identifier.
269   int getIntrinsicCost(Intrinsic::ID IID, Type *RetTy,
270                        ArrayRef<Type *> ParamTys,
271                        const User *U = nullptr) const;
272
273   /// Estimate the cost of an intrinsic when lowered.
274   ///
275   /// Mirrors the \c getCallCost method but uses an intrinsic identifier.
276   int getIntrinsicCost(Intrinsic::ID IID, Type *RetTy,
277                        ArrayRef<const Value *> Arguments,
278                        const User *U = nullptr) const;
279
280   /// \return the expected cost of a memcpy, which could e.g. depend on the
281   /// source/destination type and alignment and the number of bytes copied.
282   int getMemcpyCost(const Instruction *I) const;
283
284   /// \return The estimated number of case clusters when lowering \p 'SI'.
285   /// \p JTSize Set a jump table size only when \p SI is suitable for a jump
286   /// table.
287   unsigned getEstimatedNumberOfCaseClusters(const SwitchInst &SI,
288                                             unsigned &JTSize) const;
289
290   /// Estimate the cost of a given IR user when lowered.
291   ///
292   /// This can estimate the cost of either a ConstantExpr or Instruction when
293   /// lowered. It has two primary advantages over the \c getOperationCost and
294   /// \c getGEPCost above, and one significant disadvantage: it can only be
295   /// used when the IR construct has already been formed.
296   ///
297   /// The advantages are that it can inspect the SSA use graph to reason more
298   /// accurately about the cost. For example, all-constant-GEPs can often be
299   /// folded into a load or other instruction, but if they are used in some
300   /// other context they may not be folded. This routine can distinguish such
301   /// cases.
302   ///
303   /// \p Operands is a list of operands which can be a result of transformations
304   /// of the current operands. The number of the operands on the list must equal
305   /// to the number of the current operands the IR user has. Their order on the
306   /// list must be the same as the order of the current operands the IR user
307   /// has.
308   ///
309   /// The returned cost is defined in terms of \c TargetCostConstants, see its
310   /// comments for a detailed explanation of the cost values.
311   int getUserCost(const User *U, ArrayRef<const Value *> Operands) const;
312
313   /// This is a helper function which calls the two-argument getUserCost
314   /// with \p Operands which are the current operands U has.
315   int getUserCost(const User *U) const {
316     SmallVector<const Value *, 4> Operands(U->value_op_begin(),
317                                            U->value_op_end());
318     return getUserCost(U, Operands);
319   }
320
321   /// Return true if branch divergence exists.
322   ///
323   /// Branch divergence has a significantly negative impact on GPU performance
324   /// when threads in the same wavefront take different paths due to conditional
325   /// branches.
326   bool hasBranchDivergence() const;
327
328   /// Returns whether V is a source of divergence.
329   ///
330   /// This function provides the target-dependent information for
331   /// the target-independent LegacyDivergenceAnalysis. LegacyDivergenceAnalysis first
332   /// builds the dependency graph, and then runs the reachability algorithm
333   /// starting with the sources of divergence.
334   bool isSourceOfDivergence(const Value *V) const;
335
336   // Returns true for the target specific
337   // set of operations which produce uniform result
338   // even taking non-uniform arguments
339   bool isAlwaysUniform(const Value *V) const;
340
341   /// Returns the address space ID for a target's 'flat' address space. Note
342   /// this is not necessarily the same as addrspace(0), which LLVM sometimes
343   /// refers to as the generic address space. The flat address space is a
344   /// generic address space that can be used access multiple segments of memory
345   /// with different address spaces. Access of a memory location through a
346   /// pointer with this address space is expected to be legal but slower
347   /// compared to the same memory location accessed through a pointer with a
348   /// different address space.
349   //
350   /// This is for targets with different pointer representations which can
351   /// be converted with the addrspacecast instruction. If a pointer is converted
352   /// to this address space, optimizations should attempt to replace the access
353   /// with the source address space.
354   ///
355   /// \returns ~0u if the target does not have such a flat address space to
356   /// optimize away.
357   unsigned getFlatAddressSpace() const;
358
359   /// Test whether calls to a function lower to actual program function
360   /// calls.
361   ///
362   /// The idea is to test whether the program is likely to require a 'call'
363   /// instruction or equivalent in order to call the given function.
364   ///
365   /// FIXME: It's not clear that this is a good or useful query API. Client's
366   /// should probably move to simpler cost metrics using the above.
367   /// Alternatively, we could split the cost interface into distinct code-size
368   /// and execution-speed costs. This would allow modelling the core of this
369   /// query more accurately as a call is a single small instruction, but
370   /// incurs significant execution cost.
371   bool isLoweredToCall(const Function *F) const;
372
373   struct LSRCost {
374     /// TODO: Some of these could be merged. Also, a lexical ordering
375     /// isn't always optimal.
376     unsigned Insns;
377     unsigned NumRegs;
378     unsigned AddRecCost;
379     unsigned NumIVMuls;
380     unsigned NumBaseAdds;
381     unsigned ImmCost;
382     unsigned SetupCost;
383     unsigned ScaleCost;
384   };
385
386   /// Parameters that control the generic loop unrolling transformation.
387   struct UnrollingPreferences {
388     /// The cost threshold for the unrolled loop. Should be relative to the
389     /// getUserCost values returned by this API, and the expectation is that
390     /// the unrolled loop's instructions when run through that interface should
391     /// not exceed this cost. However, this is only an estimate. Also, specific
392     /// loops may be unrolled even with a cost above this threshold if deemed
393     /// profitable. Set this to UINT_MAX to disable the loop body cost
394     /// restriction.
395     unsigned Threshold;
396     /// If complete unrolling will reduce the cost of the loop, we will boost
397     /// the Threshold by a certain percent to allow more aggressive complete
398     /// unrolling. This value provides the maximum boost percentage that we
399     /// can apply to Threshold (The value should be no less than 100).
400     /// BoostedThreshold = Threshold * min(RolledCost / UnrolledCost,
401     ///                                    MaxPercentThresholdBoost / 100)
402     /// E.g. if complete unrolling reduces the loop execution time by 50%
403     /// then we boost the threshold by the factor of 2x. If unrolling is not
404     /// expected to reduce the running time, then we do not increase the
405     /// threshold.
406     unsigned MaxPercentThresholdBoost;
407     /// The cost threshold for the unrolled loop when optimizing for size (set
408     /// to UINT_MAX to disable).
409     unsigned OptSizeThreshold;
410     /// The cost threshold for the unrolled loop, like Threshold, but used
411     /// for partial/runtime unrolling (set to UINT_MAX to disable).
412     unsigned PartialThreshold;
413     /// The cost threshold for the unrolled loop when optimizing for size, like
414     /// OptSizeThreshold, but used for partial/runtime unrolling (set to
415     /// UINT_MAX to disable).
416     unsigned PartialOptSizeThreshold;
417     /// A forced unrolling factor (the number of concatenated bodies of the
418     /// original loop in the unrolled loop body). When set to 0, the unrolling
419     /// transformation will select an unrolling factor based on the current cost
420     /// threshold and other factors.
421     unsigned Count;
422     /// A forced peeling factor (the number of bodied of the original loop
423     /// that should be peeled off before the loop body). When set to 0, the
424     /// unrolling transformation will select a peeling factor based on profile
425     /// information and other factors.
426     unsigned PeelCount;
427     /// Default unroll count for loops with run-time trip count.
428     unsigned DefaultUnrollRuntimeCount;
429     // Set the maximum unrolling factor. The unrolling factor may be selected
430     // using the appropriate cost threshold, but may not exceed this number
431     // (set to UINT_MAX to disable). This does not apply in cases where the
432     // loop is being fully unrolled.
433     unsigned MaxCount;
434     /// Set the maximum unrolling factor for full unrolling. Like MaxCount, but
435     /// applies even if full unrolling is selected. This allows a target to fall
436     /// back to Partial unrolling if full unrolling is above FullUnrollMaxCount.
437     unsigned FullUnrollMaxCount;
438     // Represents number of instructions optimized when "back edge"
439     // becomes "fall through" in unrolled loop.
440     // For now we count a conditional branch on a backedge and a comparison
441     // feeding it.
442     unsigned BEInsns;
443     /// Allow partial unrolling (unrolling of loops to expand the size of the
444     /// loop body, not only to eliminate small constant-trip-count loops).
445     bool Partial;
446     /// Allow runtime unrolling (unrolling of loops to expand the size of the
447     /// loop body even when the number of loop iterations is not known at
448     /// compile time).
449     bool Runtime;
450     /// Allow generation of a loop remainder (extra iterations after unroll).
451     bool AllowRemainder;
452     /// Allow emitting expensive instructions (such as divisions) when computing
453     /// the trip count of a loop for runtime unrolling.
454     bool AllowExpensiveTripCount;
455     /// Apply loop unroll on any kind of loop
456     /// (mainly to loops that fail runtime unrolling).
457     bool Force;
458     /// Allow using trip count upper bound to unroll loops.
459     bool UpperBound;
460     /// Allow peeling off loop iterations for loops with low dynamic tripcount.
461     bool AllowPeeling;
462     /// Allow unrolling of all the iterations of the runtime loop remainder.
463     bool UnrollRemainder;
464     /// Allow unroll and jam. Used to enable unroll and jam for the target.
465     bool UnrollAndJam;
466     /// Threshold for unroll and jam, for inner loop size. The 'Threshold'
467     /// value above is used during unroll and jam for the outer loop size.
468     /// This value is used in the same manner to limit the size of the inner
469     /// loop.
470     unsigned UnrollAndJamInnerLoopThreshold;
471   };
472
473   /// Get target-customized preferences for the generic loop unrolling
474   /// transformation. The caller will initialize UP with the current
475   /// target-independent defaults.
476   void getUnrollingPreferences(Loop *L, ScalarEvolution &,
477                                UnrollingPreferences &UP) const;
478
479   /// Query the target whether it would be profitable to convert the given loop
480   /// into a hardware loop.
481   bool isHardwareLoopProfitable(Loop *L, ScalarEvolution &SE,
482                                 AssumptionCache &AC,
483                                 TargetLibraryInfo *LibInfo,
484                                 HardwareLoopInfo &HWLoopInfo) const;
485
486   /// @}
487
488   /// \name Scalar Target Information
489   /// @{
490
491   /// Flags indicating the kind of support for population count.
492   ///
493   /// Compared to the SW implementation, HW support is supposed to
494   /// significantly boost the performance when the population is dense, and it
495   /// may or may not degrade performance if the population is sparse. A HW
496   /// support is considered as "Fast" if it can outperform, or is on a par
497   /// with, SW implementation when the population is sparse; otherwise, it is
498   /// considered as "Slow".
499   enum PopcntSupportKind { PSK_Software, PSK_SlowHardware, PSK_FastHardware };
500
501   /// Return true if the specified immediate is legal add immediate, that
502   /// is the target has add instructions which can add a register with the
503   /// immediate without having to materialize the immediate into a register.
504   bool isLegalAddImmediate(int64_t Imm) const;
505
506   /// Return true if the specified immediate is legal icmp immediate,
507   /// that is the target has icmp instructions which can compare a register
508   /// against the immediate without having to materialize the immediate into a
509   /// register.
510   bool isLegalICmpImmediate(int64_t Imm) const;
511
512   /// Return true if the addressing mode represented by AM is legal for
513   /// this target, for a load/store of the specified type.
514   /// The type may be VoidTy, in which case only return true if the addressing
515   /// mode is legal for a load/store of any legal type.
516   /// If target returns true in LSRWithInstrQueries(), I may be valid.
517   /// TODO: Handle pre/postinc as well.
518   bool isLegalAddressingMode(Type *Ty, GlobalValue *BaseGV, int64_t BaseOffset,
519                              bool HasBaseReg, int64_t Scale,
520                              unsigned AddrSpace = 0,
521                              Instruction *I = nullptr) const;
522
523   /// Return true if LSR cost of C1 is lower than C1.
524   bool isLSRCostLess(TargetTransformInfo::LSRCost &C1,
525                      TargetTransformInfo::LSRCost &C2) const;
526
527   /// Return true if the target can fuse a compare and branch.
528   /// Loop-strength-reduction (LSR) uses that knowledge to adjust its cost
529   /// calculation for the instructions in a loop.
530   bool canMacroFuseCmp() const;
531
532   /// Return true if the target can save a compare for loop count, for example
533   /// hardware loop saves a compare.
534   bool canSaveCmp(Loop *L, BranchInst **BI, ScalarEvolution *SE, LoopInfo *LI,
535                   DominatorTree *DT, AssumptionCache *AC,
536                   TargetLibraryInfo *LibInfo) const;
537
538   /// \return True is LSR should make efforts to create/preserve post-inc
539   /// addressing mode expressions.
540   bool shouldFavorPostInc() const;
541
542   /// Return true if LSR should make efforts to generate indexed addressing
543   /// modes that operate across loop iterations.
544   bool shouldFavorBackedgeIndex(const Loop *L) const;
545
546   /// Return true if the target supports masked load.
547   bool isLegalMaskedStore(Type *DataType) const;
548   /// Return true if the target supports masked store.
549   bool isLegalMaskedLoad(Type *DataType) const;
550
551   /// Return true if the target supports nontemporal store.
552   bool isLegalNTStore(Type *DataType, unsigned Alignment) const;
553   /// Return true if the target supports nontemporal load.
554   bool isLegalNTLoad(Type *DataType, unsigned Alignment) const;
555
556   /// Return true if the target supports masked scatter.
557   bool isLegalMaskedScatter(Type *DataType) const;
558   /// Return true if the target supports masked gather.
559   bool isLegalMaskedGather(Type *DataType) const;
560
561   /// Return true if the target supports masked compress store.
562   bool isLegalMaskedCompressStore(Type *DataType) const;
563   /// Return true if the target supports masked expand load.
564   bool isLegalMaskedExpandLoad(Type *DataType) const;
565
566   /// Return true if the target has a unified operation to calculate division
567   /// and remainder. If so, the additional implicit multiplication and
568   /// subtraction required to calculate a remainder from division are free. This
569   /// can enable more aggressive transformations for division and remainder than
570   /// would typically be allowed using throughput or size cost models.
571   bool hasDivRemOp(Type *DataType, bool IsSigned) const;
572
573   /// Return true if the given instruction (assumed to be a memory access
574   /// instruction) has a volatile variant. If that's the case then we can avoid
575   /// addrspacecast to generic AS for volatile loads/stores. Default
576   /// implementation returns false, which prevents address space inference for
577   /// volatile loads/stores.
578   bool hasVolatileVariant(Instruction *I, unsigned AddrSpace) const;
579
580   /// Return true if target doesn't mind addresses in vectors.
581   bool prefersVectorizedAddressing() const;
582
583   /// Return the cost of the scaling factor used in the addressing
584   /// mode represented by AM for this target, for a load/store
585   /// of the specified type.
586   /// If the AM is supported, the return value must be >= 0.
587   /// If the AM is not supported, it returns a negative value.
588   /// TODO: Handle pre/postinc as well.
589   int getScalingFactorCost(Type *Ty, GlobalValue *BaseGV, int64_t BaseOffset,
590                            bool HasBaseReg, int64_t Scale,
591                            unsigned AddrSpace = 0) const;
592
593   /// Return true if the loop strength reduce pass should make
594   /// Instruction* based TTI queries to isLegalAddressingMode(). This is
595   /// needed on SystemZ, where e.g. a memcpy can only have a 12 bit unsigned
596   /// immediate offset and no index register.
597   bool LSRWithInstrQueries() const;
598
599   /// Return true if it's free to truncate a value of type Ty1 to type
600   /// Ty2. e.g. On x86 it's free to truncate a i32 value in register EAX to i16
601   /// by referencing its sub-register AX.
602   bool isTruncateFree(Type *Ty1, Type *Ty2) const;
603
604   /// Return true if it is profitable to hoist instruction in the
605   /// then/else to before if.
606   bool isProfitableToHoist(Instruction *I) const;
607
608   bool useAA() const;
609
610   /// Return true if this type is legal.
611   bool isTypeLegal(Type *Ty) const;
612
613   /// Returns the target's jmp_buf alignment in bytes.
614   unsigned getJumpBufAlignment() const;
615
616   /// Returns the target's jmp_buf size in bytes.
617   unsigned getJumpBufSize() const;
618
619   /// Return true if switches should be turned into lookup tables for the
620   /// target.
621   bool shouldBuildLookupTables() const;
622
623   /// Return true if switches should be turned into lookup tables
624   /// containing this constant value for the target.
625   bool shouldBuildLookupTablesForConstant(Constant *C) const;
626
627   /// Return true if the input function which is cold at all call sites,
628   ///  should use coldcc calling convention.
629   bool useColdCCForColdCall(Function &F) const;
630
631   unsigned getScalarizationOverhead(Type *Ty, bool Insert, bool Extract) const;
632
633   unsigned getOperandsScalarizationOverhead(ArrayRef<const Value *> Args,
634                                             unsigned VF) const;
635
636   /// If target has efficient vector element load/store instructions, it can
637   /// return true here so that insertion/extraction costs are not added to
638   /// the scalarization cost of a load/store.
639   bool supportsEfficientVectorElementLoadStore() const;
640
641   /// Don't restrict interleaved unrolling to small loops.
642   bool enableAggressiveInterleaving(bool LoopHasReductions) const;
643
644   /// Returns options for expansion of memcmp. IsZeroCmp is
645   // true if this is the expansion of memcmp(p1, p2, s) == 0.
646   struct MemCmpExpansionOptions {
647     // Return true if memcmp expansion is enabled.
648     operator bool() const { return MaxNumLoads > 0; }
649
650     // Maximum number of load operations.
651     unsigned MaxNumLoads = 0;
652
653     // The list of available load sizes (in bytes), sorted in decreasing order.
654     SmallVector<unsigned, 8> LoadSizes;
655
656     // For memcmp expansion when the memcmp result is only compared equal or
657     // not-equal to 0, allow up to this number of load pairs per block. As an
658     // example, this may allow 'memcmp(a, b, 3) == 0' in a single block:
659     //   a0 = load2bytes &a[0]
660     //   b0 = load2bytes &b[0]
661     //   a2 = load1byte  &a[2]
662     //   b2 = load1byte  &b[2]
663     //   r  = cmp eq (a0 ^ b0 | a2 ^ b2), 0
664     unsigned NumLoadsPerBlock = 1;
665
666     // Set to true to allow overlapping loads. For example, 7-byte compares can
667     // be done with two 4-byte compares instead of 4+2+1-byte compares. This
668     // requires all loads in LoadSizes to be doable in an unaligned way.
669     bool AllowOverlappingLoads = false;
670   };
671   MemCmpExpansionOptions enableMemCmpExpansion(bool OptSize,
672                                                bool IsZeroCmp) const;
673
674   /// Enable matching of interleaved access groups.
675   bool enableInterleavedAccessVectorization() const;
676
677   /// Enable matching of interleaved access groups that contain predicated
678   /// accesses or gaps and therefore vectorized using masked
679   /// vector loads/stores.
680   bool enableMaskedInterleavedAccessVectorization() const;
681
682   /// Indicate that it is potentially unsafe to automatically vectorize
683   /// floating-point operations because the semantics of vector and scalar
684   /// floating-point semantics may differ. For example, ARM NEON v7 SIMD math
685   /// does not support IEEE-754 denormal numbers, while depending on the
686   /// platform, scalar floating-point math does.
687   /// This applies to floating-point math operations and calls, not memory
688   /// operations, shuffles, or casts.
689   bool isFPVectorizationPotentiallyUnsafe() const;
690
691   /// Determine if the target supports unaligned memory accesses.
692   bool allowsMisalignedMemoryAccesses(LLVMContext &Context,
693                                       unsigned BitWidth, unsigned AddressSpace = 0,
694                                       unsigned Alignment = 1,
695                                       bool *Fast = nullptr) const;
696
697   /// Return hardware support for population count.
698   PopcntSupportKind getPopcntSupport(unsigned IntTyWidthInBit) const;
699
700   /// Return true if the hardware has a fast square-root instruction.
701   bool haveFastSqrt(Type *Ty) const;
702
703   /// Return true if it is faster to check if a floating-point value is NaN
704   /// (or not-NaN) versus a comparison against a constant FP zero value.
705   /// Targets should override this if materializing a 0.0 for comparison is
706   /// generally as cheap as checking for ordered/unordered.
707   bool isFCmpOrdCheaperThanFCmpZero(Type *Ty) const;
708
709   /// Return the expected cost of supporting the floating point operation
710   /// of the specified type.
711   int getFPOpCost(Type *Ty) const;
712
713   /// Return the expected cost of materializing for the given integer
714   /// immediate of the specified type.
715   int getIntImmCost(const APInt &Imm, Type *Ty) const;
716
717   /// Return the expected cost of materialization for the given integer
718   /// immediate of the specified type for a given instruction. The cost can be
719   /// zero if the immediate can be folded into the specified instruction.
720   int getIntImmCost(unsigned Opc, unsigned Idx, const APInt &Imm,
721                     Type *Ty) const;
722   int getIntImmCost(Intrinsic::ID IID, unsigned Idx, const APInt &Imm,
723                     Type *Ty) const;
724
725   /// Return the expected cost for the given integer when optimising
726   /// for size. This is different than the other integer immediate cost
727   /// functions in that it is subtarget agnostic. This is useful when you e.g.
728   /// target one ISA such as Aarch32 but smaller encodings could be possible
729   /// with another such as Thumb. This return value is used as a penalty when
730   /// the total costs for a constant is calculated (the bigger the cost, the
731   /// more beneficial constant hoisting is).
732   int getIntImmCodeSizeCost(unsigned Opc, unsigned Idx, const APInt &Imm,
733                             Type *Ty) const;
734   /// @}
735
736   /// \name Vector Target Information
737   /// @{
738
739   /// The various kinds of shuffle patterns for vector queries.
740   enum ShuffleKind {
741     SK_Broadcast,       ///< Broadcast element 0 to all other elements.
742     SK_Reverse,         ///< Reverse the order of the vector.
743     SK_Select,          ///< Selects elements from the corresponding lane of
744                         ///< either source operand. This is equivalent to a
745                         ///< vector select with a constant condition operand.
746     SK_Transpose,       ///< Transpose two vectors.
747     SK_InsertSubvector, ///< InsertSubvector. Index indicates start offset.
748     SK_ExtractSubvector,///< ExtractSubvector Index indicates start offset.
749     SK_PermuteTwoSrc,   ///< Merge elements from two source vectors into one
750                         ///< with any shuffle mask.
751     SK_PermuteSingleSrc ///< Shuffle elements of single source vector with any
752                         ///< shuffle mask.
753   };
754
755   /// Additional information about an operand's possible values.
756   enum OperandValueKind {
757     OK_AnyValue,               // Operand can have any value.
758     OK_UniformValue,           // Operand is uniform (splat of a value).
759     OK_UniformConstantValue,   // Operand is uniform constant.
760     OK_NonUniformConstantValue // Operand is a non uniform constant value.
761   };
762
763   /// Additional properties of an operand's values.
764   enum OperandValueProperties { OP_None = 0, OP_PowerOf2 = 1 };
765
766   /// \return The number of scalar or vector registers that the target has.
767   /// If 'Vectors' is true, it returns the number of vector registers. If it is
768   /// set to false, it returns the number of scalar registers.
769   unsigned getNumberOfRegisters(bool Vector) const;
770
771   /// \return The width of the largest scalar or vector register type.
772   unsigned getRegisterBitWidth(bool Vector) const;
773
774   /// \return The width of the smallest vector register type.
775   unsigned getMinVectorRegisterBitWidth() const;
776
777   /// \return True if the vectorization factor should be chosen to
778   /// make the vector of the smallest element type match the size of a
779   /// vector register. For wider element types, this could result in
780   /// creating vectors that span multiple vector registers.
781   /// If false, the vectorization factor will be chosen based on the
782   /// size of the widest element type.
783   bool shouldMaximizeVectorBandwidth(bool OptSize) const;
784
785   /// \return The minimum vectorization factor for types of given element
786   /// bit width, or 0 if there is no minimum VF. The returned value only
787   /// applies when shouldMaximizeVectorBandwidth returns true.
788   unsigned getMinimumVF(unsigned ElemWidth) const;
789
790   /// \return True if it should be considered for address type promotion.
791   /// \p AllowPromotionWithoutCommonHeader Set true if promoting \p I is
792   /// profitable without finding other extensions fed by the same input.
793   bool shouldConsiderAddressTypePromotion(
794       const Instruction &I, bool &AllowPromotionWithoutCommonHeader) const;
795
796   /// \return The size of a cache line in bytes.
797   unsigned getCacheLineSize() const;
798
799   /// The possible cache levels
800   enum class CacheLevel {
801     L1D,   // The L1 data cache
802     L2D,   // The L2 data cache
803
804     // We currently do not model L3 caches, as their sizes differ widely between
805     // microarchitectures. Also, we currently do not have a use for L3 cache
806     // size modeling yet.
807   };
808
809   /// \return The size of the cache level in bytes, if available.
810   llvm::Optional<unsigned> getCacheSize(CacheLevel Level) const;
811
812   /// \return The associativity of the cache level, if available.
813   llvm::Optional<unsigned> getCacheAssociativity(CacheLevel Level) const;
814
815   /// \return How much before a load we should place the prefetch
816   /// instruction.  This is currently measured in number of
817   /// instructions.
818   unsigned getPrefetchDistance() const;
819
820   /// \return Some HW prefetchers can handle accesses up to a certain
821   /// constant stride.  This is the minimum stride in bytes where it
822   /// makes sense to start adding SW prefetches.  The default is 1,
823   /// i.e. prefetch with any stride.
824   unsigned getMinPrefetchStride() const;
825
826   /// \return The maximum number of iterations to prefetch ahead.  If
827   /// the required number of iterations is more than this number, no
828   /// prefetching is performed.
829   unsigned getMaxPrefetchIterationsAhead() const;
830
831   /// \return The maximum interleave factor that any transform should try to
832   /// perform for this target. This number depends on the level of parallelism
833   /// and the number of execution units in the CPU.
834   unsigned getMaxInterleaveFactor(unsigned VF) const;
835
836   /// Collect properties of V used in cost analysis, e.g. OP_PowerOf2.
837   static OperandValueKind getOperandInfo(Value *V,
838                                          OperandValueProperties &OpProps);
839
840   /// This is an approximation of reciprocal throughput of a math/logic op.
841   /// A higher cost indicates less expected throughput.
842   /// From Agner Fog's guides, reciprocal throughput is "the average number of
843   /// clock cycles per instruction when the instructions are not part of a
844   /// limiting dependency chain."
845   /// Therefore, costs should be scaled to account for multiple execution units
846   /// on the target that can process this type of instruction. For example, if
847   /// there are 5 scalar integer units and 2 vector integer units that can
848   /// calculate an 'add' in a single cycle, this model should indicate that the
849   /// cost of the vector add instruction is 2.5 times the cost of the scalar
850   /// add instruction.
851   /// \p Args is an optional argument which holds the instruction operands
852   /// values so the TTI can analyze those values searching for special
853   /// cases or optimizations based on those values.
854   int getArithmeticInstrCost(
855       unsigned Opcode, Type *Ty, OperandValueKind Opd1Info = OK_AnyValue,
856       OperandValueKind Opd2Info = OK_AnyValue,
857       OperandValueProperties Opd1PropInfo = OP_None,
858       OperandValueProperties Opd2PropInfo = OP_None,
859       ArrayRef<const Value *> Args = ArrayRef<const Value *>()) const;
860
861   /// \return The cost of a shuffle instruction of kind Kind and of type Tp.
862   /// The index and subtype parameters are used by the subvector insertion and
863   /// extraction shuffle kinds to show the insert/extract point and the type of
864   /// the subvector being inserted/extracted.
865   /// NOTE: For subvector extractions Tp represents the source type.
866   int getShuffleCost(ShuffleKind Kind, Type *Tp, int Index = 0,
867                      Type *SubTp = nullptr) const;
868
869   /// \return The expected cost of cast instructions, such as bitcast, trunc,
870   /// zext, etc. If there is an existing instruction that holds Opcode, it
871   /// may be passed in the 'I' parameter.
872   int getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src,
873                        const Instruction *I = nullptr) const;
874
875   /// \return The expected cost of a sign- or zero-extended vector extract. Use
876   /// -1 to indicate that there is no information about the index value.
877   int getExtractWithExtendCost(unsigned Opcode, Type *Dst, VectorType *VecTy,
878                                unsigned Index = -1) const;
879
880   /// \return The expected cost of control-flow related instructions such as
881   /// Phi, Ret, Br.
882   int getCFInstrCost(unsigned Opcode) const;
883
884   /// \returns The expected cost of compare and select instructions. If there
885   /// is an existing instruction that holds Opcode, it may be passed in the
886   /// 'I' parameter.
887   int getCmpSelInstrCost(unsigned Opcode, Type *ValTy,
888                  Type *CondTy = nullptr, const Instruction *I = nullptr) const;
889
890   /// \return The expected cost of vector Insert and Extract.
891   /// Use -1 to indicate that there is no information on the index value.
892   int getVectorInstrCost(unsigned Opcode, Type *Val, unsigned Index = -1) const;
893
894   /// \return The cost of Load and Store instructions.
895   int getMemoryOpCost(unsigned Opcode, Type *Src, unsigned Alignment,
896                       unsigned AddressSpace, const Instruction *I = nullptr) const;
897
898   /// \return The cost of masked Load and Store instructions.
899   int getMaskedMemoryOpCost(unsigned Opcode, Type *Src, unsigned Alignment,
900                             unsigned AddressSpace) const;
901
902   /// \return The cost of Gather or Scatter operation
903   /// \p Opcode - is a type of memory access Load or Store
904   /// \p DataTy - a vector type of the data to be loaded or stored
905   /// \p Ptr - pointer [or vector of pointers] - address[es] in memory
906   /// \p VariableMask - true when the memory access is predicated with a mask
907   ///                   that is not a compile-time constant
908   /// \p Alignment - alignment of single element
909   int getGatherScatterOpCost(unsigned Opcode, Type *DataTy, Value *Ptr,
910                              bool VariableMask, unsigned Alignment) const;
911
912   /// \return The cost of the interleaved memory operation.
913   /// \p Opcode is the memory operation code
914   /// \p VecTy is the vector type of the interleaved access.
915   /// \p Factor is the interleave factor
916   /// \p Indices is the indices for interleaved load members (as interleaved
917   ///    load allows gaps)
918   /// \p Alignment is the alignment of the memory operation
919   /// \p AddressSpace is address space of the pointer.
920   /// \p UseMaskForCond indicates if the memory access is predicated.
921   /// \p UseMaskForGaps indicates if gaps should be masked.
922   int getInterleavedMemoryOpCost(unsigned Opcode, Type *VecTy, unsigned Factor,
923                                  ArrayRef<unsigned> Indices, unsigned Alignment,
924                                  unsigned AddressSpace,
925                                  bool UseMaskForCond = false,
926                                  bool UseMaskForGaps = false) const;
927
928   /// Calculate the cost of performing a vector reduction.
929   ///
930   /// This is the cost of reducing the vector value of type \p Ty to a scalar
931   /// value using the operation denoted by \p Opcode. The form of the reduction
932   /// can either be a pairwise reduction or a reduction that splits the vector
933   /// at every reduction level.
934   ///
935   /// Pairwise:
936   ///  (v0, v1, v2, v3)
937   ///  ((v0+v1), (v2+v3), undef, undef)
938   /// Split:
939   ///  (v0, v1, v2, v3)
940   ///  ((v0+v2), (v1+v3), undef, undef)
941   int getArithmeticReductionCost(unsigned Opcode, Type *Ty,
942                                  bool IsPairwiseForm) const;
943   int getMinMaxReductionCost(Type *Ty, Type *CondTy, bool IsPairwiseForm,
944                              bool IsUnsigned) const;
945
946   /// \returns The cost of Intrinsic instructions. Analyses the real arguments.
947   /// Three cases are handled: 1. scalar instruction 2. vector instruction
948   /// 3. scalar instruction which is to be vectorized with VF.
949   int getIntrinsicInstrCost(Intrinsic::ID ID, Type *RetTy,
950                             ArrayRef<Value *> Args, FastMathFlags FMF,
951                             unsigned VF = 1) const;
952
953   /// \returns The cost of Intrinsic instructions. Types analysis only.
954   /// If ScalarizationCostPassed is UINT_MAX, the cost of scalarizing the
955   /// arguments and the return value will be computed based on types.
956   int getIntrinsicInstrCost(Intrinsic::ID ID, Type *RetTy,
957                             ArrayRef<Type *> Tys, FastMathFlags FMF,
958                             unsigned ScalarizationCostPassed = UINT_MAX) const;
959
960   /// \returns The cost of Call instructions.
961   int getCallInstrCost(Function *F, Type *RetTy, ArrayRef<Type *> Tys) const;
962
963   /// \returns The number of pieces into which the provided type must be
964   /// split during legalization. Zero is returned when the answer is unknown.
965   unsigned getNumberOfParts(Type *Tp) const;
966
967   /// \returns The cost of the address computation. For most targets this can be
968   /// merged into the instruction indexing mode. Some targets might want to
969   /// distinguish between address computation for memory operations on vector
970   /// types and scalar types. Such targets should override this function.
971   /// The 'SE' parameter holds pointer for the scalar evolution object which
972   /// is used in order to get the Ptr step value in case of constant stride.
973   /// The 'Ptr' parameter holds SCEV of the access pointer.
974   int getAddressComputationCost(Type *Ty, ScalarEvolution *SE = nullptr,
975                                 const SCEV *Ptr = nullptr) const;
976
977   /// \returns The cost, if any, of keeping values of the given types alive
978   /// over a callsite.
979   ///
980   /// Some types may require the use of register classes that do not have
981   /// any callee-saved registers, so would require a spill and fill.
982   unsigned getCostOfKeepingLiveOverCall(ArrayRef<Type *> Tys) const;
983
984   /// \returns True if the intrinsic is a supported memory intrinsic.  Info
985   /// will contain additional information - whether the intrinsic may write
986   /// or read to memory, volatility and the pointer.  Info is undefined
987   /// if false is returned.
988   bool getTgtMemIntrinsic(IntrinsicInst *Inst, MemIntrinsicInfo &Info) const;
989
990   /// \returns The maximum element size, in bytes, for an element
991   /// unordered-atomic memory intrinsic.
992   unsigned getAtomicMemIntrinsicMaxElementSize() const;
993
994   /// \returns A value which is the result of the given memory intrinsic.  New
995   /// instructions may be created to extract the result from the given intrinsic
996   /// memory operation.  Returns nullptr if the target cannot create a result
997   /// from the given intrinsic.
998   Value *getOrCreateResultFromMemIntrinsic(IntrinsicInst *Inst,
999                                            Type *ExpectedType) const;
1000
1001   /// \returns The type to use in a loop expansion of a memcpy call.
1002   Type *getMemcpyLoopLoweringType(LLVMContext &Context, Value *Length,
1003                                   unsigned SrcAlign, unsigned DestAlign) const;
1004
1005   /// \param[out] OpsOut The operand types to copy RemainingBytes of memory.
1006   /// \param RemainingBytes The number of bytes to copy.
1007   ///
1008   /// Calculates the operand types to use when copying \p RemainingBytes of
1009   /// memory, where source and destination alignments are \p SrcAlign and
1010   /// \p DestAlign respectively.
1011   void getMemcpyLoopResidualLoweringType(SmallVectorImpl<Type *> &OpsOut,
1012                                          LLVMContext &Context,
1013                                          unsigned RemainingBytes,
1014                                          unsigned SrcAlign,
1015                                          unsigned DestAlign) const;
1016
1017   /// \returns True if the two functions have compatible attributes for inlining
1018   /// purposes.
1019   bool areInlineCompatible(const Function *Caller,
1020                            const Function *Callee) const;
1021
1022   /// \returns True if the caller and callee agree on how \p Args will be passed
1023   /// to the callee.
1024   /// \param[out] Args The list of compatible arguments.  The implementation may
1025   /// filter out any incompatible args from this list.
1026   bool areFunctionArgsABICompatible(const Function *Caller,
1027                                     const Function *Callee,
1028                                     SmallPtrSetImpl<Argument *> &Args) const;
1029
1030   /// The type of load/store indexing.
1031   enum MemIndexedMode {
1032     MIM_Unindexed,  ///< No indexing.
1033     MIM_PreInc,     ///< Pre-incrementing.
1034     MIM_PreDec,     ///< Pre-decrementing.
1035     MIM_PostInc,    ///< Post-incrementing.
1036     MIM_PostDec     ///< Post-decrementing.
1037   };
1038
1039   /// \returns True if the specified indexed load for the given type is legal.
1040   bool isIndexedLoadLegal(enum MemIndexedMode Mode, Type *Ty) const;
1041
1042   /// \returns True if the specified indexed store for the given type is legal.
1043   bool isIndexedStoreLegal(enum MemIndexedMode Mode, Type *Ty) const;
1044
1045   /// \returns The bitwidth of the largest vector type that should be used to
1046   /// load/store in the given address space.
1047   unsigned getLoadStoreVecRegBitWidth(unsigned AddrSpace) const;
1048
1049   /// \returns True if the load instruction is legal to vectorize.
1050   bool isLegalToVectorizeLoad(LoadInst *LI) const;
1051
1052   /// \returns True if the store instruction is legal to vectorize.
1053   bool isLegalToVectorizeStore(StoreInst *SI) const;
1054
1055   /// \returns True if it is legal to vectorize the given load chain.
1056   bool isLegalToVectorizeLoadChain(unsigned ChainSizeInBytes,
1057                                    unsigned Alignment,
1058                                    unsigned AddrSpace) const;
1059
1060   /// \returns True if it is legal to vectorize the given store chain.
1061   bool isLegalToVectorizeStoreChain(unsigned ChainSizeInBytes,
1062                                     unsigned Alignment,
1063                                     unsigned AddrSpace) const;
1064
1065   /// \returns The new vector factor value if the target doesn't support \p
1066   /// SizeInBytes loads or has a better vector factor.
1067   unsigned getLoadVectorFactor(unsigned VF, unsigned LoadSize,
1068                                unsigned ChainSizeInBytes,
1069                                VectorType *VecTy) const;
1070
1071   /// \returns The new vector factor value if the target doesn't support \p
1072   /// SizeInBytes stores or has a better vector factor.
1073   unsigned getStoreVectorFactor(unsigned VF, unsigned StoreSize,
1074                                 unsigned ChainSizeInBytes,
1075                                 VectorType *VecTy) const;
1076
1077   /// Flags describing the kind of vector reduction.
1078   struct ReductionFlags {
1079     ReductionFlags() : IsMaxOp(false), IsSigned(false), NoNaN(false) {}
1080     bool IsMaxOp;  ///< If the op a min/max kind, true if it's a max operation.
1081     bool IsSigned; ///< Whether the operation is a signed int reduction.
1082     bool NoNaN;    ///< If op is an fp min/max, whether NaNs may be present.
1083   };
1084
1085   /// \returns True if the target wants to handle the given reduction idiom in
1086   /// the intrinsics form instead of the shuffle form.
1087   bool useReductionIntrinsic(unsigned Opcode, Type *Ty,
1088                              ReductionFlags Flags) const;
1089
1090   /// \returns True if the target wants to expand the given reduction intrinsic
1091   /// into a shuffle sequence.
1092   bool shouldExpandReduction(const IntrinsicInst *II) const;
1093
1094   /// \returns the size cost of rematerializing a GlobalValue address relative
1095   /// to a stack reload.
1096   unsigned getGISelRematGlobalCost() const;
1097
1098   /// @}
1099
1100 private:
1101   /// Estimate the latency of specified instruction.
1102   /// Returns 1 as the default value.
1103   int getInstructionLatency(const Instruction *I) const;
1104
1105   /// Returns the expected throughput cost of the instruction.
1106   /// Returns -1 if the cost is unknown.
1107   int getInstructionThroughput(const Instruction *I) const;
1108
1109   /// The abstract base class used to type erase specific TTI
1110   /// implementations.
1111   class Concept;
1112
1113   /// The template model for the base class which wraps a concrete
1114   /// implementation in a type erased interface.
1115   template <typename T> class Model;
1116
1117   std::unique_ptr<Concept> TTIImpl;
1118 };
1119
1120 class TargetTransformInfo::Concept {
1121 public:
1122   virtual ~Concept() = 0;
1123   virtual const DataLayout &getDataLayout() const = 0;
1124   virtual int getOperationCost(unsigned Opcode, Type *Ty, Type *OpTy) = 0;
1125   virtual int getGEPCost(Type *PointeeType, const Value *Ptr,
1126                          ArrayRef<const Value *> Operands) = 0;
1127   virtual int getExtCost(const Instruction *I, const Value *Src) = 0;
1128   virtual int getCallCost(FunctionType *FTy, int NumArgs, const User *U) = 0;
1129   virtual int getCallCost(const Function *F, int NumArgs, const User *U) = 0;
1130   virtual int getCallCost(const Function *F,
1131                           ArrayRef<const Value *> Arguments, const User *U) = 0;
1132   virtual unsigned getInliningThresholdMultiplier() = 0;
1133   virtual int getIntrinsicCost(Intrinsic::ID IID, Type *RetTy,
1134                                ArrayRef<Type *> ParamTys, const User *U) = 0;
1135   virtual int getIntrinsicCost(Intrinsic::ID IID, Type *RetTy,
1136                                ArrayRef<const Value *> Arguments,
1137                                const User *U) = 0;
1138   virtual int getMemcpyCost(const Instruction *I) = 0;
1139   virtual unsigned getEstimatedNumberOfCaseClusters(const SwitchInst &SI,
1140                                                     unsigned &JTSize) = 0;
1141   virtual int
1142   getUserCost(const User *U, ArrayRef<const Value *> Operands) = 0;
1143   virtual bool hasBranchDivergence() = 0;
1144   virtual bool isSourceOfDivergence(const Value *V) = 0;
1145   virtual bool isAlwaysUniform(const Value *V) = 0;
1146   virtual unsigned getFlatAddressSpace() = 0;
1147   virtual bool isLoweredToCall(const Function *F) = 0;
1148   virtual void getUnrollingPreferences(Loop *L, ScalarEvolution &,
1149                                        UnrollingPreferences &UP) = 0;
1150   virtual bool isHardwareLoopProfitable(Loop *L, ScalarEvolution &SE,
1151                                         AssumptionCache &AC,
1152                                         TargetLibraryInfo *LibInfo,
1153                                         HardwareLoopInfo &HWLoopInfo) = 0;
1154   virtual bool isLegalAddImmediate(int64_t Imm) = 0;
1155   virtual bool isLegalICmpImmediate(int64_t Imm) = 0;
1156   virtual bool isLegalAddressingMode(Type *Ty, GlobalValue *BaseGV,
1157                                      int64_t BaseOffset, bool HasBaseReg,
1158                                      int64_t Scale,
1159                                      unsigned AddrSpace,
1160                                      Instruction *I) = 0;
1161   virtual bool isLSRCostLess(TargetTransformInfo::LSRCost &C1,
1162                              TargetTransformInfo::LSRCost &C2) = 0;
1163   virtual bool canMacroFuseCmp() = 0;
1164   virtual bool canSaveCmp(Loop *L, BranchInst **BI, ScalarEvolution *SE,
1165                           LoopInfo *LI, DominatorTree *DT, AssumptionCache *AC,
1166                           TargetLibraryInfo *LibInfo) = 0;
1167   virtual bool shouldFavorPostInc() const = 0;
1168   virtual bool shouldFavorBackedgeIndex(const Loop *L) const = 0;
1169   virtual bool isLegalMaskedStore(Type *DataType) = 0;
1170   virtual bool isLegalMaskedLoad(Type *DataType) = 0;
1171   virtual bool isLegalNTStore(Type *DataType, unsigned Alignment) = 0;
1172   virtual bool isLegalNTLoad(Type *DataType, unsigned Alignment) = 0;
1173   virtual bool isLegalMaskedScatter(Type *DataType) = 0;
1174   virtual bool isLegalMaskedGather(Type *DataType) = 0;
1175   virtual bool isLegalMaskedCompressStore(Type *DataType) = 0;
1176   virtual bool isLegalMaskedExpandLoad(Type *DataType) = 0;
1177   virtual bool hasDivRemOp(Type *DataType, bool IsSigned) = 0;
1178   virtual bool hasVolatileVariant(Instruction *I, unsigned AddrSpace) = 0;
1179   virtual bool prefersVectorizedAddressing() = 0;
1180   virtual int getScalingFactorCost(Type *Ty, GlobalValue *BaseGV,
1181                                    int64_t BaseOffset, bool HasBaseReg,
1182                                    int64_t Scale, unsigned AddrSpace) = 0;
1183   virtual bool LSRWithInstrQueries() = 0;
1184   virtual bool isTruncateFree(Type *Ty1, Type *Ty2) = 0;
1185   virtual bool isProfitableToHoist(Instruction *I) = 0;
1186   virtual bool useAA() = 0;
1187   virtual bool isTypeLegal(Type *Ty) = 0;
1188   virtual unsigned getJumpBufAlignment() = 0;
1189   virtual unsigned getJumpBufSize() = 0;
1190   virtual bool shouldBuildLookupTables() = 0;
1191   virtual bool shouldBuildLookupTablesForConstant(Constant *C) = 0;
1192   virtual bool useColdCCForColdCall(Function &F) = 0;
1193   virtual unsigned
1194   getScalarizationOverhead(Type *Ty, bool Insert, bool Extract) = 0;
1195   virtual unsigned getOperandsScalarizationOverhead(ArrayRef<const Value *> Args,
1196                                                     unsigned VF) = 0;
1197   virtual bool supportsEfficientVectorElementLoadStore() = 0;
1198   virtual bool enableAggressiveInterleaving(bool LoopHasReductions) = 0;
1199   virtual MemCmpExpansionOptions
1200   enableMemCmpExpansion(bool OptSize, bool IsZeroCmp) const = 0;
1201   virtual bool enableInterleavedAccessVectorization() = 0;
1202   virtual bool enableMaskedInterleavedAccessVectorization() = 0;
1203   virtual bool isFPVectorizationPotentiallyUnsafe() = 0;
1204   virtual bool allowsMisalignedMemoryAccesses(LLVMContext &Context,
1205                                               unsigned BitWidth,
1206                                               unsigned AddressSpace,
1207                                               unsigned Alignment,
1208                                               bool *Fast) = 0;
1209   virtual PopcntSupportKind getPopcntSupport(unsigned IntTyWidthInBit) = 0;
1210   virtual bool haveFastSqrt(Type *Ty) = 0;
1211   virtual bool isFCmpOrdCheaperThanFCmpZero(Type *Ty) = 0;
1212   virtual int getFPOpCost(Type *Ty) = 0;
1213   virtual int getIntImmCodeSizeCost(unsigned Opc, unsigned Idx, const APInt &Imm,
1214                                     Type *Ty) = 0;
1215   virtual int getIntImmCost(const APInt &Imm, Type *Ty) = 0;
1216   virtual int getIntImmCost(unsigned Opc, unsigned Idx, const APInt &Imm,
1217                             Type *Ty) = 0;
1218   virtual int getIntImmCost(Intrinsic::ID IID, unsigned Idx, const APInt &Imm,
1219                             Type *Ty) = 0;
1220   virtual unsigned getNumberOfRegisters(bool Vector) = 0;
1221   virtual unsigned getRegisterBitWidth(bool Vector) const = 0;
1222   virtual unsigned getMinVectorRegisterBitWidth() = 0;
1223   virtual bool shouldMaximizeVectorBandwidth(bool OptSize) const = 0;
1224   virtual unsigned getMinimumVF(unsigned ElemWidth) const = 0;
1225   virtual bool shouldConsiderAddressTypePromotion(
1226       const Instruction &I, bool &AllowPromotionWithoutCommonHeader) = 0;
1227   virtual unsigned getCacheLineSize() const = 0;
1228   virtual llvm::Optional<unsigned> getCacheSize(CacheLevel Level) const = 0;
1229   virtual llvm::Optional<unsigned> getCacheAssociativity(CacheLevel Level) const = 0;
1230
1231   /// \return How much before a load we should place the prefetch
1232   /// instruction.  This is currently measured in number of
1233   /// instructions.
1234   virtual unsigned getPrefetchDistance() const = 0;
1235
1236   /// \return Some HW prefetchers can handle accesses up to a certain
1237   /// constant stride.  This is the minimum stride in bytes where it
1238   /// makes sense to start adding SW prefetches.  The default is 1,
1239   /// i.e. prefetch with any stride.
1240   virtual unsigned getMinPrefetchStride() const = 0;
1241
1242   /// \return The maximum number of iterations to prefetch ahead.  If
1243   /// the required number of iterations is more than this number, no
1244   /// prefetching is performed.
1245   virtual unsigned getMaxPrefetchIterationsAhead() const = 0;
1246
1247   virtual unsigned getMaxInterleaveFactor(unsigned VF) = 0;
1248   virtual unsigned
1249   getArithmeticInstrCost(unsigned Opcode, Type *Ty, OperandValueKind Opd1Info,
1250                          OperandValueKind Opd2Info,
1251                          OperandValueProperties Opd1PropInfo,
1252                          OperandValueProperties Opd2PropInfo,
1253                          ArrayRef<const Value *> Args) = 0;
1254   virtual int getShuffleCost(ShuffleKind Kind, Type *Tp, int Index,
1255                              Type *SubTp) = 0;
1256   virtual int getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src,
1257                                const Instruction *I) = 0;
1258   virtual int getExtractWithExtendCost(unsigned Opcode, Type *Dst,
1259                                        VectorType *VecTy, unsigned Index) = 0;
1260   virtual int getCFInstrCost(unsigned Opcode) = 0;
1261   virtual int getCmpSelInstrCost(unsigned Opcode, Type *ValTy,
1262                                 Type *CondTy, const Instruction *I) = 0;
1263   virtual int getVectorInstrCost(unsigned Opcode, Type *Val,
1264                                  unsigned Index) = 0;
1265   virtual int getMemoryOpCost(unsigned Opcode, Type *Src, unsigned Alignment,
1266                               unsigned AddressSpace, const Instruction *I) = 0;
1267   virtual int getMaskedMemoryOpCost(unsigned Opcode, Type *Src,
1268                                     unsigned Alignment,
1269                                     unsigned AddressSpace) = 0;
1270   virtual int getGatherScatterOpCost(unsigned Opcode, Type *DataTy,
1271                                      Value *Ptr, bool VariableMask,
1272                                      unsigned Alignment) = 0;
1273   virtual int getInterleavedMemoryOpCost(unsigned Opcode, Type *VecTy,
1274                                          unsigned Factor,
1275                                          ArrayRef<unsigned> Indices,
1276                                          unsigned Alignment,
1277                                          unsigned AddressSpace,
1278                                          bool UseMaskForCond = false,
1279                                          bool UseMaskForGaps = false) = 0;
1280   virtual int getArithmeticReductionCost(unsigned Opcode, Type *Ty,
1281                                          bool IsPairwiseForm) = 0;
1282   virtual int getMinMaxReductionCost(Type *Ty, Type *CondTy,
1283                                      bool IsPairwiseForm, bool IsUnsigned) = 0;
1284   virtual int getIntrinsicInstrCost(Intrinsic::ID ID, Type *RetTy,
1285                       ArrayRef<Type *> Tys, FastMathFlags FMF,
1286                       unsigned ScalarizationCostPassed) = 0;
1287   virtual int getIntrinsicInstrCost(Intrinsic::ID ID, Type *RetTy,
1288          ArrayRef<Value *> Args, FastMathFlags FMF, unsigned VF) = 0;
1289   virtual int getCallInstrCost(Function *F, Type *RetTy,
1290                                ArrayRef<Type *> Tys) = 0;
1291   virtual unsigned getNumberOfParts(Type *Tp) = 0;
1292   virtual int getAddressComputationCost(Type *Ty, ScalarEvolution *SE,
1293                                         const SCEV *Ptr) = 0;
1294   virtual unsigned getCostOfKeepingLiveOverCall(ArrayRef<Type *> Tys) = 0;
1295   virtual bool getTgtMemIntrinsic(IntrinsicInst *Inst,
1296                                   MemIntrinsicInfo &Info) = 0;
1297   virtual unsigned getAtomicMemIntrinsicMaxElementSize() const = 0;
1298   virtual Value *getOrCreateResultFromMemIntrinsic(IntrinsicInst *Inst,
1299                                                    Type *ExpectedType) = 0;
1300   virtual Type *getMemcpyLoopLoweringType(LLVMContext &Context, Value *Length,
1301                                           unsigned SrcAlign,
1302                                           unsigned DestAlign) const = 0;
1303   virtual void getMemcpyLoopResidualLoweringType(
1304       SmallVectorImpl<Type *> &OpsOut, LLVMContext &Context,
1305       unsigned RemainingBytes, unsigned SrcAlign, unsigned DestAlign) const = 0;
1306   virtual bool areInlineCompatible(const Function *Caller,
1307                                    const Function *Callee) const = 0;
1308   virtual bool
1309   areFunctionArgsABICompatible(const Function *Caller, const Function *Callee,
1310                                SmallPtrSetImpl<Argument *> &Args) const = 0;
1311   virtual bool isIndexedLoadLegal(MemIndexedMode Mode, Type *Ty) const = 0;
1312   virtual bool isIndexedStoreLegal(MemIndexedMode Mode,Type *Ty) const = 0;
1313   virtual unsigned getLoadStoreVecRegBitWidth(unsigned AddrSpace) const = 0;
1314   virtual bool isLegalToVectorizeLoad(LoadInst *LI) const = 0;
1315   virtual bool isLegalToVectorizeStore(StoreInst *SI) const = 0;
1316   virtual bool isLegalToVectorizeLoadChain(unsigned ChainSizeInBytes,
1317                                            unsigned Alignment,
1318                                            unsigned AddrSpace) const = 0;
1319   virtual bool isLegalToVectorizeStoreChain(unsigned ChainSizeInBytes,
1320                                             unsigned Alignment,
1321                                             unsigned AddrSpace) const = 0;
1322   virtual unsigned getLoadVectorFactor(unsigned VF, unsigned LoadSize,
1323                                        unsigned ChainSizeInBytes,
1324                                        VectorType *VecTy) const = 0;
1325   virtual unsigned getStoreVectorFactor(unsigned VF, unsigned StoreSize,
1326                                         unsigned ChainSizeInBytes,
1327                                         VectorType *VecTy) const = 0;
1328   virtual bool useReductionIntrinsic(unsigned Opcode, Type *Ty,
1329                                      ReductionFlags) const = 0;
1330   virtual bool shouldExpandReduction(const IntrinsicInst *II) const = 0;
1331   virtual unsigned getGISelRematGlobalCost() const = 0;
1332   virtual int getInstructionLatency(const Instruction *I) = 0;
1333 };
1334
1335 template <typename T>
1336 class TargetTransformInfo::Model final : public TargetTransformInfo::Concept {
1337   T Impl;
1338
1339 public:
1340   Model(T Impl) : Impl(std::move(Impl)) {}
1341   ~Model() override {}
1342
1343   const DataLayout &getDataLayout() const override {
1344     return Impl.getDataLayout();
1345   }
1346
1347   int getOperationCost(unsigned Opcode, Type *Ty, Type *OpTy) override {
1348     return Impl.getOperationCost(Opcode, Ty, OpTy);
1349   }
1350   int getGEPCost(Type *PointeeType, const Value *Ptr,
1351                  ArrayRef<const Value *> Operands) override {
1352     return Impl.getGEPCost(PointeeType, Ptr, Operands);
1353   }
1354   int getExtCost(const Instruction *I, const Value *Src) override {
1355     return Impl.getExtCost(I, Src);
1356   }
1357   int getCallCost(FunctionType *FTy, int NumArgs, const User *U) override {
1358     return Impl.getCallCost(FTy, NumArgs, U);
1359   }
1360   int getCallCost(const Function *F, int NumArgs, const User *U) override {
1361     return Impl.getCallCost(F, NumArgs, U);
1362   }
1363   int getCallCost(const Function *F,
1364                   ArrayRef<const Value *> Arguments, const User *U) override {
1365     return Impl.getCallCost(F, Arguments, U);
1366   }
1367   unsigned getInliningThresholdMultiplier() override {
1368     return Impl.getInliningThresholdMultiplier();
1369   }
1370   int getIntrinsicCost(Intrinsic::ID IID, Type *RetTy,
1371                        ArrayRef<Type *> ParamTys, const User *U = nullptr) override {
1372     return Impl.getIntrinsicCost(IID, RetTy, ParamTys, U);
1373   }
1374   int getIntrinsicCost(Intrinsic::ID IID, Type *RetTy,
1375                        ArrayRef<const Value *> Arguments,
1376                        const User *U = nullptr) override {
1377     return Impl.getIntrinsicCost(IID, RetTy, Arguments, U);
1378   }
1379   int getMemcpyCost(const Instruction *I) override {
1380     return Impl.getMemcpyCost(I);
1381   }
1382   int getUserCost(const User *U, ArrayRef<const Value *> Operands) override {
1383     return Impl.getUserCost(U, Operands);
1384   }
1385   bool hasBranchDivergence() override { return Impl.hasBranchDivergence(); }
1386   bool isSourceOfDivergence(const Value *V) override {
1387     return Impl.isSourceOfDivergence(V);
1388   }
1389
1390   bool isAlwaysUniform(const Value *V) override {
1391     return Impl.isAlwaysUniform(V);
1392   }
1393
1394   unsigned getFlatAddressSpace() override {
1395     return Impl.getFlatAddressSpace();
1396   }
1397
1398   bool isLoweredToCall(const Function *F) override {
1399     return Impl.isLoweredToCall(F);
1400   }
1401   void getUnrollingPreferences(Loop *L, ScalarEvolution &SE,
1402                                UnrollingPreferences &UP) override {
1403     return Impl.getUnrollingPreferences(L, SE, UP);
1404   }
1405   bool isHardwareLoopProfitable(Loop *L, ScalarEvolution &SE,
1406                                 AssumptionCache &AC,
1407                                 TargetLibraryInfo *LibInfo,
1408                                 HardwareLoopInfo &HWLoopInfo) override {
1409     return Impl.isHardwareLoopProfitable(L, SE, AC, LibInfo, HWLoopInfo);
1410   }
1411   bool isLegalAddImmediate(int64_t Imm) override {
1412     return Impl.isLegalAddImmediate(Imm);
1413   }
1414   bool isLegalICmpImmediate(int64_t Imm) override {
1415     return Impl.isLegalICmpImmediate(Imm);
1416   }
1417   bool isLegalAddressingMode(Type *Ty, GlobalValue *BaseGV, int64_t BaseOffset,
1418                              bool HasBaseReg, int64_t Scale,
1419                              unsigned AddrSpace,
1420                              Instruction *I) override {
1421     return Impl.isLegalAddressingMode(Ty, BaseGV, BaseOffset, HasBaseReg,
1422                                       Scale, AddrSpace, I);
1423   }
1424   bool isLSRCostLess(TargetTransformInfo::LSRCost &C1,
1425                      TargetTransformInfo::LSRCost &C2) override {
1426     return Impl.isLSRCostLess(C1, C2);
1427   }
1428   bool canMacroFuseCmp() override {
1429     return Impl.canMacroFuseCmp();
1430   }
1431   bool canSaveCmp(Loop *L, BranchInst **BI,
1432                         ScalarEvolution *SE,
1433                         LoopInfo *LI, DominatorTree *DT, AssumptionCache *AC,
1434                         TargetLibraryInfo *LibInfo) override {
1435     return Impl.canSaveCmp(L, BI, SE, LI, DT, AC, LibInfo);
1436   }
1437   bool shouldFavorPostInc() const override {
1438     return Impl.shouldFavorPostInc();
1439   }
1440   bool shouldFavorBackedgeIndex(const Loop *L) const override {
1441     return Impl.shouldFavorBackedgeIndex(L);
1442   }
1443   bool isLegalMaskedStore(Type *DataType) override {
1444     return Impl.isLegalMaskedStore(DataType);
1445   }
1446   bool isLegalMaskedLoad(Type *DataType) override {
1447     return Impl.isLegalMaskedLoad(DataType);
1448   }
1449   bool isLegalNTStore(Type *DataType, unsigned Alignment) override {
1450     return Impl.isLegalNTStore(DataType, Alignment);
1451   }
1452   bool isLegalNTLoad(Type *DataType, unsigned Alignment) override {
1453     return Impl.isLegalNTLoad(DataType, Alignment);
1454   }
1455   bool isLegalMaskedScatter(Type *DataType) override {
1456     return Impl.isLegalMaskedScatter(DataType);
1457   }
1458   bool isLegalMaskedGather(Type *DataType) override {
1459     return Impl.isLegalMaskedGather(DataType);
1460   }
1461   bool isLegalMaskedCompressStore(Type *DataType) override {
1462     return Impl.isLegalMaskedCompressStore(DataType);
1463   }
1464   bool isLegalMaskedExpandLoad(Type *DataType) override {
1465     return Impl.isLegalMaskedExpandLoad(DataType);
1466   }
1467   bool hasDivRemOp(Type *DataType, bool IsSigned) override {
1468     return Impl.hasDivRemOp(DataType, IsSigned);
1469   }
1470   bool hasVolatileVariant(Instruction *I, unsigned AddrSpace) override {
1471     return Impl.hasVolatileVariant(I, AddrSpace);
1472   }
1473   bool prefersVectorizedAddressing() override {
1474     return Impl.prefersVectorizedAddressing();
1475   }
1476   int getScalingFactorCost(Type *Ty, GlobalValue *BaseGV, int64_t BaseOffset,
1477                            bool HasBaseReg, int64_t Scale,
1478                            unsigned AddrSpace) override {
1479     return Impl.getScalingFactorCost(Ty, BaseGV, BaseOffset, HasBaseReg,
1480                                      Scale, AddrSpace);
1481   }
1482   bool LSRWithInstrQueries() override {
1483     return Impl.LSRWithInstrQueries();
1484   }
1485   bool isTruncateFree(Type *Ty1, Type *Ty2) override {
1486     return Impl.isTruncateFree(Ty1, Ty2);
1487   }
1488   bool isProfitableToHoist(Instruction *I) override {
1489     return Impl.isProfitableToHoist(I);
1490   }
1491   bool useAA() override { return Impl.useAA(); }
1492   bool isTypeLegal(Type *Ty) override { return Impl.isTypeLegal(Ty); }
1493   unsigned getJumpBufAlignment() override { return Impl.getJumpBufAlignment(); }
1494   unsigned getJumpBufSize() override { return Impl.getJumpBufSize(); }
1495   bool shouldBuildLookupTables() override {
1496     return Impl.shouldBuildLookupTables();
1497   }
1498   bool shouldBuildLookupTablesForConstant(Constant *C) override {
1499     return Impl.shouldBuildLookupTablesForConstant(C);
1500   }
1501   bool useColdCCForColdCall(Function &F) override {
1502     return Impl.useColdCCForColdCall(F);
1503   }
1504
1505   unsigned getScalarizationOverhead(Type *Ty, bool Insert,
1506                                     bool Extract) override {
1507     return Impl.getScalarizationOverhead(Ty, Insert, Extract);
1508   }
1509   unsigned getOperandsScalarizationOverhead(ArrayRef<const Value *> Args,
1510                                             unsigned VF) override {
1511     return Impl.getOperandsScalarizationOverhead(Args, VF);
1512   }
1513
1514   bool supportsEfficientVectorElementLoadStore() override {
1515     return Impl.supportsEfficientVectorElementLoadStore();
1516   }
1517
1518   bool enableAggressiveInterleaving(bool LoopHasReductions) override {
1519     return Impl.enableAggressiveInterleaving(LoopHasReductions);
1520   }
1521   MemCmpExpansionOptions enableMemCmpExpansion(bool OptSize,
1522                                                bool IsZeroCmp) const override {
1523     return Impl.enableMemCmpExpansion(OptSize, IsZeroCmp);
1524   }
1525   bool enableInterleavedAccessVectorization() override {
1526     return Impl.enableInterleavedAccessVectorization();
1527   }
1528   bool enableMaskedInterleavedAccessVectorization() override {
1529     return Impl.enableMaskedInterleavedAccessVectorization();
1530   }
1531   bool isFPVectorizationPotentiallyUnsafe() override {
1532     return Impl.isFPVectorizationPotentiallyUnsafe();
1533   }
1534   bool allowsMisalignedMemoryAccesses(LLVMContext &Context,
1535                                       unsigned BitWidth, unsigned AddressSpace,
1536                                       unsigned Alignment, bool *Fast) override {
1537     return Impl.allowsMisalignedMemoryAccesses(Context, BitWidth, AddressSpace,
1538                                                Alignment, Fast);
1539   }
1540   PopcntSupportKind getPopcntSupport(unsigned IntTyWidthInBit) override {
1541     return Impl.getPopcntSupport(IntTyWidthInBit);
1542   }
1543   bool haveFastSqrt(Type *Ty) override { return Impl.haveFastSqrt(Ty); }
1544
1545   bool isFCmpOrdCheaperThanFCmpZero(Type *Ty) override {
1546     return Impl.isFCmpOrdCheaperThanFCmpZero(Ty);
1547   }
1548
1549   int getFPOpCost(Type *Ty) override { return Impl.getFPOpCost(Ty); }
1550
1551   int getIntImmCodeSizeCost(unsigned Opc, unsigned Idx, const APInt &Imm,
1552                             Type *Ty) override {
1553     return Impl.getIntImmCodeSizeCost(Opc, Idx, Imm, Ty);
1554   }
1555   int getIntImmCost(const APInt &Imm, Type *Ty) override {
1556     return Impl.getIntImmCost(Imm, Ty);
1557   }
1558   int getIntImmCost(unsigned Opc, unsigned Idx, const APInt &Imm,
1559                     Type *Ty) override {
1560     return Impl.getIntImmCost(Opc, Idx, Imm, Ty);
1561   }
1562   int getIntImmCost(Intrinsic::ID IID, unsigned Idx, const APInt &Imm,
1563                     Type *Ty) override {
1564     return Impl.getIntImmCost(IID, Idx, Imm, Ty);
1565   }
1566   unsigned getNumberOfRegisters(bool Vector) override {
1567     return Impl.getNumberOfRegisters(Vector);
1568   }
1569   unsigned getRegisterBitWidth(bool Vector) const override {
1570     return Impl.getRegisterBitWidth(Vector);
1571   }
1572   unsigned getMinVectorRegisterBitWidth() override {
1573     return Impl.getMinVectorRegisterBitWidth();
1574   }
1575   bool shouldMaximizeVectorBandwidth(bool OptSize) const override {
1576     return Impl.shouldMaximizeVectorBandwidth(OptSize);
1577   }
1578   unsigned getMinimumVF(unsigned ElemWidth) const override {
1579     return Impl.getMinimumVF(ElemWidth);
1580   }
1581   bool shouldConsiderAddressTypePromotion(
1582       const Instruction &I, bool &AllowPromotionWithoutCommonHeader) override {
1583     return Impl.shouldConsiderAddressTypePromotion(
1584         I, AllowPromotionWithoutCommonHeader);
1585   }
1586   unsigned getCacheLineSize() const override {
1587     return Impl.getCacheLineSize();
1588   }
1589   llvm::Optional<unsigned> getCacheSize(CacheLevel Level) const override {
1590     return Impl.getCacheSize(Level);
1591   }
1592   llvm::Optional<unsigned> getCacheAssociativity(CacheLevel Level) const override {
1593     return Impl.getCacheAssociativity(Level);
1594   }
1595
1596   /// Return the preferred prefetch distance in terms of instructions.
1597   ///
1598   unsigned getPrefetchDistance() const override {
1599     return Impl.getPrefetchDistance();
1600   }
1601
1602   /// Return the minimum stride necessary to trigger software
1603   /// prefetching.
1604   ///
1605   unsigned getMinPrefetchStride() const override {
1606     return Impl.getMinPrefetchStride();
1607   }
1608
1609   /// Return the maximum prefetch distance in terms of loop
1610   /// iterations.
1611   ///
1612   unsigned getMaxPrefetchIterationsAhead() const override {
1613     return Impl.getMaxPrefetchIterationsAhead();
1614   }
1615
1616   unsigned getMaxInterleaveFactor(unsigned VF) override {
1617     return Impl.getMaxInterleaveFactor(VF);
1618   }
1619   unsigned getEstimatedNumberOfCaseClusters(const SwitchInst &SI,
1620                                             unsigned &JTSize) override {
1621     return Impl.getEstimatedNumberOfCaseClusters(SI, JTSize);
1622   }
1623   unsigned
1624   getArithmeticInstrCost(unsigned Opcode, Type *Ty, OperandValueKind Opd1Info,
1625                          OperandValueKind Opd2Info,
1626                          OperandValueProperties Opd1PropInfo,
1627                          OperandValueProperties Opd2PropInfo,
1628                          ArrayRef<const Value *> Args) override {
1629     return Impl.getArithmeticInstrCost(Opcode, Ty, Opd1Info, Opd2Info,
1630                                        Opd1PropInfo, Opd2PropInfo, Args);
1631   }
1632   int getShuffleCost(ShuffleKind Kind, Type *Tp, int Index,
1633                      Type *SubTp) override {
1634     return Impl.getShuffleCost(Kind, Tp, Index, SubTp);
1635   }
1636   int getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src,
1637                        const Instruction *I) override {
1638     return Impl.getCastInstrCost(Opcode, Dst, Src, I);
1639   }
1640   int getExtractWithExtendCost(unsigned Opcode, Type *Dst, VectorType *VecTy,
1641                                unsigned Index) override {
1642     return Impl.getExtractWithExtendCost(Opcode, Dst, VecTy, Index);
1643   }
1644   int getCFInstrCost(unsigned Opcode) override {
1645     return Impl.getCFInstrCost(Opcode);
1646   }
1647   int getCmpSelInstrCost(unsigned Opcode, Type *ValTy, Type *CondTy,
1648                          const Instruction *I) override {
1649     return Impl.getCmpSelInstrCost(Opcode, ValTy, CondTy, I);
1650   }
1651   int getVectorInstrCost(unsigned Opcode, Type *Val, unsigned Index) override {
1652     return Impl.getVectorInstrCost(Opcode, Val, Index);
1653   }
1654   int getMemoryOpCost(unsigned Opcode, Type *Src, unsigned Alignment,
1655                       unsigned AddressSpace, const Instruction *I) override {
1656     return Impl.getMemoryOpCost(Opcode, Src, Alignment, AddressSpace, I);
1657   }
1658   int getMaskedMemoryOpCost(unsigned Opcode, Type *Src, unsigned Alignment,
1659                             unsigned AddressSpace) override {
1660     return Impl.getMaskedMemoryOpCost(Opcode, Src, Alignment, AddressSpace);
1661   }
1662   int getGatherScatterOpCost(unsigned Opcode, Type *DataTy,
1663                              Value *Ptr, bool VariableMask,
1664                              unsigned Alignment) override {
1665     return Impl.getGatherScatterOpCost(Opcode, DataTy, Ptr, VariableMask,
1666                                        Alignment);
1667   }
1668   int getInterleavedMemoryOpCost(unsigned Opcode, Type *VecTy, unsigned Factor,
1669                                  ArrayRef<unsigned> Indices, unsigned Alignment,
1670                                  unsigned AddressSpace, bool UseMaskForCond,
1671                                  bool UseMaskForGaps) override {
1672     return Impl.getInterleavedMemoryOpCost(Opcode, VecTy, Factor, Indices,
1673                                            Alignment, AddressSpace,
1674                                            UseMaskForCond, UseMaskForGaps);
1675   }
1676   int getArithmeticReductionCost(unsigned Opcode, Type *Ty,
1677                                  bool IsPairwiseForm) override {
1678     return Impl.getArithmeticReductionCost(Opcode, Ty, IsPairwiseForm);
1679   }
1680   int getMinMaxReductionCost(Type *Ty, Type *CondTy,
1681                              bool IsPairwiseForm, bool IsUnsigned) override {
1682     return Impl.getMinMaxReductionCost(Ty, CondTy, IsPairwiseForm, IsUnsigned);
1683    }
1684   int getIntrinsicInstrCost(Intrinsic::ID ID, Type *RetTy, ArrayRef<Type *> Tys,
1685                FastMathFlags FMF, unsigned ScalarizationCostPassed) override {
1686     return Impl.getIntrinsicInstrCost(ID, RetTy, Tys, FMF,
1687                                       ScalarizationCostPassed);
1688   }
1689   int getIntrinsicInstrCost(Intrinsic::ID ID, Type *RetTy,
1690        ArrayRef<Value *> Args, FastMathFlags FMF, unsigned VF) override {
1691     return Impl.getIntrinsicInstrCost(ID, RetTy, Args, FMF, VF);
1692   }
1693   int getCallInstrCost(Function *F, Type *RetTy,
1694                        ArrayRef<Type *> Tys) override {
1695     return Impl.getCallInstrCost(F, RetTy, Tys);
1696   }
1697   unsigned getNumberOfParts(Type *Tp) override {
1698     return Impl.getNumberOfParts(Tp);
1699   }
1700   int getAddressComputationCost(Type *Ty, ScalarEvolution *SE,
1701                                 const SCEV *Ptr) override {
1702     return Impl.getAddressComputationCost(Ty, SE, Ptr);
1703   }
1704   unsigned getCostOfKeepingLiveOverCall(ArrayRef<Type *> Tys) override {
1705     return Impl.getCostOfKeepingLiveOverCall(Tys);
1706   }
1707   bool getTgtMemIntrinsic(IntrinsicInst *Inst,
1708                           MemIntrinsicInfo &Info) override {
1709     return Impl.getTgtMemIntrinsic(Inst, Info);
1710   }
1711   unsigned getAtomicMemIntrinsicMaxElementSize() const override {
1712     return Impl.getAtomicMemIntrinsicMaxElementSize();
1713   }
1714   Value *getOrCreateResultFromMemIntrinsic(IntrinsicInst *Inst,
1715                                            Type *ExpectedType) override {
1716     return Impl.getOrCreateResultFromMemIntrinsic(Inst, ExpectedType);
1717   }
1718   Type *getMemcpyLoopLoweringType(LLVMContext &Context, Value *Length,
1719                                   unsigned SrcAlign,
1720                                   unsigned DestAlign) const override {
1721     return Impl.getMemcpyLoopLoweringType(Context, Length, SrcAlign, DestAlign);
1722   }
1723   void getMemcpyLoopResidualLoweringType(SmallVectorImpl<Type *> &OpsOut,
1724                                          LLVMContext &Context,
1725                                          unsigned RemainingBytes,
1726                                          unsigned SrcAlign,
1727                                          unsigned DestAlign) const override {
1728     Impl.getMemcpyLoopResidualLoweringType(OpsOut, Context, RemainingBytes,
1729                                            SrcAlign, DestAlign);
1730   }
1731   bool areInlineCompatible(const Function *Caller,
1732                            const Function *Callee) const override {
1733     return Impl.areInlineCompatible(Caller, Callee);
1734   }
1735   bool areFunctionArgsABICompatible(
1736       const Function *Caller, const Function *Callee,
1737       SmallPtrSetImpl<Argument *> &Args) const override {
1738     return Impl.areFunctionArgsABICompatible(Caller, Callee, Args);
1739   }
1740   bool isIndexedLoadLegal(MemIndexedMode Mode, Type *Ty) const override {
1741     return Impl.isIndexedLoadLegal(Mode, Ty, getDataLayout());
1742   }
1743   bool isIndexedStoreLegal(MemIndexedMode Mode, Type *Ty) const override {
1744     return Impl.isIndexedStoreLegal(Mode, Ty, getDataLayout());
1745   }
1746   unsigned getLoadStoreVecRegBitWidth(unsigned AddrSpace) const override {
1747     return Impl.getLoadStoreVecRegBitWidth(AddrSpace);
1748   }
1749   bool isLegalToVectorizeLoad(LoadInst *LI) const override {
1750     return Impl.isLegalToVectorizeLoad(LI);
1751   }
1752   bool isLegalToVectorizeStore(StoreInst *SI) const override {
1753     return Impl.isLegalToVectorizeStore(SI);
1754   }
1755   bool isLegalToVectorizeLoadChain(unsigned ChainSizeInBytes,
1756                                    unsigned Alignment,
1757                                    unsigned AddrSpace) const override {
1758     return Impl.isLegalToVectorizeLoadChain(ChainSizeInBytes, Alignment,
1759                                             AddrSpace);
1760   }
1761   bool isLegalToVectorizeStoreChain(unsigned ChainSizeInBytes,
1762                                     unsigned Alignment,
1763                                     unsigned AddrSpace) const override {
1764     return Impl.isLegalToVectorizeStoreChain(ChainSizeInBytes, Alignment,
1765                                              AddrSpace);
1766   }
1767   unsigned getLoadVectorFactor(unsigned VF, unsigned LoadSize,
1768                                unsigned ChainSizeInBytes,
1769                                VectorType *VecTy) const override {
1770     return Impl.getLoadVectorFactor(VF, LoadSize, ChainSizeInBytes, VecTy);
1771   }
1772   unsigned getStoreVectorFactor(unsigned VF, unsigned StoreSize,
1773                                 unsigned ChainSizeInBytes,
1774                                 VectorType *VecTy) const override {
1775     return Impl.getStoreVectorFactor(VF, StoreSize, ChainSizeInBytes, VecTy);
1776   }
1777   bool useReductionIntrinsic(unsigned Opcode, Type *Ty,
1778                              ReductionFlags Flags) const override {
1779     return Impl.useReductionIntrinsic(Opcode, Ty, Flags);
1780   }
1781   bool shouldExpandReduction(const IntrinsicInst *II) const override {
1782     return Impl.shouldExpandReduction(II);
1783   }
1784
1785   unsigned getGISelRematGlobalCost() const override {
1786     return Impl.getGISelRematGlobalCost();
1787   }
1788
1789   int getInstructionLatency(const Instruction *I) override {
1790     return Impl.getInstructionLatency(I);
1791   }
1792 };
1793
1794 template <typename T>
1795 TargetTransformInfo::TargetTransformInfo(T Impl)
1796     : TTIImpl(new Model<T>(Impl)) {}
1797
1798 /// Analysis pass providing the \c TargetTransformInfo.
1799 ///
1800 /// The core idea of the TargetIRAnalysis is to expose an interface through
1801 /// which LLVM targets can analyze and provide information about the middle
1802 /// end's target-independent IR. This supports use cases such as target-aware
1803 /// cost modeling of IR constructs.
1804 ///
1805 /// This is a function analysis because much of the cost modeling for targets
1806 /// is done in a subtarget specific way and LLVM supports compiling different
1807 /// functions targeting different subtargets in order to support runtime
1808 /// dispatch according to the observed subtarget.
1809 class TargetIRAnalysis : public AnalysisInfoMixin<TargetIRAnalysis> {
1810 public:
1811   typedef TargetTransformInfo Result;
1812
1813   /// Default construct a target IR analysis.
1814   ///
1815   /// This will use the module's datalayout to construct a baseline
1816   /// conservative TTI result.
1817   TargetIRAnalysis();
1818
1819   /// Construct an IR analysis pass around a target-provide callback.
1820   ///
1821   /// The callback will be called with a particular function for which the TTI
1822   /// is needed and must return a TTI object for that function.
1823   TargetIRAnalysis(std::function<Result(const Function &)> TTICallback);
1824
1825   // Value semantics. We spell out the constructors for MSVC.
1826   TargetIRAnalysis(const TargetIRAnalysis &Arg)
1827       : TTICallback(Arg.TTICallback) {}
1828   TargetIRAnalysis(TargetIRAnalysis &&Arg)
1829       : TTICallback(std::move(Arg.TTICallback)) {}
1830   TargetIRAnalysis &operator=(const TargetIRAnalysis &RHS) {
1831     TTICallback = RHS.TTICallback;
1832     return *this;
1833   }
1834   TargetIRAnalysis &operator=(TargetIRAnalysis &&RHS) {
1835     TTICallback = std::move(RHS.TTICallback);
1836     return *this;
1837   }
1838
1839   Result run(const Function &F, FunctionAnalysisManager &);
1840
1841 private:
1842   friend AnalysisInfoMixin<TargetIRAnalysis>;
1843   static AnalysisKey Key;
1844
1845   /// The callback used to produce a result.
1846   ///
1847   /// We use a completely opaque callback so that targets can provide whatever
1848   /// mechanism they desire for constructing the TTI for a given function.
1849   ///
1850   /// FIXME: Should we really use std::function? It's relatively inefficient.
1851   /// It might be possible to arrange for even stateful callbacks to outlive
1852   /// the analysis and thus use a function_ref which would be lighter weight.
1853   /// This may also be less error prone as the callback is likely to reference
1854   /// the external TargetMachine, and that reference needs to never dangle.
1855   std::function<Result(const Function &)> TTICallback;
1856
1857   /// Helper function used as the callback in the default constructor.
1858   static Result getDefaultTTI(const Function &F);
1859 };
1860
1861 /// Wrapper pass for TargetTransformInfo.
1862 ///
1863 /// This pass can be constructed from a TTI object which it stores internally
1864 /// and is queried by passes.
1865 class TargetTransformInfoWrapperPass : public ImmutablePass {
1866   TargetIRAnalysis TIRA;
1867   Optional<TargetTransformInfo> TTI;
1868
1869   virtual void anchor();
1870
1871 public:
1872   static char ID;
1873
1874   /// We must provide a default constructor for the pass but it should
1875   /// never be used.
1876   ///
1877   /// Use the constructor below or call one of the creation routines.
1878   TargetTransformInfoWrapperPass();
1879
1880   explicit TargetTransformInfoWrapperPass(TargetIRAnalysis TIRA);
1881
1882   TargetTransformInfo &getTTI(const Function &F);
1883 };
1884
1885 /// Create an analysis pass wrapper around a TTI object.
1886 ///
1887 /// This analysis pass just holds the TTI instance and makes it available to
1888 /// clients.
1889 ImmutablePass *createTargetTransformInfoWrapperPass(TargetIRAnalysis TIRA);
1890
1891 } // End llvm namespace
1892
1893 #endif