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