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/Sema/TemplateInstCallback.h"
22 #include "clang/Serialization/ASTReader.h"
23 #include "clang/Serialization/ASTWriter.h"
24 #include "llvm/Support/FileSystem.h"
25 #include "llvm/Support/MemoryBuffer.h"
26 #include "llvm/Support/Path.h"
27 #include "llvm/Support/raw_ostream.h"
28 #include "llvm/Support/YAMLTraits.h"
30 #include <system_error>
32 using namespace clang;
35 CodeCompleteConsumer *GetCodeCompletionConsumer(CompilerInstance &CI) {
36 return CI.hasCodeCompletionConsumer() ? &CI.getCodeCompletionConsumer()
40 void EnsureSemaIsCreated(CompilerInstance &CI, FrontendAction &Action) {
41 if (Action.hasCodeCompletionSupport() &&
42 !CI.getFrontendOpts().CodeCompletionAt.FileName.empty())
43 CI.createCodeCompletionConsumer();
46 CI.createSema(Action.getTranslationUnitKind(),
47 GetCodeCompletionConsumer(CI));
51 //===----------------------------------------------------------------------===//
53 //===----------------------------------------------------------------------===//
55 std::unique_ptr<ASTConsumer>
56 InitOnlyAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
57 return llvm::make_unique<ASTConsumer>();
60 void InitOnlyAction::ExecuteAction() {
63 //===----------------------------------------------------------------------===//
64 // AST Consumer Actions
65 //===----------------------------------------------------------------------===//
67 std::unique_ptr<ASTConsumer>
68 ASTPrintAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
69 if (std::unique_ptr<raw_ostream> OS =
70 CI.createDefaultOutputFile(false, InFile))
71 return CreateASTPrinter(std::move(OS), CI.getFrontendOpts().ASTDumpFilter);
75 std::unique_ptr<ASTConsumer>
76 ASTDumpAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
77 return CreateASTDumper(nullptr /*Dump to stdout.*/,
78 CI.getFrontendOpts().ASTDumpFilter,
79 CI.getFrontendOpts().ASTDumpDecls,
80 CI.getFrontendOpts().ASTDumpAll,
81 CI.getFrontendOpts().ASTDumpLookups);
84 std::unique_ptr<ASTConsumer>
85 ASTDeclListAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
86 return CreateASTDeclNodeLister();
89 std::unique_ptr<ASTConsumer>
90 ASTViewAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
91 return CreateASTViewer();
94 std::unique_ptr<ASTConsumer>
95 DeclContextPrintAction::CreateASTConsumer(CompilerInstance &CI,
97 return CreateDeclContextPrinter();
100 std::unique_ptr<ASTConsumer>
101 GeneratePCHAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
103 if (!ComputeASTConsumerArguments(CI, /*ref*/ Sysroot))
106 std::string OutputFile;
107 std::unique_ptr<raw_pwrite_stream> OS =
108 CreateOutputFile(CI, InFile, /*ref*/ OutputFile);
112 if (!CI.getFrontendOpts().RelocatablePCH)
115 const auto &FrontendOpts = CI.getFrontendOpts();
116 auto Buffer = std::make_shared<PCHBuffer>();
117 std::vector<std::unique_ptr<ASTConsumer>> Consumers;
118 Consumers.push_back(llvm::make_unique<PCHGenerator>(
119 CI.getPreprocessor(), OutputFile, Sysroot,
120 Buffer, FrontendOpts.ModuleFileExtensions,
121 CI.getPreprocessorOpts().AllowPCHWithCompilerErrors,
122 FrontendOpts.IncludeTimestamps));
123 Consumers.push_back(CI.getPCHContainerWriter().CreatePCHContainerGenerator(
124 CI, InFile, OutputFile, std::move(OS), Buffer));
126 return llvm::make_unique<MultiplexConsumer>(std::move(Consumers));
129 bool GeneratePCHAction::ComputeASTConsumerArguments(CompilerInstance &CI,
130 std::string &Sysroot) {
131 Sysroot = CI.getHeaderSearchOpts().Sysroot;
132 if (CI.getFrontendOpts().RelocatablePCH && Sysroot.empty()) {
133 CI.getDiagnostics().Report(diag::err_relocatable_without_isysroot);
140 std::unique_ptr<llvm::raw_pwrite_stream>
141 GeneratePCHAction::CreateOutputFile(CompilerInstance &CI, StringRef InFile,
142 std::string &OutputFile) {
143 // We use createOutputFile here because this is exposed via libclang, and we
144 // must disable the RemoveFileOnSignal behavior.
145 // We use a temporary to avoid race conditions.
146 std::unique_ptr<raw_pwrite_stream> OS =
147 CI.createOutputFile(CI.getFrontendOpts().OutputFile, /*Binary=*/true,
148 /*RemoveFileOnSignal=*/false, InFile,
149 /*Extension=*/"", /*useTemporary=*/true);
153 OutputFile = CI.getFrontendOpts().OutputFile;
157 bool GeneratePCHAction::shouldEraseOutputFiles() {
158 if (getCompilerInstance().getPreprocessorOpts().AllowPCHWithCompilerErrors)
160 return ASTFrontendAction::shouldEraseOutputFiles();
163 bool GeneratePCHAction::BeginSourceFileAction(CompilerInstance &CI) {
164 CI.getLangOpts().CompilingPCH = true;
168 std::unique_ptr<ASTConsumer>
169 GenerateModuleAction::CreateASTConsumer(CompilerInstance &CI,
171 std::unique_ptr<raw_pwrite_stream> OS = CreateOutputFile(CI, InFile);
175 std::string OutputFile = CI.getFrontendOpts().OutputFile;
178 auto Buffer = std::make_shared<PCHBuffer>();
179 std::vector<std::unique_ptr<ASTConsumer>> Consumers;
181 Consumers.push_back(llvm::make_unique<PCHGenerator>(
182 CI.getPreprocessor(), OutputFile, Sysroot,
183 Buffer, CI.getFrontendOpts().ModuleFileExtensions,
184 /*AllowASTWithErrors=*/false,
185 /*IncludeTimestamps=*/
186 +CI.getFrontendOpts().BuildingImplicitModule));
187 Consumers.push_back(CI.getPCHContainerWriter().CreatePCHContainerGenerator(
188 CI, InFile, OutputFile, std::move(OS), Buffer));
189 return llvm::make_unique<MultiplexConsumer>(std::move(Consumers));
192 bool GenerateModuleFromModuleMapAction::BeginSourceFileAction(
193 CompilerInstance &CI) {
194 if (!CI.getLangOpts().Modules) {
195 CI.getDiagnostics().Report(diag::err_module_build_requires_fmodules);
199 return GenerateModuleAction::BeginSourceFileAction(CI);
202 std::unique_ptr<raw_pwrite_stream>
203 GenerateModuleFromModuleMapAction::CreateOutputFile(CompilerInstance &CI,
205 // If no output file was provided, figure out where this module would go
206 // in the module cache.
207 if (CI.getFrontendOpts().OutputFile.empty()) {
208 StringRef ModuleMapFile = CI.getFrontendOpts().OriginalModuleMap;
209 if (ModuleMapFile.empty())
210 ModuleMapFile = InFile;
212 HeaderSearch &HS = CI.getPreprocessor().getHeaderSearchInfo();
213 CI.getFrontendOpts().OutputFile =
214 HS.getCachedModuleFileName(CI.getLangOpts().CurrentModule,
218 // We use createOutputFile here because this is exposed via libclang, and we
219 // must disable the RemoveFileOnSignal behavior.
220 // We use a temporary to avoid race conditions.
221 return CI.createOutputFile(CI.getFrontendOpts().OutputFile, /*Binary=*/true,
222 /*RemoveFileOnSignal=*/false, InFile,
223 /*Extension=*/"", /*useTemporary=*/true,
224 /*CreateMissingDirectories=*/true);
227 bool GenerateModuleInterfaceAction::BeginSourceFileAction(
228 CompilerInstance &CI) {
229 if (!CI.getLangOpts().ModulesTS) {
230 CI.getDiagnostics().Report(diag::err_module_interface_requires_modules_ts);
234 CI.getLangOpts().setCompilingModule(LangOptions::CMK_ModuleInterface);
236 return GenerateModuleAction::BeginSourceFileAction(CI);
239 std::unique_ptr<raw_pwrite_stream>
240 GenerateModuleInterfaceAction::CreateOutputFile(CompilerInstance &CI,
242 return CI.createDefaultOutputFile(/*Binary=*/true, InFile, "pcm");
245 SyntaxOnlyAction::~SyntaxOnlyAction() {
248 std::unique_ptr<ASTConsumer>
249 SyntaxOnlyAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
250 return llvm::make_unique<ASTConsumer>();
253 std::unique_ptr<ASTConsumer>
254 DumpModuleInfoAction::CreateASTConsumer(CompilerInstance &CI,
256 return llvm::make_unique<ASTConsumer>();
259 std::unique_ptr<ASTConsumer>
260 VerifyPCHAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
261 return llvm::make_unique<ASTConsumer>();
264 void VerifyPCHAction::ExecuteAction() {
265 CompilerInstance &CI = getCompilerInstance();
266 bool Preamble = CI.getPreprocessorOpts().PrecompiledPreambleBytes.first != 0;
267 const std::string &Sysroot = CI.getHeaderSearchOpts().Sysroot;
268 std::unique_ptr<ASTReader> Reader(new ASTReader(
269 CI.getPreprocessor(), &CI.getASTContext(), CI.getPCHContainerReader(),
270 CI.getFrontendOpts().ModuleFileExtensions,
271 Sysroot.empty() ? "" : Sysroot.c_str(),
272 /*DisableValidation*/ false,
273 /*AllowPCHWithCompilerErrors*/ false,
274 /*AllowConfigurationMismatch*/ true,
275 /*ValidateSystemInputs*/ true));
277 Reader->ReadAST(getCurrentFile(),
278 Preamble ? serialization::MK_Preamble
279 : serialization::MK_PCH,
281 ASTReader::ARR_ConfigurationMismatch);
285 struct TemplightEntry {
289 std::string DefinitionLocation;
290 std::string PointOfInstantiation;
296 template <> struct MappingTraits<TemplightEntry> {
297 static void mapping(IO &io, TemplightEntry &fields) {
298 io.mapRequired("name", fields.Name);
299 io.mapRequired("kind", fields.Kind);
300 io.mapRequired("event", fields.Event);
301 io.mapRequired("orig", fields.DefinitionLocation);
302 io.mapRequired("poi", fields.PointOfInstantiation);
309 class DefaultTemplateInstCallback : public TemplateInstantiationCallback {
310 using CodeSynthesisContext = Sema::CodeSynthesisContext;
313 void initialize(const Sema &) override {}
315 void finalize(const Sema &) override {}
317 void atTemplateBegin(const Sema &TheSema,
318 const CodeSynthesisContext &Inst) override {
319 displayTemplightEntry<true>(llvm::outs(), TheSema, Inst);
322 void atTemplateEnd(const Sema &TheSema,
323 const CodeSynthesisContext &Inst) override {
324 displayTemplightEntry<false>(llvm::outs(), TheSema, Inst);
328 static std::string toString(CodeSynthesisContext::SynthesisKind Kind) {
330 case CodeSynthesisContext::TemplateInstantiation:
331 return "TemplateInstantiation";
332 case CodeSynthesisContext::DefaultTemplateArgumentInstantiation:
333 return "DefaultTemplateArgumentInstantiation";
334 case CodeSynthesisContext::DefaultFunctionArgumentInstantiation:
335 return "DefaultFunctionArgumentInstantiation";
336 case CodeSynthesisContext::ExplicitTemplateArgumentSubstitution:
337 return "ExplicitTemplateArgumentSubstitution";
338 case CodeSynthesisContext::DeducedTemplateArgumentSubstitution:
339 return "DeducedTemplateArgumentSubstitution";
340 case CodeSynthesisContext::PriorTemplateArgumentSubstitution:
341 return "PriorTemplateArgumentSubstitution";
342 case CodeSynthesisContext::DefaultTemplateArgumentChecking:
343 return "DefaultTemplateArgumentChecking";
344 case CodeSynthesisContext::ExceptionSpecInstantiation:
345 return "ExceptionSpecInstantiation";
346 case CodeSynthesisContext::DeclaringSpecialMember:
347 return "DeclaringSpecialMember";
348 case CodeSynthesisContext::DefiningSynthesizedFunction:
349 return "DefiningSynthesizedFunction";
350 case CodeSynthesisContext::Memoization:
351 return "Memoization";
356 template <bool BeginInstantiation>
357 static void displayTemplightEntry(llvm::raw_ostream &Out, const Sema &TheSema,
358 const CodeSynthesisContext &Inst) {
361 llvm::raw_string_ostream OS(YAML);
362 llvm::yaml::Output YO(OS);
363 TemplightEntry Entry =
364 getTemplightEntry<BeginInstantiation>(TheSema, Inst);
365 llvm::yaml::EmptyContext Context;
366 llvm::yaml::yamlize(YO, Entry, true, Context);
368 Out << "---" << YAML << "\n";
371 template <bool BeginInstantiation>
372 static TemplightEntry getTemplightEntry(const Sema &TheSema,
373 const CodeSynthesisContext &Inst) {
374 TemplightEntry Entry;
375 Entry.Kind = toString(Inst.Kind);
376 Entry.Event = BeginInstantiation ? "Begin" : "End";
377 if (auto *NamedTemplate = dyn_cast_or_null<NamedDecl>(Inst.Entity)) {
378 llvm::raw_string_ostream OS(Entry.Name);
379 NamedTemplate->getNameForDiagnostic(OS, TheSema.getLangOpts(), true);
380 const PresumedLoc DefLoc =
381 TheSema.getSourceManager().getPresumedLoc(Inst.Entity->getLocation());
382 if(!DefLoc.isInvalid())
383 Entry.DefinitionLocation = std::string(DefLoc.getFilename()) + ":" +
384 std::to_string(DefLoc.getLine()) + ":" +
385 std::to_string(DefLoc.getColumn());
387 const PresumedLoc PoiLoc =
388 TheSema.getSourceManager().getPresumedLoc(Inst.PointOfInstantiation);
389 if (!PoiLoc.isInvalid()) {
390 Entry.PointOfInstantiation = std::string(PoiLoc.getFilename()) + ":" +
391 std::to_string(PoiLoc.getLine()) + ":" +
392 std::to_string(PoiLoc.getColumn());
399 std::unique_ptr<ASTConsumer>
400 TemplightDumpAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
401 return llvm::make_unique<ASTConsumer>();
404 void TemplightDumpAction::ExecuteAction() {
405 CompilerInstance &CI = getCompilerInstance();
407 // This part is normally done by ASTFrontEndAction, but needs to happen
408 // before Templight observers can be created
409 // FIXME: Move the truncation aspect of this into Sema, we delayed this till
410 // here so the source manager would be initialized.
411 EnsureSemaIsCreated(CI, *this);
413 CI.getSema().TemplateInstCallbacks.push_back(
414 llvm::make_unique<DefaultTemplateInstCallback>());
415 ASTFrontendAction::ExecuteAction();
419 /// AST reader listener that dumps module information for a module
421 class DumpModuleInfoListener : public ASTReaderListener {
422 llvm::raw_ostream &Out;
425 DumpModuleInfoListener(llvm::raw_ostream &Out) : Out(Out) { }
427 #define DUMP_BOOLEAN(Value, Text) \
428 Out.indent(4) << Text << ": " << (Value? "Yes" : "No") << "\n"
430 bool ReadFullVersionInformation(StringRef FullVersion) override {
433 << (FullVersion == getClangFullRepositoryVersion()? "this"
435 << " Clang: " << FullVersion << "\n";
436 return ASTReaderListener::ReadFullVersionInformation(FullVersion);
439 void ReadModuleName(StringRef ModuleName) override {
440 Out.indent(2) << "Module name: " << ModuleName << "\n";
442 void ReadModuleMapFile(StringRef ModuleMapPath) override {
443 Out.indent(2) << "Module map file: " << ModuleMapPath << "\n";
446 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
447 bool AllowCompatibleDifferences) override {
448 Out.indent(2) << "Language options:\n";
449 #define LANGOPT(Name, Bits, Default, Description) \
450 DUMP_BOOLEAN(LangOpts.Name, Description);
451 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
452 Out.indent(4) << Description << ": " \
453 << static_cast<unsigned>(LangOpts.get##Name()) << "\n";
454 #define VALUE_LANGOPT(Name, Bits, Default, Description) \
455 Out.indent(4) << Description << ": " << LangOpts.Name << "\n";
456 #define BENIGN_LANGOPT(Name, Bits, Default, Description)
457 #define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
458 #include "clang/Basic/LangOptions.def"
460 if (!LangOpts.ModuleFeatures.empty()) {
461 Out.indent(4) << "Module features:\n";
462 for (StringRef Feature : LangOpts.ModuleFeatures)
463 Out.indent(6) << Feature << "\n";
469 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
470 bool AllowCompatibleDifferences) override {
471 Out.indent(2) << "Target options:\n";
472 Out.indent(4) << " Triple: " << TargetOpts.Triple << "\n";
473 Out.indent(4) << " CPU: " << TargetOpts.CPU << "\n";
474 Out.indent(4) << " ABI: " << TargetOpts.ABI << "\n";
476 if (!TargetOpts.FeaturesAsWritten.empty()) {
477 Out.indent(4) << "Target features:\n";
478 for (unsigned I = 0, N = TargetOpts.FeaturesAsWritten.size();
480 Out.indent(6) << TargetOpts.FeaturesAsWritten[I] << "\n";
487 bool ReadDiagnosticOptions(IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts,
488 bool Complain) override {
489 Out.indent(2) << "Diagnostic options:\n";
490 #define DIAGOPT(Name, Bits, Default) DUMP_BOOLEAN(DiagOpts->Name, #Name);
491 #define ENUM_DIAGOPT(Name, Type, Bits, Default) \
492 Out.indent(4) << #Name << ": " << DiagOpts->get##Name() << "\n";
493 #define VALUE_DIAGOPT(Name, Bits, Default) \
494 Out.indent(4) << #Name << ": " << DiagOpts->Name << "\n";
495 #include "clang/Basic/DiagnosticOptions.def"
497 Out.indent(4) << "Diagnostic flags:\n";
498 for (const std::string &Warning : DiagOpts->Warnings)
499 Out.indent(6) << "-W" << Warning << "\n";
500 for (const std::string &Remark : DiagOpts->Remarks)
501 Out.indent(6) << "-R" << Remark << "\n";
506 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
507 StringRef SpecificModuleCachePath,
508 bool Complain) override {
509 Out.indent(2) << "Header search options:\n";
510 Out.indent(4) << "System root [-isysroot=]: '" << HSOpts.Sysroot << "'\n";
511 Out.indent(4) << "Resource dir [ -resource-dir=]: '" << HSOpts.ResourceDir << "'\n";
512 Out.indent(4) << "Module Cache: '" << SpecificModuleCachePath << "'\n";
513 DUMP_BOOLEAN(HSOpts.UseBuiltinIncludes,
514 "Use builtin include directories [-nobuiltininc]");
515 DUMP_BOOLEAN(HSOpts.UseStandardSystemIncludes,
516 "Use standard system include directories [-nostdinc]");
517 DUMP_BOOLEAN(HSOpts.UseStandardCXXIncludes,
518 "Use standard C++ include directories [-nostdinc++]");
519 DUMP_BOOLEAN(HSOpts.UseLibcxx,
520 "Use libc++ (rather than libstdc++) [-stdlib=]");
524 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
526 std::string &SuggestedPredefines) override {
527 Out.indent(2) << "Preprocessor options:\n";
528 DUMP_BOOLEAN(PPOpts.UsePredefines,
529 "Uses compiler/target-specific predefines [-undef]");
530 DUMP_BOOLEAN(PPOpts.DetailedRecord,
531 "Uses detailed preprocessing record (for indexing)");
533 if (!PPOpts.Macros.empty()) {
534 Out.indent(4) << "Predefined macros:\n";
537 for (std::vector<std::pair<std::string, bool/*isUndef*/> >::const_iterator
538 I = PPOpts.Macros.begin(), IEnd = PPOpts.Macros.end();
545 Out << I->first << "\n";
550 /// Indicates that a particular module file extension has been read.
551 void readModuleFileExtension(
552 const ModuleFileExtensionMetadata &Metadata) override {
553 Out.indent(2) << "Module file extension '"
554 << Metadata.BlockName << "' " << Metadata.MajorVersion
555 << "." << Metadata.MinorVersion;
556 if (!Metadata.UserInfo.empty()) {
558 Out.write_escaped(Metadata.UserInfo);
564 /// Tells the \c ASTReaderListener that we want to receive the
565 /// input files of the AST file via \c visitInputFile.
566 bool needsInputFileVisitation() override { return true; }
568 /// Tells the \c ASTReaderListener that we want to receive the
569 /// input files of the AST file via \c visitInputFile.
570 bool needsSystemInputFileVisitation() override { return true; }
572 /// Indicates that the AST file contains particular input file.
574 /// \returns true to continue receiving the next input file, false to stop.
575 bool visitInputFile(StringRef Filename, bool isSystem,
576 bool isOverridden, bool isExplicitModule) override {
578 Out.indent(2) << "Input file: " << Filename;
580 if (isSystem || isOverridden || isExplicitModule) {
584 if (isOverridden || isExplicitModule)
589 if (isExplicitModule)
592 if (isExplicitModule)
593 Out << "ExplicitModule";
606 bool DumpModuleInfoAction::BeginInvocation(CompilerInstance &CI) {
607 // The Object file reader also supports raw ast files and there is no point in
608 // being strict about the module file format in -module-file-info mode.
609 CI.getHeaderSearchOpts().ModuleFormat = "obj";
613 void DumpModuleInfoAction::ExecuteAction() {
614 // Set up the output file.
615 std::unique_ptr<llvm::raw_fd_ostream> OutFile;
616 StringRef OutputFileName = getCompilerInstance().getFrontendOpts().OutputFile;
617 if (!OutputFileName.empty() && OutputFileName != "-") {
619 OutFile.reset(new llvm::raw_fd_ostream(OutputFileName.str(), EC,
620 llvm::sys::fs::F_Text));
622 llvm::raw_ostream &Out = OutFile.get()? *OutFile.get() : llvm::outs();
624 Out << "Information for module file '" << getCurrentFile() << "':\n";
625 auto &FileMgr = getCompilerInstance().getFileManager();
626 auto Buffer = FileMgr.getBufferForFile(getCurrentFile());
627 StringRef Magic = (*Buffer)->getMemBufferRef().getBuffer();
628 bool IsRaw = (Magic.size() >= 4 && Magic[0] == 'C' && Magic[1] == 'P' &&
629 Magic[2] == 'C' && Magic[3] == 'H');
630 Out << " Module format: " << (IsRaw ? "raw" : "obj") << "\n";
632 Preprocessor &PP = getCompilerInstance().getPreprocessor();
633 DumpModuleInfoListener Listener(Out);
634 HeaderSearchOptions &HSOpts =
635 PP.getHeaderSearchInfo().getHeaderSearchOpts();
636 ASTReader::readASTFileControlBlock(
637 getCurrentFile(), FileMgr, getCompilerInstance().getPCHContainerReader(),
638 /*FindModuleFileExtensions=*/true, Listener,
639 HSOpts.ModulesValidateDiagnosticOptions);
642 //===----------------------------------------------------------------------===//
643 // Preprocessor Actions
644 //===----------------------------------------------------------------------===//
646 void DumpRawTokensAction::ExecuteAction() {
647 Preprocessor &PP = getCompilerInstance().getPreprocessor();
648 SourceManager &SM = PP.getSourceManager();
650 // Start lexing the specified input file.
651 const llvm::MemoryBuffer *FromFile = SM.getBuffer(SM.getMainFileID());
652 Lexer RawLex(SM.getMainFileID(), FromFile, SM, PP.getLangOpts());
653 RawLex.SetKeepWhitespaceMode(true);
656 RawLex.LexFromRawLexer(RawTok);
657 while (RawTok.isNot(tok::eof)) {
658 PP.DumpToken(RawTok, true);
659 llvm::errs() << "\n";
660 RawLex.LexFromRawLexer(RawTok);
664 void DumpTokensAction::ExecuteAction() {
665 Preprocessor &PP = getCompilerInstance().getPreprocessor();
666 // Start preprocessing the specified input file.
668 PP.EnterMainSourceFile();
671 PP.DumpToken(Tok, true);
672 llvm::errs() << "\n";
673 } while (Tok.isNot(tok::eof));
676 void GeneratePTHAction::ExecuteAction() {
677 CompilerInstance &CI = getCompilerInstance();
678 std::unique_ptr<raw_pwrite_stream> OS =
679 CI.createDefaultOutputFile(true, getCurrentFile());
683 CacheTokens(CI.getPreprocessor(), OS.get());
686 void PreprocessOnlyAction::ExecuteAction() {
687 Preprocessor &PP = getCompilerInstance().getPreprocessor();
689 // Ignore unknown pragmas.
693 // Start parsing the specified input file.
694 PP.EnterMainSourceFile();
697 } while (Tok.isNot(tok::eof));
700 void PrintPreprocessedAction::ExecuteAction() {
701 CompilerInstance &CI = getCompilerInstance();
702 // Output file may need to be set to 'Binary', to avoid converting Unix style
703 // line feeds (<LF>) to Microsoft style line feeds (<CR><LF>).
705 // Look to see what type of line endings the file uses. If there's a
706 // CRLF, then we won't open the file up in binary mode. If there is
707 // just an LF or CR, then we will open the file up in binary mode.
708 // In this fashion, the output format should match the input format, unless
709 // the input format has inconsistent line endings.
711 // This should be a relatively fast operation since most files won't have
712 // all of their source code on a single line. However, that is still a
713 // concern, so if we scan for too long, we'll just assume the file should
714 // be opened in binary mode.
715 bool BinaryMode = true;
716 bool InvalidFile = false;
717 const SourceManager& SM = CI.getSourceManager();
718 const llvm::MemoryBuffer *Buffer = SM.getBuffer(SM.getMainFileID(),
721 const char *cur = Buffer->getBufferStart();
722 const char *end = Buffer->getBufferEnd();
723 const char *next = (cur != end) ? cur + 1 : end;
725 // Limit ourselves to only scanning 256 characters into the source
726 // file. This is mostly a sanity check in case the file has no
727 // newlines whatsoever.
728 if (end - cur > 256) end = cur + 256;
731 if (*cur == 0x0D) { // CR
732 if (*next == 0x0A) // CRLF
736 } else if (*cur == 0x0A) // LF
744 std::unique_ptr<raw_ostream> OS =
745 CI.createDefaultOutputFile(BinaryMode, getCurrentFile());
748 // If we're preprocessing a module map, start by dumping the contents of the
749 // module itself before switching to the input buffer.
750 auto &Input = getCurrentInput();
751 if (Input.getKind().getFormat() == InputKind::ModuleMap) {
752 if (Input.isFile()) {
754 OS->write_escaped(Input.getFile());
757 // FIXME: Include additional information here so that we don't need the
758 // original source files to exist on disk.
759 getCurrentModule()->print(*OS);
760 (*OS) << "#pragma clang module contents\n";
763 DoPrintPreprocessedInput(CI.getPreprocessor(), OS.get(),
764 CI.getPreprocessorOutputOpts());
767 void PrintPreambleAction::ExecuteAction() {
768 switch (getCurrentFileKind().getLanguage()) {
771 case InputKind::ObjC:
772 case InputKind::ObjCXX:
773 case InputKind::OpenCL:
774 case InputKind::CUDA:
778 case InputKind::Unknown:
780 case InputKind::LLVM_IR:
781 case InputKind::RenderScript:
782 // We can't do anything with these.
786 // We don't expect to find any #include directives in a preprocessed input.
787 if (getCurrentFileKind().isPreprocessed())
790 CompilerInstance &CI = getCompilerInstance();
791 auto Buffer = CI.getFileManager().getBufferForFile(getCurrentFile());
794 Lexer::ComputePreamble((*Buffer)->getBuffer(), CI.getLangOpts()).Size;
795 llvm::outs().write((*Buffer)->getBufferStart(), Preamble);
799 void DumpCompilerOptionsAction::ExecuteAction() {
800 CompilerInstance &CI = getCompilerInstance();
801 std::unique_ptr<raw_ostream> OSP =
802 CI.createDefaultOutputFile(false, getCurrentFile());
806 raw_ostream &OS = *OSP;
807 const Preprocessor &PP = CI.getPreprocessor();
808 const LangOptions &LangOpts = PP.getLangOpts();
810 // FIXME: Rather than manually format the JSON (which is awkward due to
811 // needing to remove trailing commas), this should make use of a JSON library.
812 // FIXME: Instead of printing enums as an integral value and specifying the
813 // type as a separate field, use introspection to print the enumerator.
816 OS << "\n\"features\" : [\n";
818 llvm::SmallString<128> Str;
819 #define FEATURE(Name, Predicate) \
820 ("\t{\"" #Name "\" : " + llvm::Twine(Predicate ? "true" : "false") + "},\n") \
822 #include "clang/Basic/Features.def"
824 // Remove the newline and comma from the last entry to ensure this remains
826 OS << Str.substr(0, Str.size() - 2);
830 OS << "\n\"extensions\" : [\n";
832 llvm::SmallString<128> Str;
833 #define EXTENSION(Name, Predicate) \
834 ("\t{\"" #Name "\" : " + llvm::Twine(Predicate ? "true" : "false") + "},\n") \
836 #include "clang/Basic/Features.def"
838 // Remove the newline and comma from the last entry to ensure this remains
840 OS << Str.substr(0, Str.size() - 2);