1 //===--- 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"
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"
28 #include <memory>
29 #include <system_error>
30 
31 using namespace clang;
32 
33 //===----------------------------------------------------------------------===//
34 // Custom Actions
35 //===----------------------------------------------------------------------===//
36 
37 std::unique_ptr<ASTConsumer>
38 InitOnlyAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
39   return llvm::make_unique<ASTConsumer>();
40 }
41 
42 void InitOnlyAction::ExecuteAction() {
43 }
44 
45 //===----------------------------------------------------------------------===//
46 // AST Consumer Actions
47 //===----------------------------------------------------------------------===//
48 
49 std::unique_ptr<ASTConsumer>
50 ASTPrintAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
51   if (raw_ostream *OS = CI.createDefaultOutputFile(false, InFile))
52     return CreateASTPrinter(OS, CI.getFrontendOpts().ASTDumpFilter);
53   return nullptr;
54 }
55 
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().ASTDumpLookups);
61 }
62 
63 std::unique_ptr<ASTConsumer>
64 ASTDeclListAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
65   return CreateASTDeclNodeLister();
66 }
67 
68 std::unique_ptr<ASTConsumer>
69 ASTViewAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
70   return CreateASTViewer();
71 }
72 
73 std::unique_ptr<ASTConsumer>
74 DeclContextPrintAction::CreateASTConsumer(CompilerInstance &CI,
75                                           StringRef InFile) {
76   return CreateDeclContextPrinter();
77 }
78 
79 std::unique_ptr<ASTConsumer>
80 GeneratePCHAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
81   std::string Sysroot;
82   std::string OutputFile;
83   raw_pwrite_stream *OS =
84       ComputeASTConsumerArguments(CI, InFile, Sysroot, OutputFile);
85   if (!OS)
86     return nullptr;
87 
88   if (!CI.getFrontendOpts().RelocatablePCH)
89     Sysroot.clear();
90 
91   auto Buffer = std::make_shared<PCHBuffer>();
92   std::vector<std::unique_ptr<ASTConsumer>> Consumers;
93   Consumers.push_back(llvm::make_unique<PCHGenerator>(
94                         CI.getPreprocessor(), OutputFile, nullptr, Sysroot,
95                         Buffer, CI.getFrontendOpts().ModuleFileExtensions));
96   Consumers.push_back(CI.getPCHContainerWriter().CreatePCHContainerGenerator(
97       CI, InFile, OutputFile, OS, Buffer));
98 
99   return llvm::make_unique<MultiplexConsumer>(std::move(Consumers));
100 }
101 
102 raw_pwrite_stream *GeneratePCHAction::ComputeASTConsumerArguments(
103     CompilerInstance &CI, StringRef InFile, std::string &Sysroot,
104     std::string &OutputFile) {
105   Sysroot = CI.getHeaderSearchOpts().Sysroot;
106   if (CI.getFrontendOpts().RelocatablePCH && Sysroot.empty()) {
107     CI.getDiagnostics().Report(diag::err_relocatable_without_isysroot);
108     return nullptr;
109   }
110 
111   // We use createOutputFile here because this is exposed via libclang, and we
112   // must disable the RemoveFileOnSignal behavior.
113   // We use a temporary to avoid race conditions.
114   raw_pwrite_stream *OS =
115       CI.createOutputFile(CI.getFrontendOpts().OutputFile, /*Binary=*/true,
116                           /*RemoveFileOnSignal=*/false, InFile,
117                           /*Extension=*/"", /*useTemporary=*/true);
118   if (!OS)
119     return nullptr;
120 
121   OutputFile = CI.getFrontendOpts().OutputFile;
122   return OS;
123 }
124 
125 std::unique_ptr<ASTConsumer>
126 GenerateModuleAction::CreateASTConsumer(CompilerInstance &CI,
127                                         StringRef InFile) {
128   std::string Sysroot;
129   std::string OutputFile;
130   raw_pwrite_stream *OS =
131       ComputeASTConsumerArguments(CI, InFile, Sysroot, OutputFile);
132   if (!OS)
133     return nullptr;
134 
135   auto Buffer = std::make_shared<PCHBuffer>();
136   std::vector<std::unique_ptr<ASTConsumer>> Consumers;
137 
138   Consumers.push_back(llvm::make_unique<PCHGenerator>(
139                         CI.getPreprocessor(), OutputFile, Module, Sysroot,
140                         Buffer, CI.getFrontendOpts().ModuleFileExtensions,
141                         /*AllowASTWithErrors=*/false,
142                         /*IncludeTimestamps=*/
143                           +CI.getFrontendOpts().BuildingImplicitModule));
144   Consumers.push_back(CI.getPCHContainerWriter().CreatePCHContainerGenerator(
145       CI, InFile, OutputFile, OS, Buffer));
146   return llvm::make_unique<MultiplexConsumer>(std::move(Consumers));
147 }
148 
149 static SmallVectorImpl<char> &
150 operator+=(SmallVectorImpl<char> &Includes, StringRef RHS) {
151   Includes.append(RHS.begin(), RHS.end());
152   return Includes;
153 }
154 
155 static void addHeaderInclude(StringRef HeaderName,
156                              SmallVectorImpl<char> &Includes,
157                              const LangOptions &LangOpts,
158                              bool IsExternC) {
159   if (IsExternC && LangOpts.CPlusPlus)
160     Includes += "extern \"C\" {\n";
161   if (LangOpts.ObjC1)
162     Includes += "#import \"";
163   else
164     Includes += "#include \"";
165 
166   Includes += HeaderName;
167 
168   Includes += "\"\n";
169   if (IsExternC && LangOpts.CPlusPlus)
170     Includes += "}\n";
171 }
172 
173 /// \brief Collect the set of header includes needed to construct the given
174 /// module and update the TopHeaders file set of the module.
175 ///
176 /// \param Module The module we're collecting includes from.
177 ///
178 /// \param Includes Will be augmented with the set of \#includes or \#imports
179 /// needed to load all of the named headers.
180 static std::error_code
181 collectModuleHeaderIncludes(const LangOptions &LangOpts, FileManager &FileMgr,
182                             ModuleMap &ModMap, clang::Module *Module,
183                             SmallVectorImpl<char> &Includes) {
184   // Don't collect any headers for unavailable modules.
185   if (!Module->isAvailable())
186     return std::error_code();
187 
188   // Add includes for each of these headers.
189   for (auto HK : {Module::HK_Normal, Module::HK_Private}) {
190     for (Module::Header &H : Module->Headers[HK]) {
191       Module->addTopHeader(H.Entry);
192       // Use the path as specified in the module map file. We'll look for this
193       // file relative to the module build directory (the directory containing
194       // the module map file) so this will find the same file that we found
195       // while parsing the module map.
196       addHeaderInclude(H.NameAsWritten, Includes, LangOpts, Module->IsExternC);
197     }
198   }
199   // Note that Module->PrivateHeaders will not be a TopHeader.
200 
201   if (Module::Header UmbrellaHeader = Module->getUmbrellaHeader()) {
202     Module->addTopHeader(UmbrellaHeader.Entry);
203     if (Module->Parent)
204       // Include the umbrella header for submodules.
205       addHeaderInclude(UmbrellaHeader.NameAsWritten, Includes, LangOpts,
206                        Module->IsExternC);
207   } else if (Module::DirectoryName UmbrellaDir = Module->getUmbrellaDir()) {
208     // Add all of the headers we find in this subdirectory.
209     std::error_code EC;
210     SmallString<128> DirNative;
211     llvm::sys::path::native(UmbrellaDir.Entry->getName(), DirNative);
212     for (llvm::sys::fs::recursive_directory_iterator Dir(DirNative, EC),
213                                                      DirEnd;
214          Dir != DirEnd && !EC; Dir.increment(EC)) {
215       // Check whether this entry has an extension typically associated with
216       // headers.
217       if (!llvm::StringSwitch<bool>(llvm::sys::path::extension(Dir->path()))
218           .Cases(".h", ".H", ".hh", ".hpp", true)
219           .Default(false))
220         continue;
221 
222       const FileEntry *Header = FileMgr.getFile(Dir->path());
223       // FIXME: This shouldn't happen unless there is a file system race. Is
224       // that worth diagnosing?
225       if (!Header)
226         continue;
227 
228       // If this header is marked 'unavailable' in this module, don't include
229       // it.
230       if (ModMap.isHeaderUnavailableInModule(Header, Module))
231         continue;
232 
233       // Compute the relative path from the directory to this file.
234       SmallVector<StringRef, 16> Components;
235       auto PathIt = llvm::sys::path::rbegin(Dir->path());
236       for (int I = 0; I != Dir.level() + 1; ++I, ++PathIt)
237         Components.push_back(*PathIt);
238       SmallString<128> RelativeHeader(UmbrellaDir.NameAsWritten);
239       for (auto It = Components.rbegin(), End = Components.rend(); It != End;
240            ++It)
241         llvm::sys::path::append(RelativeHeader, *It);
242 
243       // Include this header as part of the umbrella directory.
244       Module->addTopHeader(Header);
245       addHeaderInclude(RelativeHeader, Includes, LangOpts, Module->IsExternC);
246     }
247 
248     if (EC)
249       return EC;
250   }
251 
252   // Recurse into submodules.
253   for (clang::Module::submodule_iterator Sub = Module->submodule_begin(),
254                                       SubEnd = Module->submodule_end();
255        Sub != SubEnd; ++Sub)
256     if (std::error_code Err = collectModuleHeaderIncludes(
257             LangOpts, FileMgr, ModMap, *Sub, Includes))
258       return Err;
259 
260   return std::error_code();
261 }
262 
263 bool GenerateModuleAction::BeginSourceFileAction(CompilerInstance &CI,
264                                                  StringRef Filename) {
265   CI.getLangOpts().CompilingModule = true;
266 
267   // Find the module map file.
268   const FileEntry *ModuleMap =
269       CI.getFileManager().getFile(Filename, /*openFile*/true);
270   if (!ModuleMap)  {
271     CI.getDiagnostics().Report(diag::err_module_map_not_found)
272       << Filename;
273     return false;
274   }
275 
276   // Set up embedding for any specified files. Do this before we load any
277   // source files, including the primary module map for the compilation.
278   for (const auto &F : CI.getFrontendOpts().ModulesEmbedFiles) {
279     if (const auto *FE = CI.getFileManager().getFile(F, /*openFile*/true))
280       CI.getSourceManager().setFileIsTransient(FE);
281     else
282       CI.getDiagnostics().Report(diag::err_modules_embed_file_not_found) << F;
283   }
284   if (CI.getFrontendOpts().ModulesEmbedAllFiles)
285     CI.getSourceManager().setAllFilesAreTransient(true);
286 
287   // Parse the module map file.
288   HeaderSearch &HS = CI.getPreprocessor().getHeaderSearchInfo();
289   if (HS.loadModuleMapFile(ModuleMap, IsSystem))
290     return false;
291 
292   if (CI.getLangOpts().CurrentModule.empty()) {
293     CI.getDiagnostics().Report(diag::err_missing_module_name);
294 
295     // FIXME: Eventually, we could consider asking whether there was just
296     // a single module described in the module map, and use that as a
297     // default. Then it would be fairly trivial to just "compile" a module
298     // map with a single module (the common case).
299     return false;
300   }
301 
302   // If we're being run from the command-line, the module build stack will not
303   // have been filled in yet, so complete it now in order to allow us to detect
304   // module cycles.
305   SourceManager &SourceMgr = CI.getSourceManager();
306   if (SourceMgr.getModuleBuildStack().empty())
307     SourceMgr.pushModuleBuildStack(CI.getLangOpts().CurrentModule,
308                                    FullSourceLoc(SourceLocation(), SourceMgr));
309 
310   // Dig out the module definition.
311   Module = HS.lookupModule(CI.getLangOpts().CurrentModule,
312                            /*AllowSearch=*/false);
313   if (!Module) {
314     CI.getDiagnostics().Report(diag::err_missing_module)
315       << CI.getLangOpts().CurrentModule << Filename;
316 
317     return false;
318   }
319 
320   // Check whether we can build this module at all.
321   clang::Module::Requirement Requirement;
322   clang::Module::UnresolvedHeaderDirective MissingHeader;
323   if (!Module->isAvailable(CI.getLangOpts(), CI.getTarget(), Requirement,
324                            MissingHeader)) {
325     if (MissingHeader.FileNameLoc.isValid()) {
326       CI.getDiagnostics().Report(MissingHeader.FileNameLoc,
327                                  diag::err_module_header_missing)
328         << MissingHeader.IsUmbrella << MissingHeader.FileName;
329     } else {
330       CI.getDiagnostics().Report(diag::err_module_unavailable)
331         << Module->getFullModuleName()
332         << Requirement.second << Requirement.first;
333     }
334 
335     return false;
336   }
337 
338   if (ModuleMapForUniquing && ModuleMapForUniquing != ModuleMap) {
339     Module->IsInferred = true;
340     HS.getModuleMap().setInferredModuleAllowedBy(Module, ModuleMapForUniquing);
341   } else {
342     ModuleMapForUniquing = ModuleMap;
343   }
344 
345   FileManager &FileMgr = CI.getFileManager();
346 
347   // Collect the set of #includes we need to build the module.
348   SmallString<256> HeaderContents;
349   std::error_code Err = std::error_code();
350   if (Module::Header UmbrellaHeader = Module->getUmbrellaHeader())
351     addHeaderInclude(UmbrellaHeader.NameAsWritten, HeaderContents,
352                      CI.getLangOpts(), Module->IsExternC);
353   Err = collectModuleHeaderIncludes(
354         CI.getLangOpts(), FileMgr,
355         CI.getPreprocessor().getHeaderSearchInfo().getModuleMap(), Module,
356         HeaderContents);
357 
358   if (Err) {
359     CI.getDiagnostics().Report(diag::err_module_cannot_create_includes)
360       << Module->getFullModuleName() << Err.message();
361     return false;
362   }
363 
364   // Inform the preprocessor that includes from within the input buffer should
365   // be resolved relative to the build directory of the module map file.
366   CI.getPreprocessor().setMainFileDir(Module->Directory);
367 
368   std::unique_ptr<llvm::MemoryBuffer> InputBuffer =
369       llvm::MemoryBuffer::getMemBufferCopy(HeaderContents,
370                                            Module::getModuleInputBufferName());
371   // Ownership of InputBuffer will be transferred to the SourceManager.
372   setCurrentInput(FrontendInputFile(InputBuffer.release(), getCurrentFileKind(),
373                                     Module->IsSystem));
374   return true;
375 }
376 
377 raw_pwrite_stream *GenerateModuleAction::ComputeASTConsumerArguments(
378     CompilerInstance &CI, StringRef InFile, std::string &Sysroot,
379     std::string &OutputFile) {
380   // If no output file was provided, figure out where this module would go
381   // in the module cache.
382   if (CI.getFrontendOpts().OutputFile.empty()) {
383     HeaderSearch &HS = CI.getPreprocessor().getHeaderSearchInfo();
384     CI.getFrontendOpts().OutputFile =
385         HS.getModuleFileName(CI.getLangOpts().CurrentModule,
386                              ModuleMapForUniquing->getName());
387   }
388 
389   // We use createOutputFile here because this is exposed via libclang, and we
390   // must disable the RemoveFileOnSignal behavior.
391   // We use a temporary to avoid race conditions.
392   raw_pwrite_stream *OS =
393       CI.createOutputFile(CI.getFrontendOpts().OutputFile, /*Binary=*/true,
394                           /*RemoveFileOnSignal=*/false, InFile,
395                           /*Extension=*/"", /*useTemporary=*/true,
396                           /*CreateMissingDirectories=*/true);
397   if (!OS)
398     return nullptr;
399 
400   OutputFile = CI.getFrontendOpts().OutputFile;
401   return OS;
402 }
403 
404 std::unique_ptr<ASTConsumer>
405 SyntaxOnlyAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
406   return llvm::make_unique<ASTConsumer>();
407 }
408 
409 std::unique_ptr<ASTConsumer>
410 DumpModuleInfoAction::CreateASTConsumer(CompilerInstance &CI,
411                                         StringRef InFile) {
412   return llvm::make_unique<ASTConsumer>();
413 }
414 
415 std::unique_ptr<ASTConsumer>
416 VerifyPCHAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
417   return llvm::make_unique<ASTConsumer>();
418 }
419 
420 void VerifyPCHAction::ExecuteAction() {
421   CompilerInstance &CI = getCompilerInstance();
422   bool Preamble = CI.getPreprocessorOpts().PrecompiledPreambleBytes.first != 0;
423   const std::string &Sysroot = CI.getHeaderSearchOpts().Sysroot;
424   std::unique_ptr<ASTReader> Reader(new ASTReader(
425       CI.getPreprocessor(), CI.getASTContext(), CI.getPCHContainerReader(),
426       CI.getFrontendOpts().ModuleFileExtensions,
427       Sysroot.empty() ? "" : Sysroot.c_str(),
428       /*DisableValidation*/ false,
429       /*AllowPCHWithCompilerErrors*/ false,
430       /*AllowConfigurationMismatch*/ true,
431       /*ValidateSystemInputs*/ true));
432 
433   Reader->ReadAST(getCurrentFile(),
434                   Preamble ? serialization::MK_Preamble
435                            : serialization::MK_PCH,
436                   SourceLocation(),
437                   ASTReader::ARR_ConfigurationMismatch);
438 }
439 
440 namespace {
441   /// \brief AST reader listener that dumps module information for a module
442   /// file.
443   class DumpModuleInfoListener : public ASTReaderListener {
444     llvm::raw_ostream &Out;
445 
446   public:
447     DumpModuleInfoListener(llvm::raw_ostream &Out) : Out(Out) { }
448 
449 #define DUMP_BOOLEAN(Value, Text)                       \
450     Out.indent(4) << Text << ": " << (Value? "Yes" : "No") << "\n"
451 
452     bool ReadFullVersionInformation(StringRef FullVersion) override {
453       Out.indent(2)
454         << "Generated by "
455         << (FullVersion == getClangFullRepositoryVersion()? "this"
456                                                           : "a different")
457         << " Clang: " << FullVersion << "\n";
458       return ASTReaderListener::ReadFullVersionInformation(FullVersion);
459     }
460 
461     void ReadModuleName(StringRef ModuleName) override {
462       Out.indent(2) << "Module name: " << ModuleName << "\n";
463     }
464     void ReadModuleMapFile(StringRef ModuleMapPath) override {
465       Out.indent(2) << "Module map file: " << ModuleMapPath << "\n";
466     }
467 
468     bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
469                              bool AllowCompatibleDifferences) override {
470       Out.indent(2) << "Language options:\n";
471 #define LANGOPT(Name, Bits, Default, Description) \
472       DUMP_BOOLEAN(LangOpts.Name, Description);
473 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
474       Out.indent(4) << Description << ": "                   \
475                     << static_cast<unsigned>(LangOpts.get##Name()) << "\n";
476 #define VALUE_LANGOPT(Name, Bits, Default, Description) \
477       Out.indent(4) << Description << ": " << LangOpts.Name << "\n";
478 #define BENIGN_LANGOPT(Name, Bits, Default, Description)
479 #define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
480 #include "clang/Basic/LangOptions.def"
481 
482       if (!LangOpts.ModuleFeatures.empty()) {
483         Out.indent(4) << "Module features:\n";
484         for (StringRef Feature : LangOpts.ModuleFeatures)
485           Out.indent(6) << Feature << "\n";
486       }
487 
488       return false;
489     }
490 
491     bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
492                            bool AllowCompatibleDifferences) override {
493       Out.indent(2) << "Target options:\n";
494       Out.indent(4) << "  Triple: " << TargetOpts.Triple << "\n";
495       Out.indent(4) << "  CPU: " << TargetOpts.CPU << "\n";
496       Out.indent(4) << "  ABI: " << TargetOpts.ABI << "\n";
497 
498       if (!TargetOpts.FeaturesAsWritten.empty()) {
499         Out.indent(4) << "Target features:\n";
500         for (unsigned I = 0, N = TargetOpts.FeaturesAsWritten.size();
501              I != N; ++I) {
502           Out.indent(6) << TargetOpts.FeaturesAsWritten[I] << "\n";
503         }
504       }
505 
506       return false;
507     }
508 
509     bool ReadDiagnosticOptions(IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts,
510                                bool Complain) override {
511       Out.indent(2) << "Diagnostic options:\n";
512 #define DIAGOPT(Name, Bits, Default) DUMP_BOOLEAN(DiagOpts->Name, #Name);
513 #define ENUM_DIAGOPT(Name, Type, Bits, Default) \
514       Out.indent(4) << #Name << ": " << DiagOpts->get##Name() << "\n";
515 #define VALUE_DIAGOPT(Name, Bits, Default) \
516       Out.indent(4) << #Name << ": " << DiagOpts->Name << "\n";
517 #include "clang/Basic/DiagnosticOptions.def"
518 
519       Out.indent(4) << "Diagnostic flags:\n";
520       for (const std::string &Warning : DiagOpts->Warnings)
521         Out.indent(6) << "-W" << Warning << "\n";
522       for (const std::string &Remark : DiagOpts->Remarks)
523         Out.indent(6) << "-R" << Remark << "\n";
524 
525       return false;
526     }
527 
528     bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
529                                  StringRef SpecificModuleCachePath,
530                                  bool Complain) override {
531       Out.indent(2) << "Header search options:\n";
532       Out.indent(4) << "System root [-isysroot=]: '" << HSOpts.Sysroot << "'\n";
533       Out.indent(4) << "Module Cache: '" << SpecificModuleCachePath << "'\n";
534       DUMP_BOOLEAN(HSOpts.UseBuiltinIncludes,
535                    "Use builtin include directories [-nobuiltininc]");
536       DUMP_BOOLEAN(HSOpts.UseStandardSystemIncludes,
537                    "Use standard system include directories [-nostdinc]");
538       DUMP_BOOLEAN(HSOpts.UseStandardCXXIncludes,
539                    "Use standard C++ include directories [-nostdinc++]");
540       DUMP_BOOLEAN(HSOpts.UseLibcxx,
541                    "Use libc++ (rather than libstdc++) [-stdlib=]");
542       return false;
543     }
544 
545     bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
546                                  bool Complain,
547                                  std::string &SuggestedPredefines) override {
548       Out.indent(2) << "Preprocessor options:\n";
549       DUMP_BOOLEAN(PPOpts.UsePredefines,
550                    "Uses compiler/target-specific predefines [-undef]");
551       DUMP_BOOLEAN(PPOpts.DetailedRecord,
552                    "Uses detailed preprocessing record (for indexing)");
553 
554       if (!PPOpts.Macros.empty()) {
555         Out.indent(4) << "Predefined macros:\n";
556       }
557 
558       for (std::vector<std::pair<std::string, bool/*isUndef*/> >::const_iterator
559              I = PPOpts.Macros.begin(), IEnd = PPOpts.Macros.end();
560            I != IEnd; ++I) {
561         Out.indent(6);
562         if (I->second)
563           Out << "-U";
564         else
565           Out << "-D";
566         Out << I->first << "\n";
567       }
568       return false;
569     }
570 
571     /// Indicates that a particular module file extension has been read.
572     void readModuleFileExtension(
573            const ModuleFileExtensionMetadata &Metadata) override {
574       Out.indent(2) << "Module file extension '"
575                     << Metadata.BlockName << "' " << Metadata.MajorVersion
576                     << "." << Metadata.MinorVersion;
577       if (!Metadata.UserInfo.empty()) {
578         Out << ": ";
579         Out.write_escaped(Metadata.UserInfo);
580       }
581 
582       Out << "\n";
583     }
584 #undef DUMP_BOOLEAN
585   };
586 }
587 
588 void DumpModuleInfoAction::ExecuteAction() {
589   // Set up the output file.
590   std::unique_ptr<llvm::raw_fd_ostream> OutFile;
591   StringRef OutputFileName = getCompilerInstance().getFrontendOpts().OutputFile;
592   if (!OutputFileName.empty() && OutputFileName != "-") {
593     std::error_code EC;
594     OutFile.reset(new llvm::raw_fd_ostream(OutputFileName.str(), EC,
595                                            llvm::sys::fs::F_Text));
596   }
597   llvm::raw_ostream &Out = OutFile.get()? *OutFile.get() : llvm::outs();
598 
599   Out << "Information for module file '" << getCurrentFile() << "':\n";
600   DumpModuleInfoListener Listener(Out);
601   ASTReader::readASTFileControlBlock(
602       getCurrentFile(), getCompilerInstance().getFileManager(),
603       getCompilerInstance().getPCHContainerReader(),
604       /*FindModuleFileExtensions=*/true, Listener);
605 }
606 
607 //===----------------------------------------------------------------------===//
608 // Preprocessor Actions
609 //===----------------------------------------------------------------------===//
610 
611 void DumpRawTokensAction::ExecuteAction() {
612   Preprocessor &PP = getCompilerInstance().getPreprocessor();
613   SourceManager &SM = PP.getSourceManager();
614 
615   // Start lexing the specified input file.
616   const llvm::MemoryBuffer *FromFile = SM.getBuffer(SM.getMainFileID());
617   Lexer RawLex(SM.getMainFileID(), FromFile, SM, PP.getLangOpts());
618   RawLex.SetKeepWhitespaceMode(true);
619 
620   Token RawTok;
621   RawLex.LexFromRawLexer(RawTok);
622   while (RawTok.isNot(tok::eof)) {
623     PP.DumpToken(RawTok, true);
624     llvm::errs() << "\n";
625     RawLex.LexFromRawLexer(RawTok);
626   }
627 }
628 
629 void DumpTokensAction::ExecuteAction() {
630   Preprocessor &PP = getCompilerInstance().getPreprocessor();
631   // Start preprocessing the specified input file.
632   Token Tok;
633   PP.EnterMainSourceFile();
634   do {
635     PP.Lex(Tok);
636     PP.DumpToken(Tok, true);
637     llvm::errs() << "\n";
638   } while (Tok.isNot(tok::eof));
639 }
640 
641 void GeneratePTHAction::ExecuteAction() {
642   CompilerInstance &CI = getCompilerInstance();
643   raw_pwrite_stream *OS = CI.createDefaultOutputFile(true, getCurrentFile());
644   if (!OS)
645     return;
646 
647   CacheTokens(CI.getPreprocessor(), OS);
648 }
649 
650 void PreprocessOnlyAction::ExecuteAction() {
651   Preprocessor &PP = getCompilerInstance().getPreprocessor();
652 
653   // Ignore unknown pragmas.
654   PP.IgnorePragmas();
655 
656   Token Tok;
657   // Start parsing the specified input file.
658   PP.EnterMainSourceFile();
659   do {
660     PP.Lex(Tok);
661   } while (Tok.isNot(tok::eof));
662 }
663 
664 void PrintPreprocessedAction::ExecuteAction() {
665   CompilerInstance &CI = getCompilerInstance();
666   // Output file may need to be set to 'Binary', to avoid converting Unix style
667   // line feeds (<LF>) to Microsoft style line feeds (<CR><LF>).
668   //
669   // Look to see what type of line endings the file uses. If there's a
670   // CRLF, then we won't open the file up in binary mode. If there is
671   // just an LF or CR, then we will open the file up in binary mode.
672   // In this fashion, the output format should match the input format, unless
673   // the input format has inconsistent line endings.
674   //
675   // This should be a relatively fast operation since most files won't have
676   // all of their source code on a single line. However, that is still a
677   // concern, so if we scan for too long, we'll just assume the file should
678   // be opened in binary mode.
679   bool BinaryMode = true;
680   bool InvalidFile = false;
681   const SourceManager& SM = CI.getSourceManager();
682   const llvm::MemoryBuffer *Buffer = SM.getBuffer(SM.getMainFileID(),
683                                                      &InvalidFile);
684   if (!InvalidFile) {
685     const char *cur = Buffer->getBufferStart();
686     const char *end = Buffer->getBufferEnd();
687     const char *next = (cur != end) ? cur + 1 : end;
688 
689     // Limit ourselves to only scanning 256 characters into the source
690     // file.  This is mostly a sanity check in case the file has no
691     // newlines whatsoever.
692     if (end - cur > 256) end = cur + 256;
693 
694     while (next < end) {
695       if (*cur == 0x0D) {  // CR
696         if (*next == 0x0A)  // CRLF
697           BinaryMode = false;
698 
699         break;
700       } else if (*cur == 0x0A)  // LF
701         break;
702 
703       ++cur;
704       ++next;
705     }
706   }
707 
708   raw_ostream *OS = CI.createDefaultOutputFile(BinaryMode, getCurrentFile());
709   if (!OS) return;
710 
711   DoPrintPreprocessedInput(CI.getPreprocessor(), OS,
712                            CI.getPreprocessorOutputOpts());
713 }
714 
715 void PrintPreambleAction::ExecuteAction() {
716   switch (getCurrentFileKind()) {
717   case IK_C:
718   case IK_CXX:
719   case IK_ObjC:
720   case IK_ObjCXX:
721   case IK_OpenCL:
722   case IK_CUDA:
723     break;
724 
725   case IK_None:
726   case IK_Asm:
727   case IK_PreprocessedC:
728   case IK_PreprocessedCuda:
729   case IK_PreprocessedCXX:
730   case IK_PreprocessedObjC:
731   case IK_PreprocessedObjCXX:
732   case IK_AST:
733   case IK_LLVM_IR:
734     // We can't do anything with these.
735     return;
736   }
737 
738   CompilerInstance &CI = getCompilerInstance();
739   auto Buffer = CI.getFileManager().getBufferForFile(getCurrentFile());
740   if (Buffer) {
741     unsigned Preamble =
742         Lexer::ComputePreamble((*Buffer)->getBuffer(), CI.getLangOpts()).first;
743     llvm::outs().write((*Buffer)->getBufferStart(), Preamble);
744   }
745 }
746