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   if (Inputs.CompileCommand.CommandLine.empty())
87     return nullptr;
88   std::vector<const char *> ArgStrs;
89   for (const auto &S : Inputs.CompileCommand.CommandLine)
90     ArgStrs.push_back(S.c_str());
91 
92   auto VFS = Inputs.TFS->view(Inputs.CompileCommand.Directory);
93   llvm::IntrusiveRefCntPtr<DiagnosticsEngine> CommandLineDiagsEngine =
94       CompilerInstance::createDiagnostics(new DiagnosticOptions, &D, false);
95   std::unique_ptr<CompilerInvocation> CI = createInvocationFromCommandLine(
96       ArgStrs, CommandLineDiagsEngine, std::move(VFS),
97       /*ShouldRecoverOnErrors=*/true, CC1Args);
98   if (!CI)
99     return nullptr;
100   // createInvocationFromCommandLine sets DisableFree.
101   CI->getFrontendOpts().DisableFree = false;
102   CI->getLangOpts()->CommentOpts.ParseAllComments = true;
103   CI->getLangOpts()->RetainCommentsFromSystemHeaders = true;
104 
105   disableUnsupportedOptions(*CI);
106   return CI;
107 }
108 
109 std::unique_ptr<CompilerInstance>
110 prepareCompilerInstance(std::unique_ptr<clang::CompilerInvocation> CI,
111                         const PrecompiledPreamble *Preamble,
112                         std::unique_ptr<llvm::MemoryBuffer> Buffer,
113                         llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS,
114                         DiagnosticConsumer &DiagsClient) {
115   assert(VFS && "VFS is null");
116   assert(!CI->getPreprocessorOpts().RetainRemappedFileBuffers &&
117          "Setting RetainRemappedFileBuffers to true will cause a memory leak "
118          "of ContentsBuffer");
119 
120   // NOTE: we use Buffer.get() when adding remapped files, so we have to make
121   // sure it will be released if no error is emitted.
122   if (Preamble) {
123     Preamble->OverridePreamble(*CI, VFS, Buffer.get());
124   } else {
125     CI->getPreprocessorOpts().addRemappedFile(
126         CI->getFrontendOpts().Inputs[0].getFile(), Buffer.get());
127   }
128 
129   auto Clang = std::make_unique<CompilerInstance>(
130       std::make_shared<PCHContainerOperations>());
131   Clang->setInvocation(std::move(CI));
132   Clang->createDiagnostics(&DiagsClient, false);
133 
134   if (auto VFSWithRemapping = createVFSFromCompilerInvocation(
135           Clang->getInvocation(), Clang->getDiagnostics(), VFS))
136     VFS = VFSWithRemapping;
137   Clang->createFileManager(VFS);
138 
139   if (!Clang->createTarget())
140     return nullptr;
141 
142   // RemappedFileBuffers will handle the lifetime of the Buffer pointer,
143   // release it.
144   Buffer.release();
145   return Clang;
146 }
147 
148 } // namespace clangd
149 } // namespace clang
150