blob: e5830d6ae68763698701a433e8e1e12b06dab829 [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 Blaikie6beb6aa2014-08-10 19:56:51 +000036std::unique_ptr<ASTConsumer>
37InitOnlyAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
38 return llvm::make_unique<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 Blaikie6beb6aa2014-08-10 19:56:51 +000048std::unique_ptr<ASTConsumer>
49ASTPrintAction::CreateASTConsumer(CompilerInstance &CI, 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 Blaikie6beb6aa2014-08-10 19:56:51 +000055std::unique_ptr<ASTConsumer>
56ASTDumpAction::CreateASTConsumer(CompilerInstance &CI, 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 Blaikie6beb6aa2014-08-10 19:56:51 +000061std::unique_ptr<ASTConsumer>
62ASTDeclListAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
Alexander Kornienko4de03592012-07-31 09:37:40 +000063 return CreateASTDeclNodeLister();
64}
65
David Blaikie6beb6aa2014-08-10 19:56:51 +000066std::unique_ptr<ASTConsumer>
67ASTViewAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
Daniel Dunbar02bd2d72009-11-14 10:42:46 +000068 return CreateASTViewer();
69}
70
David Blaikie6beb6aa2014-08-10 19:56:51 +000071std::unique_ptr<ASTConsumer>
72DeclContextPrintAction::CreateASTConsumer(CompilerInstance &CI,
73 StringRef InFile) {
Daniel Dunbar02bd2d72009-11-14 10:42:46 +000074 return CreateDeclContextPrinter();
75}
76
David Blaikie6beb6aa2014-08-10 19:56:51 +000077std::unique_ptr<ASTConsumer>
78GeneratePCHAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
Douglas Gregor48c8cd32010-08-03 08:14:03 +000079 std::string Sysroot;
Argyrios Kyrtzidis10b23682011-02-15 17:54:22 +000080 std::string OutputFile;
Craig Topper49a27902014-05-22 04:46:25 +000081 raw_ostream *OS = nullptr;
Douglas Gregor36db4f92011-08-25 22:35:51 +000082 if (ComputeASTConsumerArguments(CI, InFile, Sysroot, OutputFile, OS))
Craig Topper49a27902014-05-22 04:46:25 +000083 return nullptr;
Douglas Gregor48c8cd32010-08-03 08:14:03 +000084
Douglas Gregorc567ba22011-07-22 16:35:34 +000085 if (!CI.getFrontendOpts().RelocatablePCH)
86 Sysroot.clear();
David Blaikie6beb6aa2014-08-10 19:56:51 +000087 return llvm::make_unique<PCHGenerator>(CI.getPreprocessor(), OutputFile,
88 nullptr, Sysroot, OS);
Douglas Gregor48c8cd32010-08-03 08:14:03 +000089}
90
91bool GeneratePCHAction::ComputeASTConsumerArguments(CompilerInstance &CI,
Chris Lattner0e62c1c2011-07-23 10:55:15 +000092 StringRef InFile,
Douglas Gregor48c8cd32010-08-03 08:14:03 +000093 std::string &Sysroot,
Argyrios Kyrtzidis10b23682011-02-15 17:54:22 +000094 std::string &OutputFile,
Douglas Gregor36db4f92011-08-25 22:35:51 +000095 raw_ostream *&OS) {
Douglas Gregor48c8cd32010-08-03 08:14:03 +000096 Sysroot = CI.getHeaderSearchOpts().Sysroot;
97 if (CI.getFrontendOpts().RelocatablePCH && Sysroot.empty()) {
Sebastian Redlea68af42010-08-17 17:55:38 +000098 CI.getDiagnostics().Report(diag::err_relocatable_without_isysroot);
Douglas Gregor48c8cd32010-08-03 08:14:03 +000099 return true;
Daniel Dunbar02bd2d72009-11-14 10:42:46 +0000100 }
101
Daniel Dunbara2867c72011-01-31 22:00:44 +0000102 // We use createOutputFile here because this is exposed via libclang, and we
103 // must disable the RemoveFileOnSignal behavior.
Argyrios Kyrtzidis08a2bfd2011-07-28 00:45:10 +0000104 // We use a temporary to avoid race conditions.
Daniel Dunbara2867c72011-01-31 22:00:44 +0000105 OS = CI.createOutputFile(CI.getFrontendOpts().OutputFile, /*Binary=*/true,
Argyrios Kyrtzidis08a2bfd2011-07-28 00:45:10 +0000106 /*RemoveFileOnSignal=*/false, InFile,
107 /*Extension=*/"", /*useTemporary=*/true);
Daniel Dunbar75546992009-12-03 09:13:30 +0000108 if (!OS)
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000109 return true;
Daniel Dunbar75546992009-12-03 09:13:30 +0000110
Argyrios Kyrtzidis10b23682011-02-15 17:54:22 +0000111 OutputFile = CI.getFrontendOpts().OutputFile;
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000112 return false;
Daniel Dunbar02bd2d72009-11-14 10:42:46 +0000113}
114
David Blaikie6beb6aa2014-08-10 19:56:51 +0000115std::unique_ptr<ASTConsumer>
116GenerateModuleAction::CreateASTConsumer(CompilerInstance &CI,
117 StringRef InFile) {
Douglas Gregor2b20cb82011-11-16 00:09:06 +0000118 std::string Sysroot;
119 std::string OutputFile;
Craig Topper49a27902014-05-22 04:46:25 +0000120 raw_ostream *OS = nullptr;
Douglas Gregor2b20cb82011-11-16 00:09:06 +0000121 if (ComputeASTConsumerArguments(CI, InFile, Sysroot, OutputFile, OS))
Craig Topper49a27902014-05-22 04:46:25 +0000122 return nullptr;
123
David Blaikie6beb6aa2014-08-10 19:56:51 +0000124 return llvm::make_unique<PCHGenerator>(CI.getPreprocessor(), OutputFile,
125 Module, Sysroot, OS);
Douglas Gregor2b20cb82011-11-16 00:09:06 +0000126}
127
Argyrios Kyrtzidis130190f2012-10-10 02:12:39 +0000128static SmallVectorImpl<char> &
129operator+=(SmallVectorImpl<char> &Includes, StringRef RHS) {
130 Includes.append(RHS.begin(), RHS.end());
131 return Includes;
132}
133
Rafael Espindolac0809172014-06-12 14:02:15 +0000134static std::error_code addHeaderInclude(StringRef HeaderName,
135 SmallVectorImpl<char> &Includes,
136 const LangOptions &LangOpts,
137 bool IsExternC) {
Richard Smith9bca2982014-03-08 00:03:56 +0000138 if (IsExternC && LangOpts.CPlusPlus)
Richard Smith77944862014-03-02 05:58:18 +0000139 Includes += "extern \"C\" {\n";
Argyrios Kyrtzidis130190f2012-10-10 02:12:39 +0000140 if (LangOpts.ObjC1)
141 Includes += "#import \"";
142 else
143 Includes += "#include \"";
Richard Smith723928c2014-03-11 02:02:47 +0000144 // Use an absolute path for the include; there's no reason to think that
145 // a relative path will work (. might not be on our include path) or that
146 // it will find the same file.
147 if (llvm::sys::path::is_absolute(HeaderName)) {
148 Includes += HeaderName;
149 } else {
150 SmallString<256> Header = HeaderName;
Rafael Espindolac0809172014-06-12 14:02:15 +0000151 if (std::error_code Err = llvm::sys::fs::make_absolute(Header))
Richard Smith723928c2014-03-11 02:02:47 +0000152 return Err;
153 Includes += Header;
154 }
Argyrios Kyrtzidis130190f2012-10-10 02:12:39 +0000155 Includes += "\"\n";
Richard Smith9bca2982014-03-08 00:03:56 +0000156 if (IsExternC && LangOpts.CPlusPlus)
Richard Smith77944862014-03-02 05:58:18 +0000157 Includes += "}\n";
Rafael Espindolac0809172014-06-12 14:02:15 +0000158 return std::error_code();
Argyrios Kyrtzidis130190f2012-10-10 02:12:39 +0000159}
160
Rafael Espindolac0809172014-06-12 14:02:15 +0000161static std::error_code addHeaderInclude(const FileEntry *Header,
162 SmallVectorImpl<char> &Includes,
163 const LangOptions &LangOpts,
164 bool IsExternC) {
Richard Smith723928c2014-03-11 02:02:47 +0000165 return addHeaderInclude(Header->getName(), Includes, LangOpts, IsExternC);
Argyrios Kyrtzidis130190f2012-10-10 02:12:39 +0000166}
167
Douglas Gregor4332b322011-11-16 17:04:00 +0000168/// \brief Collect the set of header includes needed to construct the given
Argyrios Kyrtzidisc597c8c2012-10-05 00:22:33 +0000169/// module and update the TopHeaders file set of the module.
Douglas Gregor4332b322011-11-16 17:04:00 +0000170///
171/// \param Module The module we're collecting includes from.
Douglas Gregore5626c42011-12-06 17:15:11 +0000172///
James Dennettc423c532012-06-15 21:48:19 +0000173/// \param Includes Will be augmented with the set of \#includes or \#imports
Douglas Gregore5626c42011-12-06 17:15:11 +0000174/// needed to load all of the named headers.
Rafael Espindolac0809172014-06-12 14:02:15 +0000175static std::error_code
Richard Smith723928c2014-03-11 02:02:47 +0000176collectModuleHeaderIncludes(const LangOptions &LangOpts, FileManager &FileMgr,
177 ModuleMap &ModMap, clang::Module *Module,
178 SmallVectorImpl<char> &Includes) {
Douglas Gregor1fb5c3a2011-12-31 04:05:44 +0000179 // Don't collect any headers for unavailable modules.
180 if (!Module->isAvailable())
Rafael Espindolac0809172014-06-12 14:02:15 +0000181 return std::error_code();
Douglas Gregor1fb5c3a2011-12-31 04:05:44 +0000182
Douglas Gregore5626c42011-12-06 17:15:11 +0000183 // Add includes for each of these headers.
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000184 for (unsigned I = 0, N = Module->NormalHeaders.size(); I != N; ++I) {
185 const FileEntry *Header = Module->NormalHeaders[I];
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +0000186 Module->addTopHeader(Header);
Rafael Espindolac0809172014-06-12 14:02:15 +0000187 if (std::error_code Err =
Richard Smith723928c2014-03-11 02:02:47 +0000188 addHeaderInclude(Header, Includes, LangOpts, Module->IsExternC))
189 return Err;
Douglas Gregor3ec66632012-02-02 18:42:48 +0000190 }
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000191 // Note that Module->PrivateHeaders will not be a TopHeader.
Douglas Gregore5626c42011-12-06 17:15:11 +0000192
Douglas Gregor73141fa2011-12-08 17:39:04 +0000193 if (const FileEntry *UmbrellaHeader = Module->getUmbrellaHeader()) {
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +0000194 Module->addTopHeader(UmbrellaHeader);
Douglas Gregor3ec66632012-02-02 18:42:48 +0000195 if (Module->Parent) {
196 // Include the umbrella header for submodules.
Rafael Espindolac0809172014-06-12 14:02:15 +0000197 if (std::error_code Err = addHeaderInclude(UmbrellaHeader, Includes,
198 LangOpts, Module->IsExternC))
Richard Smith723928c2014-03-11 02:02:47 +0000199 return Err;
Douglas Gregor3ec66632012-02-02 18:42:48 +0000200 }
Douglas Gregor524e33e2011-12-08 19:11:24 +0000201 } else if (const DirectoryEntry *UmbrellaDir = Module->getUmbrellaDir()) {
Douglas Gregord2a8fe12012-01-05 00:04:05 +0000202 // Add all of the headers we find in this subdirectory.
Rafael Espindolac0809172014-06-12 14:02:15 +0000203 std::error_code EC;
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000204 SmallString<128> DirNative;
Douglas Gregor524e33e2011-12-08 19:11:24 +0000205 llvm::sys::path::native(UmbrellaDir->getName(), DirNative);
Douglas Gregorc1aaf8c2011-12-12 19:13:53 +0000206 for (llvm::sys::fs::recursive_directory_iterator Dir(DirNative.str(), EC),
207 DirEnd;
Douglas Gregor524e33e2011-12-08 19:11:24 +0000208 Dir != DirEnd && !EC; Dir.increment(EC)) {
209 // Check whether this entry has an extension typically associated with
210 // headers.
211 if (!llvm::StringSwitch<bool>(llvm::sys::path::extension(Dir->path()))
212 .Cases(".h", ".H", ".hh", ".hpp", true)
213 .Default(false))
214 continue;
215
Douglas Gregord2a8fe12012-01-05 00:04:05 +0000216 // If this header is marked 'unavailable' in this module, don't include
217 // it.
Argyrios Kyrtzidisc597c8c2012-10-05 00:22:33 +0000218 if (const FileEntry *Header = FileMgr.getFile(Dir->path())) {
Richard Smith50996ce2014-04-08 13:13:04 +0000219 if (ModMap.isHeaderUnavailableInModule(Header, Module))
Douglas Gregord2a8fe12012-01-05 00:04:05 +0000220 continue;
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +0000221 Module->addTopHeader(Header);
Argyrios Kyrtzidisc597c8c2012-10-05 00:22:33 +0000222 }
Douglas Gregord2a8fe12012-01-05 00:04:05 +0000223
Richard Smith723928c2014-03-11 02:02:47 +0000224 // Include this header as part of the umbrella directory.
Rafael Espindolac0809172014-06-12 14:02:15 +0000225 if (std::error_code Err = addHeaderInclude(Dir->path(), Includes,
226 LangOpts, Module->IsExternC))
Richard Smith723928c2014-03-11 02:02:47 +0000227 return Err;
Douglas Gregor524e33e2011-12-08 19:11:24 +0000228 }
Richard Smith723928c2014-03-11 02:02:47 +0000229
230 if (EC)
231 return EC;
Douglas Gregor4332b322011-11-16 17:04:00 +0000232 }
233
234 // Recurse into submodules.
Douglas Gregoreb90e832012-01-04 23:32:19 +0000235 for (clang::Module::submodule_iterator Sub = Module->submodule_begin(),
236 SubEnd = Module->submodule_end();
Douglas Gregore5626c42011-12-06 17:15:11 +0000237 Sub != SubEnd; ++Sub)
Rafael Espindolac0809172014-06-12 14:02:15 +0000238 if (std::error_code Err = collectModuleHeaderIncludes(
Richard Smith723928c2014-03-11 02:02:47 +0000239 LangOpts, FileMgr, ModMap, *Sub, Includes))
240 return Err;
241
Rafael Espindolac0809172014-06-12 14:02:15 +0000242 return std::error_code();
Douglas Gregor4332b322011-11-16 17:04:00 +0000243}
244
Douglas Gregor2b20cb82011-11-16 00:09:06 +0000245bool GenerateModuleAction::BeginSourceFileAction(CompilerInstance &CI,
246 StringRef Filename) {
247 // Find the module map file.
248 const FileEntry *ModuleMap = CI.getFileManager().getFile(Filename);
249 if (!ModuleMap) {
250 CI.getDiagnostics().Report(diag::err_module_map_not_found)
251 << Filename;
252 return false;
253 }
254
255 // Parse the module map file.
256 HeaderSearch &HS = CI.getPreprocessor().getHeaderSearchInfo();
Douglas Gregor963c5532013-06-21 16:28:10 +0000257 if (HS.loadModuleMapFile(ModuleMap, IsSystem))
Douglas Gregor2b20cb82011-11-16 00:09:06 +0000258 return false;
259
260 if (CI.getLangOpts().CurrentModule.empty()) {
261 CI.getDiagnostics().Report(diag::err_missing_module_name);
262
263 // FIXME: Eventually, we could consider asking whether there was just
264 // a single module described in the module map, and use that as a
265 // default. Then it would be fairly trivial to just "compile" a module
266 // map with a single module (the common case).
267 return false;
268 }
Richard Smith7bea1d42014-03-05 20:55:36 +0000269
270 // If we're being run from the command-line, the module build stack will not
271 // have been filled in yet, so complete it now in order to allow us to detect
272 // module cycles.
273 SourceManager &SourceMgr = CI.getSourceManager();
274 if (SourceMgr.getModuleBuildStack().empty())
275 SourceMgr.pushModuleBuildStack(CI.getLangOpts().CurrentModule,
276 FullSourceLoc(SourceLocation(), SourceMgr));
277
Douglas Gregor2b20cb82011-11-16 00:09:06 +0000278 // Dig out the module definition.
Douglas Gregor279a6c32012-01-29 17:08:11 +0000279 Module = HS.lookupModule(CI.getLangOpts().CurrentModule,
280 /*AllowSearch=*/false);
Douglas Gregor2b20cb82011-11-16 00:09:06 +0000281 if (!Module) {
282 CI.getDiagnostics().Report(diag::err_missing_module)
283 << CI.getLangOpts().CurrentModule << Filename;
284
285 return false;
286 }
Douglas Gregor1fb5c3a2011-12-31 04:05:44 +0000287
288 // Check whether we can build this module at all.
Richard Smitha3feee22013-10-28 22:18:19 +0000289 clang::Module::Requirement Requirement;
Daniel Jasper0761a8a2013-12-17 10:31:37 +0000290 clang::Module::HeaderDirective MissingHeader;
291 if (!Module->isAvailable(CI.getLangOpts(), CI.getTarget(), Requirement,
292 MissingHeader)) {
293 if (MissingHeader.FileNameLoc.isValid()) {
Ben Langmuirec8c9752014-04-18 22:07:31 +0000294 CI.getDiagnostics().Report(MissingHeader.FileNameLoc,
295 diag::err_module_header_missing)
Daniel Jasper0761a8a2013-12-17 10:31:37 +0000296 << MissingHeader.IsUmbrella << MissingHeader.FileName;
297 } else {
298 CI.getDiagnostics().Report(diag::err_module_unavailable)
299 << Module->getFullModuleName()
300 << Requirement.second << Requirement.first;
301 }
Douglas Gregor1fb5c3a2011-12-31 04:05:44 +0000302
303 return false;
304 }
305
Ben Langmuir9d6448b2014-08-09 00:57:23 +0000306 if (ModuleMapForUniquing && ModuleMapForUniquing != ModuleMap) {
307 Module->IsInferred = true;
308 HS.getModuleMap().setInferredModuleAllowedBy(Module, ModuleMapForUniquing);
309 } else {
Ben Langmuirbeee15e2014-04-14 18:00:01 +0000310 ModuleMapForUniquing = ModuleMap;
Ben Langmuir9d6448b2014-08-09 00:57:23 +0000311 }
Ben Langmuirbeee15e2014-04-14 18:00:01 +0000312
Argyrios Kyrtzidis130190f2012-10-10 02:12:39 +0000313 FileManager &FileMgr = CI.getFileManager();
314
Douglas Gregor4332b322011-11-16 17:04:00 +0000315 // Collect the set of #includes we need to build the module.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000316 SmallString<256> HeaderContents;
Rafael Espindola8e650d72014-06-12 20:37:59 +0000317 std::error_code Err = std::error_code();
Argyrios Kyrtzidis130190f2012-10-10 02:12:39 +0000318 if (const FileEntry *UmbrellaHeader = Module->getUmbrellaHeader())
Richard Smith723928c2014-03-11 02:02:47 +0000319 Err = addHeaderInclude(UmbrellaHeader, HeaderContents, CI.getLangOpts(),
320 Module->IsExternC);
321 if (!Err)
322 Err = collectModuleHeaderIncludes(
323 CI.getLangOpts(), FileMgr,
324 CI.getPreprocessor().getHeaderSearchInfo().getModuleMap(), Module,
325 HeaderContents);
326
327 if (Err) {
328 CI.getDiagnostics().Report(diag::err_module_cannot_create_includes)
329 << Module->getFullModuleName() << Err.message();
330 return false;
331 }
Douglas Gregor4332b322011-11-16 17:04:00 +0000332
Argyrios Kyrtzidis52595242012-11-15 18:57:27 +0000333 llvm::MemoryBuffer *InputBuffer =
334 llvm::MemoryBuffer::getMemBufferCopy(HeaderContents,
335 Module::getModuleInputBufferName());
Alp Tokerf6a24ce2013-12-05 16:25:25 +0000336 // Ownership of InputBuffer will be transferred to the SourceManager.
Argyrios Kyrtzidis52595242012-11-15 18:57:27 +0000337 setCurrentInput(FrontendInputFile(InputBuffer, getCurrentFileKind(),
Douglas Gregora686e1b2012-01-27 19:52:33 +0000338 Module->IsSystem));
Douglas Gregor2b20cb82011-11-16 00:09:06 +0000339 return true;
340}
341
342bool GenerateModuleAction::ComputeASTConsumerArguments(CompilerInstance &CI,
343 StringRef InFile,
344 std::string &Sysroot,
345 std::string &OutputFile,
346 raw_ostream *&OS) {
347 // If no output file was provided, figure out where this module would go
348 // in the module cache.
349 if (CI.getFrontendOpts().OutputFile.empty()) {
350 HeaderSearch &HS = CI.getPreprocessor().getHeaderSearchInfo();
Ben Langmuirbeee15e2014-04-14 18:00:01 +0000351 CI.getFrontendOpts().OutputFile =
352 HS.getModuleFileName(CI.getLangOpts().CurrentModule,
353 ModuleMapForUniquing->getName());
Douglas Gregor2b20cb82011-11-16 00:09:06 +0000354 }
355
356 // We use createOutputFile here because this is exposed via libclang, and we
357 // must disable the RemoveFileOnSignal behavior.
358 // We use a temporary to avoid race conditions.
359 OS = CI.createOutputFile(CI.getFrontendOpts().OutputFile, /*Binary=*/true,
360 /*RemoveFileOnSignal=*/false, InFile,
Daniel Dunbarb9c62c02012-03-03 00:36:02 +0000361 /*Extension=*/"", /*useTemporary=*/true,
362 /*CreateMissingDirectories=*/true);
Douglas Gregor2b20cb82011-11-16 00:09:06 +0000363 if (!OS)
364 return true;
365
366 OutputFile = CI.getFrontendOpts().OutputFile;
367 return false;
368}
369
David Blaikie6beb6aa2014-08-10 19:56:51 +0000370std::unique_ptr<ASTConsumer>
371SyntaxOnlyAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
372 return llvm::make_unique<ASTConsumer>();
Daniel Dunbar02bd2d72009-11-14 10:42:46 +0000373}
374
David Blaikie6beb6aa2014-08-10 19:56:51 +0000375std::unique_ptr<ASTConsumer>
376DumpModuleInfoAction::CreateASTConsumer(CompilerInstance &CI,
377 StringRef InFile) {
378 return llvm::make_unique<ASTConsumer>();
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000379}
380
David Blaikie6beb6aa2014-08-10 19:56:51 +0000381std::unique_ptr<ASTConsumer>
382VerifyPCHAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
383 return llvm::make_unique<ASTConsumer>();
Ben Langmuir2cb4a782014-02-05 22:21:15 +0000384}
385
386void VerifyPCHAction::ExecuteAction() {
Ben Langmuir3d4417c2014-02-07 17:31:11 +0000387 CompilerInstance &CI = getCompilerInstance();
388 bool Preamble = CI.getPreprocessorOpts().PrecompiledPreambleBytes.first != 0;
389 const std::string &Sysroot = CI.getHeaderSearchOpts().Sysroot;
Ahmed Charlesb8984322014-03-07 20:03:18 +0000390 std::unique_ptr<ASTReader> Reader(
391 new ASTReader(CI.getPreprocessor(), CI.getASTContext(),
392 Sysroot.empty() ? "" : Sysroot.c_str(),
393 /*DisableValidation*/ false,
394 /*AllowPCHWithCompilerErrors*/ false,
395 /*AllowConfigurationMismatch*/ true,
396 /*ValidateSystemInputs*/ true));
Ben Langmuir3d4417c2014-02-07 17:31:11 +0000397
398 Reader->ReadAST(getCurrentFile(),
399 Preamble ? serialization::MK_Preamble
400 : serialization::MK_PCH,
401 SourceLocation(),
402 ASTReader::ARR_ConfigurationMismatch);
Ben Langmuir2cb4a782014-02-05 22:21:15 +0000403}
404
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000405namespace {
406 /// \brief AST reader listener that dumps module information for a module
407 /// file.
408 class DumpModuleInfoListener : public ASTReaderListener {
409 llvm::raw_ostream &Out;
410
411 public:
412 DumpModuleInfoListener(llvm::raw_ostream &Out) : Out(Out) { }
413
414#define DUMP_BOOLEAN(Value, Text) \
415 Out.indent(4) << Text << ": " << (Value? "Yes" : "No") << "\n"
416
Craig Topperafa7cb32014-03-13 06:07:04 +0000417 bool ReadFullVersionInformation(StringRef FullVersion) override {
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000418 Out.indent(2)
419 << "Generated by "
420 << (FullVersion == getClangFullRepositoryVersion()? "this"
421 : "a different")
422 << " Clang: " << FullVersion << "\n";
423 return ASTReaderListener::ReadFullVersionInformation(FullVersion);
424 }
425
Ben Langmuir4f5212a2014-04-14 22:12:44 +0000426 void ReadModuleName(StringRef ModuleName) override {
427 Out.indent(2) << "Module name: " << ModuleName << "\n";
428 }
429 void ReadModuleMapFile(StringRef ModuleMapPath) override {
430 Out.indent(2) << "Module map file: " << ModuleMapPath << "\n";
431 }
432
Craig Topperafa7cb32014-03-13 06:07:04 +0000433 bool ReadLanguageOptions(const LangOptions &LangOpts,
434 bool Complain) override {
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000435 Out.indent(2) << "Language options:\n";
436#define LANGOPT(Name, Bits, Default, Description) \
437 DUMP_BOOLEAN(LangOpts.Name, Description);
438#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
439 Out.indent(4) << Description << ": " \
440 << static_cast<unsigned>(LangOpts.get##Name()) << "\n";
441#define VALUE_LANGOPT(Name, Bits, Default, Description) \
442 Out.indent(4) << Description << ": " << LangOpts.Name << "\n";
443#define BENIGN_LANGOPT(Name, Bits, Default, Description)
444#define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
445#include "clang/Basic/LangOptions.def"
446 return false;
447 }
448
Craig Topperafa7cb32014-03-13 06:07:04 +0000449 bool ReadTargetOptions(const TargetOptions &TargetOpts,
450 bool Complain) override {
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000451 Out.indent(2) << "Target options:\n";
452 Out.indent(4) << " Triple: " << TargetOpts.Triple << "\n";
453 Out.indent(4) << " CPU: " << TargetOpts.CPU << "\n";
454 Out.indent(4) << " ABI: " << TargetOpts.ABI << "\n";
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000455
456 if (!TargetOpts.FeaturesAsWritten.empty()) {
457 Out.indent(4) << "Target features:\n";
458 for (unsigned I = 0, N = TargetOpts.FeaturesAsWritten.size();
459 I != N; ++I) {
460 Out.indent(6) << TargetOpts.FeaturesAsWritten[I] << "\n";
461 }
462 }
463
464 return false;
465 }
466
Ben Langmuirb92de022014-04-29 16:25:26 +0000467 virtual bool
468 ReadDiagnosticOptions(IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts,
469 bool Complain) override {
470 Out.indent(2) << "Diagnostic options:\n";
471#define DIAGOPT(Name, Bits, Default) DUMP_BOOLEAN(DiagOpts->Name, #Name);
472#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
473 Out.indent(4) << #Name << ": " << DiagOpts->get##Name() << "\n";
474#define VALUE_DIAGOPT(Name, Bits, Default) \
475 Out.indent(4) << #Name << ": " << DiagOpts->Name << "\n";
476#include "clang/Basic/DiagnosticOptions.def"
477
Richard Smith3be1cb22014-08-07 00:24:21 +0000478 Out.indent(4) << "Diagnostic flags:\n";
479 for (const std::string &Warning : DiagOpts->Warnings)
Ben Langmuirb92de022014-04-29 16:25:26 +0000480 Out.indent(6) << "-W" << Warning << "\n";
Richard Smith3be1cb22014-08-07 00:24:21 +0000481 for (const std::string &Remark : DiagOpts->Remarks)
482 Out.indent(6) << "-R" << Remark << "\n";
Ben Langmuirb92de022014-04-29 16:25:26 +0000483
484 return false;
485 }
486
Craig Topperafa7cb32014-03-13 06:07:04 +0000487 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
488 bool Complain) override {
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000489 Out.indent(2) << "Header search options:\n";
490 Out.indent(4) << "System root [-isysroot=]: '" << HSOpts.Sysroot << "'\n";
491 DUMP_BOOLEAN(HSOpts.UseBuiltinIncludes,
492 "Use builtin include directories [-nobuiltininc]");
493 DUMP_BOOLEAN(HSOpts.UseStandardSystemIncludes,
494 "Use standard system include directories [-nostdinc]");
495 DUMP_BOOLEAN(HSOpts.UseStandardCXXIncludes,
496 "Use standard C++ include directories [-nostdinc++]");
497 DUMP_BOOLEAN(HSOpts.UseLibcxx,
498 "Use libc++ (rather than libstdc++) [-stdlib=]");
499 return false;
500 }
501
Craig Topperafa7cb32014-03-13 06:07:04 +0000502 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
503 bool Complain,
504 std::string &SuggestedPredefines) override {
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000505 Out.indent(2) << "Preprocessor options:\n";
506 DUMP_BOOLEAN(PPOpts.UsePredefines,
507 "Uses compiler/target-specific predefines [-undef]");
508 DUMP_BOOLEAN(PPOpts.DetailedRecord,
509 "Uses detailed preprocessing record (for indexing)");
510
511 if (!PPOpts.Macros.empty()) {
512 Out.indent(4) << "Predefined macros:\n";
513 }
514
515 for (std::vector<std::pair<std::string, bool/*isUndef*/> >::const_iterator
516 I = PPOpts.Macros.begin(), IEnd = PPOpts.Macros.end();
517 I != IEnd; ++I) {
518 Out.indent(6);
519 if (I->second)
520 Out << "-U";
521 else
522 Out << "-D";
523 Out << I->first << "\n";
524 }
525 return false;
526 }
527#undef DUMP_BOOLEAN
528 };
529}
530
531void DumpModuleInfoAction::ExecuteAction() {
532 // Set up the output file.
Ahmed Charlesb8984322014-03-07 20:03:18 +0000533 std::unique_ptr<llvm::raw_fd_ostream> OutFile;
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000534 StringRef OutputFileName = getCompilerInstance().getFrontendOpts().OutputFile;
535 if (!OutputFileName.empty() && OutputFileName != "-") {
536 std::string ErrorInfo;
537 OutFile.reset(new llvm::raw_fd_ostream(OutputFileName.str().c_str(),
Rafael Espindola4fbd3732014-02-24 18:20:21 +0000538 ErrorInfo, llvm::sys::fs::F_Text));
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000539 }
540 llvm::raw_ostream &Out = OutFile.get()? *OutFile.get() : llvm::outs();
541
542 Out << "Information for module file '" << getCurrentFile() << "':\n";
543 DumpModuleInfoListener Listener(Out);
544 ASTReader::readASTFileControlBlock(getCurrentFile(),
545 getCompilerInstance().getFileManager(),
546 Listener);
547}
548
Daniel Dunbar88357802009-11-14 10:42:57 +0000549//===----------------------------------------------------------------------===//
550// Preprocessor Actions
551//===----------------------------------------------------------------------===//
552
553void DumpRawTokensAction::ExecuteAction() {
554 Preprocessor &PP = getCompilerInstance().getPreprocessor();
555 SourceManager &SM = PP.getSourceManager();
556
557 // Start lexing the specified input file.
Chris Lattner710bb872009-11-30 04:18:44 +0000558 const llvm::MemoryBuffer *FromFile = SM.getBuffer(SM.getMainFileID());
David Blaikiebbafb8a2012-03-11 07:00:24 +0000559 Lexer RawLex(SM.getMainFileID(), FromFile, SM, PP.getLangOpts());
Daniel Dunbar88357802009-11-14 10:42:57 +0000560 RawLex.SetKeepWhitespaceMode(true);
561
562 Token RawTok;
563 RawLex.LexFromRawLexer(RawTok);
564 while (RawTok.isNot(tok::eof)) {
565 PP.DumpToken(RawTok, true);
Daniel Dunbar75024622009-11-25 10:27:48 +0000566 llvm::errs() << "\n";
Daniel Dunbar88357802009-11-14 10:42:57 +0000567 RawLex.LexFromRawLexer(RawTok);
568 }
569}
570
571void DumpTokensAction::ExecuteAction() {
572 Preprocessor &PP = getCompilerInstance().getPreprocessor();
573 // Start preprocessing the specified input file.
574 Token Tok;
Chris Lattnerfb24a3a2010-04-20 20:35:58 +0000575 PP.EnterMainSourceFile();
Daniel Dunbar88357802009-11-14 10:42:57 +0000576 do {
577 PP.Lex(Tok);
578 PP.DumpToken(Tok, true);
Daniel Dunbar75024622009-11-25 10:27:48 +0000579 llvm::errs() << "\n";
Daniel Dunbar88357802009-11-14 10:42:57 +0000580 } while (Tok.isNot(tok::eof));
581}
582
583void GeneratePTHAction::ExecuteAction() {
584 CompilerInstance &CI = getCompilerInstance();
585 if (CI.getFrontendOpts().OutputFile.empty() ||
586 CI.getFrontendOpts().OutputFile == "-") {
587 // FIXME: Don't fail this way.
588 // FIXME: Verify that we can actually seek in the given file.
Chris Lattner4b73cfa2010-04-07 22:58:06 +0000589 llvm::report_fatal_error("PTH requires a seekable file for output!");
Daniel Dunbar88357802009-11-14 10:42:57 +0000590 }
591 llvm::raw_fd_ostream *OS =
592 CI.createDefaultOutputFile(true, getCurrentFile());
Daniel Dunbar75546992009-12-03 09:13:30 +0000593 if (!OS) return;
594
Daniel Dunbar88357802009-11-14 10:42:57 +0000595 CacheTokens(CI.getPreprocessor(), OS);
596}
597
Daniel Dunbar88357802009-11-14 10:42:57 +0000598void PreprocessOnlyAction::ExecuteAction() {
599 Preprocessor &PP = getCompilerInstance().getPreprocessor();
600
Daniel Dunbard839e772010-06-11 20:10:12 +0000601 // Ignore unknown pragmas.
Lubos Lunak576a0412014-05-01 12:54:03 +0000602 PP.IgnorePragmas();
Daniel Dunbard839e772010-06-11 20:10:12 +0000603
Daniel Dunbar88357802009-11-14 10:42:57 +0000604 Token Tok;
605 // Start parsing the specified input file.
Chris Lattnerfb24a3a2010-04-20 20:35:58 +0000606 PP.EnterMainSourceFile();
Daniel Dunbar88357802009-11-14 10:42:57 +0000607 do {
608 PP.Lex(Tok);
609 } while (Tok.isNot(tok::eof));
610}
611
Daniel Dunbar88357802009-11-14 10:42:57 +0000612void PrintPreprocessedAction::ExecuteAction() {
613 CompilerInstance &CI = getCompilerInstance();
Douglas Gregor52da28b2011-09-23 23:43:36 +0000614 // Output file may need to be set to 'Binary', to avoid converting Unix style
Steve Naroff3d38a682010-01-05 17:33:23 +0000615 // line feeds (<LF>) to Microsoft style line feeds (<CR><LF>).
Douglas Gregor52da28b2011-09-23 23:43:36 +0000616 //
617 // Look to see what type of line endings the file uses. If there's a
618 // CRLF, then we won't open the file up in binary mode. If there is
619 // just an LF or CR, then we will open the file up in binary mode.
620 // In this fashion, the output format should match the input format, unless
621 // the input format has inconsistent line endings.
622 //
623 // This should be a relatively fast operation since most files won't have
624 // all of their source code on a single line. However, that is still a
625 // concern, so if we scan for too long, we'll just assume the file should
626 // be opened in binary mode.
627 bool BinaryMode = true;
628 bool InvalidFile = false;
629 const SourceManager& SM = CI.getSourceManager();
630 const llvm::MemoryBuffer *Buffer = SM.getBuffer(SM.getMainFileID(),
631 &InvalidFile);
632 if (!InvalidFile) {
633 const char *cur = Buffer->getBufferStart();
634 const char *end = Buffer->getBufferEnd();
635 const char *next = (cur != end) ? cur + 1 : end;
636
637 // Limit ourselves to only scanning 256 characters into the source
638 // file. This is mostly a sanity check in case the file has no
639 // newlines whatsoever.
640 if (end - cur > 256) end = cur + 256;
641
642 while (next < end) {
643 if (*cur == 0x0D) { // CR
644 if (*next == 0x0A) // CRLF
645 BinaryMode = false;
646
647 break;
648 } else if (*cur == 0x0A) // LF
649 break;
650
651 ++cur, ++next;
652 }
653 }
654
655 raw_ostream *OS = CI.createDefaultOutputFile(BinaryMode, getCurrentFile());
Daniel Dunbar75546992009-12-03 09:13:30 +0000656 if (!OS) return;
657
Daniel Dunbar88357802009-11-14 10:42:57 +0000658 DoPrintPreprocessedInput(CI.getPreprocessor(), OS,
659 CI.getPreprocessorOutputOpts());
660}
Douglas Gregoraf82e352010-07-20 20:18:03 +0000661
662void PrintPreambleAction::ExecuteAction() {
663 switch (getCurrentFileKind()) {
664 case IK_C:
665 case IK_CXX:
666 case IK_ObjC:
667 case IK_ObjCXX:
668 case IK_OpenCL:
Peter Collingbourne62089b82010-12-01 03:15:20 +0000669 case IK_CUDA:
Douglas Gregoraf82e352010-07-20 20:18:03 +0000670 break;
671
672 case IK_None:
673 case IK_Asm:
674 case IK_PreprocessedC:
675 case IK_PreprocessedCXX:
676 case IK_PreprocessedObjC:
677 case IK_PreprocessedObjCXX:
678 case IK_AST:
679 case IK_LLVM_IR:
680 // We can't do anything with these.
681 return;
682 }
683
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000684 CompilerInstance &CI = getCompilerInstance();
685 llvm::MemoryBuffer *Buffer
Chris Lattner5159f612010-11-23 08:35:12 +0000686 = CI.getFileManager().getBufferForFile(getCurrentFile());
Douglas Gregoraf82e352010-07-20 20:18:03 +0000687 if (Buffer) {
David Blaikie3d95d852014-08-11 22:08:06 +0000688 unsigned Preamble = Lexer::ComputePreamble(*Buffer, CI.getLangOpts()).first;
Douglas Gregoraf82e352010-07-20 20:18:03 +0000689 llvm::outs().write(Buffer->getBufferStart(), Preamble);
690 delete Buffer;
691 }
692}