blob: f587d829b396c9403c01fde86760c85c1c7fa7d1 [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"
Nick Lewycky784fad72010-04-24 01:30:46 +000024#include "llvm/ADT/OwningPtr.h"
Douglas Gregor524e33e2011-12-08 19:11:24 +000025#include "llvm/Support/FileSystem.h"
Douglas Gregoraf82e352010-07-20 20:18:03 +000026#include "llvm/Support/MemoryBuffer.h"
Daniel Dunbar02bd2d72009-11-14 10:42:46 +000027#include "llvm/Support/raw_ostream.h"
Douglas Gregor52da28b2011-09-23 23:43:36 +000028#include "llvm/Support/system_error.h"
29
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
131static void addHeaderInclude(StringRef HeaderName,
132 SmallVectorImpl<char> &Includes,
Richard Smith77944862014-03-02 05:58:18 +0000133 const LangOptions &LangOpts,
134 bool IsExternC) {
135 if (IsExternC)
136 Includes += "extern \"C\" {\n";
Argyrios Kyrtzidis130190f2012-10-10 02:12:39 +0000137 if (LangOpts.ObjC1)
138 Includes += "#import \"";
139 else
140 Includes += "#include \"";
141 Includes += HeaderName;
142 Includes += "\"\n";
Richard Smith77944862014-03-02 05:58:18 +0000143 if (IsExternC)
144 Includes += "}\n";
Argyrios Kyrtzidis130190f2012-10-10 02:12:39 +0000145}
146
147static void addHeaderInclude(const FileEntry *Header,
148 SmallVectorImpl<char> &Includes,
Richard Smith77944862014-03-02 05:58:18 +0000149 const LangOptions &LangOpts,
150 bool IsExternC) {
151 addHeaderInclude(Header->getName(), Includes, LangOpts, IsExternC);
Argyrios Kyrtzidis130190f2012-10-10 02:12:39 +0000152}
153
Douglas Gregor4332b322011-11-16 17:04:00 +0000154/// \brief Collect the set of header includes needed to construct the given
Argyrios Kyrtzidisc597c8c2012-10-05 00:22:33 +0000155/// module and update the TopHeaders file set of the module.
Douglas Gregor4332b322011-11-16 17:04:00 +0000156///
157/// \param Module The module we're collecting includes from.
Douglas Gregore5626c42011-12-06 17:15:11 +0000158///
James Dennettc423c532012-06-15 21:48:19 +0000159/// \param Includes Will be augmented with the set of \#includes or \#imports
Douglas Gregore5626c42011-12-06 17:15:11 +0000160/// needed to load all of the named headers.
Douglas Gregor4332b322011-11-16 17:04:00 +0000161static void collectModuleHeaderIncludes(const LangOptions &LangOpts,
Douglas Gregord2a8fe12012-01-05 00:04:05 +0000162 FileManager &FileMgr,
163 ModuleMap &ModMap,
Douglas Gregorde3ef502011-11-30 23:21:26 +0000164 clang::Module *Module,
Argyrios Kyrtzidis130190f2012-10-10 02:12:39 +0000165 SmallVectorImpl<char> &Includes) {
Douglas Gregor1fb5c3a2011-12-31 04:05:44 +0000166 // Don't collect any headers for unavailable modules.
167 if (!Module->isAvailable())
168 return;
169
Douglas Gregore5626c42011-12-06 17:15:11 +0000170 // Add includes for each of these headers.
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000171 for (unsigned I = 0, N = Module->NormalHeaders.size(); I != N; ++I) {
172 const FileEntry *Header = Module->NormalHeaders[I];
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +0000173 Module->addTopHeader(Header);
Richard Smith77944862014-03-02 05:58:18 +0000174 addHeaderInclude(Header, Includes, LangOpts, Module->IsExternC);
Douglas Gregor3ec66632012-02-02 18:42:48 +0000175 }
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000176 // Note that Module->PrivateHeaders will not be a TopHeader.
Douglas Gregore5626c42011-12-06 17:15:11 +0000177
Douglas Gregor73141fa2011-12-08 17:39:04 +0000178 if (const FileEntry *UmbrellaHeader = Module->getUmbrellaHeader()) {
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +0000179 Module->addTopHeader(UmbrellaHeader);
Douglas Gregor3ec66632012-02-02 18:42:48 +0000180 if (Module->Parent) {
181 // Include the umbrella header for submodules.
Richard Smith77944862014-03-02 05:58:18 +0000182 addHeaderInclude(UmbrellaHeader, Includes, LangOpts, Module->IsExternC);
Douglas Gregor3ec66632012-02-02 18:42:48 +0000183 }
Douglas Gregor524e33e2011-12-08 19:11:24 +0000184 } else if (const DirectoryEntry *UmbrellaDir = Module->getUmbrellaDir()) {
Douglas Gregord2a8fe12012-01-05 00:04:05 +0000185 // Add all of the headers we find in this subdirectory.
Douglas Gregor524e33e2011-12-08 19:11:24 +0000186 llvm::error_code EC;
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000187 SmallString<128> DirNative;
Douglas Gregor524e33e2011-12-08 19:11:24 +0000188 llvm::sys::path::native(UmbrellaDir->getName(), DirNative);
Douglas Gregorc1aaf8c2011-12-12 19:13:53 +0000189 for (llvm::sys::fs::recursive_directory_iterator Dir(DirNative.str(), EC),
190 DirEnd;
Douglas Gregor524e33e2011-12-08 19:11:24 +0000191 Dir != DirEnd && !EC; Dir.increment(EC)) {
192 // Check whether this entry has an extension typically associated with
193 // headers.
194 if (!llvm::StringSwitch<bool>(llvm::sys::path::extension(Dir->path()))
195 .Cases(".h", ".H", ".hh", ".hpp", true)
196 .Default(false))
197 continue;
198
Douglas Gregord2a8fe12012-01-05 00:04:05 +0000199 // If this header is marked 'unavailable' in this module, don't include
200 // it.
Argyrios Kyrtzidisc597c8c2012-10-05 00:22:33 +0000201 if (const FileEntry *Header = FileMgr.getFile(Dir->path())) {
Douglas Gregord2a8fe12012-01-05 00:04:05 +0000202 if (ModMap.isHeaderInUnavailableModule(Header))
203 continue;
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +0000204 Module->addTopHeader(Header);
Argyrios Kyrtzidisc597c8c2012-10-05 00:22:33 +0000205 }
Douglas Gregord2a8fe12012-01-05 00:04:05 +0000206
Douglas Gregor3ec66632012-02-02 18:42:48 +0000207 // Include this header umbrella header for submodules.
Richard Smith77944862014-03-02 05:58:18 +0000208 addHeaderInclude(Dir->path(), Includes, LangOpts, Module->IsExternC);
Douglas Gregor524e33e2011-12-08 19:11:24 +0000209 }
Douglas Gregor4332b322011-11-16 17:04:00 +0000210 }
211
212 // Recurse into submodules.
Douglas Gregoreb90e832012-01-04 23:32:19 +0000213 for (clang::Module::submodule_iterator Sub = Module->submodule_begin(),
214 SubEnd = Module->submodule_end();
Douglas Gregore5626c42011-12-06 17:15:11 +0000215 Sub != SubEnd; ++Sub)
Douglas Gregor3ec66632012-02-02 18:42:48 +0000216 collectModuleHeaderIncludes(LangOpts, FileMgr, ModMap, *Sub, Includes);
Douglas Gregor4332b322011-11-16 17:04:00 +0000217}
218
Douglas Gregor2b20cb82011-11-16 00:09:06 +0000219bool GenerateModuleAction::BeginSourceFileAction(CompilerInstance &CI,
220 StringRef Filename) {
221 // Find the module map file.
222 const FileEntry *ModuleMap = CI.getFileManager().getFile(Filename);
223 if (!ModuleMap) {
224 CI.getDiagnostics().Report(diag::err_module_map_not_found)
225 << Filename;
226 return false;
227 }
228
229 // Parse the module map file.
230 HeaderSearch &HS = CI.getPreprocessor().getHeaderSearchInfo();
Douglas Gregor963c5532013-06-21 16:28:10 +0000231 if (HS.loadModuleMapFile(ModuleMap, IsSystem))
Douglas Gregor2b20cb82011-11-16 00:09:06 +0000232 return false;
233
234 if (CI.getLangOpts().CurrentModule.empty()) {
235 CI.getDiagnostics().Report(diag::err_missing_module_name);
236
237 // FIXME: Eventually, we could consider asking whether there was just
238 // a single module described in the module map, and use that as a
239 // default. Then it would be fairly trivial to just "compile" a module
240 // map with a single module (the common case).
241 return false;
242 }
243
244 // Dig out the module definition.
Douglas Gregor279a6c32012-01-29 17:08:11 +0000245 Module = HS.lookupModule(CI.getLangOpts().CurrentModule,
246 /*AllowSearch=*/false);
Douglas Gregor2b20cb82011-11-16 00:09:06 +0000247 if (!Module) {
248 CI.getDiagnostics().Report(diag::err_missing_module)
249 << CI.getLangOpts().CurrentModule << Filename;
250
251 return false;
252 }
Douglas Gregor1fb5c3a2011-12-31 04:05:44 +0000253
254 // Check whether we can build this module at all.
Richard Smitha3feee22013-10-28 22:18:19 +0000255 clang::Module::Requirement Requirement;
Daniel Jasper0761a8a2013-12-17 10:31:37 +0000256 clang::Module::HeaderDirective MissingHeader;
257 if (!Module->isAvailable(CI.getLangOpts(), CI.getTarget(), Requirement,
258 MissingHeader)) {
259 if (MissingHeader.FileNameLoc.isValid()) {
260 CI.getDiagnostics().Report(diag::err_module_header_missing)
261 << MissingHeader.IsUmbrella << MissingHeader.FileName;
262 } else {
263 CI.getDiagnostics().Report(diag::err_module_unavailable)
264 << Module->getFullModuleName()
265 << Requirement.second << Requirement.first;
266 }
Douglas Gregor1fb5c3a2011-12-31 04:05:44 +0000267
268 return false;
269 }
270
Argyrios Kyrtzidis130190f2012-10-10 02:12:39 +0000271 FileManager &FileMgr = CI.getFileManager();
272
Douglas Gregor4332b322011-11-16 17:04:00 +0000273 // Collect the set of #includes we need to build the module.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000274 SmallString<256> HeaderContents;
Argyrios Kyrtzidis130190f2012-10-10 02:12:39 +0000275 if (const FileEntry *UmbrellaHeader = Module->getUmbrellaHeader())
Richard Smith77944862014-03-02 05:58:18 +0000276 addHeaderInclude(UmbrellaHeader, HeaderContents, CI.getLangOpts(),
277 Module->IsExternC);
Argyrios Kyrtzidis130190f2012-10-10 02:12:39 +0000278 collectModuleHeaderIncludes(CI.getLangOpts(), FileMgr,
Douglas Gregord2a8fe12012-01-05 00:04:05 +0000279 CI.getPreprocessor().getHeaderSearchInfo().getModuleMap(),
Douglas Gregor3ec66632012-02-02 18:42:48 +0000280 Module, HeaderContents);
Douglas Gregor4332b322011-11-16 17:04:00 +0000281
Argyrios Kyrtzidis52595242012-11-15 18:57:27 +0000282 llvm::MemoryBuffer *InputBuffer =
283 llvm::MemoryBuffer::getMemBufferCopy(HeaderContents,
284 Module::getModuleInputBufferName());
Alp Tokerf6a24ce2013-12-05 16:25:25 +0000285 // Ownership of InputBuffer will be transferred to the SourceManager.
Argyrios Kyrtzidis52595242012-11-15 18:57:27 +0000286 setCurrentInput(FrontendInputFile(InputBuffer, getCurrentFileKind(),
Douglas Gregora686e1b2012-01-27 19:52:33 +0000287 Module->IsSystem));
Douglas Gregor2b20cb82011-11-16 00:09:06 +0000288 return true;
289}
290
291bool GenerateModuleAction::ComputeASTConsumerArguments(CompilerInstance &CI,
292 StringRef InFile,
293 std::string &Sysroot,
294 std::string &OutputFile,
295 raw_ostream *&OS) {
296 // If no output file was provided, figure out where this module would go
297 // in the module cache.
298 if (CI.getFrontendOpts().OutputFile.empty()) {
299 HeaderSearch &HS = CI.getPreprocessor().getHeaderSearchInfo();
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000300 SmallString<256> ModuleFileName(HS.getModuleCachePath());
Douglas Gregor2b20cb82011-11-16 00:09:06 +0000301 llvm::sys::path::append(ModuleFileName,
302 CI.getLangOpts().CurrentModule + ".pcm");
303 CI.getFrontendOpts().OutputFile = ModuleFileName.str();
304 }
305
306 // We use createOutputFile here because this is exposed via libclang, and we
307 // must disable the RemoveFileOnSignal behavior.
308 // We use a temporary to avoid race conditions.
309 OS = CI.createOutputFile(CI.getFrontendOpts().OutputFile, /*Binary=*/true,
310 /*RemoveFileOnSignal=*/false, InFile,
Daniel Dunbarb9c62c02012-03-03 00:36:02 +0000311 /*Extension=*/"", /*useTemporary=*/true,
312 /*CreateMissingDirectories=*/true);
Douglas Gregor2b20cb82011-11-16 00:09:06 +0000313 if (!OS)
314 return true;
315
316 OutputFile = CI.getFrontendOpts().OutputFile;
317 return false;
318}
319
Daniel Dunbar02bd2d72009-11-14 10:42:46 +0000320ASTConsumer *SyntaxOnlyAction::CreateASTConsumer(CompilerInstance &CI,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000321 StringRef InFile) {
Daniel Dunbar02bd2d72009-11-14 10:42:46 +0000322 return new ASTConsumer();
323}
324
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000325ASTConsumer *DumpModuleInfoAction::CreateASTConsumer(CompilerInstance &CI,
326 StringRef InFile) {
327 return new ASTConsumer();
328}
329
Ben Langmuir2cb4a782014-02-05 22:21:15 +0000330ASTConsumer *VerifyPCHAction::CreateASTConsumer(CompilerInstance &CI,
331 StringRef InFile) {
332 return new ASTConsumer();
333}
334
335void VerifyPCHAction::ExecuteAction() {
Ben Langmuir3d4417c2014-02-07 17:31:11 +0000336 CompilerInstance &CI = getCompilerInstance();
337 bool Preamble = CI.getPreprocessorOpts().PrecompiledPreambleBytes.first != 0;
338 const std::string &Sysroot = CI.getHeaderSearchOpts().Sysroot;
339 OwningPtr<ASTReader> Reader(new ASTReader(
340 CI.getPreprocessor(), CI.getASTContext(),
341 Sysroot.empty() ? "" : Sysroot.c_str(),
342 /*DisableValidation*/false,
343 /*AllowPCHWithCompilerErrors*/false,
344 /*AllowConfigurationMismatch*/true,
345 /*ValidateSystemInputs*/true));
346
347 Reader->ReadAST(getCurrentFile(),
348 Preamble ? serialization::MK_Preamble
349 : serialization::MK_PCH,
350 SourceLocation(),
351 ASTReader::ARR_ConfigurationMismatch);
Ben Langmuir2cb4a782014-02-05 22:21:15 +0000352}
353
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000354namespace {
355 /// \brief AST reader listener that dumps module information for a module
356 /// file.
357 class DumpModuleInfoListener : public ASTReaderListener {
358 llvm::raw_ostream &Out;
359
360 public:
361 DumpModuleInfoListener(llvm::raw_ostream &Out) : Out(Out) { }
362
363#define DUMP_BOOLEAN(Value, Text) \
364 Out.indent(4) << Text << ": " << (Value? "Yes" : "No") << "\n"
365
366 virtual bool ReadFullVersionInformation(StringRef FullVersion) {
367 Out.indent(2)
368 << "Generated by "
369 << (FullVersion == getClangFullRepositoryVersion()? "this"
370 : "a different")
371 << " Clang: " << FullVersion << "\n";
372 return ASTReaderListener::ReadFullVersionInformation(FullVersion);
373 }
374
375 virtual bool ReadLanguageOptions(const LangOptions &LangOpts,
376 bool Complain) {
377 Out.indent(2) << "Language options:\n";
378#define LANGOPT(Name, Bits, Default, Description) \
379 DUMP_BOOLEAN(LangOpts.Name, Description);
380#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
381 Out.indent(4) << Description << ": " \
382 << static_cast<unsigned>(LangOpts.get##Name()) << "\n";
383#define VALUE_LANGOPT(Name, Bits, Default, Description) \
384 Out.indent(4) << Description << ": " << LangOpts.Name << "\n";
385#define BENIGN_LANGOPT(Name, Bits, Default, Description)
386#define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
387#include "clang/Basic/LangOptions.def"
388 return false;
389 }
390
391 virtual bool ReadTargetOptions(const TargetOptions &TargetOpts,
392 bool Complain) {
393 Out.indent(2) << "Target options:\n";
394 Out.indent(4) << " Triple: " << TargetOpts.Triple << "\n";
395 Out.indent(4) << " CPU: " << TargetOpts.CPU << "\n";
396 Out.indent(4) << " ABI: " << TargetOpts.ABI << "\n";
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000397 Out.indent(4) << " Linker version: " << TargetOpts.LinkerVersion << "\n";
398
399 if (!TargetOpts.FeaturesAsWritten.empty()) {
400 Out.indent(4) << "Target features:\n";
401 for (unsigned I = 0, N = TargetOpts.FeaturesAsWritten.size();
402 I != N; ++I) {
403 Out.indent(6) << TargetOpts.FeaturesAsWritten[I] << "\n";
404 }
405 }
406
407 return false;
408 }
409
410 virtual bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
411 bool Complain) {
412 Out.indent(2) << "Header search options:\n";
413 Out.indent(4) << "System root [-isysroot=]: '" << HSOpts.Sysroot << "'\n";
414 DUMP_BOOLEAN(HSOpts.UseBuiltinIncludes,
415 "Use builtin include directories [-nobuiltininc]");
416 DUMP_BOOLEAN(HSOpts.UseStandardSystemIncludes,
417 "Use standard system include directories [-nostdinc]");
418 DUMP_BOOLEAN(HSOpts.UseStandardCXXIncludes,
419 "Use standard C++ include directories [-nostdinc++]");
420 DUMP_BOOLEAN(HSOpts.UseLibcxx,
421 "Use libc++ (rather than libstdc++) [-stdlib=]");
422 return false;
423 }
424
425 virtual bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
426 bool Complain,
427 std::string &SuggestedPredefines) {
428 Out.indent(2) << "Preprocessor options:\n";
429 DUMP_BOOLEAN(PPOpts.UsePredefines,
430 "Uses compiler/target-specific predefines [-undef]");
431 DUMP_BOOLEAN(PPOpts.DetailedRecord,
432 "Uses detailed preprocessing record (for indexing)");
433
434 if (!PPOpts.Macros.empty()) {
435 Out.indent(4) << "Predefined macros:\n";
436 }
437
438 for (std::vector<std::pair<std::string, bool/*isUndef*/> >::const_iterator
439 I = PPOpts.Macros.begin(), IEnd = PPOpts.Macros.end();
440 I != IEnd; ++I) {
441 Out.indent(6);
442 if (I->second)
443 Out << "-U";
444 else
445 Out << "-D";
446 Out << I->first << "\n";
447 }
448 return false;
449 }
450#undef DUMP_BOOLEAN
451 };
452}
453
454void DumpModuleInfoAction::ExecuteAction() {
455 // Set up the output file.
456 llvm::OwningPtr<llvm::raw_fd_ostream> OutFile;
457 StringRef OutputFileName = getCompilerInstance().getFrontendOpts().OutputFile;
458 if (!OutputFileName.empty() && OutputFileName != "-") {
459 std::string ErrorInfo;
460 OutFile.reset(new llvm::raw_fd_ostream(OutputFileName.str().c_str(),
Rafael Espindola4fbd3732014-02-24 18:20:21 +0000461 ErrorInfo, llvm::sys::fs::F_Text));
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000462 }
463 llvm::raw_ostream &Out = OutFile.get()? *OutFile.get() : llvm::outs();
464
465 Out << "Information for module file '" << getCurrentFile() << "':\n";
466 DumpModuleInfoListener Listener(Out);
467 ASTReader::readASTFileControlBlock(getCurrentFile(),
468 getCompilerInstance().getFileManager(),
469 Listener);
470}
471
Daniel Dunbar88357802009-11-14 10:42:57 +0000472//===----------------------------------------------------------------------===//
473// Preprocessor Actions
474//===----------------------------------------------------------------------===//
475
476void DumpRawTokensAction::ExecuteAction() {
477 Preprocessor &PP = getCompilerInstance().getPreprocessor();
478 SourceManager &SM = PP.getSourceManager();
479
480 // Start lexing the specified input file.
Chris Lattner710bb872009-11-30 04:18:44 +0000481 const llvm::MemoryBuffer *FromFile = SM.getBuffer(SM.getMainFileID());
David Blaikiebbafb8a2012-03-11 07:00:24 +0000482 Lexer RawLex(SM.getMainFileID(), FromFile, SM, PP.getLangOpts());
Daniel Dunbar88357802009-11-14 10:42:57 +0000483 RawLex.SetKeepWhitespaceMode(true);
484
485 Token RawTok;
486 RawLex.LexFromRawLexer(RawTok);
487 while (RawTok.isNot(tok::eof)) {
488 PP.DumpToken(RawTok, true);
Daniel Dunbar75024622009-11-25 10:27:48 +0000489 llvm::errs() << "\n";
Daniel Dunbar88357802009-11-14 10:42:57 +0000490 RawLex.LexFromRawLexer(RawTok);
491 }
492}
493
494void DumpTokensAction::ExecuteAction() {
495 Preprocessor &PP = getCompilerInstance().getPreprocessor();
496 // Start preprocessing the specified input file.
497 Token Tok;
Chris Lattnerfb24a3a2010-04-20 20:35:58 +0000498 PP.EnterMainSourceFile();
Daniel Dunbar88357802009-11-14 10:42:57 +0000499 do {
500 PP.Lex(Tok);
501 PP.DumpToken(Tok, true);
Daniel Dunbar75024622009-11-25 10:27:48 +0000502 llvm::errs() << "\n";
Daniel Dunbar88357802009-11-14 10:42:57 +0000503 } while (Tok.isNot(tok::eof));
504}
505
506void GeneratePTHAction::ExecuteAction() {
507 CompilerInstance &CI = getCompilerInstance();
508 if (CI.getFrontendOpts().OutputFile.empty() ||
509 CI.getFrontendOpts().OutputFile == "-") {
510 // FIXME: Don't fail this way.
511 // FIXME: Verify that we can actually seek in the given file.
Chris Lattner4b73cfa2010-04-07 22:58:06 +0000512 llvm::report_fatal_error("PTH requires a seekable file for output!");
Daniel Dunbar88357802009-11-14 10:42:57 +0000513 }
514 llvm::raw_fd_ostream *OS =
515 CI.createDefaultOutputFile(true, getCurrentFile());
Daniel Dunbar75546992009-12-03 09:13:30 +0000516 if (!OS) return;
517
Daniel Dunbar88357802009-11-14 10:42:57 +0000518 CacheTokens(CI.getPreprocessor(), OS);
519}
520
Daniel Dunbar88357802009-11-14 10:42:57 +0000521void PreprocessOnlyAction::ExecuteAction() {
522 Preprocessor &PP = getCompilerInstance().getPreprocessor();
523
Daniel Dunbard839e772010-06-11 20:10:12 +0000524 // Ignore unknown pragmas.
NAKAMURA Takumiddc86792013-12-04 11:12:26 +0000525 PP.AddPragmaHandler(new EmptyPragmaHandler());
Daniel Dunbard839e772010-06-11 20:10:12 +0000526
Daniel Dunbar88357802009-11-14 10:42:57 +0000527 Token Tok;
528 // Start parsing the specified input file.
Chris Lattnerfb24a3a2010-04-20 20:35:58 +0000529 PP.EnterMainSourceFile();
Daniel Dunbar88357802009-11-14 10:42:57 +0000530 do {
531 PP.Lex(Tok);
532 } while (Tok.isNot(tok::eof));
533}
534
Daniel Dunbar88357802009-11-14 10:42:57 +0000535void PrintPreprocessedAction::ExecuteAction() {
536 CompilerInstance &CI = getCompilerInstance();
Douglas Gregor52da28b2011-09-23 23:43:36 +0000537 // Output file may need to be set to 'Binary', to avoid converting Unix style
Steve Naroff3d38a682010-01-05 17:33:23 +0000538 // line feeds (<LF>) to Microsoft style line feeds (<CR><LF>).
Douglas Gregor52da28b2011-09-23 23:43:36 +0000539 //
540 // Look to see what type of line endings the file uses. If there's a
541 // CRLF, then we won't open the file up in binary mode. If there is
542 // just an LF or CR, then we will open the file up in binary mode.
543 // In this fashion, the output format should match the input format, unless
544 // the input format has inconsistent line endings.
545 //
546 // This should be a relatively fast operation since most files won't have
547 // all of their source code on a single line. However, that is still a
548 // concern, so if we scan for too long, we'll just assume the file should
549 // be opened in binary mode.
550 bool BinaryMode = true;
551 bool InvalidFile = false;
552 const SourceManager& SM = CI.getSourceManager();
553 const llvm::MemoryBuffer *Buffer = SM.getBuffer(SM.getMainFileID(),
554 &InvalidFile);
555 if (!InvalidFile) {
556 const char *cur = Buffer->getBufferStart();
557 const char *end = Buffer->getBufferEnd();
558 const char *next = (cur != end) ? cur + 1 : end;
559
560 // Limit ourselves to only scanning 256 characters into the source
561 // file. This is mostly a sanity check in case the file has no
562 // newlines whatsoever.
563 if (end - cur > 256) end = cur + 256;
564
565 while (next < end) {
566 if (*cur == 0x0D) { // CR
567 if (*next == 0x0A) // CRLF
568 BinaryMode = false;
569
570 break;
571 } else if (*cur == 0x0A) // LF
572 break;
573
574 ++cur, ++next;
575 }
576 }
577
578 raw_ostream *OS = CI.createDefaultOutputFile(BinaryMode, getCurrentFile());
Daniel Dunbar75546992009-12-03 09:13:30 +0000579 if (!OS) return;
580
Daniel Dunbar88357802009-11-14 10:42:57 +0000581 DoPrintPreprocessedInput(CI.getPreprocessor(), OS,
582 CI.getPreprocessorOutputOpts());
583}
Douglas Gregoraf82e352010-07-20 20:18:03 +0000584
585void PrintPreambleAction::ExecuteAction() {
586 switch (getCurrentFileKind()) {
587 case IK_C:
588 case IK_CXX:
589 case IK_ObjC:
590 case IK_ObjCXX:
591 case IK_OpenCL:
Peter Collingbourne62089b82010-12-01 03:15:20 +0000592 case IK_CUDA:
Douglas Gregoraf82e352010-07-20 20:18:03 +0000593 break;
594
595 case IK_None:
596 case IK_Asm:
597 case IK_PreprocessedC:
598 case IK_PreprocessedCXX:
599 case IK_PreprocessedObjC:
600 case IK_PreprocessedObjCXX:
601 case IK_AST:
602 case IK_LLVM_IR:
603 // We can't do anything with these.
604 return;
605 }
606
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000607 CompilerInstance &CI = getCompilerInstance();
608 llvm::MemoryBuffer *Buffer
Chris Lattner5159f612010-11-23 08:35:12 +0000609 = CI.getFileManager().getBufferForFile(getCurrentFile());
Douglas Gregoraf82e352010-07-20 20:18:03 +0000610 if (Buffer) {
Argyrios Kyrtzidis7aecbc72011-08-25 20:39:19 +0000611 unsigned Preamble = Lexer::ComputePreamble(Buffer, CI.getLangOpts()).first;
Douglas Gregoraf82e352010-07-20 20:18:03 +0000612 llvm::outs().write(Buffer->getBufferStart(), Preamble);
613 delete Buffer;
614 }
615}