blob: d24700535e270e83cefef7546a8bdd76ba798f18 [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();
Vassil Vassilevda31c932018-05-20 09:38:52 +000091 if (const NamedDecl *ND = dyn_cast<NamedDecl>(D)) {
92 llvm::outs() << " - ";
93 ND->printQualifiedName(llvm::outs());
94 }
Argyrios Kyrtzidisa11aca42010-10-14 20:14:18 +000095 llvm::outs() << "\n";
96
Argyrios Kyrtzidisb12986f2011-10-28 22:54:31 +000097 DelegatingDeserializationListener::DeclRead(ID, D);
Argyrios Kyrtzidisa11aca42010-10-14 20:14:18 +000098 }
Argyrios Kyrtzidisa11aca42010-10-14 20:14:18 +000099};
100
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000101/// Checks deserialized declarations and emits error if a name
David Blaikie48b81282012-05-29 17:05:42 +0000102/// matches one given in command-line using -error-on-deserialized-decl.
103class DeserializedDeclsChecker : public DelegatingDeserializationListener {
104 ASTContext &Ctx;
105 std::set<std::string> NamesToCheck;
Argyrios Kyrtzidis0427be92010-10-14 20:14:25 +0000106
David Blaikie48b81282012-05-29 17:05:42 +0000107public:
108 DeserializedDeclsChecker(ASTContext &Ctx,
109 const std::set<std::string> &NamesToCheck,
Nico Weber824285e2014-05-08 04:26:47 +0000110 ASTDeserializationListener *Previous,
111 bool DeletePrevious)
112 : DelegatingDeserializationListener(Previous, DeletePrevious), Ctx(Ctx),
113 NamesToCheck(NamesToCheck) {}
Argyrios Kyrtzidis0427be92010-10-14 20:14:25 +0000114
Craig Topperafa7cb32014-03-13 06:07:04 +0000115 void DeclRead(serialization::DeclID ID, const Decl *D) override {
David Blaikie48b81282012-05-29 17:05:42 +0000116 if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
117 if (NamesToCheck.find(ND->getNameAsString()) != NamesToCheck.end()) {
118 unsigned DiagID
119 = Ctx.getDiagnostics().getCustomDiagID(DiagnosticsEngine::Error,
120 "%0 was deserialized");
121 Ctx.getDiagnostics().Report(Ctx.getFullLoc(D->getLocation()), DiagID)
122 << ND->getNameAsString();
123 }
Argyrios Kyrtzidis0427be92010-10-14 20:14:25 +0000124
David Blaikie48b81282012-05-29 17:05:42 +0000125 DelegatingDeserializationListener::DeclRead(ID, D);
126 }
Argyrios Kyrtzidis0427be92010-10-14 20:14:25 +0000127};
128
Argyrios Kyrtzidisa11aca42010-10-14 20:14:18 +0000129} // end anonymous namespace
130
Craig Topper49a27902014-05-22 04:46:25 +0000131FrontendAction::FrontendAction() : Instance(nullptr) {}
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000132
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +0000133FrontendAction::~FrontendAction() {}
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000134
Douglas Gregor32fbe312012-01-20 16:28:04 +0000135void FrontendAction::setCurrentInput(const FrontendInputFile &CurrentInput,
David Blaikief62d4e72014-08-10 17:03:42 +0000136 std::unique_ptr<ASTUnit> AST) {
Douglas Gregor32fbe312012-01-20 16:28:04 +0000137 this->CurrentInput = CurrentInput;
David Blaikief62d4e72014-08-10 17:03:42 +0000138 CurrentASTUnit = std::move(AST);
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000139}
140
Richard Smith8128f332017-05-05 22:18:51 +0000141Module *FrontendAction::getCurrentModule() const {
142 CompilerInstance &CI = getCompilerInstance();
143 return CI.getPreprocessor().getHeaderSearchInfo().lookupModule(
144 CI.getLangOpts().CurrentModule, /*AllowSearch*/false);
145}
146
David Blaikie6beb6aa2014-08-10 19:56:51 +0000147std::unique_ptr<ASTConsumer>
148FrontendAction::CreateWrappedASTConsumer(CompilerInstance &CI,
149 StringRef InFile) {
150 std::unique_ptr<ASTConsumer> Consumer = CreateASTConsumer(CI, InFile);
Nico Weber2992efa2011-01-25 20:34:14 +0000151 if (!Consumer)
Craig Topper49a27902014-05-22 04:46:25 +0000152 return nullptr;
Nico Weber2992efa2011-01-25 20:34:14 +0000153
John Brawn6c789742016-03-15 12:51:40 +0000154 // If there are no registered plugins we don't need to wrap the consumer
Ivan Donchevskiif70d28b2018-05-17 09:15:22 +0000155 if (FrontendPluginRegistry::begin() == FrontendPluginRegistry::end())
156 return Consumer;
157
Ivan Donchevskii270ef5b2018-05-17 09:21:07 +0000158 // If this is a code completion run, avoid invoking the plugin consumers
159 if (CI.hasCodeCompletionConsumer())
160 return Consumer;
161
Ivan Donchevskiif70d28b2018-05-17 09:15:22 +0000162 // Collect the list of plugins that go before the main action (in Consumers)
163 // or after it (in AfterConsumers)
164 std::vector<std::unique_ptr<ASTConsumer>> Consumers;
John Brawn6c789742016-03-15 12:51:40 +0000165 std::vector<std::unique_ptr<ASTConsumer>> AfterConsumers;
166 for (FrontendPluginRegistry::iterator it = FrontendPluginRegistry::begin(),
167 ie = FrontendPluginRegistry::end();
168 it != ie; ++it) {
169 std::unique_ptr<PluginASTAction> P = it->instantiate();
170 PluginASTAction::ActionType ActionType = P->getActionType();
171 if (ActionType == PluginASTAction::Cmdline) {
172 // This is O(|plugins| * |add_plugins|), but since both numbers are
173 // way below 50 in practice, that's ok.
174 for (size_t i = 0, e = CI.getFrontendOpts().AddPluginActions.size();
175 i != e; ++i) {
176 if (it->getName() == CI.getFrontendOpts().AddPluginActions[i]) {
177 ActionType = PluginASTAction::AddAfterMainAction;
178 break;
179 }
180 }
Nico Weber2992efa2011-01-25 20:34:14 +0000181 }
John Brawn6c789742016-03-15 12:51:40 +0000182 if ((ActionType == PluginASTAction::AddBeforeMainAction ||
183 ActionType == PluginASTAction::AddAfterMainAction) &&
184 P->ParseArgs(CI, CI.getFrontendOpts().PluginArgs[it->getName()])) {
185 std::unique_ptr<ASTConsumer> PluginConsumer = P->CreateASTConsumer(CI, InFile);
186 if (ActionType == PluginASTAction::AddBeforeMainAction) {
187 Consumers.push_back(std::move(PluginConsumer));
188 } else {
189 AfterConsumers.push_back(std::move(PluginConsumer));
190 }
191 }
192 }
193
194 // Add to Consumers the main consumer, then all the plugins that go after it
195 Consumers.push_back(std::move(Consumer));
196 for (auto &C : AfterConsumers) {
197 Consumers.push_back(std::move(C));
Nico Weber2992efa2011-01-25 20:34:14 +0000198 }
199
David Blaikie6beb6aa2014-08-10 19:56:51 +0000200 return llvm::make_unique<MultiplexConsumer>(std::move(Consumers));
Nico Weber2992efa2011-01-25 20:34:14 +0000201}
202
Richard Smith8128f332017-05-05 22:18:51 +0000203/// For preprocessed files, if the first line is the linemarker and specifies
204/// the original source file name, use that name as the input file name.
205/// Returns the location of the first token after the line marker directive.
206///
207/// \param CI The compiler instance.
208/// \param InputFile Populated with the filename from the line marker.
Richard Smithf3f84612017-06-29 02:19:42 +0000209/// \param IsModuleMap If \c true, add a line note corresponding to this line
210/// directive. (We need to do this because the directive will not be
211/// visited by the preprocessor.)
Richard Smith8128f332017-05-05 22:18:51 +0000212static SourceLocation ReadOriginalFileName(CompilerInstance &CI,
213 std::string &InputFile,
Richard Smithf3f84612017-06-29 02:19:42 +0000214 bool IsModuleMap = false) {
Taewook Oh06b1af52017-03-07 20:20:23 +0000215 auto &SourceMgr = CI.getSourceManager();
216 auto MainFileID = SourceMgr.getMainFileID();
Richard Smith8128f332017-05-05 22:18:51 +0000217
218 bool Invalid = false;
Taewook Oh06b1af52017-03-07 20:20:23 +0000219 const auto *MainFileBuf = SourceMgr.getBuffer(MainFileID, &Invalid);
220 if (Invalid)
Richard Smith8128f332017-05-05 22:18:51 +0000221 return SourceLocation();
Taewook Oh06b1af52017-03-07 20:20:23 +0000222
223 std::unique_ptr<Lexer> RawLexer(
224 new Lexer(MainFileID, MainFileBuf, SourceMgr, CI.getLangOpts()));
225
226 // If the first line has the syntax of
227 //
228 // # NUM "FILENAME"
229 //
230 // we use FILENAME as the input file name.
231 Token T;
232 if (RawLexer->LexFromRawLexer(T) || T.getKind() != tok::hash)
Richard Smith8128f332017-05-05 22:18:51 +0000233 return SourceLocation();
Taewook Oh06b1af52017-03-07 20:20:23 +0000234 if (RawLexer->LexFromRawLexer(T) || T.isAtStartOfLine() ||
235 T.getKind() != tok::numeric_constant)
Richard Smith8128f332017-05-05 22:18:51 +0000236 return SourceLocation();
237
238 unsigned LineNo;
239 SourceLocation LineNoLoc = T.getLocation();
Richard Smithf3f84612017-06-29 02:19:42 +0000240 if (IsModuleMap) {
Richard Smith8128f332017-05-05 22:18:51 +0000241 llvm::SmallString<16> Buffer;
242 if (Lexer::getSpelling(LineNoLoc, Buffer, SourceMgr, CI.getLangOpts())
243 .getAsInteger(10, LineNo))
244 return SourceLocation();
245 }
246
Taewook Oh06b1af52017-03-07 20:20:23 +0000247 RawLexer->LexFromRawLexer(T);
248 if (T.isAtStartOfLine() || T.getKind() != tok::string_literal)
Richard Smith8128f332017-05-05 22:18:51 +0000249 return SourceLocation();
Taewook Oh06b1af52017-03-07 20:20:23 +0000250
251 StringLiteralParser Literal(T, CI.getPreprocessor());
252 if (Literal.hadError)
Richard Smith8128f332017-05-05 22:18:51 +0000253 return SourceLocation();
254 RawLexer->LexFromRawLexer(T);
255 if (T.isNot(tok::eof) && !T.isAtStartOfLine())
256 return SourceLocation();
Taewook Oh06b1af52017-03-07 20:20:23 +0000257 InputFile = Literal.GetString().str();
Richard Smith8128f332017-05-05 22:18:51 +0000258
Richard Smithf3f84612017-06-29 02:19:42 +0000259 if (IsModuleMap)
Richard Smith8128f332017-05-05 22:18:51 +0000260 CI.getSourceManager().AddLineNote(
Reid Klecknereb00ee02017-05-22 21:42:58 +0000261 LineNoLoc, LineNo, SourceMgr.getLineTableFilenameID(InputFile), false,
Richard Smithf3f84612017-06-29 02:19:42 +0000262 false, SrcMgr::C_User_ModuleMap);
Richard Smith8128f332017-05-05 22:18:51 +0000263
264 return T.getLocation();
Taewook Oh06b1af52017-03-07 20:20:23 +0000265}
266
Richard Smithf74d9462017-04-28 01:49:42 +0000267static SmallVectorImpl<char> &
268operator+=(SmallVectorImpl<char> &Includes, StringRef RHS) {
269 Includes.append(RHS.begin(), RHS.end());
270 return Includes;
271}
272
273static void addHeaderInclude(StringRef HeaderName,
274 SmallVectorImpl<char> &Includes,
275 const LangOptions &LangOpts,
276 bool IsExternC) {
277 if (IsExternC && LangOpts.CPlusPlus)
278 Includes += "extern \"C\" {\n";
279 if (LangOpts.ObjC1)
280 Includes += "#import \"";
281 else
282 Includes += "#include \"";
283
284 Includes += HeaderName;
285
286 Includes += "\"\n";
287 if (IsExternC && LangOpts.CPlusPlus)
288 Includes += "}\n";
289}
290
Fangrui Song6907ce22018-07-30 19:24:48 +0000291/// Collect the set of header includes needed to construct the given
Richard Smithf74d9462017-04-28 01:49:42 +0000292/// module and update the TopHeaders file set of the module.
293///
294/// \param Module The module we're collecting includes from.
295///
296/// \param Includes Will be augmented with the set of \#includes or \#imports
297/// needed to load all of the named headers.
Richard Smith040e1262017-06-02 01:55:39 +0000298static std::error_code collectModuleHeaderIncludes(
299 const LangOptions &LangOpts, FileManager &FileMgr, DiagnosticsEngine &Diag,
300 ModuleMap &ModMap, clang::Module *Module, SmallVectorImpl<char> &Includes) {
Richard Smithf74d9462017-04-28 01:49:42 +0000301 // Don't collect any headers for unavailable modules.
302 if (!Module->isAvailable())
303 return std::error_code();
304
Richard Smith040e1262017-06-02 01:55:39 +0000305 // Resolve all lazy header directives to header files.
306 ModMap.resolveHeaderDirectives(Module);
307
308 // If any headers are missing, we can't build this module. In most cases,
309 // diagnostics for this should have already been produced; we only get here
310 // if explicit stat information was provided.
311 // FIXME: If the name resolves to a file with different stat information,
312 // produce a better diagnostic.
313 if (!Module->MissingHeaders.empty()) {
314 auto &MissingHeader = Module->MissingHeaders.front();
315 Diag.Report(MissingHeader.FileNameLoc, diag::err_module_header_missing)
316 << MissingHeader.IsUmbrella << MissingHeader.FileName;
317 return std::error_code();
318 }
319
Richard Smithf74d9462017-04-28 01:49:42 +0000320 // Add includes for each of these headers.
321 for (auto HK : {Module::HK_Normal, Module::HK_Private}) {
322 for (Module::Header &H : Module->Headers[HK]) {
323 Module->addTopHeader(H.Entry);
324 // Use the path as specified in the module map file. We'll look for this
325 // file relative to the module build directory (the directory containing
326 // the module map file) so this will find the same file that we found
327 // while parsing the module map.
328 addHeaderInclude(H.NameAsWritten, Includes, LangOpts, Module->IsExternC);
329 }
330 }
331 // Note that Module->PrivateHeaders will not be a TopHeader.
332
333 if (Module::Header UmbrellaHeader = Module->getUmbrellaHeader()) {
334 Module->addTopHeader(UmbrellaHeader.Entry);
335 if (Module->Parent)
336 // Include the umbrella header for submodules.
337 addHeaderInclude(UmbrellaHeader.NameAsWritten, Includes, LangOpts,
338 Module->IsExternC);
339 } else if (Module::DirectoryName UmbrellaDir = Module->getUmbrellaDir()) {
340 // Add all of the headers we find in this subdirectory.
341 std::error_code EC;
342 SmallString<128> DirNative;
343 llvm::sys::path::native(UmbrellaDir.Entry->getName(), DirNative);
344
345 vfs::FileSystem &FS = *FileMgr.getVirtualFileSystem();
346 for (vfs::recursive_directory_iterator Dir(FS, DirNative, EC), End;
347 Dir != End && !EC; Dir.increment(EC)) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000348 // Check whether this entry has an extension typically associated with
Richard Smithf74d9462017-04-28 01:49:42 +0000349 // headers.
Sam McCall0ae00562018-09-14 12:47:38 +0000350 if (!llvm::StringSwitch<bool>(llvm::sys::path::extension(Dir->path()))
351 .Cases(".h", ".H", ".hh", ".hpp", true)
352 .Default(false))
Richard Smithf74d9462017-04-28 01:49:42 +0000353 continue;
354
Sam McCall0ae00562018-09-14 12:47:38 +0000355 const FileEntry *Header = FileMgr.getFile(Dir->path());
Richard Smithf74d9462017-04-28 01:49:42 +0000356 // FIXME: This shouldn't happen unless there is a file system race. Is
357 // that worth diagnosing?
358 if (!Header)
359 continue;
360
Fangrui Song6907ce22018-07-30 19:24:48 +0000361 // If this header is marked 'unavailable' in this module, don't include
Richard Smithf74d9462017-04-28 01:49:42 +0000362 // it.
363 if (ModMap.isHeaderUnavailableInModule(Header, Module))
364 continue;
365
366 // Compute the relative path from the directory to this file.
367 SmallVector<StringRef, 16> Components;
Sam McCall0ae00562018-09-14 12:47:38 +0000368 auto PathIt = llvm::sys::path::rbegin(Dir->path());
Richard Smithf74d9462017-04-28 01:49:42 +0000369 for (int I = 0; I != Dir.level() + 1; ++I, ++PathIt)
370 Components.push_back(*PathIt);
371 SmallString<128> RelativeHeader(UmbrellaDir.NameAsWritten);
372 for (auto It = Components.rbegin(), End = Components.rend(); It != End;
373 ++It)
374 llvm::sys::path::append(RelativeHeader, *It);
375
376 // Include this header as part of the umbrella directory.
377 Module->addTopHeader(Header);
378 addHeaderInclude(RelativeHeader, Includes, LangOpts, Module->IsExternC);
379 }
380
381 if (EC)
382 return EC;
383 }
384
385 // Recurse into submodules.
386 for (clang::Module::submodule_iterator Sub = Module->submodule_begin(),
387 SubEnd = Module->submodule_end();
388 Sub != SubEnd; ++Sub)
389 if (std::error_code Err = collectModuleHeaderIncludes(
Richard Smith040e1262017-06-02 01:55:39 +0000390 LangOpts, FileMgr, Diag, ModMap, *Sub, Includes))
Richard Smithf74d9462017-04-28 01:49:42 +0000391 return Err;
392
393 return std::error_code();
394}
395
Richard Smithab755972017-06-05 18:10:11 +0000396static bool loadModuleMapForModuleBuild(CompilerInstance &CI, bool IsSystem,
Richard Smith8b706102017-05-31 20:56:55 +0000397 bool IsPreprocessed,
398 std::string &PresumedModuleMapFile,
399 unsigned &Offset) {
Richard Smith8128f332017-05-05 22:18:51 +0000400 auto &SrcMgr = CI.getSourceManager();
401 HeaderSearch &HS = CI.getPreprocessor().getHeaderSearchInfo();
402
403 // Map the current input to a file.
404 FileID ModuleMapID = SrcMgr.getMainFileID();
405 const FileEntry *ModuleMap = SrcMgr.getFileEntryForID(ModuleMapID);
406
407 // If the module map is preprocessed, handle the initial line marker;
408 // line directives are not part of the module map syntax in general.
409 Offset = 0;
410 if (IsPreprocessed) {
Richard Smith8128f332017-05-05 22:18:51 +0000411 SourceLocation EndOfLineMarker =
Richard Smithf3f84612017-06-29 02:19:42 +0000412 ReadOriginalFileName(CI, PresumedModuleMapFile, /*IsModuleMap*/ true);
Richard Smith8128f332017-05-05 22:18:51 +0000413 if (EndOfLineMarker.isValid())
414 Offset = CI.getSourceManager().getDecomposedLoc(EndOfLineMarker).second;
Richard Smithf74d9462017-04-28 01:49:42 +0000415 }
416
Richard Smith8128f332017-05-05 22:18:51 +0000417 // Load the module map file.
Richard Smith8b706102017-05-31 20:56:55 +0000418 if (HS.loadModuleMapFile(ModuleMap, IsSystem, ModuleMapID, &Offset,
419 PresumedModuleMapFile))
Richard Smith8128f332017-05-05 22:18:51 +0000420 return true;
421
422 if (SrcMgr.getBuffer(ModuleMapID)->getBufferSize() == Offset)
423 Offset = 0;
424
425 return false;
426}
427
428static Module *prepareToBuildModule(CompilerInstance &CI,
429 StringRef ModuleMapFilename) {
Richard Smithf74d9462017-04-28 01:49:42 +0000430 if (CI.getLangOpts().CurrentModule.empty()) {
431 CI.getDiagnostics().Report(diag::err_missing_module_name);
Richard Smith8128f332017-05-05 22:18:51 +0000432
Richard Smithf74d9462017-04-28 01:49:42 +0000433 // FIXME: Eventually, we could consider asking whether there was just
Fangrui Song6907ce22018-07-30 19:24:48 +0000434 // a single module described in the module map, and use that as a
Richard Smithf74d9462017-04-28 01:49:42 +0000435 // default. Then it would be fairly trivial to just "compile" a module
436 // map with a single module (the common case).
437 return nullptr;
438 }
439
Richard Smithf74d9462017-04-28 01:49:42 +0000440 // Dig out the module definition.
Richard Smith8128f332017-05-05 22:18:51 +0000441 HeaderSearch &HS = CI.getPreprocessor().getHeaderSearchInfo();
Richard Smithf74d9462017-04-28 01:49:42 +0000442 Module *M = HS.lookupModule(CI.getLangOpts().CurrentModule,
443 /*AllowSearch=*/false);
444 if (!M) {
445 CI.getDiagnostics().Report(diag::err_missing_module)
Richard Smith8128f332017-05-05 22:18:51 +0000446 << CI.getLangOpts().CurrentModule << ModuleMapFilename;
447
Richard Smithf74d9462017-04-28 01:49:42 +0000448 return nullptr;
449 }
450
451 // Check whether we can build this module at all.
Richard Smith27e5aa02017-06-05 18:57:56 +0000452 if (Preprocessor::checkModuleIsAvailable(CI.getLangOpts(), CI.getTarget(),
453 CI.getDiagnostics(), M))
Richard Smithf74d9462017-04-28 01:49:42 +0000454 return nullptr;
Richard Smithf74d9462017-04-28 01:49:42 +0000455
Richard Smith8128f332017-05-05 22:18:51 +0000456 // Inform the preprocessor that includes from within the input buffer should
457 // be resolved relative to the build directory of the module map file.
458 CI.getPreprocessor().setMainFileDir(M->Directory);
459
460 // If the module was inferred from a different module map (via an expanded
461 // umbrella module definition), track that fact.
462 // FIXME: It would be preferable to fill this in as part of processing
463 // the module map, rather than adding it after the fact.
464 StringRef OriginalModuleMapName = CI.getFrontendOpts().OriginalModuleMap;
465 if (!OriginalModuleMapName.empty()) {
466 auto *OriginalModuleMap =
467 CI.getFileManager().getFile(OriginalModuleMapName,
468 /*openFile*/ true);
469 if (!OriginalModuleMap) {
470 CI.getDiagnostics().Report(diag::err_module_map_not_found)
471 << OriginalModuleMapName;
472 return nullptr;
473 }
474 if (OriginalModuleMap != CI.getSourceManager().getFileEntryForID(
475 CI.getSourceManager().getMainFileID())) {
476 M->IsInferred = true;
477 CI.getPreprocessor().getHeaderSearchInfo().getModuleMap()
478 .setInferredModuleAllowedBy(M, OriginalModuleMap);
479 }
Richard Smithf74d9462017-04-28 01:49:42 +0000480 }
481
Richard Smith8128f332017-05-05 22:18:51 +0000482 // If we're being run from the command-line, the module build stack will not
483 // have been filled in yet, so complete it now in order to allow us to detect
484 // module cycles.
485 SourceManager &SourceMgr = CI.getSourceManager();
486 if (SourceMgr.getModuleBuildStack().empty())
487 SourceMgr.pushModuleBuildStack(CI.getLangOpts().CurrentModule,
488 FullSourceLoc(SourceLocation(), SourceMgr));
489 return M;
490}
491
492/// Compute the input buffer that should be used to build the specified module.
493static std::unique_ptr<llvm::MemoryBuffer>
494getInputBufferForModule(CompilerInstance &CI, Module *M) {
Richard Smithf74d9462017-04-28 01:49:42 +0000495 FileManager &FileMgr = CI.getFileManager();
496
497 // Collect the set of #includes we need to build the module.
498 SmallString<256> HeaderContents;
499 std::error_code Err = std::error_code();
500 if (Module::Header UmbrellaHeader = M->getUmbrellaHeader())
501 addHeaderInclude(UmbrellaHeader.NameAsWritten, HeaderContents,
502 CI.getLangOpts(), M->IsExternC);
503 Err = collectModuleHeaderIncludes(
Richard Smith040e1262017-06-02 01:55:39 +0000504 CI.getLangOpts(), FileMgr, CI.getDiagnostics(),
Richard Smithf74d9462017-04-28 01:49:42 +0000505 CI.getPreprocessor().getHeaderSearchInfo().getModuleMap(), M,
506 HeaderContents);
507
508 if (Err) {
509 CI.getDiagnostics().Report(diag::err_module_cannot_create_includes)
510 << M->getFullModuleName() << Err.message();
511 return nullptr;
512 }
513
Richard Smithf74d9462017-04-28 01:49:42 +0000514 return llvm::MemoryBuffer::getMemBufferCopy(
515 HeaderContents, Module::getModuleInputBufferName());
516}
517
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000518bool FrontendAction::BeginSourceFile(CompilerInstance &CI,
Richard Smithab755972017-06-05 18:10:11 +0000519 const FrontendInputFile &RealInput) {
520 FrontendInputFile Input(RealInput);
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000521 assert(!Instance && "Already processing a source file!");
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +0000522 assert(!Input.isEmpty() && "Unexpected empty filename!");
Douglas Gregor32fbe312012-01-20 16:28:04 +0000523 setCurrentInput(Input);
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000524 setCompilerInstance(&CI);
525
Jordan Roseea762b02012-08-10 01:06:08 +0000526 bool HasBegunSourceFile = false;
Richard Smithab755972017-06-05 18:10:11 +0000527 bool ReplayASTFile = Input.getKind().getFormat() == InputKind::Precompiled &&
528 usesPreprocessorOnly();
Argyrios Kyrtzidis90b6a2a2011-06-18 00:53:41 +0000529 if (!BeginInvocation(CI))
530 goto failure;
531
Richard Smithab755972017-06-05 18:10:11 +0000532 // If we're replaying the build of an AST file, import it and set up
533 // the initial state from its build.
534 if (ReplayASTFile) {
535 IntrusiveRefCntPtr<DiagnosticsEngine> Diags(&CI.getDiagnostics());
536
537 // The AST unit populates its own diagnostics engine rather than ours.
538 IntrusiveRefCntPtr<DiagnosticsEngine> ASTDiags(
539 new DiagnosticsEngine(Diags->getDiagnosticIDs(),
540 &Diags->getDiagnosticOptions()));
541 ASTDiags->setClient(Diags->getClient(), /*OwnsClient*/false);
542
Richard Smithd6509cf2018-09-15 01:21:15 +0000543 // FIXME: What if the input is a memory buffer?
544 StringRef InputFile = Input.getFile();
545
Richard Smithab755972017-06-05 18:10:11 +0000546 std::unique_ptr<ASTUnit> AST = ASTUnit::LoadFromASTFile(
Richard Smithdbafb6c2017-06-29 23:23:46 +0000547 InputFile, CI.getPCHContainerReader(), ASTUnit::LoadPreprocessorOnly,
548 ASTDiags, CI.getFileSystemOpts(), CI.getCodeGenOpts().DebugTypeExtRefs);
Richard Smithab755972017-06-05 18:10:11 +0000549 if (!AST)
550 goto failure;
551
552 // Options relating to how we treat the input (but not what we do with it)
553 // are inherited from the AST unit.
Richard Smith18934752017-06-06 00:32:01 +0000554 CI.getHeaderSearchOpts() = AST->getHeaderSearchOpts();
555 CI.getPreprocessorOpts() = AST->getPreprocessorOpts();
Richard Smithab755972017-06-05 18:10:11 +0000556 CI.getLangOpts() = AST->getLangOpts();
557
Richard Smithab755972017-06-05 18:10:11 +0000558 // Set the shared objects, these are reset when we finish processing the
559 // file, otherwise the CompilerInstance will happily destroy them.
560 CI.setFileManager(&AST->getFileManager());
561 CI.createSourceManager(CI.getFileManager());
562 CI.getSourceManager().initializeForReplay(AST->getSourceManager());
Richard Smithab755972017-06-05 18:10:11 +0000563
Richard Smithf3f84612017-06-29 02:19:42 +0000564 // Preload all the module files loaded transitively by the AST unit. Also
565 // load all module map files that were parsed as part of building the AST
566 // unit.
567 if (auto ASTReader = AST->getASTReader()) {
568 auto &MM = ASTReader->getModuleManager();
569 auto &PrimaryModule = MM.getPrimaryModule();
570
571 for (ModuleFile &MF : MM)
572 if (&MF != &PrimaryModule)
573 CI.getFrontendOpts().ModuleFiles.push_back(MF.FileName);
574
575 ASTReader->visitTopLevelModuleMaps(PrimaryModule,
576 [&](const FileEntry *FE) {
577 CI.getFrontendOpts().ModuleMapFiles.push_back(FE->getName());
578 });
579 }
580
Richard Smithab755972017-06-05 18:10:11 +0000581 // Set up the input file for replay purposes.
582 auto Kind = AST->getInputKind();
583 if (Kind.getFormat() == InputKind::ModuleMap) {
584 Module *ASTModule =
585 AST->getPreprocessor().getHeaderSearchInfo().lookupModule(
586 AST->getLangOpts().CurrentModule, /*AllowSearch*/ false);
Richard Smithdbafb6c2017-06-29 23:23:46 +0000587 assert(ASTModule && "module file does not define its own module");
Richard Smithab755972017-06-05 18:10:11 +0000588 Input = FrontendInputFile(ASTModule->PresumedModuleMapFile, Kind);
589 } else {
Richard Smith8b464f22018-09-15 01:21:18 +0000590 auto &OldSM = AST->getSourceManager();
591 FileID ID = OldSM.getMainFileID();
592 if (auto *File = OldSM.getFileEntryForID(ID))
Richard Smithab755972017-06-05 18:10:11 +0000593 Input = FrontendInputFile(File->getName(), Kind);
594 else
Richard Smith8b464f22018-09-15 01:21:18 +0000595 Input = FrontendInputFile(OldSM.getBuffer(ID), Kind);
Richard Smithab755972017-06-05 18:10:11 +0000596 }
597 setCurrentInput(Input, std::move(AST));
598 }
599
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000600 // AST files follow a very different path, since they share objects via the
601 // AST unit.
Richard Smith40c0efa2017-04-26 18:57:40 +0000602 if (Input.getKind().getFormat() == InputKind::Precompiled) {
Richard Smithab755972017-06-05 18:10:11 +0000603 assert(!usesPreprocessorOnly() && "this case was handled above");
Daniel Dunbarfa6214c2010-06-07 23:24:43 +0000604 assert(hasASTFileSupport() &&
605 "This action does not have AST file support!");
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000606
Dylan Noblesmithc95d8192012-02-20 14:00:23 +0000607 IntrusiveRefCntPtr<DiagnosticsEngine> Diags(&CI.getDiagnostics());
Alp Toker965f8822013-11-27 05:22:15 +0000608
Richard Smithd6509cf2018-09-15 01:21:15 +0000609 // FIXME: What if the input is a memory buffer?
610 StringRef InputFile = Input.getFile();
611
Adrian Prantl6b21ab22015-08-27 19:46:20 +0000612 std::unique_ptr<ASTUnit> AST = ASTUnit::LoadFromASTFile(
Richard Smithdbafb6c2017-06-29 23:23:46 +0000613 InputFile, CI.getPCHContainerReader(), ASTUnit::LoadEverything, Diags,
614 CI.getFileSystemOpts(), CI.getCodeGenOpts().DebugTypeExtRefs);
David Blaikief62d4e72014-08-10 17:03:42 +0000615
Daniel Dunbar59203002009-12-03 01:45:44 +0000616 if (!AST)
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000617 goto failure;
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000618
Argyrios Kyrtzidisc00f43a2013-03-18 22:55:24 +0000619 // Inform the diagnostic client we are processing a source file.
Craig Topper49a27902014-05-22 04:46:25 +0000620 CI.getDiagnosticClient().BeginSourceFile(CI.getLangOpts(), nullptr);
Argyrios Kyrtzidisc00f43a2013-03-18 22:55:24 +0000621 HasBegunSourceFile = true;
622
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000623 // Set the shared objects, these are reset when we finish processing the
624 // file, otherwise the CompilerInstance will happily destroy them.
625 CI.setFileManager(&AST->getFileManager());
626 CI.setSourceManager(&AST->getSourceManager());
David Blaikie41565462017-01-05 19:48:07 +0000627 CI.setPreprocessor(AST->getPreprocessorPtr());
David Blaikieee123222017-02-08 20:51:11 +0000628 Preprocessor &PP = CI.getPreprocessor();
629 PP.getBuiltinInfo().initializeBuiltins(PP.getIdentifierTable(),
630 PP.getLangOpts());
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000631 CI.setASTContext(&AST->getASTContext());
632
David Blaikief62d4e72014-08-10 17:03:42 +0000633 setCurrentInput(Input, std::move(AST));
634
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000635 // Initialize the action.
Richard Smithd9259c22017-06-09 01:36:10 +0000636 if (!BeginSourceFileAction(CI))
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000637 goto failure;
638
James Dennettf8317672013-01-23 00:45:44 +0000639 // Create the AST consumer.
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +0000640 CI.setASTConsumer(CreateWrappedASTConsumer(CI, InputFile));
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000641 if (!CI.hasASTConsumer())
642 goto failure;
643
644 return true;
645 }
646
Daniel Dunbar9507f9c2010-06-07 23:26:47 +0000647 // Set up the file and source managers, if needed.
Raphael Isemannabc3d042017-09-12 16:54:53 +0000648 if (!CI.hasFileManager()) {
649 if (!CI.createFileManager()) {
650 goto failure;
651 }
652 }
Daniel Dunbaraed46fc2010-06-07 23:23:50 +0000653 if (!CI.hasSourceManager())
Chris Lattner5159f612010-11-23 08:35:12 +0000654 CI.createSourceManager(CI.getFileManager());
Daniel Dunbar9507f9c2010-06-07 23:26:47 +0000655
Richard Smithf74d9462017-04-28 01:49:42 +0000656 // Set up embedding for any specified files. Do this before we load any
657 // source files, including the primary module map for the compilation.
658 for (const auto &F : CI.getFrontendOpts().ModulesEmbedFiles) {
659 if (const auto *FE = CI.getFileManager().getFile(F, /*openFile*/true))
660 CI.getSourceManager().setFileIsTransient(FE);
661 else
662 CI.getDiagnostics().Report(diag::err_modules_embed_file_not_found) << F;
663 }
664 if (CI.getFrontendOpts().ModulesEmbedAllFiles)
665 CI.getSourceManager().setAllFilesAreTransient(true);
666
Daniel Dunbar9507f9c2010-06-07 23:26:47 +0000667 // IR files bypass the rest of initialization.
Richard Smith40c0efa2017-04-26 18:57:40 +0000668 if (Input.getKind().getLanguage() == InputKind::LLVM_IR) {
Daniel Dunbar9507f9c2010-06-07 23:26:47 +0000669 assert(hasIRSupport() &&
670 "This action does not have IR file support!");
671
672 // Inform the diagnostic client we are processing a source file.
Craig Topper49a27902014-05-22 04:46:25 +0000673 CI.getDiagnosticClient().BeginSourceFile(CI.getLangOpts(), nullptr);
Jordan Roseea762b02012-08-10 01:06:08 +0000674 HasBegunSourceFile = true;
Daniel Dunbar9507f9c2010-06-07 23:26:47 +0000675
676 // Initialize the action.
Richard Smithd9259c22017-06-09 01:36:10 +0000677 if (!BeginSourceFileAction(CI))
Daniel Dunbar9507f9c2010-06-07 23:26:47 +0000678 goto failure;
679
Ben Langmuirbeee15e2014-04-14 18:00:01 +0000680 // Initialize the main file entry.
681 if (!CI.InitializeSourceManager(CurrentInput))
682 goto failure;
683
Daniel Dunbar9507f9c2010-06-07 23:26:47 +0000684 return true;
685 }
686
Douglas Gregorfc9e7a22012-10-23 06:18:24 +0000687 // If the implicit PCH include is actually a directory, rather than
688 // a single file, search for a suitable PCH file in that directory.
689 if (!CI.getPreprocessorOpts().ImplicitPCHInclude.empty()) {
690 FileManager &FileMgr = CI.getFileManager();
691 PreprocessorOptions &PPOpts = CI.getPreprocessorOpts();
692 StringRef PCHInclude = PPOpts.ImplicitPCHInclude;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000693 std::string SpecificModuleCachePath = CI.getSpecificModuleCachePath();
Douglas Gregorfc9e7a22012-10-23 06:18:24 +0000694 if (const DirectoryEntry *PCHDir = FileMgr.getDirectory(PCHInclude)) {
Rafael Espindolac0809172014-06-12 14:02:15 +0000695 std::error_code EC;
Douglas Gregorfc9e7a22012-10-23 06:18:24 +0000696 SmallString<128> DirNative;
697 llvm::sys::path::native(PCHDir->getName(), DirNative);
698 bool Found = false;
Bruno Cardoso Lopesb4d56f12016-12-12 19:28:21 +0000699 vfs::FileSystem &FS = *FileMgr.getVirtualFileSystem();
700 for (vfs::directory_iterator Dir = FS.dir_begin(DirNative, EC), DirEnd;
Douglas Gregorfc9e7a22012-10-23 06:18:24 +0000701 Dir != DirEnd && !EC; Dir.increment(EC)) {
702 // Check whether this is an acceptable AST file.
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000703 if (ASTReader::isAcceptableASTFile(
Sam McCall0ae00562018-09-14 12:47:38 +0000704 Dir->path(), FileMgr, CI.getPCHContainerReader(),
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000705 CI.getLangOpts(), CI.getTargetOpts(), CI.getPreprocessorOpts(),
706 SpecificModuleCachePath)) {
Sam McCall0ae00562018-09-14 12:47:38 +0000707 PPOpts.ImplicitPCHInclude = Dir->path();
Argyrios Kyrtzidis48b72d82013-02-05 16:36:52 +0000708 Found = true;
Douglas Gregorfc9e7a22012-10-23 06:18:24 +0000709 break;
710 }
711 }
712
713 if (!Found) {
714 CI.getDiagnostics().Report(diag::err_fe_no_pch_in_dir) << PCHInclude;
Richard Smith81c72482015-09-04 21:44:32 +0000715 goto failure;
Douglas Gregorfc9e7a22012-10-23 06:18:24 +0000716 }
717 }
718 }
719
Ted Kremenekeeccb302014-08-27 15:14:15 +0000720 // Set up the preprocessor if needed. When parsing model files the
721 // preprocessor of the original source is reused.
722 if (!isModelParsingAction())
723 CI.createPreprocessor(getTranslationUnitKind());
Daniel Dunbaraed46fc2010-06-07 23:23:50 +0000724
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000725 // Inform the diagnostic client we are processing a source file.
726 CI.getDiagnosticClient().BeginSourceFile(CI.getLangOpts(),
727 &CI.getPreprocessor());
Jordan Roseea762b02012-08-10 01:06:08 +0000728 HasBegunSourceFile = true;
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000729
Richard Smith8128f332017-05-05 22:18:51 +0000730 // Initialize the main file entry.
731 if (!CI.InitializeSourceManager(Input))
732 goto failure;
733
Richard Smithf74d9462017-04-28 01:49:42 +0000734 // For module map files, we first parse the module map and synthesize a
735 // "<module-includes>" buffer before more conventional processing.
736 if (Input.getKind().getFormat() == InputKind::ModuleMap) {
737 CI.getLangOpts().setCompilingModule(LangOptions::CMK_ModuleMap);
738
Richard Smith8b706102017-05-31 20:56:55 +0000739 std::string PresumedModuleMapFile;
Richard Smith8128f332017-05-05 22:18:51 +0000740 unsigned OffsetToContents;
Richard Smithab755972017-06-05 18:10:11 +0000741 if (loadModuleMapForModuleBuild(CI, Input.isSystem(),
Richard Smith8b706102017-05-31 20:56:55 +0000742 Input.isPreprocessed(),
743 PresumedModuleMapFile, OffsetToContents))
Richard Smithf74d9462017-04-28 01:49:42 +0000744 goto failure;
745
Richard Smith8128f332017-05-05 22:18:51 +0000746 auto *CurrentModule = prepareToBuildModule(CI, Input.getFile());
747 if (!CurrentModule)
748 goto failure;
Richard Smithf74d9462017-04-28 01:49:42 +0000749
Richard Smith8b706102017-05-31 20:56:55 +0000750 CurrentModule->PresumedModuleMapFile = PresumedModuleMapFile;
751
Richard Smith8128f332017-05-05 22:18:51 +0000752 if (OffsetToContents)
753 // If the module contents are in the same file, skip to them.
754 CI.getPreprocessor().setSkipMainFilePreamble(OffsetToContents, true);
755 else {
756 // Otherwise, convert the module description to a suitable input buffer.
757 auto Buffer = getInputBufferForModule(CI, CurrentModule);
758 if (!Buffer)
759 goto failure;
760
761 // Reinitialize the main file entry to refer to the new input.
Richard Smith6d9bc272017-09-09 01:14:04 +0000762 auto Kind = CurrentModule->IsSystem ? SrcMgr::C_System : SrcMgr::C_User;
763 auto &SourceMgr = CI.getSourceManager();
764 auto BufferID = SourceMgr.createFileID(std::move(Buffer), Kind);
765 assert(BufferID.isValid() && "couldn't creaate module buffer ID");
766 SourceMgr.setMainFileID(BufferID);
Richard Smith8128f332017-05-05 22:18:51 +0000767 }
Richard Smithf74d9462017-04-28 01:49:42 +0000768 }
769
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000770 // Initialize the action.
Richard Smithd9259c22017-06-09 01:36:10 +0000771 if (!BeginSourceFileAction(CI))
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000772 goto failure;
773
Bruno Cardoso Lopes7315d2d2018-07-19 12:32:06 +0000774 // If we were asked to load any module map files, do so now.
775 for (const auto &Filename : CI.getFrontendOpts().ModuleMapFiles) {
776 if (auto *File = CI.getFileManager().getFile(Filename))
777 CI.getPreprocessor().getHeaderSearchInfo().loadModuleMapFile(
778 File, /*IsSystem*/false);
779 else
780 CI.getDiagnostics().Report(diag::err_module_map_not_found) << Filename;
781 }
782
783 // Add a module declaration scope so that modules from -fmodule-map-file
784 // arguments may shadow modules found implicitly in search paths.
785 CI.getPreprocessor()
786 .getHeaderSearchInfo()
787 .getModuleMap()
788 .finishModuleDeclarationScope();
789
James Dennettf8317672013-01-23 00:45:44 +0000790 // Create the AST context and consumer unless this is a preprocessor only
791 // action.
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000792 if (!usesPreprocessorOnly()) {
Ted Kremenekeeccb302014-08-27 15:14:15 +0000793 // Parsing a model file should reuse the existing ASTContext.
794 if (!isModelParsingAction())
795 CI.createASTContext();
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000796
Taewook Oh06b1af52017-03-07 20:20:23 +0000797 // For preprocessed files, check if the first line specifies the original
798 // source file name with a linemarker.
Richard Smithd6509cf2018-09-15 01:21:15 +0000799 std::string PresumedInputFile = getCurrentFileOrBufferName();
Taewook Oh06b1af52017-03-07 20:20:23 +0000800 if (Input.isPreprocessed())
Richard Smith8128f332017-05-05 22:18:51 +0000801 ReadOriginalFileName(CI, PresumedInputFile);
Taewook Oh06b1af52017-03-07 20:20:23 +0000802
David Blaikie6beb6aa2014-08-10 19:56:51 +0000803 std::unique_ptr<ASTConsumer> Consumer =
Richard Smith8128f332017-05-05 22:18:51 +0000804 CreateWrappedASTConsumer(CI, PresumedInputFile);
Fariborz Jahanian2129ccf2010-10-29 19:49:13 +0000805 if (!Consumer)
806 goto failure;
Sebastian Redl07a89a82010-07-30 00:29:29 +0000807
Ted Kremenekeeccb302014-08-27 15:14:15 +0000808 // FIXME: should not overwrite ASTMutationListener when parsing model files?
809 if (!isModelParsingAction())
810 CI.getASTContext().setASTMutationListener(Consumer->GetASTMutationListener());
Richard Smithe842a472014-10-22 02:05:46 +0000811
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +0000812 if (!CI.getPreprocessorOpts().ChainedIncludes.empty()) {
813 // Convert headers to PCH and chain them.
Alp Toker9e0523d2014-07-07 11:07:10 +0000814 IntrusiveRefCntPtr<ExternalSemaSource> source, FinalReader;
815 source = createChainedIncludesSource(CI, FinalReader);
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +0000816 if (!source)
817 goto failure;
Alp Toker9e0523d2014-07-07 11:07:10 +0000818 CI.setModuleManager(static_cast<ASTReader *>(FinalReader.get()));
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +0000819 CI.getASTContext().setExternalSource(source);
Vassil Vassileva2c2d942017-02-07 21:49:41 +0000820 } else if (CI.getLangOpts().Modules ||
821 !CI.getPreprocessorOpts().ImplicitPCHInclude.empty()) {
822 // Use PCM or PCH.
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000823 assert(hasPCHSupport() && "This action does not have PCH support!");
Douglas Gregor925296b2011-07-19 16:10:42 +0000824 ASTDeserializationListener *DeserialListener =
825 Consumer->GetASTDeserializationListener();
Nico Weber824285e2014-05-08 04:26:47 +0000826 bool DeleteDeserialListener = false;
827 if (CI.getPreprocessorOpts().DumpDeserializedPCHDecls) {
828 DeserialListener = new DeserializedDeclsDumper(DeserialListener,
829 DeleteDeserialListener);
830 DeleteDeserialListener = true;
831 }
832 if (!CI.getPreprocessorOpts().DeserializedPCHDeclsToErrorOn.empty()) {
833 DeserialListener = new DeserializedDeclsChecker(
834 CI.getASTContext(),
835 CI.getPreprocessorOpts().DeserializedPCHDeclsToErrorOn,
836 DeserialListener, DeleteDeserialListener);
837 DeleteDeserialListener = true;
838 }
Vassil Vassileva2c2d942017-02-07 21:49:41 +0000839 if (!CI.getPreprocessorOpts().ImplicitPCHInclude.empty()) {
840 CI.createPCHExternalASTSource(
841 CI.getPreprocessorOpts().ImplicitPCHInclude,
842 CI.getPreprocessorOpts().DisablePCHValidation,
Nico Weber824285e2014-05-08 04:26:47 +0000843 CI.getPreprocessorOpts().AllowPCHWithCompilerErrors, DeserialListener,
Vassil Vassileva2c2d942017-02-07 21:49:41 +0000844 DeleteDeserialListener);
845 if (!CI.getASTContext().getExternalSource())
846 goto failure;
847 }
848 // If modules are enabled, create the module manager before creating
849 // any builtins, so that all declarations know that they might be
850 // extended by an external source.
851 if (CI.getLangOpts().Modules || !CI.hasASTContext() ||
852 !CI.getASTContext().getExternalSource()) {
853 CI.createModuleManager();
854 CI.getModuleManager()->setDeserializationListener(DeserialListener,
855 DeleteDeserialListener);
856 }
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000857 }
Sebastian Redl4d3af3e2010-07-09 21:00:24 +0000858
David Blaikie6beb6aa2014-08-10 19:56:51 +0000859 CI.setASTConsumer(std::move(Consumer));
Sebastian Redl4d3af3e2010-07-09 21:00:24 +0000860 if (!CI.hasASTConsumer())
861 goto failure;
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000862 }
863
Jonathan D. Turner0248f572011-08-05 22:17:03 +0000864 // Initialize built-in info as long as we aren't using an external AST
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000865 // source.
Vassil Vassileva2c2d942017-02-07 21:49:41 +0000866 if (CI.getLangOpts().Modules || !CI.hasASTContext() ||
867 !CI.getASTContext().getExternalSource()) {
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000868 Preprocessor &PP = CI.getPreprocessor();
Eric Christopher02d5d862015-08-06 01:01:12 +0000869 PP.getBuiltinInfo().initializeBuiltins(PP.getIdentifierTable(),
David Blaikiebbafb8a2012-03-11 07:00:24 +0000870 PP.getLangOpts());
Richard Smith053f6c62014-05-16 23:01:30 +0000871 } else {
872 // FIXME: If this is a problem, recover from it by creating a multiplex
873 // source.
874 assert((!CI.getLangOpts().Modules || CI.getModuleManager()) &&
875 "modules enabled but created an external source that "
876 "doesn't support modules");
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000877 }
878
Richard Smithd4b230b2014-10-27 23:01:16 +0000879 // If we were asked to load any module files, do so now.
880 for (const auto &ModuleFile : CI.getFrontendOpts().ModuleFiles)
881 if (!CI.loadModuleFile(ModuleFile))
Richard Smithe842a472014-10-22 02:05:46 +0000882 goto failure;
Richard Smithe842a472014-10-22 02:05:46 +0000883
Douglas Gregore9fc3772012-01-26 07:55:45 +0000884 // If there is a layout overrides file, attach an external AST source that
885 // provides the layouts from that file.
Taewook Oh06b1af52017-03-07 20:20:23 +0000886 if (!CI.getFrontendOpts().OverrideRecordLayoutsFile.empty() &&
Douglas Gregore9fc3772012-01-26 07:55:45 +0000887 CI.hasASTContext() && !CI.getASTContext().getExternalSource()) {
Taewook Oh06b1af52017-03-07 20:20:23 +0000888 IntrusiveRefCntPtr<ExternalASTSource>
Douglas Gregore9fc3772012-01-26 07:55:45 +0000889 Override(new LayoutOverrideSource(
890 CI.getFrontendOpts().OverrideRecordLayoutsFile));
891 CI.getASTContext().setExternalSource(Override);
892 }
Richard Smith053f6c62014-05-16 23:01:30 +0000893
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000894 return true;
895
896 // If we failed, reset state since the client will not end up calling the
897 // matching EndSourceFile().
Richard Smithab755972017-06-05 18:10:11 +0000898failure:
Jordan Roseea762b02012-08-10 01:06:08 +0000899 if (HasBegunSourceFile)
900 CI.getDiagnosticClient().EndSourceFile();
Benjamin Kramer3c717b42012-10-14 19:21:21 +0000901 CI.clearOutputFiles(/*EraseFiles=*/true);
Richard Smithf74d9462017-04-28 01:49:42 +0000902 CI.getLangOpts().setCompilingModule(LangOptions::CMK_None);
Douglas Gregor32fbe312012-01-20 16:28:04 +0000903 setCurrentInput(FrontendInputFile());
Craig Topper49a27902014-05-22 04:46:25 +0000904 setCompilerInstance(nullptr);
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000905 return false;
906}
907
Argyrios Kyrtzidis1416e172012-06-08 05:48:06 +0000908bool FrontendAction::Execute() {
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000909 CompilerInstance &CI = getCompilerInstance();
910
Kovarththanan Rajaratnam5505dff2009-11-29 09:57:35 +0000911 if (CI.hasFrontendTimer()) {
912 llvm::TimeRegion Timer(CI.getFrontendTimer());
913 ExecuteAction();
914 }
915 else ExecuteAction();
Argyrios Kyrtzidis1416e172012-06-08 05:48:06 +0000916
Douglas Gregor5e306b12013-01-23 22:38:11 +0000917 // If we are supposed to rebuild the global module index, do so now unless
Douglas Gregorc1bbec82013-01-25 00:45:27 +0000918 // there were any module-build failures.
919 if (CI.shouldBuildGlobalModuleIndex() && CI.hasFileManager() &&
920 CI.hasPreprocessor()) {
Richard Smith3938f0c2015-08-15 00:34:15 +0000921 StringRef Cache =
922 CI.getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
923 if (!Cache.empty())
924 GlobalModuleIndex::writeIndex(CI.getFileManager(),
925 CI.getPCHContainerReader(), Cache);
Douglas Gregor5e306b12013-01-23 22:38:11 +0000926 }
927
Argyrios Kyrtzidis1416e172012-06-08 05:48:06 +0000928 return true;
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000929}
930
931void FrontendAction::EndSourceFile() {
932 CompilerInstance &CI = getCompilerInstance();
933
Douglas Gregor1388a892011-02-09 18:47:31 +0000934 // Inform the diagnostic client we are done with this source file.
935 CI.getDiagnosticClient().EndSourceFile();
936
Benjamin Kramer88d99e42014-08-07 20:51:16 +0000937 // Inform the preprocessor we are done.
938 if (CI.hasPreprocessor())
939 CI.getPreprocessor().EndSourceFile();
940
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000941 // Finalize the action.
942 EndSourceFileAction();
943
Nico Weber7de358e2014-04-24 02:42:04 +0000944 // Sema references the ast consumer, so reset sema first.
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000945 //
946 // FIXME: There is more per-file stuff we could just drop here?
Nico Weber7de358e2014-04-24 02:42:04 +0000947 bool DisableFree = CI.getFrontendOpts().DisableFree;
948 if (DisableFree) {
Duncan P. N. Exon Smith4a8212a2015-05-04 14:59:20 +0000949 CI.resetAndLeakSema();
950 CI.resetAndLeakASTContext();
David Blaikie6beb6aa2014-08-10 19:56:51 +0000951 BuryPointer(CI.takeASTConsumer().get());
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000952 } else {
Duncan P. N. Exon Smith4a8212a2015-05-04 14:59:20 +0000953 CI.setSema(nullptr);
954 CI.setASTContext(nullptr);
Craig Topper49a27902014-05-22 04:46:25 +0000955 CI.setASTConsumer(nullptr);
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000956 }
957
958 if (CI.getFrontendOpts().ShowStats) {
959 llvm::errs() << "\nSTATISTICS FOR '" << getCurrentFile() << "':\n";
960 CI.getPreprocessor().PrintStats();
961 CI.getPreprocessor().getIdentifierTable().PrintStats();
962 CI.getPreprocessor().getHeaderSearchInfo().PrintStats();
963 CI.getSourceManager().PrintStats();
964 llvm::errs() << "\n";
965 }
966
Argyrios Kyrtzidisf0168de2013-06-11 00:36:55 +0000967 // Cleanup the output streams, and erase the output files if instructed by the
968 // FrontendAction.
969 CI.clearOutputFiles(/*EraseFiles=*/shouldEraseOutputFiles());
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000970
Nico Weber1f29ccf2014-04-24 03:31:27 +0000971 if (isCurrentFileAST()) {
Duncan P. N. Exon Smith4a8212a2015-05-04 14:59:20 +0000972 if (DisableFree) {
973 CI.resetAndLeakPreprocessor();
974 CI.resetAndLeakSourceManager();
975 CI.resetAndLeakFileManager();
Richard Smithab755972017-06-05 18:10:11 +0000976 BuryPointer(CurrentASTUnit.release());
Duncan P. N. Exon Smith4a8212a2015-05-04 14:59:20 +0000977 } else {
978 CI.setPreprocessor(nullptr);
979 CI.setSourceManager(nullptr);
980 CI.setFileManager(nullptr);
981 }
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000982 }
983
Craig Topper49a27902014-05-22 04:46:25 +0000984 setCompilerInstance(nullptr);
Douglas Gregor32fbe312012-01-20 16:28:04 +0000985 setCurrentInput(FrontendInputFile());
Richard Smithf74d9462017-04-28 01:49:42 +0000986 CI.getLangOpts().setCompilingModule(LangOptions::CMK_None);
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000987}
988
Argyrios Kyrtzidisf0168de2013-06-11 00:36:55 +0000989bool FrontendAction::shouldEraseOutputFiles() {
990 return getCompilerInstance().getDiagnostics().hasErrorOccurred();
991}
992
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000993//===----------------------------------------------------------------------===//
994// Utility Actions
995//===----------------------------------------------------------------------===//
996
997void ASTFrontendAction::ExecuteAction() {
998 CompilerInstance &CI = getCompilerInstance();
Rafael Espindola5150f2f2013-07-28 13:23:37 +0000999 if (!CI.hasPreprocessor())
1000 return;
Daniel Dunbara0ff58d2009-11-14 10:42:35 +00001001
1002 // FIXME: Move the truncation aspect of this into Sema, we delayed this till
1003 // here so the source manager would be initialized.
1004 if (hasCodeCompletionSupport() &&
1005 !CI.getFrontendOpts().CodeCompletionAt.FileName.empty())
1006 CI.createCodeCompletionConsumer();
1007
1008 // Use a code completion consumer?
Craig Topper49a27902014-05-22 04:46:25 +00001009 CodeCompleteConsumer *CompletionConsumer = nullptr;
Daniel Dunbara0ff58d2009-11-14 10:42:35 +00001010 if (CI.hasCodeCompletionConsumer())
1011 CompletionConsumer = &CI.getCodeCompletionConsumer();
1012
Douglas Gregor0e93f012010-08-12 23:31:19 +00001013 if (!CI.hasSema())
Douglas Gregor69f74f82011-08-25 22:30:56 +00001014 CI.createSema(getTranslationUnitKind(), CompletionConsumer);
Douglas Gregor0e93f012010-08-12 23:31:19 +00001015
Erik Verbruggen6e922512012-04-12 10:11:59 +00001016 ParseAST(CI.getSema(), CI.getFrontendOpts().ShowStats,
1017 CI.getFrontendOpts().SkipFunctionBodies);
Daniel Dunbara0ff58d2009-11-14 10:42:35 +00001018}
1019
David Blaikie68e081d2011-12-20 02:48:34 +00001020void PluginASTAction::anchor() { }
1021
David Blaikie6beb6aa2014-08-10 19:56:51 +00001022std::unique_ptr<ASTConsumer>
Daniel Dunbara0ff58d2009-11-14 10:42:35 +00001023PreprocessorFrontendAction::CreateASTConsumer(CompilerInstance &CI,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001024 StringRef InFile) {
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00001025 llvm_unreachable("Invalid CreateASTConsumer on preprocessor action!");
Daniel Dunbara0ff58d2009-11-14 10:42:35 +00001026}
Chandler Carruthb5703512011-06-16 16:17:05 +00001027
David Blaikie6beb6aa2014-08-10 19:56:51 +00001028std::unique_ptr<ASTConsumer>
1029WrapperFrontendAction::CreateASTConsumer(CompilerInstance &CI,
1030 StringRef InFile) {
Chandler Carruthb5703512011-06-16 16:17:05 +00001031 return WrappedAction->CreateASTConsumer(CI, InFile);
1032}
Argyrios Kyrtzidis90b6a2a2011-06-18 00:53:41 +00001033bool WrapperFrontendAction::BeginInvocation(CompilerInstance &CI) {
1034 return WrappedAction->BeginInvocation(CI);
1035}
Richard Smithd9259c22017-06-09 01:36:10 +00001036bool WrapperFrontendAction::BeginSourceFileAction(CompilerInstance &CI) {
Douglas Gregor32fbe312012-01-20 16:28:04 +00001037 WrappedAction->setCurrentInput(getCurrentInput());
Argyrios Kyrtzidis90b6a2a2011-06-18 00:53:41 +00001038 WrappedAction->setCompilerInstance(&CI);
Richard Smithd9259c22017-06-09 01:36:10 +00001039 auto Ret = WrappedAction->BeginSourceFileAction(CI);
Argyrios Kyrtzidise89a1792016-02-16 05:39:33 +00001040 // BeginSourceFileAction may change CurrentInput, e.g. during module builds.
1041 setCurrentInput(WrappedAction->getCurrentInput());
1042 return Ret;
Chandler Carruthb5703512011-06-16 16:17:05 +00001043}
1044void WrapperFrontendAction::ExecuteAction() {
1045 WrappedAction->ExecuteAction();
1046}
1047void WrapperFrontendAction::EndSourceFileAction() {
1048 WrappedAction->EndSourceFileAction();
1049}
1050
1051bool WrapperFrontendAction::usesPreprocessorOnly() const {
1052 return WrappedAction->usesPreprocessorOnly();
1053}
Douglas Gregor69f74f82011-08-25 22:30:56 +00001054TranslationUnitKind WrapperFrontendAction::getTranslationUnitKind() {
1055 return WrappedAction->getTranslationUnitKind();
Chandler Carruthb5703512011-06-16 16:17:05 +00001056}
1057bool WrapperFrontendAction::hasPCHSupport() const {
1058 return WrappedAction->hasPCHSupport();
1059}
1060bool WrapperFrontendAction::hasASTFileSupport() const {
1061 return WrappedAction->hasASTFileSupport();
1062}
1063bool WrapperFrontendAction::hasIRSupport() const {
1064 return WrappedAction->hasIRSupport();
1065}
1066bool WrapperFrontendAction::hasCodeCompletionSupport() const {
1067 return WrappedAction->hasCodeCompletionSupport();
1068}
1069
Argyrios Kyrtzidisd35e98f2016-02-07 19:28:36 +00001070WrapperFrontendAction::WrapperFrontendAction(
1071 std::unique_ptr<FrontendAction> WrappedAction)
1072 : WrappedAction(std::move(WrappedAction)) {}
Chandler Carruthb5703512011-06-16 16:17:05 +00001073