Add InstCount Pass Before Optimization (#198874)

This way we can count instructions before the optimization pipeline for
analysis sake
This commit is contained in:
Iñaki V Arrechea 2026-05-20 17:52:28 -06:00 committed by GitHub
parent 1da21d72f0
commit c25924f92d
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
7 changed files with 142 additions and 21 deletions

View file

@ -20,8 +20,11 @@ namespace llvm {
class Function;
class InstCountPass : public RequiredPassInfoMixin<InstCountPass> {
bool IsPreOptimization;
public:
explicit InstCountPass() {}
explicit InstCountPass(bool IsPreOptimization = false)
: IsPreOptimization(IsPreOptimization) {}
PreservedAnalyses run(Function &F, FunctionAnalysisManager &FAM);
};

View file

@ -21,16 +21,33 @@ using namespace llvm;
#define DEBUG_TYPE "instcount"
STATISTIC(TotalInsts, "Number of instructions (of all types)");
STATISTIC(TotalInsts, "Number of instructions of all types");
STATISTIC(TotalBlocks, "Number of basic blocks");
STATISTIC(TotalFuncs, "Number of non-external functions");
STATISTIC(LargestFunctionSize,
"Largest number of instructions in a single function");
STATISTIC(LargestFunctionBBCount,
"Largest number of basic blocks in a single function");
STATISTIC(TotalInstsPreOptimization,
"Number of instructions of all types (before optimizations)");
STATISTIC(TotalBlocksPreOptimization,
"Number of basic blocks (before optimizations)");
STATISTIC(TotalFuncsPreOptimization,
"Number of non-external functions (before optimizations)");
STATISTIC(LargestFunctionSizePreOptimization,
"Largest number of instructions in a single function (before "
"optimizations)");
STATISTIC(LargestFunctionBBCountPreOptimization,
"Largest number of basic blocks in a single function (before "
"optimizations)");
#define HANDLE_INST(N, OPCODE, CLASS) \
STATISTIC(Num##OPCODE##Inst, "Number of " #OPCODE " insts");
STATISTIC(Num##OPCODE##Inst, "Number of " #OPCODE " insts"); \
STATISTIC(Num##OPCODE##InstPreOptimization, \
"Number of " #OPCODE " insts (before optimizations)");
#include "llvm/IR/Instruction.def"
@ -38,17 +55,36 @@ namespace {
class InstCount : public InstVisitor<InstCount> {
friend class InstVisitor<InstCount>;
bool IsPreOptimization;
void visitFunction(Function &F) {
++TotalFuncs;
LargestFunctionSize.updateMax(F.getInstructionCount());
LargestFunctionBBCount.updateMax(F.size());
if (IsPreOptimization) {
++TotalFuncsPreOptimization;
LargestFunctionSizePreOptimization.updateMax(F.getInstructionCount());
LargestFunctionBBCountPreOptimization.updateMax(F.size());
} else {
++TotalFuncs;
LargestFunctionSize.updateMax(F.getInstructionCount());
LargestFunctionBBCount.updateMax(F.size());
}
}
void visitBasicBlock(BasicBlock &BB) {
if (IsPreOptimization)
++TotalBlocksPreOptimization;
else
++TotalBlocks;
}
void visitBasicBlock(BasicBlock &BB) { ++TotalBlocks; }
#define HANDLE_INST(N, OPCODE, CLASS) \
void visit##OPCODE(CLASS &) { \
++Num##OPCODE##Inst; \
++TotalInsts; \
if (IsPreOptimization) { \
++Num##OPCODE##InstPreOptimization; \
++TotalInstsPreOptimization; \
} else { \
++Num##OPCODE##Inst; \
++TotalInsts; \
} \
}
#include "llvm/IR/Instruction.def"
@ -57,6 +93,10 @@ class InstCount : public InstVisitor<InstCount> {
errs() << "Instruction Count does not know about " << I;
llvm_unreachable(nullptr);
}
public:
InstCount(bool IsPreOptimization = false)
: IsPreOptimization(IsPreOptimization) {}
};
} // namespace
@ -64,7 +104,7 @@ PreservedAnalyses InstCountPass::run(Function &F,
FunctionAnalysisManager &FAM) {
LLVM_DEBUG(dbgs() << "INSTCOUNT: running on function " << F.getName()
<< "\n");
InstCount().visit(F);
InstCount(this->IsPreOptimization).visit(F);
return PreservedAnalyses::all();
}

View file

@ -831,6 +831,11 @@ Expected<bool> parseLintOptions(StringRef Params) {
"LintPass");
}
/// Parser of parameters for InstCount pass.
Expected<bool> parseInstCountOptions(StringRef Params) {
return PassBuilder::parseSinglePassOption(Params, "pre-opt", "InstCountPass");
}
/// Parser of parameters for LoopUnroll pass.
Expected<LoopUnrollOptions> parseLoopUnrollOptions(StringRef Params) {
LoopUnrollOptions UnrollOpts;

View file

@ -418,12 +418,19 @@ void PassBuilder::invokePipelineEarlySimplificationEPCallbacks(
C(MPM, Level, Phase);
}
// Get IR stats with InstCount before/after the optimization pipeline
static void instructionCountersPass(ModulePassManager &MPM,
bool IsPreOptimization) {
if (AreStatisticsEnabled()) {
MPM.addPass(
createModuleToFunctionPassAdaptor(InstCountPass(IsPreOptimization)));
}
}
// Helper to add AnnotationRemarksPass.
static void addAnnotationRemarksPass(ModulePassManager &MPM) {
MPM.addPass(createModuleToFunctionPassAdaptor(AnnotationRemarksPass()));
// Count the stats for InstCount and FunctionPropertiesAnalysis
if (AreStatisticsEnabled()) {
MPM.addPass(createModuleToFunctionPassAdaptor(InstCountPass()));
MPM.addPass(
createModuleToFunctionPassAdaptor(FunctionPropertiesStatisticsPass()));
}
@ -1732,7 +1739,7 @@ PassBuilder::buildPerModuleDefaultPipeline(OptimizationLevel Level,
return buildO0DefaultPipeline(Level, Phase);
ModulePassManager MPM;
instructionCountersPass(MPM, /* IsPreOptimization */ true);
// Currently this pipeline is only invoked in an LTO pre link pass or when we
// are not running LTO. If that changes the below checks may need updating.
assert(isLTOPreLink(Phase) || Phase == ThinOrFullLTOPhase::None);
@ -1770,6 +1777,8 @@ PassBuilder::buildPerModuleDefaultPipeline(OptimizationLevel Level,
if (isLTOPreLink(Phase))
addRequiredLTOPreLinkPasses(MPM);
instructionCountersPass(MPM, /* IsPreOptimization */ false);
return MPM;
}
@ -1777,6 +1786,9 @@ ModulePassManager
PassBuilder::buildFatLTODefaultPipeline(OptimizationLevel Level, bool ThinLTO,
bool EmitSummary) {
ModulePassManager MPM;
instructionCountersPass(MPM, /* IsPreOptimization */ true);
if (ThinLTO)
MPM.addPass(buildThinLTOPreLinkDefaultPipeline(Level));
else
@ -1818,6 +1830,9 @@ PassBuilder::buildFatLTODefaultPipeline(OptimizationLevel Level, bool ThinLTO,
// Emit annotation remarks.
addAnnotationRemarksPass(MPM);
}
instructionCountersPass(MPM, /* IsPreOptimization */ false);
return MPM;
}
@ -1828,6 +1843,8 @@ PassBuilder::buildThinLTOPreLinkDefaultPipeline(OptimizationLevel Level) {
ModulePassManager MPM;
instructionCountersPass(MPM, /* IsPreOptimization */ true);
// Convert @llvm.global.annotations to !annotation metadata.
MPM.addPass(Annotation2MetadataPass());
@ -1880,6 +1897,8 @@ PassBuilder::buildThinLTOPreLinkDefaultPipeline(OptimizationLevel Level) {
addRequiredLTOPreLinkPasses(MPM);
instructionCountersPass(MPM, /* IsPreOptimization */ false);
return MPM;
}
@ -1887,6 +1906,8 @@ ModulePassManager PassBuilder::buildThinLTODefaultPipeline(
OptimizationLevel Level, const ModuleSummaryIndex *ImportSummary) {
ModulePassManager MPM;
instructionCountersPass(MPM, /* IsPreOptimization */ true);
// If we are invoking this without a summary index noting that we are linking
// with a library containing the necessary APIs, remove any MemProf related
// attributes and metadata.
@ -1951,6 +1972,8 @@ ModulePassManager PassBuilder::buildThinLTODefaultPipeline(
// Emit annotation remarks.
addAnnotationRemarksPass(MPM);
instructionCountersPass(MPM, /* IsPreOptimization */ false);
return MPM;
}
@ -1966,6 +1989,8 @@ PassBuilder::buildLTODefaultPipeline(OptimizationLevel Level,
ModuleSummaryIndex *ExportSummary) {
ModulePassManager MPM;
instructionCountersPass(MPM, /* IsPreOptimization */ true);
invokeFullLinkTimeOptimizationEarlyEPCallbacks(MPM, Level);
// If we are invoking this without a summary index noting that we are linking
@ -2086,6 +2111,8 @@ PassBuilder::buildLTODefaultPipeline(OptimizationLevel Level,
// Emit annotation remarks.
addAnnotationRemarksPass(MPM);
instructionCountersPass(MPM, /* IsPreOptimization */ false);
return MPM;
}
@ -2323,6 +2350,8 @@ PassBuilder::buildLTODefaultPipeline(OptimizationLevel Level,
// Emit annotation remarks.
addAnnotationRemarksPass(MPM);
instructionCountersPass(MPM, /* IsPreOptimization */ false);
return MPM;
}
@ -2334,6 +2363,8 @@ PassBuilder::buildO0DefaultPipeline(OptimizationLevel Level,
ModulePassManager MPM;
instructionCountersPass(MPM, /* IsPreOptimization */ true);
// Perform pseudo probe instrumentation in O0 mode. This is for the
// consistency between different build modes. For example, a LTO build can be
// mixed with an O0 prelink and an O2 postlink. Loading a sample profile in
@ -2450,6 +2481,8 @@ PassBuilder::buildO0DefaultPipeline(OptimizationLevel Level,
// Emit annotation remarks.
addAnnotationRemarksPass(MPM);
instructionCountersPass(MPM, /* IsPreOptimization */ false);
return MPM;
}

View file

@ -461,7 +461,6 @@ FUNCTION_PASS("infer-address-spaces", InferAddressSpacesPass())
FUNCTION_PASS("infer-alignment", InferAlignmentPass())
FUNCTION_PASS("inject-tli-mappings", InjectTLIMappings())
FUNCTION_PASS("inline-asm-prepare", InlineAsmPreparePass())
FUNCTION_PASS("instcount", InstCountPass())
FUNCTION_PASS("instnamer", InstructionNamerPass())
FUNCTION_PASS("instsimplify", InstSimplifyPass())
FUNCTION_PASS("interleaved-access", InterleavedAccessPass(*TM))
@ -618,6 +617,12 @@ FUNCTION_PASS_WITH_PARAMS(
[](InstCombineOptions Opts) { return InstCombinePass(Opts); },
parseInstCombineOptions,
"no-verify-fixpoint;verify-fixpoint;max-iterations=N")
FUNCTION_PASS_WITH_PARAMS(
"instcount", "InstCountPass",
[](bool IsPreOptimizations) {
return InstCountPass(IsPreOptimizations);
},
parseInstCountOptions, "pre-opt")
FUNCTION_PASS_WITH_PARAMS(
"lint", "LintPass",
[](bool AbortOnError) { return LintPass(AbortOnError); }, parseLintOptions,

View file

@ -1,11 +1,5 @@
; REQUIRES: asserts
; RUN: opt -stats -passes=instcount -disable-output < %s 2>&1 | FileCheck %s
; RUN: opt -stats -passes='thinlto<O3>' -disable-output < %s 2>&1 | FileCheck %s
; RUN: opt -stats -passes='thinlto-pre-link<O2>' -disable-output < %s 2>&1 | FileCheck %s
; RUN: opt -stats -passes='lto<O1>' -disable-output < %s 2>&1 | FileCheck %s
; RUN: opt -stats -passes='lto-pre-link<O2>' -disable-output < %s 2>&1 | FileCheck %s
; RUN: opt -stats -O3 -disable-output < %s 2>&1 | FileCheck %s
; RUN: opt -stats -O0 -disable-output < %s 2>&1 | FileCheck %s
; CHECK-DAG: 10 instcount - Largest number of basic blocks in a single function
; CHECK-DAG: 18 instcount - Largest number of instructions in a single function
@ -17,7 +11,7 @@
; CHECK-DAG: 1 instcount - Number of Switch insts
; CHECK-DAG: 11 instcount - Number of basic blocks
; CHECK-DAG: 2 instcount - Number of non-external functions
; CHECK-DAG: 19 instcount - Number of instructions (of all types)
; CHECK-DAG: 19 instcount - Number of instructions of all types
define void @foo(i32 %i, i32 %j, i32 %n) {
entry:

View file

@ -0,0 +1,41 @@
; REQUIRES: asserts
; RUN: opt -stats -disable-output -passes='instcount<pre-opt>' < %s 2>&1 | FileCheck %s --check-prefix=PRE
; RUN: opt -stats -disable-output -passes='instcount' < %s 2>&1 | FileCheck %s --check-prefixes=POSTNOOPT
; RUN: opt -stats -disable-output -O0 < %s 2>&1 | FileCheck %s --check-prefixes=PRE,POSTNOOPT
; RUN: opt -stats -disable-output -O3 < %s 2>&1 | FileCheck %s --check-prefixes=PRE,POST
; RUN: opt -stats -disable-output -passes='lto<O3>' < %s 2>&1 | FileCheck %s --check-prefixes=PRE,POST
; RUN: opt -stats -disable-output -passes='lto-pre-link<O2>' < %s 2>&1 | FileCheck %s --check-prefixes=PRE,POST
; RUN: opt -stats -disable-output -passes='lto-pre-link<O3>' < %s 2>&1 | FileCheck %s --check-prefixes=PRE,POST
; RUN: opt -stats -disable-output -passes='thinlto<O3>' < %s 2>&1 | FileCheck %s --check-prefixes=PRE,POST
; RUN: opt -stats -disable-output -passes='thinlto-pre-link<O2>' < %s 2>&1 | FileCheck %s --check-prefixes=PRE,POST
; --- <pre-opt> ---
; PRE-DAG: 4 instcount - Number of basic blocks (before optimizations)
; PRE-DAG: 5 instcount - Number of instructions of all types (before optimizations)
; PRE-DAG: 1 instcount - Number of CondBr insts (before optimizations)
; --- No <pre-opt> in pass but no optimization passes run ---
; POSTNOOPT-DAG: 4 instcount - Number of basic blocks
; POSTNOOPT-DAG: 5 instcount - Number of instructions of all types
; POSTNOOPT-DAG: 1 instcount - Number of CondBr insts
; --- Post optimization values ---
; POST-DAG: 1 instcount - Number of basic blocks
; POST-DAG: 1 instcount - Number of instructions of all types
; POST-NOT: instcount - Number of CondBr insts
define i32 @test_count() {
entry:
; This branch is trivially resolvable
br i1 true, label %then, label %else
then:
br label %end
else:
br label %end
end:
%phi = phi i32 [ 1, %then ], [ 2, %else ]
ret i32 %phi
}