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