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