blob: d26b6937b85159dce61092b5fb7ca071e4c50b34 [file] [log] [blame]
Daniel Dunbara0ff58d2009-11-14 10:42:35 +00001//===--- FrontendAction.cpp -----------------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "clang/Frontend/FrontendAction.h"
Sebastian Redl07a89a82010-07-30 00:29:29 +000011#include "clang/AST/ASTConsumer.h"
Daniel Dunbara0ff58d2009-11-14 10:42:35 +000012#include "clang/AST/ASTContext.h"
Nico Weber2992efa2011-01-25 20:34:14 +000013#include "clang/AST/DeclGroup.h"
Daniel Dunbara0ff58d2009-11-14 10:42:35 +000014#include "clang/Frontend/ASTUnit.h"
15#include "clang/Frontend/CompilerInstance.h"
16#include "clang/Frontend/FrontendDiagnostic.h"
Nico Weber2992efa2011-01-25 20:34:14 +000017#include "clang/Frontend/FrontendPluginRegistry.h"
Douglas Gregore9fc3772012-01-26 07:55:45 +000018#include "clang/Frontend/LayoutOverrideSource.h"
Nico Weber2992efa2011-01-25 20:34:14 +000019#include "clang/Frontend/MultiplexConsumer.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000020#include "clang/Frontend/Utils.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000021#include "clang/Lex/HeaderSearch.h"
Taewook Oh06b1af52017-03-07 20:20:23 +000022#include "clang/Lex/LiteralSupport.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000023#include "clang/Lex/Preprocessor.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000024#include "clang/Lex/PreprocessorOptions.h"
John McCall8b0666c2010-08-20 18:27:03 +000025#include "clang/Parse/ParseAST.h"
Argyrios Kyrtzidisa11aca42010-10-14 20:14:18 +000026#include "clang/Serialization/ASTDeserializationListener.h"
Jonathan D. Turner0248f572011-08-05 22:17:03 +000027#include "clang/Serialization/ASTReader.h"
Douglas Gregor5e306b12013-01-23 22:38:11 +000028#include "clang/Serialization/GlobalModuleIndex.h"
Daniel Dunbara0ff58d2009-11-14 10:42:35 +000029#include "llvm/Support/ErrorHandling.h"
Douglas Gregorfc9e7a22012-10-23 06:18:24 +000030#include "llvm/Support/FileSystem.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000031#include "llvm/Support/Path.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000032#include "llvm/Support/Timer.h"
Daniel Dunbara0ff58d2009-11-14 10:42:35 +000033#include "llvm/Support/raw_ostream.h"
Rafael Espindola8a8e5542014-06-12 17:19:42 +000034#include <system_error>
Daniel Dunbara0ff58d2009-11-14 10:42:35 +000035using namespace clang;
36
John Brawn4d79ec72016-08-05 11:01:08 +000037LLVM_INSTANTIATE_REGISTRY(FrontendPluginRegistry)
NAKAMURA Takumiad4c06c2014-07-11 15:06:24 +000038
Argyrios Kyrtzidisa11aca42010-10-14 20:14:18 +000039namespace {
40
Argyrios Kyrtzidisb12986f2011-10-28 22:54:31 +000041class DelegatingDeserializationListener : public ASTDeserializationListener {
Argyrios Kyrtzidisa11aca42010-10-14 20:14:18 +000042 ASTDeserializationListener *Previous;
Nico Weber824285e2014-05-08 04:26:47 +000043 bool DeletePrevious;
Argyrios Kyrtzidisa11aca42010-10-14 20:14:18 +000044
45public:
Argyrios Kyrtzidisb12986f2011-10-28 22:54:31 +000046 explicit DelegatingDeserializationListener(
Nico Weber824285e2014-05-08 04:26:47 +000047 ASTDeserializationListener *Previous, bool DeletePrevious)
48 : Previous(Previous), DeletePrevious(DeletePrevious) {}
Alexander Kornienko34eb2072015-04-11 02:00:23 +000049 ~DelegatingDeserializationListener() override {
Nico Weber824285e2014-05-08 04:26:47 +000050 if (DeletePrevious)
51 delete Previous;
52 }
Argyrios Kyrtzidisa11aca42010-10-14 20:14:18 +000053
Craig Topperafa7cb32014-03-13 06:07:04 +000054 void ReaderInitialized(ASTReader *Reader) override {
Argyrios Kyrtzidisb12986f2011-10-28 22:54:31 +000055 if (Previous)
56 Previous->ReaderInitialized(Reader);
57 }
Craig Topperafa7cb32014-03-13 06:07:04 +000058 void IdentifierRead(serialization::IdentID ID,
59 IdentifierInfo *II) override {
Argyrios Kyrtzidisb12986f2011-10-28 22:54:31 +000060 if (Previous)
61 Previous->IdentifierRead(ID, II);
62 }
Craig Topperafa7cb32014-03-13 06:07:04 +000063 void TypeRead(serialization::TypeIdx Idx, QualType T) override {
Argyrios Kyrtzidisb12986f2011-10-28 22:54:31 +000064 if (Previous)
65 Previous->TypeRead(Idx, T);
66 }
Craig Topperafa7cb32014-03-13 06:07:04 +000067 void DeclRead(serialization::DeclID ID, const Decl *D) override {
Argyrios Kyrtzidisb12986f2011-10-28 22:54:31 +000068 if (Previous)
69 Previous->DeclRead(ID, D);
70 }
Craig Topperafa7cb32014-03-13 06:07:04 +000071 void SelectorRead(serialization::SelectorID ID, Selector Sel) override {
Argyrios Kyrtzidisb12986f2011-10-28 22:54:31 +000072 if (Previous)
73 Previous->SelectorRead(ID, Sel);
74 }
Craig Topperafa7cb32014-03-13 06:07:04 +000075 void MacroDefinitionRead(serialization::PreprocessedEntityID PPID,
Richard Smith66a81862015-05-04 02:25:31 +000076 MacroDefinitionRecord *MD) override {
Argyrios Kyrtzidisb12986f2011-10-28 22:54:31 +000077 if (Previous)
78 Previous->MacroDefinitionRead(PPID, MD);
79 }
80};
81
82/// \brief Dumps deserialized declarations.
83class DeserializedDeclsDumper : public DelegatingDeserializationListener {
84public:
Nico Weber824285e2014-05-08 04:26:47 +000085 explicit DeserializedDeclsDumper(ASTDeserializationListener *Previous,
86 bool DeletePrevious)
87 : DelegatingDeserializationListener(Previous, DeletePrevious) {}
Argyrios Kyrtzidisb12986f2011-10-28 22:54:31 +000088
Craig Topperafa7cb32014-03-13 06:07:04 +000089 void DeclRead(serialization::DeclID ID, const Decl *D) override {
Argyrios Kyrtzidisa11aca42010-10-14 20:14:18 +000090 llvm::outs() << "PCH DECL: " << D->getDeclKindName();
91 if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
Benjamin Kramerdb0fc512012-02-07 11:57:57 +000092 llvm::outs() << " - " << *ND;
Argyrios Kyrtzidisa11aca42010-10-14 20:14:18 +000093 llvm::outs() << "\n";
94
Argyrios Kyrtzidisb12986f2011-10-28 22:54:31 +000095 DelegatingDeserializationListener::DeclRead(ID, D);
Argyrios Kyrtzidisa11aca42010-10-14 20:14:18 +000096 }
Argyrios Kyrtzidisa11aca42010-10-14 20:14:18 +000097};
98
David Blaikie48b81282012-05-29 17:05:42 +000099/// \brief Checks deserialized declarations and emits error if a name
100/// matches one given in command-line using -error-on-deserialized-decl.
101class DeserializedDeclsChecker : public DelegatingDeserializationListener {
102 ASTContext &Ctx;
103 std::set<std::string> NamesToCheck;
Argyrios Kyrtzidis0427be92010-10-14 20:14:25 +0000104
David Blaikie48b81282012-05-29 17:05:42 +0000105public:
106 DeserializedDeclsChecker(ASTContext &Ctx,
107 const std::set<std::string> &NamesToCheck,
Nico Weber824285e2014-05-08 04:26:47 +0000108 ASTDeserializationListener *Previous,
109 bool DeletePrevious)
110 : DelegatingDeserializationListener(Previous, DeletePrevious), Ctx(Ctx),
111 NamesToCheck(NamesToCheck) {}
Argyrios Kyrtzidis0427be92010-10-14 20:14:25 +0000112
Craig Topperafa7cb32014-03-13 06:07:04 +0000113 void DeclRead(serialization::DeclID ID, const Decl *D) override {
David Blaikie48b81282012-05-29 17:05:42 +0000114 if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
115 if (NamesToCheck.find(ND->getNameAsString()) != NamesToCheck.end()) {
116 unsigned DiagID
117 = Ctx.getDiagnostics().getCustomDiagID(DiagnosticsEngine::Error,
118 "%0 was deserialized");
119 Ctx.getDiagnostics().Report(Ctx.getFullLoc(D->getLocation()), DiagID)
120 << ND->getNameAsString();
121 }
Argyrios Kyrtzidis0427be92010-10-14 20:14:25 +0000122
David Blaikie48b81282012-05-29 17:05:42 +0000123 DelegatingDeserializationListener::DeclRead(ID, D);
124 }
Argyrios Kyrtzidis0427be92010-10-14 20:14:25 +0000125};
126
Argyrios Kyrtzidisa11aca42010-10-14 20:14:18 +0000127} // end anonymous namespace
128
Craig Topper49a27902014-05-22 04:46:25 +0000129FrontendAction::FrontendAction() : Instance(nullptr) {}
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000130
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +0000131FrontendAction::~FrontendAction() {}
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000132
Douglas Gregor32fbe312012-01-20 16:28:04 +0000133void FrontendAction::setCurrentInput(const FrontendInputFile &CurrentInput,
David Blaikief62d4e72014-08-10 17:03:42 +0000134 std::unique_ptr<ASTUnit> AST) {
Douglas Gregor32fbe312012-01-20 16:28:04 +0000135 this->CurrentInput = CurrentInput;
David Blaikief62d4e72014-08-10 17:03:42 +0000136 CurrentASTUnit = std::move(AST);
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000137}
138
David Blaikie6beb6aa2014-08-10 19:56:51 +0000139std::unique_ptr<ASTConsumer>
140FrontendAction::CreateWrappedASTConsumer(CompilerInstance &CI,
141 StringRef InFile) {
142 std::unique_ptr<ASTConsumer> Consumer = CreateASTConsumer(CI, InFile);
Nico Weber2992efa2011-01-25 20:34:14 +0000143 if (!Consumer)
Craig Topper49a27902014-05-22 04:46:25 +0000144 return nullptr;
Nico Weber2992efa2011-01-25 20:34:14 +0000145
John Brawn6c789742016-03-15 12:51:40 +0000146 // If there are no registered plugins we don't need to wrap the consumer
147 if (FrontendPluginRegistry::begin() == FrontendPluginRegistry::end())
Nico Weber2992efa2011-01-25 20:34:14 +0000148 return Consumer;
149
John Brawn6c789742016-03-15 12:51:40 +0000150 // Collect the list of plugins that go before the main action (in Consumers)
151 // or after it (in AfterConsumers)
David Blaikie6beb6aa2014-08-10 19:56:51 +0000152 std::vector<std::unique_ptr<ASTConsumer>> Consumers;
John Brawn6c789742016-03-15 12:51:40 +0000153 std::vector<std::unique_ptr<ASTConsumer>> AfterConsumers;
154 for (FrontendPluginRegistry::iterator it = FrontendPluginRegistry::begin(),
155 ie = FrontendPluginRegistry::end();
156 it != ie; ++it) {
157 std::unique_ptr<PluginASTAction> P = it->instantiate();
158 PluginASTAction::ActionType ActionType = P->getActionType();
159 if (ActionType == PluginASTAction::Cmdline) {
160 // This is O(|plugins| * |add_plugins|), but since both numbers are
161 // way below 50 in practice, that's ok.
162 for (size_t i = 0, e = CI.getFrontendOpts().AddPluginActions.size();
163 i != e; ++i) {
164 if (it->getName() == CI.getFrontendOpts().AddPluginActions[i]) {
165 ActionType = PluginASTAction::AddAfterMainAction;
166 break;
167 }
168 }
Nico Weber2992efa2011-01-25 20:34:14 +0000169 }
John Brawn6c789742016-03-15 12:51:40 +0000170 if ((ActionType == PluginASTAction::AddBeforeMainAction ||
171 ActionType == PluginASTAction::AddAfterMainAction) &&
172 P->ParseArgs(CI, CI.getFrontendOpts().PluginArgs[it->getName()])) {
173 std::unique_ptr<ASTConsumer> PluginConsumer = P->CreateASTConsumer(CI, InFile);
174 if (ActionType == PluginASTAction::AddBeforeMainAction) {
175 Consumers.push_back(std::move(PluginConsumer));
176 } else {
177 AfterConsumers.push_back(std::move(PluginConsumer));
178 }
179 }
180 }
181
182 // Add to Consumers the main consumer, then all the plugins that go after it
183 Consumers.push_back(std::move(Consumer));
184 for (auto &C : AfterConsumers) {
185 Consumers.push_back(std::move(C));
Nico Weber2992efa2011-01-25 20:34:14 +0000186 }
187
David Blaikie6beb6aa2014-08-10 19:56:51 +0000188 return llvm::make_unique<MultiplexConsumer>(std::move(Consumers));
Nico Weber2992efa2011-01-25 20:34:14 +0000189}
190
Taewook Oh06b1af52017-03-07 20:20:23 +0000191// For preprocessed files, if the first line is the linemarker and specifies
192// the original source file name, use that name as the input file name.
193static bool ReadOriginalFileName(CompilerInstance &CI, std::string &InputFile)
194{
195 bool Invalid = false;
196 auto &SourceMgr = CI.getSourceManager();
197 auto MainFileID = SourceMgr.getMainFileID();
198 const auto *MainFileBuf = SourceMgr.getBuffer(MainFileID, &Invalid);
199 if (Invalid)
200 return false;
201
202 std::unique_ptr<Lexer> RawLexer(
203 new Lexer(MainFileID, MainFileBuf, SourceMgr, CI.getLangOpts()));
204
205 // If the first line has the syntax of
206 //
207 // # NUM "FILENAME"
208 //
209 // we use FILENAME as the input file name.
210 Token T;
211 if (RawLexer->LexFromRawLexer(T) || T.getKind() != tok::hash)
212 return false;
213 if (RawLexer->LexFromRawLexer(T) || T.isAtStartOfLine() ||
214 T.getKind() != tok::numeric_constant)
215 return false;
216 RawLexer->LexFromRawLexer(T);
217 if (T.isAtStartOfLine() || T.getKind() != tok::string_literal)
218 return false;
219
220 StringLiteralParser Literal(T, CI.getPreprocessor());
221 if (Literal.hadError)
222 return false;
223 InputFile = Literal.GetString().str();
224 return true;
225}
226
Richard Smithf74d9462017-04-28 01:49:42 +0000227static SmallVectorImpl<char> &
228operator+=(SmallVectorImpl<char> &Includes, StringRef RHS) {
229 Includes.append(RHS.begin(), RHS.end());
230 return Includes;
231}
232
233static void addHeaderInclude(StringRef HeaderName,
234 SmallVectorImpl<char> &Includes,
235 const LangOptions &LangOpts,
236 bool IsExternC) {
237 if (IsExternC && LangOpts.CPlusPlus)
238 Includes += "extern \"C\" {\n";
239 if (LangOpts.ObjC1)
240 Includes += "#import \"";
241 else
242 Includes += "#include \"";
243
244 Includes += HeaderName;
245
246 Includes += "\"\n";
247 if (IsExternC && LangOpts.CPlusPlus)
248 Includes += "}\n";
249}
250
251/// \brief Collect the set of header includes needed to construct the given
252/// module and update the TopHeaders file set of the module.
253///
254/// \param Module The module we're collecting includes from.
255///
256/// \param Includes Will be augmented with the set of \#includes or \#imports
257/// needed to load all of the named headers.
258static std::error_code
259collectModuleHeaderIncludes(const LangOptions &LangOpts, FileManager &FileMgr,
260 ModuleMap &ModMap, clang::Module *Module,
261 SmallVectorImpl<char> &Includes) {
262 // Don't collect any headers for unavailable modules.
263 if (!Module->isAvailable())
264 return std::error_code();
265
266 // Add includes for each of these headers.
267 for (auto HK : {Module::HK_Normal, Module::HK_Private}) {
268 for (Module::Header &H : Module->Headers[HK]) {
269 Module->addTopHeader(H.Entry);
270 // Use the path as specified in the module map file. We'll look for this
271 // file relative to the module build directory (the directory containing
272 // the module map file) so this will find the same file that we found
273 // while parsing the module map.
274 addHeaderInclude(H.NameAsWritten, Includes, LangOpts, Module->IsExternC);
275 }
276 }
277 // Note that Module->PrivateHeaders will not be a TopHeader.
278
279 if (Module::Header UmbrellaHeader = Module->getUmbrellaHeader()) {
280 Module->addTopHeader(UmbrellaHeader.Entry);
281 if (Module->Parent)
282 // Include the umbrella header for submodules.
283 addHeaderInclude(UmbrellaHeader.NameAsWritten, Includes, LangOpts,
284 Module->IsExternC);
285 } else if (Module::DirectoryName UmbrellaDir = Module->getUmbrellaDir()) {
286 // Add all of the headers we find in this subdirectory.
287 std::error_code EC;
288 SmallString<128> DirNative;
289 llvm::sys::path::native(UmbrellaDir.Entry->getName(), DirNative);
290
291 vfs::FileSystem &FS = *FileMgr.getVirtualFileSystem();
292 for (vfs::recursive_directory_iterator Dir(FS, DirNative, EC), End;
293 Dir != End && !EC; Dir.increment(EC)) {
294 // Check whether this entry has an extension typically associated with
295 // headers.
296 if (!llvm::StringSwitch<bool>(llvm::sys::path::extension(Dir->getName()))
297 .Cases(".h", ".H", ".hh", ".hpp", true)
298 .Default(false))
299 continue;
300
301 const FileEntry *Header = FileMgr.getFile(Dir->getName());
302 // FIXME: This shouldn't happen unless there is a file system race. Is
303 // that worth diagnosing?
304 if (!Header)
305 continue;
306
307 // If this header is marked 'unavailable' in this module, don't include
308 // it.
309 if (ModMap.isHeaderUnavailableInModule(Header, Module))
310 continue;
311
312 // Compute the relative path from the directory to this file.
313 SmallVector<StringRef, 16> Components;
314 auto PathIt = llvm::sys::path::rbegin(Dir->getName());
315 for (int I = 0; I != Dir.level() + 1; ++I, ++PathIt)
316 Components.push_back(*PathIt);
317 SmallString<128> RelativeHeader(UmbrellaDir.NameAsWritten);
318 for (auto It = Components.rbegin(), End = Components.rend(); It != End;
319 ++It)
320 llvm::sys::path::append(RelativeHeader, *It);
321
322 // Include this header as part of the umbrella directory.
323 Module->addTopHeader(Header);
324 addHeaderInclude(RelativeHeader, Includes, LangOpts, Module->IsExternC);
325 }
326
327 if (EC)
328 return EC;
329 }
330
331 // Recurse into submodules.
332 for (clang::Module::submodule_iterator Sub = Module->submodule_begin(),
333 SubEnd = Module->submodule_end();
334 Sub != SubEnd; ++Sub)
335 if (std::error_code Err = collectModuleHeaderIncludes(
336 LangOpts, FileMgr, ModMap, *Sub, Includes))
337 return Err;
338
339 return std::error_code();
340}
341
342/// Parse a module map and compute the corresponding real input buffer that
343/// should be used to build the module described by that module map and the
344/// current module name.
345static std::unique_ptr<llvm::MemoryBuffer>
346getInputBufferForModuleMap(CompilerInstance &CI, StringRef Filename,
347 bool IsSystem) {
348 // Find the module map file.
349 const FileEntry *ModuleMap =
350 CI.getFileManager().getFile(Filename, /*openFile*/true);
351 if (!ModuleMap) {
352 CI.getDiagnostics().Report(diag::err_module_map_not_found)
353 << Filename;
354 return nullptr;
355 }
356
357 // Find the module map file from which it was generated, if different.
358 const FileEntry *OriginalModuleMap = ModuleMap;
359 StringRef OriginalModuleMapName = CI.getFrontendOpts().OriginalModuleMap;
360 if (!OriginalModuleMapName.empty()) {
361 OriginalModuleMap = CI.getFileManager().getFile(OriginalModuleMapName,
362 /*openFile*/ true);
363 if (!OriginalModuleMap) {
364 CI.getDiagnostics().Report(diag::err_module_map_not_found)
365 << OriginalModuleMapName;
366 return nullptr;
367 }
368 }
369
370 // Parse the module map file.
371 HeaderSearch &HS = CI.getPreprocessor().getHeaderSearchInfo();
372 if (HS.loadModuleMapFile(ModuleMap, IsSystem))
373 return nullptr;
374
375 if (CI.getLangOpts().CurrentModule.empty()) {
376 CI.getDiagnostics().Report(diag::err_missing_module_name);
377
378 // FIXME: Eventually, we could consider asking whether there was just
379 // a single module described in the module map, and use that as a
380 // default. Then it would be fairly trivial to just "compile" a module
381 // map with a single module (the common case).
382 return nullptr;
383 }
384
385 // If we're being run from the command-line, the module build stack will not
386 // have been filled in yet, so complete it now in order to allow us to detect
387 // module cycles.
388 SourceManager &SourceMgr = CI.getSourceManager();
389 if (SourceMgr.getModuleBuildStack().empty())
390 SourceMgr.pushModuleBuildStack(CI.getLangOpts().CurrentModule,
391 FullSourceLoc(SourceLocation(), SourceMgr));
392
393 // Dig out the module definition.
394 Module *M = HS.lookupModule(CI.getLangOpts().CurrentModule,
395 /*AllowSearch=*/false);
396 if (!M) {
397 CI.getDiagnostics().Report(diag::err_missing_module)
398 << CI.getLangOpts().CurrentModule << Filename;
399
400 return nullptr;
401 }
402
403 // Check whether we can build this module at all.
404 clang::Module::Requirement Requirement;
405 clang::Module::UnresolvedHeaderDirective MissingHeader;
406 if (!M->isAvailable(CI.getLangOpts(), CI.getTarget(), Requirement,
407 MissingHeader)) {
408 if (MissingHeader.FileNameLoc.isValid()) {
409 CI.getDiagnostics().Report(MissingHeader.FileNameLoc,
410 diag::err_module_header_missing)
411 << MissingHeader.IsUmbrella << MissingHeader.FileName;
412 } else {
413 CI.getDiagnostics().Report(diag::err_module_unavailable)
414 << M->getFullModuleName() << Requirement.second << Requirement.first;
415 }
416
417 return nullptr;
418 }
419
420 if (OriginalModuleMap != ModuleMap) {
421 M->IsInferred = true;
422 HS.getModuleMap().setInferredModuleAllowedBy(M, OriginalModuleMap);
423 }
424
425 FileManager &FileMgr = CI.getFileManager();
426
427 // Collect the set of #includes we need to build the module.
428 SmallString<256> HeaderContents;
429 std::error_code Err = std::error_code();
430 if (Module::Header UmbrellaHeader = M->getUmbrellaHeader())
431 addHeaderInclude(UmbrellaHeader.NameAsWritten, HeaderContents,
432 CI.getLangOpts(), M->IsExternC);
433 Err = collectModuleHeaderIncludes(
434 CI.getLangOpts(), FileMgr,
435 CI.getPreprocessor().getHeaderSearchInfo().getModuleMap(), M,
436 HeaderContents);
437
438 if (Err) {
439 CI.getDiagnostics().Report(diag::err_module_cannot_create_includes)
440 << M->getFullModuleName() << Err.message();
441 return nullptr;
442 }
443
444 // Inform the preprocessor that includes from within the input buffer should
445 // be resolved relative to the build directory of the module map file.
446 CI.getPreprocessor().setMainFileDir(M->Directory);
447
448 return llvm::MemoryBuffer::getMemBufferCopy(
449 HeaderContents, Module::getModuleInputBufferName());
450}
451
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000452bool FrontendAction::BeginSourceFile(CompilerInstance &CI,
Douglas Gregor32fbe312012-01-20 16:28:04 +0000453 const FrontendInputFile &Input) {
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000454 assert(!Instance && "Already processing a source file!");
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +0000455 assert(!Input.isEmpty() && "Unexpected empty filename!");
Douglas Gregor32fbe312012-01-20 16:28:04 +0000456 setCurrentInput(Input);
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000457 setCompilerInstance(&CI);
458
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +0000459 StringRef InputFile = Input.getFile();
Richard Smithf74d9462017-04-28 01:49:42 +0000460 FrontendInputFile FileToProcess = Input;
Jordan Roseea762b02012-08-10 01:06:08 +0000461 bool HasBegunSourceFile = false;
Argyrios Kyrtzidis90b6a2a2011-06-18 00:53:41 +0000462 if (!BeginInvocation(CI))
463 goto failure;
464
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000465 // AST files follow a very different path, since they share objects via the
466 // AST unit.
Richard Smith40c0efa2017-04-26 18:57:40 +0000467 if (Input.getKind().getFormat() == InputKind::Precompiled) {
468 // FIXME: We should not be asserting on bad command-line arguments.
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000469 assert(!usesPreprocessorOnly() &&
470 "Attempt to pass AST file to preprocessor only action!");
Daniel Dunbarfa6214c2010-06-07 23:24:43 +0000471 assert(hasASTFileSupport() &&
472 "This action does not have AST file support!");
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000473
Dylan Noblesmithc95d8192012-02-20 14:00:23 +0000474 IntrusiveRefCntPtr<DiagnosticsEngine> Diags(&CI.getDiagnostics());
Alp Toker965f8822013-11-27 05:22:15 +0000475
Adrian Prantl6b21ab22015-08-27 19:46:20 +0000476 std::unique_ptr<ASTUnit> AST = ASTUnit::LoadFromASTFile(
477 InputFile, CI.getPCHContainerReader(), Diags, CI.getFileSystemOpts(),
478 CI.getCodeGenOpts().DebugTypeExtRefs);
David Blaikief62d4e72014-08-10 17:03:42 +0000479
Daniel Dunbar59203002009-12-03 01:45:44 +0000480 if (!AST)
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000481 goto failure;
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000482
Argyrios Kyrtzidisc00f43a2013-03-18 22:55:24 +0000483 // Inform the diagnostic client we are processing a source file.
Craig Topper49a27902014-05-22 04:46:25 +0000484 CI.getDiagnosticClient().BeginSourceFile(CI.getLangOpts(), nullptr);
Argyrios Kyrtzidisc00f43a2013-03-18 22:55:24 +0000485 HasBegunSourceFile = true;
486
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000487 // Set the shared objects, these are reset when we finish processing the
488 // file, otherwise the CompilerInstance will happily destroy them.
489 CI.setFileManager(&AST->getFileManager());
490 CI.setSourceManager(&AST->getSourceManager());
David Blaikie41565462017-01-05 19:48:07 +0000491 CI.setPreprocessor(AST->getPreprocessorPtr());
David Blaikieee123222017-02-08 20:51:11 +0000492 Preprocessor &PP = CI.getPreprocessor();
493 PP.getBuiltinInfo().initializeBuiltins(PP.getIdentifierTable(),
494 PP.getLangOpts());
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000495 CI.setASTContext(&AST->getASTContext());
496
David Blaikief62d4e72014-08-10 17:03:42 +0000497 setCurrentInput(Input, std::move(AST));
498
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000499 // Initialize the action.
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +0000500 if (!BeginSourceFileAction(CI, InputFile))
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000501 goto failure;
502
James Dennettf8317672013-01-23 00:45:44 +0000503 // Create the AST consumer.
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +0000504 CI.setASTConsumer(CreateWrappedASTConsumer(CI, InputFile));
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000505 if (!CI.hasASTConsumer())
506 goto failure;
507
508 return true;
509 }
510
Ben Langmuir8832c062014-04-15 18:16:25 +0000511 if (!CI.hasVirtualFileSystem()) {
512 if (IntrusiveRefCntPtr<vfs::FileSystem> VFS =
513 createVFSFromCompilerInvocation(CI.getInvocation(),
514 CI.getDiagnostics()))
515 CI.setVirtualFileSystem(VFS);
516 else
517 goto failure;
Ben Langmuir801272a2014-02-25 18:23:47 +0000518 }
519
Daniel Dunbar9507f9c2010-06-07 23:26:47 +0000520 // Set up the file and source managers, if needed.
Daniel Dunbaraed46fc2010-06-07 23:23:50 +0000521 if (!CI.hasFileManager())
522 CI.createFileManager();
523 if (!CI.hasSourceManager())
Chris Lattner5159f612010-11-23 08:35:12 +0000524 CI.createSourceManager(CI.getFileManager());
Daniel Dunbar9507f9c2010-06-07 23:26:47 +0000525
Richard Smithf74d9462017-04-28 01:49:42 +0000526 // Set up embedding for any specified files. Do this before we load any
527 // source files, including the primary module map for the compilation.
528 for (const auto &F : CI.getFrontendOpts().ModulesEmbedFiles) {
529 if (const auto *FE = CI.getFileManager().getFile(F, /*openFile*/true))
530 CI.getSourceManager().setFileIsTransient(FE);
531 else
532 CI.getDiagnostics().Report(diag::err_modules_embed_file_not_found) << F;
533 }
534 if (CI.getFrontendOpts().ModulesEmbedAllFiles)
535 CI.getSourceManager().setAllFilesAreTransient(true);
536
Daniel Dunbar9507f9c2010-06-07 23:26:47 +0000537 // IR files bypass the rest of initialization.
Richard Smith40c0efa2017-04-26 18:57:40 +0000538 if (Input.getKind().getLanguage() == InputKind::LLVM_IR) {
Daniel Dunbar9507f9c2010-06-07 23:26:47 +0000539 assert(hasIRSupport() &&
540 "This action does not have IR file support!");
541
542 // Inform the diagnostic client we are processing a source file.
Craig Topper49a27902014-05-22 04:46:25 +0000543 CI.getDiagnosticClient().BeginSourceFile(CI.getLangOpts(), nullptr);
Jordan Roseea762b02012-08-10 01:06:08 +0000544 HasBegunSourceFile = true;
Daniel Dunbar9507f9c2010-06-07 23:26:47 +0000545
546 // Initialize the action.
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +0000547 if (!BeginSourceFileAction(CI, InputFile))
Daniel Dunbar9507f9c2010-06-07 23:26:47 +0000548 goto failure;
549
Ben Langmuirbeee15e2014-04-14 18:00:01 +0000550 // Initialize the main file entry.
551 if (!CI.InitializeSourceManager(CurrentInput))
552 goto failure;
553
Daniel Dunbar9507f9c2010-06-07 23:26:47 +0000554 return true;
555 }
556
Douglas Gregorfc9e7a22012-10-23 06:18:24 +0000557 // If the implicit PCH include is actually a directory, rather than
558 // a single file, search for a suitable PCH file in that directory.
559 if (!CI.getPreprocessorOpts().ImplicitPCHInclude.empty()) {
560 FileManager &FileMgr = CI.getFileManager();
561 PreprocessorOptions &PPOpts = CI.getPreprocessorOpts();
562 StringRef PCHInclude = PPOpts.ImplicitPCHInclude;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000563 std::string SpecificModuleCachePath = CI.getSpecificModuleCachePath();
Douglas Gregorfc9e7a22012-10-23 06:18:24 +0000564 if (const DirectoryEntry *PCHDir = FileMgr.getDirectory(PCHInclude)) {
Rafael Espindolac0809172014-06-12 14:02:15 +0000565 std::error_code EC;
Douglas Gregorfc9e7a22012-10-23 06:18:24 +0000566 SmallString<128> DirNative;
567 llvm::sys::path::native(PCHDir->getName(), DirNative);
568 bool Found = false;
Bruno Cardoso Lopesb4d56f12016-12-12 19:28:21 +0000569 vfs::FileSystem &FS = *FileMgr.getVirtualFileSystem();
570 for (vfs::directory_iterator Dir = FS.dir_begin(DirNative, EC), DirEnd;
Douglas Gregorfc9e7a22012-10-23 06:18:24 +0000571 Dir != DirEnd && !EC; Dir.increment(EC)) {
572 // Check whether this is an acceptable AST file.
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000573 if (ASTReader::isAcceptableASTFile(
Bruno Cardoso Lopesb4d56f12016-12-12 19:28:21 +0000574 Dir->getName(), FileMgr, CI.getPCHContainerReader(),
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000575 CI.getLangOpts(), CI.getTargetOpts(), CI.getPreprocessorOpts(),
576 SpecificModuleCachePath)) {
Bruno Cardoso Lopesb4d56f12016-12-12 19:28:21 +0000577 PPOpts.ImplicitPCHInclude = Dir->getName();
Argyrios Kyrtzidis48b72d82013-02-05 16:36:52 +0000578 Found = true;
Douglas Gregorfc9e7a22012-10-23 06:18:24 +0000579 break;
580 }
581 }
582
583 if (!Found) {
584 CI.getDiagnostics().Report(diag::err_fe_no_pch_in_dir) << PCHInclude;
Richard Smith81c72482015-09-04 21:44:32 +0000585 goto failure;
Douglas Gregorfc9e7a22012-10-23 06:18:24 +0000586 }
587 }
588 }
589
Ted Kremenekeeccb302014-08-27 15:14:15 +0000590 // Set up the preprocessor if needed. When parsing model files the
591 // preprocessor of the original source is reused.
592 if (!isModelParsingAction())
593 CI.createPreprocessor(getTranslationUnitKind());
Daniel Dunbaraed46fc2010-06-07 23:23:50 +0000594
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000595 // Inform the diagnostic client we are processing a source file.
596 CI.getDiagnosticClient().BeginSourceFile(CI.getLangOpts(),
597 &CI.getPreprocessor());
Jordan Roseea762b02012-08-10 01:06:08 +0000598 HasBegunSourceFile = true;
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000599
Richard Smithf74d9462017-04-28 01:49:42 +0000600 // For module map files, we first parse the module map and synthesize a
601 // "<module-includes>" buffer before more conventional processing.
602 if (Input.getKind().getFormat() == InputKind::ModuleMap) {
603 CI.getLangOpts().setCompilingModule(LangOptions::CMK_ModuleMap);
604
605 auto Buffer = getInputBufferForModuleMap(CI, InputFile, Input.isSystem());
606 if (!Buffer)
607 goto failure;
608
609 Module *CurrentModule =
610 CI.getPreprocessor().getHeaderSearchInfo().lookupModule(
611 CI.getLangOpts().CurrentModule,
612 /*AllowSearch=*/false);
613 assert(CurrentModule && "no module info for current module");
614
615 // The input that we end up processing is the generated buffer, not the
616 // module map file itself.
617 FileToProcess = FrontendInputFile(
618 Buffer.release(), Input.getKind().withFormat(InputKind::Source),
619 CurrentModule->IsSystem);
620 }
621
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000622 // Initialize the action.
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +0000623 if (!BeginSourceFileAction(CI, InputFile))
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000624 goto failure;
625
Richard Smithf74d9462017-04-28 01:49:42 +0000626 // Initialize the main file entry.
627 if (!CI.InitializeSourceManager(FileToProcess))
Ben Langmuirbeee15e2014-04-14 18:00:01 +0000628 goto failure;
629
James Dennettf8317672013-01-23 00:45:44 +0000630 // Create the AST context and consumer unless this is a preprocessor only
631 // action.
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000632 if (!usesPreprocessorOnly()) {
Ted Kremenekeeccb302014-08-27 15:14:15 +0000633 // Parsing a model file should reuse the existing ASTContext.
634 if (!isModelParsingAction())
635 CI.createASTContext();
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000636
Taewook Oh06b1af52017-03-07 20:20:23 +0000637 // For preprocessed files, check if the first line specifies the original
638 // source file name with a linemarker.
639 std::string OrigFile;
640 if (Input.isPreprocessed())
641 if (ReadOriginalFileName(CI, OrigFile))
642 InputFile = OrigFile;
643
David Blaikie6beb6aa2014-08-10 19:56:51 +0000644 std::unique_ptr<ASTConsumer> Consumer =
645 CreateWrappedASTConsumer(CI, InputFile);
Fariborz Jahanian2129ccf2010-10-29 19:49:13 +0000646 if (!Consumer)
647 goto failure;
Sebastian Redl07a89a82010-07-30 00:29:29 +0000648
Ted Kremenekeeccb302014-08-27 15:14:15 +0000649 // FIXME: should not overwrite ASTMutationListener when parsing model files?
650 if (!isModelParsingAction())
651 CI.getASTContext().setASTMutationListener(Consumer->GetASTMutationListener());
Richard Smithe842a472014-10-22 02:05:46 +0000652
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +0000653 if (!CI.getPreprocessorOpts().ChainedIncludes.empty()) {
654 // Convert headers to PCH and chain them.
Alp Toker9e0523d2014-07-07 11:07:10 +0000655 IntrusiveRefCntPtr<ExternalSemaSource> source, FinalReader;
656 source = createChainedIncludesSource(CI, FinalReader);
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +0000657 if (!source)
658 goto failure;
Alp Toker9e0523d2014-07-07 11:07:10 +0000659 CI.setModuleManager(static_cast<ASTReader *>(FinalReader.get()));
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +0000660 CI.getASTContext().setExternalSource(source);
Vassil Vassileva2c2d942017-02-07 21:49:41 +0000661 } else if (CI.getLangOpts().Modules ||
662 !CI.getPreprocessorOpts().ImplicitPCHInclude.empty()) {
663 // Use PCM or PCH.
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000664 assert(hasPCHSupport() && "This action does not have PCH support!");
Douglas Gregor925296b2011-07-19 16:10:42 +0000665 ASTDeserializationListener *DeserialListener =
666 Consumer->GetASTDeserializationListener();
Nico Weber824285e2014-05-08 04:26:47 +0000667 bool DeleteDeserialListener = false;
668 if (CI.getPreprocessorOpts().DumpDeserializedPCHDecls) {
669 DeserialListener = new DeserializedDeclsDumper(DeserialListener,
670 DeleteDeserialListener);
671 DeleteDeserialListener = true;
672 }
673 if (!CI.getPreprocessorOpts().DeserializedPCHDeclsToErrorOn.empty()) {
674 DeserialListener = new DeserializedDeclsChecker(
675 CI.getASTContext(),
676 CI.getPreprocessorOpts().DeserializedPCHDeclsToErrorOn,
677 DeserialListener, DeleteDeserialListener);
678 DeleteDeserialListener = true;
679 }
Vassil Vassileva2c2d942017-02-07 21:49:41 +0000680 if (!CI.getPreprocessorOpts().ImplicitPCHInclude.empty()) {
681 CI.createPCHExternalASTSource(
682 CI.getPreprocessorOpts().ImplicitPCHInclude,
683 CI.getPreprocessorOpts().DisablePCHValidation,
Nico Weber824285e2014-05-08 04:26:47 +0000684 CI.getPreprocessorOpts().AllowPCHWithCompilerErrors, DeserialListener,
Vassil Vassileva2c2d942017-02-07 21:49:41 +0000685 DeleteDeserialListener);
686 if (!CI.getASTContext().getExternalSource())
687 goto failure;
688 }
689 // If modules are enabled, create the module manager before creating
690 // any builtins, so that all declarations know that they might be
691 // extended by an external source.
692 if (CI.getLangOpts().Modules || !CI.hasASTContext() ||
693 !CI.getASTContext().getExternalSource()) {
694 CI.createModuleManager();
695 CI.getModuleManager()->setDeserializationListener(DeserialListener,
696 DeleteDeserialListener);
697 }
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000698 }
Sebastian Redl4d3af3e2010-07-09 21:00:24 +0000699
David Blaikie6beb6aa2014-08-10 19:56:51 +0000700 CI.setASTConsumer(std::move(Consumer));
Sebastian Redl4d3af3e2010-07-09 21:00:24 +0000701 if (!CI.hasASTConsumer())
702 goto failure;
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000703 }
704
Jonathan D. Turner0248f572011-08-05 22:17:03 +0000705 // Initialize built-in info as long as we aren't using an external AST
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000706 // source.
Vassil Vassileva2c2d942017-02-07 21:49:41 +0000707 if (CI.getLangOpts().Modules || !CI.hasASTContext() ||
708 !CI.getASTContext().getExternalSource()) {
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000709 Preprocessor &PP = CI.getPreprocessor();
Eric Christopher02d5d862015-08-06 01:01:12 +0000710 PP.getBuiltinInfo().initializeBuiltins(PP.getIdentifierTable(),
David Blaikiebbafb8a2012-03-11 07:00:24 +0000711 PP.getLangOpts());
Richard Smith053f6c62014-05-16 23:01:30 +0000712 } else {
713 // FIXME: If this is a problem, recover from it by creating a multiplex
714 // source.
715 assert((!CI.getLangOpts().Modules || CI.getModuleManager()) &&
716 "modules enabled but created an external source that "
717 "doesn't support modules");
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000718 }
719
Richard Smithac425e92015-01-23 00:01:13 +0000720 // If we were asked to load any module map files, do so now.
721 for (const auto &Filename : CI.getFrontendOpts().ModuleMapFiles) {
722 if (auto *File = CI.getFileManager().getFile(Filename))
723 CI.getPreprocessor().getHeaderSearchInfo().loadModuleMapFile(
724 File, /*IsSystem*/false);
725 else
726 CI.getDiagnostics().Report(diag::err_module_map_not_found) << Filename;
727 }
728
Richard Smithd4b230b2014-10-27 23:01:16 +0000729 // If we were asked to load any module files, do so now.
730 for (const auto &ModuleFile : CI.getFrontendOpts().ModuleFiles)
731 if (!CI.loadModuleFile(ModuleFile))
Richard Smithe842a472014-10-22 02:05:46 +0000732 goto failure;
Richard Smithe842a472014-10-22 02:05:46 +0000733
Douglas Gregore9fc3772012-01-26 07:55:45 +0000734 // If there is a layout overrides file, attach an external AST source that
735 // provides the layouts from that file.
Taewook Oh06b1af52017-03-07 20:20:23 +0000736 if (!CI.getFrontendOpts().OverrideRecordLayoutsFile.empty() &&
Douglas Gregore9fc3772012-01-26 07:55:45 +0000737 CI.hasASTContext() && !CI.getASTContext().getExternalSource()) {
Taewook Oh06b1af52017-03-07 20:20:23 +0000738 IntrusiveRefCntPtr<ExternalASTSource>
Douglas Gregore9fc3772012-01-26 07:55:45 +0000739 Override(new LayoutOverrideSource(
740 CI.getFrontendOpts().OverrideRecordLayoutsFile));
741 CI.getASTContext().setExternalSource(Override);
742 }
Richard Smith053f6c62014-05-16 23:01:30 +0000743
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000744 return true;
745
746 // If we failed, reset state since the client will not end up calling the
747 // matching EndSourceFile().
748 failure:
749 if (isCurrentFileAST()) {
Craig Topper49a27902014-05-22 04:46:25 +0000750 CI.setASTContext(nullptr);
751 CI.setPreprocessor(nullptr);
752 CI.setSourceManager(nullptr);
753 CI.setFileManager(nullptr);
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000754 }
755
Jordan Roseea762b02012-08-10 01:06:08 +0000756 if (HasBegunSourceFile)
757 CI.getDiagnosticClient().EndSourceFile();
Benjamin Kramer3c717b42012-10-14 19:21:21 +0000758 CI.clearOutputFiles(/*EraseFiles=*/true);
Richard Smithf74d9462017-04-28 01:49:42 +0000759 CI.getLangOpts().setCompilingModule(LangOptions::CMK_None);
Douglas Gregor32fbe312012-01-20 16:28:04 +0000760 setCurrentInput(FrontendInputFile());
Craig Topper49a27902014-05-22 04:46:25 +0000761 setCompilerInstance(nullptr);
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000762 return false;
763}
764
Argyrios Kyrtzidis1416e172012-06-08 05:48:06 +0000765bool FrontendAction::Execute() {
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000766 CompilerInstance &CI = getCompilerInstance();
767
Kovarththanan Rajaratnam5505dff2009-11-29 09:57:35 +0000768 if (CI.hasFrontendTimer()) {
769 llvm::TimeRegion Timer(CI.getFrontendTimer());
770 ExecuteAction();
771 }
772 else ExecuteAction();
Argyrios Kyrtzidis1416e172012-06-08 05:48:06 +0000773
Douglas Gregor5e306b12013-01-23 22:38:11 +0000774 // If we are supposed to rebuild the global module index, do so now unless
Douglas Gregorc1bbec82013-01-25 00:45:27 +0000775 // there were any module-build failures.
776 if (CI.shouldBuildGlobalModuleIndex() && CI.hasFileManager() &&
777 CI.hasPreprocessor()) {
Richard Smith3938f0c2015-08-15 00:34:15 +0000778 StringRef Cache =
779 CI.getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
780 if (!Cache.empty())
781 GlobalModuleIndex::writeIndex(CI.getFileManager(),
782 CI.getPCHContainerReader(), Cache);
Douglas Gregor5e306b12013-01-23 22:38:11 +0000783 }
784
Argyrios Kyrtzidis1416e172012-06-08 05:48:06 +0000785 return true;
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000786}
787
788void FrontendAction::EndSourceFile() {
789 CompilerInstance &CI = getCompilerInstance();
790
Douglas Gregor1388a892011-02-09 18:47:31 +0000791 // Inform the diagnostic client we are done with this source file.
792 CI.getDiagnosticClient().EndSourceFile();
793
Benjamin Kramer88d99e42014-08-07 20:51:16 +0000794 // Inform the preprocessor we are done.
795 if (CI.hasPreprocessor())
796 CI.getPreprocessor().EndSourceFile();
797
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000798 // Finalize the action.
799 EndSourceFileAction();
800
Nico Weber7de358e2014-04-24 02:42:04 +0000801 // Sema references the ast consumer, so reset sema first.
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000802 //
803 // FIXME: There is more per-file stuff we could just drop here?
Nico Weber7de358e2014-04-24 02:42:04 +0000804 bool DisableFree = CI.getFrontendOpts().DisableFree;
805 if (DisableFree) {
Duncan P. N. Exon Smith4a8212a2015-05-04 14:59:20 +0000806 CI.resetAndLeakSema();
807 CI.resetAndLeakASTContext();
David Blaikie6beb6aa2014-08-10 19:56:51 +0000808 BuryPointer(CI.takeASTConsumer().get());
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000809 } else {
Duncan P. N. Exon Smith4a8212a2015-05-04 14:59:20 +0000810 CI.setSema(nullptr);
811 CI.setASTContext(nullptr);
Craig Topper49a27902014-05-22 04:46:25 +0000812 CI.setASTConsumer(nullptr);
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000813 }
814
815 if (CI.getFrontendOpts().ShowStats) {
816 llvm::errs() << "\nSTATISTICS FOR '" << getCurrentFile() << "':\n";
817 CI.getPreprocessor().PrintStats();
818 CI.getPreprocessor().getIdentifierTable().PrintStats();
819 CI.getPreprocessor().getHeaderSearchInfo().PrintStats();
820 CI.getSourceManager().PrintStats();
821 llvm::errs() << "\n";
822 }
823
Argyrios Kyrtzidisf0168de2013-06-11 00:36:55 +0000824 // Cleanup the output streams, and erase the output files if instructed by the
825 // FrontendAction.
826 CI.clearOutputFiles(/*EraseFiles=*/shouldEraseOutputFiles());
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000827
Nico Weber1f29ccf2014-04-24 03:31:27 +0000828 if (isCurrentFileAST()) {
Duncan P. N. Exon Smith4a8212a2015-05-04 14:59:20 +0000829 if (DisableFree) {
830 CI.resetAndLeakPreprocessor();
831 CI.resetAndLeakSourceManager();
832 CI.resetAndLeakFileManager();
833 } else {
834 CI.setPreprocessor(nullptr);
835 CI.setSourceManager(nullptr);
836 CI.setFileManager(nullptr);
837 }
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000838 }
839
Craig Topper49a27902014-05-22 04:46:25 +0000840 setCompilerInstance(nullptr);
Douglas Gregor32fbe312012-01-20 16:28:04 +0000841 setCurrentInput(FrontendInputFile());
Richard Smithf74d9462017-04-28 01:49:42 +0000842 CI.getLangOpts().setCompilingModule(LangOptions::CMK_None);
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000843}
844
Argyrios Kyrtzidisf0168de2013-06-11 00:36:55 +0000845bool FrontendAction::shouldEraseOutputFiles() {
846 return getCompilerInstance().getDiagnostics().hasErrorOccurred();
847}
848
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000849//===----------------------------------------------------------------------===//
850// Utility Actions
851//===----------------------------------------------------------------------===//
852
853void ASTFrontendAction::ExecuteAction() {
854 CompilerInstance &CI = getCompilerInstance();
Rafael Espindola5150f2f2013-07-28 13:23:37 +0000855 if (!CI.hasPreprocessor())
856 return;
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000857
858 // FIXME: Move the truncation aspect of this into Sema, we delayed this till
859 // here so the source manager would be initialized.
860 if (hasCodeCompletionSupport() &&
861 !CI.getFrontendOpts().CodeCompletionAt.FileName.empty())
862 CI.createCodeCompletionConsumer();
863
864 // Use a code completion consumer?
Craig Topper49a27902014-05-22 04:46:25 +0000865 CodeCompleteConsumer *CompletionConsumer = nullptr;
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000866 if (CI.hasCodeCompletionConsumer())
867 CompletionConsumer = &CI.getCodeCompletionConsumer();
868
Douglas Gregor0e93f012010-08-12 23:31:19 +0000869 if (!CI.hasSema())
Douglas Gregor69f74f82011-08-25 22:30:56 +0000870 CI.createSema(getTranslationUnitKind(), CompletionConsumer);
Douglas Gregor0e93f012010-08-12 23:31:19 +0000871
Erik Verbruggen6e922512012-04-12 10:11:59 +0000872 ParseAST(CI.getSema(), CI.getFrontendOpts().ShowStats,
873 CI.getFrontendOpts().SkipFunctionBodies);
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000874}
875
David Blaikie68e081d2011-12-20 02:48:34 +0000876void PluginASTAction::anchor() { }
877
David Blaikie6beb6aa2014-08-10 19:56:51 +0000878std::unique_ptr<ASTConsumer>
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000879PreprocessorFrontendAction::CreateASTConsumer(CompilerInstance &CI,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000880 StringRef InFile) {
Jeffrey Yasskin1615d452009-12-12 05:05:38 +0000881 llvm_unreachable("Invalid CreateASTConsumer on preprocessor action!");
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000882}
Chandler Carruthb5703512011-06-16 16:17:05 +0000883
David Blaikie6beb6aa2014-08-10 19:56:51 +0000884std::unique_ptr<ASTConsumer>
885WrapperFrontendAction::CreateASTConsumer(CompilerInstance &CI,
886 StringRef InFile) {
Chandler Carruthb5703512011-06-16 16:17:05 +0000887 return WrappedAction->CreateASTConsumer(CI, InFile);
888}
Argyrios Kyrtzidis90b6a2a2011-06-18 00:53:41 +0000889bool WrapperFrontendAction::BeginInvocation(CompilerInstance &CI) {
890 return WrappedAction->BeginInvocation(CI);
891}
Chandler Carruthb5703512011-06-16 16:17:05 +0000892bool WrapperFrontendAction::BeginSourceFileAction(CompilerInstance &CI,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000893 StringRef Filename) {
Douglas Gregor32fbe312012-01-20 16:28:04 +0000894 WrappedAction->setCurrentInput(getCurrentInput());
Argyrios Kyrtzidis90b6a2a2011-06-18 00:53:41 +0000895 WrappedAction->setCompilerInstance(&CI);
Argyrios Kyrtzidise89a1792016-02-16 05:39:33 +0000896 auto Ret = WrappedAction->BeginSourceFileAction(CI, Filename);
897 // BeginSourceFileAction may change CurrentInput, e.g. during module builds.
898 setCurrentInput(WrappedAction->getCurrentInput());
899 return Ret;
Chandler Carruthb5703512011-06-16 16:17:05 +0000900}
901void WrapperFrontendAction::ExecuteAction() {
902 WrappedAction->ExecuteAction();
903}
904void WrapperFrontendAction::EndSourceFileAction() {
905 WrappedAction->EndSourceFileAction();
906}
907
908bool WrapperFrontendAction::usesPreprocessorOnly() const {
909 return WrappedAction->usesPreprocessorOnly();
910}
Douglas Gregor69f74f82011-08-25 22:30:56 +0000911TranslationUnitKind WrapperFrontendAction::getTranslationUnitKind() {
912 return WrappedAction->getTranslationUnitKind();
Chandler Carruthb5703512011-06-16 16:17:05 +0000913}
914bool WrapperFrontendAction::hasPCHSupport() const {
915 return WrappedAction->hasPCHSupport();
916}
917bool WrapperFrontendAction::hasASTFileSupport() const {
918 return WrappedAction->hasASTFileSupport();
919}
920bool WrapperFrontendAction::hasIRSupport() const {
921 return WrappedAction->hasIRSupport();
922}
923bool WrapperFrontendAction::hasCodeCompletionSupport() const {
924 return WrappedAction->hasCodeCompletionSupport();
925}
926
Argyrios Kyrtzidisd35e98f2016-02-07 19:28:36 +0000927WrapperFrontendAction::WrapperFrontendAction(
928 std::unique_ptr<FrontendAction> WrappedAction)
929 : WrappedAction(std::move(WrappedAction)) {}
Chandler Carruthb5703512011-06-16 16:17:05 +0000930