blob: 0dd07d9f817bd980254cff76355e23ee61707371 [file] [log] [blame]
Daniel Dunbara0ff58d2009-11-14 10:42:35 +00001//===--- FrontendAction.cpp -----------------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "clang/Frontend/FrontendAction.h"
Sebastian Redl07a89a82010-07-30 00:29:29 +000011#include "clang/AST/ASTConsumer.h"
Daniel Dunbara0ff58d2009-11-14 10:42:35 +000012#include "clang/AST/ASTContext.h"
Nico Weber2992efa2011-01-25 20:34:14 +000013#include "clang/AST/DeclGroup.h"
Daniel Dunbara0ff58d2009-11-14 10:42:35 +000014#include "clang/Frontend/ASTUnit.h"
15#include "clang/Frontend/CompilerInstance.h"
16#include "clang/Frontend/FrontendDiagnostic.h"
Nico Weber2992efa2011-01-25 20:34:14 +000017#include "clang/Frontend/FrontendPluginRegistry.h"
Douglas Gregore9fc3772012-01-26 07:55:45 +000018#include "clang/Frontend/LayoutOverrideSource.h"
Nico Weber2992efa2011-01-25 20:34:14 +000019#include "clang/Frontend/MultiplexConsumer.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000020#include "clang/Frontend/Utils.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000021#include "clang/Lex/HeaderSearch.h"
Taewook Oh06b1af52017-03-07 20:20:23 +000022#include "clang/Lex/LiteralSupport.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000023#include "clang/Lex/Preprocessor.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000024#include "clang/Lex/PreprocessorOptions.h"
John McCall8b0666c2010-08-20 18:27:03 +000025#include "clang/Parse/ParseAST.h"
Argyrios Kyrtzidisa11aca42010-10-14 20:14:18 +000026#include "clang/Serialization/ASTDeserializationListener.h"
Jonathan D. Turner0248f572011-08-05 22:17:03 +000027#include "clang/Serialization/ASTReader.h"
Douglas Gregor5e306b12013-01-23 22:38:11 +000028#include "clang/Serialization/GlobalModuleIndex.h"
Daniel Dunbara0ff58d2009-11-14 10:42:35 +000029#include "llvm/Support/ErrorHandling.h"
Douglas Gregorfc9e7a22012-10-23 06:18:24 +000030#include "llvm/Support/FileSystem.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000031#include "llvm/Support/Path.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000032#include "llvm/Support/Timer.h"
Daniel Dunbara0ff58d2009-11-14 10:42:35 +000033#include "llvm/Support/raw_ostream.h"
Rafael Espindola8a8e5542014-06-12 17:19:42 +000034#include <system_error>
Daniel Dunbara0ff58d2009-11-14 10:42:35 +000035using namespace clang;
36
John Brawn4d79ec72016-08-05 11:01:08 +000037LLVM_INSTANTIATE_REGISTRY(FrontendPluginRegistry)
NAKAMURA Takumiad4c06c2014-07-11 15:06:24 +000038
Argyrios Kyrtzidisa11aca42010-10-14 20:14:18 +000039namespace {
40
Argyrios Kyrtzidisb12986f2011-10-28 22:54:31 +000041class DelegatingDeserializationListener : public ASTDeserializationListener {
Argyrios Kyrtzidisa11aca42010-10-14 20:14:18 +000042 ASTDeserializationListener *Previous;
Nico Weber824285e2014-05-08 04:26:47 +000043 bool DeletePrevious;
Argyrios Kyrtzidisa11aca42010-10-14 20:14:18 +000044
45public:
Argyrios Kyrtzidisb12986f2011-10-28 22:54:31 +000046 explicit DelegatingDeserializationListener(
Nico Weber824285e2014-05-08 04:26:47 +000047 ASTDeserializationListener *Previous, bool DeletePrevious)
48 : Previous(Previous), DeletePrevious(DeletePrevious) {}
Alexander Kornienko34eb2072015-04-11 02:00:23 +000049 ~DelegatingDeserializationListener() override {
Nico Weber824285e2014-05-08 04:26:47 +000050 if (DeletePrevious)
51 delete Previous;
52 }
Argyrios Kyrtzidisa11aca42010-10-14 20:14:18 +000053
Craig Topperafa7cb32014-03-13 06:07:04 +000054 void ReaderInitialized(ASTReader *Reader) override {
Argyrios Kyrtzidisb12986f2011-10-28 22:54:31 +000055 if (Previous)
56 Previous->ReaderInitialized(Reader);
57 }
Craig Topperafa7cb32014-03-13 06:07:04 +000058 void IdentifierRead(serialization::IdentID ID,
59 IdentifierInfo *II) override {
Argyrios Kyrtzidisb12986f2011-10-28 22:54:31 +000060 if (Previous)
61 Previous->IdentifierRead(ID, II);
62 }
Craig Topperafa7cb32014-03-13 06:07:04 +000063 void TypeRead(serialization::TypeIdx Idx, QualType T) override {
Argyrios Kyrtzidisb12986f2011-10-28 22:54:31 +000064 if (Previous)
65 Previous->TypeRead(Idx, T);
66 }
Craig Topperafa7cb32014-03-13 06:07:04 +000067 void DeclRead(serialization::DeclID ID, const Decl *D) override {
Argyrios Kyrtzidisb12986f2011-10-28 22:54:31 +000068 if (Previous)
69 Previous->DeclRead(ID, D);
70 }
Craig Topperafa7cb32014-03-13 06:07:04 +000071 void SelectorRead(serialization::SelectorID ID, Selector Sel) override {
Argyrios Kyrtzidisb12986f2011-10-28 22:54:31 +000072 if (Previous)
73 Previous->SelectorRead(ID, Sel);
74 }
Craig Topperafa7cb32014-03-13 06:07:04 +000075 void MacroDefinitionRead(serialization::PreprocessedEntityID PPID,
Richard Smith66a81862015-05-04 02:25:31 +000076 MacroDefinitionRecord *MD) override {
Argyrios Kyrtzidisb12986f2011-10-28 22:54:31 +000077 if (Previous)
78 Previous->MacroDefinitionRead(PPID, MD);
79 }
80};
81
82/// \brief Dumps deserialized declarations.
83class DeserializedDeclsDumper : public DelegatingDeserializationListener {
84public:
Nico Weber824285e2014-05-08 04:26:47 +000085 explicit DeserializedDeclsDumper(ASTDeserializationListener *Previous,
86 bool DeletePrevious)
87 : DelegatingDeserializationListener(Previous, DeletePrevious) {}
Argyrios Kyrtzidisb12986f2011-10-28 22:54:31 +000088
Craig Topperafa7cb32014-03-13 06:07:04 +000089 void DeclRead(serialization::DeclID ID, const Decl *D) override {
Argyrios Kyrtzidisa11aca42010-10-14 20:14:18 +000090 llvm::outs() << "PCH DECL: " << D->getDeclKindName();
91 if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
Benjamin Kramerdb0fc512012-02-07 11:57:57 +000092 llvm::outs() << " - " << *ND;
Argyrios Kyrtzidisa11aca42010-10-14 20:14:18 +000093 llvm::outs() << "\n";
94
Argyrios Kyrtzidisb12986f2011-10-28 22:54:31 +000095 DelegatingDeserializationListener::DeclRead(ID, D);
Argyrios Kyrtzidisa11aca42010-10-14 20:14:18 +000096 }
Argyrios Kyrtzidisa11aca42010-10-14 20:14:18 +000097};
98
David Blaikie48b81282012-05-29 17:05:42 +000099/// \brief Checks deserialized declarations and emits error if a name
100/// matches one given in command-line using -error-on-deserialized-decl.
101class DeserializedDeclsChecker : public DelegatingDeserializationListener {
102 ASTContext &Ctx;
103 std::set<std::string> NamesToCheck;
Argyrios Kyrtzidis0427be92010-10-14 20:14:25 +0000104
David Blaikie48b81282012-05-29 17:05:42 +0000105public:
106 DeserializedDeclsChecker(ASTContext &Ctx,
107 const std::set<std::string> &NamesToCheck,
Nico Weber824285e2014-05-08 04:26:47 +0000108 ASTDeserializationListener *Previous,
109 bool DeletePrevious)
110 : DelegatingDeserializationListener(Previous, DeletePrevious), Ctx(Ctx),
111 NamesToCheck(NamesToCheck) {}
Argyrios Kyrtzidis0427be92010-10-14 20:14:25 +0000112
Craig Topperafa7cb32014-03-13 06:07:04 +0000113 void DeclRead(serialization::DeclID ID, const Decl *D) override {
David Blaikie48b81282012-05-29 17:05:42 +0000114 if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
115 if (NamesToCheck.find(ND->getNameAsString()) != NamesToCheck.end()) {
116 unsigned DiagID
117 = Ctx.getDiagnostics().getCustomDiagID(DiagnosticsEngine::Error,
118 "%0 was deserialized");
119 Ctx.getDiagnostics().Report(Ctx.getFullLoc(D->getLocation()), DiagID)
120 << ND->getNameAsString();
121 }
Argyrios Kyrtzidis0427be92010-10-14 20:14:25 +0000122
David Blaikie48b81282012-05-29 17:05:42 +0000123 DelegatingDeserializationListener::DeclRead(ID, D);
124 }
Argyrios Kyrtzidis0427be92010-10-14 20:14:25 +0000125};
126
Argyrios Kyrtzidisa11aca42010-10-14 20:14:18 +0000127} // end anonymous namespace
128
Craig Topper49a27902014-05-22 04:46:25 +0000129FrontendAction::FrontendAction() : Instance(nullptr) {}
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000130
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +0000131FrontendAction::~FrontendAction() {}
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000132
Douglas Gregor32fbe312012-01-20 16:28:04 +0000133void FrontendAction::setCurrentInput(const FrontendInputFile &CurrentInput,
David Blaikief62d4e72014-08-10 17:03:42 +0000134 std::unique_ptr<ASTUnit> AST) {
Douglas Gregor32fbe312012-01-20 16:28:04 +0000135 this->CurrentInput = CurrentInput;
David Blaikief62d4e72014-08-10 17:03:42 +0000136 CurrentASTUnit = std::move(AST);
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000137}
138
David Blaikie6beb6aa2014-08-10 19:56:51 +0000139std::unique_ptr<ASTConsumer>
140FrontendAction::CreateWrappedASTConsumer(CompilerInstance &CI,
141 StringRef InFile) {
142 std::unique_ptr<ASTConsumer> Consumer = CreateASTConsumer(CI, InFile);
Nico Weber2992efa2011-01-25 20:34:14 +0000143 if (!Consumer)
Craig Topper49a27902014-05-22 04:46:25 +0000144 return nullptr;
Nico Weber2992efa2011-01-25 20:34:14 +0000145
John Brawn6c789742016-03-15 12:51:40 +0000146 // If there are no registered plugins we don't need to wrap the consumer
147 if (FrontendPluginRegistry::begin() == FrontendPluginRegistry::end())
Nico Weber2992efa2011-01-25 20:34:14 +0000148 return Consumer;
149
John Brawn6c789742016-03-15 12:51:40 +0000150 // Collect the list of plugins that go before the main action (in Consumers)
151 // or after it (in AfterConsumers)
David Blaikie6beb6aa2014-08-10 19:56:51 +0000152 std::vector<std::unique_ptr<ASTConsumer>> Consumers;
John Brawn6c789742016-03-15 12:51:40 +0000153 std::vector<std::unique_ptr<ASTConsumer>> AfterConsumers;
154 for (FrontendPluginRegistry::iterator it = FrontendPluginRegistry::begin(),
155 ie = FrontendPluginRegistry::end();
156 it != ie; ++it) {
157 std::unique_ptr<PluginASTAction> P = it->instantiate();
158 PluginASTAction::ActionType ActionType = P->getActionType();
159 if (ActionType == PluginASTAction::Cmdline) {
160 // This is O(|plugins| * |add_plugins|), but since both numbers are
161 // way below 50 in practice, that's ok.
162 for (size_t i = 0, e = CI.getFrontendOpts().AddPluginActions.size();
163 i != e; ++i) {
164 if (it->getName() == CI.getFrontendOpts().AddPluginActions[i]) {
165 ActionType = PluginASTAction::AddAfterMainAction;
166 break;
167 }
168 }
Nico Weber2992efa2011-01-25 20:34:14 +0000169 }
John Brawn6c789742016-03-15 12:51:40 +0000170 if ((ActionType == PluginASTAction::AddBeforeMainAction ||
171 ActionType == PluginASTAction::AddAfterMainAction) &&
172 P->ParseArgs(CI, CI.getFrontendOpts().PluginArgs[it->getName()])) {
173 std::unique_ptr<ASTConsumer> PluginConsumer = P->CreateASTConsumer(CI, InFile);
174 if (ActionType == PluginASTAction::AddBeforeMainAction) {
175 Consumers.push_back(std::move(PluginConsumer));
176 } else {
177 AfterConsumers.push_back(std::move(PluginConsumer));
178 }
179 }
180 }
181
182 // Add to Consumers the main consumer, then all the plugins that go after it
183 Consumers.push_back(std::move(Consumer));
184 for (auto &C : AfterConsumers) {
185 Consumers.push_back(std::move(C));
Nico Weber2992efa2011-01-25 20:34:14 +0000186 }
187
David Blaikie6beb6aa2014-08-10 19:56:51 +0000188 return llvm::make_unique<MultiplexConsumer>(std::move(Consumers));
Nico Weber2992efa2011-01-25 20:34:14 +0000189}
190
Taewook Oh06b1af52017-03-07 20:20:23 +0000191// For preprocessed files, if the first line is the linemarker and specifies
192// the original source file name, use that name as the input file name.
193static bool ReadOriginalFileName(CompilerInstance &CI, std::string &InputFile)
194{
195 bool Invalid = false;
196 auto &SourceMgr = CI.getSourceManager();
197 auto MainFileID = SourceMgr.getMainFileID();
198 const auto *MainFileBuf = SourceMgr.getBuffer(MainFileID, &Invalid);
199 if (Invalid)
200 return false;
201
202 std::unique_ptr<Lexer> RawLexer(
203 new Lexer(MainFileID, MainFileBuf, SourceMgr, CI.getLangOpts()));
204
205 // If the first line has the syntax of
206 //
207 // # NUM "FILENAME"
208 //
209 // we use FILENAME as the input file name.
210 Token T;
211 if (RawLexer->LexFromRawLexer(T) || T.getKind() != tok::hash)
212 return false;
213 if (RawLexer->LexFromRawLexer(T) || T.isAtStartOfLine() ||
214 T.getKind() != tok::numeric_constant)
215 return false;
216 RawLexer->LexFromRawLexer(T);
217 if (T.isAtStartOfLine() || T.getKind() != tok::string_literal)
218 return false;
219
220 StringLiteralParser Literal(T, CI.getPreprocessor());
221 if (Literal.hadError)
222 return false;
223 InputFile = Literal.GetString().str();
224 return true;
225}
226
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000227bool FrontendAction::BeginSourceFile(CompilerInstance &CI,
Douglas Gregor32fbe312012-01-20 16:28:04 +0000228 const FrontendInputFile &Input) {
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000229 assert(!Instance && "Already processing a source file!");
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +0000230 assert(!Input.isEmpty() && "Unexpected empty filename!");
Douglas Gregor32fbe312012-01-20 16:28:04 +0000231 setCurrentInput(Input);
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000232 setCompilerInstance(&CI);
233
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +0000234 StringRef InputFile = Input.getFile();
Jordan Roseea762b02012-08-10 01:06:08 +0000235 bool HasBegunSourceFile = false;
Argyrios Kyrtzidis90b6a2a2011-06-18 00:53:41 +0000236 if (!BeginInvocation(CI))
237 goto failure;
238
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000239 // AST files follow a very different path, since they share objects via the
240 // AST unit.
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +0000241 if (Input.getKind() == IK_AST) {
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000242 assert(!usesPreprocessorOnly() &&
243 "Attempt to pass AST file to preprocessor only action!");
Daniel Dunbarfa6214c2010-06-07 23:24:43 +0000244 assert(hasASTFileSupport() &&
245 "This action does not have AST file support!");
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000246
Dylan Noblesmithc95d8192012-02-20 14:00:23 +0000247 IntrusiveRefCntPtr<DiagnosticsEngine> Diags(&CI.getDiagnostics());
Alp Toker965f8822013-11-27 05:22:15 +0000248
Adrian Prantl6b21ab22015-08-27 19:46:20 +0000249 std::unique_ptr<ASTUnit> AST = ASTUnit::LoadFromASTFile(
250 InputFile, CI.getPCHContainerReader(), Diags, CI.getFileSystemOpts(),
251 CI.getCodeGenOpts().DebugTypeExtRefs);
David Blaikief62d4e72014-08-10 17:03:42 +0000252
Daniel Dunbar59203002009-12-03 01:45:44 +0000253 if (!AST)
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000254 goto failure;
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000255
Argyrios Kyrtzidisc00f43a2013-03-18 22:55:24 +0000256 // Inform the diagnostic client we are processing a source file.
Craig Topper49a27902014-05-22 04:46:25 +0000257 CI.getDiagnosticClient().BeginSourceFile(CI.getLangOpts(), nullptr);
Argyrios Kyrtzidisc00f43a2013-03-18 22:55:24 +0000258 HasBegunSourceFile = true;
259
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000260 // Set the shared objects, these are reset when we finish processing the
261 // file, otherwise the CompilerInstance will happily destroy them.
262 CI.setFileManager(&AST->getFileManager());
263 CI.setSourceManager(&AST->getSourceManager());
David Blaikie41565462017-01-05 19:48:07 +0000264 CI.setPreprocessor(AST->getPreprocessorPtr());
David Blaikieee123222017-02-08 20:51:11 +0000265 Preprocessor &PP = CI.getPreprocessor();
266 PP.getBuiltinInfo().initializeBuiltins(PP.getIdentifierTable(),
267 PP.getLangOpts());
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000268 CI.setASTContext(&AST->getASTContext());
269
David Blaikief62d4e72014-08-10 17:03:42 +0000270 setCurrentInput(Input, std::move(AST));
271
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000272 // Initialize the action.
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +0000273 if (!BeginSourceFileAction(CI, InputFile))
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000274 goto failure;
275
James Dennettf8317672013-01-23 00:45:44 +0000276 // Create the AST consumer.
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +0000277 CI.setASTConsumer(CreateWrappedASTConsumer(CI, InputFile));
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000278 if (!CI.hasASTConsumer())
279 goto failure;
280
281 return true;
282 }
283
Ben Langmuir8832c062014-04-15 18:16:25 +0000284 if (!CI.hasVirtualFileSystem()) {
285 if (IntrusiveRefCntPtr<vfs::FileSystem> VFS =
286 createVFSFromCompilerInvocation(CI.getInvocation(),
287 CI.getDiagnostics()))
288 CI.setVirtualFileSystem(VFS);
289 else
290 goto failure;
Ben Langmuir801272a2014-02-25 18:23:47 +0000291 }
292
Daniel Dunbar9507f9c2010-06-07 23:26:47 +0000293 // Set up the file and source managers, if needed.
Daniel Dunbaraed46fc2010-06-07 23:23:50 +0000294 if (!CI.hasFileManager())
295 CI.createFileManager();
296 if (!CI.hasSourceManager())
Chris Lattner5159f612010-11-23 08:35:12 +0000297 CI.createSourceManager(CI.getFileManager());
Daniel Dunbar9507f9c2010-06-07 23:26:47 +0000298
299 // IR files bypass the rest of initialization.
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +0000300 if (Input.getKind() == IK_LLVM_IR) {
Daniel Dunbar9507f9c2010-06-07 23:26:47 +0000301 assert(hasIRSupport() &&
302 "This action does not have IR file support!");
303
304 // Inform the diagnostic client we are processing a source file.
Craig Topper49a27902014-05-22 04:46:25 +0000305 CI.getDiagnosticClient().BeginSourceFile(CI.getLangOpts(), nullptr);
Jordan Roseea762b02012-08-10 01:06:08 +0000306 HasBegunSourceFile = true;
Daniel Dunbar9507f9c2010-06-07 23:26:47 +0000307
308 // Initialize the action.
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +0000309 if (!BeginSourceFileAction(CI, InputFile))
Daniel Dunbar9507f9c2010-06-07 23:26:47 +0000310 goto failure;
311
Ben Langmuirbeee15e2014-04-14 18:00:01 +0000312 // Initialize the main file entry.
313 if (!CI.InitializeSourceManager(CurrentInput))
314 goto failure;
315
Daniel Dunbar9507f9c2010-06-07 23:26:47 +0000316 return true;
317 }
318
Douglas Gregorfc9e7a22012-10-23 06:18:24 +0000319 // If the implicit PCH include is actually a directory, rather than
320 // a single file, search for a suitable PCH file in that directory.
321 if (!CI.getPreprocessorOpts().ImplicitPCHInclude.empty()) {
322 FileManager &FileMgr = CI.getFileManager();
323 PreprocessorOptions &PPOpts = CI.getPreprocessorOpts();
324 StringRef PCHInclude = PPOpts.ImplicitPCHInclude;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000325 std::string SpecificModuleCachePath = CI.getSpecificModuleCachePath();
Douglas Gregorfc9e7a22012-10-23 06:18:24 +0000326 if (const DirectoryEntry *PCHDir = FileMgr.getDirectory(PCHInclude)) {
Rafael Espindolac0809172014-06-12 14:02:15 +0000327 std::error_code EC;
Douglas Gregorfc9e7a22012-10-23 06:18:24 +0000328 SmallString<128> DirNative;
329 llvm::sys::path::native(PCHDir->getName(), DirNative);
330 bool Found = false;
Bruno Cardoso Lopesb4d56f12016-12-12 19:28:21 +0000331 vfs::FileSystem &FS = *FileMgr.getVirtualFileSystem();
332 for (vfs::directory_iterator Dir = FS.dir_begin(DirNative, EC), DirEnd;
Douglas Gregorfc9e7a22012-10-23 06:18:24 +0000333 Dir != DirEnd && !EC; Dir.increment(EC)) {
334 // Check whether this is an acceptable AST file.
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000335 if (ASTReader::isAcceptableASTFile(
Bruno Cardoso Lopesb4d56f12016-12-12 19:28:21 +0000336 Dir->getName(), FileMgr, CI.getPCHContainerReader(),
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000337 CI.getLangOpts(), CI.getTargetOpts(), CI.getPreprocessorOpts(),
338 SpecificModuleCachePath)) {
Bruno Cardoso Lopesb4d56f12016-12-12 19:28:21 +0000339 PPOpts.ImplicitPCHInclude = Dir->getName();
Argyrios Kyrtzidis48b72d82013-02-05 16:36:52 +0000340 Found = true;
Douglas Gregorfc9e7a22012-10-23 06:18:24 +0000341 break;
342 }
343 }
344
345 if (!Found) {
346 CI.getDiagnostics().Report(diag::err_fe_no_pch_in_dir) << PCHInclude;
Richard Smith81c72482015-09-04 21:44:32 +0000347 goto failure;
Douglas Gregorfc9e7a22012-10-23 06:18:24 +0000348 }
349 }
350 }
351
Ted Kremenekeeccb302014-08-27 15:14:15 +0000352 // Set up the preprocessor if needed. When parsing model files the
353 // preprocessor of the original source is reused.
354 if (!isModelParsingAction())
355 CI.createPreprocessor(getTranslationUnitKind());
Daniel Dunbaraed46fc2010-06-07 23:23:50 +0000356
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000357 // Inform the diagnostic client we are processing a source file.
358 CI.getDiagnosticClient().BeginSourceFile(CI.getLangOpts(),
359 &CI.getPreprocessor());
Jordan Roseea762b02012-08-10 01:06:08 +0000360 HasBegunSourceFile = true;
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000361
362 // Initialize the action.
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +0000363 if (!BeginSourceFileAction(CI, InputFile))
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000364 goto failure;
365
Ben Langmuirbeee15e2014-04-14 18:00:01 +0000366 // Initialize the main file entry. It is important that this occurs after
367 // BeginSourceFileAction, which may change CurrentInput during module builds.
368 if (!CI.InitializeSourceManager(CurrentInput))
369 goto failure;
370
James Dennettf8317672013-01-23 00:45:44 +0000371 // Create the AST context and consumer unless this is a preprocessor only
372 // action.
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000373 if (!usesPreprocessorOnly()) {
Ted Kremenekeeccb302014-08-27 15:14:15 +0000374 // Parsing a model file should reuse the existing ASTContext.
375 if (!isModelParsingAction())
376 CI.createASTContext();
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000377
Taewook Oh06b1af52017-03-07 20:20:23 +0000378 // For preprocessed files, check if the first line specifies the original
379 // source file name with a linemarker.
380 std::string OrigFile;
381 if (Input.isPreprocessed())
382 if (ReadOriginalFileName(CI, OrigFile))
383 InputFile = OrigFile;
384
David Blaikie6beb6aa2014-08-10 19:56:51 +0000385 std::unique_ptr<ASTConsumer> Consumer =
386 CreateWrappedASTConsumer(CI, InputFile);
Fariborz Jahanian2129ccf2010-10-29 19:49:13 +0000387 if (!Consumer)
388 goto failure;
Sebastian Redl07a89a82010-07-30 00:29:29 +0000389
Ted Kremenekeeccb302014-08-27 15:14:15 +0000390 // FIXME: should not overwrite ASTMutationListener when parsing model files?
391 if (!isModelParsingAction())
392 CI.getASTContext().setASTMutationListener(Consumer->GetASTMutationListener());
Richard Smithe842a472014-10-22 02:05:46 +0000393
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +0000394 if (!CI.getPreprocessorOpts().ChainedIncludes.empty()) {
395 // Convert headers to PCH and chain them.
Alp Toker9e0523d2014-07-07 11:07:10 +0000396 IntrusiveRefCntPtr<ExternalSemaSource> source, FinalReader;
397 source = createChainedIncludesSource(CI, FinalReader);
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +0000398 if (!source)
399 goto failure;
Alp Toker9e0523d2014-07-07 11:07:10 +0000400 CI.setModuleManager(static_cast<ASTReader *>(FinalReader.get()));
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +0000401 CI.getASTContext().setExternalSource(source);
Vassil Vassileva2c2d942017-02-07 21:49:41 +0000402 } else if (CI.getLangOpts().Modules ||
403 !CI.getPreprocessorOpts().ImplicitPCHInclude.empty()) {
404 // Use PCM or PCH.
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000405 assert(hasPCHSupport() && "This action does not have PCH support!");
Douglas Gregor925296b2011-07-19 16:10:42 +0000406 ASTDeserializationListener *DeserialListener =
407 Consumer->GetASTDeserializationListener();
Nico Weber824285e2014-05-08 04:26:47 +0000408 bool DeleteDeserialListener = false;
409 if (CI.getPreprocessorOpts().DumpDeserializedPCHDecls) {
410 DeserialListener = new DeserializedDeclsDumper(DeserialListener,
411 DeleteDeserialListener);
412 DeleteDeserialListener = true;
413 }
414 if (!CI.getPreprocessorOpts().DeserializedPCHDeclsToErrorOn.empty()) {
415 DeserialListener = new DeserializedDeclsChecker(
416 CI.getASTContext(),
417 CI.getPreprocessorOpts().DeserializedPCHDeclsToErrorOn,
418 DeserialListener, DeleteDeserialListener);
419 DeleteDeserialListener = true;
420 }
Vassil Vassileva2c2d942017-02-07 21:49:41 +0000421 if (!CI.getPreprocessorOpts().ImplicitPCHInclude.empty()) {
422 CI.createPCHExternalASTSource(
423 CI.getPreprocessorOpts().ImplicitPCHInclude,
424 CI.getPreprocessorOpts().DisablePCHValidation,
Nico Weber824285e2014-05-08 04:26:47 +0000425 CI.getPreprocessorOpts().AllowPCHWithCompilerErrors, DeserialListener,
Vassil Vassileva2c2d942017-02-07 21:49:41 +0000426 DeleteDeserialListener);
427 if (!CI.getASTContext().getExternalSource())
428 goto failure;
429 }
430 // If modules are enabled, create the module manager before creating
431 // any builtins, so that all declarations know that they might be
432 // extended by an external source.
433 if (CI.getLangOpts().Modules || !CI.hasASTContext() ||
434 !CI.getASTContext().getExternalSource()) {
435 CI.createModuleManager();
436 CI.getModuleManager()->setDeserializationListener(DeserialListener,
437 DeleteDeserialListener);
438 }
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000439 }
Sebastian Redl4d3af3e2010-07-09 21:00:24 +0000440
David Blaikie6beb6aa2014-08-10 19:56:51 +0000441 CI.setASTConsumer(std::move(Consumer));
Sebastian Redl4d3af3e2010-07-09 21:00:24 +0000442 if (!CI.hasASTConsumer())
443 goto failure;
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000444 }
445
Jonathan D. Turner0248f572011-08-05 22:17:03 +0000446 // Initialize built-in info as long as we aren't using an external AST
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000447 // source.
Vassil Vassileva2c2d942017-02-07 21:49:41 +0000448 if (CI.getLangOpts().Modules || !CI.hasASTContext() ||
449 !CI.getASTContext().getExternalSource()) {
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000450 Preprocessor &PP = CI.getPreprocessor();
Eric Christopher02d5d862015-08-06 01:01:12 +0000451 PP.getBuiltinInfo().initializeBuiltins(PP.getIdentifierTable(),
David Blaikiebbafb8a2012-03-11 07:00:24 +0000452 PP.getLangOpts());
Richard Smith053f6c62014-05-16 23:01:30 +0000453 } else {
454 // FIXME: If this is a problem, recover from it by creating a multiplex
455 // source.
456 assert((!CI.getLangOpts().Modules || CI.getModuleManager()) &&
457 "modules enabled but created an external source that "
458 "doesn't support modules");
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000459 }
460
Richard Smithac425e92015-01-23 00:01:13 +0000461 // If we were asked to load any module map files, do so now.
462 for (const auto &Filename : CI.getFrontendOpts().ModuleMapFiles) {
463 if (auto *File = CI.getFileManager().getFile(Filename))
464 CI.getPreprocessor().getHeaderSearchInfo().loadModuleMapFile(
465 File, /*IsSystem*/false);
466 else
467 CI.getDiagnostics().Report(diag::err_module_map_not_found) << Filename;
468 }
469
Richard Smithd4b230b2014-10-27 23:01:16 +0000470 // If we were asked to load any module files, do so now.
471 for (const auto &ModuleFile : CI.getFrontendOpts().ModuleFiles)
472 if (!CI.loadModuleFile(ModuleFile))
Richard Smithe842a472014-10-22 02:05:46 +0000473 goto failure;
Richard Smithe842a472014-10-22 02:05:46 +0000474
Douglas Gregore9fc3772012-01-26 07:55:45 +0000475 // If there is a layout overrides file, attach an external AST source that
476 // provides the layouts from that file.
Taewook Oh06b1af52017-03-07 20:20:23 +0000477 if (!CI.getFrontendOpts().OverrideRecordLayoutsFile.empty() &&
Douglas Gregore9fc3772012-01-26 07:55:45 +0000478 CI.hasASTContext() && !CI.getASTContext().getExternalSource()) {
Taewook Oh06b1af52017-03-07 20:20:23 +0000479 IntrusiveRefCntPtr<ExternalASTSource>
Douglas Gregore9fc3772012-01-26 07:55:45 +0000480 Override(new LayoutOverrideSource(
481 CI.getFrontendOpts().OverrideRecordLayoutsFile));
482 CI.getASTContext().setExternalSource(Override);
483 }
Richard Smith053f6c62014-05-16 23:01:30 +0000484
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000485 return true;
486
487 // If we failed, reset state since the client will not end up calling the
488 // matching EndSourceFile().
489 failure:
490 if (isCurrentFileAST()) {
Craig Topper49a27902014-05-22 04:46:25 +0000491 CI.setASTContext(nullptr);
492 CI.setPreprocessor(nullptr);
493 CI.setSourceManager(nullptr);
494 CI.setFileManager(nullptr);
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000495 }
496
Jordan Roseea762b02012-08-10 01:06:08 +0000497 if (HasBegunSourceFile)
498 CI.getDiagnosticClient().EndSourceFile();
Benjamin Kramer3c717b42012-10-14 19:21:21 +0000499 CI.clearOutputFiles(/*EraseFiles=*/true);
Douglas Gregor32fbe312012-01-20 16:28:04 +0000500 setCurrentInput(FrontendInputFile());
Craig Topper49a27902014-05-22 04:46:25 +0000501 setCompilerInstance(nullptr);
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000502 return false;
503}
504
Argyrios Kyrtzidis1416e172012-06-08 05:48:06 +0000505bool FrontendAction::Execute() {
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000506 CompilerInstance &CI = getCompilerInstance();
507
Kovarththanan Rajaratnam5505dff2009-11-29 09:57:35 +0000508 if (CI.hasFrontendTimer()) {
509 llvm::TimeRegion Timer(CI.getFrontendTimer());
510 ExecuteAction();
511 }
512 else ExecuteAction();
Argyrios Kyrtzidis1416e172012-06-08 05:48:06 +0000513
Douglas Gregor5e306b12013-01-23 22:38:11 +0000514 // If we are supposed to rebuild the global module index, do so now unless
Douglas Gregorc1bbec82013-01-25 00:45:27 +0000515 // there were any module-build failures.
516 if (CI.shouldBuildGlobalModuleIndex() && CI.hasFileManager() &&
517 CI.hasPreprocessor()) {
Richard Smith3938f0c2015-08-15 00:34:15 +0000518 StringRef Cache =
519 CI.getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
520 if (!Cache.empty())
521 GlobalModuleIndex::writeIndex(CI.getFileManager(),
522 CI.getPCHContainerReader(), Cache);
Douglas Gregor5e306b12013-01-23 22:38:11 +0000523 }
524
Argyrios Kyrtzidis1416e172012-06-08 05:48:06 +0000525 return true;
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000526}
527
528void FrontendAction::EndSourceFile() {
529 CompilerInstance &CI = getCompilerInstance();
530
Douglas Gregor1388a892011-02-09 18:47:31 +0000531 // Inform the diagnostic client we are done with this source file.
532 CI.getDiagnosticClient().EndSourceFile();
533
Benjamin Kramer88d99e42014-08-07 20:51:16 +0000534 // Inform the preprocessor we are done.
535 if (CI.hasPreprocessor())
536 CI.getPreprocessor().EndSourceFile();
537
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000538 // Finalize the action.
539 EndSourceFileAction();
540
Nico Weber7de358e2014-04-24 02:42:04 +0000541 // Sema references the ast consumer, so reset sema first.
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000542 //
543 // FIXME: There is more per-file stuff we could just drop here?
Nico Weber7de358e2014-04-24 02:42:04 +0000544 bool DisableFree = CI.getFrontendOpts().DisableFree;
545 if (DisableFree) {
Duncan P. N. Exon Smith4a8212a2015-05-04 14:59:20 +0000546 CI.resetAndLeakSema();
547 CI.resetAndLeakASTContext();
David Blaikie6beb6aa2014-08-10 19:56:51 +0000548 BuryPointer(CI.takeASTConsumer().get());
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000549 } else {
Duncan P. N. Exon Smith4a8212a2015-05-04 14:59:20 +0000550 CI.setSema(nullptr);
551 CI.setASTContext(nullptr);
Craig Topper49a27902014-05-22 04:46:25 +0000552 CI.setASTConsumer(nullptr);
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000553 }
554
555 if (CI.getFrontendOpts().ShowStats) {
556 llvm::errs() << "\nSTATISTICS FOR '" << getCurrentFile() << "':\n";
557 CI.getPreprocessor().PrintStats();
558 CI.getPreprocessor().getIdentifierTable().PrintStats();
559 CI.getPreprocessor().getHeaderSearchInfo().PrintStats();
560 CI.getSourceManager().PrintStats();
561 llvm::errs() << "\n";
562 }
563
Argyrios Kyrtzidisf0168de2013-06-11 00:36:55 +0000564 // Cleanup the output streams, and erase the output files if instructed by the
565 // FrontendAction.
566 CI.clearOutputFiles(/*EraseFiles=*/shouldEraseOutputFiles());
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000567
Nico Weber1f29ccf2014-04-24 03:31:27 +0000568 if (isCurrentFileAST()) {
Duncan P. N. Exon Smith4a8212a2015-05-04 14:59:20 +0000569 if (DisableFree) {
570 CI.resetAndLeakPreprocessor();
571 CI.resetAndLeakSourceManager();
572 CI.resetAndLeakFileManager();
573 } else {
574 CI.setPreprocessor(nullptr);
575 CI.setSourceManager(nullptr);
576 CI.setFileManager(nullptr);
577 }
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000578 }
579
Craig Topper49a27902014-05-22 04:46:25 +0000580 setCompilerInstance(nullptr);
Douglas Gregor32fbe312012-01-20 16:28:04 +0000581 setCurrentInput(FrontendInputFile());
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000582}
583
Argyrios Kyrtzidisf0168de2013-06-11 00:36:55 +0000584bool FrontendAction::shouldEraseOutputFiles() {
585 return getCompilerInstance().getDiagnostics().hasErrorOccurred();
586}
587
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000588//===----------------------------------------------------------------------===//
589// Utility Actions
590//===----------------------------------------------------------------------===//
591
592void ASTFrontendAction::ExecuteAction() {
593 CompilerInstance &CI = getCompilerInstance();
Rafael Espindola5150f2f2013-07-28 13:23:37 +0000594 if (!CI.hasPreprocessor())
595 return;
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000596
597 // FIXME: Move the truncation aspect of this into Sema, we delayed this till
598 // here so the source manager would be initialized.
599 if (hasCodeCompletionSupport() &&
600 !CI.getFrontendOpts().CodeCompletionAt.FileName.empty())
601 CI.createCodeCompletionConsumer();
602
603 // Use a code completion consumer?
Craig Topper49a27902014-05-22 04:46:25 +0000604 CodeCompleteConsumer *CompletionConsumer = nullptr;
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000605 if (CI.hasCodeCompletionConsumer())
606 CompletionConsumer = &CI.getCodeCompletionConsumer();
607
Douglas Gregor0e93f012010-08-12 23:31:19 +0000608 if (!CI.hasSema())
Douglas Gregor69f74f82011-08-25 22:30:56 +0000609 CI.createSema(getTranslationUnitKind(), CompletionConsumer);
Douglas Gregor0e93f012010-08-12 23:31:19 +0000610
Erik Verbruggen6e922512012-04-12 10:11:59 +0000611 ParseAST(CI.getSema(), CI.getFrontendOpts().ShowStats,
612 CI.getFrontendOpts().SkipFunctionBodies);
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000613}
614
David Blaikie68e081d2011-12-20 02:48:34 +0000615void PluginASTAction::anchor() { }
616
David Blaikie6beb6aa2014-08-10 19:56:51 +0000617std::unique_ptr<ASTConsumer>
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000618PreprocessorFrontendAction::CreateASTConsumer(CompilerInstance &CI,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000619 StringRef InFile) {
Jeffrey Yasskin1615d452009-12-12 05:05:38 +0000620 llvm_unreachable("Invalid CreateASTConsumer on preprocessor action!");
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000621}
Chandler Carruthb5703512011-06-16 16:17:05 +0000622
David Blaikie6beb6aa2014-08-10 19:56:51 +0000623std::unique_ptr<ASTConsumer>
624WrapperFrontendAction::CreateASTConsumer(CompilerInstance &CI,
625 StringRef InFile) {
Chandler Carruthb5703512011-06-16 16:17:05 +0000626 return WrappedAction->CreateASTConsumer(CI, InFile);
627}
Argyrios Kyrtzidis90b6a2a2011-06-18 00:53:41 +0000628bool WrapperFrontendAction::BeginInvocation(CompilerInstance &CI) {
629 return WrappedAction->BeginInvocation(CI);
630}
Chandler Carruthb5703512011-06-16 16:17:05 +0000631bool WrapperFrontendAction::BeginSourceFileAction(CompilerInstance &CI,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000632 StringRef Filename) {
Douglas Gregor32fbe312012-01-20 16:28:04 +0000633 WrappedAction->setCurrentInput(getCurrentInput());
Argyrios Kyrtzidis90b6a2a2011-06-18 00:53:41 +0000634 WrappedAction->setCompilerInstance(&CI);
Argyrios Kyrtzidise89a1792016-02-16 05:39:33 +0000635 auto Ret = WrappedAction->BeginSourceFileAction(CI, Filename);
636 // BeginSourceFileAction may change CurrentInput, e.g. during module builds.
637 setCurrentInput(WrappedAction->getCurrentInput());
638 return Ret;
Chandler Carruthb5703512011-06-16 16:17:05 +0000639}
640void WrapperFrontendAction::ExecuteAction() {
641 WrappedAction->ExecuteAction();
642}
643void WrapperFrontendAction::EndSourceFileAction() {
644 WrappedAction->EndSourceFileAction();
645}
646
647bool WrapperFrontendAction::usesPreprocessorOnly() const {
648 return WrappedAction->usesPreprocessorOnly();
649}
Douglas Gregor69f74f82011-08-25 22:30:56 +0000650TranslationUnitKind WrapperFrontendAction::getTranslationUnitKind() {
651 return WrappedAction->getTranslationUnitKind();
Chandler Carruthb5703512011-06-16 16:17:05 +0000652}
653bool WrapperFrontendAction::hasPCHSupport() const {
654 return WrappedAction->hasPCHSupport();
655}
656bool WrapperFrontendAction::hasASTFileSupport() const {
657 return WrappedAction->hasASTFileSupport();
658}
659bool WrapperFrontendAction::hasIRSupport() const {
660 return WrappedAction->hasIRSupport();
661}
662bool WrapperFrontendAction::hasCodeCompletionSupport() const {
663 return WrappedAction->hasCodeCompletionSupport();
664}
665
Argyrios Kyrtzidisd35e98f2016-02-07 19:28:36 +0000666WrapperFrontendAction::WrapperFrontendAction(
667 std::unique_ptr<FrontendAction> WrappedAction)
668 : WrappedAction(std::move(WrappedAction)) {}
Chandler Carruthb5703512011-06-16 16:17:05 +0000669