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/Frontend/CompilerInvocation.h"
13 #include "clang/Lex/PreprocessorOptions.h"
14 #include "clang/Serialization/PCHContainerOperations.h"
15 #include "llvm/ADT/StringRef.h"
16 #include "llvm/Support/Format.h"
17 #include "llvm/Support/FormatVariadic.h"
18 
19 namespace clang {
20 namespace clangd {
21 
22 void IgnoreDiagnostics::log(DiagnosticsEngine::Level DiagLevel,
23                             const clang::Diagnostic &Info) {
24   // FIXME: format lazily, in case vlog is off.
25   llvm::SmallString<64> Message;
26   Info.FormatDiagnostic(Message);
27 
28   llvm::SmallString<64> Location;
29   if (Info.hasSourceManager() && Info.getLocation().isValid()) {
30     auto &SourceMgr = Info.getSourceManager();
31     auto Loc = SourceMgr.getFileLoc(Info.getLocation());
32     llvm::raw_svector_ostream OS(Location);
33     Loc.print(OS, SourceMgr);
34     OS << ":";
35   }
36 
37   clangd::vlog("Ignored diagnostic. {0}{1}", Location, Message);
38 }
39 
40 void IgnoreDiagnostics::HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
41                                          const clang::Diagnostic &Info) {
42   IgnoreDiagnostics::log(DiagLevel, Info);
43 }
44 
45 void disableUnsupportedOptions(CompilerInvocation &CI) {
46   // Disable "clang -verify" diagnostics, they are rarely useful in clangd, and
47   // our compiler invocation set-up doesn't seem to work with it (leading
48   // assertions in VerifyDiagnosticConsumer).
49   CI.getDiagnosticOpts().VerifyDiagnostics = false;
50   CI.getDiagnosticOpts().ShowColors = false;
51 
52   // Disable any dependency outputting, we don't want to generate files or write
53   // to stdout/stderr.
54   CI.getDependencyOutputOpts().ShowIncludesDest = ShowIncludesDestination::None;
55   CI.getDependencyOutputOpts().OutputFile.clear();
56   CI.getDependencyOutputOpts().HeaderIncludeOutputFile.clear();
57   CI.getDependencyOutputOpts().DOTOutputFile.clear();
58   CI.getDependencyOutputOpts().ModuleDependencyOutputDir.clear();
59 
60   // Disable any pch generation/usage operations. Since serialized preamble
61   // format is unstable, using an incompatible one might result in unexpected
62   // behaviours, including crashes.
63   CI.getPreprocessorOpts().ImplicitPCHInclude.clear();
64   CI.getPreprocessorOpts().PrecompiledPreambleBytes = {0, false};
65   CI.getPreprocessorOpts().PCHThroughHeader.clear();
66   CI.getPreprocessorOpts().PCHWithHdrStop = false;
67   CI.getPreprocessorOpts().PCHWithHdrStopCreate = false;
68   // Don't crash on `#pragma clang __debug parser_crash`
69   CI.getPreprocessorOpts().DisablePragmaDebugCrash = true;
70 
71   // Always default to raw container format as clangd doesn't registry any other
72   // and clang dies when faced with unknown formats.
73   CI.getHeaderSearchOpts().ModuleFormat =
74       PCHContainerOperations().getRawReader().getFormat().str();
75 
76   CI.getFrontendOpts().Plugins.clear();
77   CI.getFrontendOpts().AddPluginActions.clear();
78   CI.getFrontendOpts().PluginArgs.clear();
79   CI.getFrontendOpts().ProgramAction = frontend::ParseSyntaxOnly;
80   CI.getFrontendOpts().ActionName.clear();
81 }
82 
83 std::unique_ptr<CompilerInvocation>
84 buildCompilerInvocation(const ParseInputs &Inputs, clang::DiagnosticConsumer &D,
85                         std::vector<std::string> *CC1Args) {
86   std::vector<const char *> ArgStrs;
87   for (const auto &S : Inputs.CompileCommand.CommandLine)
88     ArgStrs.push_back(S.c_str());
89 
90   auto VFS = Inputs.TFS->view(Inputs.CompileCommand.Directory);
91   llvm::IntrusiveRefCntPtr<DiagnosticsEngine> CommandLineDiagsEngine =
92       CompilerInstance::createDiagnostics(new DiagnosticOptions, &D, false);
93   std::unique_ptr<CompilerInvocation> CI = createInvocationFromCommandLine(
94       ArgStrs, CommandLineDiagsEngine, std::move(VFS),
95       /*ShouldRecoverOnErrors=*/true, CC1Args);
96   if (!CI)
97     return nullptr;
98   // createInvocationFromCommandLine sets DisableFree.
99   CI->getFrontendOpts().DisableFree = false;
100   CI->getLangOpts()->CommentOpts.ParseAllComments = true;
101   CI->getLangOpts()->RetainCommentsFromSystemHeaders = true;
102 
103   disableUnsupportedOptions(*CI);
104   return CI;
105 }
106 
107 std::unique_ptr<CompilerInstance>
108 prepareCompilerInstance(std::unique_ptr<clang::CompilerInvocation> CI,
109                         const PrecompiledPreamble *Preamble,
110                         std::unique_ptr<llvm::MemoryBuffer> Buffer,
111                         llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS,
112                         DiagnosticConsumer &DiagsClient) {
113   assert(VFS && "VFS is null");
114   assert(!CI->getPreprocessorOpts().RetainRemappedFileBuffers &&
115          "Setting RetainRemappedFileBuffers to true will cause a memory leak "
116          "of ContentsBuffer");
117 
118   // NOTE: we use Buffer.get() when adding remapped files, so we have to make
119   // sure it will be released if no error is emitted.
120   if (Preamble) {
121     Preamble->OverridePreamble(*CI, VFS, Buffer.get());
122   } else {
123     CI->getPreprocessorOpts().addRemappedFile(
124         CI->getFrontendOpts().Inputs[0].getFile(), Buffer.get());
125   }
126 
127   auto Clang = std::make_unique<CompilerInstance>(
128       std::make_shared<PCHContainerOperations>());
129   Clang->setInvocation(std::move(CI));
130   Clang->createDiagnostics(&DiagsClient, false);
131 
132   if (auto VFSWithRemapping = createVFSFromCompilerInvocation(
133           Clang->getInvocation(), Clang->getDiagnostics(), VFS))
134     VFS = VFSWithRemapping;
135   Clang->createFileManager(VFS);
136 
137   if (!Clang->createTarget())
138     return nullptr;
139 
140   // RemappedFileBuffers will handle the lifetime of the Buffer pointer,
141   // release it.
142   Buffer.release();
143   return Clang;
144 }
145 
146 } // namespace clangd
147 } // namespace clang
148