blob: 122dc23388ccd9e951009c36e69d28b9bec42c65 [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
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000082/// Dumps deserialized declarations.
Argyrios Kyrtzidisb12986f2011-10-28 22:54:31 +000083class 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
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000099/// Checks deserialized declarations and emits error if a name
David Blaikie48b81282012-05-29 17:05:42 +0000100/// 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
Ivan Donchevskiif70d28b2018-05-17 09:15:22 +0000153 if (FrontendPluginRegistry::begin() == FrontendPluginRegistry::end())
154 return Consumer;
155
Ivan Donchevskii270ef5b2018-05-17 09:21:07 +0000156 // If this is a code completion run, avoid invoking the plugin consumers
157 if (CI.hasCodeCompletionConsumer())
158 return Consumer;
159
Ivan Donchevskiif70d28b2018-05-17 09:15:22 +0000160 // Collect the list of plugins that go before the main action (in Consumers)
161 // or after it (in AfterConsumers)
162 std::vector<std::unique_ptr<ASTConsumer>> Consumers;
John Brawn6c789742016-03-15 12:51:40 +0000163 std::vector<std::unique_ptr<ASTConsumer>> AfterConsumers;
164 for (FrontendPluginRegistry::iterator it = FrontendPluginRegistry::begin(),
165 ie = FrontendPluginRegistry::end();
166 it != ie; ++it) {
167 std::unique_ptr<PluginASTAction> P = it->instantiate();
168 PluginASTAction::ActionType ActionType = P->getActionType();
169 if (ActionType == PluginASTAction::Cmdline) {
170 // This is O(|plugins| * |add_plugins|), but since both numbers are
171 // way below 50 in practice, that's ok.
172 for (size_t i = 0, e = CI.getFrontendOpts().AddPluginActions.size();
173 i != e; ++i) {
174 if (it->getName() == CI.getFrontendOpts().AddPluginActions[i]) {
175 ActionType = PluginASTAction::AddAfterMainAction;
176 break;
177 }
178 }
Nico Weber2992efa2011-01-25 20:34:14 +0000179 }
John Brawn6c789742016-03-15 12:51:40 +0000180 if ((ActionType == PluginASTAction::AddBeforeMainAction ||
181 ActionType == PluginASTAction::AddAfterMainAction) &&
182 P->ParseArgs(CI, CI.getFrontendOpts().PluginArgs[it->getName()])) {
183 std::unique_ptr<ASTConsumer> PluginConsumer = P->CreateASTConsumer(CI, InFile);
184 if (ActionType == PluginASTAction::AddBeforeMainAction) {
185 Consumers.push_back(std::move(PluginConsumer));
186 } else {
187 AfterConsumers.push_back(std::move(PluginConsumer));
188 }
189 }
190 }
191
192 // Add to Consumers the main consumer, then all the plugins that go after it
193 Consumers.push_back(std::move(Consumer));
194 for (auto &C : AfterConsumers) {
195 Consumers.push_back(std::move(C));
Nico Weber2992efa2011-01-25 20:34:14 +0000196 }
197
David Blaikie6beb6aa2014-08-10 19:56:51 +0000198 return llvm::make_unique<MultiplexConsumer>(std::move(Consumers));
Nico Weber2992efa2011-01-25 20:34:14 +0000199}
200
Richard Smith8128f332017-05-05 22:18:51 +0000201/// For preprocessed files, if the first line is the linemarker and specifies
202/// the original source file name, use that name as the input file name.
203/// Returns the location of the first token after the line marker directive.
204///
205/// \param CI The compiler instance.
206/// \param InputFile Populated with the filename from the line marker.
Richard Smithf3f84612017-06-29 02:19:42 +0000207/// \param IsModuleMap If \c true, add a line note corresponding to this line
208/// directive. (We need to do this because the directive will not be
209/// visited by the preprocessor.)
Richard Smith8128f332017-05-05 22:18:51 +0000210static SourceLocation ReadOriginalFileName(CompilerInstance &CI,
211 std::string &InputFile,
Richard Smithf3f84612017-06-29 02:19:42 +0000212 bool IsModuleMap = false) {
Taewook Oh06b1af52017-03-07 20:20:23 +0000213 auto &SourceMgr = CI.getSourceManager();
214 auto MainFileID = SourceMgr.getMainFileID();
Richard Smith8128f332017-05-05 22:18:51 +0000215
216 bool Invalid = false;
Taewook Oh06b1af52017-03-07 20:20:23 +0000217 const auto *MainFileBuf = SourceMgr.getBuffer(MainFileID, &Invalid);
218 if (Invalid)
Richard Smith8128f332017-05-05 22:18:51 +0000219 return SourceLocation();
Taewook Oh06b1af52017-03-07 20:20:23 +0000220
221 std::unique_ptr<Lexer> RawLexer(
222 new Lexer(MainFileID, MainFileBuf, SourceMgr, CI.getLangOpts()));
223
224 // If the first line has the syntax of
225 //
226 // # NUM "FILENAME"
227 //
228 // we use FILENAME as the input file name.
229 Token T;
230 if (RawLexer->LexFromRawLexer(T) || T.getKind() != tok::hash)
Richard Smith8128f332017-05-05 22:18:51 +0000231 return SourceLocation();
Taewook Oh06b1af52017-03-07 20:20:23 +0000232 if (RawLexer->LexFromRawLexer(T) || T.isAtStartOfLine() ||
233 T.getKind() != tok::numeric_constant)
Richard Smith8128f332017-05-05 22:18:51 +0000234 return SourceLocation();
235
236 unsigned LineNo;
237 SourceLocation LineNoLoc = T.getLocation();
Richard Smithf3f84612017-06-29 02:19:42 +0000238 if (IsModuleMap) {
Richard Smith8128f332017-05-05 22:18:51 +0000239 llvm::SmallString<16> Buffer;
240 if (Lexer::getSpelling(LineNoLoc, Buffer, SourceMgr, CI.getLangOpts())
241 .getAsInteger(10, LineNo))
242 return SourceLocation();
243 }
244
Taewook Oh06b1af52017-03-07 20:20:23 +0000245 RawLexer->LexFromRawLexer(T);
246 if (T.isAtStartOfLine() || T.getKind() != tok::string_literal)
Richard Smith8128f332017-05-05 22:18:51 +0000247 return SourceLocation();
Taewook Oh06b1af52017-03-07 20:20:23 +0000248
249 StringLiteralParser Literal(T, CI.getPreprocessor());
250 if (Literal.hadError)
Richard Smith8128f332017-05-05 22:18:51 +0000251 return SourceLocation();
252 RawLexer->LexFromRawLexer(T);
253 if (T.isNot(tok::eof) && !T.isAtStartOfLine())
254 return SourceLocation();
Taewook Oh06b1af52017-03-07 20:20:23 +0000255 InputFile = Literal.GetString().str();
Richard Smith8128f332017-05-05 22:18:51 +0000256
Richard Smithf3f84612017-06-29 02:19:42 +0000257 if (IsModuleMap)
Richard Smith8128f332017-05-05 22:18:51 +0000258 CI.getSourceManager().AddLineNote(
Reid Klecknereb00ee02017-05-22 21:42:58 +0000259 LineNoLoc, LineNo, SourceMgr.getLineTableFilenameID(InputFile), false,
Richard Smithf3f84612017-06-29 02:19:42 +0000260 false, SrcMgr::C_User_ModuleMap);
Richard Smith8128f332017-05-05 22:18:51 +0000261
262 return T.getLocation();
Taewook Oh06b1af52017-03-07 20:20:23 +0000263}
264
Richard Smithf74d9462017-04-28 01:49:42 +0000265static SmallVectorImpl<char> &
266operator+=(SmallVectorImpl<char> &Includes, StringRef RHS) {
267 Includes.append(RHS.begin(), RHS.end());
268 return Includes;
269}
270
271static void addHeaderInclude(StringRef HeaderName,
272 SmallVectorImpl<char> &Includes,
273 const LangOptions &LangOpts,
274 bool IsExternC) {
275 if (IsExternC && LangOpts.CPlusPlus)
276 Includes += "extern \"C\" {\n";
277 if (LangOpts.ObjC1)
278 Includes += "#import \"";
279 else
280 Includes += "#include \"";
281
282 Includes += HeaderName;
283
284 Includes += "\"\n";
285 if (IsExternC && LangOpts.CPlusPlus)
286 Includes += "}\n";
287}
288
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000289/// Collect the set of header includes needed to construct the given
Richard Smithf74d9462017-04-28 01:49:42 +0000290/// module and update the TopHeaders file set of the module.
291///
292/// \param Module The module we're collecting includes from.
293///
294/// \param Includes Will be augmented with the set of \#includes or \#imports
295/// needed to load all of the named headers.
Richard Smith040e1262017-06-02 01:55:39 +0000296static std::error_code collectModuleHeaderIncludes(
297 const LangOptions &LangOpts, FileManager &FileMgr, DiagnosticsEngine &Diag,
298 ModuleMap &ModMap, clang::Module *Module, SmallVectorImpl<char> &Includes) {
Richard Smithf74d9462017-04-28 01:49:42 +0000299 // Don't collect any headers for unavailable modules.
300 if (!Module->isAvailable())
301 return std::error_code();
302
Richard Smith040e1262017-06-02 01:55:39 +0000303 // Resolve all lazy header directives to header files.
304 ModMap.resolveHeaderDirectives(Module);
305
306 // If any headers are missing, we can't build this module. In most cases,
307 // diagnostics for this should have already been produced; we only get here
308 // if explicit stat information was provided.
309 // FIXME: If the name resolves to a file with different stat information,
310 // produce a better diagnostic.
311 if (!Module->MissingHeaders.empty()) {
312 auto &MissingHeader = Module->MissingHeaders.front();
313 Diag.Report(MissingHeader.FileNameLoc, diag::err_module_header_missing)
314 << MissingHeader.IsUmbrella << MissingHeader.FileName;
315 return std::error_code();
316 }
317
Richard Smithf74d9462017-04-28 01:49:42 +0000318 // Add includes for each of these headers.
319 for (auto HK : {Module::HK_Normal, Module::HK_Private}) {
320 for (Module::Header &H : Module->Headers[HK]) {
321 Module->addTopHeader(H.Entry);
322 // Use the path as specified in the module map file. We'll look for this
323 // file relative to the module build directory (the directory containing
324 // the module map file) so this will find the same file that we found
325 // while parsing the module map.
326 addHeaderInclude(H.NameAsWritten, Includes, LangOpts, Module->IsExternC);
327 }
328 }
329 // Note that Module->PrivateHeaders will not be a TopHeader.
330
331 if (Module::Header UmbrellaHeader = Module->getUmbrellaHeader()) {
332 Module->addTopHeader(UmbrellaHeader.Entry);
333 if (Module->Parent)
334 // Include the umbrella header for submodules.
335 addHeaderInclude(UmbrellaHeader.NameAsWritten, Includes, LangOpts,
336 Module->IsExternC);
337 } else if (Module::DirectoryName UmbrellaDir = Module->getUmbrellaDir()) {
338 // Add all of the headers we find in this subdirectory.
339 std::error_code EC;
340 SmallString<128> DirNative;
341 llvm::sys::path::native(UmbrellaDir.Entry->getName(), DirNative);
342
343 vfs::FileSystem &FS = *FileMgr.getVirtualFileSystem();
344 for (vfs::recursive_directory_iterator Dir(FS, DirNative, EC), End;
345 Dir != End && !EC; Dir.increment(EC)) {
346 // Check whether this entry has an extension typically associated with
347 // headers.
348 if (!llvm::StringSwitch<bool>(llvm::sys::path::extension(Dir->getName()))
349 .Cases(".h", ".H", ".hh", ".hpp", true)
350 .Default(false))
351 continue;
352
353 const FileEntry *Header = FileMgr.getFile(Dir->getName());
354 // FIXME: This shouldn't happen unless there is a file system race. Is
355 // that worth diagnosing?
356 if (!Header)
357 continue;
358
359 // If this header is marked 'unavailable' in this module, don't include
360 // it.
361 if (ModMap.isHeaderUnavailableInModule(Header, Module))
362 continue;
363
364 // Compute the relative path from the directory to this file.
365 SmallVector<StringRef, 16> Components;
366 auto PathIt = llvm::sys::path::rbegin(Dir->getName());
367 for (int I = 0; I != Dir.level() + 1; ++I, ++PathIt)
368 Components.push_back(*PathIt);
369 SmallString<128> RelativeHeader(UmbrellaDir.NameAsWritten);
370 for (auto It = Components.rbegin(), End = Components.rend(); It != End;
371 ++It)
372 llvm::sys::path::append(RelativeHeader, *It);
373
374 // Include this header as part of the umbrella directory.
375 Module->addTopHeader(Header);
376 addHeaderInclude(RelativeHeader, Includes, LangOpts, Module->IsExternC);
377 }
378
379 if (EC)
380 return EC;
381 }
382
383 // Recurse into submodules.
384 for (clang::Module::submodule_iterator Sub = Module->submodule_begin(),
385 SubEnd = Module->submodule_end();
386 Sub != SubEnd; ++Sub)
387 if (std::error_code Err = collectModuleHeaderIncludes(
Richard Smith040e1262017-06-02 01:55:39 +0000388 LangOpts, FileMgr, Diag, ModMap, *Sub, Includes))
Richard Smithf74d9462017-04-28 01:49:42 +0000389 return Err;
390
391 return std::error_code();
392}
393
Richard Smithab755972017-06-05 18:10:11 +0000394static bool loadModuleMapForModuleBuild(CompilerInstance &CI, bool IsSystem,
Richard Smith8b706102017-05-31 20:56:55 +0000395 bool IsPreprocessed,
396 std::string &PresumedModuleMapFile,
397 unsigned &Offset) {
Richard Smith8128f332017-05-05 22:18:51 +0000398 auto &SrcMgr = CI.getSourceManager();
399 HeaderSearch &HS = CI.getPreprocessor().getHeaderSearchInfo();
400
401 // Map the current input to a file.
402 FileID ModuleMapID = SrcMgr.getMainFileID();
403 const FileEntry *ModuleMap = SrcMgr.getFileEntryForID(ModuleMapID);
404
405 // If the module map is preprocessed, handle the initial line marker;
406 // line directives are not part of the module map syntax in general.
407 Offset = 0;
408 if (IsPreprocessed) {
Richard Smith8128f332017-05-05 22:18:51 +0000409 SourceLocation EndOfLineMarker =
Richard Smithf3f84612017-06-29 02:19:42 +0000410 ReadOriginalFileName(CI, PresumedModuleMapFile, /*IsModuleMap*/ true);
Richard Smith8128f332017-05-05 22:18:51 +0000411 if (EndOfLineMarker.isValid())
412 Offset = CI.getSourceManager().getDecomposedLoc(EndOfLineMarker).second;
Richard Smithf74d9462017-04-28 01:49:42 +0000413 }
414
Richard Smith8128f332017-05-05 22:18:51 +0000415 // Load the module map file.
Richard Smith8b706102017-05-31 20:56:55 +0000416 if (HS.loadModuleMapFile(ModuleMap, IsSystem, ModuleMapID, &Offset,
417 PresumedModuleMapFile))
Richard Smith8128f332017-05-05 22:18:51 +0000418 return true;
419
420 if (SrcMgr.getBuffer(ModuleMapID)->getBufferSize() == Offset)
421 Offset = 0;
422
423 return false;
424}
425
426static Module *prepareToBuildModule(CompilerInstance &CI,
427 StringRef ModuleMapFilename) {
Richard Smithf74d9462017-04-28 01:49:42 +0000428 if (CI.getLangOpts().CurrentModule.empty()) {
429 CI.getDiagnostics().Report(diag::err_missing_module_name);
Richard Smith8128f332017-05-05 22:18:51 +0000430
Richard Smithf74d9462017-04-28 01:49:42 +0000431 // FIXME: Eventually, we could consider asking whether there was just
432 // a single module described in the module map, and use that as a
433 // default. Then it would be fairly trivial to just "compile" a module
434 // map with a single module (the common case).
435 return nullptr;
436 }
437
Richard Smithf74d9462017-04-28 01:49:42 +0000438 // Dig out the module definition.
Richard Smith8128f332017-05-05 22:18:51 +0000439 HeaderSearch &HS = CI.getPreprocessor().getHeaderSearchInfo();
Richard Smithf74d9462017-04-28 01:49:42 +0000440 Module *M = HS.lookupModule(CI.getLangOpts().CurrentModule,
441 /*AllowSearch=*/false);
442 if (!M) {
443 CI.getDiagnostics().Report(diag::err_missing_module)
Richard Smith8128f332017-05-05 22:18:51 +0000444 << CI.getLangOpts().CurrentModule << ModuleMapFilename;
445
Richard Smithf74d9462017-04-28 01:49:42 +0000446 return nullptr;
447 }
448
449 // Check whether we can build this module at all.
Richard Smith27e5aa02017-06-05 18:57:56 +0000450 if (Preprocessor::checkModuleIsAvailable(CI.getLangOpts(), CI.getTarget(),
451 CI.getDiagnostics(), M))
Richard Smithf74d9462017-04-28 01:49:42 +0000452 return nullptr;
Richard Smithf74d9462017-04-28 01:49:42 +0000453
Richard Smith8128f332017-05-05 22:18:51 +0000454 // Inform the preprocessor that includes from within the input buffer should
455 // be resolved relative to the build directory of the module map file.
456 CI.getPreprocessor().setMainFileDir(M->Directory);
457
458 // If the module was inferred from a different module map (via an expanded
459 // umbrella module definition), track that fact.
460 // FIXME: It would be preferable to fill this in as part of processing
461 // the module map, rather than adding it after the fact.
462 StringRef OriginalModuleMapName = CI.getFrontendOpts().OriginalModuleMap;
463 if (!OriginalModuleMapName.empty()) {
464 auto *OriginalModuleMap =
465 CI.getFileManager().getFile(OriginalModuleMapName,
466 /*openFile*/ true);
467 if (!OriginalModuleMap) {
468 CI.getDiagnostics().Report(diag::err_module_map_not_found)
469 << OriginalModuleMapName;
470 return nullptr;
471 }
472 if (OriginalModuleMap != CI.getSourceManager().getFileEntryForID(
473 CI.getSourceManager().getMainFileID())) {
474 M->IsInferred = true;
475 CI.getPreprocessor().getHeaderSearchInfo().getModuleMap()
476 .setInferredModuleAllowedBy(M, OriginalModuleMap);
477 }
Richard Smithf74d9462017-04-28 01:49:42 +0000478 }
479
Richard Smith8128f332017-05-05 22:18:51 +0000480 // If we're being run from the command-line, the module build stack will not
481 // have been filled in yet, so complete it now in order to allow us to detect
482 // module cycles.
483 SourceManager &SourceMgr = CI.getSourceManager();
484 if (SourceMgr.getModuleBuildStack().empty())
485 SourceMgr.pushModuleBuildStack(CI.getLangOpts().CurrentModule,
486 FullSourceLoc(SourceLocation(), SourceMgr));
487 return M;
488}
489
490/// Compute the input buffer that should be used to build the specified module.
491static std::unique_ptr<llvm::MemoryBuffer>
492getInputBufferForModule(CompilerInstance &CI, Module *M) {
Richard Smithf74d9462017-04-28 01:49:42 +0000493 FileManager &FileMgr = CI.getFileManager();
494
495 // Collect the set of #includes we need to build the module.
496 SmallString<256> HeaderContents;
497 std::error_code Err = std::error_code();
498 if (Module::Header UmbrellaHeader = M->getUmbrellaHeader())
499 addHeaderInclude(UmbrellaHeader.NameAsWritten, HeaderContents,
500 CI.getLangOpts(), M->IsExternC);
501 Err = collectModuleHeaderIncludes(
Richard Smith040e1262017-06-02 01:55:39 +0000502 CI.getLangOpts(), FileMgr, CI.getDiagnostics(),
Richard Smithf74d9462017-04-28 01:49:42 +0000503 CI.getPreprocessor().getHeaderSearchInfo().getModuleMap(), M,
504 HeaderContents);
505
506 if (Err) {
507 CI.getDiagnostics().Report(diag::err_module_cannot_create_includes)
508 << M->getFullModuleName() << Err.message();
509 return nullptr;
510 }
511
Richard Smithf74d9462017-04-28 01:49:42 +0000512 return llvm::MemoryBuffer::getMemBufferCopy(
513 HeaderContents, Module::getModuleInputBufferName());
514}
515
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000516bool FrontendAction::BeginSourceFile(CompilerInstance &CI,
Richard Smithab755972017-06-05 18:10:11 +0000517 const FrontendInputFile &RealInput) {
518 FrontendInputFile Input(RealInput);
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000519 assert(!Instance && "Already processing a source file!");
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +0000520 assert(!Input.isEmpty() && "Unexpected empty filename!");
Douglas Gregor32fbe312012-01-20 16:28:04 +0000521 setCurrentInput(Input);
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000522 setCompilerInstance(&CI);
523
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +0000524 StringRef InputFile = Input.getFile();
Jordan Roseea762b02012-08-10 01:06:08 +0000525 bool HasBegunSourceFile = false;
Richard Smithab755972017-06-05 18:10:11 +0000526 bool ReplayASTFile = Input.getKind().getFormat() == InputKind::Precompiled &&
527 usesPreprocessorOnly();
Argyrios Kyrtzidis90b6a2a2011-06-18 00:53:41 +0000528 if (!BeginInvocation(CI))
529 goto failure;
530
Richard Smithab755972017-06-05 18:10:11 +0000531 // If we're replaying the build of an AST file, import it and set up
532 // the initial state from its build.
533 if (ReplayASTFile) {
534 IntrusiveRefCntPtr<DiagnosticsEngine> Diags(&CI.getDiagnostics());
535
536 // The AST unit populates its own diagnostics engine rather than ours.
537 IntrusiveRefCntPtr<DiagnosticsEngine> ASTDiags(
538 new DiagnosticsEngine(Diags->getDiagnosticIDs(),
539 &Diags->getDiagnosticOptions()));
540 ASTDiags->setClient(Diags->getClient(), /*OwnsClient*/false);
541
542 std::unique_ptr<ASTUnit> AST = ASTUnit::LoadFromASTFile(
Richard Smithdbafb6c2017-06-29 23:23:46 +0000543 InputFile, CI.getPCHContainerReader(), ASTUnit::LoadPreprocessorOnly,
544 ASTDiags, CI.getFileSystemOpts(), CI.getCodeGenOpts().DebugTypeExtRefs);
Richard Smithab755972017-06-05 18:10:11 +0000545 if (!AST)
546 goto failure;
547
548 // Options relating to how we treat the input (but not what we do with it)
549 // are inherited from the AST unit.
Richard Smith18934752017-06-06 00:32:01 +0000550 CI.getHeaderSearchOpts() = AST->getHeaderSearchOpts();
551 CI.getPreprocessorOpts() = AST->getPreprocessorOpts();
Richard Smithab755972017-06-05 18:10:11 +0000552 CI.getLangOpts() = AST->getLangOpts();
553
Richard Smithab755972017-06-05 18:10:11 +0000554 // Set the shared objects, these are reset when we finish processing the
555 // file, otherwise the CompilerInstance will happily destroy them.
556 CI.setFileManager(&AST->getFileManager());
557 CI.createSourceManager(CI.getFileManager());
558 CI.getSourceManager().initializeForReplay(AST->getSourceManager());
Richard Smithab755972017-06-05 18:10:11 +0000559
Richard Smithf3f84612017-06-29 02:19:42 +0000560 // Preload all the module files loaded transitively by the AST unit. Also
561 // load all module map files that were parsed as part of building the AST
562 // unit.
563 if (auto ASTReader = AST->getASTReader()) {
564 auto &MM = ASTReader->getModuleManager();
565 auto &PrimaryModule = MM.getPrimaryModule();
566
567 for (ModuleFile &MF : MM)
568 if (&MF != &PrimaryModule)
569 CI.getFrontendOpts().ModuleFiles.push_back(MF.FileName);
570
571 ASTReader->visitTopLevelModuleMaps(PrimaryModule,
572 [&](const FileEntry *FE) {
573 CI.getFrontendOpts().ModuleMapFiles.push_back(FE->getName());
574 });
575 }
576
Richard Smithab755972017-06-05 18:10:11 +0000577 // Set up the input file for replay purposes.
578 auto Kind = AST->getInputKind();
579 if (Kind.getFormat() == InputKind::ModuleMap) {
580 Module *ASTModule =
581 AST->getPreprocessor().getHeaderSearchInfo().lookupModule(
582 AST->getLangOpts().CurrentModule, /*AllowSearch*/ false);
Richard Smithdbafb6c2017-06-29 23:23:46 +0000583 assert(ASTModule && "module file does not define its own module");
Richard Smithab755972017-06-05 18:10:11 +0000584 Input = FrontendInputFile(ASTModule->PresumedModuleMapFile, Kind);
585 } else {
586 auto &SM = CI.getSourceManager();
587 FileID ID = SM.getMainFileID();
588 if (auto *File = SM.getFileEntryForID(ID))
589 Input = FrontendInputFile(File->getName(), Kind);
590 else
591 Input = FrontendInputFile(SM.getBuffer(ID), Kind);
592 }
593 setCurrentInput(Input, std::move(AST));
594 }
595
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000596 // AST files follow a very different path, since they share objects via the
597 // AST unit.
Richard Smith40c0efa2017-04-26 18:57:40 +0000598 if (Input.getKind().getFormat() == InputKind::Precompiled) {
Richard Smithab755972017-06-05 18:10:11 +0000599 assert(!usesPreprocessorOnly() && "this case was handled above");
Daniel Dunbarfa6214c2010-06-07 23:24:43 +0000600 assert(hasASTFileSupport() &&
601 "This action does not have AST file support!");
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000602
Dylan Noblesmithc95d8192012-02-20 14:00:23 +0000603 IntrusiveRefCntPtr<DiagnosticsEngine> Diags(&CI.getDiagnostics());
Alp Toker965f8822013-11-27 05:22:15 +0000604
Adrian Prantl6b21ab22015-08-27 19:46:20 +0000605 std::unique_ptr<ASTUnit> AST = ASTUnit::LoadFromASTFile(
Richard Smithdbafb6c2017-06-29 23:23:46 +0000606 InputFile, CI.getPCHContainerReader(), ASTUnit::LoadEverything, Diags,
607 CI.getFileSystemOpts(), CI.getCodeGenOpts().DebugTypeExtRefs);
David Blaikief62d4e72014-08-10 17:03:42 +0000608
Daniel Dunbar59203002009-12-03 01:45:44 +0000609 if (!AST)
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000610 goto failure;
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000611
Argyrios Kyrtzidisc00f43a2013-03-18 22:55:24 +0000612 // Inform the diagnostic client we are processing a source file.
Craig Topper49a27902014-05-22 04:46:25 +0000613 CI.getDiagnosticClient().BeginSourceFile(CI.getLangOpts(), nullptr);
Argyrios Kyrtzidisc00f43a2013-03-18 22:55:24 +0000614 HasBegunSourceFile = true;
615
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000616 // Set the shared objects, these are reset when we finish processing the
617 // file, otherwise the CompilerInstance will happily destroy them.
618 CI.setFileManager(&AST->getFileManager());
619 CI.setSourceManager(&AST->getSourceManager());
David Blaikie41565462017-01-05 19:48:07 +0000620 CI.setPreprocessor(AST->getPreprocessorPtr());
David Blaikieee123222017-02-08 20:51:11 +0000621 Preprocessor &PP = CI.getPreprocessor();
622 PP.getBuiltinInfo().initializeBuiltins(PP.getIdentifierTable(),
623 PP.getLangOpts());
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000624 CI.setASTContext(&AST->getASTContext());
625
David Blaikief62d4e72014-08-10 17:03:42 +0000626 setCurrentInput(Input, std::move(AST));
627
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000628 // Initialize the action.
Richard Smithd9259c22017-06-09 01:36:10 +0000629 if (!BeginSourceFileAction(CI))
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000630 goto failure;
631
James Dennettf8317672013-01-23 00:45:44 +0000632 // Create the AST consumer.
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +0000633 CI.setASTConsumer(CreateWrappedASTConsumer(CI, InputFile));
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000634 if (!CI.hasASTConsumer())
635 goto failure;
636
637 return true;
638 }
639
Daniel Dunbar9507f9c2010-06-07 23:26:47 +0000640 // Set up the file and source managers, if needed.
Raphael Isemannabc3d042017-09-12 16:54:53 +0000641 if (!CI.hasFileManager()) {
642 if (!CI.createFileManager()) {
643 goto failure;
644 }
645 }
Daniel Dunbaraed46fc2010-06-07 23:23:50 +0000646 if (!CI.hasSourceManager())
Chris Lattner5159f612010-11-23 08:35:12 +0000647 CI.createSourceManager(CI.getFileManager());
Daniel Dunbar9507f9c2010-06-07 23:26:47 +0000648
Richard Smithf74d9462017-04-28 01:49:42 +0000649 // Set up embedding for any specified files. Do this before we load any
650 // source files, including the primary module map for the compilation.
651 for (const auto &F : CI.getFrontendOpts().ModulesEmbedFiles) {
652 if (const auto *FE = CI.getFileManager().getFile(F, /*openFile*/true))
653 CI.getSourceManager().setFileIsTransient(FE);
654 else
655 CI.getDiagnostics().Report(diag::err_modules_embed_file_not_found) << F;
656 }
657 if (CI.getFrontendOpts().ModulesEmbedAllFiles)
658 CI.getSourceManager().setAllFilesAreTransient(true);
659
Daniel Dunbar9507f9c2010-06-07 23:26:47 +0000660 // IR files bypass the rest of initialization.
Richard Smith40c0efa2017-04-26 18:57:40 +0000661 if (Input.getKind().getLanguage() == InputKind::LLVM_IR) {
Daniel Dunbar9507f9c2010-06-07 23:26:47 +0000662 assert(hasIRSupport() &&
663 "This action does not have IR file support!");
664
665 // Inform the diagnostic client we are processing a source file.
Craig Topper49a27902014-05-22 04:46:25 +0000666 CI.getDiagnosticClient().BeginSourceFile(CI.getLangOpts(), nullptr);
Jordan Roseea762b02012-08-10 01:06:08 +0000667 HasBegunSourceFile = true;
Daniel Dunbar9507f9c2010-06-07 23:26:47 +0000668
669 // Initialize the action.
Richard Smithd9259c22017-06-09 01:36:10 +0000670 if (!BeginSourceFileAction(CI))
Daniel Dunbar9507f9c2010-06-07 23:26:47 +0000671 goto failure;
672
Ben Langmuirbeee15e2014-04-14 18:00:01 +0000673 // Initialize the main file entry.
674 if (!CI.InitializeSourceManager(CurrentInput))
675 goto failure;
676
Daniel Dunbar9507f9c2010-06-07 23:26:47 +0000677 return true;
678 }
679
Douglas Gregorfc9e7a22012-10-23 06:18:24 +0000680 // If the implicit PCH include is actually a directory, rather than
681 // a single file, search for a suitable PCH file in that directory.
682 if (!CI.getPreprocessorOpts().ImplicitPCHInclude.empty()) {
683 FileManager &FileMgr = CI.getFileManager();
684 PreprocessorOptions &PPOpts = CI.getPreprocessorOpts();
685 StringRef PCHInclude = PPOpts.ImplicitPCHInclude;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000686 std::string SpecificModuleCachePath = CI.getSpecificModuleCachePath();
Douglas Gregorfc9e7a22012-10-23 06:18:24 +0000687 if (const DirectoryEntry *PCHDir = FileMgr.getDirectory(PCHInclude)) {
Rafael Espindolac0809172014-06-12 14:02:15 +0000688 std::error_code EC;
Douglas Gregorfc9e7a22012-10-23 06:18:24 +0000689 SmallString<128> DirNative;
690 llvm::sys::path::native(PCHDir->getName(), DirNative);
691 bool Found = false;
Bruno Cardoso Lopesb4d56f12016-12-12 19:28:21 +0000692 vfs::FileSystem &FS = *FileMgr.getVirtualFileSystem();
693 for (vfs::directory_iterator Dir = FS.dir_begin(DirNative, EC), DirEnd;
Douglas Gregorfc9e7a22012-10-23 06:18:24 +0000694 Dir != DirEnd && !EC; Dir.increment(EC)) {
695 // Check whether this is an acceptable AST file.
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000696 if (ASTReader::isAcceptableASTFile(
Bruno Cardoso Lopesb4d56f12016-12-12 19:28:21 +0000697 Dir->getName(), FileMgr, CI.getPCHContainerReader(),
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000698 CI.getLangOpts(), CI.getTargetOpts(), CI.getPreprocessorOpts(),
699 SpecificModuleCachePath)) {
Bruno Cardoso Lopesb4d56f12016-12-12 19:28:21 +0000700 PPOpts.ImplicitPCHInclude = Dir->getName();
Argyrios Kyrtzidis48b72d82013-02-05 16:36:52 +0000701 Found = true;
Douglas Gregorfc9e7a22012-10-23 06:18:24 +0000702 break;
703 }
704 }
705
706 if (!Found) {
707 CI.getDiagnostics().Report(diag::err_fe_no_pch_in_dir) << PCHInclude;
Richard Smith81c72482015-09-04 21:44:32 +0000708 goto failure;
Douglas Gregorfc9e7a22012-10-23 06:18:24 +0000709 }
710 }
711 }
712
Ted Kremenekeeccb302014-08-27 15:14:15 +0000713 // Set up the preprocessor if needed. When parsing model files the
714 // preprocessor of the original source is reused.
715 if (!isModelParsingAction())
716 CI.createPreprocessor(getTranslationUnitKind());
Daniel Dunbaraed46fc2010-06-07 23:23:50 +0000717
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000718 // Inform the diagnostic client we are processing a source file.
719 CI.getDiagnosticClient().BeginSourceFile(CI.getLangOpts(),
720 &CI.getPreprocessor());
Jordan Roseea762b02012-08-10 01:06:08 +0000721 HasBegunSourceFile = true;
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000722
Richard Smith8128f332017-05-05 22:18:51 +0000723 // Initialize the main file entry.
724 if (!CI.InitializeSourceManager(Input))
725 goto failure;
726
Richard Smithf74d9462017-04-28 01:49:42 +0000727 // For module map files, we first parse the module map and synthesize a
728 // "<module-includes>" buffer before more conventional processing.
729 if (Input.getKind().getFormat() == InputKind::ModuleMap) {
730 CI.getLangOpts().setCompilingModule(LangOptions::CMK_ModuleMap);
731
Richard Smith8b706102017-05-31 20:56:55 +0000732 std::string PresumedModuleMapFile;
Richard Smith8128f332017-05-05 22:18:51 +0000733 unsigned OffsetToContents;
Richard Smithab755972017-06-05 18:10:11 +0000734 if (loadModuleMapForModuleBuild(CI, Input.isSystem(),
Richard Smith8b706102017-05-31 20:56:55 +0000735 Input.isPreprocessed(),
736 PresumedModuleMapFile, OffsetToContents))
Richard Smithf74d9462017-04-28 01:49:42 +0000737 goto failure;
738
Richard Smith8128f332017-05-05 22:18:51 +0000739 auto *CurrentModule = prepareToBuildModule(CI, Input.getFile());
740 if (!CurrentModule)
741 goto failure;
Richard Smithf74d9462017-04-28 01:49:42 +0000742
Richard Smith8b706102017-05-31 20:56:55 +0000743 CurrentModule->PresumedModuleMapFile = PresumedModuleMapFile;
744
Richard Smith8128f332017-05-05 22:18:51 +0000745 if (OffsetToContents)
746 // If the module contents are in the same file, skip to them.
747 CI.getPreprocessor().setSkipMainFilePreamble(OffsetToContents, true);
748 else {
749 // Otherwise, convert the module description to a suitable input buffer.
750 auto Buffer = getInputBufferForModule(CI, CurrentModule);
751 if (!Buffer)
752 goto failure;
753
754 // Reinitialize the main file entry to refer to the new input.
Richard Smith6d9bc272017-09-09 01:14:04 +0000755 auto Kind = CurrentModule->IsSystem ? SrcMgr::C_System : SrcMgr::C_User;
756 auto &SourceMgr = CI.getSourceManager();
757 auto BufferID = SourceMgr.createFileID(std::move(Buffer), Kind);
758 assert(BufferID.isValid() && "couldn't creaate module buffer ID");
759 SourceMgr.setMainFileID(BufferID);
Richard Smith8128f332017-05-05 22:18:51 +0000760 }
Richard Smithf74d9462017-04-28 01:49:42 +0000761 }
762
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000763 // Initialize the action.
Richard Smithd9259c22017-06-09 01:36:10 +0000764 if (!BeginSourceFileAction(CI))
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000765 goto failure;
766
James Dennettf8317672013-01-23 00:45:44 +0000767 // Create the AST context and consumer unless this is a preprocessor only
768 // action.
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000769 if (!usesPreprocessorOnly()) {
Ted Kremenekeeccb302014-08-27 15:14:15 +0000770 // Parsing a model file should reuse the existing ASTContext.
771 if (!isModelParsingAction())
772 CI.createASTContext();
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000773
Taewook Oh06b1af52017-03-07 20:20:23 +0000774 // For preprocessed files, check if the first line specifies the original
775 // source file name with a linemarker.
Richard Smith8128f332017-05-05 22:18:51 +0000776 std::string PresumedInputFile = InputFile;
Taewook Oh06b1af52017-03-07 20:20:23 +0000777 if (Input.isPreprocessed())
Richard Smith8128f332017-05-05 22:18:51 +0000778 ReadOriginalFileName(CI, PresumedInputFile);
Taewook Oh06b1af52017-03-07 20:20:23 +0000779
David Blaikie6beb6aa2014-08-10 19:56:51 +0000780 std::unique_ptr<ASTConsumer> Consumer =
Richard Smith8128f332017-05-05 22:18:51 +0000781 CreateWrappedASTConsumer(CI, PresumedInputFile);
Fariborz Jahanian2129ccf2010-10-29 19:49:13 +0000782 if (!Consumer)
783 goto failure;
Sebastian Redl07a89a82010-07-30 00:29:29 +0000784
Ted Kremenekeeccb302014-08-27 15:14:15 +0000785 // FIXME: should not overwrite ASTMutationListener when parsing model files?
786 if (!isModelParsingAction())
787 CI.getASTContext().setASTMutationListener(Consumer->GetASTMutationListener());
Richard Smithe842a472014-10-22 02:05:46 +0000788
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +0000789 if (!CI.getPreprocessorOpts().ChainedIncludes.empty()) {
790 // Convert headers to PCH and chain them.
Alp Toker9e0523d2014-07-07 11:07:10 +0000791 IntrusiveRefCntPtr<ExternalSemaSource> source, FinalReader;
792 source = createChainedIncludesSource(CI, FinalReader);
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +0000793 if (!source)
794 goto failure;
Alp Toker9e0523d2014-07-07 11:07:10 +0000795 CI.setModuleManager(static_cast<ASTReader *>(FinalReader.get()));
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +0000796 CI.getASTContext().setExternalSource(source);
Vassil Vassileva2c2d942017-02-07 21:49:41 +0000797 } else if (CI.getLangOpts().Modules ||
798 !CI.getPreprocessorOpts().ImplicitPCHInclude.empty()) {
799 // Use PCM or PCH.
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000800 assert(hasPCHSupport() && "This action does not have PCH support!");
Douglas Gregor925296b2011-07-19 16:10:42 +0000801 ASTDeserializationListener *DeserialListener =
802 Consumer->GetASTDeserializationListener();
Nico Weber824285e2014-05-08 04:26:47 +0000803 bool DeleteDeserialListener = false;
804 if (CI.getPreprocessorOpts().DumpDeserializedPCHDecls) {
805 DeserialListener = new DeserializedDeclsDumper(DeserialListener,
806 DeleteDeserialListener);
807 DeleteDeserialListener = true;
808 }
809 if (!CI.getPreprocessorOpts().DeserializedPCHDeclsToErrorOn.empty()) {
810 DeserialListener = new DeserializedDeclsChecker(
811 CI.getASTContext(),
812 CI.getPreprocessorOpts().DeserializedPCHDeclsToErrorOn,
813 DeserialListener, DeleteDeserialListener);
814 DeleteDeserialListener = true;
815 }
Vassil Vassileva2c2d942017-02-07 21:49:41 +0000816 if (!CI.getPreprocessorOpts().ImplicitPCHInclude.empty()) {
817 CI.createPCHExternalASTSource(
818 CI.getPreprocessorOpts().ImplicitPCHInclude,
819 CI.getPreprocessorOpts().DisablePCHValidation,
Nico Weber824285e2014-05-08 04:26:47 +0000820 CI.getPreprocessorOpts().AllowPCHWithCompilerErrors, DeserialListener,
Vassil Vassileva2c2d942017-02-07 21:49:41 +0000821 DeleteDeserialListener);
822 if (!CI.getASTContext().getExternalSource())
823 goto failure;
824 }
825 // If modules are enabled, create the module manager before creating
826 // any builtins, so that all declarations know that they might be
827 // extended by an external source.
828 if (CI.getLangOpts().Modules || !CI.hasASTContext() ||
829 !CI.getASTContext().getExternalSource()) {
830 CI.createModuleManager();
831 CI.getModuleManager()->setDeserializationListener(DeserialListener,
832 DeleteDeserialListener);
833 }
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000834 }
Sebastian Redl4d3af3e2010-07-09 21:00:24 +0000835
David Blaikie6beb6aa2014-08-10 19:56:51 +0000836 CI.setASTConsumer(std::move(Consumer));
Sebastian Redl4d3af3e2010-07-09 21:00:24 +0000837 if (!CI.hasASTConsumer())
838 goto failure;
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000839 }
840
Jonathan D. Turner0248f572011-08-05 22:17:03 +0000841 // Initialize built-in info as long as we aren't using an external AST
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000842 // source.
Vassil Vassileva2c2d942017-02-07 21:49:41 +0000843 if (CI.getLangOpts().Modules || !CI.hasASTContext() ||
844 !CI.getASTContext().getExternalSource()) {
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000845 Preprocessor &PP = CI.getPreprocessor();
Eric Christopher02d5d862015-08-06 01:01:12 +0000846 PP.getBuiltinInfo().initializeBuiltins(PP.getIdentifierTable(),
David Blaikiebbafb8a2012-03-11 07:00:24 +0000847 PP.getLangOpts());
Richard Smith053f6c62014-05-16 23:01:30 +0000848 } else {
849 // FIXME: If this is a problem, recover from it by creating a multiplex
850 // source.
851 assert((!CI.getLangOpts().Modules || CI.getModuleManager()) &&
852 "modules enabled but created an external source that "
853 "doesn't support modules");
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000854 }
855
Richard Smithac425e92015-01-23 00:01:13 +0000856 // If we were asked to load any module map files, do so now.
857 for (const auto &Filename : CI.getFrontendOpts().ModuleMapFiles) {
858 if (auto *File = CI.getFileManager().getFile(Filename))
859 CI.getPreprocessor().getHeaderSearchInfo().loadModuleMapFile(
860 File, /*IsSystem*/false);
861 else
862 CI.getDiagnostics().Report(diag::err_module_map_not_found) << Filename;
863 }
864
Bruno Cardoso Lopesc192d192018-01-05 22:13:56 +0000865 // Add a module declaration scope so that modules from -fmodule-map-file
866 // arguments may shadow modules found implicitly in search paths.
867 CI.getPreprocessor()
868 .getHeaderSearchInfo()
869 .getModuleMap()
870 .finishModuleDeclarationScope();
871
Richard Smithd4b230b2014-10-27 23:01:16 +0000872 // If we were asked to load any module files, do so now.
873 for (const auto &ModuleFile : CI.getFrontendOpts().ModuleFiles)
874 if (!CI.loadModuleFile(ModuleFile))
Richard Smithe842a472014-10-22 02:05:46 +0000875 goto failure;
Richard Smithe842a472014-10-22 02:05:46 +0000876
Douglas Gregore9fc3772012-01-26 07:55:45 +0000877 // If there is a layout overrides file, attach an external AST source that
878 // provides the layouts from that file.
Taewook Oh06b1af52017-03-07 20:20:23 +0000879 if (!CI.getFrontendOpts().OverrideRecordLayoutsFile.empty() &&
Douglas Gregore9fc3772012-01-26 07:55:45 +0000880 CI.hasASTContext() && !CI.getASTContext().getExternalSource()) {
Taewook Oh06b1af52017-03-07 20:20:23 +0000881 IntrusiveRefCntPtr<ExternalASTSource>
Douglas Gregore9fc3772012-01-26 07:55:45 +0000882 Override(new LayoutOverrideSource(
883 CI.getFrontendOpts().OverrideRecordLayoutsFile));
884 CI.getASTContext().setExternalSource(Override);
885 }
Richard Smith053f6c62014-05-16 23:01:30 +0000886
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000887 return true;
888
889 // If we failed, reset state since the client will not end up calling the
890 // matching EndSourceFile().
Richard Smithab755972017-06-05 18:10:11 +0000891failure:
Jordan Roseea762b02012-08-10 01:06:08 +0000892 if (HasBegunSourceFile)
893 CI.getDiagnosticClient().EndSourceFile();
Benjamin Kramer3c717b42012-10-14 19:21:21 +0000894 CI.clearOutputFiles(/*EraseFiles=*/true);
Richard Smithf74d9462017-04-28 01:49:42 +0000895 CI.getLangOpts().setCompilingModule(LangOptions::CMK_None);
Douglas Gregor32fbe312012-01-20 16:28:04 +0000896 setCurrentInput(FrontendInputFile());
Craig Topper49a27902014-05-22 04:46:25 +0000897 setCompilerInstance(nullptr);
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000898 return false;
899}
900
Argyrios Kyrtzidis1416e172012-06-08 05:48:06 +0000901bool FrontendAction::Execute() {
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000902 CompilerInstance &CI = getCompilerInstance();
903
Kovarththanan Rajaratnam5505dff2009-11-29 09:57:35 +0000904 if (CI.hasFrontendTimer()) {
905 llvm::TimeRegion Timer(CI.getFrontendTimer());
906 ExecuteAction();
907 }
908 else ExecuteAction();
Argyrios Kyrtzidis1416e172012-06-08 05:48:06 +0000909
Douglas Gregor5e306b12013-01-23 22:38:11 +0000910 // If we are supposed to rebuild the global module index, do so now unless
Douglas Gregorc1bbec82013-01-25 00:45:27 +0000911 // there were any module-build failures.
912 if (CI.shouldBuildGlobalModuleIndex() && CI.hasFileManager() &&
913 CI.hasPreprocessor()) {
Richard Smith3938f0c2015-08-15 00:34:15 +0000914 StringRef Cache =
915 CI.getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
916 if (!Cache.empty())
917 GlobalModuleIndex::writeIndex(CI.getFileManager(),
918 CI.getPCHContainerReader(), Cache);
Douglas Gregor5e306b12013-01-23 22:38:11 +0000919 }
920
Argyrios Kyrtzidis1416e172012-06-08 05:48:06 +0000921 return true;
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000922}
923
924void FrontendAction::EndSourceFile() {
925 CompilerInstance &CI = getCompilerInstance();
926
Douglas Gregor1388a892011-02-09 18:47:31 +0000927 // Inform the diagnostic client we are done with this source file.
928 CI.getDiagnosticClient().EndSourceFile();
929
Benjamin Kramer88d99e42014-08-07 20:51:16 +0000930 // Inform the preprocessor we are done.
931 if (CI.hasPreprocessor())
932 CI.getPreprocessor().EndSourceFile();
933
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000934 // Finalize the action.
935 EndSourceFileAction();
936
Nico Weber7de358e2014-04-24 02:42:04 +0000937 // Sema references the ast consumer, so reset sema first.
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000938 //
939 // FIXME: There is more per-file stuff we could just drop here?
Nico Weber7de358e2014-04-24 02:42:04 +0000940 bool DisableFree = CI.getFrontendOpts().DisableFree;
941 if (DisableFree) {
Duncan P. N. Exon Smith4a8212a2015-05-04 14:59:20 +0000942 CI.resetAndLeakSema();
943 CI.resetAndLeakASTContext();
David Blaikie6beb6aa2014-08-10 19:56:51 +0000944 BuryPointer(CI.takeASTConsumer().get());
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000945 } else {
Duncan P. N. Exon Smith4a8212a2015-05-04 14:59:20 +0000946 CI.setSema(nullptr);
947 CI.setASTContext(nullptr);
Craig Topper49a27902014-05-22 04:46:25 +0000948 CI.setASTConsumer(nullptr);
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000949 }
950
951 if (CI.getFrontendOpts().ShowStats) {
952 llvm::errs() << "\nSTATISTICS FOR '" << getCurrentFile() << "':\n";
953 CI.getPreprocessor().PrintStats();
954 CI.getPreprocessor().getIdentifierTable().PrintStats();
955 CI.getPreprocessor().getHeaderSearchInfo().PrintStats();
956 CI.getSourceManager().PrintStats();
957 llvm::errs() << "\n";
958 }
959
Argyrios Kyrtzidisf0168de2013-06-11 00:36:55 +0000960 // Cleanup the output streams, and erase the output files if instructed by the
961 // FrontendAction.
962 CI.clearOutputFiles(/*EraseFiles=*/shouldEraseOutputFiles());
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000963
Nico Weber1f29ccf2014-04-24 03:31:27 +0000964 if (isCurrentFileAST()) {
Duncan P. N. Exon Smith4a8212a2015-05-04 14:59:20 +0000965 if (DisableFree) {
966 CI.resetAndLeakPreprocessor();
967 CI.resetAndLeakSourceManager();
968 CI.resetAndLeakFileManager();
Richard Smithab755972017-06-05 18:10:11 +0000969 BuryPointer(CurrentASTUnit.release());
Duncan P. N. Exon Smith4a8212a2015-05-04 14:59:20 +0000970 } else {
971 CI.setPreprocessor(nullptr);
972 CI.setSourceManager(nullptr);
973 CI.setFileManager(nullptr);
974 }
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000975 }
976
Craig Topper49a27902014-05-22 04:46:25 +0000977 setCompilerInstance(nullptr);
Douglas Gregor32fbe312012-01-20 16:28:04 +0000978 setCurrentInput(FrontendInputFile());
Richard Smithf74d9462017-04-28 01:49:42 +0000979 CI.getLangOpts().setCompilingModule(LangOptions::CMK_None);
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000980}
981
Argyrios Kyrtzidisf0168de2013-06-11 00:36:55 +0000982bool FrontendAction::shouldEraseOutputFiles() {
983 return getCompilerInstance().getDiagnostics().hasErrorOccurred();
984}
985
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000986//===----------------------------------------------------------------------===//
987// Utility Actions
988//===----------------------------------------------------------------------===//
989
990void ASTFrontendAction::ExecuteAction() {
991 CompilerInstance &CI = getCompilerInstance();
Rafael Espindola5150f2f2013-07-28 13:23:37 +0000992 if (!CI.hasPreprocessor())
993 return;
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000994
995 // FIXME: Move the truncation aspect of this into Sema, we delayed this till
996 // here so the source manager would be initialized.
997 if (hasCodeCompletionSupport() &&
998 !CI.getFrontendOpts().CodeCompletionAt.FileName.empty())
999 CI.createCodeCompletionConsumer();
1000
1001 // Use a code completion consumer?
Craig Topper49a27902014-05-22 04:46:25 +00001002 CodeCompleteConsumer *CompletionConsumer = nullptr;
Daniel Dunbara0ff58d2009-11-14 10:42:35 +00001003 if (CI.hasCodeCompletionConsumer())
1004 CompletionConsumer = &CI.getCodeCompletionConsumer();
1005
Douglas Gregor0e93f012010-08-12 23:31:19 +00001006 if (!CI.hasSema())
Douglas Gregor69f74f82011-08-25 22:30:56 +00001007 CI.createSema(getTranslationUnitKind(), CompletionConsumer);
Douglas Gregor0e93f012010-08-12 23:31:19 +00001008
Erik Verbruggen6e922512012-04-12 10:11:59 +00001009 ParseAST(CI.getSema(), CI.getFrontendOpts().ShowStats,
1010 CI.getFrontendOpts().SkipFunctionBodies);
Daniel Dunbara0ff58d2009-11-14 10:42:35 +00001011}
1012
David Blaikie68e081d2011-12-20 02:48:34 +00001013void PluginASTAction::anchor() { }
1014
David Blaikie6beb6aa2014-08-10 19:56:51 +00001015std::unique_ptr<ASTConsumer>
Daniel Dunbara0ff58d2009-11-14 10:42:35 +00001016PreprocessorFrontendAction::CreateASTConsumer(CompilerInstance &CI,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001017 StringRef InFile) {
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00001018 llvm_unreachable("Invalid CreateASTConsumer on preprocessor action!");
Daniel Dunbara0ff58d2009-11-14 10:42:35 +00001019}
Chandler Carruthb5703512011-06-16 16:17:05 +00001020
David Blaikie6beb6aa2014-08-10 19:56:51 +00001021std::unique_ptr<ASTConsumer>
1022WrapperFrontendAction::CreateASTConsumer(CompilerInstance &CI,
1023 StringRef InFile) {
Chandler Carruthb5703512011-06-16 16:17:05 +00001024 return WrappedAction->CreateASTConsumer(CI, InFile);
1025}
Argyrios Kyrtzidis90b6a2a2011-06-18 00:53:41 +00001026bool WrapperFrontendAction::BeginInvocation(CompilerInstance &CI) {
1027 return WrappedAction->BeginInvocation(CI);
1028}
Richard Smithd9259c22017-06-09 01:36:10 +00001029bool WrapperFrontendAction::BeginSourceFileAction(CompilerInstance &CI) {
Douglas Gregor32fbe312012-01-20 16:28:04 +00001030 WrappedAction->setCurrentInput(getCurrentInput());
Argyrios Kyrtzidis90b6a2a2011-06-18 00:53:41 +00001031 WrappedAction->setCompilerInstance(&CI);
Richard Smithd9259c22017-06-09 01:36:10 +00001032 auto Ret = WrappedAction->BeginSourceFileAction(CI);
Argyrios Kyrtzidise89a1792016-02-16 05:39:33 +00001033 // BeginSourceFileAction may change CurrentInput, e.g. during module builds.
1034 setCurrentInput(WrappedAction->getCurrentInput());
1035 return Ret;
Chandler Carruthb5703512011-06-16 16:17:05 +00001036}
1037void WrapperFrontendAction::ExecuteAction() {
1038 WrappedAction->ExecuteAction();
1039}
1040void WrapperFrontendAction::EndSourceFileAction() {
1041 WrappedAction->EndSourceFileAction();
1042}
1043
1044bool WrapperFrontendAction::usesPreprocessorOnly() const {
1045 return WrappedAction->usesPreprocessorOnly();
1046}
Douglas Gregor69f74f82011-08-25 22:30:56 +00001047TranslationUnitKind WrapperFrontendAction::getTranslationUnitKind() {
1048 return WrappedAction->getTranslationUnitKind();
Chandler Carruthb5703512011-06-16 16:17:05 +00001049}
1050bool WrapperFrontendAction::hasPCHSupport() const {
1051 return WrappedAction->hasPCHSupport();
1052}
1053bool WrapperFrontendAction::hasASTFileSupport() const {
1054 return WrappedAction->hasASTFileSupport();
1055}
1056bool WrapperFrontendAction::hasIRSupport() const {
1057 return WrappedAction->hasIRSupport();
1058}
1059bool WrapperFrontendAction::hasCodeCompletionSupport() const {
1060 return WrappedAction->hasCodeCompletionSupport();
1061}
1062
Argyrios Kyrtzidisd35e98f2016-02-07 19:28:36 +00001063WrapperFrontendAction::WrapperFrontendAction(
1064 std::unique_ptr<FrontendAction> WrappedAction)
1065 : WrappedAction(std::move(WrappedAction)) {}
Chandler Carruthb5703512011-06-16 16:17:05 +00001066