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