LLVM 17.0.0git
CostModel.cpp
Go to the documentation of this file.
1//===- CostModel.cpp ------ Cost Model Analysis ---------------------------===//
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//
9// This file defines the cost model analysis. It provides a very basic cost
10// estimation for LLVM-IR. This analysis uses the services of the codegen
11// to approximate the cost of any IR instruction when lowered to machine
12// instructions. The cost results are unit-less and the cost number represents
13// the throughput of the machine assuming that all loads hit the cache, all
14// branches are predicted, etc. The cost numbers can be added in order to
15// compare two or more transformation alternatives.
16//
17//===----------------------------------------------------------------------===//
18
22#include "llvm/IR/Function.h"
23#include "llvm/IR/PassManager.h"
25#include "llvm/Pass.h"
29using namespace llvm;
30
32 "cost-kind", cl::desc("Target cost kind"),
35 "throughput", "Reciprocal throughput"),
37 "latency", "Instruction latency"),
39 "code-size", "Code size"),
41 "size-latency", "Code size and latency")));
42
43static cl::opt<bool> TypeBasedIntrinsicCost("type-based-intrinsic-cost",
44 cl::desc("Calculate intrinsics cost based only on argument types"),
45 cl::init(false));
46
47#define CM_NAME "cost-model"
48#define DEBUG_TYPE CM_NAME
49
50namespace {
51 class CostModelAnalysis : public FunctionPass {
52
53 public:
54 static char ID; // Class identification, replacement for typeinfo
55 CostModelAnalysis() : FunctionPass(ID) {
58 }
59
60 private:
61 void getAnalysisUsage(AnalysisUsage &AU) const override;
62 bool runOnFunction(Function &F) override;
63 void print(raw_ostream &OS, const Module*) const override;
64
65 /// The function that we analyze.
66 Function *F = nullptr;
67 /// Target information.
68 const TargetTransformInfo *TTI = nullptr;
69 };
70} // End of anonymous namespace
71
72// Register this pass.
73char CostModelAnalysis::ID = 0;
74static const char cm_name[] = "Cost Model Analysis";
75INITIALIZE_PASS_BEGIN(CostModelAnalysis, CM_NAME, cm_name, false, true)
76INITIALIZE_PASS_END (CostModelAnalysis, CM_NAME, cm_name, false, true)
77
79 return new CostModelAnalysis();
80}
81
82void
83CostModelAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
84 AU.setPreservesAll();
85}
86
87bool
88CostModelAnalysis::runOnFunction(Function &F) {
89 this->F = &F;
90 auto *TTIWP = getAnalysisIfAvailable<TargetTransformInfoWrapperPass>();
91 TTI = TTIWP ? &TTIWP->getTTI(F) : nullptr;
92
93 return false;
94}
95
96void CostModelAnalysis::print(raw_ostream &OS, const Module*) const {
97 if (!F)
98 return;
99
100 for (BasicBlock &B : *F) {
101 for (Instruction &Inst : B) {
103 auto *II = dyn_cast<IntrinsicInst>(&Inst);
104 if (II && TypeBasedIntrinsicCost) {
105 IntrinsicCostAttributes ICA(II->getIntrinsicID(), *II,
108 }
109 else {
111 }
112
113 if (auto CostVal = Cost.getValue())
114 OS << "Cost Model: Found an estimated cost of " << *CostVal;
115 else
116 OS << "Cost Model: Invalid cost";
117
118 OS << " for instruction: " << Inst << "\n";
119 }
120 }
121}
122
125 auto &TTI = AM.getResult<TargetIRAnalysis>(F);
126 OS << "Printing analysis 'Cost Model Analysis' for function '" << F.getName() << "':\n";
127 for (BasicBlock &B : F) {
128 for (Instruction &Inst : B) {
129 // TODO: Use a pass parameter instead of cl::opt CostKind to determine
130 // which cost kind to print.
132 auto *II = dyn_cast<IntrinsicInst>(&Inst);
133 if (II && TypeBasedIntrinsicCost) {
134 IntrinsicCostAttributes ICA(II->getIntrinsicID(), *II,
137 }
138 else {
140 }
141
142 if (auto CostVal = Cost.getValue())
143 OS << "Cost Model: Found an estimated cost of " << *CostVal;
144 else
145 OS << "Cost Model: Invalid cost";
146
147 OS << " for instruction: " << Inst << "\n";
148 }
149 }
150 return PreservedAnalyses::all();
151}
basic Basic Alias true
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define clEnumValN(ENUMVAL, FLAGNAME, DESC)
Definition: CommandLine.h:678
static cl::opt< TargetTransformInfo::TargetCostKind > CostKind("cost-kind", cl::desc("Target cost kind"), cl::init(TargetTransformInfo::TCK_RecipThroughput), cl::values(clEnumValN(TargetTransformInfo::TCK_RecipThroughput, "throughput", "Reciprocal throughput"), clEnumValN(TargetTransformInfo::TCK_Latency, "latency", "Instruction latency"), clEnumValN(TargetTransformInfo::TCK_CodeSize, "code-size", "Code size"), clEnumValN(TargetTransformInfo::TCK_SizeAndLatency, "size-latency", "Code size and latency")))
static cl::opt< bool > TypeBasedIntrinsicCost("type-based-intrinsic-cost", cl::desc("Calculate intrinsics cost based only on argument types"), cl::init(false))
static const char cm_name[]
Definition: CostModel.cpp:74
#define CM_NAME
Definition: CostModel.cpp:47
#define F(x, y, z)
Definition: MD5.cpp:55
This header defines various interfaces for pass management in LLVM.
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition: PassSupport.h:59
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition: PassSupport.h:52
raw_pwrite_stream & OS
This pass exposes codegen information to IR-level passes.
A container for analyses that lazily runs them and caches their results.
Definition: PassManager.h:620
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Definition: PassManager.h:774
Represent the analysis usage information of a pass.
void setPreservesAll()
Set by analyses that do not transform their input at all.
LLVM Basic Block Representation.
Definition: BasicBlock.h:56
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
Definition: CostModel.cpp:123
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:311
virtual bool runOnFunction(Function &F)=0
runOnFunction - Virtual method overriden by subclasses to do the per-function processing of the pass.
static InstructionCost getInvalid(CostType Val=0)
std::optional< CostType > getValue() const
This function is intended to be used as sparingly as possible, since the class provides the full rang...
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:65
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
virtual void print(raw_ostream &OS, const Module *M) const
print - Print out the internal state of the pass.
Definition: Pass.cpp:130
virtual void getAnalysisUsage(AnalysisUsage &) const
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
Definition: Pass.cpp:98
A set of analyses that are preserved following a run of a transformation pass.
Definition: PassManager.h:152
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: PassManager.h:158
Analysis pass providing the TargetTransformInfo.
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
InstructionCost getIntrinsicInstrCost(const IntrinsicCostAttributes &ICA, TTI::TargetCostKind CostKind) const
@ TCK_RecipThroughput
Reciprocal throughput.
@ TCK_CodeSize
Instruction code size.
@ TCK_SizeAndLatency
The weighted sum of size and latency.
@ TCK_Latency
The latency of instruction.
InstructionCost getInstructionCost(const User *U, ArrayRef< const Value * > Operands, TargetCostKind CostKind) const
Estimate the cost of a given IR user when lowered.
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition: raw_ostream.h:52
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition: CallingConv.h:24
ValuesClass values(OptsTy... Options)
Helper to build a ValuesClass by forwarding a variable number of arguments as an initializer list to ...
Definition: CommandLine.h:703
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:445
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
void initializeCostModelAnalysisPass(PassRegistry &)
InstructionCost Cost
FunctionPass * createCostModelAnalysisPass()
Definition: CostModel.cpp:78