forked from HabKaffee/tttc_practice
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathImplictCounter.cpp
More file actions
93 lines (73 loc) · 2.67 KB
/
Copy pathImplictCounter.cpp
File metadata and controls
93 lines (73 loc) · 2.67 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
#include "clang/AST/AST.h"
#include "clang/AST/ASTConsumer.h"
#include "clang/AST/RecursiveASTVisitor.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Frontend/FrontendPluginRegistry.h"
#include "llvm/Support/raw_ostream.h"
using namespace clang;
namespace {
class CastVisitor : public RecursiveASTVisitor<CastVisitor> {
public:
explicit CastVisitor(ASTContext *Context) : Context(Context) {}
bool VisitImplicitCastExpr(ImplicitCastExpr *ICE) {
if (!ICE->getBeginLoc().isValid()) return true;
QualType FromType = ICE->getSubExpr()->getType();
QualType ToType = ICE->getType();
std::string FromStr = FromType.getAsString();
std::string ToStr = ToType.getAsString();
CurrentFunctionCasts[FromStr + " -> " + ToStr]++;
return true;
}
void SetCurrentFunction(const FunctionDecl *FD) {
CurrentFunction = FD;
CurrentFunctionCasts.clear();
}
void PrintAndResetCounts() {
if (!CurrentFunction || CurrentFunctionCasts.empty()) return;
llvm::outs() << "Function `" << CurrentFunction->getName() << "`\n";
for (const auto &Pair : CurrentFunctionCasts) {
llvm::outs() << Pair.first << ": " << Pair.second << "\n";
}
llvm::outs() << "\n";
}
private:
ASTContext *Context;
const FunctionDecl *CurrentFunction = nullptr;
std::map<std::string, int> CurrentFunctionCasts;
};
class CastCounterConsumer : public ASTConsumer {
public:
explicit CastCounterConsumer(ASTContext *Context) : Visitor(Context) {}
void HandleTranslationUnit(ASTContext &Context) override {
TraverseDecls(Context.getTranslationUnitDecl());
}
void TraverseDecls(Decl *D) {
if (!D) return;
if (auto *FD = dyn_cast<FunctionDecl>(D)) {
Visitor.SetCurrentFunction(FD);
Visitor.TraverseDecl(D);
Visitor.PrintAndResetCounts();
}
if (auto *DC = dyn_cast<DeclContext>(D)) {
for (auto *Child : DC->decls()) {
TraverseDecls(Child);
}
}
}
private:
CastVisitor Visitor;
};
class CastCounterAction : public PluginASTAction {
protected:
std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
llvm::StringRef) override {
return std::make_unique<CastCounterConsumer>(&CI.getASTContext());
}
bool ParseArgs(const CompilerInstance &CI,
const std::vector<std::string> &args) override {
return true;
}
};
}
static FrontendPluginRegistry::Add<CastCounterAction>
X("implicit-cast-counter", "Count implicit type conversions");