blob: 476b5e6a4bbe20b7578413a6f95c238892bf3d85 [file] [log] [blame]
Jonas Devlieghereedff5f42019-02-06 04:33:14 +00001#include "clang/AST/AST.h"
2#include "clang/AST/ASTConsumer.h"
3#include "clang/AST/RecursiveASTVisitor.h"
Jonas Devlieghere1ca9dd82019-02-12 18:19:34 +00004#include "clang/CodeGen/ObjectFilePCHContainerOperations.h"
Jonas Devlieghereedff5f42019-02-06 04:33:14 +00005#include "clang/Frontend/ASTConsumers.h"
6#include "clang/Frontend/CompilerInstance.h"
7#include "clang/Frontend/FrontendActions.h"
8#include "clang/Rewrite/Core/Rewriter.h"
9#include "clang/Tooling/CommonOptionsParser.h"
10#include "clang/Tooling/Tooling.h"
11
12#include "llvm/ADT/StringExtras.h"
13#include "llvm/ADT/StringRef.h"
14#include "llvm/Support/raw_ostream.h"
15
16#include <sstream>
17#include <string>
18
19using namespace clang;
20using namespace clang::driver;
21using namespace clang::tooling;
22
23static llvm::cl::OptionCategory InstrCategory("LLDB Instrumentation Generator");
24
25/// Get the macro name for recording method calls.
26///
27/// LLDB_RECORD_METHOD
28/// LLDB_RECORD_METHOD_CONST
29/// LLDB_RECORD_METHOD_NO_ARGS
30/// LLDB_RECORD_METHOD_CONST_NO_ARGS
31/// LLDB_RECORD_STATIC_METHOD
32/// LLDB_RECORD_STATIC_METHOD_NO_ARGS
33static std::string GetRecordMethodMacroName(bool Static, bool Const,
34 bool NoArgs) {
35 std::string Macro;
36 llvm::raw_string_ostream OS(Macro);
37
38 OS << "LLDB_RECORD";
39 if (Static)
40 OS << "_STATIC";
41 OS << "_METHOD";
42 if (Const)
43 OS << "_CONST";
44 if (NoArgs)
45 OS << "_NO_ARGS";
46
47 return OS.str();
48}
49
50/// Get the macro name for register methods.
51///
52/// LLDB_REGISTER_CONSTRUCTOR
53/// LLDB_REGISTER_METHOD
54/// LLDB_REGISTER_METHOD_CONST
55/// LLDB_REGISTER_STATIC_METHOD
56static std::string GetRegisterMethodMacroName(bool Static, bool Const) {
57 std::string Macro;
58 llvm::raw_string_ostream OS(Macro);
59
60 OS << "LLDB_REGISTER";
61 if (Static)
62 OS << "_STATIC";
63 OS << "_METHOD";
64 if (Const)
65 OS << "_CONST";
66
67 return OS.str();
68}
69
70static std::string GetRecordMethodMacro(StringRef Result, StringRef Class,
71 StringRef Method, StringRef Signature,
72 StringRef Values, bool Static,
73 bool Const) {
74 std::string Macro;
75 llvm::raw_string_ostream OS(Macro);
76
77 OS << GetRecordMethodMacroName(Static, Const, Values.empty());
78 OS << "(" << Result << ", " << Class << ", " << Method;
79
80 if (!Values.empty()) {
81 OS << ", (" << Signature << "), " << Values << ");\n\n";
82 } else {
83 OS << ");\n\n";
84 }
85
86 return OS.str();
87}
88
89static std::string GetRecordConstructorMacro(StringRef Class,
90 StringRef Signature,
91 StringRef Values) {
92 std::string Macro;
93 llvm::raw_string_ostream OS(Macro);
94 if (!Values.empty()) {
95 OS << "LLDB_RECORD_CONSTRUCTOR(" << Class << ", (" << Signature << "), "
96 << Values << ");\n\n";
97 } else {
98 OS << "LLDB_RECORD_CONSTRUCTOR_NO_ARGS(" << Class << ");\n\n";
99 }
100 return OS.str();
101}
102
103static std::string GetRegisterConstructorMacro(StringRef Class,
104 StringRef Signature) {
105 std::string Macro;
106 llvm::raw_string_ostream OS(Macro);
Jonas Devlieghereb7c22312019-02-20 01:49:10 +0000107 OS << "LLDB_REGISTER_CONSTRUCTOR(" << Class << ", (" << Signature << "));\n";
Jonas Devlieghereedff5f42019-02-06 04:33:14 +0000108 return OS.str();
109}
110
111static std::string GetRegisterMethodMacro(StringRef Result, StringRef Class,
112 StringRef Method, StringRef Signature,
113 bool Static, bool Const) {
114 std::string Macro;
115 llvm::raw_string_ostream OS(Macro);
116 OS << GetRegisterMethodMacroName(Static, Const);
117 OS << "(" << Result << ", " << Class << ", " << Method << ", (" << Signature
118 << "));\n";
119 return OS.str();
120}
121
Jonas Devlieghere091b9252019-02-19 01:04:31 +0000122class SBReturnVisitor : public RecursiveASTVisitor<SBReturnVisitor> {
123public:
124 SBReturnVisitor(Rewriter &R) : MyRewriter(R) {}
125
126 bool VisitReturnStmt(ReturnStmt *Stmt) {
127 Expr *E = Stmt->getRetValue();
128
129 if (E->getBeginLoc().isMacroID())
130 return false;
131
132 SourceRange R(E->getBeginLoc(), E->getEndLoc());
133
134 StringRef WrittenExpr = Lexer::getSourceText(
135 CharSourceRange::getTokenRange(R), MyRewriter.getSourceMgr(),
136 MyRewriter.getLangOpts());
137
138 std::string ReplacementText =
139 "LLDB_RECORD_RESULT(" + WrittenExpr.str() + ")";
140 MyRewriter.ReplaceText(R, ReplacementText);
141
142 return true;
143 }
144
145private:
146 Rewriter &MyRewriter;
147};
148
Jonas Devlieghereedff5f42019-02-06 04:33:14 +0000149class SBVisitor : public RecursiveASTVisitor<SBVisitor> {
150public:
151 SBVisitor(Rewriter &R, ASTContext &Context)
152 : MyRewriter(R), Context(Context) {}
153
154 bool VisitCXXMethodDecl(CXXMethodDecl *Decl) {
155 // Not all decls should be registered. Please refer to that method's
156 // comment for details.
157 if (ShouldSkip(Decl))
158 return false;
159
Jonas Devlieghereee04d4d2019-02-19 23:13:29 +0000160 // Skip CXXMethodDecls that already starts with a macro. This should make
161 // it easier to rerun the tool to find missing macros.
162 Stmt *Body = Decl->getBody();
163 for (auto &C : Body->children()) {
164 if (C->getBeginLoc().isMacroID())
165 return false;
166 break;
167 }
168
Jonas Devlieghereedff5f42019-02-06 04:33:14 +0000169 // Print 'bool' instead of '_Bool'.
170 PrintingPolicy Policy(Context.getLangOpts());
171 Policy.Bool = true;
172
173 // Collect the functions parameter types and names.
174 std::vector<std::string> ParamTypes;
175 std::vector<std::string> ParamNames;
176 for (auto *P : Decl->parameters()) {
177 QualType T = P->getType();
178
179 // Currently we don't support functions that have function pointers as an
180 // argument.
181 if (T->isFunctionPointerType())
182 return false;
183
184 // Currently we don't support functions that have void pointers as an
185 // argument.
186 if (T->isVoidPointerType())
187 return false;
188
189 ParamTypes.push_back(T.getAsString(Policy));
190 ParamNames.push_back(P->getNameAsString());
191 }
192
193 // Convert the two lists to string for the macros.
194 std::string ParamTypesStr = llvm::join(ParamTypes, ", ");
195 std::string ParamNamesStr = llvm::join(ParamNames, ", ");
196
197 CXXRecordDecl *Record = Decl->getParent();
198 QualType ReturnType = Decl->getReturnType();
199
200 // Construct the macros.
201 std::string Macro;
202 if (isa<CXXConstructorDecl>(Decl)) {
203 llvm::outs() << GetRegisterConstructorMacro(Record->getNameAsString(),
204 ParamTypesStr);
205
206 Macro = GetRecordConstructorMacro(Record->getNameAsString(),
207 ParamTypesStr, ParamNamesStr);
208 } else {
209 llvm::outs() << GetRegisterMethodMacro(
210 ReturnType.getAsString(Policy), Record->getNameAsString(),
211 Decl->getNameAsString(), ParamTypesStr, Decl->isStatic(),
212 Decl->isConst());
213
214 Macro = GetRecordMethodMacro(
215 ReturnType.getAsString(Policy), Record->getNameAsString(),
216 Decl->getNameAsString(), ParamTypesStr, ParamNamesStr,
217 Decl->isStatic(), Decl->isConst());
218 }
219
Jonas Devlieghereedff5f42019-02-06 04:33:14 +0000220 // Insert the macro at the beginning of the function. We don't attempt to
221 // fix the formatting and instead rely on clang-format to fix it after the
222 // tool has run. This is also the reason that the macros end with two
223 // newlines, counting on clang-format to normalize this in case the macro
224 // got inserted before an existing newline.
225 SourceLocation InsertLoc = Lexer::getLocForEndOfToken(
226 Body->getBeginLoc(), 0, MyRewriter.getSourceMgr(),
227 MyRewriter.getLangOpts());
228 MyRewriter.InsertTextAfter(InsertLoc, Macro);
229
Jonas Devlieghere091b9252019-02-19 01:04:31 +0000230 // If the function returns a class or struct, we need to wrap its return
231 // statement(s).
232 if (ReturnType->isStructureOrClassType()) {
233 SBReturnVisitor Visitor(MyRewriter);
234 Visitor.TraverseDecl(Decl);
235 }
236
Jonas Devlieghereedff5f42019-02-06 04:33:14 +0000237 return true;
238 }
239
240private:
241 /// Determine whether we need to consider the given CXXMethodDecl.
242 ///
243 /// Currently we skip the following cases:
244 /// 1. Decls outside the main source file,
245 /// 2. Decls that are only present in the source file,
246 /// 3. Decls that are not definitions,
Jonas Devlieghere091b9252019-02-19 01:04:31 +0000247 /// 4. Non-public methods,
248 /// 5. Variadic methods.
249 /// 6. Destructors.
Jonas Devlieghereedff5f42019-02-06 04:33:14 +0000250 bool ShouldSkip(CXXMethodDecl *Decl) {
251 // Skip anything outside the main file.
252 if (!MyRewriter.getSourceMgr().isInMainFile(Decl->getBeginLoc()))
253 return true;
254
255 // Skip if the canonical decl in the current decl. It means that the method
256 // is declared in the implementation and is therefore not exposed as part
257 // of the API.
258 if (Decl == Decl->getCanonicalDecl())
259 return true;
260
261 // Skip decls that have no body, i.e. are just declarations.
262 Stmt *Body = Decl->getBody();
263 if (!Body)
264 return true;
265
Jonas Devlieghere091b9252019-02-19 01:04:31 +0000266 // Skip non-public methods.
Jonas Devlieghereedff5f42019-02-06 04:33:14 +0000267 AccessSpecifier AS = Decl->getAccess();
268 if (AS != AccessSpecifier::AS_public)
269 return true;
270
Jonas Devlieghere091b9252019-02-19 01:04:31 +0000271 // Skip variadic methods.
272 if (Decl->isVariadic())
273 return true;
274
Jonas Devlieghereedff5f42019-02-06 04:33:14 +0000275 // Skip destructors.
276 if (isa<CXXDestructorDecl>(Decl))
277 return true;
278
279 return false;
280 }
281
282 Rewriter &MyRewriter;
283 ASTContext &Context;
284};
285
286class SBConsumer : public ASTConsumer {
287public:
288 SBConsumer(Rewriter &R, ASTContext &Context) : Visitor(R, Context) {}
289
290 // Override the method that gets called for each parsed top-level
291 // declaration.
292 bool HandleTopLevelDecl(DeclGroupRef DR) override {
293 for (DeclGroupRef::iterator b = DR.begin(), e = DR.end(); b != e; ++b) {
294 Visitor.TraverseDecl(*b);
295 }
296 return true;
297 }
298
299private:
300 SBVisitor Visitor;
301};
302
303class SBAction : public ASTFrontendAction {
304public:
305 SBAction() = default;
306
Jonas Devlieghereb7c22312019-02-20 01:49:10 +0000307 bool BeginSourceFileAction(CompilerInstance &CI) override {
308 llvm::outs() << "{\n";
309 return true;
310 }
311
312 void EndSourceFileAction() override {
313 llvm::outs() << "}\n";
314 MyRewriter.overwriteChangedFiles();
315 }
Jonas Devlieghereedff5f42019-02-06 04:33:14 +0000316
317 std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
Jonas Devlieghereb7c22312019-02-20 01:49:10 +0000318 StringRef File) override {
Jonas Devlieghereedff5f42019-02-06 04:33:14 +0000319 MyRewriter.setSourceMgr(CI.getSourceManager(), CI.getLangOpts());
320 return llvm::make_unique<SBConsumer>(MyRewriter, CI.getASTContext());
321 }
322
323private:
324 Rewriter MyRewriter;
325};
326
327int main(int argc, const char **argv) {
328 CommonOptionsParser OP(argc, argv, InstrCategory,
329 "Utility for generating the macros for LLDB's "
330 "instrumentation framework.");
Jonas Devlieghere1ca9dd82019-02-12 18:19:34 +0000331
332 auto PCHOpts = std::make_shared<PCHContainerOperations>();
333 PCHOpts->registerWriter(llvm::make_unique<ObjectFilePCHContainerWriter>());
334 PCHOpts->registerReader(llvm::make_unique<ObjectFilePCHContainerReader>());
335
336 ClangTool T(OP.getCompilations(), OP.getSourcePathList(), PCHOpts);
Jonas Devlieghereedff5f42019-02-06 04:33:14 +0000337 return T.run(newFrontendActionFactory<SBAction>().get());
338}