1 //===--- FrontendActions.cpp ----------------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "clang/Frontend/FrontendActions.h"
11 #include "clang/AST/ASTConsumer.h"
12 #include "clang/Basic/FileManager.h"
13 #include "clang/Frontend/ASTConsumers.h"
14 #include "clang/Frontend/CompilerInstance.h"
15 #include "clang/Frontend/FrontendDiagnostic.h"
16 #include "clang/Frontend/MultiplexConsumer.h"
17 #include "clang/Frontend/Utils.h"
18 #include "clang/Lex/HeaderSearch.h"
19 #include "clang/Lex/Preprocessor.h"
20 #include "clang/Lex/PreprocessorOptions.h"
21 #include "clang/Serialization/ASTReader.h"
22 #include "clang/Serialization/ASTWriter.h"
23 #include "llvm/Support/FileSystem.h"
24 #include "llvm/Support/MemoryBuffer.h"
25 #include "llvm/Support/Path.h"
26 #include "llvm/Support/raw_ostream.h"
28 #include <system_error>
30 using namespace clang;
32 //===----------------------------------------------------------------------===//
34 //===----------------------------------------------------------------------===//
36 std::unique_ptr<ASTConsumer>
37 InitOnlyAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
38 return llvm::make_unique<ASTConsumer>();
41 void InitOnlyAction::ExecuteAction() {
44 //===----------------------------------------------------------------------===//
45 // AST Consumer Actions
46 //===----------------------------------------------------------------------===//
48 std::unique_ptr<ASTConsumer>
49 ASTPrintAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
50 if (std::unique_ptr<raw_ostream> OS =
51 CI.createDefaultOutputFile(false, InFile))
52 return CreateASTPrinter(std::move(OS), CI.getFrontendOpts().ASTDumpFilter);
56 std::unique_ptr<ASTConsumer>
57 ASTDumpAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
58 return CreateASTDumper(CI.getFrontendOpts().ASTDumpFilter,
59 CI.getFrontendOpts().ASTDumpDecls,
60 CI.getFrontendOpts().ASTDumpAll,
61 CI.getFrontendOpts().ASTDumpLookups);
64 std::unique_ptr<ASTConsumer>
65 ASTDeclListAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
66 return CreateASTDeclNodeLister();
69 std::unique_ptr<ASTConsumer>
70 ASTViewAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
71 return CreateASTViewer();
74 std::unique_ptr<ASTConsumer>
75 DeclContextPrintAction::CreateASTConsumer(CompilerInstance &CI,
77 return CreateDeclContextPrinter();
80 std::unique_ptr<ASTConsumer>
81 GeneratePCHAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
83 std::string OutputFile;
84 std::unique_ptr<raw_pwrite_stream> OS =
85 ComputeASTConsumerArguments(CI, InFile, Sysroot, OutputFile);
89 if (!CI.getFrontendOpts().RelocatablePCH)
92 auto Buffer = std::make_shared<PCHBuffer>();
93 std::vector<std::unique_ptr<ASTConsumer>> Consumers;
94 Consumers.push_back(llvm::make_unique<PCHGenerator>(
95 CI.getPreprocessor(), OutputFile, Sysroot,
96 Buffer, CI.getFrontendOpts().ModuleFileExtensions,
97 /*AllowASTWithErrors*/CI.getPreprocessorOpts().AllowPCHWithCompilerErrors,
99 +CI.getFrontendOpts().IncludeTimestamps));
100 Consumers.push_back(CI.getPCHContainerWriter().CreatePCHContainerGenerator(
101 CI, InFile, OutputFile, std::move(OS), Buffer));
103 return llvm::make_unique<MultiplexConsumer>(std::move(Consumers));
106 std::unique_ptr<raw_pwrite_stream>
107 GeneratePCHAction::ComputeASTConsumerArguments(CompilerInstance &CI,
109 std::string &Sysroot,
110 std::string &OutputFile) {
111 Sysroot = CI.getHeaderSearchOpts().Sysroot;
112 if (CI.getFrontendOpts().RelocatablePCH && Sysroot.empty()) {
113 CI.getDiagnostics().Report(diag::err_relocatable_without_isysroot);
117 // We use createOutputFile here because this is exposed via libclang, and we
118 // must disable the RemoveFileOnSignal behavior.
119 // We use a temporary to avoid race conditions.
120 std::unique_ptr<raw_pwrite_stream> OS =
121 CI.createOutputFile(CI.getFrontendOpts().OutputFile, /*Binary=*/true,
122 /*RemoveFileOnSignal=*/false, InFile,
123 /*Extension=*/"", /*useTemporary=*/true);
127 OutputFile = CI.getFrontendOpts().OutputFile;
131 bool GeneratePCHAction::shouldEraseOutputFiles() {
132 if (getCompilerInstance().getPreprocessorOpts().AllowPCHWithCompilerErrors)
134 return ASTFrontendAction::shouldEraseOutputFiles();
137 bool GeneratePCHAction::BeginSourceFileAction(CompilerInstance &CI,
138 StringRef Filename) {
139 CI.getLangOpts().CompilingPCH = true;
143 std::unique_ptr<ASTConsumer>
144 GenerateModuleAction::CreateASTConsumer(CompilerInstance &CI,
146 std::unique_ptr<raw_pwrite_stream> OS = CreateOutputFile(CI, InFile);
150 std::string OutputFile = CI.getFrontendOpts().OutputFile;
153 auto Buffer = std::make_shared<PCHBuffer>();
154 std::vector<std::unique_ptr<ASTConsumer>> Consumers;
156 Consumers.push_back(llvm::make_unique<PCHGenerator>(
157 CI.getPreprocessor(), OutputFile, Sysroot,
158 Buffer, CI.getFrontendOpts().ModuleFileExtensions,
159 /*AllowASTWithErrors=*/false,
160 /*IncludeTimestamps=*/
161 +CI.getFrontendOpts().BuildingImplicitModule));
162 Consumers.push_back(CI.getPCHContainerWriter().CreatePCHContainerGenerator(
163 CI, InFile, OutputFile, std::move(OS), Buffer));
164 return llvm::make_unique<MultiplexConsumer>(std::move(Consumers));
167 bool GenerateModuleAction::BeginSourceFileAction(CompilerInstance &CI,
168 StringRef Filename) {
169 // Set up embedding for any specified files. Do this before we load any
170 // source files, including the primary module map for the compilation.
171 for (const auto &F : CI.getFrontendOpts().ModulesEmbedFiles) {
172 if (const auto *FE = CI.getFileManager().getFile(F, /*openFile*/true))
173 CI.getSourceManager().setFileIsTransient(FE);
175 CI.getDiagnostics().Report(diag::err_modules_embed_file_not_found) << F;
177 if (CI.getFrontendOpts().ModulesEmbedAllFiles)
178 CI.getSourceManager().setAllFilesAreTransient(true);
184 static SmallVectorImpl<char> &
185 operator+=(SmallVectorImpl<char> &Includes, StringRef RHS) {
186 Includes.append(RHS.begin(), RHS.end());
190 static void addHeaderInclude(StringRef HeaderName,
191 SmallVectorImpl<char> &Includes,
192 const LangOptions &LangOpts,
194 if (IsExternC && LangOpts.CPlusPlus)
195 Includes += "extern \"C\" {\n";
197 Includes += "#import \"";
199 Includes += "#include \"";
201 Includes += HeaderName;
204 if (IsExternC && LangOpts.CPlusPlus)
208 /// \brief Collect the set of header includes needed to construct the given
209 /// module and update the TopHeaders file set of the module.
211 /// \param Module The module we're collecting includes from.
213 /// \param Includes Will be augmented with the set of \#includes or \#imports
214 /// needed to load all of the named headers.
215 static std::error_code
216 collectModuleHeaderIncludes(const LangOptions &LangOpts, FileManager &FileMgr,
217 ModuleMap &ModMap, clang::Module *Module,
218 SmallVectorImpl<char> &Includes) {
219 // Don't collect any headers for unavailable modules.
220 if (!Module->isAvailable())
221 return std::error_code();
223 // Add includes for each of these headers.
224 for (auto HK : {Module::HK_Normal, Module::HK_Private}) {
225 for (Module::Header &H : Module->Headers[HK]) {
226 Module->addTopHeader(H.Entry);
227 // Use the path as specified in the module map file. We'll look for this
228 // file relative to the module build directory (the directory containing
229 // the module map file) so this will find the same file that we found
230 // while parsing the module map.
231 addHeaderInclude(H.NameAsWritten, Includes, LangOpts, Module->IsExternC);
234 // Note that Module->PrivateHeaders will not be a TopHeader.
236 if (Module::Header UmbrellaHeader = Module->getUmbrellaHeader()) {
237 Module->addTopHeader(UmbrellaHeader.Entry);
239 // Include the umbrella header for submodules.
240 addHeaderInclude(UmbrellaHeader.NameAsWritten, Includes, LangOpts,
242 } else if (Module::DirectoryName UmbrellaDir = Module->getUmbrellaDir()) {
243 // Add all of the headers we find in this subdirectory.
245 SmallString<128> DirNative;
246 llvm::sys::path::native(UmbrellaDir.Entry->getName(), DirNative);
248 vfs::FileSystem &FS = *FileMgr.getVirtualFileSystem();
249 for (vfs::recursive_directory_iterator Dir(FS, DirNative, EC), End;
250 Dir != End && !EC; Dir.increment(EC)) {
251 // Check whether this entry has an extension typically associated with
253 if (!llvm::StringSwitch<bool>(llvm::sys::path::extension(Dir->getName()))
254 .Cases(".h", ".H", ".hh", ".hpp", true)
258 const FileEntry *Header = FileMgr.getFile(Dir->getName());
259 // FIXME: This shouldn't happen unless there is a file system race. Is
260 // that worth diagnosing?
264 // If this header is marked 'unavailable' in this module, don't include
266 if (ModMap.isHeaderUnavailableInModule(Header, Module))
269 // Compute the relative path from the directory to this file.
270 SmallVector<StringRef, 16> Components;
271 auto PathIt = llvm::sys::path::rbegin(Dir->getName());
272 for (int I = 0; I != Dir.level() + 1; ++I, ++PathIt)
273 Components.push_back(*PathIt);
274 SmallString<128> RelativeHeader(UmbrellaDir.NameAsWritten);
275 for (auto It = Components.rbegin(), End = Components.rend(); It != End;
277 llvm::sys::path::append(RelativeHeader, *It);
279 // Include this header as part of the umbrella directory.
280 Module->addTopHeader(Header);
281 addHeaderInclude(RelativeHeader, Includes, LangOpts, Module->IsExternC);
288 // Recurse into submodules.
289 for (clang::Module::submodule_iterator Sub = Module->submodule_begin(),
290 SubEnd = Module->submodule_end();
291 Sub != SubEnd; ++Sub)
292 if (std::error_code Err = collectModuleHeaderIncludes(
293 LangOpts, FileMgr, ModMap, *Sub, Includes))
296 return std::error_code();
299 bool GenerateModuleFromModuleMapAction::BeginSourceFileAction(
300 CompilerInstance &CI, StringRef Filename) {
301 CI.getLangOpts().setCompilingModule(LangOptions::CMK_ModuleMap);
303 if (!GenerateModuleAction::BeginSourceFileAction(CI, Filename))
306 // Find the module map file.
307 const FileEntry *ModuleMap =
308 CI.getFileManager().getFile(Filename, /*openFile*/true);
310 CI.getDiagnostics().Report(diag::err_module_map_not_found)
315 // Parse the module map file.
316 HeaderSearch &HS = CI.getPreprocessor().getHeaderSearchInfo();
317 if (HS.loadModuleMapFile(ModuleMap, IsSystem))
320 if (CI.getLangOpts().CurrentModule.empty()) {
321 CI.getDiagnostics().Report(diag::err_missing_module_name);
323 // FIXME: Eventually, we could consider asking whether there was just
324 // a single module described in the module map, and use that as a
325 // default. Then it would be fairly trivial to just "compile" a module
326 // map with a single module (the common case).
330 // If we're being run from the command-line, the module build stack will not
331 // have been filled in yet, so complete it now in order to allow us to detect
333 SourceManager &SourceMgr = CI.getSourceManager();
334 if (SourceMgr.getModuleBuildStack().empty())
335 SourceMgr.pushModuleBuildStack(CI.getLangOpts().CurrentModule,
336 FullSourceLoc(SourceLocation(), SourceMgr));
338 // Dig out the module definition.
339 Module = HS.lookupModule(CI.getLangOpts().CurrentModule,
340 /*AllowSearch=*/false);
342 CI.getDiagnostics().Report(diag::err_missing_module)
343 << CI.getLangOpts().CurrentModule << Filename;
348 // Check whether we can build this module at all.
349 clang::Module::Requirement Requirement;
350 clang::Module::UnresolvedHeaderDirective MissingHeader;
351 if (!Module->isAvailable(CI.getLangOpts(), CI.getTarget(), Requirement,
353 if (MissingHeader.FileNameLoc.isValid()) {
354 CI.getDiagnostics().Report(MissingHeader.FileNameLoc,
355 diag::err_module_header_missing)
356 << MissingHeader.IsUmbrella << MissingHeader.FileName;
358 CI.getDiagnostics().Report(diag::err_module_unavailable)
359 << Module->getFullModuleName()
360 << Requirement.second << Requirement.first;
366 if (ModuleMapForUniquing && ModuleMapForUniquing != ModuleMap) {
367 Module->IsInferred = true;
368 HS.getModuleMap().setInferredModuleAllowedBy(Module, ModuleMapForUniquing);
370 ModuleMapForUniquing = ModuleMap;
373 FileManager &FileMgr = CI.getFileManager();
375 // Collect the set of #includes we need to build the module.
376 SmallString<256> HeaderContents;
377 std::error_code Err = std::error_code();
378 if (Module::Header UmbrellaHeader = Module->getUmbrellaHeader())
379 addHeaderInclude(UmbrellaHeader.NameAsWritten, HeaderContents,
380 CI.getLangOpts(), Module->IsExternC);
381 Err = collectModuleHeaderIncludes(
382 CI.getLangOpts(), FileMgr,
383 CI.getPreprocessor().getHeaderSearchInfo().getModuleMap(), Module,
387 CI.getDiagnostics().Report(diag::err_module_cannot_create_includes)
388 << Module->getFullModuleName() << Err.message();
392 // Inform the preprocessor that includes from within the input buffer should
393 // be resolved relative to the build directory of the module map file.
394 CI.getPreprocessor().setMainFileDir(Module->Directory);
396 std::unique_ptr<llvm::MemoryBuffer> InputBuffer =
397 llvm::MemoryBuffer::getMemBufferCopy(HeaderContents,
398 Module::getModuleInputBufferName());
399 // Ownership of InputBuffer will be transferred to the SourceManager.
400 setCurrentInput(FrontendInputFile(InputBuffer.release(), getCurrentFileKind(),
405 std::unique_ptr<raw_pwrite_stream>
406 GenerateModuleFromModuleMapAction::CreateOutputFile(CompilerInstance &CI,
408 // If no output file was provided, figure out where this module would go
409 // in the module cache.
410 if (CI.getFrontendOpts().OutputFile.empty()) {
411 HeaderSearch &HS = CI.getPreprocessor().getHeaderSearchInfo();
412 CI.getFrontendOpts().OutputFile =
413 HS.getModuleFileName(CI.getLangOpts().CurrentModule,
414 ModuleMapForUniquing->getName(),
415 /*UsePrebuiltPath=*/false);
418 // We use createOutputFile here because this is exposed via libclang, and we
419 // must disable the RemoveFileOnSignal behavior.
420 // We use a temporary to avoid race conditions.
421 return CI.createOutputFile(CI.getFrontendOpts().OutputFile, /*Binary=*/true,
422 /*RemoveFileOnSignal=*/false, InFile,
423 /*Extension=*/"", /*useTemporary=*/true,
424 /*CreateMissingDirectories=*/true);
427 bool GenerateModuleInterfaceAction::BeginSourceFileAction(CompilerInstance &CI,
428 StringRef Filename) {
429 if (!CI.getLangOpts().ModulesTS) {
430 CI.getDiagnostics().Report(diag::err_module_interface_requires_modules_ts);
434 CI.getLangOpts().setCompilingModule(LangOptions::CMK_ModuleInterface);
436 return GenerateModuleAction::BeginSourceFileAction(CI, Filename);
439 std::unique_ptr<raw_pwrite_stream>
440 GenerateModuleInterfaceAction::CreateOutputFile(CompilerInstance &CI,
442 return CI.createDefaultOutputFile(/*Binary=*/true, InFile, "pcm");
445 SyntaxOnlyAction::~SyntaxOnlyAction() {
448 std::unique_ptr<ASTConsumer>
449 SyntaxOnlyAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
450 return llvm::make_unique<ASTConsumer>();
453 std::unique_ptr<ASTConsumer>
454 DumpModuleInfoAction::CreateASTConsumer(CompilerInstance &CI,
456 return llvm::make_unique<ASTConsumer>();
459 std::unique_ptr<ASTConsumer>
460 VerifyPCHAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
461 return llvm::make_unique<ASTConsumer>();
464 void VerifyPCHAction::ExecuteAction() {
465 CompilerInstance &CI = getCompilerInstance();
466 bool Preamble = CI.getPreprocessorOpts().PrecompiledPreambleBytes.first != 0;
467 const std::string &Sysroot = CI.getHeaderSearchOpts().Sysroot;
468 std::unique_ptr<ASTReader> Reader(new ASTReader(
469 CI.getPreprocessor(), CI.getASTContext(), CI.getPCHContainerReader(),
470 CI.getFrontendOpts().ModuleFileExtensions,
471 Sysroot.empty() ? "" : Sysroot.c_str(),
472 /*DisableValidation*/ false,
473 /*AllowPCHWithCompilerErrors*/ false,
474 /*AllowConfigurationMismatch*/ true,
475 /*ValidateSystemInputs*/ true));
477 Reader->ReadAST(getCurrentFile(),
478 Preamble ? serialization::MK_Preamble
479 : serialization::MK_PCH,
481 ASTReader::ARR_ConfigurationMismatch);
485 /// \brief AST reader listener that dumps module information for a module
487 class DumpModuleInfoListener : public ASTReaderListener {
488 llvm::raw_ostream &Out;
491 DumpModuleInfoListener(llvm::raw_ostream &Out) : Out(Out) { }
493 #define DUMP_BOOLEAN(Value, Text) \
494 Out.indent(4) << Text << ": " << (Value? "Yes" : "No") << "\n"
496 bool ReadFullVersionInformation(StringRef FullVersion) override {
499 << (FullVersion == getClangFullRepositoryVersion()? "this"
501 << " Clang: " << FullVersion << "\n";
502 return ASTReaderListener::ReadFullVersionInformation(FullVersion);
505 void ReadModuleName(StringRef ModuleName) override {
506 Out.indent(2) << "Module name: " << ModuleName << "\n";
508 void ReadModuleMapFile(StringRef ModuleMapPath) override {
509 Out.indent(2) << "Module map file: " << ModuleMapPath << "\n";
512 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
513 bool AllowCompatibleDifferences) override {
514 Out.indent(2) << "Language options:\n";
515 #define LANGOPT(Name, Bits, Default, Description) \
516 DUMP_BOOLEAN(LangOpts.Name, Description);
517 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
518 Out.indent(4) << Description << ": " \
519 << static_cast<unsigned>(LangOpts.get##Name()) << "\n";
520 #define VALUE_LANGOPT(Name, Bits, Default, Description) \
521 Out.indent(4) << Description << ": " << LangOpts.Name << "\n";
522 #define BENIGN_LANGOPT(Name, Bits, Default, Description)
523 #define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
524 #include "clang/Basic/LangOptions.def"
526 if (!LangOpts.ModuleFeatures.empty()) {
527 Out.indent(4) << "Module features:\n";
528 for (StringRef Feature : LangOpts.ModuleFeatures)
529 Out.indent(6) << Feature << "\n";
535 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
536 bool AllowCompatibleDifferences) override {
537 Out.indent(2) << "Target options:\n";
538 Out.indent(4) << " Triple: " << TargetOpts.Triple << "\n";
539 Out.indent(4) << " CPU: " << TargetOpts.CPU << "\n";
540 Out.indent(4) << " ABI: " << TargetOpts.ABI << "\n";
542 if (!TargetOpts.FeaturesAsWritten.empty()) {
543 Out.indent(4) << "Target features:\n";
544 for (unsigned I = 0, N = TargetOpts.FeaturesAsWritten.size();
546 Out.indent(6) << TargetOpts.FeaturesAsWritten[I] << "\n";
553 bool ReadDiagnosticOptions(IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts,
554 bool Complain) override {
555 Out.indent(2) << "Diagnostic options:\n";
556 #define DIAGOPT(Name, Bits, Default) DUMP_BOOLEAN(DiagOpts->Name, #Name);
557 #define ENUM_DIAGOPT(Name, Type, Bits, Default) \
558 Out.indent(4) << #Name << ": " << DiagOpts->get##Name() << "\n";
559 #define VALUE_DIAGOPT(Name, Bits, Default) \
560 Out.indent(4) << #Name << ": " << DiagOpts->Name << "\n";
561 #include "clang/Basic/DiagnosticOptions.def"
563 Out.indent(4) << "Diagnostic flags:\n";
564 for (const std::string &Warning : DiagOpts->Warnings)
565 Out.indent(6) << "-W" << Warning << "\n";
566 for (const std::string &Remark : DiagOpts->Remarks)
567 Out.indent(6) << "-R" << Remark << "\n";
572 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
573 StringRef SpecificModuleCachePath,
574 bool Complain) override {
575 Out.indent(2) << "Header search options:\n";
576 Out.indent(4) << "System root [-isysroot=]: '" << HSOpts.Sysroot << "'\n";
577 Out.indent(4) << "Resource dir [ -resource-dir=]: '" << HSOpts.ResourceDir << "'\n";
578 Out.indent(4) << "Module Cache: '" << SpecificModuleCachePath << "'\n";
579 DUMP_BOOLEAN(HSOpts.UseBuiltinIncludes,
580 "Use builtin include directories [-nobuiltininc]");
581 DUMP_BOOLEAN(HSOpts.UseStandardSystemIncludes,
582 "Use standard system include directories [-nostdinc]");
583 DUMP_BOOLEAN(HSOpts.UseStandardCXXIncludes,
584 "Use standard C++ include directories [-nostdinc++]");
585 DUMP_BOOLEAN(HSOpts.UseLibcxx,
586 "Use libc++ (rather than libstdc++) [-stdlib=]");
590 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
592 std::string &SuggestedPredefines) override {
593 Out.indent(2) << "Preprocessor options:\n";
594 DUMP_BOOLEAN(PPOpts.UsePredefines,
595 "Uses compiler/target-specific predefines [-undef]");
596 DUMP_BOOLEAN(PPOpts.DetailedRecord,
597 "Uses detailed preprocessing record (for indexing)");
599 if (!PPOpts.Macros.empty()) {
600 Out.indent(4) << "Predefined macros:\n";
603 for (std::vector<std::pair<std::string, bool/*isUndef*/> >::const_iterator
604 I = PPOpts.Macros.begin(), IEnd = PPOpts.Macros.end();
611 Out << I->first << "\n";
616 /// Indicates that a particular module file extension has been read.
617 void readModuleFileExtension(
618 const ModuleFileExtensionMetadata &Metadata) override {
619 Out.indent(2) << "Module file extension '"
620 << Metadata.BlockName << "' " << Metadata.MajorVersion
621 << "." << Metadata.MinorVersion;
622 if (!Metadata.UserInfo.empty()) {
624 Out.write_escaped(Metadata.UserInfo);
633 bool DumpModuleInfoAction::BeginInvocation(CompilerInstance &CI) {
634 // The Object file reader also supports raw ast files and there is no point in
635 // being strict about the module file format in -module-file-info mode.
636 CI.getHeaderSearchOpts().ModuleFormat = "obj";
640 void DumpModuleInfoAction::ExecuteAction() {
641 // Set up the output file.
642 std::unique_ptr<llvm::raw_fd_ostream> OutFile;
643 StringRef OutputFileName = getCompilerInstance().getFrontendOpts().OutputFile;
644 if (!OutputFileName.empty() && OutputFileName != "-") {
646 OutFile.reset(new llvm::raw_fd_ostream(OutputFileName.str(), EC,
647 llvm::sys::fs::F_Text));
649 llvm::raw_ostream &Out = OutFile.get()? *OutFile.get() : llvm::outs();
651 Out << "Information for module file '" << getCurrentFile() << "':\n";
652 auto &FileMgr = getCompilerInstance().getFileManager();
653 auto Buffer = FileMgr.getBufferForFile(getCurrentFile());
654 StringRef Magic = (*Buffer)->getMemBufferRef().getBuffer();
655 bool IsRaw = (Magic.size() >= 4 && Magic[0] == 'C' && Magic[1] == 'P' &&
656 Magic[2] == 'C' && Magic[3] == 'H');
657 Out << " Module format: " << (IsRaw ? "raw" : "obj") << "\n";
659 Preprocessor &PP = getCompilerInstance().getPreprocessor();
660 DumpModuleInfoListener Listener(Out);
661 HeaderSearchOptions &HSOpts =
662 PP.getHeaderSearchInfo().getHeaderSearchOpts();
663 ASTReader::readASTFileControlBlock(
664 getCurrentFile(), FileMgr, getCompilerInstance().getPCHContainerReader(),
665 /*FindModuleFileExtensions=*/true, Listener,
666 HSOpts.ModulesValidateDiagnosticOptions);
669 //===----------------------------------------------------------------------===//
670 // Preprocessor Actions
671 //===----------------------------------------------------------------------===//
673 void DumpRawTokensAction::ExecuteAction() {
674 Preprocessor &PP = getCompilerInstance().getPreprocessor();
675 SourceManager &SM = PP.getSourceManager();
677 // Start lexing the specified input file.
678 const llvm::MemoryBuffer *FromFile = SM.getBuffer(SM.getMainFileID());
679 Lexer RawLex(SM.getMainFileID(), FromFile, SM, PP.getLangOpts());
680 RawLex.SetKeepWhitespaceMode(true);
683 RawLex.LexFromRawLexer(RawTok);
684 while (RawTok.isNot(tok::eof)) {
685 PP.DumpToken(RawTok, true);
686 llvm::errs() << "\n";
687 RawLex.LexFromRawLexer(RawTok);
691 void DumpTokensAction::ExecuteAction() {
692 Preprocessor &PP = getCompilerInstance().getPreprocessor();
693 // Start preprocessing the specified input file.
695 PP.EnterMainSourceFile();
698 PP.DumpToken(Tok, true);
699 llvm::errs() << "\n";
700 } while (Tok.isNot(tok::eof));
703 void GeneratePTHAction::ExecuteAction() {
704 CompilerInstance &CI = getCompilerInstance();
705 std::unique_ptr<raw_pwrite_stream> OS =
706 CI.createDefaultOutputFile(true, getCurrentFile());
710 CacheTokens(CI.getPreprocessor(), OS.get());
713 void PreprocessOnlyAction::ExecuteAction() {
714 Preprocessor &PP = getCompilerInstance().getPreprocessor();
716 // Ignore unknown pragmas.
720 // Start parsing the specified input file.
721 PP.EnterMainSourceFile();
724 } while (Tok.isNot(tok::eof));
727 void PrintPreprocessedAction::ExecuteAction() {
728 CompilerInstance &CI = getCompilerInstance();
729 // Output file may need to be set to 'Binary', to avoid converting Unix style
730 // line feeds (<LF>) to Microsoft style line feeds (<CR><LF>).
732 // Look to see what type of line endings the file uses. If there's a
733 // CRLF, then we won't open the file up in binary mode. If there is
734 // just an LF or CR, then we will open the file up in binary mode.
735 // In this fashion, the output format should match the input format, unless
736 // the input format has inconsistent line endings.
738 // This should be a relatively fast operation since most files won't have
739 // all of their source code on a single line. However, that is still a
740 // concern, so if we scan for too long, we'll just assume the file should
741 // be opened in binary mode.
742 bool BinaryMode = true;
743 bool InvalidFile = false;
744 const SourceManager& SM = CI.getSourceManager();
745 const llvm::MemoryBuffer *Buffer = SM.getBuffer(SM.getMainFileID(),
748 const char *cur = Buffer->getBufferStart();
749 const char *end = Buffer->getBufferEnd();
750 const char *next = (cur != end) ? cur + 1 : end;
752 // Limit ourselves to only scanning 256 characters into the source
753 // file. This is mostly a sanity check in case the file has no
754 // newlines whatsoever.
755 if (end - cur > 256) end = cur + 256;
758 if (*cur == 0x0D) { // CR
759 if (*next == 0x0A) // CRLF
763 } else if (*cur == 0x0A) // LF
771 std::unique_ptr<raw_ostream> OS =
772 CI.createDefaultOutputFile(BinaryMode, getCurrentFile());
775 DoPrintPreprocessedInput(CI.getPreprocessor(), OS.get(),
776 CI.getPreprocessorOutputOpts());
779 void PrintPreambleAction::ExecuteAction() {
780 switch (getCurrentFileKind()) {
791 case IK_PreprocessedC:
792 case IK_PreprocessedCuda:
793 case IK_PreprocessedCXX:
794 case IK_PreprocessedObjC:
795 case IK_PreprocessedObjCXX:
798 case IK_RenderScript:
799 // We can't do anything with these.
803 CompilerInstance &CI = getCompilerInstance();
804 auto Buffer = CI.getFileManager().getBufferForFile(getCurrentFile());
807 Lexer::ComputePreamble((*Buffer)->getBuffer(), CI.getLangOpts()).first;
808 llvm::outs().write((*Buffer)->getBufferStart(), Preamble);