blob: 3c2470715077bd59a9c0cf78df4322cd707c8e6f [file] [log] [blame]
Daniel Dunbar02bd2d72009-11-14 10:42:46 +00001//===--- FrontendActions.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/FrontendActions.h"
11#include "clang/AST/ASTConsumer.h"
12#include "clang/Basic/FileManager.h"
Daniel Dunbar02bd2d72009-11-14 10:42:46 +000013#include "clang/Frontend/ASTConsumers.h"
14#include "clang/Frontend/ASTUnit.h"
15#include "clang/Frontend/CompilerInstance.h"
Daniel Dunbar02bd2d72009-11-14 10:42:46 +000016#include "clang/Frontend/FrontendDiagnostic.h"
17#include "clang/Frontend/Utils.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000018#include "clang/Lex/HeaderSearch.h"
19#include "clang/Lex/Pragma.h"
20#include "clang/Lex/Preprocessor.h"
21#include "clang/Parse/Parser.h"
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +000022#include "clang/Serialization/ASTReader.h"
Sebastian Redl1914c6f2010-08-18 23:56:37 +000023#include "clang/Serialization/ASTWriter.h"
Douglas Gregor524e33e2011-12-08 19:11:24 +000024#include "llvm/Support/FileSystem.h"
Douglas Gregoraf82e352010-07-20 20:18:03 +000025#include "llvm/Support/MemoryBuffer.h"
Daniel Dunbar02bd2d72009-11-14 10:42:46 +000026#include "llvm/Support/raw_ostream.h"
Ahmed Charlesdfca6f92014-03-09 11:36:40 +000027#include <memory>
Rafael Espindola8a8e5542014-06-12 17:19:42 +000028#include <system_error>
Douglas Gregor52da28b2011-09-23 23:43:36 +000029
Daniel Dunbar02bd2d72009-11-14 10:42:46 +000030using namespace clang;
31
Daniel Dunbar88357802009-11-14 10:42:57 +000032//===----------------------------------------------------------------------===//
Daniel Dunbar1c201fb2010-03-19 19:44:04 +000033// Custom Actions
34//===----------------------------------------------------------------------===//
35
David Blaikie62a56f32014-07-17 22:34:12 +000036ASTConsumer *InitOnlyAction::CreateASTConsumer(CompilerInstance &CI,
37 StringRef InFile) {
38 return new ASTConsumer();
Daniel Dunbar1c201fb2010-03-19 19:44:04 +000039}
40
41void InitOnlyAction::ExecuteAction() {
42}
43
44//===----------------------------------------------------------------------===//
Daniel Dunbar88357802009-11-14 10:42:57 +000045// AST Consumer Actions
46//===----------------------------------------------------------------------===//
47
David Blaikie62a56f32014-07-17 22:34:12 +000048ASTConsumer *ASTPrintAction::CreateASTConsumer(CompilerInstance &CI,
49 StringRef InFile) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +000050 if (raw_ostream *OS = CI.createDefaultOutputFile(false, InFile))
Alexander Kornienko3db68ee2012-07-26 16:01:23 +000051 return CreateASTPrinter(OS, CI.getFrontendOpts().ASTDumpFilter);
Craig Topper49a27902014-05-22 04:46:25 +000052 return nullptr;
Daniel Dunbar02bd2d72009-11-14 10:42:46 +000053}
54
David Blaikie62a56f32014-07-17 22:34:12 +000055ASTConsumer *ASTDumpAction::CreateASTConsumer(CompilerInstance &CI,
56 StringRef InFile) {
Richard Smith6ea05822013-06-24 01:45:33 +000057 return CreateASTDumper(CI.getFrontendOpts().ASTDumpFilter,
58 CI.getFrontendOpts().ASTDumpLookups);
Daniel Dunbar02bd2d72009-11-14 10:42:46 +000059}
60
David Blaikie62a56f32014-07-17 22:34:12 +000061ASTConsumer *ASTDeclListAction::CreateASTConsumer(CompilerInstance &CI,
62 StringRef InFile) {
Alexander Kornienko4de03592012-07-31 09:37:40 +000063 return CreateASTDeclNodeLister();
64}
65
David Blaikie62a56f32014-07-17 22:34:12 +000066ASTConsumer *ASTViewAction::CreateASTConsumer(CompilerInstance &CI,
67 StringRef InFile) {
Daniel Dunbar02bd2d72009-11-14 10:42:46 +000068 return CreateASTViewer();
69}
70
David Blaikie62a56f32014-07-17 22:34:12 +000071ASTConsumer *DeclContextPrintAction::CreateASTConsumer(CompilerInstance &CI,
72 StringRef InFile) {
Daniel Dunbar02bd2d72009-11-14 10:42:46 +000073 return CreateDeclContextPrinter();
74}
75
David Blaikie62a56f32014-07-17 22:34:12 +000076ASTConsumer *GeneratePCHAction::CreateASTConsumer(CompilerInstance &CI,
77 StringRef InFile) {
Douglas Gregor48c8cd32010-08-03 08:14:03 +000078 std::string Sysroot;
Argyrios Kyrtzidis10b23682011-02-15 17:54:22 +000079 std::string OutputFile;
Craig Topper49a27902014-05-22 04:46:25 +000080 raw_ostream *OS = nullptr;
Douglas Gregor36db4f92011-08-25 22:35:51 +000081 if (ComputeASTConsumerArguments(CI, InFile, Sysroot, OutputFile, OS))
Craig Topper49a27902014-05-22 04:46:25 +000082 return nullptr;
Douglas Gregor48c8cd32010-08-03 08:14:03 +000083
Douglas Gregorc567ba22011-07-22 16:35:34 +000084 if (!CI.getFrontendOpts().RelocatablePCH)
85 Sysroot.clear();
David Blaikie62a56f32014-07-17 22:34:12 +000086 return new PCHGenerator(CI.getPreprocessor(), OutputFile, nullptr, Sysroot,
87 OS);
Douglas Gregor48c8cd32010-08-03 08:14:03 +000088}
89
90bool GeneratePCHAction::ComputeASTConsumerArguments(CompilerInstance &CI,
Chris Lattner0e62c1c2011-07-23 10:55:15 +000091 StringRef InFile,
Douglas Gregor48c8cd32010-08-03 08:14:03 +000092 std::string &Sysroot,
Argyrios Kyrtzidis10b23682011-02-15 17:54:22 +000093 std::string &OutputFile,
Douglas Gregor36db4f92011-08-25 22:35:51 +000094 raw_ostream *&OS) {
Douglas Gregor48c8cd32010-08-03 08:14:03 +000095 Sysroot = CI.getHeaderSearchOpts().Sysroot;
96 if (CI.getFrontendOpts().RelocatablePCH && Sysroot.empty()) {
Sebastian Redlea68af42010-08-17 17:55:38 +000097 CI.getDiagnostics().Report(diag::err_relocatable_without_isysroot);
Douglas Gregor48c8cd32010-08-03 08:14:03 +000098 return true;
Daniel Dunbar02bd2d72009-11-14 10:42:46 +000099 }
100
Daniel Dunbara2867c72011-01-31 22:00:44 +0000101 // We use createOutputFile here because this is exposed via libclang, and we
102 // must disable the RemoveFileOnSignal behavior.
Argyrios Kyrtzidis08a2bfd2011-07-28 00:45:10 +0000103 // We use a temporary to avoid race conditions.
Daniel Dunbara2867c72011-01-31 22:00:44 +0000104 OS = CI.createOutputFile(CI.getFrontendOpts().OutputFile, /*Binary=*/true,
Argyrios Kyrtzidis08a2bfd2011-07-28 00:45:10 +0000105 /*RemoveFileOnSignal=*/false, InFile,
106 /*Extension=*/"", /*useTemporary=*/true);
Daniel Dunbar75546992009-12-03 09:13:30 +0000107 if (!OS)
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000108 return true;
Daniel Dunbar75546992009-12-03 09:13:30 +0000109
Argyrios Kyrtzidis10b23682011-02-15 17:54:22 +0000110 OutputFile = CI.getFrontendOpts().OutputFile;
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000111 return false;
Daniel Dunbar02bd2d72009-11-14 10:42:46 +0000112}
113
David Blaikie62a56f32014-07-17 22:34:12 +0000114ASTConsumer *GenerateModuleAction::CreateASTConsumer(CompilerInstance &CI,
115 StringRef InFile) {
Douglas Gregor2b20cb82011-11-16 00:09:06 +0000116 std::string Sysroot;
117 std::string OutputFile;
Craig Topper49a27902014-05-22 04:46:25 +0000118 raw_ostream *OS = nullptr;
Douglas Gregor2b20cb82011-11-16 00:09:06 +0000119 if (ComputeASTConsumerArguments(CI, InFile, Sysroot, OutputFile, OS))
Craig Topper49a27902014-05-22 04:46:25 +0000120 return nullptr;
121
David Blaikie62a56f32014-07-17 22:34:12 +0000122 return new PCHGenerator(CI.getPreprocessor(), OutputFile, Module,
123 Sysroot, OS);
Douglas Gregor2b20cb82011-11-16 00:09:06 +0000124}
125
Argyrios Kyrtzidis130190f2012-10-10 02:12:39 +0000126static SmallVectorImpl<char> &
127operator+=(SmallVectorImpl<char> &Includes, StringRef RHS) {
128 Includes.append(RHS.begin(), RHS.end());
129 return Includes;
130}
131
Rafael Espindolac0809172014-06-12 14:02:15 +0000132static std::error_code addHeaderInclude(StringRef HeaderName,
133 SmallVectorImpl<char> &Includes,
134 const LangOptions &LangOpts,
135 bool IsExternC) {
Richard Smith9bca2982014-03-08 00:03:56 +0000136 if (IsExternC && LangOpts.CPlusPlus)
Richard Smith77944862014-03-02 05:58:18 +0000137 Includes += "extern \"C\" {\n";
Argyrios Kyrtzidis130190f2012-10-10 02:12:39 +0000138 if (LangOpts.ObjC1)
139 Includes += "#import \"";
140 else
141 Includes += "#include \"";
Richard Smith723928c2014-03-11 02:02:47 +0000142 // Use an absolute path for the include; there's no reason to think that
143 // a relative path will work (. might not be on our include path) or that
144 // it will find the same file.
145 if (llvm::sys::path::is_absolute(HeaderName)) {
146 Includes += HeaderName;
147 } else {
148 SmallString<256> Header = HeaderName;
Rafael Espindolac0809172014-06-12 14:02:15 +0000149 if (std::error_code Err = llvm::sys::fs::make_absolute(Header))
Richard Smith723928c2014-03-11 02:02:47 +0000150 return Err;
151 Includes += Header;
152 }
Argyrios Kyrtzidis130190f2012-10-10 02:12:39 +0000153 Includes += "\"\n";
Richard Smith9bca2982014-03-08 00:03:56 +0000154 if (IsExternC && LangOpts.CPlusPlus)
Richard Smith77944862014-03-02 05:58:18 +0000155 Includes += "}\n";
Rafael Espindolac0809172014-06-12 14:02:15 +0000156 return std::error_code();
Argyrios Kyrtzidis130190f2012-10-10 02:12:39 +0000157}
158
Rafael Espindolac0809172014-06-12 14:02:15 +0000159static std::error_code addHeaderInclude(const FileEntry *Header,
160 SmallVectorImpl<char> &Includes,
161 const LangOptions &LangOpts,
162 bool IsExternC) {
Richard Smith723928c2014-03-11 02:02:47 +0000163 return addHeaderInclude(Header->getName(), Includes, LangOpts, IsExternC);
Argyrios Kyrtzidis130190f2012-10-10 02:12:39 +0000164}
165
Douglas Gregor4332b322011-11-16 17:04:00 +0000166/// \brief Collect the set of header includes needed to construct the given
Argyrios Kyrtzidisc597c8c2012-10-05 00:22:33 +0000167/// module and update the TopHeaders file set of the module.
Douglas Gregor4332b322011-11-16 17:04:00 +0000168///
169/// \param Module The module we're collecting includes from.
Douglas Gregore5626c42011-12-06 17:15:11 +0000170///
James Dennettc423c532012-06-15 21:48:19 +0000171/// \param Includes Will be augmented with the set of \#includes or \#imports
Douglas Gregore5626c42011-12-06 17:15:11 +0000172/// needed to load all of the named headers.
Rafael Espindolac0809172014-06-12 14:02:15 +0000173static std::error_code
Richard Smith723928c2014-03-11 02:02:47 +0000174collectModuleHeaderIncludes(const LangOptions &LangOpts, FileManager &FileMgr,
175 ModuleMap &ModMap, clang::Module *Module,
176 SmallVectorImpl<char> &Includes) {
Douglas Gregor1fb5c3a2011-12-31 04:05:44 +0000177 // Don't collect any headers for unavailable modules.
178 if (!Module->isAvailable())
Rafael Espindolac0809172014-06-12 14:02:15 +0000179 return std::error_code();
Douglas Gregor1fb5c3a2011-12-31 04:05:44 +0000180
Douglas Gregore5626c42011-12-06 17:15:11 +0000181 // Add includes for each of these headers.
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000182 for (unsigned I = 0, N = Module->NormalHeaders.size(); I != N; ++I) {
183 const FileEntry *Header = Module->NormalHeaders[I];
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +0000184 Module->addTopHeader(Header);
Rafael Espindolac0809172014-06-12 14:02:15 +0000185 if (std::error_code Err =
Richard Smith723928c2014-03-11 02:02:47 +0000186 addHeaderInclude(Header, Includes, LangOpts, Module->IsExternC))
187 return Err;
Douglas Gregor3ec66632012-02-02 18:42:48 +0000188 }
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000189 // Note that Module->PrivateHeaders will not be a TopHeader.
Douglas Gregore5626c42011-12-06 17:15:11 +0000190
Douglas Gregor73141fa2011-12-08 17:39:04 +0000191 if (const FileEntry *UmbrellaHeader = Module->getUmbrellaHeader()) {
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +0000192 Module->addTopHeader(UmbrellaHeader);
Douglas Gregor3ec66632012-02-02 18:42:48 +0000193 if (Module->Parent) {
194 // Include the umbrella header for submodules.
Rafael Espindolac0809172014-06-12 14:02:15 +0000195 if (std::error_code Err = addHeaderInclude(UmbrellaHeader, Includes,
196 LangOpts, Module->IsExternC))
Richard Smith723928c2014-03-11 02:02:47 +0000197 return Err;
Douglas Gregor3ec66632012-02-02 18:42:48 +0000198 }
Douglas Gregor524e33e2011-12-08 19:11:24 +0000199 } else if (const DirectoryEntry *UmbrellaDir = Module->getUmbrellaDir()) {
Douglas Gregord2a8fe12012-01-05 00:04:05 +0000200 // Add all of the headers we find in this subdirectory.
Rafael Espindolac0809172014-06-12 14:02:15 +0000201 std::error_code EC;
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000202 SmallString<128> DirNative;
Douglas Gregor524e33e2011-12-08 19:11:24 +0000203 llvm::sys::path::native(UmbrellaDir->getName(), DirNative);
Douglas Gregorc1aaf8c2011-12-12 19:13:53 +0000204 for (llvm::sys::fs::recursive_directory_iterator Dir(DirNative.str(), EC),
205 DirEnd;
Douglas Gregor524e33e2011-12-08 19:11:24 +0000206 Dir != DirEnd && !EC; Dir.increment(EC)) {
207 // Check whether this entry has an extension typically associated with
208 // headers.
209 if (!llvm::StringSwitch<bool>(llvm::sys::path::extension(Dir->path()))
210 .Cases(".h", ".H", ".hh", ".hpp", true)
211 .Default(false))
212 continue;
213
Douglas Gregord2a8fe12012-01-05 00:04:05 +0000214 // If this header is marked 'unavailable' in this module, don't include
215 // it.
Argyrios Kyrtzidisc597c8c2012-10-05 00:22:33 +0000216 if (const FileEntry *Header = FileMgr.getFile(Dir->path())) {
Richard Smith50996ce2014-04-08 13:13:04 +0000217 if (ModMap.isHeaderUnavailableInModule(Header, Module))
Douglas Gregord2a8fe12012-01-05 00:04:05 +0000218 continue;
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +0000219 Module->addTopHeader(Header);
Argyrios Kyrtzidisc597c8c2012-10-05 00:22:33 +0000220 }
Douglas Gregord2a8fe12012-01-05 00:04:05 +0000221
Richard Smith723928c2014-03-11 02:02:47 +0000222 // Include this header as part of the umbrella directory.
Rafael Espindolac0809172014-06-12 14:02:15 +0000223 if (std::error_code Err = addHeaderInclude(Dir->path(), Includes,
224 LangOpts, Module->IsExternC))
Richard Smith723928c2014-03-11 02:02:47 +0000225 return Err;
Douglas Gregor524e33e2011-12-08 19:11:24 +0000226 }
Richard Smith723928c2014-03-11 02:02:47 +0000227
228 if (EC)
229 return EC;
Douglas Gregor4332b322011-11-16 17:04:00 +0000230 }
231
232 // Recurse into submodules.
Douglas Gregoreb90e832012-01-04 23:32:19 +0000233 for (clang::Module::submodule_iterator Sub = Module->submodule_begin(),
234 SubEnd = Module->submodule_end();
Douglas Gregore5626c42011-12-06 17:15:11 +0000235 Sub != SubEnd; ++Sub)
Rafael Espindolac0809172014-06-12 14:02:15 +0000236 if (std::error_code Err = collectModuleHeaderIncludes(
Richard Smith723928c2014-03-11 02:02:47 +0000237 LangOpts, FileMgr, ModMap, *Sub, Includes))
238 return Err;
239
Rafael Espindolac0809172014-06-12 14:02:15 +0000240 return std::error_code();
Douglas Gregor4332b322011-11-16 17:04:00 +0000241}
242
Douglas Gregor2b20cb82011-11-16 00:09:06 +0000243bool GenerateModuleAction::BeginSourceFileAction(CompilerInstance &CI,
244 StringRef Filename) {
245 // Find the module map file.
246 const FileEntry *ModuleMap = CI.getFileManager().getFile(Filename);
247 if (!ModuleMap) {
248 CI.getDiagnostics().Report(diag::err_module_map_not_found)
249 << Filename;
250 return false;
251 }
252
253 // Parse the module map file.
254 HeaderSearch &HS = CI.getPreprocessor().getHeaderSearchInfo();
Douglas Gregor963c5532013-06-21 16:28:10 +0000255 if (HS.loadModuleMapFile(ModuleMap, IsSystem))
Douglas Gregor2b20cb82011-11-16 00:09:06 +0000256 return false;
257
258 if (CI.getLangOpts().CurrentModule.empty()) {
259 CI.getDiagnostics().Report(diag::err_missing_module_name);
260
261 // FIXME: Eventually, we could consider asking whether there was just
262 // a single module described in the module map, and use that as a
263 // default. Then it would be fairly trivial to just "compile" a module
264 // map with a single module (the common case).
265 return false;
266 }
Richard Smith7bea1d42014-03-05 20:55:36 +0000267
268 // If we're being run from the command-line, the module build stack will not
269 // have been filled in yet, so complete it now in order to allow us to detect
270 // module cycles.
271 SourceManager &SourceMgr = CI.getSourceManager();
272 if (SourceMgr.getModuleBuildStack().empty())
273 SourceMgr.pushModuleBuildStack(CI.getLangOpts().CurrentModule,
274 FullSourceLoc(SourceLocation(), SourceMgr));
275
Douglas Gregor2b20cb82011-11-16 00:09:06 +0000276 // Dig out the module definition.
Douglas Gregor279a6c32012-01-29 17:08:11 +0000277 Module = HS.lookupModule(CI.getLangOpts().CurrentModule,
278 /*AllowSearch=*/false);
Douglas Gregor2b20cb82011-11-16 00:09:06 +0000279 if (!Module) {
280 CI.getDiagnostics().Report(diag::err_missing_module)
281 << CI.getLangOpts().CurrentModule << Filename;
282
283 return false;
284 }
Douglas Gregor1fb5c3a2011-12-31 04:05:44 +0000285
286 // Check whether we can build this module at all.
Richard Smitha3feee22013-10-28 22:18:19 +0000287 clang::Module::Requirement Requirement;
Daniel Jasper0761a8a2013-12-17 10:31:37 +0000288 clang::Module::HeaderDirective MissingHeader;
289 if (!Module->isAvailable(CI.getLangOpts(), CI.getTarget(), Requirement,
290 MissingHeader)) {
291 if (MissingHeader.FileNameLoc.isValid()) {
Ben Langmuirec8c9752014-04-18 22:07:31 +0000292 CI.getDiagnostics().Report(MissingHeader.FileNameLoc,
293 diag::err_module_header_missing)
Daniel Jasper0761a8a2013-12-17 10:31:37 +0000294 << MissingHeader.IsUmbrella << MissingHeader.FileName;
295 } else {
296 CI.getDiagnostics().Report(diag::err_module_unavailable)
297 << Module->getFullModuleName()
298 << Requirement.second << Requirement.first;
299 }
Douglas Gregor1fb5c3a2011-12-31 04:05:44 +0000300
301 return false;
302 }
303
Ben Langmuir9d6448b2014-08-09 00:57:23 +0000304 if (ModuleMapForUniquing && ModuleMapForUniquing != ModuleMap) {
305 Module->IsInferred = true;
306 HS.getModuleMap().setInferredModuleAllowedBy(Module, ModuleMapForUniquing);
307 } else {
Ben Langmuirbeee15e2014-04-14 18:00:01 +0000308 ModuleMapForUniquing = ModuleMap;
Ben Langmuir9d6448b2014-08-09 00:57:23 +0000309 }
Ben Langmuirbeee15e2014-04-14 18:00:01 +0000310
Argyrios Kyrtzidis130190f2012-10-10 02:12:39 +0000311 FileManager &FileMgr = CI.getFileManager();
312
Douglas Gregor4332b322011-11-16 17:04:00 +0000313 // Collect the set of #includes we need to build the module.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000314 SmallString<256> HeaderContents;
Rafael Espindola8e650d72014-06-12 20:37:59 +0000315 std::error_code Err = std::error_code();
Argyrios Kyrtzidis130190f2012-10-10 02:12:39 +0000316 if (const FileEntry *UmbrellaHeader = Module->getUmbrellaHeader())
Richard Smith723928c2014-03-11 02:02:47 +0000317 Err = addHeaderInclude(UmbrellaHeader, HeaderContents, CI.getLangOpts(),
318 Module->IsExternC);
319 if (!Err)
320 Err = collectModuleHeaderIncludes(
321 CI.getLangOpts(), FileMgr,
322 CI.getPreprocessor().getHeaderSearchInfo().getModuleMap(), Module,
323 HeaderContents);
324
325 if (Err) {
326 CI.getDiagnostics().Report(diag::err_module_cannot_create_includes)
327 << Module->getFullModuleName() << Err.message();
328 return false;
329 }
Douglas Gregor4332b322011-11-16 17:04:00 +0000330
Argyrios Kyrtzidis52595242012-11-15 18:57:27 +0000331 llvm::MemoryBuffer *InputBuffer =
332 llvm::MemoryBuffer::getMemBufferCopy(HeaderContents,
333 Module::getModuleInputBufferName());
Alp Tokerf6a24ce2013-12-05 16:25:25 +0000334 // Ownership of InputBuffer will be transferred to the SourceManager.
Argyrios Kyrtzidis52595242012-11-15 18:57:27 +0000335 setCurrentInput(FrontendInputFile(InputBuffer, getCurrentFileKind(),
Douglas Gregora686e1b2012-01-27 19:52:33 +0000336 Module->IsSystem));
Douglas Gregor2b20cb82011-11-16 00:09:06 +0000337 return true;
338}
339
340bool GenerateModuleAction::ComputeASTConsumerArguments(CompilerInstance &CI,
341 StringRef InFile,
342 std::string &Sysroot,
343 std::string &OutputFile,
344 raw_ostream *&OS) {
345 // If no output file was provided, figure out where this module would go
346 // in the module cache.
347 if (CI.getFrontendOpts().OutputFile.empty()) {
348 HeaderSearch &HS = CI.getPreprocessor().getHeaderSearchInfo();
Ben Langmuirbeee15e2014-04-14 18:00:01 +0000349 CI.getFrontendOpts().OutputFile =
350 HS.getModuleFileName(CI.getLangOpts().CurrentModule,
351 ModuleMapForUniquing->getName());
Douglas Gregor2b20cb82011-11-16 00:09:06 +0000352 }
353
354 // We use createOutputFile here because this is exposed via libclang, and we
355 // must disable the RemoveFileOnSignal behavior.
356 // We use a temporary to avoid race conditions.
357 OS = CI.createOutputFile(CI.getFrontendOpts().OutputFile, /*Binary=*/true,
358 /*RemoveFileOnSignal=*/false, InFile,
Daniel Dunbarb9c62c02012-03-03 00:36:02 +0000359 /*Extension=*/"", /*useTemporary=*/true,
360 /*CreateMissingDirectories=*/true);
Douglas Gregor2b20cb82011-11-16 00:09:06 +0000361 if (!OS)
362 return true;
363
364 OutputFile = CI.getFrontendOpts().OutputFile;
365 return false;
366}
367
David Blaikie62a56f32014-07-17 22:34:12 +0000368ASTConsumer *SyntaxOnlyAction::CreateASTConsumer(CompilerInstance &CI,
369 StringRef InFile) {
370 return new ASTConsumer();
Daniel Dunbar02bd2d72009-11-14 10:42:46 +0000371}
372
David Blaikie62a56f32014-07-17 22:34:12 +0000373ASTConsumer *DumpModuleInfoAction::CreateASTConsumer(CompilerInstance &CI,
374 StringRef InFile) {
375 return new ASTConsumer();
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000376}
377
David Blaikie62a56f32014-07-17 22:34:12 +0000378ASTConsumer *VerifyPCHAction::CreateASTConsumer(CompilerInstance &CI,
379 StringRef InFile) {
380 return new ASTConsumer();
Ben Langmuir2cb4a782014-02-05 22:21:15 +0000381}
382
383void VerifyPCHAction::ExecuteAction() {
Ben Langmuir3d4417c2014-02-07 17:31:11 +0000384 CompilerInstance &CI = getCompilerInstance();
385 bool Preamble = CI.getPreprocessorOpts().PrecompiledPreambleBytes.first != 0;
386 const std::string &Sysroot = CI.getHeaderSearchOpts().Sysroot;
Ahmed Charlesb8984322014-03-07 20:03:18 +0000387 std::unique_ptr<ASTReader> Reader(
388 new ASTReader(CI.getPreprocessor(), CI.getASTContext(),
389 Sysroot.empty() ? "" : Sysroot.c_str(),
390 /*DisableValidation*/ false,
391 /*AllowPCHWithCompilerErrors*/ false,
392 /*AllowConfigurationMismatch*/ true,
393 /*ValidateSystemInputs*/ true));
Ben Langmuir3d4417c2014-02-07 17:31:11 +0000394
395 Reader->ReadAST(getCurrentFile(),
396 Preamble ? serialization::MK_Preamble
397 : serialization::MK_PCH,
398 SourceLocation(),
399 ASTReader::ARR_ConfigurationMismatch);
Ben Langmuir2cb4a782014-02-05 22:21:15 +0000400}
401
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000402namespace {
403 /// \brief AST reader listener that dumps module information for a module
404 /// file.
405 class DumpModuleInfoListener : public ASTReaderListener {
406 llvm::raw_ostream &Out;
407
408 public:
409 DumpModuleInfoListener(llvm::raw_ostream &Out) : Out(Out) { }
410
411#define DUMP_BOOLEAN(Value, Text) \
412 Out.indent(4) << Text << ": " << (Value? "Yes" : "No") << "\n"
413
Craig Topperafa7cb32014-03-13 06:07:04 +0000414 bool ReadFullVersionInformation(StringRef FullVersion) override {
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000415 Out.indent(2)
416 << "Generated by "
417 << (FullVersion == getClangFullRepositoryVersion()? "this"
418 : "a different")
419 << " Clang: " << FullVersion << "\n";
420 return ASTReaderListener::ReadFullVersionInformation(FullVersion);
421 }
422
Ben Langmuir4f5212a2014-04-14 22:12:44 +0000423 void ReadModuleName(StringRef ModuleName) override {
424 Out.indent(2) << "Module name: " << ModuleName << "\n";
425 }
426 void ReadModuleMapFile(StringRef ModuleMapPath) override {
427 Out.indent(2) << "Module map file: " << ModuleMapPath << "\n";
428 }
429
Craig Topperafa7cb32014-03-13 06:07:04 +0000430 bool ReadLanguageOptions(const LangOptions &LangOpts,
431 bool Complain) override {
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000432 Out.indent(2) << "Language options:\n";
433#define LANGOPT(Name, Bits, Default, Description) \
434 DUMP_BOOLEAN(LangOpts.Name, Description);
435#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
436 Out.indent(4) << Description << ": " \
437 << static_cast<unsigned>(LangOpts.get##Name()) << "\n";
438#define VALUE_LANGOPT(Name, Bits, Default, Description) \
439 Out.indent(4) << Description << ": " << LangOpts.Name << "\n";
440#define BENIGN_LANGOPT(Name, Bits, Default, Description)
441#define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
442#include "clang/Basic/LangOptions.def"
443 return false;
444 }
445
Craig Topperafa7cb32014-03-13 06:07:04 +0000446 bool ReadTargetOptions(const TargetOptions &TargetOpts,
447 bool Complain) override {
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000448 Out.indent(2) << "Target options:\n";
449 Out.indent(4) << " Triple: " << TargetOpts.Triple << "\n";
450 Out.indent(4) << " CPU: " << TargetOpts.CPU << "\n";
451 Out.indent(4) << " ABI: " << TargetOpts.ABI << "\n";
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000452
453 if (!TargetOpts.FeaturesAsWritten.empty()) {
454 Out.indent(4) << "Target features:\n";
455 for (unsigned I = 0, N = TargetOpts.FeaturesAsWritten.size();
456 I != N; ++I) {
457 Out.indent(6) << TargetOpts.FeaturesAsWritten[I] << "\n";
458 }
459 }
460
461 return false;
462 }
463
Ben Langmuirb92de022014-04-29 16:25:26 +0000464 virtual bool
465 ReadDiagnosticOptions(IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts,
466 bool Complain) override {
467 Out.indent(2) << "Diagnostic options:\n";
468#define DIAGOPT(Name, Bits, Default) DUMP_BOOLEAN(DiagOpts->Name, #Name);
469#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
470 Out.indent(4) << #Name << ": " << DiagOpts->get##Name() << "\n";
471#define VALUE_DIAGOPT(Name, Bits, Default) \
472 Out.indent(4) << #Name << ": " << DiagOpts->Name << "\n";
473#include "clang/Basic/DiagnosticOptions.def"
474
Richard Smith3be1cb22014-08-07 00:24:21 +0000475 Out.indent(4) << "Diagnostic flags:\n";
476 for (const std::string &Warning : DiagOpts->Warnings)
Ben Langmuirb92de022014-04-29 16:25:26 +0000477 Out.indent(6) << "-W" << Warning << "\n";
Richard Smith3be1cb22014-08-07 00:24:21 +0000478 for (const std::string &Remark : DiagOpts->Remarks)
479 Out.indent(6) << "-R" << Remark << "\n";
Ben Langmuirb92de022014-04-29 16:25:26 +0000480
481 return false;
482 }
483
Craig Topperafa7cb32014-03-13 06:07:04 +0000484 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
485 bool Complain) override {
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000486 Out.indent(2) << "Header search options:\n";
487 Out.indent(4) << "System root [-isysroot=]: '" << HSOpts.Sysroot << "'\n";
488 DUMP_BOOLEAN(HSOpts.UseBuiltinIncludes,
489 "Use builtin include directories [-nobuiltininc]");
490 DUMP_BOOLEAN(HSOpts.UseStandardSystemIncludes,
491 "Use standard system include directories [-nostdinc]");
492 DUMP_BOOLEAN(HSOpts.UseStandardCXXIncludes,
493 "Use standard C++ include directories [-nostdinc++]");
494 DUMP_BOOLEAN(HSOpts.UseLibcxx,
495 "Use libc++ (rather than libstdc++) [-stdlib=]");
496 return false;
497 }
498
Craig Topperafa7cb32014-03-13 06:07:04 +0000499 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
500 bool Complain,
501 std::string &SuggestedPredefines) override {
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000502 Out.indent(2) << "Preprocessor options:\n";
503 DUMP_BOOLEAN(PPOpts.UsePredefines,
504 "Uses compiler/target-specific predefines [-undef]");
505 DUMP_BOOLEAN(PPOpts.DetailedRecord,
506 "Uses detailed preprocessing record (for indexing)");
507
508 if (!PPOpts.Macros.empty()) {
509 Out.indent(4) << "Predefined macros:\n";
510 }
511
512 for (std::vector<std::pair<std::string, bool/*isUndef*/> >::const_iterator
513 I = PPOpts.Macros.begin(), IEnd = PPOpts.Macros.end();
514 I != IEnd; ++I) {
515 Out.indent(6);
516 if (I->second)
517 Out << "-U";
518 else
519 Out << "-D";
520 Out << I->first << "\n";
521 }
522 return false;
523 }
524#undef DUMP_BOOLEAN
525 };
526}
527
528void DumpModuleInfoAction::ExecuteAction() {
529 // Set up the output file.
Ahmed Charlesb8984322014-03-07 20:03:18 +0000530 std::unique_ptr<llvm::raw_fd_ostream> OutFile;
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000531 StringRef OutputFileName = getCompilerInstance().getFrontendOpts().OutputFile;
532 if (!OutputFileName.empty() && OutputFileName != "-") {
533 std::string ErrorInfo;
534 OutFile.reset(new llvm::raw_fd_ostream(OutputFileName.str().c_str(),
Rafael Espindola4fbd3732014-02-24 18:20:21 +0000535 ErrorInfo, llvm::sys::fs::F_Text));
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000536 }
537 llvm::raw_ostream &Out = OutFile.get()? *OutFile.get() : llvm::outs();
538
539 Out << "Information for module file '" << getCurrentFile() << "':\n";
540 DumpModuleInfoListener Listener(Out);
541 ASTReader::readASTFileControlBlock(getCurrentFile(),
542 getCompilerInstance().getFileManager(),
543 Listener);
544}
545
Daniel Dunbar88357802009-11-14 10:42:57 +0000546//===----------------------------------------------------------------------===//
547// Preprocessor Actions
548//===----------------------------------------------------------------------===//
549
550void DumpRawTokensAction::ExecuteAction() {
551 Preprocessor &PP = getCompilerInstance().getPreprocessor();
552 SourceManager &SM = PP.getSourceManager();
553
554 // Start lexing the specified input file.
Chris Lattner710bb872009-11-30 04:18:44 +0000555 const llvm::MemoryBuffer *FromFile = SM.getBuffer(SM.getMainFileID());
David Blaikiebbafb8a2012-03-11 07:00:24 +0000556 Lexer RawLex(SM.getMainFileID(), FromFile, SM, PP.getLangOpts());
Daniel Dunbar88357802009-11-14 10:42:57 +0000557 RawLex.SetKeepWhitespaceMode(true);
558
559 Token RawTok;
560 RawLex.LexFromRawLexer(RawTok);
561 while (RawTok.isNot(tok::eof)) {
562 PP.DumpToken(RawTok, true);
Daniel Dunbar75024622009-11-25 10:27:48 +0000563 llvm::errs() << "\n";
Daniel Dunbar88357802009-11-14 10:42:57 +0000564 RawLex.LexFromRawLexer(RawTok);
565 }
566}
567
568void DumpTokensAction::ExecuteAction() {
569 Preprocessor &PP = getCompilerInstance().getPreprocessor();
570 // Start preprocessing the specified input file.
571 Token Tok;
Chris Lattnerfb24a3a2010-04-20 20:35:58 +0000572 PP.EnterMainSourceFile();
Daniel Dunbar88357802009-11-14 10:42:57 +0000573 do {
574 PP.Lex(Tok);
575 PP.DumpToken(Tok, true);
Daniel Dunbar75024622009-11-25 10:27:48 +0000576 llvm::errs() << "\n";
Daniel Dunbar88357802009-11-14 10:42:57 +0000577 } while (Tok.isNot(tok::eof));
578}
579
580void GeneratePTHAction::ExecuteAction() {
581 CompilerInstance &CI = getCompilerInstance();
582 if (CI.getFrontendOpts().OutputFile.empty() ||
583 CI.getFrontendOpts().OutputFile == "-") {
584 // FIXME: Don't fail this way.
585 // FIXME: Verify that we can actually seek in the given file.
Chris Lattner4b73cfa2010-04-07 22:58:06 +0000586 llvm::report_fatal_error("PTH requires a seekable file for output!");
Daniel Dunbar88357802009-11-14 10:42:57 +0000587 }
588 llvm::raw_fd_ostream *OS =
589 CI.createDefaultOutputFile(true, getCurrentFile());
Daniel Dunbar75546992009-12-03 09:13:30 +0000590 if (!OS) return;
591
Daniel Dunbar88357802009-11-14 10:42:57 +0000592 CacheTokens(CI.getPreprocessor(), OS);
593}
594
Daniel Dunbar88357802009-11-14 10:42:57 +0000595void PreprocessOnlyAction::ExecuteAction() {
596 Preprocessor &PP = getCompilerInstance().getPreprocessor();
597
Daniel Dunbard839e772010-06-11 20:10:12 +0000598 // Ignore unknown pragmas.
Lubos Lunak576a0412014-05-01 12:54:03 +0000599 PP.IgnorePragmas();
Daniel Dunbard839e772010-06-11 20:10:12 +0000600
Daniel Dunbar88357802009-11-14 10:42:57 +0000601 Token Tok;
602 // Start parsing the specified input file.
Chris Lattnerfb24a3a2010-04-20 20:35:58 +0000603 PP.EnterMainSourceFile();
Daniel Dunbar88357802009-11-14 10:42:57 +0000604 do {
605 PP.Lex(Tok);
606 } while (Tok.isNot(tok::eof));
607}
608
Daniel Dunbar88357802009-11-14 10:42:57 +0000609void PrintPreprocessedAction::ExecuteAction() {
610 CompilerInstance &CI = getCompilerInstance();
Douglas Gregor52da28b2011-09-23 23:43:36 +0000611 // Output file may need to be set to 'Binary', to avoid converting Unix style
Steve Naroff3d38a682010-01-05 17:33:23 +0000612 // line feeds (<LF>) to Microsoft style line feeds (<CR><LF>).
Douglas Gregor52da28b2011-09-23 23:43:36 +0000613 //
614 // Look to see what type of line endings the file uses. If there's a
615 // CRLF, then we won't open the file up in binary mode. If there is
616 // just an LF or CR, then we will open the file up in binary mode.
617 // In this fashion, the output format should match the input format, unless
618 // the input format has inconsistent line endings.
619 //
620 // This should be a relatively fast operation since most files won't have
621 // all of their source code on a single line. However, that is still a
622 // concern, so if we scan for too long, we'll just assume the file should
623 // be opened in binary mode.
624 bool BinaryMode = true;
625 bool InvalidFile = false;
626 const SourceManager& SM = CI.getSourceManager();
627 const llvm::MemoryBuffer *Buffer = SM.getBuffer(SM.getMainFileID(),
628 &InvalidFile);
629 if (!InvalidFile) {
630 const char *cur = Buffer->getBufferStart();
631 const char *end = Buffer->getBufferEnd();
632 const char *next = (cur != end) ? cur + 1 : end;
633
634 // Limit ourselves to only scanning 256 characters into the source
635 // file. This is mostly a sanity check in case the file has no
636 // newlines whatsoever.
637 if (end - cur > 256) end = cur + 256;
638
639 while (next < end) {
640 if (*cur == 0x0D) { // CR
641 if (*next == 0x0A) // CRLF
642 BinaryMode = false;
643
644 break;
645 } else if (*cur == 0x0A) // LF
646 break;
647
648 ++cur, ++next;
649 }
650 }
651
652 raw_ostream *OS = CI.createDefaultOutputFile(BinaryMode, getCurrentFile());
Daniel Dunbar75546992009-12-03 09:13:30 +0000653 if (!OS) return;
654
Daniel Dunbar88357802009-11-14 10:42:57 +0000655 DoPrintPreprocessedInput(CI.getPreprocessor(), OS,
656 CI.getPreprocessorOutputOpts());
657}
Douglas Gregoraf82e352010-07-20 20:18:03 +0000658
659void PrintPreambleAction::ExecuteAction() {
660 switch (getCurrentFileKind()) {
661 case IK_C:
662 case IK_CXX:
663 case IK_ObjC:
664 case IK_ObjCXX:
665 case IK_OpenCL:
Peter Collingbourne62089b82010-12-01 03:15:20 +0000666 case IK_CUDA:
Douglas Gregoraf82e352010-07-20 20:18:03 +0000667 break;
668
669 case IK_None:
670 case IK_Asm:
671 case IK_PreprocessedC:
672 case IK_PreprocessedCXX:
673 case IK_PreprocessedObjC:
674 case IK_PreprocessedObjCXX:
675 case IK_AST:
676 case IK_LLVM_IR:
677 // We can't do anything with these.
678 return;
679 }
680
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000681 CompilerInstance &CI = getCompilerInstance();
682 llvm::MemoryBuffer *Buffer
Chris Lattner5159f612010-11-23 08:35:12 +0000683 = CI.getFileManager().getBufferForFile(getCurrentFile());
Douglas Gregoraf82e352010-07-20 20:18:03 +0000684 if (Buffer) {
Argyrios Kyrtzidis7aecbc72011-08-25 20:39:19 +0000685 unsigned Preamble = Lexer::ComputePreamble(Buffer, CI.getLangOpts()).first;
Douglas Gregoraf82e352010-07-20 20:18:03 +0000686 llvm::outs().write(Buffer->getBufferStart(), Preamble);
687 delete Buffer;
688 }
689}