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