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/ASTUnit.h"
15 #include "clang/Frontend/CompilerInstance.h"
16 #include "clang/Frontend/FrontendDiagnostic.h"
17 #include "clang/Frontend/MultiplexConsumer.h"
18 #include "clang/Frontend/Utils.h"
19 #include "clang/Lex/HeaderSearch.h"
20 #include "clang/Lex/Pragma.h"
21 #include "clang/Lex/Preprocessor.h"
22 #include "clang/Parse/Parser.h"
23 #include "clang/Serialization/ASTReader.h"
24 #include "clang/Serialization/ASTWriter.h"
25 #include "llvm/Support/FileSystem.h"
26 #include "llvm/Support/MemoryBuffer.h"
27 #include "llvm/Support/raw_ostream.h"
29 #include <system_error>
31 using namespace clang;
33 //===----------------------------------------------------------------------===//
35 //===----------------------------------------------------------------------===//
37 std::unique_ptr<ASTConsumer>
38 InitOnlyAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
39 return llvm::make_unique<ASTConsumer>();
42 void InitOnlyAction::ExecuteAction() {
45 //===----------------------------------------------------------------------===//
46 // AST Consumer Actions
47 //===----------------------------------------------------------------------===//
49 std::unique_ptr<ASTConsumer>
50 ASTPrintAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
51 if (std::unique_ptr<raw_ostream> OS =
52 CI.createDefaultOutputFile(false, InFile))
53 return CreateASTPrinter(std::move(OS), CI.getFrontendOpts().ASTDumpFilter);
57 std::unique_ptr<ASTConsumer>
58 ASTDumpAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
59 return CreateASTDumper(CI.getFrontendOpts().ASTDumpFilter,
60 CI.getFrontendOpts().ASTDumpDecls,
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, nullptr, Sysroot,
96 Buffer, CI.getFrontendOpts().ModuleFileExtensions,
97 /*AllowASTWithErrors*/false,
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 std::unique_ptr<ASTConsumer>
132 GenerateModuleAction::CreateASTConsumer(CompilerInstance &CI,
135 std::string OutputFile;
136 std::unique_ptr<raw_pwrite_stream> OS =
137 ComputeASTConsumerArguments(CI, InFile, Sysroot, OutputFile);
141 auto Buffer = std::make_shared<PCHBuffer>();
142 std::vector<std::unique_ptr<ASTConsumer>> Consumers;
144 Consumers.push_back(llvm::make_unique<PCHGenerator>(
145 CI.getPreprocessor(), OutputFile, Module, Sysroot,
146 Buffer, CI.getFrontendOpts().ModuleFileExtensions,
147 /*AllowASTWithErrors=*/false,
148 /*IncludeTimestamps=*/
149 +CI.getFrontendOpts().BuildingImplicitModule));
150 Consumers.push_back(CI.getPCHContainerWriter().CreatePCHContainerGenerator(
151 CI, InFile, OutputFile, std::move(OS), Buffer));
152 return llvm::make_unique<MultiplexConsumer>(std::move(Consumers));
155 static SmallVectorImpl<char> &
156 operator+=(SmallVectorImpl<char> &Includes, StringRef RHS) {
157 Includes.append(RHS.begin(), RHS.end());
161 static void addHeaderInclude(StringRef HeaderName,
162 SmallVectorImpl<char> &Includes,
163 const LangOptions &LangOpts,
165 if (IsExternC && LangOpts.CPlusPlus)
166 Includes += "extern \"C\" {\n";
168 Includes += "#import \"";
170 Includes += "#include \"";
172 Includes += HeaderName;
175 if (IsExternC && LangOpts.CPlusPlus)
179 /// \brief Collect the set of header includes needed to construct the given
180 /// module and update the TopHeaders file set of the module.
182 /// \param Module The module we're collecting includes from.
184 /// \param Includes Will be augmented with the set of \#includes or \#imports
185 /// needed to load all of the named headers.
186 static std::error_code
187 collectModuleHeaderIncludes(const LangOptions &LangOpts, FileManager &FileMgr,
188 ModuleMap &ModMap, clang::Module *Module,
189 SmallVectorImpl<char> &Includes) {
190 // Don't collect any headers for unavailable modules.
191 if (!Module->isAvailable())
192 return std::error_code();
194 // Add includes for each of these headers.
195 for (auto HK : {Module::HK_Normal, Module::HK_Private}) {
196 for (Module::Header &H : Module->Headers[HK]) {
197 Module->addTopHeader(H.Entry);
198 // Use the path as specified in the module map file. We'll look for this
199 // file relative to the module build directory (the directory containing
200 // the module map file) so this will find the same file that we found
201 // while parsing the module map.
202 addHeaderInclude(H.NameAsWritten, Includes, LangOpts, Module->IsExternC);
205 // Note that Module->PrivateHeaders will not be a TopHeader.
207 if (Module::Header UmbrellaHeader = Module->getUmbrellaHeader()) {
208 Module->addTopHeader(UmbrellaHeader.Entry);
210 // Include the umbrella header for submodules.
211 addHeaderInclude(UmbrellaHeader.NameAsWritten, Includes, LangOpts,
213 } else if (Module::DirectoryName UmbrellaDir = Module->getUmbrellaDir()) {
214 // Add all of the headers we find in this subdirectory.
216 SmallString<128> DirNative;
217 llvm::sys::path::native(UmbrellaDir.Entry->getName(), DirNative);
219 vfs::FileSystem &FS = *FileMgr.getVirtualFileSystem();
220 for (vfs::recursive_directory_iterator Dir(FS, DirNative, EC), End;
221 Dir != End && !EC; Dir.increment(EC)) {
222 // Check whether this entry has an extension typically associated with
224 if (!llvm::StringSwitch<bool>(llvm::sys::path::extension(Dir->getName()))
225 .Cases(".h", ".H", ".hh", ".hpp", true)
229 const FileEntry *Header = FileMgr.getFile(Dir->getName());
230 // FIXME: This shouldn't happen unless there is a file system race. Is
231 // that worth diagnosing?
235 // If this header is marked 'unavailable' in this module, don't include
237 if (ModMap.isHeaderUnavailableInModule(Header, Module))
240 // Compute the relative path from the directory to this file.
241 SmallVector<StringRef, 16> Components;
242 auto PathIt = llvm::sys::path::rbegin(Dir->getName());
243 for (int I = 0; I != Dir.level() + 1; ++I, ++PathIt)
244 Components.push_back(*PathIt);
245 SmallString<128> RelativeHeader(UmbrellaDir.NameAsWritten);
246 for (auto It = Components.rbegin(), End = Components.rend(); It != End;
248 llvm::sys::path::append(RelativeHeader, *It);
250 // Include this header as part of the umbrella directory.
251 Module->addTopHeader(Header);
252 addHeaderInclude(RelativeHeader, Includes, LangOpts, Module->IsExternC);
259 // Recurse into submodules.
260 for (clang::Module::submodule_iterator Sub = Module->submodule_begin(),
261 SubEnd = Module->submodule_end();
262 Sub != SubEnd; ++Sub)
263 if (std::error_code Err = collectModuleHeaderIncludes(
264 LangOpts, FileMgr, ModMap, *Sub, Includes))
267 return std::error_code();
270 bool GenerateModuleAction::BeginSourceFileAction(CompilerInstance &CI,
271 StringRef Filename) {
272 CI.getLangOpts().CompilingModule = true;
274 // Find the module map file.
275 const FileEntry *ModuleMap =
276 CI.getFileManager().getFile(Filename, /*openFile*/true);
278 CI.getDiagnostics().Report(diag::err_module_map_not_found)
283 // Set up embedding for any specified files. Do this before we load any
284 // source files, including the primary module map for the compilation.
285 for (const auto &F : CI.getFrontendOpts().ModulesEmbedFiles) {
286 if (const auto *FE = CI.getFileManager().getFile(F, /*openFile*/true))
287 CI.getSourceManager().setFileIsTransient(FE);
289 CI.getDiagnostics().Report(diag::err_modules_embed_file_not_found) << F;
291 if (CI.getFrontendOpts().ModulesEmbedAllFiles)
292 CI.getSourceManager().setAllFilesAreTransient(true);
294 // Parse the module map file.
295 HeaderSearch &HS = CI.getPreprocessor().getHeaderSearchInfo();
296 if (HS.loadModuleMapFile(ModuleMap, IsSystem))
299 if (CI.getLangOpts().CurrentModule.empty()) {
300 CI.getDiagnostics().Report(diag::err_missing_module_name);
302 // FIXME: Eventually, we could consider asking whether there was just
303 // a single module described in the module map, and use that as a
304 // default. Then it would be fairly trivial to just "compile" a module
305 // map with a single module (the common case).
309 // If we're being run from the command-line, the module build stack will not
310 // have been filled in yet, so complete it now in order to allow us to detect
312 SourceManager &SourceMgr = CI.getSourceManager();
313 if (SourceMgr.getModuleBuildStack().empty())
314 SourceMgr.pushModuleBuildStack(CI.getLangOpts().CurrentModule,
315 FullSourceLoc(SourceLocation(), SourceMgr));
317 // Dig out the module definition.
318 Module = HS.lookupModule(CI.getLangOpts().CurrentModule,
319 /*AllowSearch=*/false);
321 CI.getDiagnostics().Report(diag::err_missing_module)
322 << CI.getLangOpts().CurrentModule << Filename;
327 // Check whether we can build this module at all.
328 clang::Module::Requirement Requirement;
329 clang::Module::UnresolvedHeaderDirective MissingHeader;
330 if (!Module->isAvailable(CI.getLangOpts(), CI.getTarget(), Requirement,
332 if (MissingHeader.FileNameLoc.isValid()) {
333 CI.getDiagnostics().Report(MissingHeader.FileNameLoc,
334 diag::err_module_header_missing)
335 << MissingHeader.IsUmbrella << MissingHeader.FileName;
337 CI.getDiagnostics().Report(diag::err_module_unavailable)
338 << Module->getFullModuleName()
339 << Requirement.second << Requirement.first;
345 if (ModuleMapForUniquing && ModuleMapForUniquing != ModuleMap) {
346 Module->IsInferred = true;
347 HS.getModuleMap().setInferredModuleAllowedBy(Module, ModuleMapForUniquing);
349 ModuleMapForUniquing = ModuleMap;
352 FileManager &FileMgr = CI.getFileManager();
354 // Collect the set of #includes we need to build the module.
355 SmallString<256> HeaderContents;
356 std::error_code Err = std::error_code();
357 if (Module::Header UmbrellaHeader = Module->getUmbrellaHeader())
358 addHeaderInclude(UmbrellaHeader.NameAsWritten, HeaderContents,
359 CI.getLangOpts(), Module->IsExternC);
360 Err = collectModuleHeaderIncludes(
361 CI.getLangOpts(), FileMgr,
362 CI.getPreprocessor().getHeaderSearchInfo().getModuleMap(), Module,
366 CI.getDiagnostics().Report(diag::err_module_cannot_create_includes)
367 << Module->getFullModuleName() << Err.message();
371 // Inform the preprocessor that includes from within the input buffer should
372 // be resolved relative to the build directory of the module map file.
373 CI.getPreprocessor().setMainFileDir(Module->Directory);
375 std::unique_ptr<llvm::MemoryBuffer> InputBuffer =
376 llvm::MemoryBuffer::getMemBufferCopy(HeaderContents,
377 Module::getModuleInputBufferName());
378 // Ownership of InputBuffer will be transferred to the SourceManager.
379 setCurrentInput(FrontendInputFile(InputBuffer.release(), getCurrentFileKind(),
384 std::unique_ptr<raw_pwrite_stream>
385 GenerateModuleAction::ComputeASTConsumerArguments(CompilerInstance &CI,
387 std::string &Sysroot,
388 std::string &OutputFile) {
389 // If no output file was provided, figure out where this module would go
390 // in the module cache.
391 if (CI.getFrontendOpts().OutputFile.empty()) {
392 HeaderSearch &HS = CI.getPreprocessor().getHeaderSearchInfo();
393 CI.getFrontendOpts().OutputFile =
394 HS.getModuleFileName(CI.getLangOpts().CurrentModule,
395 ModuleMapForUniquing->getName());
398 // We use createOutputFile here because this is exposed via libclang, and we
399 // must disable the RemoveFileOnSignal behavior.
400 // We use a temporary to avoid race conditions.
401 std::unique_ptr<raw_pwrite_stream> OS =
402 CI.createOutputFile(CI.getFrontendOpts().OutputFile, /*Binary=*/true,
403 /*RemoveFileOnSignal=*/false, InFile,
404 /*Extension=*/"", /*useTemporary=*/true,
405 /*CreateMissingDirectories=*/true);
409 OutputFile = CI.getFrontendOpts().OutputFile;
413 SyntaxOnlyAction::~SyntaxOnlyAction() {
416 std::unique_ptr<ASTConsumer>
417 SyntaxOnlyAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
418 return llvm::make_unique<ASTConsumer>();
421 std::unique_ptr<ASTConsumer>
422 DumpModuleInfoAction::CreateASTConsumer(CompilerInstance &CI,
424 return llvm::make_unique<ASTConsumer>();
427 std::unique_ptr<ASTConsumer>
428 VerifyPCHAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
429 return llvm::make_unique<ASTConsumer>();
432 void VerifyPCHAction::ExecuteAction() {
433 CompilerInstance &CI = getCompilerInstance();
434 bool Preamble = CI.getPreprocessorOpts().PrecompiledPreambleBytes.first != 0;
435 const std::string &Sysroot = CI.getHeaderSearchOpts().Sysroot;
436 std::unique_ptr<ASTReader> Reader(new ASTReader(
437 CI.getPreprocessor(), CI.getASTContext(), CI.getPCHContainerReader(),
438 CI.getFrontendOpts().ModuleFileExtensions,
439 Sysroot.empty() ? "" : Sysroot.c_str(),
440 /*DisableValidation*/ false,
441 /*AllowPCHWithCompilerErrors*/ false,
442 /*AllowConfigurationMismatch*/ true,
443 /*ValidateSystemInputs*/ true));
445 Reader->ReadAST(getCurrentFile(),
446 Preamble ? serialization::MK_Preamble
447 : serialization::MK_PCH,
449 ASTReader::ARR_ConfigurationMismatch);
453 /// \brief AST reader listener that dumps module information for a module
455 class DumpModuleInfoListener : public ASTReaderListener {
456 llvm::raw_ostream &Out;
459 DumpModuleInfoListener(llvm::raw_ostream &Out) : Out(Out) { }
461 #define DUMP_BOOLEAN(Value, Text) \
462 Out.indent(4) << Text << ": " << (Value? "Yes" : "No") << "\n"
464 bool ReadFullVersionInformation(StringRef FullVersion) override {
467 << (FullVersion == getClangFullRepositoryVersion()? "this"
469 << " Clang: " << FullVersion << "\n";
470 return ASTReaderListener::ReadFullVersionInformation(FullVersion);
473 void ReadModuleName(StringRef ModuleName) override {
474 Out.indent(2) << "Module name: " << ModuleName << "\n";
476 void ReadModuleMapFile(StringRef ModuleMapPath) override {
477 Out.indent(2) << "Module map file: " << ModuleMapPath << "\n";
480 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
481 bool AllowCompatibleDifferences) override {
482 Out.indent(2) << "Language options:\n";
483 #define LANGOPT(Name, Bits, Default, Description) \
484 DUMP_BOOLEAN(LangOpts.Name, Description);
485 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
486 Out.indent(4) << Description << ": " \
487 << static_cast<unsigned>(LangOpts.get##Name()) << "\n";
488 #define VALUE_LANGOPT(Name, Bits, Default, Description) \
489 Out.indent(4) << Description << ": " << LangOpts.Name << "\n";
490 #define BENIGN_LANGOPT(Name, Bits, Default, Description)
491 #define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
492 #include "clang/Basic/LangOptions.def"
494 if (!LangOpts.ModuleFeatures.empty()) {
495 Out.indent(4) << "Module features:\n";
496 for (StringRef Feature : LangOpts.ModuleFeatures)
497 Out.indent(6) << Feature << "\n";
503 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
504 bool AllowCompatibleDifferences) override {
505 Out.indent(2) << "Target options:\n";
506 Out.indent(4) << " Triple: " << TargetOpts.Triple << "\n";
507 Out.indent(4) << " CPU: " << TargetOpts.CPU << "\n";
508 Out.indent(4) << " ABI: " << TargetOpts.ABI << "\n";
510 if (!TargetOpts.FeaturesAsWritten.empty()) {
511 Out.indent(4) << "Target features:\n";
512 for (unsigned I = 0, N = TargetOpts.FeaturesAsWritten.size();
514 Out.indent(6) << TargetOpts.FeaturesAsWritten[I] << "\n";
521 bool ReadDiagnosticOptions(IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts,
522 bool Complain) override {
523 Out.indent(2) << "Diagnostic options:\n";
524 #define DIAGOPT(Name, Bits, Default) DUMP_BOOLEAN(DiagOpts->Name, #Name);
525 #define ENUM_DIAGOPT(Name, Type, Bits, Default) \
526 Out.indent(4) << #Name << ": " << DiagOpts->get##Name() << "\n";
527 #define VALUE_DIAGOPT(Name, Bits, Default) \
528 Out.indent(4) << #Name << ": " << DiagOpts->Name << "\n";
529 #include "clang/Basic/DiagnosticOptions.def"
531 Out.indent(4) << "Diagnostic flags:\n";
532 for (const std::string &Warning : DiagOpts->Warnings)
533 Out.indent(6) << "-W" << Warning << "\n";
534 for (const std::string &Remark : DiagOpts->Remarks)
535 Out.indent(6) << "-R" << Remark << "\n";
540 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
541 StringRef SpecificModuleCachePath,
542 bool Complain) override {
543 Out.indent(2) << "Header search options:\n";
544 Out.indent(4) << "System root [-isysroot=]: '" << HSOpts.Sysroot << "'\n";
545 Out.indent(4) << "Module Cache: '" << SpecificModuleCachePath << "'\n";
546 DUMP_BOOLEAN(HSOpts.UseBuiltinIncludes,
547 "Use builtin include directories [-nobuiltininc]");
548 DUMP_BOOLEAN(HSOpts.UseStandardSystemIncludes,
549 "Use standard system include directories [-nostdinc]");
550 DUMP_BOOLEAN(HSOpts.UseStandardCXXIncludes,
551 "Use standard C++ include directories [-nostdinc++]");
552 DUMP_BOOLEAN(HSOpts.UseLibcxx,
553 "Use libc++ (rather than libstdc++) [-stdlib=]");
557 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
559 std::string &SuggestedPredefines) override {
560 Out.indent(2) << "Preprocessor options:\n";
561 DUMP_BOOLEAN(PPOpts.UsePredefines,
562 "Uses compiler/target-specific predefines [-undef]");
563 DUMP_BOOLEAN(PPOpts.DetailedRecord,
564 "Uses detailed preprocessing record (for indexing)");
566 if (!PPOpts.Macros.empty()) {
567 Out.indent(4) << "Predefined macros:\n";
570 for (std::vector<std::pair<std::string, bool/*isUndef*/> >::const_iterator
571 I = PPOpts.Macros.begin(), IEnd = PPOpts.Macros.end();
578 Out << I->first << "\n";
583 /// Indicates that a particular module file extension has been read.
584 void readModuleFileExtension(
585 const ModuleFileExtensionMetadata &Metadata) override {
586 Out.indent(2) << "Module file extension '"
587 << Metadata.BlockName << "' " << Metadata.MajorVersion
588 << "." << Metadata.MinorVersion;
589 if (!Metadata.UserInfo.empty()) {
591 Out.write_escaped(Metadata.UserInfo);
600 void DumpModuleInfoAction::ExecuteAction() {
601 // Set up the output file.
602 std::unique_ptr<llvm::raw_fd_ostream> OutFile;
603 StringRef OutputFileName = getCompilerInstance().getFrontendOpts().OutputFile;
604 if (!OutputFileName.empty() && OutputFileName != "-") {
606 OutFile.reset(new llvm::raw_fd_ostream(OutputFileName.str(), EC,
607 llvm::sys::fs::F_Text));
609 llvm::raw_ostream &Out = OutFile.get()? *OutFile.get() : llvm::outs();
611 Out << "Information for module file '" << getCurrentFile() << "':\n";
612 DumpModuleInfoListener Listener(Out);
613 ASTReader::readASTFileControlBlock(
614 getCurrentFile(), getCompilerInstance().getFileManager(),
615 getCompilerInstance().getPCHContainerReader(),
616 /*FindModuleFileExtensions=*/true, Listener);
619 //===----------------------------------------------------------------------===//
620 // Preprocessor Actions
621 //===----------------------------------------------------------------------===//
623 void DumpRawTokensAction::ExecuteAction() {
624 Preprocessor &PP = getCompilerInstance().getPreprocessor();
625 SourceManager &SM = PP.getSourceManager();
627 // Start lexing the specified input file.
628 const llvm::MemoryBuffer *FromFile = SM.getBuffer(SM.getMainFileID());
629 Lexer RawLex(SM.getMainFileID(), FromFile, SM, PP.getLangOpts());
630 RawLex.SetKeepWhitespaceMode(true);
633 RawLex.LexFromRawLexer(RawTok);
634 while (RawTok.isNot(tok::eof)) {
635 PP.DumpToken(RawTok, true);
636 llvm::errs() << "\n";
637 RawLex.LexFromRawLexer(RawTok);
641 void DumpTokensAction::ExecuteAction() {
642 Preprocessor &PP = getCompilerInstance().getPreprocessor();
643 // Start preprocessing the specified input file.
645 PP.EnterMainSourceFile();
648 PP.DumpToken(Tok, true);
649 llvm::errs() << "\n";
650 } while (Tok.isNot(tok::eof));
653 void GeneratePTHAction::ExecuteAction() {
654 CompilerInstance &CI = getCompilerInstance();
655 std::unique_ptr<raw_pwrite_stream> OS =
656 CI.createDefaultOutputFile(true, getCurrentFile());
660 CacheTokens(CI.getPreprocessor(), OS.get());
663 void PreprocessOnlyAction::ExecuteAction() {
664 Preprocessor &PP = getCompilerInstance().getPreprocessor();
666 // Ignore unknown pragmas.
670 // Start parsing the specified input file.
671 PP.EnterMainSourceFile();
674 } while (Tok.isNot(tok::eof));
677 void PrintPreprocessedAction::ExecuteAction() {
678 CompilerInstance &CI = getCompilerInstance();
679 // Output file may need to be set to 'Binary', to avoid converting Unix style
680 // line feeds (<LF>) to Microsoft style line feeds (<CR><LF>).
682 // Look to see what type of line endings the file uses. If there's a
683 // CRLF, then we won't open the file up in binary mode. If there is
684 // just an LF or CR, then we will open the file up in binary mode.
685 // In this fashion, the output format should match the input format, unless
686 // the input format has inconsistent line endings.
688 // This should be a relatively fast operation since most files won't have
689 // all of their source code on a single line. However, that is still a
690 // concern, so if we scan for too long, we'll just assume the file should
691 // be opened in binary mode.
692 bool BinaryMode = true;
693 bool InvalidFile = false;
694 const SourceManager& SM = CI.getSourceManager();
695 const llvm::MemoryBuffer *Buffer = SM.getBuffer(SM.getMainFileID(),
698 const char *cur = Buffer->getBufferStart();
699 const char *end = Buffer->getBufferEnd();
700 const char *next = (cur != end) ? cur + 1 : end;
702 // Limit ourselves to only scanning 256 characters into the source
703 // file. This is mostly a sanity check in case the file has no
704 // newlines whatsoever.
705 if (end - cur > 256) end = cur + 256;
708 if (*cur == 0x0D) { // CR
709 if (*next == 0x0A) // CRLF
713 } else if (*cur == 0x0A) // LF
721 std::unique_ptr<raw_ostream> OS =
722 CI.createDefaultOutputFile(BinaryMode, getCurrentFile());
725 DoPrintPreprocessedInput(CI.getPreprocessor(), OS.get(),
726 CI.getPreprocessorOutputOpts());
729 void PrintPreambleAction::ExecuteAction() {
730 switch (getCurrentFileKind()) {
741 case IK_PreprocessedC:
742 case IK_PreprocessedCuda:
743 case IK_PreprocessedCXX:
744 case IK_PreprocessedObjC:
745 case IK_PreprocessedObjCXX:
748 case IK_RenderScript:
749 // We can't do anything with these.
753 CompilerInstance &CI = getCompilerInstance();
754 auto Buffer = CI.getFileManager().getBufferForFile(getCurrentFile());
757 Lexer::ComputePreamble((*Buffer)->getBuffer(), CI.getLangOpts()).first;
758 llvm::outs().write((*Buffer)->getBufferStart(), Preamble);