1//===-- clang-import-test.cpp - ASTImporter/ExternalASTSource testbed -----===//
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#include "clang/AST/ASTContext.h"
10#include "clang/AST/ASTImporter.h"
11#include "clang/AST/DeclObjC.h"
12#include "clang/AST/ExternalASTMerger.h"
13#include "clang/Basic/Builtins.h"
14#include "clang/Basic/FileManager.h"
15#include "clang/Basic/IdentifierTable.h"
16#include "clang/Basic/SourceLocation.h"
17#include "clang/Basic/TargetInfo.h"
18#include "clang/Basic/TargetOptions.h"
19#include "clang/CodeGen/ModuleBuilder.h"
20#include "clang/Driver/Types.h"
21#include "clang/Frontend/ASTConsumers.h"
22#include "clang/Frontend/CompilerInstance.h"
23#include "clang/Frontend/MultiplexConsumer.h"
24#include "clang/Frontend/TextDiagnosticBuffer.h"
25#include "clang/Lex/Lexer.h"
26#include "clang/Lex/Preprocessor.h"
27#include "clang/Parse/ParseAST.h"
28
29#include "llvm/IR/LLVMContext.h"
30#include "llvm/IR/Module.h"
31#include "llvm/Support/CommandLine.h"
32#include "llvm/Support/Error.h"
33#include "llvm/Support/Signals.h"
34#include "llvm/Support/VirtualFileSystem.h"
35#include "llvm/TargetParser/Host.h"
36
37#include <memory>
38#include <string>
39
40using namespace clang;
41
42static llvm::cl::opt<std::string> Expression(
43 "expression", llvm::cl::Required,
44 llvm::cl::desc("Path to a file containing the expression to parse"));
45
46static llvm::cl::list<std::string>
47 Imports("import",
48 llvm::cl::desc("Path to a file containing declarations to import"));
49
50static llvm::cl::opt<bool>
51 Direct("direct",
52 llvm::cl::desc("Use the parsed declarations without indirection"));
53
54static llvm::cl::opt<bool> UseOrigins(
55 "use-origins",
56 llvm::cl::desc(
57 "Use DeclContext origin information for more accurate lookups"));
58
59static llvm::cl::list<std::string>
60 ClangArgs("Xcc",
61 llvm::cl::desc("Argument to pass to the CompilerInvocation"),
62 llvm::cl::CommaSeparated);
63
64static llvm::cl::opt<std::string>
65 Input("x", llvm::cl::desc("The language to parse (default: c++)"),
66 llvm::cl::init(Val: "c++"));
67
68static llvm::cl::opt<bool> ObjCARC("objc-arc", llvm::cl::init(Val: false),
69 llvm::cl::desc("Emable ObjC ARC"));
70
71static llvm::cl::opt<bool> DumpAST("dump-ast", llvm::cl::init(Val: false),
72 llvm::cl::desc("Dump combined AST"));
73
74static llvm::cl::opt<bool> DumpIR("dump-ir", llvm::cl::init(Val: false),
75 llvm::cl::desc("Dump IR from final parse"));
76
77namespace init_convenience {
78class TestDiagnosticConsumer : public DiagnosticConsumer {
79private:
80 std::unique_ptr<TextDiagnosticBuffer> Passthrough;
81 const LangOptions *LangOpts = nullptr;
82
83public:
84 TestDiagnosticConsumer()
85 : Passthrough(std::make_unique<TextDiagnosticBuffer>()) {}
86
87 void BeginSourceFile(const LangOptions &LangOpts,
88 const Preprocessor *PP = nullptr) override {
89 this->LangOpts = &LangOpts;
90 return Passthrough->BeginSourceFile(LangOpts, PP);
91 }
92
93 void EndSourceFile() override {
94 this->LangOpts = nullptr;
95 Passthrough->EndSourceFile();
96 }
97
98 bool IncludeInDiagnosticCounts() const override {
99 return Passthrough->IncludeInDiagnosticCounts();
100 }
101
102private:
103 static void PrintSourceForLocation(const SourceLocation &Loc,
104 SourceManager &SM) {
105 const char *LocData = SM.getCharacterData(SL: Loc, /*Invalid=*/nullptr);
106 unsigned LocColumn =
107 SM.getSpellingColumnNumber(Loc, /*Invalid=*/nullptr) - 1;
108 FileID FID = SM.getFileID(SpellingLoc: Loc);
109 llvm::MemoryBufferRef Buffer = SM.getBufferOrFake(FID, Loc);
110
111 assert(LocData >= Buffer.getBufferStart() &&
112 LocData < Buffer.getBufferEnd());
113
114 const char *LineBegin = LocData - LocColumn;
115
116 assert(LineBegin >= Buffer.getBufferStart());
117
118 const char *LineEnd = nullptr;
119
120 for (LineEnd = LineBegin; *LineEnd != '\n' && *LineEnd != '\r' &&
121 LineEnd < Buffer.getBufferEnd();
122 ++LineEnd)
123 ;
124
125 llvm::StringRef LineString(LineBegin, LineEnd - LineBegin);
126
127 llvm::errs() << LineString << '\n';
128 llvm::errs().indent(NumSpaces: LocColumn);
129 llvm::errs() << '^';
130 llvm::errs() << '\n';
131 }
132
133 void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
134 const Diagnostic &Info) override {
135 if (Info.hasSourceManager() && LangOpts) {
136 SourceManager &SM = Info.getSourceManager();
137
138 if (Info.getLocation().isValid()) {
139 Info.getLocation().print(OS&: llvm::errs(), SM);
140 llvm::errs() << ": ";
141 }
142
143 SmallString<16> DiagText;
144 Info.FormatDiagnostic(OutStr&: DiagText);
145 llvm::errs() << DiagText << '\n';
146
147 if (Info.getLocation().isValid()) {
148 PrintSourceForLocation(Loc: Info.getLocation(), SM);
149 }
150
151 for (const CharSourceRange &Range : Info.getRanges()) {
152 bool Invalid = true;
153 StringRef Ref = Lexer::getSourceText(Range, SM, LangOpts: *LangOpts, Invalid: &Invalid);
154 if (!Invalid) {
155 llvm::errs() << Ref << '\n';
156 }
157 }
158 }
159 DiagnosticConsumer::HandleDiagnostic(DiagLevel, Info);
160 }
161};
162
163std::unique_ptr<CompilerInstance> BuildCompilerInstance() {
164 DiagnosticOptions DiagOpts;
165 auto DC = std::make_unique<TestDiagnosticConsumer>();
166 auto Diags = CompilerInstance::createDiagnostics(
167 VFS&: *llvm::vfs::getRealFileSystem(), Opts&: DiagOpts, Client: DC.get(),
168 /*ShouldOwnClient=*/false);
169
170 auto Inv = std::make_unique<CompilerInvocation>();
171
172 std::vector<const char *> ClangArgv(ClangArgs.size());
173 std::transform(first: ClangArgs.begin(), last: ClangArgs.end(), result: ClangArgv.begin(),
174 unary_op: [](const std::string &s) -> const char * { return s.data(); });
175 CompilerInvocation::CreateFromArgs(Res&: *Inv, CommandLineArgs: ClangArgv, Diags&: *Diags);
176
177 {
178 using namespace driver::types;
179 ID Id = lookupTypeForTypeSpecifier(Name: Input.c_str());
180 assert(Id != TY_INVALID);
181 if (isCXX(Id)) {
182 Inv->getLangOpts().CPlusPlus = true;
183 Inv->getLangOpts().CPlusPlus11 = true;
184 Inv->getHeaderSearchOpts().UseLibcxx = true;
185 }
186 if (isObjC(Id)) {
187 Inv->getLangOpts().ObjC = 1;
188 }
189 }
190 Inv->getLangOpts().ObjCAutoRefCount = ObjCARC;
191
192 Inv->getLangOpts().Bool = true;
193 Inv->getLangOpts().WChar = true;
194 Inv->getLangOpts().Blocks = true;
195 Inv->getLangOpts().DebuggerSupport = true;
196 Inv->getLangOpts().SpellChecking = false;
197 Inv->getLangOpts().ThreadsafeStatics = false;
198 Inv->getLangOpts().AccessControl = false;
199 Inv->getLangOpts().DollarIdents = true;
200 Inv->getLangOpts().Exceptions = true;
201 Inv->getLangOpts().CXXExceptions = true;
202 // Needed for testing dynamic_cast.
203 Inv->getLangOpts().RTTI = true;
204 Inv->getCodeGenOpts().setDebugInfo(llvm::codegenoptions::FullDebugInfo);
205 Inv->getTargetOpts().Triple = llvm::sys::getDefaultTargetTriple();
206
207 auto Ins = std::make_unique<CompilerInstance>(args: std::move(Inv));
208
209 Ins->createVirtualFileSystem(BaseFS: llvm::vfs::getRealFileSystem(), DC: DC.get());
210 Ins->createDiagnostics(Client: DC.release(), /*ShouldOwnClient=*/true);
211
212 TargetInfo *TI = TargetInfo::CreateTargetInfo(
213 Diags&: Ins->getDiagnostics(), Opts&: Ins->getInvocation().getTargetOpts());
214 Ins->setTarget(TI);
215 Ins->getTarget().adjust(Diags&: Ins->getDiagnostics(), Opts&: Ins->getLangOpts(),
216 /*AuxTarget=*/Aux: nullptr);
217 Ins->createFileManager();
218 Ins->createSourceManager();
219 Ins->createPreprocessor(TUKind: TU_Complete);
220
221 return Ins;
222}
223
224std::unique_ptr<ASTContext>
225BuildASTContext(CompilerInstance &CI, SelectorTable &ST, Builtin::Context &BC) {
226 auto &PP = CI.getPreprocessor();
227 auto AST = std::make_unique<ASTContext>(
228 args&: CI.getLangOpts(), args&: CI.getSourceManager(),
229 args&: PP.getIdentifierTable(), args&: ST, args&: BC, args: PP.TUKind);
230 AST->InitBuiltinTypes(Target: CI.getTarget());
231 return AST;
232}
233
234std::unique_ptr<CodeGenerator> BuildCodeGen(CompilerInstance &CI,
235 llvm::LLVMContext &LLVMCtx) {
236 StringRef ModuleName("$__module");
237 return CreateLLVMCodeGen(CI, ModuleName, C&: LLVMCtx);
238}
239} // namespace init_convenience
240
241namespace {
242
243/// A container for a CompilerInstance (possibly with an ExternalASTMerger
244/// attached to its ASTContext).
245///
246/// Provides an accessor for the DeclContext origins associated with the
247/// ExternalASTMerger (or an empty list of origins if no ExternalASTMerger is
248/// attached).
249///
250/// This is the main unit of parsed source code maintained by clang-import-test.
251struct CIAndOrigins {
252 using OriginMap = clang::ExternalASTMerger::OriginMap;
253 std::unique_ptr<CompilerInstance> CI;
254
255 ASTContext &getASTContext() { return CI->getASTContext(); }
256 FileManager &getFileManager() { return CI->getFileManager(); }
257 const OriginMap &getOriginMap() {
258 static const OriginMap EmptyOriginMap{};
259 if (ExternalASTSource *Source = CI->getASTContext().getExternalSource())
260 return static_cast<ExternalASTMerger *>(Source)->GetOrigins();
261 return EmptyOriginMap;
262 }
263 DiagnosticConsumer &getDiagnosticClient() {
264 return CI->getDiagnosticClient();
265 }
266 CompilerInstance &getCompilerInstance() { return *CI; }
267};
268
269void AddExternalSource(CIAndOrigins &CI,
270 llvm::MutableArrayRef<CIAndOrigins> Imports) {
271 ExternalASTMerger::ImporterTarget Target(
272 {.AST: CI.getASTContext(), .FM: CI.getFileManager()});
273 llvm::SmallVector<ExternalASTMerger::ImporterSource, 3> Sources;
274 for (CIAndOrigins &Import : Imports)
275 Sources.emplace_back(Args&: Import.getASTContext(), Args&: Import.getFileManager(),
276 Args: Import.getOriginMap());
277 auto ES = std::make_unique<ExternalASTMerger>(args&: Target, args&: Sources);
278 CI.getASTContext().setExternalSource(ES.release());
279 CI.getASTContext().getTranslationUnitDecl()->setHasExternalVisibleStorage();
280}
281
282CIAndOrigins BuildIndirect(CIAndOrigins &CI) {
283 CIAndOrigins IndirectCI{.CI: init_convenience::BuildCompilerInstance()};
284 auto ST = std::make_unique<SelectorTable>();
285 auto BC = std::make_unique<Builtin::Context>();
286 std::unique_ptr<ASTContext> AST = init_convenience::BuildASTContext(
287 CI&: IndirectCI.getCompilerInstance(), ST&: *ST, BC&: *BC);
288 IndirectCI.getCompilerInstance().setASTContext(AST.release());
289 AddExternalSource(CI&: IndirectCI, Imports: CI);
290 return IndirectCI;
291}
292
293llvm::Error ParseSource(const std::string &Path, CompilerInstance &CI,
294 ASTConsumer &Consumer) {
295 SourceManager &SM = CI.getSourceManager();
296 auto FE = CI.getFileManager().getFileRef(Filename: Path);
297 if (!FE) {
298 llvm::consumeError(Err: FE.takeError());
299 return llvm::make_error<llvm::StringError>(
300 Args: llvm::Twine("No such file or directory: ", Path), Args: std::error_code());
301 }
302 SM.setMainFileID(SM.createFileID(SourceFile: *FE, IncludePos: SourceLocation(), FileCharacter: SrcMgr::C_User));
303 ParseAST(pp&: CI.getPreprocessor(), C: &Consumer, Ctx&: CI.getASTContext());
304 return llvm::Error::success();
305}
306
307llvm::Expected<CIAndOrigins> Parse(const std::string &Path,
308 llvm::MutableArrayRef<CIAndOrigins> Imports,
309 bool ShouldDumpAST, bool ShouldDumpIR) {
310 CIAndOrigins CI{.CI: init_convenience::BuildCompilerInstance()};
311 auto ST = std::make_unique<SelectorTable>();
312 auto BC = std::make_unique<Builtin::Context>();
313 std::unique_ptr<ASTContext> AST =
314 init_convenience::BuildASTContext(CI&: CI.getCompilerInstance(), ST&: *ST, BC&: *BC);
315 CI.getCompilerInstance().setASTContext(AST.release());
316 if (Imports.size())
317 AddExternalSource(CI, Imports);
318
319 std::vector<std::unique_ptr<ASTConsumer>> ASTConsumers;
320
321 auto LLVMCtx = std::make_unique<llvm::LLVMContext>();
322 ASTConsumers.push_back(
323 x: init_convenience::BuildCodeGen(CI&: CI.getCompilerInstance(), LLVMCtx&: *LLVMCtx));
324 auto &CG = *static_cast<CodeGenerator *>(ASTConsumers.back().get());
325
326 if (ShouldDumpAST)
327 ASTConsumers.push_back(x: CreateASTDumper(OS: nullptr /*Dump to stdout.*/, FilterString: "", FilterPath: "",
328 DumpDecls: true, Deserialize: false, DumpLookups: false, DumpDeclTypes: false,
329 Format: clang::ADOF_Default));
330
331 CI.getDiagnosticClient().BeginSourceFile(
332 LangOpts: CI.getCompilerInstance().getLangOpts(),
333 PP: &CI.getCompilerInstance().getPreprocessor());
334 MultiplexConsumer Consumers(std::move(ASTConsumers));
335 Consumers.Initialize(Context&: CI.getASTContext());
336
337 if (llvm::Error PE = ParseSource(Path, CI&: CI.getCompilerInstance(), Consumer&: Consumers))
338 return std::move(PE);
339 CI.getDiagnosticClient().EndSourceFile();
340 if (ShouldDumpIR) {
341 CG.GetModule()->renumberMetadataForAssembly();
342 CG.GetModule()->print(OS&: llvm::outs(), AAW: nullptr);
343 }
344 if (CI.getDiagnosticClient().getNumErrors())
345 return llvm::make_error<llvm::StringError>(
346 Args: "Errors occurred while parsing the expression.", Args: std::error_code());
347 return std::move(CI);
348}
349
350void Forget(CIAndOrigins &CI, llvm::MutableArrayRef<CIAndOrigins> Imports) {
351 llvm::SmallVector<ExternalASTMerger::ImporterSource, 3> Sources;
352 for (CIAndOrigins &Import : Imports)
353 Sources.push_back(Elt: {Import.getASTContext(), Import.getFileManager(),
354 Import.getOriginMap()});
355 ExternalASTSource *Source = CI.CI->getASTContext().getExternalSource();
356 auto *Merger = static_cast<ExternalASTMerger *>(Source);
357 Merger->RemoveSources(Sources);
358}
359
360} // end namespace
361
362int main(int argc, const char **argv) {
363 const bool DisableCrashReporting = true;
364 llvm::sys::PrintStackTraceOnErrorSignal(Argv0: argv[0], DisableCrashReporting);
365 llvm::cl::ParseCommandLineOptions(argc, argv);
366 std::vector<CIAndOrigins> ImportCIs;
367 for (auto I : Imports) {
368 llvm::Expected<CIAndOrigins> ImportCI = Parse(Path: I, Imports: {}, ShouldDumpAST: false, ShouldDumpIR: false);
369 if (auto E = ImportCI.takeError()) {
370 llvm::errs() << "error: " << llvm::toString(E: std::move(E)) << "\n";
371 exit(status: -1);
372 }
373 ImportCIs.push_back(x: std::move(*ImportCI));
374 }
375 std::vector<CIAndOrigins> IndirectCIs;
376 if (!Direct || UseOrigins) {
377 for (auto &ImportCI : ImportCIs) {
378 CIAndOrigins IndirectCI = BuildIndirect(CI&: ImportCI);
379 IndirectCIs.push_back(x: std::move(IndirectCI));
380 }
381 }
382 if (UseOrigins)
383 for (auto &ImportCI : ImportCIs)
384 IndirectCIs.push_back(x: std::move(ImportCI));
385 llvm::Expected<CIAndOrigins> ExpressionCI =
386 Parse(Path: Expression, Imports: (Direct && !UseOrigins) ? ImportCIs : IndirectCIs,
387 ShouldDumpAST: DumpAST, ShouldDumpIR: DumpIR);
388 if (auto E = ExpressionCI.takeError()) {
389 llvm::errs() << "error: " << llvm::toString(E: std::move(E)) << "\n";
390 exit(status: -1);
391 }
392 Forget(CI&: *ExpressionCI, Imports: (Direct && !UseOrigins) ? ImportCIs : IndirectCIs);
393 return 0;
394}
395