blob: 704d51509851fa41d52a586cee0c17cb340d075b [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.
Richard Smithf3f84612017-06-29 02:19:42 +0000203/// \param IsModuleMap If \c true, add a line note corresponding to this line
204/// directive. (We need to do this because the directive will not be
205/// visited by the preprocessor.)
Richard Smith8128f332017-05-05 22:18:51 +0000206static SourceLocation ReadOriginalFileName(CompilerInstance &CI,
207 std::string &InputFile,
Richard Smithf3f84612017-06-29 02:19:42 +0000208 bool IsModuleMap = 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();
Richard Smithf3f84612017-06-29 02:19:42 +0000234 if (IsModuleMap) {
Richard Smith8128f332017-05-05 22:18:51 +0000235 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
Richard Smithf3f84612017-06-29 02:19:42 +0000253 if (IsModuleMap)
Richard Smith8128f332017-05-05 22:18:51 +0000254 CI.getSourceManager().AddLineNote(
Reid Klecknereb00ee02017-05-22 21:42:58 +0000255 LineNoLoc, LineNo, SourceMgr.getLineTableFilenameID(InputFile), false,
Richard Smithf3f84612017-06-29 02:19:42 +0000256 false, SrcMgr::C_User_ModuleMap);
Richard Smith8128f332017-05-05 22:18:51 +0000257
258 return T.getLocation();
Taewook Oh06b1af52017-03-07 20:20:23 +0000259}
260
Richard Smithf74d9462017-04-28 01:49:42 +0000261static SmallVectorImpl<char> &
262operator+=(SmallVectorImpl<char> &Includes, StringRef RHS) {
263 Includes.append(RHS.begin(), RHS.end());
264 return Includes;
265}
266
267static void addHeaderInclude(StringRef HeaderName,
268 SmallVectorImpl<char> &Includes,
269 const LangOptions &LangOpts,
270 bool IsExternC) {
271 if (IsExternC && LangOpts.CPlusPlus)
272 Includes += "extern \"C\" {\n";
273 if (LangOpts.ObjC1)
274 Includes += "#import \"";
275 else
276 Includes += "#include \"";
277
278 Includes += HeaderName;
279
280 Includes += "\"\n";
281 if (IsExternC && LangOpts.CPlusPlus)
282 Includes += "}\n";
283}
284
285/// \brief Collect the set of header includes needed to construct the given
286/// module and update the TopHeaders file set of the module.
287///
288/// \param Module The module we're collecting includes from.
289///
290/// \param Includes Will be augmented with the set of \#includes or \#imports
291/// needed to load all of the named headers.
Richard Smith040e1262017-06-02 01:55:39 +0000292static std::error_code collectModuleHeaderIncludes(
293 const LangOptions &LangOpts, FileManager &FileMgr, DiagnosticsEngine &Diag,
294 ModuleMap &ModMap, clang::Module *Module, SmallVectorImpl<char> &Includes) {
Richard Smithf74d9462017-04-28 01:49:42 +0000295 // Don't collect any headers for unavailable modules.
296 if (!Module->isAvailable())
297 return std::error_code();
298
Richard Smith040e1262017-06-02 01:55:39 +0000299 // Resolve all lazy header directives to header files.
300 ModMap.resolveHeaderDirectives(Module);
301
302 // If any headers are missing, we can't build this module. In most cases,
303 // diagnostics for this should have already been produced; we only get here
304 // if explicit stat information was provided.
305 // FIXME: If the name resolves to a file with different stat information,
306 // produce a better diagnostic.
307 if (!Module->MissingHeaders.empty()) {
308 auto &MissingHeader = Module->MissingHeaders.front();
309 Diag.Report(MissingHeader.FileNameLoc, diag::err_module_header_missing)
310 << MissingHeader.IsUmbrella << MissingHeader.FileName;
311 return std::error_code();
312 }
313
Richard Smithf74d9462017-04-28 01:49:42 +0000314 // Add includes for each of these headers.
315 for (auto HK : {Module::HK_Normal, Module::HK_Private}) {
316 for (Module::Header &H : Module->Headers[HK]) {
317 Module->addTopHeader(H.Entry);
318 // Use the path as specified in the module map file. We'll look for this
319 // file relative to the module build directory (the directory containing
320 // the module map file) so this will find the same file that we found
321 // while parsing the module map.
322 addHeaderInclude(H.NameAsWritten, Includes, LangOpts, Module->IsExternC);
323 }
324 }
325 // Note that Module->PrivateHeaders will not be a TopHeader.
326
327 if (Module::Header UmbrellaHeader = Module->getUmbrellaHeader()) {
328 Module->addTopHeader(UmbrellaHeader.Entry);
329 if (Module->Parent)
330 // Include the umbrella header for submodules.
331 addHeaderInclude(UmbrellaHeader.NameAsWritten, Includes, LangOpts,
332 Module->IsExternC);
333 } else if (Module::DirectoryName UmbrellaDir = Module->getUmbrellaDir()) {
334 // Add all of the headers we find in this subdirectory.
335 std::error_code EC;
336 SmallString<128> DirNative;
337 llvm::sys::path::native(UmbrellaDir.Entry->getName(), DirNative);
338
339 vfs::FileSystem &FS = *FileMgr.getVirtualFileSystem();
340 for (vfs::recursive_directory_iterator Dir(FS, DirNative, EC), End;
341 Dir != End && !EC; Dir.increment(EC)) {
342 // Check whether this entry has an extension typically associated with
343 // headers.
344 if (!llvm::StringSwitch<bool>(llvm::sys::path::extension(Dir->getName()))
345 .Cases(".h", ".H", ".hh", ".hpp", true)
346 .Default(false))
347 continue;
348
349 const FileEntry *Header = FileMgr.getFile(Dir->getName());
350 // FIXME: This shouldn't happen unless there is a file system race. Is
351 // that worth diagnosing?
352 if (!Header)
353 continue;
354
355 // If this header is marked 'unavailable' in this module, don't include
356 // it.
357 if (ModMap.isHeaderUnavailableInModule(Header, Module))
358 continue;
359
360 // Compute the relative path from the directory to this file.
361 SmallVector<StringRef, 16> Components;
362 auto PathIt = llvm::sys::path::rbegin(Dir->getName());
363 for (int I = 0; I != Dir.level() + 1; ++I, ++PathIt)
364 Components.push_back(*PathIt);
365 SmallString<128> RelativeHeader(UmbrellaDir.NameAsWritten);
366 for (auto It = Components.rbegin(), End = Components.rend(); It != End;
367 ++It)
368 llvm::sys::path::append(RelativeHeader, *It);
369
370 // Include this header as part of the umbrella directory.
371 Module->addTopHeader(Header);
372 addHeaderInclude(RelativeHeader, Includes, LangOpts, Module->IsExternC);
373 }
374
375 if (EC)
376 return EC;
377 }
378
379 // Recurse into submodules.
380 for (clang::Module::submodule_iterator Sub = Module->submodule_begin(),
381 SubEnd = Module->submodule_end();
382 Sub != SubEnd; ++Sub)
383 if (std::error_code Err = collectModuleHeaderIncludes(
Richard Smith040e1262017-06-02 01:55:39 +0000384 LangOpts, FileMgr, Diag, ModMap, *Sub, Includes))
Richard Smithf74d9462017-04-28 01:49:42 +0000385 return Err;
386
387 return std::error_code();
388}
389
Richard Smithab755972017-06-05 18:10:11 +0000390static bool loadModuleMapForModuleBuild(CompilerInstance &CI, bool IsSystem,
Richard Smith8b706102017-05-31 20:56:55 +0000391 bool IsPreprocessed,
392 std::string &PresumedModuleMapFile,
393 unsigned &Offset) {
Richard Smith8128f332017-05-05 22:18:51 +0000394 auto &SrcMgr = CI.getSourceManager();
395 HeaderSearch &HS = CI.getPreprocessor().getHeaderSearchInfo();
396
397 // Map the current input to a file.
398 FileID ModuleMapID = SrcMgr.getMainFileID();
399 const FileEntry *ModuleMap = SrcMgr.getFileEntryForID(ModuleMapID);
400
401 // If the module map is preprocessed, handle the initial line marker;
402 // line directives are not part of the module map syntax in general.
403 Offset = 0;
404 if (IsPreprocessed) {
Richard Smith8128f332017-05-05 22:18:51 +0000405 SourceLocation EndOfLineMarker =
Richard Smithf3f84612017-06-29 02:19:42 +0000406 ReadOriginalFileName(CI, PresumedModuleMapFile, /*IsModuleMap*/ true);
Richard Smith8128f332017-05-05 22:18:51 +0000407 if (EndOfLineMarker.isValid())
408 Offset = CI.getSourceManager().getDecomposedLoc(EndOfLineMarker).second;
Richard Smithf74d9462017-04-28 01:49:42 +0000409 }
410
Richard Smith8128f332017-05-05 22:18:51 +0000411 // Load the module map file.
Richard Smith8b706102017-05-31 20:56:55 +0000412 if (HS.loadModuleMapFile(ModuleMap, IsSystem, ModuleMapID, &Offset,
413 PresumedModuleMapFile))
Richard Smith8128f332017-05-05 22:18:51 +0000414 return true;
415
416 if (SrcMgr.getBuffer(ModuleMapID)->getBufferSize() == Offset)
417 Offset = 0;
418
419 return false;
420}
421
422static Module *prepareToBuildModule(CompilerInstance &CI,
423 StringRef ModuleMapFilename) {
Richard Smithf74d9462017-04-28 01:49:42 +0000424 if (CI.getLangOpts().CurrentModule.empty()) {
425 CI.getDiagnostics().Report(diag::err_missing_module_name);
Richard Smith8128f332017-05-05 22:18:51 +0000426
Richard Smithf74d9462017-04-28 01:49:42 +0000427 // FIXME: Eventually, we could consider asking whether there was just
428 // a single module described in the module map, and use that as a
429 // default. Then it would be fairly trivial to just "compile" a module
430 // map with a single module (the common case).
431 return nullptr;
432 }
433
Richard Smithf74d9462017-04-28 01:49:42 +0000434 // Dig out the module definition.
Richard Smith8128f332017-05-05 22:18:51 +0000435 HeaderSearch &HS = CI.getPreprocessor().getHeaderSearchInfo();
Richard Smithf74d9462017-04-28 01:49:42 +0000436 Module *M = HS.lookupModule(CI.getLangOpts().CurrentModule,
437 /*AllowSearch=*/false);
438 if (!M) {
439 CI.getDiagnostics().Report(diag::err_missing_module)
Richard Smith8128f332017-05-05 22:18:51 +0000440 << CI.getLangOpts().CurrentModule << ModuleMapFilename;
441
Richard Smithf74d9462017-04-28 01:49:42 +0000442 return nullptr;
443 }
444
445 // Check whether we can build this module at all.
Richard Smith27e5aa02017-06-05 18:57:56 +0000446 if (Preprocessor::checkModuleIsAvailable(CI.getLangOpts(), CI.getTarget(),
447 CI.getDiagnostics(), M))
Richard Smithf74d9462017-04-28 01:49:42 +0000448 return nullptr;
Richard Smithf74d9462017-04-28 01:49:42 +0000449
Richard Smith8128f332017-05-05 22:18:51 +0000450 // Inform the preprocessor that includes from within the input buffer should
451 // be resolved relative to the build directory of the module map file.
452 CI.getPreprocessor().setMainFileDir(M->Directory);
453
454 // If the module was inferred from a different module map (via an expanded
455 // umbrella module definition), track that fact.
456 // FIXME: It would be preferable to fill this in as part of processing
457 // the module map, rather than adding it after the fact.
458 StringRef OriginalModuleMapName = CI.getFrontendOpts().OriginalModuleMap;
459 if (!OriginalModuleMapName.empty()) {
460 auto *OriginalModuleMap =
461 CI.getFileManager().getFile(OriginalModuleMapName,
462 /*openFile*/ true);
463 if (!OriginalModuleMap) {
464 CI.getDiagnostics().Report(diag::err_module_map_not_found)
465 << OriginalModuleMapName;
466 return nullptr;
467 }
468 if (OriginalModuleMap != CI.getSourceManager().getFileEntryForID(
469 CI.getSourceManager().getMainFileID())) {
470 M->IsInferred = true;
471 CI.getPreprocessor().getHeaderSearchInfo().getModuleMap()
472 .setInferredModuleAllowedBy(M, OriginalModuleMap);
473 }
Richard Smithf74d9462017-04-28 01:49:42 +0000474 }
475
Richard Smith8128f332017-05-05 22:18:51 +0000476 // If we're being run from the command-line, the module build stack will not
477 // have been filled in yet, so complete it now in order to allow us to detect
478 // module cycles.
479 SourceManager &SourceMgr = CI.getSourceManager();
480 if (SourceMgr.getModuleBuildStack().empty())
481 SourceMgr.pushModuleBuildStack(CI.getLangOpts().CurrentModule,
482 FullSourceLoc(SourceLocation(), SourceMgr));
483 return M;
484}
485
486/// Compute the input buffer that should be used to build the specified module.
487static std::unique_ptr<llvm::MemoryBuffer>
488getInputBufferForModule(CompilerInstance &CI, Module *M) {
Richard Smithf74d9462017-04-28 01:49:42 +0000489 FileManager &FileMgr = CI.getFileManager();
490
491 // Collect the set of #includes we need to build the module.
492 SmallString<256> HeaderContents;
493 std::error_code Err = std::error_code();
494 if (Module::Header UmbrellaHeader = M->getUmbrellaHeader())
495 addHeaderInclude(UmbrellaHeader.NameAsWritten, HeaderContents,
496 CI.getLangOpts(), M->IsExternC);
497 Err = collectModuleHeaderIncludes(
Richard Smith040e1262017-06-02 01:55:39 +0000498 CI.getLangOpts(), FileMgr, CI.getDiagnostics(),
Richard Smithf74d9462017-04-28 01:49:42 +0000499 CI.getPreprocessor().getHeaderSearchInfo().getModuleMap(), M,
500 HeaderContents);
501
502 if (Err) {
503 CI.getDiagnostics().Report(diag::err_module_cannot_create_includes)
504 << M->getFullModuleName() << Err.message();
505 return nullptr;
506 }
507
Richard Smithf74d9462017-04-28 01:49:42 +0000508 return llvm::MemoryBuffer::getMemBufferCopy(
509 HeaderContents, Module::getModuleInputBufferName());
510}
511
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000512bool FrontendAction::BeginSourceFile(CompilerInstance &CI,
Richard Smithab755972017-06-05 18:10:11 +0000513 const FrontendInputFile &RealInput) {
514 FrontendInputFile Input(RealInput);
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000515 assert(!Instance && "Already processing a source file!");
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +0000516 assert(!Input.isEmpty() && "Unexpected empty filename!");
Douglas Gregor32fbe312012-01-20 16:28:04 +0000517 setCurrentInput(Input);
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000518 setCompilerInstance(&CI);
519
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +0000520 StringRef InputFile = Input.getFile();
Jordan Roseea762b02012-08-10 01:06:08 +0000521 bool HasBegunSourceFile = false;
Richard Smithab755972017-06-05 18:10:11 +0000522 bool ReplayASTFile = Input.getKind().getFormat() == InputKind::Precompiled &&
523 usesPreprocessorOnly();
Argyrios Kyrtzidis90b6a2a2011-06-18 00:53:41 +0000524 if (!BeginInvocation(CI))
525 goto failure;
526
Richard Smithab755972017-06-05 18:10:11 +0000527 // If we're replaying the build of an AST file, import it and set up
528 // the initial state from its build.
529 if (ReplayASTFile) {
530 IntrusiveRefCntPtr<DiagnosticsEngine> Diags(&CI.getDiagnostics());
531
532 // The AST unit populates its own diagnostics engine rather than ours.
533 IntrusiveRefCntPtr<DiagnosticsEngine> ASTDiags(
534 new DiagnosticsEngine(Diags->getDiagnosticIDs(),
535 &Diags->getDiagnosticOptions()));
536 ASTDiags->setClient(Diags->getClient(), /*OwnsClient*/false);
537
538 std::unique_ptr<ASTUnit> AST = ASTUnit::LoadFromASTFile(
Richard Smithdbafb6c2017-06-29 23:23:46 +0000539 InputFile, CI.getPCHContainerReader(), ASTUnit::LoadPreprocessorOnly,
540 ASTDiags, CI.getFileSystemOpts(), CI.getCodeGenOpts().DebugTypeExtRefs);
Richard Smithab755972017-06-05 18:10:11 +0000541 if (!AST)
542 goto failure;
543
544 // Options relating to how we treat the input (but not what we do with it)
545 // are inherited from the AST unit.
Richard Smith18934752017-06-06 00:32:01 +0000546 CI.getHeaderSearchOpts() = AST->getHeaderSearchOpts();
547 CI.getPreprocessorOpts() = AST->getPreprocessorOpts();
Richard Smithab755972017-06-05 18:10:11 +0000548 CI.getLangOpts() = AST->getLangOpts();
549
Richard Smithab755972017-06-05 18:10:11 +0000550 // Set the shared objects, these are reset when we finish processing the
551 // file, otherwise the CompilerInstance will happily destroy them.
552 CI.setFileManager(&AST->getFileManager());
553 CI.createSourceManager(CI.getFileManager());
554 CI.getSourceManager().initializeForReplay(AST->getSourceManager());
Richard Smithab755972017-06-05 18:10:11 +0000555
Richard Smithf3f84612017-06-29 02:19:42 +0000556 // Preload all the module files loaded transitively by the AST unit. Also
557 // load all module map files that were parsed as part of building the AST
558 // unit.
559 if (auto ASTReader = AST->getASTReader()) {
560 auto &MM = ASTReader->getModuleManager();
561 auto &PrimaryModule = MM.getPrimaryModule();
562
563 for (ModuleFile &MF : MM)
564 if (&MF != &PrimaryModule)
565 CI.getFrontendOpts().ModuleFiles.push_back(MF.FileName);
566
567 ASTReader->visitTopLevelModuleMaps(PrimaryModule,
568 [&](const FileEntry *FE) {
569 CI.getFrontendOpts().ModuleMapFiles.push_back(FE->getName());
570 });
571 }
572
Richard Smithab755972017-06-05 18:10:11 +0000573 // Set up the input file for replay purposes.
574 auto Kind = AST->getInputKind();
575 if (Kind.getFormat() == InputKind::ModuleMap) {
576 Module *ASTModule =
577 AST->getPreprocessor().getHeaderSearchInfo().lookupModule(
578 AST->getLangOpts().CurrentModule, /*AllowSearch*/ false);
Richard Smithdbafb6c2017-06-29 23:23:46 +0000579 assert(ASTModule && "module file does not define its own module");
Richard Smithab755972017-06-05 18:10:11 +0000580 Input = FrontendInputFile(ASTModule->PresumedModuleMapFile, Kind);
581 } else {
582 auto &SM = CI.getSourceManager();
583 FileID ID = SM.getMainFileID();
584 if (auto *File = SM.getFileEntryForID(ID))
585 Input = FrontendInputFile(File->getName(), Kind);
586 else
587 Input = FrontendInputFile(SM.getBuffer(ID), Kind);
588 }
589 setCurrentInput(Input, std::move(AST));
590 }
591
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000592 // AST files follow a very different path, since they share objects via the
593 // AST unit.
Richard Smith40c0efa2017-04-26 18:57:40 +0000594 if (Input.getKind().getFormat() == InputKind::Precompiled) {
Richard Smithab755972017-06-05 18:10:11 +0000595 assert(!usesPreprocessorOnly() && "this case was handled above");
Daniel Dunbarfa6214c2010-06-07 23:24:43 +0000596 assert(hasASTFileSupport() &&
597 "This action does not have AST file support!");
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000598
Dylan Noblesmithc95d8192012-02-20 14:00:23 +0000599 IntrusiveRefCntPtr<DiagnosticsEngine> Diags(&CI.getDiagnostics());
Alp Toker965f8822013-11-27 05:22:15 +0000600
Adrian Prantl6b21ab22015-08-27 19:46:20 +0000601 std::unique_ptr<ASTUnit> AST = ASTUnit::LoadFromASTFile(
Richard Smithdbafb6c2017-06-29 23:23:46 +0000602 InputFile, CI.getPCHContainerReader(), ASTUnit::LoadEverything, Diags,
603 CI.getFileSystemOpts(), CI.getCodeGenOpts().DebugTypeExtRefs);
David Blaikief62d4e72014-08-10 17:03:42 +0000604
Daniel Dunbar59203002009-12-03 01:45:44 +0000605 if (!AST)
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000606 goto failure;
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000607
Argyrios Kyrtzidisc00f43a2013-03-18 22:55:24 +0000608 // Inform the diagnostic client we are processing a source file.
Craig Topper49a27902014-05-22 04:46:25 +0000609 CI.getDiagnosticClient().BeginSourceFile(CI.getLangOpts(), nullptr);
Argyrios Kyrtzidisc00f43a2013-03-18 22:55:24 +0000610 HasBegunSourceFile = true;
611
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000612 // Set the shared objects, these are reset when we finish processing the
613 // file, otherwise the CompilerInstance will happily destroy them.
614 CI.setFileManager(&AST->getFileManager());
615 CI.setSourceManager(&AST->getSourceManager());
David Blaikie41565462017-01-05 19:48:07 +0000616 CI.setPreprocessor(AST->getPreprocessorPtr());
David Blaikieee123222017-02-08 20:51:11 +0000617 Preprocessor &PP = CI.getPreprocessor();
618 PP.getBuiltinInfo().initializeBuiltins(PP.getIdentifierTable(),
619 PP.getLangOpts());
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000620 CI.setASTContext(&AST->getASTContext());
621
David Blaikief62d4e72014-08-10 17:03:42 +0000622 setCurrentInput(Input, std::move(AST));
623
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000624 // Initialize the action.
Richard Smithd9259c22017-06-09 01:36:10 +0000625 if (!BeginSourceFileAction(CI))
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000626 goto failure;
627
James Dennettf8317672013-01-23 00:45:44 +0000628 // Create the AST consumer.
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +0000629 CI.setASTConsumer(CreateWrappedASTConsumer(CI, InputFile));
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000630 if (!CI.hasASTConsumer())
631 goto failure;
632
633 return true;
634 }
635
Ben Langmuir8832c062014-04-15 18:16:25 +0000636 if (!CI.hasVirtualFileSystem()) {
637 if (IntrusiveRefCntPtr<vfs::FileSystem> VFS =
638 createVFSFromCompilerInvocation(CI.getInvocation(),
639 CI.getDiagnostics()))
640 CI.setVirtualFileSystem(VFS);
641 else
642 goto failure;
Ben Langmuir801272a2014-02-25 18:23:47 +0000643 }
644
Daniel Dunbar9507f9c2010-06-07 23:26:47 +0000645 // Set up the file and source managers, if needed.
Daniel Dunbaraed46fc2010-06-07 23:23:50 +0000646 if (!CI.hasFileManager())
647 CI.createFileManager();
648 if (!CI.hasSourceManager())
Chris Lattner5159f612010-11-23 08:35:12 +0000649 CI.createSourceManager(CI.getFileManager());
Daniel Dunbar9507f9c2010-06-07 23:26:47 +0000650
Richard Smithf74d9462017-04-28 01:49:42 +0000651 // Set up embedding for any specified files. Do this before we load any
652 // source files, including the primary module map for the compilation.
653 for (const auto &F : CI.getFrontendOpts().ModulesEmbedFiles) {
654 if (const auto *FE = CI.getFileManager().getFile(F, /*openFile*/true))
655 CI.getSourceManager().setFileIsTransient(FE);
656 else
657 CI.getDiagnostics().Report(diag::err_modules_embed_file_not_found) << F;
658 }
659 if (CI.getFrontendOpts().ModulesEmbedAllFiles)
660 CI.getSourceManager().setAllFilesAreTransient(true);
661
Daniel Dunbar9507f9c2010-06-07 23:26:47 +0000662 // IR files bypass the rest of initialization.
Richard Smith40c0efa2017-04-26 18:57:40 +0000663 if (Input.getKind().getLanguage() == InputKind::LLVM_IR) {
Daniel Dunbar9507f9c2010-06-07 23:26:47 +0000664 assert(hasIRSupport() &&
665 "This action does not have IR file support!");
666
667 // Inform the diagnostic client we are processing a source file.
Craig Topper49a27902014-05-22 04:46:25 +0000668 CI.getDiagnosticClient().BeginSourceFile(CI.getLangOpts(), nullptr);
Jordan Roseea762b02012-08-10 01:06:08 +0000669 HasBegunSourceFile = true;
Daniel Dunbar9507f9c2010-06-07 23:26:47 +0000670
671 // Initialize the action.
Richard Smithd9259c22017-06-09 01:36:10 +0000672 if (!BeginSourceFileAction(CI))
Daniel Dunbar9507f9c2010-06-07 23:26:47 +0000673 goto failure;
674
Ben Langmuirbeee15e2014-04-14 18:00:01 +0000675 // Initialize the main file entry.
676 if (!CI.InitializeSourceManager(CurrentInput))
677 goto failure;
678
Daniel Dunbar9507f9c2010-06-07 23:26:47 +0000679 return true;
680 }
681
Douglas Gregorfc9e7a22012-10-23 06:18:24 +0000682 // If the implicit PCH include is actually a directory, rather than
683 // a single file, search for a suitable PCH file in that directory.
684 if (!CI.getPreprocessorOpts().ImplicitPCHInclude.empty()) {
685 FileManager &FileMgr = CI.getFileManager();
686 PreprocessorOptions &PPOpts = CI.getPreprocessorOpts();
687 StringRef PCHInclude = PPOpts.ImplicitPCHInclude;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000688 std::string SpecificModuleCachePath = CI.getSpecificModuleCachePath();
Douglas Gregorfc9e7a22012-10-23 06:18:24 +0000689 if (const DirectoryEntry *PCHDir = FileMgr.getDirectory(PCHInclude)) {
Rafael Espindolac0809172014-06-12 14:02:15 +0000690 std::error_code EC;
Douglas Gregorfc9e7a22012-10-23 06:18:24 +0000691 SmallString<128> DirNative;
692 llvm::sys::path::native(PCHDir->getName(), DirNative);
693 bool Found = false;
Bruno Cardoso Lopesb4d56f12016-12-12 19:28:21 +0000694 vfs::FileSystem &FS = *FileMgr.getVirtualFileSystem();
695 for (vfs::directory_iterator Dir = FS.dir_begin(DirNative, EC), DirEnd;
Douglas Gregorfc9e7a22012-10-23 06:18:24 +0000696 Dir != DirEnd && !EC; Dir.increment(EC)) {
697 // Check whether this is an acceptable AST file.
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000698 if (ASTReader::isAcceptableASTFile(
Bruno Cardoso Lopesb4d56f12016-12-12 19:28:21 +0000699 Dir->getName(), FileMgr, CI.getPCHContainerReader(),
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000700 CI.getLangOpts(), CI.getTargetOpts(), CI.getPreprocessorOpts(),
701 SpecificModuleCachePath)) {
Bruno Cardoso Lopesb4d56f12016-12-12 19:28:21 +0000702 PPOpts.ImplicitPCHInclude = Dir->getName();
Argyrios Kyrtzidis48b72d82013-02-05 16:36:52 +0000703 Found = true;
Douglas Gregorfc9e7a22012-10-23 06:18:24 +0000704 break;
705 }
706 }
707
708 if (!Found) {
709 CI.getDiagnostics().Report(diag::err_fe_no_pch_in_dir) << PCHInclude;
Richard Smith81c72482015-09-04 21:44:32 +0000710 goto failure;
Douglas Gregorfc9e7a22012-10-23 06:18:24 +0000711 }
712 }
713 }
714
Ted Kremenekeeccb302014-08-27 15:14:15 +0000715 // Set up the preprocessor if needed. When parsing model files the
716 // preprocessor of the original source is reused.
717 if (!isModelParsingAction())
718 CI.createPreprocessor(getTranslationUnitKind());
Daniel Dunbaraed46fc2010-06-07 23:23:50 +0000719
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000720 // Inform the diagnostic client we are processing a source file.
721 CI.getDiagnosticClient().BeginSourceFile(CI.getLangOpts(),
722 &CI.getPreprocessor());
Jordan Roseea762b02012-08-10 01:06:08 +0000723 HasBegunSourceFile = true;
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000724
Richard Smith8128f332017-05-05 22:18:51 +0000725 // Initialize the main file entry.
726 if (!CI.InitializeSourceManager(Input))
727 goto failure;
728
Richard Smithf74d9462017-04-28 01:49:42 +0000729 // For module map files, we first parse the module map and synthesize a
730 // "<module-includes>" buffer before more conventional processing.
731 if (Input.getKind().getFormat() == InputKind::ModuleMap) {
732 CI.getLangOpts().setCompilingModule(LangOptions::CMK_ModuleMap);
733
Richard Smith8b706102017-05-31 20:56:55 +0000734 std::string PresumedModuleMapFile;
Richard Smith8128f332017-05-05 22:18:51 +0000735 unsigned OffsetToContents;
Richard Smithab755972017-06-05 18:10:11 +0000736 if (loadModuleMapForModuleBuild(CI, Input.isSystem(),
Richard Smith8b706102017-05-31 20:56:55 +0000737 Input.isPreprocessed(),
738 PresumedModuleMapFile, OffsetToContents))
Richard Smithf74d9462017-04-28 01:49:42 +0000739 goto failure;
740
Richard Smith8128f332017-05-05 22:18:51 +0000741 auto *CurrentModule = prepareToBuildModule(CI, Input.getFile());
742 if (!CurrentModule)
743 goto failure;
Richard Smithf74d9462017-04-28 01:49:42 +0000744
Richard Smith8b706102017-05-31 20:56:55 +0000745 CurrentModule->PresumedModuleMapFile = PresumedModuleMapFile;
746
Richard Smith8128f332017-05-05 22:18:51 +0000747 if (OffsetToContents)
748 // If the module contents are in the same file, skip to them.
749 CI.getPreprocessor().setSkipMainFilePreamble(OffsetToContents, true);
750 else {
751 // Otherwise, convert the module description to a suitable input buffer.
752 auto Buffer = getInputBufferForModule(CI, CurrentModule);
753 if (!Buffer)
754 goto failure;
755
756 // Reinitialize the main file entry to refer to the new input.
757 if (!CI.InitializeSourceManager(FrontendInputFile(
758 Buffer.release(), Input.getKind().withFormat(InputKind::Source),
759 CurrentModule->IsSystem)))
760 goto failure;
761 }
Richard Smithf74d9462017-04-28 01:49:42 +0000762 }
763
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000764 // Initialize the action.
Richard Smithd9259c22017-06-09 01:36:10 +0000765 if (!BeginSourceFileAction(CI))
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000766 goto failure;
767
James Dennettf8317672013-01-23 00:45:44 +0000768 // Create the AST context and consumer unless this is a preprocessor only
769 // action.
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000770 if (!usesPreprocessorOnly()) {
Ted Kremenekeeccb302014-08-27 15:14:15 +0000771 // Parsing a model file should reuse the existing ASTContext.
772 if (!isModelParsingAction())
773 CI.createASTContext();
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000774
Taewook Oh06b1af52017-03-07 20:20:23 +0000775 // For preprocessed files, check if the first line specifies the original
776 // source file name with a linemarker.
Richard Smith8128f332017-05-05 22:18:51 +0000777 std::string PresumedInputFile = InputFile;
Taewook Oh06b1af52017-03-07 20:20:23 +0000778 if (Input.isPreprocessed())
Richard Smith8128f332017-05-05 22:18:51 +0000779 ReadOriginalFileName(CI, PresumedInputFile);
Taewook Oh06b1af52017-03-07 20:20:23 +0000780
David Blaikie6beb6aa2014-08-10 19:56:51 +0000781 std::unique_ptr<ASTConsumer> Consumer =
Richard Smith8128f332017-05-05 22:18:51 +0000782 CreateWrappedASTConsumer(CI, PresumedInputFile);
Fariborz Jahanian2129ccf2010-10-29 19:49:13 +0000783 if (!Consumer)
784 goto failure;
Sebastian Redl07a89a82010-07-30 00:29:29 +0000785
Ted Kremenekeeccb302014-08-27 15:14:15 +0000786 // FIXME: should not overwrite ASTMutationListener when parsing model files?
787 if (!isModelParsingAction())
788 CI.getASTContext().setASTMutationListener(Consumer->GetASTMutationListener());
Richard Smithe842a472014-10-22 02:05:46 +0000789
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +0000790 if (!CI.getPreprocessorOpts().ChainedIncludes.empty()) {
791 // Convert headers to PCH and chain them.
Alp Toker9e0523d2014-07-07 11:07:10 +0000792 IntrusiveRefCntPtr<ExternalSemaSource> source, FinalReader;
793 source = createChainedIncludesSource(CI, FinalReader);
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +0000794 if (!source)
795 goto failure;
Alp Toker9e0523d2014-07-07 11:07:10 +0000796 CI.setModuleManager(static_cast<ASTReader *>(FinalReader.get()));
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +0000797 CI.getASTContext().setExternalSource(source);
Vassil Vassileva2c2d942017-02-07 21:49:41 +0000798 } else if (CI.getLangOpts().Modules ||
799 !CI.getPreprocessorOpts().ImplicitPCHInclude.empty()) {
800 // Use PCM or PCH.
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000801 assert(hasPCHSupport() && "This action does not have PCH support!");
Douglas Gregor925296b2011-07-19 16:10:42 +0000802 ASTDeserializationListener *DeserialListener =
803 Consumer->GetASTDeserializationListener();
Nico Weber824285e2014-05-08 04:26:47 +0000804 bool DeleteDeserialListener = false;
805 if (CI.getPreprocessorOpts().DumpDeserializedPCHDecls) {
806 DeserialListener = new DeserializedDeclsDumper(DeserialListener,
807 DeleteDeserialListener);
808 DeleteDeserialListener = true;
809 }
810 if (!CI.getPreprocessorOpts().DeserializedPCHDeclsToErrorOn.empty()) {
811 DeserialListener = new DeserializedDeclsChecker(
812 CI.getASTContext(),
813 CI.getPreprocessorOpts().DeserializedPCHDeclsToErrorOn,
814 DeserialListener, DeleteDeserialListener);
815 DeleteDeserialListener = true;
816 }
Vassil Vassileva2c2d942017-02-07 21:49:41 +0000817 if (!CI.getPreprocessorOpts().ImplicitPCHInclude.empty()) {
818 CI.createPCHExternalASTSource(
819 CI.getPreprocessorOpts().ImplicitPCHInclude,
820 CI.getPreprocessorOpts().DisablePCHValidation,
Nico Weber824285e2014-05-08 04:26:47 +0000821 CI.getPreprocessorOpts().AllowPCHWithCompilerErrors, DeserialListener,
Vassil Vassileva2c2d942017-02-07 21:49:41 +0000822 DeleteDeserialListener);
823 if (!CI.getASTContext().getExternalSource())
824 goto failure;
825 }
826 // If modules are enabled, create the module manager before creating
827 // any builtins, so that all declarations know that they might be
828 // extended by an external source.
829 if (CI.getLangOpts().Modules || !CI.hasASTContext() ||
830 !CI.getASTContext().getExternalSource()) {
831 CI.createModuleManager();
832 CI.getModuleManager()->setDeserializationListener(DeserialListener,
833 DeleteDeserialListener);
834 }
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000835 }
Sebastian Redl4d3af3e2010-07-09 21:00:24 +0000836
David Blaikie6beb6aa2014-08-10 19:56:51 +0000837 CI.setASTConsumer(std::move(Consumer));
Sebastian Redl4d3af3e2010-07-09 21:00:24 +0000838 if (!CI.hasASTConsumer())
839 goto failure;
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000840 }
841
Jonathan D. Turner0248f572011-08-05 22:17:03 +0000842 // Initialize built-in info as long as we aren't using an external AST
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000843 // source.
Vassil Vassileva2c2d942017-02-07 21:49:41 +0000844 if (CI.getLangOpts().Modules || !CI.hasASTContext() ||
845 !CI.getASTContext().getExternalSource()) {
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000846 Preprocessor &PP = CI.getPreprocessor();
Eric Christopher02d5d862015-08-06 01:01:12 +0000847 PP.getBuiltinInfo().initializeBuiltins(PP.getIdentifierTable(),
David Blaikiebbafb8a2012-03-11 07:00:24 +0000848 PP.getLangOpts());
Richard Smith053f6c62014-05-16 23:01:30 +0000849 } else {
850 // FIXME: If this is a problem, recover from it by creating a multiplex
851 // source.
852 assert((!CI.getLangOpts().Modules || CI.getModuleManager()) &&
853 "modules enabled but created an external source that "
854 "doesn't support modules");
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000855 }
856
Richard Smithac425e92015-01-23 00:01:13 +0000857 // If we were asked to load any module map files, do so now.
858 for (const auto &Filename : CI.getFrontendOpts().ModuleMapFiles) {
859 if (auto *File = CI.getFileManager().getFile(Filename))
860 CI.getPreprocessor().getHeaderSearchInfo().loadModuleMapFile(
861 File, /*IsSystem*/false);
862 else
863 CI.getDiagnostics().Report(diag::err_module_map_not_found) << Filename;
864 }
865
Richard Smithd4b230b2014-10-27 23:01:16 +0000866 // If we were asked to load any module files, do so now.
867 for (const auto &ModuleFile : CI.getFrontendOpts().ModuleFiles)
868 if (!CI.loadModuleFile(ModuleFile))
Richard Smithe842a472014-10-22 02:05:46 +0000869 goto failure;
Richard Smithe842a472014-10-22 02:05:46 +0000870
Douglas Gregore9fc3772012-01-26 07:55:45 +0000871 // If there is a layout overrides file, attach an external AST source that
872 // provides the layouts from that file.
Taewook Oh06b1af52017-03-07 20:20:23 +0000873 if (!CI.getFrontendOpts().OverrideRecordLayoutsFile.empty() &&
Douglas Gregore9fc3772012-01-26 07:55:45 +0000874 CI.hasASTContext() && !CI.getASTContext().getExternalSource()) {
Taewook Oh06b1af52017-03-07 20:20:23 +0000875 IntrusiveRefCntPtr<ExternalASTSource>
Douglas Gregore9fc3772012-01-26 07:55:45 +0000876 Override(new LayoutOverrideSource(
877 CI.getFrontendOpts().OverrideRecordLayoutsFile));
878 CI.getASTContext().setExternalSource(Override);
879 }
Richard Smith053f6c62014-05-16 23:01:30 +0000880
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000881 return true;
882
883 // If we failed, reset state since the client will not end up calling the
884 // matching EndSourceFile().
Richard Smithab755972017-06-05 18:10:11 +0000885failure:
Jordan Roseea762b02012-08-10 01:06:08 +0000886 if (HasBegunSourceFile)
887 CI.getDiagnosticClient().EndSourceFile();
Benjamin Kramer3c717b42012-10-14 19:21:21 +0000888 CI.clearOutputFiles(/*EraseFiles=*/true);
Richard Smithf74d9462017-04-28 01:49:42 +0000889 CI.getLangOpts().setCompilingModule(LangOptions::CMK_None);
Douglas Gregor32fbe312012-01-20 16:28:04 +0000890 setCurrentInput(FrontendInputFile());
Craig Topper49a27902014-05-22 04:46:25 +0000891 setCompilerInstance(nullptr);
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000892 return false;
893}
894
Argyrios Kyrtzidis1416e172012-06-08 05:48:06 +0000895bool FrontendAction::Execute() {
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000896 CompilerInstance &CI = getCompilerInstance();
897
Kovarththanan Rajaratnam5505dff2009-11-29 09:57:35 +0000898 if (CI.hasFrontendTimer()) {
899 llvm::TimeRegion Timer(CI.getFrontendTimer());
900 ExecuteAction();
901 }
902 else ExecuteAction();
Argyrios Kyrtzidis1416e172012-06-08 05:48:06 +0000903
Douglas Gregor5e306b12013-01-23 22:38:11 +0000904 // If we are supposed to rebuild the global module index, do so now unless
Douglas Gregorc1bbec82013-01-25 00:45:27 +0000905 // there were any module-build failures.
906 if (CI.shouldBuildGlobalModuleIndex() && CI.hasFileManager() &&
907 CI.hasPreprocessor()) {
Richard Smith3938f0c2015-08-15 00:34:15 +0000908 StringRef Cache =
909 CI.getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
910 if (!Cache.empty())
911 GlobalModuleIndex::writeIndex(CI.getFileManager(),
912 CI.getPCHContainerReader(), Cache);
Douglas Gregor5e306b12013-01-23 22:38:11 +0000913 }
914
Argyrios Kyrtzidis1416e172012-06-08 05:48:06 +0000915 return true;
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000916}
917
918void FrontendAction::EndSourceFile() {
919 CompilerInstance &CI = getCompilerInstance();
920
Douglas Gregor1388a892011-02-09 18:47:31 +0000921 // Inform the diagnostic client we are done with this source file.
922 CI.getDiagnosticClient().EndSourceFile();
923
Benjamin Kramer88d99e42014-08-07 20:51:16 +0000924 // Inform the preprocessor we are done.
925 if (CI.hasPreprocessor())
926 CI.getPreprocessor().EndSourceFile();
927
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000928 // Finalize the action.
929 EndSourceFileAction();
930
Nico Weber7de358e2014-04-24 02:42:04 +0000931 // Sema references the ast consumer, so reset sema first.
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000932 //
933 // FIXME: There is more per-file stuff we could just drop here?
Nico Weber7de358e2014-04-24 02:42:04 +0000934 bool DisableFree = CI.getFrontendOpts().DisableFree;
935 if (DisableFree) {
Duncan P. N. Exon Smith4a8212a2015-05-04 14:59:20 +0000936 CI.resetAndLeakSema();
937 CI.resetAndLeakASTContext();
David Blaikie6beb6aa2014-08-10 19:56:51 +0000938 BuryPointer(CI.takeASTConsumer().get());
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000939 } else {
Duncan P. N. Exon Smith4a8212a2015-05-04 14:59:20 +0000940 CI.setSema(nullptr);
941 CI.setASTContext(nullptr);
Craig Topper49a27902014-05-22 04:46:25 +0000942 CI.setASTConsumer(nullptr);
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000943 }
944
945 if (CI.getFrontendOpts().ShowStats) {
946 llvm::errs() << "\nSTATISTICS FOR '" << getCurrentFile() << "':\n";
947 CI.getPreprocessor().PrintStats();
948 CI.getPreprocessor().getIdentifierTable().PrintStats();
949 CI.getPreprocessor().getHeaderSearchInfo().PrintStats();
950 CI.getSourceManager().PrintStats();
951 llvm::errs() << "\n";
952 }
953
Argyrios Kyrtzidisf0168de2013-06-11 00:36:55 +0000954 // Cleanup the output streams, and erase the output files if instructed by the
955 // FrontendAction.
956 CI.clearOutputFiles(/*EraseFiles=*/shouldEraseOutputFiles());
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000957
Nico Weber1f29ccf2014-04-24 03:31:27 +0000958 if (isCurrentFileAST()) {
Duncan P. N. Exon Smith4a8212a2015-05-04 14:59:20 +0000959 if (DisableFree) {
960 CI.resetAndLeakPreprocessor();
961 CI.resetAndLeakSourceManager();
962 CI.resetAndLeakFileManager();
Richard Smithab755972017-06-05 18:10:11 +0000963 BuryPointer(CurrentASTUnit.release());
Duncan P. N. Exon Smith4a8212a2015-05-04 14:59:20 +0000964 } else {
965 CI.setPreprocessor(nullptr);
966 CI.setSourceManager(nullptr);
967 CI.setFileManager(nullptr);
968 }
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000969 }
970
Craig Topper49a27902014-05-22 04:46:25 +0000971 setCompilerInstance(nullptr);
Douglas Gregor32fbe312012-01-20 16:28:04 +0000972 setCurrentInput(FrontendInputFile());
Richard Smithf74d9462017-04-28 01:49:42 +0000973 CI.getLangOpts().setCompilingModule(LangOptions::CMK_None);
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000974}
975
Argyrios Kyrtzidisf0168de2013-06-11 00:36:55 +0000976bool FrontendAction::shouldEraseOutputFiles() {
977 return getCompilerInstance().getDiagnostics().hasErrorOccurred();
978}
979
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000980//===----------------------------------------------------------------------===//
981// Utility Actions
982//===----------------------------------------------------------------------===//
983
984void ASTFrontendAction::ExecuteAction() {
985 CompilerInstance &CI = getCompilerInstance();
Rafael Espindola5150f2f2013-07-28 13:23:37 +0000986 if (!CI.hasPreprocessor())
987 return;
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000988
989 // FIXME: Move the truncation aspect of this into Sema, we delayed this till
990 // here so the source manager would be initialized.
991 if (hasCodeCompletionSupport() &&
992 !CI.getFrontendOpts().CodeCompletionAt.FileName.empty())
993 CI.createCodeCompletionConsumer();
994
995 // Use a code completion consumer?
Craig Topper49a27902014-05-22 04:46:25 +0000996 CodeCompleteConsumer *CompletionConsumer = nullptr;
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000997 if (CI.hasCodeCompletionConsumer())
998 CompletionConsumer = &CI.getCodeCompletionConsumer();
999
Douglas Gregor0e93f012010-08-12 23:31:19 +00001000 if (!CI.hasSema())
Douglas Gregor69f74f82011-08-25 22:30:56 +00001001 CI.createSema(getTranslationUnitKind(), CompletionConsumer);
Douglas Gregor0e93f012010-08-12 23:31:19 +00001002
Erik Verbruggen6e922512012-04-12 10:11:59 +00001003 ParseAST(CI.getSema(), CI.getFrontendOpts().ShowStats,
1004 CI.getFrontendOpts().SkipFunctionBodies);
Daniel Dunbara0ff58d2009-11-14 10:42:35 +00001005}
1006
David Blaikie68e081d2011-12-20 02:48:34 +00001007void PluginASTAction::anchor() { }
1008
David Blaikie6beb6aa2014-08-10 19:56:51 +00001009std::unique_ptr<ASTConsumer>
Daniel Dunbara0ff58d2009-11-14 10:42:35 +00001010PreprocessorFrontendAction::CreateASTConsumer(CompilerInstance &CI,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001011 StringRef InFile) {
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00001012 llvm_unreachable("Invalid CreateASTConsumer on preprocessor action!");
Daniel Dunbara0ff58d2009-11-14 10:42:35 +00001013}
Chandler Carruthb5703512011-06-16 16:17:05 +00001014
David Blaikie6beb6aa2014-08-10 19:56:51 +00001015std::unique_ptr<ASTConsumer>
1016WrapperFrontendAction::CreateASTConsumer(CompilerInstance &CI,
1017 StringRef InFile) {
Chandler Carruthb5703512011-06-16 16:17:05 +00001018 return WrappedAction->CreateASTConsumer(CI, InFile);
1019}
Argyrios Kyrtzidis90b6a2a2011-06-18 00:53:41 +00001020bool WrapperFrontendAction::BeginInvocation(CompilerInstance &CI) {
1021 return WrappedAction->BeginInvocation(CI);
1022}
Richard Smithd9259c22017-06-09 01:36:10 +00001023bool WrapperFrontendAction::BeginSourceFileAction(CompilerInstance &CI) {
Douglas Gregor32fbe312012-01-20 16:28:04 +00001024 WrappedAction->setCurrentInput(getCurrentInput());
Argyrios Kyrtzidis90b6a2a2011-06-18 00:53:41 +00001025 WrappedAction->setCompilerInstance(&CI);
Richard Smithd9259c22017-06-09 01:36:10 +00001026 auto Ret = WrappedAction->BeginSourceFileAction(CI);
Argyrios Kyrtzidise89a1792016-02-16 05:39:33 +00001027 // BeginSourceFileAction may change CurrentInput, e.g. during module builds.
1028 setCurrentInput(WrappedAction->getCurrentInput());
1029 return Ret;
Chandler Carruthb5703512011-06-16 16:17:05 +00001030}
1031void WrapperFrontendAction::ExecuteAction() {
1032 WrappedAction->ExecuteAction();
1033}
1034void WrapperFrontendAction::EndSourceFileAction() {
1035 WrappedAction->EndSourceFileAction();
1036}
1037
1038bool WrapperFrontendAction::usesPreprocessorOnly() const {
1039 return WrappedAction->usesPreprocessorOnly();
1040}
Douglas Gregor69f74f82011-08-25 22:30:56 +00001041TranslationUnitKind WrapperFrontendAction::getTranslationUnitKind() {
1042 return WrappedAction->getTranslationUnitKind();
Chandler Carruthb5703512011-06-16 16:17:05 +00001043}
1044bool WrapperFrontendAction::hasPCHSupport() const {
1045 return WrappedAction->hasPCHSupport();
1046}
1047bool WrapperFrontendAction::hasASTFileSupport() const {
1048 return WrappedAction->hasASTFileSupport();
1049}
1050bool WrapperFrontendAction::hasIRSupport() const {
1051 return WrappedAction->hasIRSupport();
1052}
1053bool WrapperFrontendAction::hasCodeCompletionSupport() const {
1054 return WrappedAction->hasCodeCompletionSupport();
1055}
1056
Argyrios Kyrtzidisd35e98f2016-02-07 19:28:36 +00001057WrapperFrontendAction::WrapperFrontendAction(
1058 std::unique_ptr<FrontendAction> WrappedAction)
1059 : WrappedAction(std::move(WrappedAction)) {}
Chandler Carruthb5703512011-06-16 16:17:05 +00001060