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