blob: 2657c9878b8e7db05440d622de2b4e0d234f48d4 [file] [log] [blame]
Daniel Dunbar8305d012009-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 Dunbar8305d012009-11-14 10:42:46 +000013#include "clang/Frontend/ASTConsumers.h"
14#include "clang/Frontend/ASTUnit.h"
15#include "clang/Frontend/CompilerInstance.h"
Daniel Dunbar8305d012009-11-14 10:42:46 +000016#include "clang/Frontend/FrontendDiagnostic.h"
17#include "clang/Frontend/Utils.h"
Chandler Carruth55fc8732012-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 Gregorc544ba02013-03-27 16:47:18 +000022#include "clang/Serialization/ASTReader.h"
Sebastian Redl7faa2ec2010-08-18 23:56:37 +000023#include "clang/Serialization/ASTWriter.h"
Douglas Gregor77d029f2011-12-08 19:11:24 +000024#include "llvm/Support/FileSystem.h"
Douglas Gregorf033f1d2010-07-20 20:18:03 +000025#include "llvm/Support/MemoryBuffer.h"
Daniel Dunbar8305d012009-11-14 10:42:46 +000026#include "llvm/Support/raw_ostream.h"
Douglas Gregor10efbaf2011-09-23 23:43:36 +000027#include "llvm/Support/system_error.h"
Stephen Hines651f13c2014-04-23 16:59:28 -070028#include <memory>
Douglas Gregor10efbaf2011-09-23 23:43:36 +000029
Daniel Dunbar8305d012009-11-14 10:42:46 +000030using namespace clang;
31
Daniel Dunbar5f3b9972009-11-14 10:42:57 +000032//===----------------------------------------------------------------------===//
Daniel Dunbar27585952010-03-19 19:44:04 +000033// Custom Actions
34//===----------------------------------------------------------------------===//
35
36ASTConsumer *InitOnlyAction::CreateASTConsumer(CompilerInstance &CI,
Chris Lattner5f9e2722011-07-23 10:55:15 +000037 StringRef InFile) {
Daniel Dunbar27585952010-03-19 19:44:04 +000038 return new ASTConsumer();
39}
40
41void InitOnlyAction::ExecuteAction() {
42}
43
44//===----------------------------------------------------------------------===//
Daniel Dunbar5f3b9972009-11-14 10:42:57 +000045// AST Consumer Actions
46//===----------------------------------------------------------------------===//
47
Daniel Dunbar8305d012009-11-14 10:42:46 +000048ASTConsumer *ASTPrintAction::CreateASTConsumer(CompilerInstance &CI,
Chris Lattner5f9e2722011-07-23 10:55:15 +000049 StringRef InFile) {
50 if (raw_ostream *OS = CI.createDefaultOutputFile(false, InFile))
Alexander Kornienkoe34a0522012-07-26 16:01:23 +000051 return CreateASTPrinter(OS, CI.getFrontendOpts().ASTDumpFilter);
Daniel Dunbar36043592009-12-03 09:13:30 +000052 return 0;
Daniel Dunbar8305d012009-11-14 10:42:46 +000053}
54
Daniel Dunbar8305d012009-11-14 10:42:46 +000055ASTConsumer *ASTDumpAction::CreateASTConsumer(CompilerInstance &CI,
Chris Lattner5f9e2722011-07-23 10:55:15 +000056 StringRef InFile) {
Richard Smithab297cc2013-06-24 01:45:33 +000057 return CreateASTDumper(CI.getFrontendOpts().ASTDumpFilter,
58 CI.getFrontendOpts().ASTDumpLookups);
Daniel Dunbar8305d012009-11-14 10:42:46 +000059}
60
Alexander Kornienko171af642012-07-31 09:37:40 +000061ASTConsumer *ASTDeclListAction::CreateASTConsumer(CompilerInstance &CI,
62 StringRef InFile) {
63 return CreateASTDeclNodeLister();
64}
65
Daniel Dunbar8305d012009-11-14 10:42:46 +000066ASTConsumer *ASTViewAction::CreateASTConsumer(CompilerInstance &CI,
Chris Lattner5f9e2722011-07-23 10:55:15 +000067 StringRef InFile) {
Daniel Dunbar8305d012009-11-14 10:42:46 +000068 return CreateASTViewer();
69}
70
71ASTConsumer *DeclContextPrintAction::CreateASTConsumer(CompilerInstance &CI,
Chris Lattner5f9e2722011-07-23 10:55:15 +000072 StringRef InFile) {
Daniel Dunbar8305d012009-11-14 10:42:46 +000073 return CreateDeclContextPrinter();
74}
75
Daniel Dunbar8305d012009-11-14 10:42:46 +000076ASTConsumer *GeneratePCHAction::CreateASTConsumer(CompilerInstance &CI,
Chris Lattner5f9e2722011-07-23 10:55:15 +000077 StringRef InFile) {
Douglas Gregor1d715ac2010-08-03 08:14:03 +000078 std::string Sysroot;
Argyrios Kyrtzidis8e3df4d2011-02-15 17:54:22 +000079 std::string OutputFile;
Chris Lattner5f9e2722011-07-23 10:55:15 +000080 raw_ostream *OS = 0;
Douglas Gregor9293ba82011-08-25 22:35:51 +000081 if (ComputeASTConsumerArguments(CI, InFile, Sysroot, OutputFile, OS))
Daniel Dunbar8305d012009-11-14 10:42:46 +000082 return 0;
Douglas Gregor1d715ac2010-08-03 08:14:03 +000083
Douglas Gregor832d6202011-07-22 16:35:34 +000084 if (!CI.getFrontendOpts().RelocatablePCH)
85 Sysroot.clear();
Douglas Gregora8cc6ce2011-11-30 04:39:39 +000086 return new PCHGenerator(CI.getPreprocessor(), OutputFile, 0, Sysroot, OS);
Douglas Gregor1d715ac2010-08-03 08:14:03 +000087}
88
89bool GeneratePCHAction::ComputeASTConsumerArguments(CompilerInstance &CI,
Chris Lattner5f9e2722011-07-23 10:55:15 +000090 StringRef InFile,
Douglas Gregor1d715ac2010-08-03 08:14:03 +000091 std::string &Sysroot,
Argyrios Kyrtzidis8e3df4d2011-02-15 17:54:22 +000092 std::string &OutputFile,
Douglas Gregor9293ba82011-08-25 22:35:51 +000093 raw_ostream *&OS) {
Douglas Gregor1d715ac2010-08-03 08:14:03 +000094 Sysroot = CI.getHeaderSearchOpts().Sysroot;
95 if (CI.getFrontendOpts().RelocatablePCH && Sysroot.empty()) {
Sebastian Redl11c3dc42010-08-17 17:55:38 +000096 CI.getDiagnostics().Report(diag::err_relocatable_without_isysroot);
Douglas Gregor1d715ac2010-08-03 08:14:03 +000097 return true;
Daniel Dunbar8305d012009-11-14 10:42:46 +000098 }
99
Daniel Dunbarc7a9cda2011-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 Kyrtzidis7e909852011-07-28 00:45:10 +0000102 // We use a temporary to avoid race conditions.
Daniel Dunbarc7a9cda2011-01-31 22:00:44 +0000103 OS = CI.createOutputFile(CI.getFrontendOpts().OutputFile, /*Binary=*/true,
Argyrios Kyrtzidis7e909852011-07-28 00:45:10 +0000104 /*RemoveFileOnSignal=*/false, InFile,
105 /*Extension=*/"", /*useTemporary=*/true);
Daniel Dunbar36043592009-12-03 09:13:30 +0000106 if (!OS)
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000107 return true;
Daniel Dunbar36043592009-12-03 09:13:30 +0000108
Argyrios Kyrtzidis8e3df4d2011-02-15 17:54:22 +0000109 OutputFile = CI.getFrontendOpts().OutputFile;
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000110 return false;
Daniel Dunbar8305d012009-11-14 10:42:46 +0000111}
112
Douglas Gregordb1cde72011-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 Gregora8cc6ce2011-11-30 04:39:39 +0000121 return new PCHGenerator(CI.getPreprocessor(), OutputFile, Module,
Douglas Gregordb1cde72011-11-16 00:09:06 +0000122 Sysroot, OS);
123}
124
Argyrios Kyrtzidis2a857182012-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
Stephen Hines651f13c2014-04-23 16:59:28 -0700131static llvm::error_code addHeaderInclude(StringRef HeaderName,
132 SmallVectorImpl<char> &Includes,
133 const LangOptions &LangOpts,
134 bool IsExternC) {
135 if (IsExternC && LangOpts.CPlusPlus)
136 Includes += "extern \"C\" {\n";
Argyrios Kyrtzidis2a857182012-10-10 02:12:39 +0000137 if (LangOpts.ObjC1)
138 Includes += "#import \"";
139 else
140 Includes += "#include \"";
Stephen Hines651f13c2014-04-23 16:59:28 -0700141 // 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 Kyrtzidis2a857182012-10-10 02:12:39 +0000152 Includes += "\"\n";
Stephen Hines651f13c2014-04-23 16:59:28 -0700153 if (IsExternC && LangOpts.CPlusPlus)
154 Includes += "}\n";
155 return llvm::error_code::success();
Argyrios Kyrtzidis2a857182012-10-10 02:12:39 +0000156}
157
Stephen Hines651f13c2014-04-23 16:59:28 -0700158static 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 Kyrtzidis2a857182012-10-10 02:12:39 +0000163}
164
Douglas Gregor261e75b2011-11-16 17:04:00 +0000165/// \brief Collect the set of header includes needed to construct the given
Argyrios Kyrtzidisc7782d92012-10-05 00:22:33 +0000166/// module and update the TopHeaders file set of the module.
Douglas Gregor261e75b2011-11-16 17:04:00 +0000167///
168/// \param Module The module we're collecting includes from.
Douglas Gregor8075ce62011-12-06 17:15:11 +0000169///
James Dennett5e9dda62012-06-15 21:48:19 +0000170/// \param Includes Will be augmented with the set of \#includes or \#imports
Douglas Gregor8075ce62011-12-06 17:15:11 +0000171/// needed to load all of the named headers.
Stephen Hines651f13c2014-04-23 16:59:28 -0700172static llvm::error_code
173collectModuleHeaderIncludes(const LangOptions &LangOpts, FileManager &FileMgr,
174 ModuleMap &ModMap, clang::Module *Module,
175 SmallVectorImpl<char> &Includes) {
Douglas Gregor51f564f2011-12-31 04:05:44 +0000176 // Don't collect any headers for unavailable modules.
177 if (!Module->isAvailable())
Stephen Hines651f13c2014-04-23 16:59:28 -0700178 return llvm::error_code::success();
Douglas Gregor51f564f2011-12-31 04:05:44 +0000179
Douglas Gregor8075ce62011-12-06 17:15:11 +0000180 // Add includes for each of these headers.
Lawrence Crowlbc3f6282013-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 Kyrtzidisc1d22392013-03-13 21:13:43 +0000183 Module->addTopHeader(Header);
Stephen Hines651f13c2014-04-23 16:59:28 -0700184 if (llvm::error_code Err =
185 addHeaderInclude(Header, Includes, LangOpts, Module->IsExternC))
186 return Err;
Douglas Gregor2f04f182012-02-02 18:42:48 +0000187 }
Lawrence Crowlbc3f6282013-06-20 21:14:14 +0000188 // Note that Module->PrivateHeaders will not be a TopHeader.
Douglas Gregor8075ce62011-12-06 17:15:11 +0000189
Douglas Gregor10694ce2011-12-08 17:39:04 +0000190 if (const FileEntry *UmbrellaHeader = Module->getUmbrellaHeader()) {
Argyrios Kyrtzidisc1d22392013-03-13 21:13:43 +0000191 Module->addTopHeader(UmbrellaHeader);
Douglas Gregor2f04f182012-02-02 18:42:48 +0000192 if (Module->Parent) {
193 // Include the umbrella header for submodules.
Stephen Hines651f13c2014-04-23 16:59:28 -0700194 if (llvm::error_code Err = addHeaderInclude(UmbrellaHeader, Includes,
195 LangOpts, Module->IsExternC))
196 return Err;
Douglas Gregor2f04f182012-02-02 18:42:48 +0000197 }
Douglas Gregor77d029f2011-12-08 19:11:24 +0000198 } else if (const DirectoryEntry *UmbrellaDir = Module->getUmbrellaDir()) {
Douglas Gregor752769f2012-01-05 00:04:05 +0000199 // Add all of the headers we find in this subdirectory.
Douglas Gregor77d029f2011-12-08 19:11:24 +0000200 llvm::error_code EC;
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000201 SmallString<128> DirNative;
Douglas Gregor77d029f2011-12-08 19:11:24 +0000202 llvm::sys::path::native(UmbrellaDir->getName(), DirNative);
Douglas Gregor3b29bb92011-12-12 19:13:53 +0000203 for (llvm::sys::fs::recursive_directory_iterator Dir(DirNative.str(), EC),
204 DirEnd;
Douglas Gregor77d029f2011-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 Gregor752769f2012-01-05 00:04:05 +0000213 // If this header is marked 'unavailable' in this module, don't include
214 // it.
Argyrios Kyrtzidisc7782d92012-10-05 00:22:33 +0000215 if (const FileEntry *Header = FileMgr.getFile(Dir->path())) {
Douglas Gregor752769f2012-01-05 00:04:05 +0000216 if (ModMap.isHeaderInUnavailableModule(Header))
217 continue;
Argyrios Kyrtzidisc1d22392013-03-13 21:13:43 +0000218 Module->addTopHeader(Header);
Argyrios Kyrtzidisc7782d92012-10-05 00:22:33 +0000219 }
Douglas Gregor752769f2012-01-05 00:04:05 +0000220
Stephen Hines651f13c2014-04-23 16:59:28 -0700221 // 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 Gregor77d029f2011-12-08 19:11:24 +0000225 }
Stephen Hines651f13c2014-04-23 16:59:28 -0700226
227 if (EC)
228 return EC;
Douglas Gregor261e75b2011-11-16 17:04:00 +0000229 }
230
231 // Recurse into submodules.
Douglas Gregorb7a78192012-01-04 23:32:19 +0000232 for (clang::Module::submodule_iterator Sub = Module->submodule_begin(),
233 SubEnd = Module->submodule_end();
Douglas Gregor8075ce62011-12-06 17:15:11 +0000234 Sub != SubEnd; ++Sub)
Stephen Hines651f13c2014-04-23 16:59:28 -0700235 if (llvm::error_code Err = collectModuleHeaderIncludes(
236 LangOpts, FileMgr, ModMap, *Sub, Includes))
237 return Err;
238
239 return llvm::error_code::success();
Douglas Gregor261e75b2011-11-16 17:04:00 +0000240}
241
Douglas Gregordb1cde72011-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 Gregor8f5d7d12013-06-21 16:28:10 +0000254 if (HS.loadModuleMapFile(ModuleMap, IsSystem))
Douglas Gregordb1cde72011-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 }
Stephen Hines651f13c2014-04-23 16:59:28 -0700266
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 Gregordb1cde72011-11-16 00:09:06 +0000275 // Dig out the module definition.
Douglas Gregore434ec72012-01-29 17:08:11 +0000276 Module = HS.lookupModule(CI.getLangOpts().CurrentModule,
277 /*AllowSearch=*/false);
Douglas Gregordb1cde72011-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 Gregor51f564f2011-12-31 04:05:44 +0000284
285 // Check whether we can build this module at all.
Richard Smith5794b532013-10-28 22:18:19 +0000286 clang::Module::Requirement Requirement;
Stephen Hines651f13c2014-04-23 16:59:28 -0700287 clang::Module::HeaderDirective MissingHeader;
288 if (!Module->isAvailable(CI.getLangOpts(), CI.getTarget(), Requirement,
289 MissingHeader)) {
290 if (MissingHeader.FileNameLoc.isValid()) {
291 CI.getDiagnostics().Report(diag::err_module_header_missing)
292 << MissingHeader.IsUmbrella << MissingHeader.FileName;
293 } else {
294 CI.getDiagnostics().Report(diag::err_module_unavailable)
295 << Module->getFullModuleName()
296 << Requirement.second << Requirement.first;
297 }
Douglas Gregor51f564f2011-12-31 04:05:44 +0000298
299 return false;
300 }
301
Argyrios Kyrtzidis2a857182012-10-10 02:12:39 +0000302 FileManager &FileMgr = CI.getFileManager();
303
Douglas Gregor261e75b2011-11-16 17:04:00 +0000304 // Collect the set of #includes we need to build the module.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000305 SmallString<256> HeaderContents;
Stephen Hines651f13c2014-04-23 16:59:28 -0700306 llvm::error_code Err = llvm::error_code::success();
Argyrios Kyrtzidis2a857182012-10-10 02:12:39 +0000307 if (const FileEntry *UmbrellaHeader = Module->getUmbrellaHeader())
Stephen Hines651f13c2014-04-23 16:59:28 -0700308 Err = addHeaderInclude(UmbrellaHeader, HeaderContents, CI.getLangOpts(),
309 Module->IsExternC);
310 if (!Err)
311 Err = collectModuleHeaderIncludes(
312 CI.getLangOpts(), FileMgr,
313 CI.getPreprocessor().getHeaderSearchInfo().getModuleMap(), Module,
314 HeaderContents);
315
316 if (Err) {
317 CI.getDiagnostics().Report(diag::err_module_cannot_create_includes)
318 << Module->getFullModuleName() << Err.message();
319 return false;
320 }
Douglas Gregor261e75b2011-11-16 17:04:00 +0000321
Argyrios Kyrtzidis992d9172012-11-15 18:57:27 +0000322 llvm::MemoryBuffer *InputBuffer =
323 llvm::MemoryBuffer::getMemBufferCopy(HeaderContents,
324 Module::getModuleInputBufferName());
Stephen Hines651f13c2014-04-23 16:59:28 -0700325 // Ownership of InputBuffer will be transferred to the SourceManager.
Argyrios Kyrtzidis992d9172012-11-15 18:57:27 +0000326 setCurrentInput(FrontendInputFile(InputBuffer, getCurrentFileKind(),
Douglas Gregora1f1fad2012-01-27 19:52:33 +0000327 Module->IsSystem));
Douglas Gregordb1cde72011-11-16 00:09:06 +0000328 return true;
329}
330
331bool GenerateModuleAction::ComputeASTConsumerArguments(CompilerInstance &CI,
332 StringRef InFile,
333 std::string &Sysroot,
334 std::string &OutputFile,
335 raw_ostream *&OS) {
336 // If no output file was provided, figure out where this module would go
337 // in the module cache.
338 if (CI.getFrontendOpts().OutputFile.empty()) {
339 HeaderSearch &HS = CI.getPreprocessor().getHeaderSearchInfo();
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000340 SmallString<256> ModuleFileName(HS.getModuleCachePath());
Douglas Gregordb1cde72011-11-16 00:09:06 +0000341 llvm::sys::path::append(ModuleFileName,
342 CI.getLangOpts().CurrentModule + ".pcm");
343 CI.getFrontendOpts().OutputFile = ModuleFileName.str();
344 }
345
346 // We use createOutputFile here because this is exposed via libclang, and we
347 // must disable the RemoveFileOnSignal behavior.
348 // We use a temporary to avoid race conditions.
349 OS = CI.createOutputFile(CI.getFrontendOpts().OutputFile, /*Binary=*/true,
350 /*RemoveFileOnSignal=*/false, InFile,
Daniel Dunbar12f28ab2012-03-03 00:36:02 +0000351 /*Extension=*/"", /*useTemporary=*/true,
352 /*CreateMissingDirectories=*/true);
Douglas Gregordb1cde72011-11-16 00:09:06 +0000353 if (!OS)
354 return true;
355
356 OutputFile = CI.getFrontendOpts().OutputFile;
357 return false;
358}
359
Daniel Dunbar8305d012009-11-14 10:42:46 +0000360ASTConsumer *SyntaxOnlyAction::CreateASTConsumer(CompilerInstance &CI,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000361 StringRef InFile) {
Daniel Dunbar8305d012009-11-14 10:42:46 +0000362 return new ASTConsumer();
363}
364
Douglas Gregorc544ba02013-03-27 16:47:18 +0000365ASTConsumer *DumpModuleInfoAction::CreateASTConsumer(CompilerInstance &CI,
366 StringRef InFile) {
367 return new ASTConsumer();
368}
369
Stephen Hines651f13c2014-04-23 16:59:28 -0700370ASTConsumer *VerifyPCHAction::CreateASTConsumer(CompilerInstance &CI,
371 StringRef InFile) {
372 return new ASTConsumer();
373}
374
375void VerifyPCHAction::ExecuteAction() {
376 CompilerInstance &CI = getCompilerInstance();
377 bool Preamble = CI.getPreprocessorOpts().PrecompiledPreambleBytes.first != 0;
378 const std::string &Sysroot = CI.getHeaderSearchOpts().Sysroot;
379 std::unique_ptr<ASTReader> Reader(
380 new ASTReader(CI.getPreprocessor(), CI.getASTContext(),
381 Sysroot.empty() ? "" : Sysroot.c_str(),
382 /*DisableValidation*/ false,
383 /*AllowPCHWithCompilerErrors*/ false,
384 /*AllowConfigurationMismatch*/ true,
385 /*ValidateSystemInputs*/ true));
386
387 Reader->ReadAST(getCurrentFile(),
388 Preamble ? serialization::MK_Preamble
389 : serialization::MK_PCH,
390 SourceLocation(),
391 ASTReader::ARR_ConfigurationMismatch);
392}
393
Douglas Gregorc544ba02013-03-27 16:47:18 +0000394namespace {
395 /// \brief AST reader listener that dumps module information for a module
396 /// file.
397 class DumpModuleInfoListener : public ASTReaderListener {
398 llvm::raw_ostream &Out;
399
400 public:
401 DumpModuleInfoListener(llvm::raw_ostream &Out) : Out(Out) { }
402
403#define DUMP_BOOLEAN(Value, Text) \
404 Out.indent(4) << Text << ": " << (Value? "Yes" : "No") << "\n"
405
Stephen Hines651f13c2014-04-23 16:59:28 -0700406 bool ReadFullVersionInformation(StringRef FullVersion) override {
Douglas Gregorc544ba02013-03-27 16:47:18 +0000407 Out.indent(2)
408 << "Generated by "
409 << (FullVersion == getClangFullRepositoryVersion()? "this"
410 : "a different")
411 << " Clang: " << FullVersion << "\n";
412 return ASTReaderListener::ReadFullVersionInformation(FullVersion);
413 }
414
Stephen Hines651f13c2014-04-23 16:59:28 -0700415 bool ReadLanguageOptions(const LangOptions &LangOpts,
416 bool Complain) override {
Douglas Gregorc544ba02013-03-27 16:47:18 +0000417 Out.indent(2) << "Language options:\n";
418#define LANGOPT(Name, Bits, Default, Description) \
419 DUMP_BOOLEAN(LangOpts.Name, Description);
420#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
421 Out.indent(4) << Description << ": " \
422 << static_cast<unsigned>(LangOpts.get##Name()) << "\n";
423#define VALUE_LANGOPT(Name, Bits, Default, Description) \
424 Out.indent(4) << Description << ": " << LangOpts.Name << "\n";
425#define BENIGN_LANGOPT(Name, Bits, Default, Description)
426#define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
427#include "clang/Basic/LangOptions.def"
428 return false;
429 }
430
Stephen Hines651f13c2014-04-23 16:59:28 -0700431 bool ReadTargetOptions(const TargetOptions &TargetOpts,
432 bool Complain) override {
Douglas Gregorc544ba02013-03-27 16:47:18 +0000433 Out.indent(2) << "Target options:\n";
434 Out.indent(4) << " Triple: " << TargetOpts.Triple << "\n";
435 Out.indent(4) << " CPU: " << TargetOpts.CPU << "\n";
436 Out.indent(4) << " ABI: " << TargetOpts.ABI << "\n";
Douglas Gregorc544ba02013-03-27 16:47:18 +0000437 Out.indent(4) << " Linker version: " << TargetOpts.LinkerVersion << "\n";
438
439 if (!TargetOpts.FeaturesAsWritten.empty()) {
440 Out.indent(4) << "Target features:\n";
441 for (unsigned I = 0, N = TargetOpts.FeaturesAsWritten.size();
442 I != N; ++I) {
443 Out.indent(6) << TargetOpts.FeaturesAsWritten[I] << "\n";
444 }
445 }
446
447 return false;
448 }
449
Stephen Hines651f13c2014-04-23 16:59:28 -0700450 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
451 bool Complain) override {
Douglas Gregorc544ba02013-03-27 16:47:18 +0000452 Out.indent(2) << "Header search options:\n";
453 Out.indent(4) << "System root [-isysroot=]: '" << HSOpts.Sysroot << "'\n";
454 DUMP_BOOLEAN(HSOpts.UseBuiltinIncludes,
455 "Use builtin include directories [-nobuiltininc]");
456 DUMP_BOOLEAN(HSOpts.UseStandardSystemIncludes,
457 "Use standard system include directories [-nostdinc]");
458 DUMP_BOOLEAN(HSOpts.UseStandardCXXIncludes,
459 "Use standard C++ include directories [-nostdinc++]");
460 DUMP_BOOLEAN(HSOpts.UseLibcxx,
461 "Use libc++ (rather than libstdc++) [-stdlib=]");
462 return false;
463 }
464
Stephen Hines651f13c2014-04-23 16:59:28 -0700465 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
466 bool Complain,
467 std::string &SuggestedPredefines) override {
Douglas Gregorc544ba02013-03-27 16:47:18 +0000468 Out.indent(2) << "Preprocessor options:\n";
469 DUMP_BOOLEAN(PPOpts.UsePredefines,
470 "Uses compiler/target-specific predefines [-undef]");
471 DUMP_BOOLEAN(PPOpts.DetailedRecord,
472 "Uses detailed preprocessing record (for indexing)");
473
474 if (!PPOpts.Macros.empty()) {
475 Out.indent(4) << "Predefined macros:\n";
476 }
477
478 for (std::vector<std::pair<std::string, bool/*isUndef*/> >::const_iterator
479 I = PPOpts.Macros.begin(), IEnd = PPOpts.Macros.end();
480 I != IEnd; ++I) {
481 Out.indent(6);
482 if (I->second)
483 Out << "-U";
484 else
485 Out << "-D";
486 Out << I->first << "\n";
487 }
488 return false;
489 }
490#undef DUMP_BOOLEAN
491 };
492}
493
494void DumpModuleInfoAction::ExecuteAction() {
495 // Set up the output file.
Stephen Hines651f13c2014-04-23 16:59:28 -0700496 std::unique_ptr<llvm::raw_fd_ostream> OutFile;
Douglas Gregorc544ba02013-03-27 16:47:18 +0000497 StringRef OutputFileName = getCompilerInstance().getFrontendOpts().OutputFile;
498 if (!OutputFileName.empty() && OutputFileName != "-") {
499 std::string ErrorInfo;
500 OutFile.reset(new llvm::raw_fd_ostream(OutputFileName.str().c_str(),
Stephen Hines651f13c2014-04-23 16:59:28 -0700501 ErrorInfo, llvm::sys::fs::F_Text));
Douglas Gregorc544ba02013-03-27 16:47:18 +0000502 }
503 llvm::raw_ostream &Out = OutFile.get()? *OutFile.get() : llvm::outs();
504
505 Out << "Information for module file '" << getCurrentFile() << "':\n";
506 DumpModuleInfoListener Listener(Out);
507 ASTReader::readASTFileControlBlock(getCurrentFile(),
508 getCompilerInstance().getFileManager(),
509 Listener);
510}
511
Daniel Dunbar5f3b9972009-11-14 10:42:57 +0000512//===----------------------------------------------------------------------===//
513// Preprocessor Actions
514//===----------------------------------------------------------------------===//
515
516void DumpRawTokensAction::ExecuteAction() {
517 Preprocessor &PP = getCompilerInstance().getPreprocessor();
518 SourceManager &SM = PP.getSourceManager();
519
520 // Start lexing the specified input file.
Chris Lattner6e290142009-11-30 04:18:44 +0000521 const llvm::MemoryBuffer *FromFile = SM.getBuffer(SM.getMainFileID());
David Blaikie4e4d0842012-03-11 07:00:24 +0000522 Lexer RawLex(SM.getMainFileID(), FromFile, SM, PP.getLangOpts());
Daniel Dunbar5f3b9972009-11-14 10:42:57 +0000523 RawLex.SetKeepWhitespaceMode(true);
524
525 Token RawTok;
526 RawLex.LexFromRawLexer(RawTok);
527 while (RawTok.isNot(tok::eof)) {
528 PP.DumpToken(RawTok, true);
Daniel Dunbar33f57f82009-11-25 10:27:48 +0000529 llvm::errs() << "\n";
Daniel Dunbar5f3b9972009-11-14 10:42:57 +0000530 RawLex.LexFromRawLexer(RawTok);
531 }
532}
533
534void DumpTokensAction::ExecuteAction() {
535 Preprocessor &PP = getCompilerInstance().getPreprocessor();
536 // Start preprocessing the specified input file.
537 Token Tok;
Chris Lattnere127a0d2010-04-20 20:35:58 +0000538 PP.EnterMainSourceFile();
Daniel Dunbar5f3b9972009-11-14 10:42:57 +0000539 do {
540 PP.Lex(Tok);
541 PP.DumpToken(Tok, true);
Daniel Dunbar33f57f82009-11-25 10:27:48 +0000542 llvm::errs() << "\n";
Daniel Dunbar5f3b9972009-11-14 10:42:57 +0000543 } while (Tok.isNot(tok::eof));
544}
545
546void GeneratePTHAction::ExecuteAction() {
547 CompilerInstance &CI = getCompilerInstance();
548 if (CI.getFrontendOpts().OutputFile.empty() ||
549 CI.getFrontendOpts().OutputFile == "-") {
550 // FIXME: Don't fail this way.
551 // FIXME: Verify that we can actually seek in the given file.
Chris Lattner83e7a782010-04-07 22:58:06 +0000552 llvm::report_fatal_error("PTH requires a seekable file for output!");
Daniel Dunbar5f3b9972009-11-14 10:42:57 +0000553 }
554 llvm::raw_fd_ostream *OS =
555 CI.createDefaultOutputFile(true, getCurrentFile());
Daniel Dunbar36043592009-12-03 09:13:30 +0000556 if (!OS) return;
557
Daniel Dunbar5f3b9972009-11-14 10:42:57 +0000558 CacheTokens(CI.getPreprocessor(), OS);
559}
560
Daniel Dunbar5f3b9972009-11-14 10:42:57 +0000561void PreprocessOnlyAction::ExecuteAction() {
562 Preprocessor &PP = getCompilerInstance().getPreprocessor();
563
Daniel Dunbarc72cc502010-06-11 20:10:12 +0000564 // Ignore unknown pragmas.
Argyrios Kyrtzidis9b36c3f2010-07-13 09:07:17 +0000565 PP.AddPragmaHandler(new EmptyPragmaHandler());
Daniel Dunbarc72cc502010-06-11 20:10:12 +0000566
Daniel Dunbar5f3b9972009-11-14 10:42:57 +0000567 Token Tok;
568 // Start parsing the specified input file.
Chris Lattnere127a0d2010-04-20 20:35:58 +0000569 PP.EnterMainSourceFile();
Daniel Dunbar5f3b9972009-11-14 10:42:57 +0000570 do {
571 PP.Lex(Tok);
572 } while (Tok.isNot(tok::eof));
573}
574
Daniel Dunbar5f3b9972009-11-14 10:42:57 +0000575void PrintPreprocessedAction::ExecuteAction() {
576 CompilerInstance &CI = getCompilerInstance();
Douglas Gregor10efbaf2011-09-23 23:43:36 +0000577 // Output file may need to be set to 'Binary', to avoid converting Unix style
Steve Naroffd57d7c02010-01-05 17:33:23 +0000578 // line feeds (<LF>) to Microsoft style line feeds (<CR><LF>).
Douglas Gregor10efbaf2011-09-23 23:43:36 +0000579 //
580 // Look to see what type of line endings the file uses. If there's a
581 // CRLF, then we won't open the file up in binary mode. If there is
582 // just an LF or CR, then we will open the file up in binary mode.
583 // In this fashion, the output format should match the input format, unless
584 // the input format has inconsistent line endings.
585 //
586 // This should be a relatively fast operation since most files won't have
587 // all of their source code on a single line. However, that is still a
588 // concern, so if we scan for too long, we'll just assume the file should
589 // be opened in binary mode.
590 bool BinaryMode = true;
591 bool InvalidFile = false;
592 const SourceManager& SM = CI.getSourceManager();
593 const llvm::MemoryBuffer *Buffer = SM.getBuffer(SM.getMainFileID(),
594 &InvalidFile);
595 if (!InvalidFile) {
596 const char *cur = Buffer->getBufferStart();
597 const char *end = Buffer->getBufferEnd();
598 const char *next = (cur != end) ? cur + 1 : end;
599
600 // Limit ourselves to only scanning 256 characters into the source
601 // file. This is mostly a sanity check in case the file has no
602 // newlines whatsoever.
603 if (end - cur > 256) end = cur + 256;
604
605 while (next < end) {
606 if (*cur == 0x0D) { // CR
607 if (*next == 0x0A) // CRLF
608 BinaryMode = false;
609
610 break;
611 } else if (*cur == 0x0A) // LF
612 break;
613
614 ++cur, ++next;
615 }
616 }
617
618 raw_ostream *OS = CI.createDefaultOutputFile(BinaryMode, getCurrentFile());
Daniel Dunbar36043592009-12-03 09:13:30 +0000619 if (!OS) return;
620
Daniel Dunbar5f3b9972009-11-14 10:42:57 +0000621 DoPrintPreprocessedInput(CI.getPreprocessor(), OS,
622 CI.getPreprocessorOutputOpts());
623}
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000624
625void PrintPreambleAction::ExecuteAction() {
626 switch (getCurrentFileKind()) {
627 case IK_C:
628 case IK_CXX:
629 case IK_ObjC:
630 case IK_ObjCXX:
631 case IK_OpenCL:
Peter Collingbourne895fcca2010-12-01 03:15:20 +0000632 case IK_CUDA:
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000633 break;
634
635 case IK_None:
636 case IK_Asm:
637 case IK_PreprocessedC:
638 case IK_PreprocessedCXX:
639 case IK_PreprocessedObjC:
640 case IK_PreprocessedObjCXX:
641 case IK_AST:
642 case IK_LLVM_IR:
643 // We can't do anything with these.
644 return;
645 }
646
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +0000647 CompilerInstance &CI = getCompilerInstance();
648 llvm::MemoryBuffer *Buffer
Chris Lattner39b49bc2010-11-23 08:35:12 +0000649 = CI.getFileManager().getBufferForFile(getCurrentFile());
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000650 if (Buffer) {
Argyrios Kyrtzidis03c107a2011-08-25 20:39:19 +0000651 unsigned Preamble = Lexer::ComputePreamble(Buffer, CI.getLangOpts()).first;
Douglas Gregorf033f1d2010-07-20 20:18:03 +0000652 llvm::outs().write(Buffer->getBufferStart(), Preamble);
653 delete Buffer;
654 }
655}