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