blob: 3d65ae32c019349d963e61fa95a73597226ddfba [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"
Douglas Gregor52da28b2011-09-23 23:43:36 +000027#include "llvm/Support/system_error.h"
Ahmed Charlesdfca6f92014-03-09 11:36:40 +000028#include <memory>
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
36ASTConsumer *InitOnlyAction::CreateASTConsumer(CompilerInstance &CI,
Chris Lattner0e62c1c2011-07-23 10:55:15 +000037 StringRef InFile) {
Daniel Dunbar1c201fb2010-03-19 19:44:04 +000038 return new ASTConsumer();
39}
40
41void InitOnlyAction::ExecuteAction() {
42}
43
44//===----------------------------------------------------------------------===//
Daniel Dunbar88357802009-11-14 10:42:57 +000045// AST Consumer Actions
46//===----------------------------------------------------------------------===//
47
Daniel Dunbar02bd2d72009-11-14 10:42:46 +000048ASTConsumer *ASTPrintAction::CreateASTConsumer(CompilerInstance &CI,
Chris Lattner0e62c1c2011-07-23 10:55:15 +000049 StringRef InFile) {
50 if (raw_ostream *OS = CI.createDefaultOutputFile(false, InFile))
Alexander Kornienko3db68ee2012-07-26 16:01:23 +000051 return CreateASTPrinter(OS, CI.getFrontendOpts().ASTDumpFilter);
Daniel Dunbar75546992009-12-03 09:13:30 +000052 return 0;
Daniel Dunbar02bd2d72009-11-14 10:42:46 +000053}
54
Daniel Dunbar02bd2d72009-11-14 10:42:46 +000055ASTConsumer *ASTDumpAction::CreateASTConsumer(CompilerInstance &CI,
Chris Lattner0e62c1c2011-07-23 10:55:15 +000056 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
Alexander Kornienko4de03592012-07-31 09:37:40 +000061ASTConsumer *ASTDeclListAction::CreateASTConsumer(CompilerInstance &CI,
62 StringRef InFile) {
63 return CreateASTDeclNodeLister();
64}
65
Daniel Dunbar02bd2d72009-11-14 10:42:46 +000066ASTConsumer *ASTViewAction::CreateASTConsumer(CompilerInstance &CI,
Chris Lattner0e62c1c2011-07-23 10:55:15 +000067 StringRef InFile) {
Daniel Dunbar02bd2d72009-11-14 10:42:46 +000068 return CreateASTViewer();
69}
70
71ASTConsumer *DeclContextPrintAction::CreateASTConsumer(CompilerInstance &CI,
Chris Lattner0e62c1c2011-07-23 10:55:15 +000072 StringRef InFile) {
Daniel Dunbar02bd2d72009-11-14 10:42:46 +000073 return CreateDeclContextPrinter();
74}
75
Daniel Dunbar02bd2d72009-11-14 10:42:46 +000076ASTConsumer *GeneratePCHAction::CreateASTConsumer(CompilerInstance &CI,
Chris Lattner0e62c1c2011-07-23 10:55:15 +000077 StringRef InFile) {
Douglas Gregor48c8cd32010-08-03 08:14:03 +000078 std::string Sysroot;
Argyrios Kyrtzidis10b23682011-02-15 17:54:22 +000079 std::string OutputFile;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000080 raw_ostream *OS = 0;
Douglas Gregor36db4f92011-08-25 22:35:51 +000081 if (ComputeASTConsumerArguments(CI, InFile, Sysroot, OutputFile, OS))
Daniel Dunbar02bd2d72009-11-14 10:42:46 +000082 return 0;
Douglas Gregor48c8cd32010-08-03 08:14:03 +000083
Douglas Gregorc567ba22011-07-22 16:35:34 +000084 if (!CI.getFrontendOpts().RelocatablePCH)
85 Sysroot.clear();
Douglas Gregorf7a700fd2011-11-30 04:39:39 +000086 return new PCHGenerator(CI.getPreprocessor(), OutputFile, 0, Sysroot, OS);
Douglas Gregor48c8cd32010-08-03 08:14:03 +000087}
88
89bool GeneratePCHAction::ComputeASTConsumerArguments(CompilerInstance &CI,
Chris Lattner0e62c1c2011-07-23 10:55:15 +000090 StringRef InFile,
Douglas Gregor48c8cd32010-08-03 08:14:03 +000091 std::string &Sysroot,
Argyrios Kyrtzidis10b23682011-02-15 17:54:22 +000092 std::string &OutputFile,
Douglas Gregor36db4f92011-08-25 22:35:51 +000093 raw_ostream *&OS) {
Douglas Gregor48c8cd32010-08-03 08:14:03 +000094 Sysroot = CI.getHeaderSearchOpts().Sysroot;
95 if (CI.getFrontendOpts().RelocatablePCH && Sysroot.empty()) {
Sebastian Redlea68af42010-08-17 17:55:38 +000096 CI.getDiagnostics().Report(diag::err_relocatable_without_isysroot);
Douglas Gregor48c8cd32010-08-03 08:14:03 +000097 return true;
Daniel Dunbar02bd2d72009-11-14 10:42:46 +000098 }
99
Daniel Dunbara2867c72011-01-31 22:00:44 +0000100 // We use createOutputFile here because this is exposed via libclang, and we
101 // must disable the RemoveFileOnSignal behavior.
Argyrios Kyrtzidis08a2bfd2011-07-28 00:45:10 +0000102 // We use a temporary to avoid race conditions.
Daniel Dunbara2867c72011-01-31 22:00:44 +0000103 OS = CI.createOutputFile(CI.getFrontendOpts().OutputFile, /*Binary=*/true,
Argyrios Kyrtzidis08a2bfd2011-07-28 00:45:10 +0000104 /*RemoveFileOnSignal=*/false, InFile,
105 /*Extension=*/"", /*useTemporary=*/true);
Daniel Dunbar75546992009-12-03 09:13:30 +0000106 if (!OS)
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000107 return true;
Daniel Dunbar75546992009-12-03 09:13:30 +0000108
Argyrios Kyrtzidis10b23682011-02-15 17:54:22 +0000109 OutputFile = CI.getFrontendOpts().OutputFile;
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000110 return false;
Daniel Dunbar02bd2d72009-11-14 10:42:46 +0000111}
112
Douglas Gregor2b20cb82011-11-16 00:09:06 +0000113ASTConsumer *GenerateModuleAction::CreateASTConsumer(CompilerInstance &CI,
114 StringRef InFile) {
115 std::string Sysroot;
116 std::string OutputFile;
117 raw_ostream *OS = 0;
118 if (ComputeASTConsumerArguments(CI, InFile, Sysroot, OutputFile, OS))
119 return 0;
120
Douglas Gregorf7a700fd2011-11-30 04:39:39 +0000121 return new PCHGenerator(CI.getPreprocessor(), OutputFile, Module,
Douglas Gregor2b20cb82011-11-16 00:09:06 +0000122 Sysroot, OS);
123}
124
Argyrios Kyrtzidis130190f2012-10-10 02:12:39 +0000125static SmallVectorImpl<char> &
126operator+=(SmallVectorImpl<char> &Includes, StringRef RHS) {
127 Includes.append(RHS.begin(), RHS.end());
128 return Includes;
129}
130
Richard Smith723928c2014-03-11 02:02:47 +0000131static llvm::error_code addHeaderInclude(StringRef HeaderName,
132 SmallVectorImpl<char> &Includes,
133 const LangOptions &LangOpts,
134 bool IsExternC) {
Richard Smith9bca2982014-03-08 00:03:56 +0000135 if (IsExternC && LangOpts.CPlusPlus)
Richard Smith77944862014-03-02 05:58:18 +0000136 Includes += "extern \"C\" {\n";
Argyrios Kyrtzidis130190f2012-10-10 02:12:39 +0000137 if (LangOpts.ObjC1)
138 Includes += "#import \"";
139 else
140 Includes += "#include \"";
Richard Smith723928c2014-03-11 02:02:47 +0000141 // Use an absolute path for the include; there's no reason to think that
142 // a relative path will work (. might not be on our include path) or that
143 // it will find the same file.
144 if (llvm::sys::path::is_absolute(HeaderName)) {
145 Includes += HeaderName;
146 } else {
147 SmallString<256> Header = HeaderName;
148 if (llvm::error_code Err = llvm::sys::fs::make_absolute(Header))
149 return Err;
150 Includes += Header;
151 }
Argyrios Kyrtzidis130190f2012-10-10 02:12:39 +0000152 Includes += "\"\n";
Richard Smith9bca2982014-03-08 00:03:56 +0000153 if (IsExternC && LangOpts.CPlusPlus)
Richard Smith77944862014-03-02 05:58:18 +0000154 Includes += "}\n";
Richard Smith723928c2014-03-11 02:02:47 +0000155 return llvm::error_code::success();
Argyrios Kyrtzidis130190f2012-10-10 02:12:39 +0000156}
157
Richard Smith723928c2014-03-11 02:02:47 +0000158static llvm::error_code addHeaderInclude(const FileEntry *Header,
159 SmallVectorImpl<char> &Includes,
160 const LangOptions &LangOpts,
161 bool IsExternC) {
162 return addHeaderInclude(Header->getName(), Includes, LangOpts, IsExternC);
Argyrios Kyrtzidis130190f2012-10-10 02:12:39 +0000163}
164
Douglas Gregor4332b322011-11-16 17:04:00 +0000165/// \brief Collect the set of header includes needed to construct the given
Argyrios Kyrtzidisc597c8c2012-10-05 00:22:33 +0000166/// module and update the TopHeaders file set of the module.
Douglas Gregor4332b322011-11-16 17:04:00 +0000167///
168/// \param Module The module we're collecting includes from.
Douglas Gregore5626c42011-12-06 17:15:11 +0000169///
James Dennettc423c532012-06-15 21:48:19 +0000170/// \param Includes Will be augmented with the set of \#includes or \#imports
Douglas Gregore5626c42011-12-06 17:15:11 +0000171/// needed to load all of the named headers.
Richard Smith723928c2014-03-11 02:02:47 +0000172static llvm::error_code
173collectModuleHeaderIncludes(const LangOptions &LangOpts, FileManager &FileMgr,
174 ModuleMap &ModMap, clang::Module *Module,
175 SmallVectorImpl<char> &Includes) {
Douglas Gregor1fb5c3a2011-12-31 04:05:44 +0000176 // Don't collect any headers for unavailable modules.
177 if (!Module->isAvailable())
Richard Smith723928c2014-03-11 02:02:47 +0000178 return llvm::error_code::success();
Douglas Gregor1fb5c3a2011-12-31 04:05:44 +0000179
Douglas Gregore5626c42011-12-06 17:15:11 +0000180 // Add includes for each of these headers.
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000181 for (unsigned I = 0, N = Module->NormalHeaders.size(); I != N; ++I) {
182 const FileEntry *Header = Module->NormalHeaders[I];
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +0000183 Module->addTopHeader(Header);
Richard Smith723928c2014-03-11 02:02:47 +0000184 if (llvm::error_code Err =
185 addHeaderInclude(Header, Includes, LangOpts, Module->IsExternC))
186 return Err;
Douglas Gregor3ec66632012-02-02 18:42:48 +0000187 }
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000188 // Note that Module->PrivateHeaders will not be a TopHeader.
Douglas Gregore5626c42011-12-06 17:15:11 +0000189
Douglas Gregor73141fa2011-12-08 17:39:04 +0000190 if (const FileEntry *UmbrellaHeader = Module->getUmbrellaHeader()) {
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +0000191 Module->addTopHeader(UmbrellaHeader);
Douglas Gregor3ec66632012-02-02 18:42:48 +0000192 if (Module->Parent) {
193 // Include the umbrella header for submodules.
Richard Smith723928c2014-03-11 02:02:47 +0000194 if (llvm::error_code Err = addHeaderInclude(UmbrellaHeader, Includes,
195 LangOpts, Module->IsExternC))
196 return Err;
Douglas Gregor3ec66632012-02-02 18:42:48 +0000197 }
Douglas Gregor524e33e2011-12-08 19:11:24 +0000198 } else if (const DirectoryEntry *UmbrellaDir = Module->getUmbrellaDir()) {
Douglas Gregord2a8fe12012-01-05 00:04:05 +0000199 // Add all of the headers we find in this subdirectory.
Douglas Gregor524e33e2011-12-08 19:11:24 +0000200 llvm::error_code EC;
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000201 SmallString<128> DirNative;
Douglas Gregor524e33e2011-12-08 19:11:24 +0000202 llvm::sys::path::native(UmbrellaDir->getName(), DirNative);
Douglas Gregorc1aaf8c2011-12-12 19:13:53 +0000203 for (llvm::sys::fs::recursive_directory_iterator Dir(DirNative.str(), EC),
204 DirEnd;
Douglas Gregor524e33e2011-12-08 19:11:24 +0000205 Dir != DirEnd && !EC; Dir.increment(EC)) {
206 // Check whether this entry has an extension typically associated with
207 // headers.
208 if (!llvm::StringSwitch<bool>(llvm::sys::path::extension(Dir->path()))
209 .Cases(".h", ".H", ".hh", ".hpp", true)
210 .Default(false))
211 continue;
212
Douglas Gregord2a8fe12012-01-05 00:04:05 +0000213 // If this header is marked 'unavailable' in this module, don't include
214 // it.
Argyrios Kyrtzidisc597c8c2012-10-05 00:22:33 +0000215 if (const FileEntry *Header = FileMgr.getFile(Dir->path())) {
Richard Smith50996ce2014-04-08 13:13:04 +0000216 if (ModMap.isHeaderUnavailableInModule(Header, Module))
Douglas Gregord2a8fe12012-01-05 00:04:05 +0000217 continue;
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +0000218 Module->addTopHeader(Header);
Argyrios Kyrtzidisc597c8c2012-10-05 00:22:33 +0000219 }
Douglas Gregord2a8fe12012-01-05 00:04:05 +0000220
Richard Smith723928c2014-03-11 02:02:47 +0000221 // Include this header as part of the umbrella directory.
222 if (llvm::error_code Err = addHeaderInclude(Dir->path(), Includes,
223 LangOpts, Module->IsExternC))
224 return Err;
Douglas Gregor524e33e2011-12-08 19:11:24 +0000225 }
Richard Smith723928c2014-03-11 02:02:47 +0000226
227 if (EC)
228 return EC;
Douglas Gregor4332b322011-11-16 17:04:00 +0000229 }
230
231 // Recurse into submodules.
Douglas Gregoreb90e832012-01-04 23:32:19 +0000232 for (clang::Module::submodule_iterator Sub = Module->submodule_begin(),
233 SubEnd = Module->submodule_end();
Douglas Gregore5626c42011-12-06 17:15:11 +0000234 Sub != SubEnd; ++Sub)
Richard Smith723928c2014-03-11 02:02:47 +0000235 if (llvm::error_code Err = collectModuleHeaderIncludes(
236 LangOpts, FileMgr, ModMap, *Sub, Includes))
237 return Err;
238
239 return llvm::error_code::success();
Douglas Gregor4332b322011-11-16 17:04:00 +0000240}
241
Douglas Gregor2b20cb82011-11-16 00:09:06 +0000242bool GenerateModuleAction::BeginSourceFileAction(CompilerInstance &CI,
243 StringRef Filename) {
244 // Find the module map file.
245 const FileEntry *ModuleMap = CI.getFileManager().getFile(Filename);
246 if (!ModuleMap) {
247 CI.getDiagnostics().Report(diag::err_module_map_not_found)
248 << Filename;
249 return false;
250 }
251
252 // Parse the module map file.
253 HeaderSearch &HS = CI.getPreprocessor().getHeaderSearchInfo();
Douglas Gregor963c5532013-06-21 16:28:10 +0000254 if (HS.loadModuleMapFile(ModuleMap, IsSystem))
Douglas Gregor2b20cb82011-11-16 00:09:06 +0000255 return false;
256
257 if (CI.getLangOpts().CurrentModule.empty()) {
258 CI.getDiagnostics().Report(diag::err_missing_module_name);
259
260 // FIXME: Eventually, we could consider asking whether there was just
261 // a single module described in the module map, and use that as a
262 // default. Then it would be fairly trivial to just "compile" a module
263 // map with a single module (the common case).
264 return false;
265 }
Richard Smith7bea1d42014-03-05 20:55:36 +0000266
267 // If we're being run from the command-line, the module build stack will not
268 // have been filled in yet, so complete it now in order to allow us to detect
269 // module cycles.
270 SourceManager &SourceMgr = CI.getSourceManager();
271 if (SourceMgr.getModuleBuildStack().empty())
272 SourceMgr.pushModuleBuildStack(CI.getLangOpts().CurrentModule,
273 FullSourceLoc(SourceLocation(), SourceMgr));
274
Douglas Gregor2b20cb82011-11-16 00:09:06 +0000275 // Dig out the module definition.
Douglas Gregor279a6c32012-01-29 17:08:11 +0000276 Module = HS.lookupModule(CI.getLangOpts().CurrentModule,
277 /*AllowSearch=*/false);
Douglas Gregor2b20cb82011-11-16 00:09:06 +0000278 if (!Module) {
279 CI.getDiagnostics().Report(diag::err_missing_module)
280 << CI.getLangOpts().CurrentModule << Filename;
281
282 return false;
283 }
Douglas Gregor1fb5c3a2011-12-31 04:05:44 +0000284
285 // Check whether we can build this module at all.
Richard Smitha3feee22013-10-28 22:18:19 +0000286 clang::Module::Requirement Requirement;
Daniel Jasper0761a8a2013-12-17 10:31:37 +0000287 clang::Module::HeaderDirective MissingHeader;
288 if (!Module->isAvailable(CI.getLangOpts(), CI.getTarget(), Requirement,
289 MissingHeader)) {
290 if (MissingHeader.FileNameLoc.isValid()) {
Ben Langmuirec8c9752014-04-18 22:07:31 +0000291 CI.getDiagnostics().Report(MissingHeader.FileNameLoc,
292 diag::err_module_header_missing)
Daniel Jasper0761a8a2013-12-17 10:31:37 +0000293 << MissingHeader.IsUmbrella << MissingHeader.FileName;
294 } else {
295 CI.getDiagnostics().Report(diag::err_module_unavailable)
296 << Module->getFullModuleName()
297 << Requirement.second << Requirement.first;
298 }
Douglas Gregor1fb5c3a2011-12-31 04:05:44 +0000299
300 return false;
301 }
302
Ben Langmuirbeee15e2014-04-14 18:00:01 +0000303 if (!ModuleMapForUniquing)
304 ModuleMapForUniquing = ModuleMap;
305 Module->ModuleMap = ModuleMapForUniquing;
306 assert(Module->ModuleMap && "missing module map file");
307
Argyrios Kyrtzidis130190f2012-10-10 02:12:39 +0000308 FileManager &FileMgr = CI.getFileManager();
309
Douglas Gregor4332b322011-11-16 17:04:00 +0000310 // Collect the set of #includes we need to build the module.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000311 SmallString<256> HeaderContents;
Richard Smith723928c2014-03-11 02:02:47 +0000312 llvm::error_code Err = llvm::error_code::success();
Argyrios Kyrtzidis130190f2012-10-10 02:12:39 +0000313 if (const FileEntry *UmbrellaHeader = Module->getUmbrellaHeader())
Richard Smith723928c2014-03-11 02:02:47 +0000314 Err = addHeaderInclude(UmbrellaHeader, HeaderContents, CI.getLangOpts(),
315 Module->IsExternC);
316 if (!Err)
317 Err = collectModuleHeaderIncludes(
318 CI.getLangOpts(), FileMgr,
319 CI.getPreprocessor().getHeaderSearchInfo().getModuleMap(), Module,
320 HeaderContents);
321
322 if (Err) {
323 CI.getDiagnostics().Report(diag::err_module_cannot_create_includes)
324 << Module->getFullModuleName() << Err.message();
325 return false;
326 }
Douglas Gregor4332b322011-11-16 17:04:00 +0000327
Argyrios Kyrtzidis52595242012-11-15 18:57:27 +0000328 llvm::MemoryBuffer *InputBuffer =
329 llvm::MemoryBuffer::getMemBufferCopy(HeaderContents,
330 Module::getModuleInputBufferName());
Alp Tokerf6a24ce2013-12-05 16:25:25 +0000331 // Ownership of InputBuffer will be transferred to the SourceManager.
Argyrios Kyrtzidis52595242012-11-15 18:57:27 +0000332 setCurrentInput(FrontendInputFile(InputBuffer, getCurrentFileKind(),
Douglas Gregora686e1b2012-01-27 19:52:33 +0000333 Module->IsSystem));
Douglas Gregor2b20cb82011-11-16 00:09:06 +0000334 return true;
335}
336
337bool GenerateModuleAction::ComputeASTConsumerArguments(CompilerInstance &CI,
338 StringRef InFile,
339 std::string &Sysroot,
340 std::string &OutputFile,
341 raw_ostream *&OS) {
342 // If no output file was provided, figure out where this module would go
343 // in the module cache.
344 if (CI.getFrontendOpts().OutputFile.empty()) {
345 HeaderSearch &HS = CI.getPreprocessor().getHeaderSearchInfo();
Ben Langmuirbeee15e2014-04-14 18:00:01 +0000346 CI.getFrontendOpts().OutputFile =
347 HS.getModuleFileName(CI.getLangOpts().CurrentModule,
348 ModuleMapForUniquing->getName());
Douglas Gregor2b20cb82011-11-16 00:09:06 +0000349 }
350
351 // We use createOutputFile here because this is exposed via libclang, and we
352 // must disable the RemoveFileOnSignal behavior.
353 // We use a temporary to avoid race conditions.
354 OS = CI.createOutputFile(CI.getFrontendOpts().OutputFile, /*Binary=*/true,
355 /*RemoveFileOnSignal=*/false, InFile,
Daniel Dunbarb9c62c02012-03-03 00:36:02 +0000356 /*Extension=*/"", /*useTemporary=*/true,
357 /*CreateMissingDirectories=*/true);
Douglas Gregor2b20cb82011-11-16 00:09:06 +0000358 if (!OS)
359 return true;
360
361 OutputFile = CI.getFrontendOpts().OutputFile;
362 return false;
363}
364
Daniel Dunbar02bd2d72009-11-14 10:42:46 +0000365ASTConsumer *SyntaxOnlyAction::CreateASTConsumer(CompilerInstance &CI,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000366 StringRef InFile) {
Daniel Dunbar02bd2d72009-11-14 10:42:46 +0000367 return new ASTConsumer();
368}
369
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000370ASTConsumer *DumpModuleInfoAction::CreateASTConsumer(CompilerInstance &CI,
371 StringRef InFile) {
372 return new ASTConsumer();
373}
374
Ben Langmuir2cb4a782014-02-05 22:21:15 +0000375ASTConsumer *VerifyPCHAction::CreateASTConsumer(CompilerInstance &CI,
376 StringRef InFile) {
377 return new ASTConsumer();
378}
379
380void VerifyPCHAction::ExecuteAction() {
Ben Langmuir3d4417c2014-02-07 17:31:11 +0000381 CompilerInstance &CI = getCompilerInstance();
382 bool Preamble = CI.getPreprocessorOpts().PrecompiledPreambleBytes.first != 0;
383 const std::string &Sysroot = CI.getHeaderSearchOpts().Sysroot;
Ahmed Charlesb8984322014-03-07 20:03:18 +0000384 std::unique_ptr<ASTReader> Reader(
385 new ASTReader(CI.getPreprocessor(), CI.getASTContext(),
386 Sysroot.empty() ? "" : Sysroot.c_str(),
387 /*DisableValidation*/ false,
388 /*AllowPCHWithCompilerErrors*/ false,
389 /*AllowConfigurationMismatch*/ true,
390 /*ValidateSystemInputs*/ true));
Ben Langmuir3d4417c2014-02-07 17:31:11 +0000391
392 Reader->ReadAST(getCurrentFile(),
393 Preamble ? serialization::MK_Preamble
394 : serialization::MK_PCH,
395 SourceLocation(),
396 ASTReader::ARR_ConfigurationMismatch);
Ben Langmuir2cb4a782014-02-05 22:21:15 +0000397}
398
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000399namespace {
400 /// \brief AST reader listener that dumps module information for a module
401 /// file.
402 class DumpModuleInfoListener : public ASTReaderListener {
403 llvm::raw_ostream &Out;
404
405 public:
406 DumpModuleInfoListener(llvm::raw_ostream &Out) : Out(Out) { }
407
408#define DUMP_BOOLEAN(Value, Text) \
409 Out.indent(4) << Text << ": " << (Value? "Yes" : "No") << "\n"
410
Craig Topperafa7cb32014-03-13 06:07:04 +0000411 bool ReadFullVersionInformation(StringRef FullVersion) override {
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000412 Out.indent(2)
413 << "Generated by "
414 << (FullVersion == getClangFullRepositoryVersion()? "this"
415 : "a different")
416 << " Clang: " << FullVersion << "\n";
417 return ASTReaderListener::ReadFullVersionInformation(FullVersion);
418 }
419
Ben Langmuir4f5212a2014-04-14 22:12:44 +0000420 void ReadModuleName(StringRef ModuleName) override {
421 Out.indent(2) << "Module name: " << ModuleName << "\n";
422 }
423 void ReadModuleMapFile(StringRef ModuleMapPath) override {
424 Out.indent(2) << "Module map file: " << ModuleMapPath << "\n";
425 }
426
Craig Topperafa7cb32014-03-13 06:07:04 +0000427 bool ReadLanguageOptions(const LangOptions &LangOpts,
428 bool Complain) override {
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000429 Out.indent(2) << "Language options:\n";
430#define LANGOPT(Name, Bits, Default, Description) \
431 DUMP_BOOLEAN(LangOpts.Name, Description);
432#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
433 Out.indent(4) << Description << ": " \
434 << static_cast<unsigned>(LangOpts.get##Name()) << "\n";
435#define VALUE_LANGOPT(Name, Bits, Default, Description) \
436 Out.indent(4) << Description << ": " << LangOpts.Name << "\n";
437#define BENIGN_LANGOPT(Name, Bits, Default, Description)
438#define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
439#include "clang/Basic/LangOptions.def"
440 return false;
441 }
442
Craig Topperafa7cb32014-03-13 06:07:04 +0000443 bool ReadTargetOptions(const TargetOptions &TargetOpts,
444 bool Complain) override {
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000445 Out.indent(2) << "Target options:\n";
446 Out.indent(4) << " Triple: " << TargetOpts.Triple << "\n";
447 Out.indent(4) << " CPU: " << TargetOpts.CPU << "\n";
448 Out.indent(4) << " ABI: " << TargetOpts.ABI << "\n";
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000449 Out.indent(4) << " Linker version: " << TargetOpts.LinkerVersion << "\n";
450
451 if (!TargetOpts.FeaturesAsWritten.empty()) {
452 Out.indent(4) << "Target features:\n";
453 for (unsigned I = 0, N = TargetOpts.FeaturesAsWritten.size();
454 I != N; ++I) {
455 Out.indent(6) << TargetOpts.FeaturesAsWritten[I] << "\n";
456 }
457 }
458
459 return false;
460 }
461
Craig Topperafa7cb32014-03-13 06:07:04 +0000462 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
463 bool Complain) override {
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000464 Out.indent(2) << "Header search options:\n";
465 Out.indent(4) << "System root [-isysroot=]: '" << HSOpts.Sysroot << "'\n";
466 DUMP_BOOLEAN(HSOpts.UseBuiltinIncludes,
467 "Use builtin include directories [-nobuiltininc]");
468 DUMP_BOOLEAN(HSOpts.UseStandardSystemIncludes,
469 "Use standard system include directories [-nostdinc]");
470 DUMP_BOOLEAN(HSOpts.UseStandardCXXIncludes,
471 "Use standard C++ include directories [-nostdinc++]");
472 DUMP_BOOLEAN(HSOpts.UseLibcxx,
473 "Use libc++ (rather than libstdc++) [-stdlib=]");
474 return false;
475 }
476
Craig Topperafa7cb32014-03-13 06:07:04 +0000477 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
478 bool Complain,
479 std::string &SuggestedPredefines) override {
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000480 Out.indent(2) << "Preprocessor options:\n";
481 DUMP_BOOLEAN(PPOpts.UsePredefines,
482 "Uses compiler/target-specific predefines [-undef]");
483 DUMP_BOOLEAN(PPOpts.DetailedRecord,
484 "Uses detailed preprocessing record (for indexing)");
485
486 if (!PPOpts.Macros.empty()) {
487 Out.indent(4) << "Predefined macros:\n";
488 }
489
490 for (std::vector<std::pair<std::string, bool/*isUndef*/> >::const_iterator
491 I = PPOpts.Macros.begin(), IEnd = PPOpts.Macros.end();
492 I != IEnd; ++I) {
493 Out.indent(6);
494 if (I->second)
495 Out << "-U";
496 else
497 Out << "-D";
498 Out << I->first << "\n";
499 }
500 return false;
501 }
502#undef DUMP_BOOLEAN
503 };
504}
505
506void DumpModuleInfoAction::ExecuteAction() {
507 // Set up the output file.
Ahmed Charlesb8984322014-03-07 20:03:18 +0000508 std::unique_ptr<llvm::raw_fd_ostream> OutFile;
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000509 StringRef OutputFileName = getCompilerInstance().getFrontendOpts().OutputFile;
510 if (!OutputFileName.empty() && OutputFileName != "-") {
511 std::string ErrorInfo;
512 OutFile.reset(new llvm::raw_fd_ostream(OutputFileName.str().c_str(),
Rafael Espindola4fbd3732014-02-24 18:20:21 +0000513 ErrorInfo, llvm::sys::fs::F_Text));
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000514 }
515 llvm::raw_ostream &Out = OutFile.get()? *OutFile.get() : llvm::outs();
516
517 Out << "Information for module file '" << getCurrentFile() << "':\n";
518 DumpModuleInfoListener Listener(Out);
519 ASTReader::readASTFileControlBlock(getCurrentFile(),
520 getCompilerInstance().getFileManager(),
521 Listener);
522}
523
Daniel Dunbar88357802009-11-14 10:42:57 +0000524//===----------------------------------------------------------------------===//
525// Preprocessor Actions
526//===----------------------------------------------------------------------===//
527
528void DumpRawTokensAction::ExecuteAction() {
529 Preprocessor &PP = getCompilerInstance().getPreprocessor();
530 SourceManager &SM = PP.getSourceManager();
531
532 // Start lexing the specified input file.
Chris Lattner710bb872009-11-30 04:18:44 +0000533 const llvm::MemoryBuffer *FromFile = SM.getBuffer(SM.getMainFileID());
David Blaikiebbafb8a2012-03-11 07:00:24 +0000534 Lexer RawLex(SM.getMainFileID(), FromFile, SM, PP.getLangOpts());
Daniel Dunbar88357802009-11-14 10:42:57 +0000535 RawLex.SetKeepWhitespaceMode(true);
536
537 Token RawTok;
538 RawLex.LexFromRawLexer(RawTok);
539 while (RawTok.isNot(tok::eof)) {
540 PP.DumpToken(RawTok, true);
Daniel Dunbar75024622009-11-25 10:27:48 +0000541 llvm::errs() << "\n";
Daniel Dunbar88357802009-11-14 10:42:57 +0000542 RawLex.LexFromRawLexer(RawTok);
543 }
544}
545
546void DumpTokensAction::ExecuteAction() {
547 Preprocessor &PP = getCompilerInstance().getPreprocessor();
548 // Start preprocessing the specified input file.
549 Token Tok;
Chris Lattnerfb24a3a2010-04-20 20:35:58 +0000550 PP.EnterMainSourceFile();
Daniel Dunbar88357802009-11-14 10:42:57 +0000551 do {
552 PP.Lex(Tok);
553 PP.DumpToken(Tok, true);
Daniel Dunbar75024622009-11-25 10:27:48 +0000554 llvm::errs() << "\n";
Daniel Dunbar88357802009-11-14 10:42:57 +0000555 } while (Tok.isNot(tok::eof));
556}
557
558void GeneratePTHAction::ExecuteAction() {
559 CompilerInstance &CI = getCompilerInstance();
560 if (CI.getFrontendOpts().OutputFile.empty() ||
561 CI.getFrontendOpts().OutputFile == "-") {
562 // FIXME: Don't fail this way.
563 // FIXME: Verify that we can actually seek in the given file.
Chris Lattner4b73cfa2010-04-07 22:58:06 +0000564 llvm::report_fatal_error("PTH requires a seekable file for output!");
Daniel Dunbar88357802009-11-14 10:42:57 +0000565 }
566 llvm::raw_fd_ostream *OS =
567 CI.createDefaultOutputFile(true, getCurrentFile());
Daniel Dunbar75546992009-12-03 09:13:30 +0000568 if (!OS) return;
569
Daniel Dunbar88357802009-11-14 10:42:57 +0000570 CacheTokens(CI.getPreprocessor(), OS);
571}
572
Daniel Dunbar88357802009-11-14 10:42:57 +0000573void PreprocessOnlyAction::ExecuteAction() {
574 Preprocessor &PP = getCompilerInstance().getPreprocessor();
575
Daniel Dunbard839e772010-06-11 20:10:12 +0000576 // Ignore unknown pragmas.
NAKAMURA Takumiddc86792013-12-04 11:12:26 +0000577 PP.AddPragmaHandler(new EmptyPragmaHandler());
Daniel Dunbard839e772010-06-11 20:10:12 +0000578
Daniel Dunbar88357802009-11-14 10:42:57 +0000579 Token Tok;
580 // Start parsing the specified input file.
Chris Lattnerfb24a3a2010-04-20 20:35:58 +0000581 PP.EnterMainSourceFile();
Daniel Dunbar88357802009-11-14 10:42:57 +0000582 do {
583 PP.Lex(Tok);
584 } while (Tok.isNot(tok::eof));
585}
586
Daniel Dunbar88357802009-11-14 10:42:57 +0000587void PrintPreprocessedAction::ExecuteAction() {
588 CompilerInstance &CI = getCompilerInstance();
Douglas Gregor52da28b2011-09-23 23:43:36 +0000589 // Output file may need to be set to 'Binary', to avoid converting Unix style
Steve Naroff3d38a682010-01-05 17:33:23 +0000590 // line feeds (<LF>) to Microsoft style line feeds (<CR><LF>).
Douglas Gregor52da28b2011-09-23 23:43:36 +0000591 //
592 // Look to see what type of line endings the file uses. If there's a
593 // CRLF, then we won't open the file up in binary mode. If there is
594 // just an LF or CR, then we will open the file up in binary mode.
595 // In this fashion, the output format should match the input format, unless
596 // the input format has inconsistent line endings.
597 //
598 // This should be a relatively fast operation since most files won't have
599 // all of their source code on a single line. However, that is still a
600 // concern, so if we scan for too long, we'll just assume the file should
601 // be opened in binary mode.
602 bool BinaryMode = true;
603 bool InvalidFile = false;
604 const SourceManager& SM = CI.getSourceManager();
605 const llvm::MemoryBuffer *Buffer = SM.getBuffer(SM.getMainFileID(),
606 &InvalidFile);
607 if (!InvalidFile) {
608 const char *cur = Buffer->getBufferStart();
609 const char *end = Buffer->getBufferEnd();
610 const char *next = (cur != end) ? cur + 1 : end;
611
612 // Limit ourselves to only scanning 256 characters into the source
613 // file. This is mostly a sanity check in case the file has no
614 // newlines whatsoever.
615 if (end - cur > 256) end = cur + 256;
616
617 while (next < end) {
618 if (*cur == 0x0D) { // CR
619 if (*next == 0x0A) // CRLF
620 BinaryMode = false;
621
622 break;
623 } else if (*cur == 0x0A) // LF
624 break;
625
626 ++cur, ++next;
627 }
628 }
629
630 raw_ostream *OS = CI.createDefaultOutputFile(BinaryMode, getCurrentFile());
Daniel Dunbar75546992009-12-03 09:13:30 +0000631 if (!OS) return;
632
Daniel Dunbar88357802009-11-14 10:42:57 +0000633 DoPrintPreprocessedInput(CI.getPreprocessor(), OS,
634 CI.getPreprocessorOutputOpts());
635}
Douglas Gregoraf82e352010-07-20 20:18:03 +0000636
637void PrintPreambleAction::ExecuteAction() {
638 switch (getCurrentFileKind()) {
639 case IK_C:
640 case IK_CXX:
641 case IK_ObjC:
642 case IK_ObjCXX:
643 case IK_OpenCL:
Peter Collingbourne62089b82010-12-01 03:15:20 +0000644 case IK_CUDA:
Douglas Gregoraf82e352010-07-20 20:18:03 +0000645 break;
646
647 case IK_None:
648 case IK_Asm:
649 case IK_PreprocessedC:
650 case IK_PreprocessedCXX:
651 case IK_PreprocessedObjC:
652 case IK_PreprocessedObjCXX:
653 case IK_AST:
654 case IK_LLVM_IR:
655 // We can't do anything with these.
656 return;
657 }
658
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000659 CompilerInstance &CI = getCompilerInstance();
660 llvm::MemoryBuffer *Buffer
Chris Lattner5159f612010-11-23 08:35:12 +0000661 = CI.getFileManager().getBufferForFile(getCurrentFile());
Douglas Gregoraf82e352010-07-20 20:18:03 +0000662 if (Buffer) {
Argyrios Kyrtzidis7aecbc72011-08-25 20:39:19 +0000663 unsigned Preamble = Lexer::ComputePreamble(Buffer, CI.getLangOpts()).first;
Douglas Gregoraf82e352010-07-20 20:18:03 +0000664 llvm::outs().write(Buffer->getBufferStart(), Preamble);
665 delete Buffer;
666 }
667}