LLVM  14.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 
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/Analysis/Passes.h"
23 #include "llvm/IR/Function.h"
24 #include "llvm/IR/PassManager.h"
25 #include "llvm/InitializePasses.h"
26 #include "llvm/Pass.h"
28 #include "llvm/Support/Debug.h"
30 using namespace llvm;
31 
33  "cost-kind", cl::desc("Target cost kind"),
36  "throughput", "Reciprocal throughput"),
38  "latency", "Instruction latency"),
40  "code-size", "Code size"),
42  "size-latency", "Code size and latency")));
43 
44 
45 #define CM_NAME "cost-model"
46 #define DEBUG_TYPE CM_NAME
47 
48 namespace {
49  class CostModelAnalysis : public FunctionPass {
50 
51  public:
52  static char ID; // Class identification, replacement for typeinfo
53  CostModelAnalysis() : FunctionPass(ID), F(nullptr), TTI(nullptr) {
56  }
57 
58  /// Returns the expected cost of the instruction.
59  /// Returns -1 if the cost is unknown.
60  /// Note, this method does not cache the cost calculation and it
61  /// can be expensive in some cases.
62  InstructionCost getInstructionCost(const Instruction *I) const {
64  }
65 
66  private:
67  void getAnalysisUsage(AnalysisUsage &AU) const override;
68  bool runOnFunction(Function &F) override;
69  void print(raw_ostream &OS, const Module*) const override;
70 
71  /// The function that we analyze.
72  Function *F;
73  /// Target information.
74  const TargetTransformInfo *TTI;
75  };
76 } // End of anonymous namespace
77 
78 // Register this pass.
79 char CostModelAnalysis::ID = 0;
80 static const char cm_name[] = "Cost Model Analysis";
81 INITIALIZE_PASS_BEGIN(CostModelAnalysis, CM_NAME, cm_name, false, true)
82 INITIALIZE_PASS_END (CostModelAnalysis, CM_NAME, cm_name, false, true)
83 
85  return new CostModelAnalysis();
86 }
87 
88 void
89 CostModelAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
90  AU.setPreservesAll();
91 }
92 
93 bool
95  this->F = &F;
96  auto *TTIWP = getAnalysisIfAvailable<TargetTransformInfoWrapperPass>();
97  TTI = TTIWP ? &TTIWP->getTTI(F) : nullptr;
98 
99  return false;
100 }
101 
102 void CostModelAnalysis::print(raw_ostream &OS, const Module*) const {
103  if (!F)
104  return;
105 
106  for (BasicBlock &B : *F) {
107  for (Instruction &Inst : B) {
109  if (auto CostVal = Cost.getValue())
110  OS << "Cost Model: Found an estimated cost of " << *CostVal;
111  else
112  OS << "Cost Model: Invalid cost";
113 
114  OS << " for instruction: " << Inst << "\n";
115  }
116  }
117 }
118 
121  auto &TTI = AM.getResult<TargetIRAnalysis>(F);
122  OS << "Cost Model for function '" << F.getName() << "'\n";
123  for (BasicBlock &B : F) {
124  for (Instruction &Inst : B) {
125  // TODO: Use a pass parameter instead of cl::opt CostKind to determine
126  // which cost kind to print.
128  if (auto CostVal = Cost.getValue())
129  OS << "Cost Model: Found an estimated cost of " << *CostVal;
130  else
131  OS << "Cost Model: Invalid cost";
132 
133  OS << " for instruction: " << Inst << "\n";
134  }
135  }
136  return PreservedAnalyses::all();
137 }
llvm::InstructionCost
Definition: InstructionCost.h:29
llvm::PreservedAnalyses
A set of analyses that are preserved following a run of a transformation pass.
Definition: PassManager.h:155
llvm::TargetIRAnalysis
Analysis pass providing the TargetTransformInfo.
Definition: TargetTransformInfo.h:2331
llvm
---------------------— PointerInfo ------------------------------------—
Definition: AllocatorList.h:23
llvm::InstructionCost::getValue
Optional< CostType > getValue() const
This function is intended to be used as sparingly as possible, since the class provides the full rang...
Definition: InstructionCost.h:87
llvm::TargetTransformInfo::TCK_Latency
@ TCK_Latency
The latency of instruction.
Definition: TargetTransformInfo.h:213
print
static void print(raw_ostream &Out, object::Archive::Kind Kind, T Val)
Definition: ArchiveWriter.cpp:147
llvm::AnalysisManager::getResult
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Definition: PassManager.h:779
llvm::Function
Definition: Function.h:61
Pass.h
llvm::TargetTransformInfo
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
Definition: TargetTransformInfo.h:168
llvm::TargetTransformInfo::TCK_CodeSize
@ TCK_CodeSize
Instruction code size.
Definition: TargetTransformInfo.h:214
STLExtras.h
F
#define F(x, y, z)
Definition: MD5.cpp:56
llvm::BasicBlock
LLVM Basic Block Representation.
Definition: BasicBlock.h:58
CommandLine.h
llvm::PassRegistry::getPassRegistry
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
Definition: PassRegistry.cpp:31
llvm::CostModelPrinterPass::run
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
Definition: CostModel.cpp:119
llvm::AnalysisUsage
Represent the analysis usage information of a pass.
Definition: PassAnalysisSupport.h:47
false
Definition: StackSlotColoring.cpp:142
B
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
llvm::Instruction
Definition: Instruction.h:45
llvm::raw_ostream
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition: raw_ostream.h:53
llvm::createCostModelAnalysisPass
FunctionPass * createCostModelAnalysisPass()
Definition: CostModel.cpp:84
INITIALIZE_PASS_END
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition: PassSupport.h:58
llvm::cl::opt
Definition: CommandLine.h:1434
llvm::cl::values
ValuesClass values(OptsTy... Options)
Helper to build a ValuesClass by forwarding a variable number of arguments as an initializer list to ...
Definition: CommandLine.h:699
cm_name
static const char cm_name[]
Definition: CostModel.cpp:80
I
#define I(x, y, z)
Definition: MD5.cpp:59
llvm::cl::init
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:443
llvm::TTI
TargetTransformInfo TTI
Definition: TargetTransformInfo.h:163
llvm::Module
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:67
llvm::TargetTransformInfo::TCK_SizeAndLatency
@ TCK_SizeAndLatency
The weighted sum of size and latency.
Definition: TargetTransformInfo.h:215
CostKind
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")))
clEnumValN
#define clEnumValN(ENUMVAL, FLAGNAME, DESC)
Definition: CommandLine.h:674
CostModel.h
runOnFunction
static bool runOnFunction(Function &F, bool PostInlining)
Definition: EntryExitInstrumenter.cpp:69
llvm::AnalysisUsage::setPreservesAll
void setPreservesAll()
Set by analyses that do not transform their input at all.
Definition: PassAnalysisSupport.h:130
llvm::PreservedAnalyses::all
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: PassManager.h:161
Function.h
PassManager.h
llvm::TargetTransformInfo::getInstructionCost
InstructionCost getInstructionCost(const Instruction *I, enum TargetCostKind kind) const
Query the cost of a specified instruction.
Definition: TargetTransformInfo.h:225
INITIALIZE_PASS_BEGIN
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition: PassSupport.h:51
TargetTransformInfo.h
llvm::AnalysisManager
A container for analyses that lazily runs them and caches their results.
Definition: InstructionSimplify.h:44
llvm::FunctionPass
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:298
llvm::cl::desc
Definition: CommandLine.h:414
raw_ostream.h
true
basic Basic Alias true
Definition: BasicAliasAnalysis.cpp:1815
llvm::initializeCostModelAnalysisPass
void initializeCostModelAnalysisPass(PassRegistry &)
CM_NAME
#define CM_NAME
Definition: CostModel.cpp:45
InitializePasses.h
llvm::TargetTransformInfo::TCK_RecipThroughput
@ TCK_RecipThroughput
Reciprocal throughput.
Definition: TargetTransformInfo.h:212
Debug.h
Passes.h
llvm::Intrinsic::ID
unsigned ID
Definition: TargetTransformInfo.h:37