blob: 1fbb2b054badbfa1df461a298b9fee41de96b616 [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
Richard Smith8128f332017-05-05 22:18:51 +0000139Module *FrontendAction::getCurrentModule() const {
140 CompilerInstance &CI = getCompilerInstance();
141 return CI.getPreprocessor().getHeaderSearchInfo().lookupModule(
142 CI.getLangOpts().CurrentModule, /*AllowSearch*/false);
143}
144
David Blaikie6beb6aa2014-08-10 19:56:51 +0000145std::unique_ptr<ASTConsumer>
146FrontendAction::CreateWrappedASTConsumer(CompilerInstance &CI,
147 StringRef InFile) {
148 std::unique_ptr<ASTConsumer> Consumer = CreateASTConsumer(CI, InFile);
Nico Weber2992efa2011-01-25 20:34:14 +0000149 if (!Consumer)
Craig Topper49a27902014-05-22 04:46:25 +0000150 return nullptr;
Nico Weber2992efa2011-01-25 20:34:14 +0000151
John Brawn6c789742016-03-15 12:51:40 +0000152 // If there are no registered plugins we don't need to wrap the consumer
153 if (FrontendPluginRegistry::begin() == FrontendPluginRegistry::end())
Nico Weber2992efa2011-01-25 20:34:14 +0000154 return Consumer;
155
John Brawn6c789742016-03-15 12:51:40 +0000156 // Collect the list of plugins that go before the main action (in Consumers)
157 // or after it (in AfterConsumers)
David Blaikie6beb6aa2014-08-10 19:56:51 +0000158 std::vector<std::unique_ptr<ASTConsumer>> Consumers;
John Brawn6c789742016-03-15 12:51:40 +0000159 std::vector<std::unique_ptr<ASTConsumer>> AfterConsumers;
160 for (FrontendPluginRegistry::iterator it = FrontendPluginRegistry::begin(),
161 ie = FrontendPluginRegistry::end();
162 it != ie; ++it) {
163 std::unique_ptr<PluginASTAction> P = it->instantiate();
164 PluginASTAction::ActionType ActionType = P->getActionType();
165 if (ActionType == PluginASTAction::Cmdline) {
166 // This is O(|plugins| * |add_plugins|), but since both numbers are
167 // way below 50 in practice, that's ok.
168 for (size_t i = 0, e = CI.getFrontendOpts().AddPluginActions.size();
169 i != e; ++i) {
170 if (it->getName() == CI.getFrontendOpts().AddPluginActions[i]) {
171 ActionType = PluginASTAction::AddAfterMainAction;
172 break;
173 }
174 }
Nico Weber2992efa2011-01-25 20:34:14 +0000175 }
John Brawn6c789742016-03-15 12:51:40 +0000176 if ((ActionType == PluginASTAction::AddBeforeMainAction ||
177 ActionType == PluginASTAction::AddAfterMainAction) &&
178 P->ParseArgs(CI, CI.getFrontendOpts().PluginArgs[it->getName()])) {
179 std::unique_ptr<ASTConsumer> PluginConsumer = P->CreateASTConsumer(CI, InFile);
180 if (ActionType == PluginASTAction::AddBeforeMainAction) {
181 Consumers.push_back(std::move(PluginConsumer));
182 } else {
183 AfterConsumers.push_back(std::move(PluginConsumer));
184 }
185 }
186 }
187
188 // Add to Consumers the main consumer, then all the plugins that go after it
189 Consumers.push_back(std::move(Consumer));
190 for (auto &C : AfterConsumers) {
191 Consumers.push_back(std::move(C));
Nico Weber2992efa2011-01-25 20:34:14 +0000192 }
193
David Blaikie6beb6aa2014-08-10 19:56:51 +0000194 return llvm::make_unique<MultiplexConsumer>(std::move(Consumers));
Nico Weber2992efa2011-01-25 20:34:14 +0000195}
196
Richard Smith8128f332017-05-05 22:18:51 +0000197/// For preprocessed files, if the first line is the linemarker and specifies
198/// the original source file name, use that name as the input file name.
199/// Returns the location of the first token after the line marker directive.
200///
201/// \param CI The compiler instance.
202/// \param InputFile Populated with the filename from the line marker.
203/// \param AddLineNote If \c true, add a line note corresponding to this line
204/// directive. Only use this if the directive will not actually be
205/// visited by the preprocessor.
206static SourceLocation ReadOriginalFileName(CompilerInstance &CI,
207 std::string &InputFile,
208 bool AddLineNote = false) {
Taewook Oh06b1af52017-03-07 20:20:23 +0000209 auto &SourceMgr = CI.getSourceManager();
210 auto MainFileID = SourceMgr.getMainFileID();
Richard Smith8128f332017-05-05 22:18:51 +0000211
212 bool Invalid = false;
Taewook Oh06b1af52017-03-07 20:20:23 +0000213 const auto *MainFileBuf = SourceMgr.getBuffer(MainFileID, &Invalid);
214 if (Invalid)
Richard Smith8128f332017-05-05 22:18:51 +0000215 return SourceLocation();
Taewook Oh06b1af52017-03-07 20:20:23 +0000216
217 std::unique_ptr<Lexer> RawLexer(
218 new Lexer(MainFileID, MainFileBuf, SourceMgr, CI.getLangOpts()));
219
220 // If the first line has the syntax of
221 //
222 // # NUM "FILENAME"
223 //
224 // we use FILENAME as the input file name.
225 Token T;
226 if (RawLexer->LexFromRawLexer(T) || T.getKind() != tok::hash)
Richard Smith8128f332017-05-05 22:18:51 +0000227 return SourceLocation();
Taewook Oh06b1af52017-03-07 20:20:23 +0000228 if (RawLexer->LexFromRawLexer(T) || T.isAtStartOfLine() ||
229 T.getKind() != tok::numeric_constant)
Richard Smith8128f332017-05-05 22:18:51 +0000230 return SourceLocation();
231
232 unsigned LineNo;
233 SourceLocation LineNoLoc = T.getLocation();
234 if (AddLineNote) {
235 llvm::SmallString<16> Buffer;
236 if (Lexer::getSpelling(LineNoLoc, Buffer, SourceMgr, CI.getLangOpts())
237 .getAsInteger(10, LineNo))
238 return SourceLocation();
239 }
240
Taewook Oh06b1af52017-03-07 20:20:23 +0000241 RawLexer->LexFromRawLexer(T);
242 if (T.isAtStartOfLine() || T.getKind() != tok::string_literal)
Richard Smith8128f332017-05-05 22:18:51 +0000243 return SourceLocation();
Taewook Oh06b1af52017-03-07 20:20:23 +0000244
245 StringLiteralParser Literal(T, CI.getPreprocessor());
246 if (Literal.hadError)
Richard Smith8128f332017-05-05 22:18:51 +0000247 return SourceLocation();
248 RawLexer->LexFromRawLexer(T);
249 if (T.isNot(tok::eof) && !T.isAtStartOfLine())
250 return SourceLocation();
Taewook Oh06b1af52017-03-07 20:20:23 +0000251 InputFile = Literal.GetString().str();
Richard Smith8128f332017-05-05 22:18:51 +0000252
253 if (AddLineNote)
254 CI.getSourceManager().AddLineNote(
255 LineNoLoc, LineNo, SourceMgr.getLineTableFilenameID(InputFile));
256
257 return T.getLocation();
Taewook Oh06b1af52017-03-07 20:20:23 +0000258}
259
Richard Smithf74d9462017-04-28 01:49:42 +0000260static SmallVectorImpl<char> &
261operator+=(SmallVectorImpl<char> &Includes, StringRef RHS) {
262 Includes.append(RHS.begin(), RHS.end());
263 return Includes;
264}
265
266static void addHeaderInclude(StringRef HeaderName,
267 SmallVectorImpl<char> &Includes,
268 const LangOptions &LangOpts,
269 bool IsExternC) {
270 if (IsExternC && LangOpts.CPlusPlus)
271 Includes += "extern \"C\" {\n";
272 if (LangOpts.ObjC1)
273 Includes += "#import \"";
274 else
275 Includes += "#include \"";
276
277 Includes += HeaderName;
278
279 Includes += "\"\n";
280 if (IsExternC && LangOpts.CPlusPlus)
281 Includes += "}\n";
282}
283
284/// \brief Collect the set of header includes needed to construct the given
285/// module and update the TopHeaders file set of the module.
286///
287/// \param Module The module we're collecting includes from.
288///
289/// \param Includes Will be augmented with the set of \#includes or \#imports
290/// needed to load all of the named headers.
291static std::error_code
292collectModuleHeaderIncludes(const LangOptions &LangOpts, FileManager &FileMgr,
293 ModuleMap &ModMap, clang::Module *Module,
294 SmallVectorImpl<char> &Includes) {
295 // Don't collect any headers for unavailable modules.
296 if (!Module->isAvailable())
297 return std::error_code();
298
299 // Add includes for each of these headers.
300 for (auto HK : {Module::HK_Normal, Module::HK_Private}) {
301 for (Module::Header &H : Module->Headers[HK]) {
302 Module->addTopHeader(H.Entry);
303 // Use the path as specified in the module map file. We'll look for this
304 // file relative to the module build directory (the directory containing
305 // the module map file) so this will find the same file that we found
306 // while parsing the module map.
307 addHeaderInclude(H.NameAsWritten, Includes, LangOpts, Module->IsExternC);
308 }
309 }
310 // Note that Module->PrivateHeaders will not be a TopHeader.
311
312 if (Module::Header UmbrellaHeader = Module->getUmbrellaHeader()) {
313 Module->addTopHeader(UmbrellaHeader.Entry);
314 if (Module->Parent)
315 // Include the umbrella header for submodules.
316 addHeaderInclude(UmbrellaHeader.NameAsWritten, Includes, LangOpts,
317 Module->IsExternC);
318 } else if (Module::DirectoryName UmbrellaDir = Module->getUmbrellaDir()) {
319 // Add all of the headers we find in this subdirectory.
320 std::error_code EC;
321 SmallString<128> DirNative;
322 llvm::sys::path::native(UmbrellaDir.Entry->getName(), DirNative);
323
324 vfs::FileSystem &FS = *FileMgr.getVirtualFileSystem();
325 for (vfs::recursive_directory_iterator Dir(FS, DirNative, EC), End;
326 Dir != End && !EC; Dir.increment(EC)) {
327 // Check whether this entry has an extension typically associated with
328 // headers.
329 if (!llvm::StringSwitch<bool>(llvm::sys::path::extension(Dir->getName()))
330 .Cases(".h", ".H", ".hh", ".hpp", true)
331 .Default(false))
332 continue;
333
334 const FileEntry *Header = FileMgr.getFile(Dir->getName());
335 // FIXME: This shouldn't happen unless there is a file system race. Is
336 // that worth diagnosing?
337 if (!Header)
338 continue;
339
340 // If this header is marked 'unavailable' in this module, don't include
341 // it.
342 if (ModMap.isHeaderUnavailableInModule(Header, Module))
343 continue;
344
345 // Compute the relative path from the directory to this file.
346 SmallVector<StringRef, 16> Components;
347 auto PathIt = llvm::sys::path::rbegin(Dir->getName());
348 for (int I = 0; I != Dir.level() + 1; ++I, ++PathIt)
349 Components.push_back(*PathIt);
350 SmallString<128> RelativeHeader(UmbrellaDir.NameAsWritten);
351 for (auto It = Components.rbegin(), End = Components.rend(); It != End;
352 ++It)
353 llvm::sys::path::append(RelativeHeader, *It);
354
355 // Include this header as part of the umbrella directory.
356 Module->addTopHeader(Header);
357 addHeaderInclude(RelativeHeader, Includes, LangOpts, Module->IsExternC);
358 }
359
360 if (EC)
361 return EC;
362 }
363
364 // Recurse into submodules.
365 for (clang::Module::submodule_iterator Sub = Module->submodule_begin(),
366 SubEnd = Module->submodule_end();
367 Sub != SubEnd; ++Sub)
368 if (std::error_code Err = collectModuleHeaderIncludes(
369 LangOpts, FileMgr, ModMap, *Sub, Includes))
370 return Err;
371
372 return std::error_code();
373}
374
Richard Smith8128f332017-05-05 22:18:51 +0000375static bool
376loadModuleMapForModuleBuild(CompilerInstance &CI, StringRef Filename,
377 bool IsSystem, bool IsPreprocessed,
378 unsigned &Offset) {
379 auto &SrcMgr = CI.getSourceManager();
380 HeaderSearch &HS = CI.getPreprocessor().getHeaderSearchInfo();
381
382 // Map the current input to a file.
383 FileID ModuleMapID = SrcMgr.getMainFileID();
384 const FileEntry *ModuleMap = SrcMgr.getFileEntryForID(ModuleMapID);
385
386 // If the module map is preprocessed, handle the initial line marker;
387 // line directives are not part of the module map syntax in general.
388 Offset = 0;
389 if (IsPreprocessed) {
390 std::string PresumedModuleMapFile;
391 SourceLocation EndOfLineMarker =
392 ReadOriginalFileName(CI, PresumedModuleMapFile, /*AddLineNote*/true);
393 if (EndOfLineMarker.isValid())
394 Offset = CI.getSourceManager().getDecomposedLoc(EndOfLineMarker).second;
395 // FIXME: Use PresumedModuleMapFile as the MODULE_MAP_FILE in the PCM.
Richard Smithf74d9462017-04-28 01:49:42 +0000396 }
397
Richard Smith8128f332017-05-05 22:18:51 +0000398 // Load the module map file.
399 if (HS.loadModuleMapFile(ModuleMap, IsSystem, ModuleMapID, &Offset))
400 return true;
401
402 if (SrcMgr.getBuffer(ModuleMapID)->getBufferSize() == Offset)
403 Offset = 0;
404
405 return false;
406}
407
408static Module *prepareToBuildModule(CompilerInstance &CI,
409 StringRef ModuleMapFilename) {
Richard Smithf74d9462017-04-28 01:49:42 +0000410 if (CI.getLangOpts().CurrentModule.empty()) {
411 CI.getDiagnostics().Report(diag::err_missing_module_name);
Richard Smith8128f332017-05-05 22:18:51 +0000412
Richard Smithf74d9462017-04-28 01:49:42 +0000413 // FIXME: Eventually, we could consider asking whether there was just
414 // a single module described in the module map, and use that as a
415 // default. Then it would be fairly trivial to just "compile" a module
416 // map with a single module (the common case).
417 return nullptr;
418 }
419
Richard Smithf74d9462017-04-28 01:49:42 +0000420 // Dig out the module definition.
Richard Smith8128f332017-05-05 22:18:51 +0000421 HeaderSearch &HS = CI.getPreprocessor().getHeaderSearchInfo();
Richard Smithf74d9462017-04-28 01:49:42 +0000422 Module *M = HS.lookupModule(CI.getLangOpts().CurrentModule,
423 /*AllowSearch=*/false);
424 if (!M) {
425 CI.getDiagnostics().Report(diag::err_missing_module)
Richard Smith8128f332017-05-05 22:18:51 +0000426 << CI.getLangOpts().CurrentModule << ModuleMapFilename;
427
Richard Smithf74d9462017-04-28 01:49:42 +0000428 return nullptr;
429 }
430
431 // Check whether we can build this module at all.
432 clang::Module::Requirement Requirement;
433 clang::Module::UnresolvedHeaderDirective MissingHeader;
434 if (!M->isAvailable(CI.getLangOpts(), CI.getTarget(), Requirement,
435 MissingHeader)) {
436 if (MissingHeader.FileNameLoc.isValid()) {
437 CI.getDiagnostics().Report(MissingHeader.FileNameLoc,
438 diag::err_module_header_missing)
439 << MissingHeader.IsUmbrella << MissingHeader.FileName;
440 } else {
441 CI.getDiagnostics().Report(diag::err_module_unavailable)
442 << M->getFullModuleName() << Requirement.second << Requirement.first;
443 }
444
445 return nullptr;
446 }
447
Richard Smith8128f332017-05-05 22:18:51 +0000448 // Inform the preprocessor that includes from within the input buffer should
449 // be resolved relative to the build directory of the module map file.
450 CI.getPreprocessor().setMainFileDir(M->Directory);
451
452 // If the module was inferred from a different module map (via an expanded
453 // umbrella module definition), track that fact.
454 // FIXME: It would be preferable to fill this in as part of processing
455 // the module map, rather than adding it after the fact.
456 StringRef OriginalModuleMapName = CI.getFrontendOpts().OriginalModuleMap;
457 if (!OriginalModuleMapName.empty()) {
458 auto *OriginalModuleMap =
459 CI.getFileManager().getFile(OriginalModuleMapName,
460 /*openFile*/ true);
461 if (!OriginalModuleMap) {
462 CI.getDiagnostics().Report(diag::err_module_map_not_found)
463 << OriginalModuleMapName;
464 return nullptr;
465 }
466 if (OriginalModuleMap != CI.getSourceManager().getFileEntryForID(
467 CI.getSourceManager().getMainFileID())) {
468 M->IsInferred = true;
469 CI.getPreprocessor().getHeaderSearchInfo().getModuleMap()
470 .setInferredModuleAllowedBy(M, OriginalModuleMap);
471 }
Richard Smithf74d9462017-04-28 01:49:42 +0000472 }
473
Richard Smith8128f332017-05-05 22:18:51 +0000474 // If we're being run from the command-line, the module build stack will not
475 // have been filled in yet, so complete it now in order to allow us to detect
476 // module cycles.
477 SourceManager &SourceMgr = CI.getSourceManager();
478 if (SourceMgr.getModuleBuildStack().empty())
479 SourceMgr.pushModuleBuildStack(CI.getLangOpts().CurrentModule,
480 FullSourceLoc(SourceLocation(), SourceMgr));
481 return M;
482}
483
484/// Compute the input buffer that should be used to build the specified module.
485static std::unique_ptr<llvm::MemoryBuffer>
486getInputBufferForModule(CompilerInstance &CI, Module *M) {
Richard Smithf74d9462017-04-28 01:49:42 +0000487 FileManager &FileMgr = CI.getFileManager();
488
489 // Collect the set of #includes we need to build the module.
490 SmallString<256> HeaderContents;
491 std::error_code Err = std::error_code();
492 if (Module::Header UmbrellaHeader = M->getUmbrellaHeader())
493 addHeaderInclude(UmbrellaHeader.NameAsWritten, HeaderContents,
494 CI.getLangOpts(), M->IsExternC);
495 Err = collectModuleHeaderIncludes(
496 CI.getLangOpts(), FileMgr,
497 CI.getPreprocessor().getHeaderSearchInfo().getModuleMap(), M,
498 HeaderContents);
499
500 if (Err) {
501 CI.getDiagnostics().Report(diag::err_module_cannot_create_includes)
502 << M->getFullModuleName() << Err.message();
503 return nullptr;
504 }
505
Richard Smithf74d9462017-04-28 01:49:42 +0000506 return llvm::MemoryBuffer::getMemBufferCopy(
507 HeaderContents, Module::getModuleInputBufferName());
508}
509
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000510bool FrontendAction::BeginSourceFile(CompilerInstance &CI,
Douglas Gregor32fbe312012-01-20 16:28:04 +0000511 const FrontendInputFile &Input) {
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000512 assert(!Instance && "Already processing a source file!");
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +0000513 assert(!Input.isEmpty() && "Unexpected empty filename!");
Douglas Gregor32fbe312012-01-20 16:28:04 +0000514 setCurrentInput(Input);
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000515 setCompilerInstance(&CI);
516
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +0000517 StringRef InputFile = Input.getFile();
Jordan Roseea762b02012-08-10 01:06:08 +0000518 bool HasBegunSourceFile = false;
Argyrios Kyrtzidis90b6a2a2011-06-18 00:53:41 +0000519 if (!BeginInvocation(CI))
520 goto failure;
521
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000522 // AST files follow a very different path, since they share objects via the
523 // AST unit.
Richard Smith40c0efa2017-04-26 18:57:40 +0000524 if (Input.getKind().getFormat() == InputKind::Precompiled) {
525 // FIXME: We should not be asserting on bad command-line arguments.
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000526 assert(!usesPreprocessorOnly() &&
527 "Attempt to pass AST file to preprocessor only action!");
Daniel Dunbarfa6214c2010-06-07 23:24:43 +0000528 assert(hasASTFileSupport() &&
529 "This action does not have AST file support!");
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000530
Dylan Noblesmithc95d8192012-02-20 14:00:23 +0000531 IntrusiveRefCntPtr<DiagnosticsEngine> Diags(&CI.getDiagnostics());
Alp Toker965f8822013-11-27 05:22:15 +0000532
Adrian Prantl6b21ab22015-08-27 19:46:20 +0000533 std::unique_ptr<ASTUnit> AST = ASTUnit::LoadFromASTFile(
534 InputFile, CI.getPCHContainerReader(), Diags, CI.getFileSystemOpts(),
535 CI.getCodeGenOpts().DebugTypeExtRefs);
David Blaikief62d4e72014-08-10 17:03:42 +0000536
Daniel Dunbar59203002009-12-03 01:45:44 +0000537 if (!AST)
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000538 goto failure;
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000539
Argyrios Kyrtzidisc00f43a2013-03-18 22:55:24 +0000540 // Inform the diagnostic client we are processing a source file.
Craig Topper49a27902014-05-22 04:46:25 +0000541 CI.getDiagnosticClient().BeginSourceFile(CI.getLangOpts(), nullptr);
Argyrios Kyrtzidisc00f43a2013-03-18 22:55:24 +0000542 HasBegunSourceFile = true;
543
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000544 // Set the shared objects, these are reset when we finish processing the
545 // file, otherwise the CompilerInstance will happily destroy them.
546 CI.setFileManager(&AST->getFileManager());
547 CI.setSourceManager(&AST->getSourceManager());
David Blaikie41565462017-01-05 19:48:07 +0000548 CI.setPreprocessor(AST->getPreprocessorPtr());
David Blaikieee123222017-02-08 20:51:11 +0000549 Preprocessor &PP = CI.getPreprocessor();
550 PP.getBuiltinInfo().initializeBuiltins(PP.getIdentifierTable(),
551 PP.getLangOpts());
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000552 CI.setASTContext(&AST->getASTContext());
553
David Blaikief62d4e72014-08-10 17:03:42 +0000554 setCurrentInput(Input, std::move(AST));
555
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000556 // Initialize the action.
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +0000557 if (!BeginSourceFileAction(CI, InputFile))
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000558 goto failure;
559
James Dennettf8317672013-01-23 00:45:44 +0000560 // Create the AST consumer.
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +0000561 CI.setASTConsumer(CreateWrappedASTConsumer(CI, InputFile));
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000562 if (!CI.hasASTConsumer())
563 goto failure;
564
565 return true;
566 }
567
Ben Langmuir8832c062014-04-15 18:16:25 +0000568 if (!CI.hasVirtualFileSystem()) {
569 if (IntrusiveRefCntPtr<vfs::FileSystem> VFS =
570 createVFSFromCompilerInvocation(CI.getInvocation(),
571 CI.getDiagnostics()))
572 CI.setVirtualFileSystem(VFS);
573 else
574 goto failure;
Ben Langmuir801272a2014-02-25 18:23:47 +0000575 }
576
Daniel Dunbar9507f9c2010-06-07 23:26:47 +0000577 // Set up the file and source managers, if needed.
Daniel Dunbaraed46fc2010-06-07 23:23:50 +0000578 if (!CI.hasFileManager())
579 CI.createFileManager();
580 if (!CI.hasSourceManager())
Chris Lattner5159f612010-11-23 08:35:12 +0000581 CI.createSourceManager(CI.getFileManager());
Daniel Dunbar9507f9c2010-06-07 23:26:47 +0000582
Richard Smithf74d9462017-04-28 01:49:42 +0000583 // Set up embedding for any specified files. Do this before we load any
584 // source files, including the primary module map for the compilation.
585 for (const auto &F : CI.getFrontendOpts().ModulesEmbedFiles) {
586 if (const auto *FE = CI.getFileManager().getFile(F, /*openFile*/true))
587 CI.getSourceManager().setFileIsTransient(FE);
588 else
589 CI.getDiagnostics().Report(diag::err_modules_embed_file_not_found) << F;
590 }
591 if (CI.getFrontendOpts().ModulesEmbedAllFiles)
592 CI.getSourceManager().setAllFilesAreTransient(true);
593
Daniel Dunbar9507f9c2010-06-07 23:26:47 +0000594 // IR files bypass the rest of initialization.
Richard Smith40c0efa2017-04-26 18:57:40 +0000595 if (Input.getKind().getLanguage() == InputKind::LLVM_IR) {
Daniel Dunbar9507f9c2010-06-07 23:26:47 +0000596 assert(hasIRSupport() &&
597 "This action does not have IR file support!");
598
599 // Inform the diagnostic client we are processing a source file.
Craig Topper49a27902014-05-22 04:46:25 +0000600 CI.getDiagnosticClient().BeginSourceFile(CI.getLangOpts(), nullptr);
Jordan Roseea762b02012-08-10 01:06:08 +0000601 HasBegunSourceFile = true;
Daniel Dunbar9507f9c2010-06-07 23:26:47 +0000602
603 // Initialize the action.
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +0000604 if (!BeginSourceFileAction(CI, InputFile))
Daniel Dunbar9507f9c2010-06-07 23:26:47 +0000605 goto failure;
606
Ben Langmuirbeee15e2014-04-14 18:00:01 +0000607 // Initialize the main file entry.
608 if (!CI.InitializeSourceManager(CurrentInput))
609 goto failure;
610
Daniel Dunbar9507f9c2010-06-07 23:26:47 +0000611 return true;
612 }
613
Douglas Gregorfc9e7a22012-10-23 06:18:24 +0000614 // If the implicit PCH include is actually a directory, rather than
615 // a single file, search for a suitable PCH file in that directory.
616 if (!CI.getPreprocessorOpts().ImplicitPCHInclude.empty()) {
617 FileManager &FileMgr = CI.getFileManager();
618 PreprocessorOptions &PPOpts = CI.getPreprocessorOpts();
619 StringRef PCHInclude = PPOpts.ImplicitPCHInclude;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000620 std::string SpecificModuleCachePath = CI.getSpecificModuleCachePath();
Douglas Gregorfc9e7a22012-10-23 06:18:24 +0000621 if (const DirectoryEntry *PCHDir = FileMgr.getDirectory(PCHInclude)) {
Rafael Espindolac0809172014-06-12 14:02:15 +0000622 std::error_code EC;
Douglas Gregorfc9e7a22012-10-23 06:18:24 +0000623 SmallString<128> DirNative;
624 llvm::sys::path::native(PCHDir->getName(), DirNative);
625 bool Found = false;
Bruno Cardoso Lopesb4d56f12016-12-12 19:28:21 +0000626 vfs::FileSystem &FS = *FileMgr.getVirtualFileSystem();
627 for (vfs::directory_iterator Dir = FS.dir_begin(DirNative, EC), DirEnd;
Douglas Gregorfc9e7a22012-10-23 06:18:24 +0000628 Dir != DirEnd && !EC; Dir.increment(EC)) {
629 // Check whether this is an acceptable AST file.
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000630 if (ASTReader::isAcceptableASTFile(
Bruno Cardoso Lopesb4d56f12016-12-12 19:28:21 +0000631 Dir->getName(), FileMgr, CI.getPCHContainerReader(),
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000632 CI.getLangOpts(), CI.getTargetOpts(), CI.getPreprocessorOpts(),
633 SpecificModuleCachePath)) {
Bruno Cardoso Lopesb4d56f12016-12-12 19:28:21 +0000634 PPOpts.ImplicitPCHInclude = Dir->getName();
Argyrios Kyrtzidis48b72d82013-02-05 16:36:52 +0000635 Found = true;
Douglas Gregorfc9e7a22012-10-23 06:18:24 +0000636 break;
637 }
638 }
639
640 if (!Found) {
641 CI.getDiagnostics().Report(diag::err_fe_no_pch_in_dir) << PCHInclude;
Richard Smith81c72482015-09-04 21:44:32 +0000642 goto failure;
Douglas Gregorfc9e7a22012-10-23 06:18:24 +0000643 }
644 }
645 }
646
Ted Kremenekeeccb302014-08-27 15:14:15 +0000647 // Set up the preprocessor if needed. When parsing model files the
648 // preprocessor of the original source is reused.
649 if (!isModelParsingAction())
650 CI.createPreprocessor(getTranslationUnitKind());
Daniel Dunbaraed46fc2010-06-07 23:23:50 +0000651
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000652 // Inform the diagnostic client we are processing a source file.
653 CI.getDiagnosticClient().BeginSourceFile(CI.getLangOpts(),
654 &CI.getPreprocessor());
Jordan Roseea762b02012-08-10 01:06:08 +0000655 HasBegunSourceFile = true;
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000656
Richard Smith8128f332017-05-05 22:18:51 +0000657 // Initialize the main file entry.
658 if (!CI.InitializeSourceManager(Input))
659 goto failure;
660
Richard Smithf74d9462017-04-28 01:49:42 +0000661 // For module map files, we first parse the module map and synthesize a
662 // "<module-includes>" buffer before more conventional processing.
663 if (Input.getKind().getFormat() == InputKind::ModuleMap) {
664 CI.getLangOpts().setCompilingModule(LangOptions::CMK_ModuleMap);
665
Richard Smith8128f332017-05-05 22:18:51 +0000666 unsigned OffsetToContents;
667 if (loadModuleMapForModuleBuild(CI, Input.getFile(), Input.isSystem(),
668 Input.isPreprocessed(), OffsetToContents))
Richard Smithf74d9462017-04-28 01:49:42 +0000669 goto failure;
670
Richard Smith8128f332017-05-05 22:18:51 +0000671 auto *CurrentModule = prepareToBuildModule(CI, Input.getFile());
672 if (!CurrentModule)
673 goto failure;
Richard Smithf74d9462017-04-28 01:49:42 +0000674
Richard Smith8128f332017-05-05 22:18:51 +0000675 if (OffsetToContents)
676 // If the module contents are in the same file, skip to them.
677 CI.getPreprocessor().setSkipMainFilePreamble(OffsetToContents, true);
678 else {
679 // Otherwise, convert the module description to a suitable input buffer.
680 auto Buffer = getInputBufferForModule(CI, CurrentModule);
681 if (!Buffer)
682 goto failure;
683
684 // Reinitialize the main file entry to refer to the new input.
685 if (!CI.InitializeSourceManager(FrontendInputFile(
686 Buffer.release(), Input.getKind().withFormat(InputKind::Source),
687 CurrentModule->IsSystem)))
688 goto failure;
689 }
Richard Smithf74d9462017-04-28 01:49:42 +0000690 }
691
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000692 // Initialize the action.
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +0000693 if (!BeginSourceFileAction(CI, InputFile))
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000694 goto failure;
695
James Dennettf8317672013-01-23 00:45:44 +0000696 // Create the AST context and consumer unless this is a preprocessor only
697 // action.
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000698 if (!usesPreprocessorOnly()) {
Ted Kremenekeeccb302014-08-27 15:14:15 +0000699 // Parsing a model file should reuse the existing ASTContext.
700 if (!isModelParsingAction())
701 CI.createASTContext();
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000702
Taewook Oh06b1af52017-03-07 20:20:23 +0000703 // For preprocessed files, check if the first line specifies the original
704 // source file name with a linemarker.
Richard Smith8128f332017-05-05 22:18:51 +0000705 std::string PresumedInputFile = InputFile;
Taewook Oh06b1af52017-03-07 20:20:23 +0000706 if (Input.isPreprocessed())
Richard Smith8128f332017-05-05 22:18:51 +0000707 ReadOriginalFileName(CI, PresumedInputFile);
Taewook Oh06b1af52017-03-07 20:20:23 +0000708
David Blaikie6beb6aa2014-08-10 19:56:51 +0000709 std::unique_ptr<ASTConsumer> Consumer =
Richard Smith8128f332017-05-05 22:18:51 +0000710 CreateWrappedASTConsumer(CI, PresumedInputFile);
Fariborz Jahanian2129ccf2010-10-29 19:49:13 +0000711 if (!Consumer)
712 goto failure;
Sebastian Redl07a89a82010-07-30 00:29:29 +0000713
Ted Kremenekeeccb302014-08-27 15:14:15 +0000714 // FIXME: should not overwrite ASTMutationListener when parsing model files?
715 if (!isModelParsingAction())
716 CI.getASTContext().setASTMutationListener(Consumer->GetASTMutationListener());
Richard Smithe842a472014-10-22 02:05:46 +0000717
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +0000718 if (!CI.getPreprocessorOpts().ChainedIncludes.empty()) {
719 // Convert headers to PCH and chain them.
Alp Toker9e0523d2014-07-07 11:07:10 +0000720 IntrusiveRefCntPtr<ExternalSemaSource> source, FinalReader;
721 source = createChainedIncludesSource(CI, FinalReader);
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +0000722 if (!source)
723 goto failure;
Alp Toker9e0523d2014-07-07 11:07:10 +0000724 CI.setModuleManager(static_cast<ASTReader *>(FinalReader.get()));
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +0000725 CI.getASTContext().setExternalSource(source);
Vassil Vassileva2c2d942017-02-07 21:49:41 +0000726 } else if (CI.getLangOpts().Modules ||
727 !CI.getPreprocessorOpts().ImplicitPCHInclude.empty()) {
728 // Use PCM or PCH.
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000729 assert(hasPCHSupport() && "This action does not have PCH support!");
Douglas Gregor925296b2011-07-19 16:10:42 +0000730 ASTDeserializationListener *DeserialListener =
731 Consumer->GetASTDeserializationListener();
Nico Weber824285e2014-05-08 04:26:47 +0000732 bool DeleteDeserialListener = false;
733 if (CI.getPreprocessorOpts().DumpDeserializedPCHDecls) {
734 DeserialListener = new DeserializedDeclsDumper(DeserialListener,
735 DeleteDeserialListener);
736 DeleteDeserialListener = true;
737 }
738 if (!CI.getPreprocessorOpts().DeserializedPCHDeclsToErrorOn.empty()) {
739 DeserialListener = new DeserializedDeclsChecker(
740 CI.getASTContext(),
741 CI.getPreprocessorOpts().DeserializedPCHDeclsToErrorOn,
742 DeserialListener, DeleteDeserialListener);
743 DeleteDeserialListener = true;
744 }
Vassil Vassileva2c2d942017-02-07 21:49:41 +0000745 if (!CI.getPreprocessorOpts().ImplicitPCHInclude.empty()) {
746 CI.createPCHExternalASTSource(
747 CI.getPreprocessorOpts().ImplicitPCHInclude,
748 CI.getPreprocessorOpts().DisablePCHValidation,
Nico Weber824285e2014-05-08 04:26:47 +0000749 CI.getPreprocessorOpts().AllowPCHWithCompilerErrors, DeserialListener,
Vassil Vassileva2c2d942017-02-07 21:49:41 +0000750 DeleteDeserialListener);
751 if (!CI.getASTContext().getExternalSource())
752 goto failure;
753 }
754 // If modules are enabled, create the module manager before creating
755 // any builtins, so that all declarations know that they might be
756 // extended by an external source.
757 if (CI.getLangOpts().Modules || !CI.hasASTContext() ||
758 !CI.getASTContext().getExternalSource()) {
759 CI.createModuleManager();
760 CI.getModuleManager()->setDeserializationListener(DeserialListener,
761 DeleteDeserialListener);
762 }
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000763 }
Sebastian Redl4d3af3e2010-07-09 21:00:24 +0000764
David Blaikie6beb6aa2014-08-10 19:56:51 +0000765 CI.setASTConsumer(std::move(Consumer));
Sebastian Redl4d3af3e2010-07-09 21:00:24 +0000766 if (!CI.hasASTConsumer())
767 goto failure;
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000768 }
769
Jonathan D. Turner0248f572011-08-05 22:17:03 +0000770 // Initialize built-in info as long as we aren't using an external AST
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000771 // source.
Vassil Vassileva2c2d942017-02-07 21:49:41 +0000772 if (CI.getLangOpts().Modules || !CI.hasASTContext() ||
773 !CI.getASTContext().getExternalSource()) {
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000774 Preprocessor &PP = CI.getPreprocessor();
Eric Christopher02d5d862015-08-06 01:01:12 +0000775 PP.getBuiltinInfo().initializeBuiltins(PP.getIdentifierTable(),
David Blaikiebbafb8a2012-03-11 07:00:24 +0000776 PP.getLangOpts());
Richard Smith053f6c62014-05-16 23:01:30 +0000777 } else {
778 // FIXME: If this is a problem, recover from it by creating a multiplex
779 // source.
780 assert((!CI.getLangOpts().Modules || CI.getModuleManager()) &&
781 "modules enabled but created an external source that "
782 "doesn't support modules");
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000783 }
784
Richard Smithac425e92015-01-23 00:01:13 +0000785 // If we were asked to load any module map files, do so now.
786 for (const auto &Filename : CI.getFrontendOpts().ModuleMapFiles) {
787 if (auto *File = CI.getFileManager().getFile(Filename))
788 CI.getPreprocessor().getHeaderSearchInfo().loadModuleMapFile(
789 File, /*IsSystem*/false);
790 else
791 CI.getDiagnostics().Report(diag::err_module_map_not_found) << Filename;
792 }
793
Richard Smithd4b230b2014-10-27 23:01:16 +0000794 // If we were asked to load any module files, do so now.
795 for (const auto &ModuleFile : CI.getFrontendOpts().ModuleFiles)
796 if (!CI.loadModuleFile(ModuleFile))
Richard Smithe842a472014-10-22 02:05:46 +0000797 goto failure;
Richard Smithe842a472014-10-22 02:05:46 +0000798
Douglas Gregore9fc3772012-01-26 07:55:45 +0000799 // If there is a layout overrides file, attach an external AST source that
800 // provides the layouts from that file.
Taewook Oh06b1af52017-03-07 20:20:23 +0000801 if (!CI.getFrontendOpts().OverrideRecordLayoutsFile.empty() &&
Douglas Gregore9fc3772012-01-26 07:55:45 +0000802 CI.hasASTContext() && !CI.getASTContext().getExternalSource()) {
Taewook Oh06b1af52017-03-07 20:20:23 +0000803 IntrusiveRefCntPtr<ExternalASTSource>
Douglas Gregore9fc3772012-01-26 07:55:45 +0000804 Override(new LayoutOverrideSource(
805 CI.getFrontendOpts().OverrideRecordLayoutsFile));
806 CI.getASTContext().setExternalSource(Override);
807 }
Richard Smith053f6c62014-05-16 23:01:30 +0000808
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000809 return true;
810
811 // If we failed, reset state since the client will not end up calling the
812 // matching EndSourceFile().
813 failure:
814 if (isCurrentFileAST()) {
Craig Topper49a27902014-05-22 04:46:25 +0000815 CI.setASTContext(nullptr);
816 CI.setPreprocessor(nullptr);
817 CI.setSourceManager(nullptr);
818 CI.setFileManager(nullptr);
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000819 }
820
Jordan Roseea762b02012-08-10 01:06:08 +0000821 if (HasBegunSourceFile)
822 CI.getDiagnosticClient().EndSourceFile();
Benjamin Kramer3c717b42012-10-14 19:21:21 +0000823 CI.clearOutputFiles(/*EraseFiles=*/true);
Richard Smithf74d9462017-04-28 01:49:42 +0000824 CI.getLangOpts().setCompilingModule(LangOptions::CMK_None);
Douglas Gregor32fbe312012-01-20 16:28:04 +0000825 setCurrentInput(FrontendInputFile());
Craig Topper49a27902014-05-22 04:46:25 +0000826 setCompilerInstance(nullptr);
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000827 return false;
828}
829
Argyrios Kyrtzidis1416e172012-06-08 05:48:06 +0000830bool FrontendAction::Execute() {
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000831 CompilerInstance &CI = getCompilerInstance();
832
Kovarththanan Rajaratnam5505dff2009-11-29 09:57:35 +0000833 if (CI.hasFrontendTimer()) {
834 llvm::TimeRegion Timer(CI.getFrontendTimer());
835 ExecuteAction();
836 }
837 else ExecuteAction();
Argyrios Kyrtzidis1416e172012-06-08 05:48:06 +0000838
Douglas Gregor5e306b12013-01-23 22:38:11 +0000839 // If we are supposed to rebuild the global module index, do so now unless
Douglas Gregorc1bbec82013-01-25 00:45:27 +0000840 // there were any module-build failures.
841 if (CI.shouldBuildGlobalModuleIndex() && CI.hasFileManager() &&
842 CI.hasPreprocessor()) {
Richard Smith3938f0c2015-08-15 00:34:15 +0000843 StringRef Cache =
844 CI.getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
845 if (!Cache.empty())
846 GlobalModuleIndex::writeIndex(CI.getFileManager(),
847 CI.getPCHContainerReader(), Cache);
Douglas Gregor5e306b12013-01-23 22:38:11 +0000848 }
849
Argyrios Kyrtzidis1416e172012-06-08 05:48:06 +0000850 return true;
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000851}
852
853void FrontendAction::EndSourceFile() {
854 CompilerInstance &CI = getCompilerInstance();
855
Douglas Gregor1388a892011-02-09 18:47:31 +0000856 // Inform the diagnostic client we are done with this source file.
857 CI.getDiagnosticClient().EndSourceFile();
858
Benjamin Kramer88d99e42014-08-07 20:51:16 +0000859 // Inform the preprocessor we are done.
860 if (CI.hasPreprocessor())
861 CI.getPreprocessor().EndSourceFile();
862
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000863 // Finalize the action.
864 EndSourceFileAction();
865
Nico Weber7de358e2014-04-24 02:42:04 +0000866 // Sema references the ast consumer, so reset sema first.
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000867 //
868 // FIXME: There is more per-file stuff we could just drop here?
Nico Weber7de358e2014-04-24 02:42:04 +0000869 bool DisableFree = CI.getFrontendOpts().DisableFree;
870 if (DisableFree) {
Duncan P. N. Exon Smith4a8212a2015-05-04 14:59:20 +0000871 CI.resetAndLeakSema();
872 CI.resetAndLeakASTContext();
David Blaikie6beb6aa2014-08-10 19:56:51 +0000873 BuryPointer(CI.takeASTConsumer().get());
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000874 } else {
Duncan P. N. Exon Smith4a8212a2015-05-04 14:59:20 +0000875 CI.setSema(nullptr);
876 CI.setASTContext(nullptr);
Craig Topper49a27902014-05-22 04:46:25 +0000877 CI.setASTConsumer(nullptr);
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000878 }
879
880 if (CI.getFrontendOpts().ShowStats) {
881 llvm::errs() << "\nSTATISTICS FOR '" << getCurrentFile() << "':\n";
882 CI.getPreprocessor().PrintStats();
883 CI.getPreprocessor().getIdentifierTable().PrintStats();
884 CI.getPreprocessor().getHeaderSearchInfo().PrintStats();
885 CI.getSourceManager().PrintStats();
886 llvm::errs() << "\n";
887 }
888
Argyrios Kyrtzidisf0168de2013-06-11 00:36:55 +0000889 // Cleanup the output streams, and erase the output files if instructed by the
890 // FrontendAction.
891 CI.clearOutputFiles(/*EraseFiles=*/shouldEraseOutputFiles());
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000892
Nico Weber1f29ccf2014-04-24 03:31:27 +0000893 if (isCurrentFileAST()) {
Duncan P. N. Exon Smith4a8212a2015-05-04 14:59:20 +0000894 if (DisableFree) {
895 CI.resetAndLeakPreprocessor();
896 CI.resetAndLeakSourceManager();
897 CI.resetAndLeakFileManager();
898 } else {
899 CI.setPreprocessor(nullptr);
900 CI.setSourceManager(nullptr);
901 CI.setFileManager(nullptr);
902 }
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000903 }
904
Craig Topper49a27902014-05-22 04:46:25 +0000905 setCompilerInstance(nullptr);
Douglas Gregor32fbe312012-01-20 16:28:04 +0000906 setCurrentInput(FrontendInputFile());
Richard Smithf74d9462017-04-28 01:49:42 +0000907 CI.getLangOpts().setCompilingModule(LangOptions::CMK_None);
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000908}
909
Argyrios Kyrtzidisf0168de2013-06-11 00:36:55 +0000910bool FrontendAction::shouldEraseOutputFiles() {
911 return getCompilerInstance().getDiagnostics().hasErrorOccurred();
912}
913
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000914//===----------------------------------------------------------------------===//
915// Utility Actions
916//===----------------------------------------------------------------------===//
917
918void ASTFrontendAction::ExecuteAction() {
919 CompilerInstance &CI = getCompilerInstance();
Rafael Espindola5150f2f2013-07-28 13:23:37 +0000920 if (!CI.hasPreprocessor())
921 return;
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000922
923 // FIXME: Move the truncation aspect of this into Sema, we delayed this till
924 // here so the source manager would be initialized.
925 if (hasCodeCompletionSupport() &&
926 !CI.getFrontendOpts().CodeCompletionAt.FileName.empty())
927 CI.createCodeCompletionConsumer();
928
929 // Use a code completion consumer?
Craig Topper49a27902014-05-22 04:46:25 +0000930 CodeCompleteConsumer *CompletionConsumer = nullptr;
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000931 if (CI.hasCodeCompletionConsumer())
932 CompletionConsumer = &CI.getCodeCompletionConsumer();
933
Douglas Gregor0e93f012010-08-12 23:31:19 +0000934 if (!CI.hasSema())
Douglas Gregor69f74f82011-08-25 22:30:56 +0000935 CI.createSema(getTranslationUnitKind(), CompletionConsumer);
Douglas Gregor0e93f012010-08-12 23:31:19 +0000936
Erik Verbruggen6e922512012-04-12 10:11:59 +0000937 ParseAST(CI.getSema(), CI.getFrontendOpts().ShowStats,
938 CI.getFrontendOpts().SkipFunctionBodies);
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000939}
940
David Blaikie68e081d2011-12-20 02:48:34 +0000941void PluginASTAction::anchor() { }
942
David Blaikie6beb6aa2014-08-10 19:56:51 +0000943std::unique_ptr<ASTConsumer>
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000944PreprocessorFrontendAction::CreateASTConsumer(CompilerInstance &CI,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000945 StringRef InFile) {
Jeffrey Yasskin1615d452009-12-12 05:05:38 +0000946 llvm_unreachable("Invalid CreateASTConsumer on preprocessor action!");
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000947}
Chandler Carruthb5703512011-06-16 16:17:05 +0000948
David Blaikie6beb6aa2014-08-10 19:56:51 +0000949std::unique_ptr<ASTConsumer>
950WrapperFrontendAction::CreateASTConsumer(CompilerInstance &CI,
951 StringRef InFile) {
Chandler Carruthb5703512011-06-16 16:17:05 +0000952 return WrappedAction->CreateASTConsumer(CI, InFile);
953}
Argyrios Kyrtzidis90b6a2a2011-06-18 00:53:41 +0000954bool WrapperFrontendAction::BeginInvocation(CompilerInstance &CI) {
955 return WrappedAction->BeginInvocation(CI);
956}
Chandler Carruthb5703512011-06-16 16:17:05 +0000957bool WrapperFrontendAction::BeginSourceFileAction(CompilerInstance &CI,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000958 StringRef Filename) {
Douglas Gregor32fbe312012-01-20 16:28:04 +0000959 WrappedAction->setCurrentInput(getCurrentInput());
Argyrios Kyrtzidis90b6a2a2011-06-18 00:53:41 +0000960 WrappedAction->setCompilerInstance(&CI);
Argyrios Kyrtzidise89a1792016-02-16 05:39:33 +0000961 auto Ret = WrappedAction->BeginSourceFileAction(CI, Filename);
962 // BeginSourceFileAction may change CurrentInput, e.g. during module builds.
963 setCurrentInput(WrappedAction->getCurrentInput());
964 return Ret;
Chandler Carruthb5703512011-06-16 16:17:05 +0000965}
966void WrapperFrontendAction::ExecuteAction() {
967 WrappedAction->ExecuteAction();
968}
969void WrapperFrontendAction::EndSourceFileAction() {
970 WrappedAction->EndSourceFileAction();
971}
972
973bool WrapperFrontendAction::usesPreprocessorOnly() const {
974 return WrappedAction->usesPreprocessorOnly();
975}
Douglas Gregor69f74f82011-08-25 22:30:56 +0000976TranslationUnitKind WrapperFrontendAction::getTranslationUnitKind() {
977 return WrappedAction->getTranslationUnitKind();
Chandler Carruthb5703512011-06-16 16:17:05 +0000978}
979bool WrapperFrontendAction::hasPCHSupport() const {
980 return WrappedAction->hasPCHSupport();
981}
982bool WrapperFrontendAction::hasASTFileSupport() const {
983 return WrappedAction->hasASTFileSupport();
984}
985bool WrapperFrontendAction::hasIRSupport() const {
986 return WrappedAction->hasIRSupport();
987}
988bool WrapperFrontendAction::hasCodeCompletionSupport() const {
989 return WrappedAction->hasCodeCompletionSupport();
990}
991
Argyrios Kyrtzidisd35e98f2016-02-07 19:28:36 +0000992WrapperFrontendAction::WrapperFrontendAction(
993 std::unique_ptr<FrontendAction> WrappedAction)
994 : WrappedAction(std::move(WrappedAction)) {}
Chandler Carruthb5703512011-06-16 16:17:05 +0000995