Add a new pass FunctionTargetTransformInfo. This pass serves as a
[oota-llvm.git] / include / llvm / Analysis / TargetTransformInfo.h
1 //===- llvm/Analysis/TargetTransformInfo.h ----------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass exposes codegen information to IR-level passes. Every
11 // transformation that uses codegen information is broken into three parts:
12 // 1. The IR-level analysis pass.
13 // 2. The IR-level transformation interface which provides the needed
14 //    information.
15 // 3. Codegen-level implementation which uses target-specific hooks.
16 //
17 // This file defines #2, which is the interface that IR-level transformations
18 // use for querying the codegen.
19 //
20 //===----------------------------------------------------------------------===//
21
22 #ifndef LLVM_ANALYSIS_TARGETTRANSFORMINFO_H
23 #define LLVM_ANALYSIS_TARGETTRANSFORMINFO_H
24
25 #include "llvm/IR/Intrinsics.h"
26 #include "llvm/Pass.h"
27 #include "llvm/Support/DataTypes.h"
28
29 namespace llvm {
30
31 class Function;
32 class GlobalValue;
33 class Loop;
34 class Type;
35 class User;
36 class Value;
37
38 /// TargetTransformInfo - This pass provides access to the codegen
39 /// interfaces that are needed for IR-level transformations.
40 class TargetTransformInfo {
41 protected:
42   /// \brief The TTI instance one level down the stack.
43   ///
44   /// This is used to implement the default behavior all of the methods which
45   /// is to delegate up through the stack of TTIs until one can answer the
46   /// query.
47   TargetTransformInfo *PrevTTI;
48
49   /// \brief The top of the stack of TTI analyses available.
50   ///
51   /// This is a convenience routine maintained as TTI analyses become available
52   /// that complements the PrevTTI delegation chain. When one part of an
53   /// analysis pass wants to query another part of the analysis pass it can use
54   /// this to start back at the top of the stack.
55   TargetTransformInfo *TopTTI;
56
57   /// All pass subclasses must in their initializePass routine call
58   /// pushTTIStack with themselves to update the pointers tracking the previous
59   /// TTI instance in the analysis group's stack, and the top of the analysis
60   /// group's stack.
61   void pushTTIStack(Pass *P);
62
63   /// All pass subclasses must call TargetTransformInfo::getAnalysisUsage.
64   virtual void getAnalysisUsage(AnalysisUsage &AU) const;
65
66 public:
67   /// This class is intended to be subclassed by real implementations.
68   virtual ~TargetTransformInfo() = 0;
69
70   /// \name Generic Target Information
71   /// @{
72
73   /// \brief Underlying constants for 'cost' values in this interface.
74   ///
75   /// Many APIs in this interface return a cost. This enum defines the
76   /// fundamental values that should be used to interpret (and produce) those
77   /// costs. The costs are returned as an unsigned rather than a member of this
78   /// enumeration because it is expected that the cost of one IR instruction
79   /// may have a multiplicative factor to it or otherwise won't fit directly
80   /// into the enum. Moreover, it is common to sum or average costs which works
81   /// better as simple integral values. Thus this enum only provides constants.
82   ///
83   /// Note that these costs should usually reflect the intersection of code-size
84   /// cost and execution cost. A free instruction is typically one that folds
85   /// into another instruction. For example, reg-to-reg moves can often be
86   /// skipped by renaming the registers in the CPU, but they still are encoded
87   /// and thus wouldn't be considered 'free' here.
88   enum TargetCostConstants {
89     TCC_Free = 0,       ///< Expected to fold away in lowering.
90     TCC_Basic = 1,      ///< The cost of a typical 'add' instruction.
91     TCC_Expensive = 4   ///< The cost of a 'div' instruction on x86.
92   };
93
94   /// \brief Estimate the cost of a specific operation when lowered.
95   ///
96   /// Note that this is designed to work on an arbitrary synthetic opcode, and
97   /// thus work for hypothetical queries before an instruction has even been
98   /// formed. However, this does *not* work for GEPs, and must not be called
99   /// for a GEP instruction. Instead, use the dedicated getGEPCost interface as
100   /// analyzing a GEP's cost required more information.
101   ///
102   /// Typically only the result type is required, and the operand type can be
103   /// omitted. However, if the opcode is one of the cast instructions, the
104   /// operand type is required.
105   ///
106   /// The returned cost is defined in terms of \c TargetCostConstants, see its
107   /// comments for a detailed explanation of the cost values.
108   virtual unsigned getOperationCost(unsigned Opcode, Type *Ty,
109                                     Type *OpTy = nullptr) const;
110
111   /// \brief Estimate the cost of a GEP operation when lowered.
112   ///
113   /// The contract for this function is the same as \c getOperationCost except
114   /// that it supports an interface that provides extra information specific to
115   /// the GEP operation.
116   virtual unsigned getGEPCost(const Value *Ptr,
117                               ArrayRef<const Value *> Operands) const;
118
119   /// \brief Estimate the cost of a function call when lowered.
120   ///
121   /// The contract for this is the same as \c getOperationCost except that it
122   /// supports an interface that provides extra information specific to call
123   /// instructions.
124   ///
125   /// This is the most basic query for estimating call cost: it only knows the
126   /// function type and (potentially) the number of arguments at the call site.
127   /// The latter is only interesting for varargs function types.
128   virtual unsigned getCallCost(FunctionType *FTy, int NumArgs = -1) const;
129
130   /// \brief Estimate the cost of calling a specific function when lowered.
131   ///
132   /// This overload adds the ability to reason about the particular function
133   /// being called in the event it is a library call with special lowering.
134   virtual unsigned getCallCost(const Function *F, int NumArgs = -1) const;
135
136   /// \brief Estimate the cost of calling a specific function when lowered.
137   ///
138   /// This overload allows specifying a set of candidate argument values.
139   virtual unsigned getCallCost(const Function *F,
140                                ArrayRef<const Value *> Arguments) const;
141
142   /// \brief Estimate the cost of an intrinsic when lowered.
143   ///
144   /// Mirrors the \c getCallCost method but uses an intrinsic identifier.
145   virtual unsigned getIntrinsicCost(Intrinsic::ID IID, Type *RetTy,
146                                     ArrayRef<Type *> ParamTys) const;
147
148   /// \brief Estimate the cost of an intrinsic when lowered.
149   ///
150   /// Mirrors the \c getCallCost method but uses an intrinsic identifier.
151   virtual unsigned getIntrinsicCost(Intrinsic::ID IID, Type *RetTy,
152                                     ArrayRef<const Value *> Arguments) const;
153
154   /// \brief Estimate the cost of a given IR user when lowered.
155   ///
156   /// This can estimate the cost of either a ConstantExpr or Instruction when
157   /// lowered. It has two primary advantages over the \c getOperationCost and
158   /// \c getGEPCost above, and one significant disadvantage: it can only be
159   /// used when the IR construct has already been formed.
160   ///
161   /// The advantages are that it can inspect the SSA use graph to reason more
162   /// accurately about the cost. For example, all-constant-GEPs can often be
163   /// folded into a load or other instruction, but if they are used in some
164   /// other context they may not be folded. This routine can distinguish such
165   /// cases.
166   ///
167   /// The returned cost is defined in terms of \c TargetCostConstants, see its
168   /// comments for a detailed explanation of the cost values.
169   virtual unsigned getUserCost(const User *U) const;
170
171   /// \brief hasBranchDivergence - Return true if branch divergence exists.
172   /// Branch divergence has a significantly negative impact on GPU performance
173   /// when threads in the same wavefront take different paths due to conditional
174   /// branches.
175   virtual bool hasBranchDivergence() const;
176
177   /// \brief Test whether calls to a function lower to actual program function
178   /// calls.
179   ///
180   /// The idea is to test whether the program is likely to require a 'call'
181   /// instruction or equivalent in order to call the given function.
182   ///
183   /// FIXME: It's not clear that this is a good or useful query API. Client's
184   /// should probably move to simpler cost metrics using the above.
185   /// Alternatively, we could split the cost interface into distinct code-size
186   /// and execution-speed costs. This would allow modelling the core of this
187   /// query more accurately as a call is a single small instruction, but
188   /// incurs significant execution cost.
189   virtual bool isLoweredToCall(const Function *F) const;
190
191   /// Parameters that control the generic loop unrolling transformation.
192   struct UnrollingPreferences {
193     /// The cost threshold for the unrolled loop, compared to
194     /// CodeMetrics.NumInsts aggregated over all basic blocks in the loop body.
195     /// The unrolling factor is set such that the unrolled loop body does not
196     /// exceed this cost. Set this to UINT_MAX to disable the loop body cost
197     /// restriction.
198     unsigned Threshold;
199     /// The cost threshold for the unrolled loop when optimizing for size (set
200     /// to UINT_MAX to disable).
201     unsigned OptSizeThreshold;
202     /// The cost threshold for the unrolled loop, like Threshold, but used
203     /// for partial/runtime unrolling (set to UINT_MAX to disable).
204     unsigned PartialThreshold;
205     /// The cost threshold for the unrolled loop when optimizing for size, like
206     /// OptSizeThreshold, but used for partial/runtime unrolling (set to UINT_MAX
207     /// to disable).
208     unsigned PartialOptSizeThreshold;
209     /// A forced unrolling factor (the number of concatenated bodies of the
210     /// original loop in the unrolled loop body). When set to 0, the unrolling
211     /// transformation will select an unrolling factor based on the current cost
212     /// threshold and other factors.
213     unsigned Count;
214     // Set the maximum unrolling factor. The unrolling factor may be selected
215     // using the appropriate cost threshold, but may not exceed this number
216     // (set to UINT_MAX to disable). This does not apply in cases where the
217     // loop is being fully unrolled.
218     unsigned MaxCount;
219     /// Allow partial unrolling (unrolling of loops to expand the size of the
220     /// loop body, not only to eliminate small constant-trip-count loops).
221     bool     Partial;
222     /// Allow runtime unrolling (unrolling of loops to expand the size of the
223     /// loop body even when the number of loop iterations is not known at compile
224     /// time).
225     bool     Runtime;
226   };
227
228   /// \brief Get target-customized preferences for the generic loop unrolling
229   /// transformation. The caller will initialize UP with the current
230   /// target-independent defaults.
231   virtual void getUnrollingPreferences(const Function *F, Loop *L,
232                                        UnrollingPreferences &UP) const;
233
234   /// @}
235
236   /// \name Scalar Target Information
237   /// @{
238
239   /// \brief Flags indicating the kind of support for population count.
240   ///
241   /// Compared to the SW implementation, HW support is supposed to
242   /// significantly boost the performance when the population is dense, and it
243   /// may or may not degrade performance if the population is sparse. A HW
244   /// support is considered as "Fast" if it can outperform, or is on a par
245   /// with, SW implementation when the population is sparse; otherwise, it is
246   /// considered as "Slow".
247   enum PopcntSupportKind {
248     PSK_Software,
249     PSK_SlowHardware,
250     PSK_FastHardware
251   };
252
253   /// \brief Return true if the specified immediate is legal add immediate, that
254   /// is the target has add instructions which can add a register with the
255   /// immediate without having to materialize the immediate into a register.
256   virtual bool isLegalAddImmediate(int64_t Imm) const;
257
258   /// \brief Return true if the specified immediate is legal icmp immediate,
259   /// that is the target has icmp instructions which can compare a register
260   /// against the immediate without having to materialize the immediate into a
261   /// register.
262   virtual bool isLegalICmpImmediate(int64_t Imm) const;
263
264   /// \brief Return true if the addressing mode represented by AM is legal for
265   /// this target, for a load/store of the specified type.
266   /// The type may be VoidTy, in which case only return true if the addressing
267   /// mode is legal for a load/store of any legal type.
268   /// TODO: Handle pre/postinc as well.
269   virtual bool isLegalAddressingMode(Type *Ty, GlobalValue *BaseGV,
270                                      int64_t BaseOffset, bool HasBaseReg,
271                                      int64_t Scale) const;
272
273   /// \brief Return the cost of the scaling factor used in the addressing
274   /// mode represented by AM for this target, for a load/store
275   /// of the specified type.
276   /// If the AM is supported, the return value must be >= 0.
277   /// If the AM is not supported, it returns a negative value.
278   /// TODO: Handle pre/postinc as well.
279   virtual int getScalingFactorCost(Type *Ty, GlobalValue *BaseGV,
280                                    int64_t BaseOffset, bool HasBaseReg,
281                                    int64_t Scale) const;
282
283   /// \brief Return true if it's free to truncate a value of type Ty1 to type
284   /// Ty2. e.g. On x86 it's free to truncate a i32 value in register EAX to i16
285   /// by referencing its sub-register AX.
286   virtual bool isTruncateFree(Type *Ty1, Type *Ty2) const;
287
288   /// \brief Return true if this type is legal.
289   virtual bool isTypeLegal(Type *Ty) const;
290
291   /// \brief Returns the target's jmp_buf alignment in bytes.
292   virtual unsigned getJumpBufAlignment() const;
293
294   /// \brief Returns the target's jmp_buf size in bytes.
295   virtual unsigned getJumpBufSize() const;
296
297   /// \brief Return true if switches should be turned into lookup tables for the
298   /// target.
299   virtual bool shouldBuildLookupTables() const;
300
301   /// \brief Return hardware support for population count.
302   virtual PopcntSupportKind getPopcntSupport(unsigned IntTyWidthInBit) const;
303
304   /// \brief Return true if the hardware has a fast square-root instruction.
305   virtual bool haveFastSqrt(Type *Ty) const;
306
307   /// \brief Return the expected cost of materializing for the given integer
308   /// immediate of the specified type.
309   virtual unsigned getIntImmCost(const APInt &Imm, Type *Ty) const;
310
311   /// \brief Return the expected cost of materialization for the given integer
312   /// immediate of the specified type for a given instruction. The cost can be
313   /// zero if the immediate can be folded into the specified instruction.
314   virtual unsigned getIntImmCost(unsigned Opc, unsigned Idx, const APInt &Imm,
315                                  Type *Ty) const;
316   virtual unsigned getIntImmCost(Intrinsic::ID IID, unsigned Idx,
317                                  const APInt &Imm, Type *Ty) const;
318   /// @}
319
320   /// \name Vector Target Information
321   /// @{
322
323   /// \brief The various kinds of shuffle patterns for vector queries.
324   enum ShuffleKind {
325     SK_Broadcast,       ///< Broadcast element 0 to all other elements.
326     SK_Reverse,         ///< Reverse the order of the vector.
327     SK_Alternate,       ///< Choose alternate elements from vector.
328     SK_InsertSubvector, ///< InsertSubvector. Index indicates start offset.
329     SK_ExtractSubvector ///< ExtractSubvector Index indicates start offset.
330   };
331
332   /// \brief Additional information about an operand's possible values.
333   enum OperandValueKind {
334     OK_AnyValue,                 // Operand can have any value.
335     OK_UniformValue,             // Operand is uniform (splat of a value).
336     OK_UniformConstantValue,     // Operand is uniform constant.
337     OK_NonUniformConstantValue   // Operand is a non uniform constant value.
338   };
339
340   /// \brief Additional properties of an operand's values.
341   enum OperandValueProperties { OP_None = 0, OP_PowerOf2 = 1 };
342
343   /// \return The number of scalar or vector registers that the target has.
344   /// If 'Vectors' is true, it returns the number of vector registers. If it is
345   /// set to false, it returns the number of scalar registers.
346   virtual unsigned getNumberOfRegisters(bool Vector) const;
347
348   /// \return The width of the largest scalar or vector register type.
349   virtual unsigned getRegisterBitWidth(bool Vector) const;
350
351   /// \return The maximum interleave factor that any transform should try to
352   /// perform for this target. This number depends on the level of parallelism
353   /// and the number of execution units in the CPU.
354   virtual unsigned getMaxInterleaveFactor() const;
355
356   /// \return The expected cost of arithmetic ops, such as mul, xor, fsub, etc.
357   virtual unsigned
358   getArithmeticInstrCost(unsigned Opcode, Type *Ty,
359                          OperandValueKind Opd1Info = OK_AnyValue,
360                          OperandValueKind Opd2Info = OK_AnyValue,
361                          OperandValueProperties Opd1PropInfo = OP_None,
362                          OperandValueProperties Opd2PropInfo = OP_None) const;
363
364   /// \return The cost of a shuffle instruction of kind Kind and of type Tp.
365   /// The index and subtype parameters are used by the subvector insertion and
366   /// extraction shuffle kinds.
367   virtual unsigned getShuffleCost(ShuffleKind Kind, Type *Tp, int Index = 0,
368                                   Type *SubTp = nullptr) const;
369
370   /// \return The expected cost of cast instructions, such as bitcast, trunc,
371   /// zext, etc.
372   virtual unsigned getCastInstrCost(unsigned Opcode, Type *Dst,
373                                     Type *Src) const;
374
375   /// \return The expected cost of control-flow related instructions such as
376   /// Phi, Ret, Br.
377   virtual unsigned getCFInstrCost(unsigned Opcode) const;
378
379   /// \returns The expected cost of compare and select instructions.
380   virtual unsigned getCmpSelInstrCost(unsigned Opcode, Type *ValTy,
381                                       Type *CondTy = nullptr) const;
382
383   /// \return The expected cost of vector Insert and Extract.
384   /// Use -1 to indicate that there is no information on the index value.
385   virtual unsigned getVectorInstrCost(unsigned Opcode, Type *Val,
386                                       unsigned Index = -1) const;
387
388   /// \return The cost of Load and Store instructions.
389   virtual unsigned getMemoryOpCost(unsigned Opcode, Type *Src,
390                                    unsigned Alignment,
391                                    unsigned AddressSpace) const;
392
393   /// \brief Calculate the cost of performing a vector reduction.
394   ///
395   /// This is the cost of reducing the vector value of type \p Ty to a scalar
396   /// value using the operation denoted by \p Opcode. The form of the reduction
397   /// can either be a pairwise reduction or a reduction that splits the vector
398   /// at every reduction level.
399   ///
400   /// Pairwise:
401   ///  (v0, v1, v2, v3)
402   ///  ((v0+v1), (v2, v3), undef, undef)
403   /// Split:
404   ///  (v0, v1, v2, v3)
405   ///  ((v0+v2), (v1+v3), undef, undef)
406   virtual unsigned getReductionCost(unsigned Opcode, Type *Ty,
407                                     bool IsPairwiseForm) const;
408
409   /// \returns The cost of Intrinsic instructions.
410   virtual unsigned getIntrinsicInstrCost(Intrinsic::ID ID, Type *RetTy,
411                                          ArrayRef<Type *> Tys) const;
412
413   /// \returns The number of pieces into which the provided type must be
414   /// split during legalization. Zero is returned when the answer is unknown.
415   virtual unsigned getNumberOfParts(Type *Tp) const;
416
417   /// \returns The cost of the address computation. For most targets this can be
418   /// merged into the instruction indexing mode. Some targets might want to
419   /// distinguish between address computation for memory operations on vector
420   /// types and scalar types. Such targets should override this function.
421   /// The 'IsComplex' parameter is a hint that the address computation is likely
422   /// to involve multiple instructions and as such unlikely to be merged into
423   /// the address indexing mode.
424   virtual unsigned getAddressComputationCost(Type *Ty,
425                                              bool IsComplex = false) const;
426
427   /// \returns The cost, if any, of keeping values of the given types alive
428   /// over a callsite.
429   ///
430   /// Some types may require the use of register classes that do not have
431   /// any callee-saved registers, so would require a spill and fill.
432   virtual unsigned getCostOfKeepingLiveOverCall(ArrayRef<Type*> Tys) const;
433
434   /// @}
435
436   /// Analysis group identification.
437   static char ID;
438 };
439
440 /// \brief Create the base case instance of a pass in the TTI analysis group.
441 ///
442 /// This class provides the base case for the stack of TTI analyzes. It doesn't
443 /// delegate to anything and uses the STTI and VTTI objects passed in to
444 /// satisfy the queries.
445 ImmutablePass *createNoTargetTransformInfoPass();
446
447 } // End llvm namespace
448
449 #endif