1 //===--- Compiler.cpp --------------------------------------------*- C++-*-===//
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 "Compiler.h"
10 #include "support/Logger.h"
11 #include "clang/Basic/TargetInfo.h"
12 #include "clang/Lex/PreprocessorOptions.h"
13 #include "clang/Serialization/PCHContainerOperations.h"
14 #include "llvm/ADT/StringRef.h"
15 #include "llvm/Support/Format.h"
16 #include "llvm/Support/FormatVariadic.h"
17
18 namespace clang {
19 namespace clangd {
20
log(DiagnosticsEngine::Level DiagLevel,const clang::Diagnostic & Info)21 void IgnoreDiagnostics::log(DiagnosticsEngine::Level DiagLevel,
22 const clang::Diagnostic &Info) {
23 // FIXME: format lazily, in case vlog is off.
24 llvm::SmallString<64> Message;
25 Info.FormatDiagnostic(Message);
26
27 llvm::SmallString<64> Location;
28 if (Info.hasSourceManager() && Info.getLocation().isValid()) {
29 auto &SourceMgr = Info.getSourceManager();
30 auto Loc = SourceMgr.getFileLoc(Info.getLocation());
31 llvm::raw_svector_ostream OS(Location);
32 Loc.print(OS, SourceMgr);
33 OS << ":";
34 }
35
36 clangd::vlog("Ignored diagnostic. {0}{1}", Location, Message);
37 }
38
HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,const clang::Diagnostic & Info)39 void IgnoreDiagnostics::HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
40 const clang::Diagnostic &Info) {
41 IgnoreDiagnostics::log(DiagLevel, Info);
42 }
43
44 std::unique_ptr<CompilerInvocation>
buildCompilerInvocation(const ParseInputs & Inputs,clang::DiagnosticConsumer & D,std::vector<std::string> * CC1Args)45 buildCompilerInvocation(const ParseInputs &Inputs, clang::DiagnosticConsumer &D,
46 std::vector<std::string> *CC1Args) {
47 std::vector<const char *> ArgStrs;
48 for (const auto &S : Inputs.CompileCommand.CommandLine)
49 ArgStrs.push_back(S.c_str());
50
51 auto VFS = Inputs.TFS->view(Inputs.CompileCommand.Directory);
52 llvm::IntrusiveRefCntPtr<DiagnosticsEngine> CommandLineDiagsEngine =
53 CompilerInstance::createDiagnostics(new DiagnosticOptions, &D, false);
54 std::unique_ptr<CompilerInvocation> CI = createInvocationFromCommandLine(
55 ArgStrs, CommandLineDiagsEngine, std::move(VFS),
56 /*ShouldRecoverOnErrors=*/true, CC1Args);
57 if (!CI)
58 return nullptr;
59 // createInvocationFromCommandLine sets DisableFree.
60 CI->getFrontendOpts().DisableFree = false;
61 CI->getLangOpts()->CommentOpts.ParseAllComments = true;
62 CI->getLangOpts()->RetainCommentsFromSystemHeaders = true;
63
64 // Disable any dependency outputting, we don't want to generate files or write
65 // to stdout/stderr.
66 CI->getDependencyOutputOpts().ShowIncludesDest =
67 ShowIncludesDestination::None;
68 CI->getDependencyOutputOpts().OutputFile.clear();
69 CI->getDependencyOutputOpts().HeaderIncludeOutputFile.clear();
70 CI->getDependencyOutputOpts().DOTOutputFile.clear();
71 CI->getDependencyOutputOpts().ModuleDependencyOutputDir.clear();
72
73 // Disable any pch generation/usage operations. Since serialized preamble
74 // format is unstable, using an incompatible one might result in unexpected
75 // behaviours, including crashes.
76 CI->getPreprocessorOpts().ImplicitPCHInclude.clear();
77 CI->getPreprocessorOpts().PrecompiledPreambleBytes = {0, false};
78 CI->getPreprocessorOpts().PCHThroughHeader.clear();
79 CI->getPreprocessorOpts().PCHWithHdrStop = false;
80 CI->getPreprocessorOpts().PCHWithHdrStopCreate = false;
81
82 // Recovery expression currently only works for C++.
83 if (CI->getLangOpts()->CPlusPlus) {
84 CI->getLangOpts()->RecoveryAST = Inputs.Opts.BuildRecoveryAST;
85 CI->getLangOpts()->RecoveryASTType = Inputs.Opts.PreserveRecoveryASTType;
86 }
87 return CI;
88 }
89
90 std::unique_ptr<CompilerInstance>
prepareCompilerInstance(std::unique_ptr<clang::CompilerInvocation> CI,const PrecompiledPreamble * Preamble,std::unique_ptr<llvm::MemoryBuffer> Buffer,llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS,DiagnosticConsumer & DiagsClient)91 prepareCompilerInstance(std::unique_ptr<clang::CompilerInvocation> CI,
92 const PrecompiledPreamble *Preamble,
93 std::unique_ptr<llvm::MemoryBuffer> Buffer,
94 llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS,
95 DiagnosticConsumer &DiagsClient) {
96 assert(VFS && "VFS is null");
97 assert(!CI->getPreprocessorOpts().RetainRemappedFileBuffers &&
98 "Setting RetainRemappedFileBuffers to true will cause a memory leak "
99 "of ContentsBuffer");
100
101 // NOTE: we use Buffer.get() when adding remapped files, so we have to make
102 // sure it will be released if no error is emitted.
103 if (Preamble) {
104 Preamble->OverridePreamble(*CI, VFS, Buffer.get());
105 } else {
106 CI->getPreprocessorOpts().addRemappedFile(
107 CI->getFrontendOpts().Inputs[0].getFile(), Buffer.get());
108 }
109
110 auto Clang = std::make_unique<CompilerInstance>(
111 std::make_shared<PCHContainerOperations>());
112 Clang->setInvocation(std::move(CI));
113 Clang->createDiagnostics(&DiagsClient, false);
114
115 if (auto VFSWithRemapping = createVFSFromCompilerInvocation(
116 Clang->getInvocation(), Clang->getDiagnostics(), VFS))
117 VFS = VFSWithRemapping;
118 Clang->createFileManager(VFS);
119
120 Clang->setTarget(TargetInfo::CreateTargetInfo(
121 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
122 if (!Clang->hasTarget())
123 return nullptr;
124
125 // RemappedFileBuffers will handle the lifetime of the Buffer pointer,
126 // release it.
127 Buffer.release();
128 return Clang;
129 }
130
131 } // namespace clangd
132 } // namespace clang
133