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