xref: /llvm-project/clang/lib/Frontend/CompilerInstance.cpp (revision 171b780c914bcee77b9db530bced2647ee1e561e)
1 //===--- CompilerInstance.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/CompilerInstance.h"
11 #include "clang/AST/ASTConsumer.h"
12 #include "clang/AST/ASTContext.h"
13 #include "clang/Basic/Diagnostic.h"
14 #include "clang/Basic/FileManager.h"
15 #include "clang/Basic/SourceManager.h"
16 #include "clang/Basic/TargetInfo.h"
17 #include "clang/Basic/Version.h"
18 #include "clang/Lex/HeaderSearch.h"
19 #include "clang/Lex/Preprocessor.h"
20 #include "clang/Lex/PTHManager.h"
21 #include "clang/Frontend/ChainedDiagnosticClient.h"
22 #include "clang/Frontend/FrontendAction.h"
23 #include "clang/Frontend/PCHReader.h"
24 #include "clang/Frontend/FrontendDiagnostic.h"
25 #include "clang/Frontend/TextDiagnosticPrinter.h"
26 #include "clang/Frontend/VerifyDiagnosticsClient.h"
27 #include "clang/Frontend/Utils.h"
28 #include "clang/Sema/CodeCompleteConsumer.h"
29 #include "llvm/LLVMContext.h"
30 #include "llvm/Support/MemoryBuffer.h"
31 #include "llvm/Support/raw_ostream.h"
32 #include "llvm/ADT/Statistic.h"
33 #include "llvm/Support/Timer.h"
34 #include "llvm/System/Host.h"
35 #include "llvm/System/Path.h"
36 #include "llvm/System/Program.h"
37 using namespace clang;
38 
39 CompilerInstance::CompilerInstance()
40   : Invocation(new CompilerInvocation()) {
41 }
42 
43 CompilerInstance::~CompilerInstance() {
44 }
45 
46 void CompilerInstance::setLLVMContext(llvm::LLVMContext *Value) {
47   LLVMContext.reset(Value);
48 }
49 
50 void CompilerInstance::setInvocation(CompilerInvocation *Value) {
51   Invocation.reset(Value);
52 }
53 
54 void CompilerInstance::setDiagnostics(Diagnostic *Value) {
55   Diagnostics.reset(Value);
56 }
57 
58 void CompilerInstance::setDiagnosticClient(DiagnosticClient *Value) {
59   DiagClient.reset(Value);
60 }
61 
62 void CompilerInstance::setTarget(TargetInfo *Value) {
63   Target.reset(Value);
64 }
65 
66 void CompilerInstance::setFileManager(FileManager *Value) {
67   FileMgr.reset(Value);
68 }
69 
70 void CompilerInstance::setSourceManager(SourceManager *Value) {
71   SourceMgr.reset(Value);
72 }
73 
74 void CompilerInstance::setPreprocessor(Preprocessor *Value) {
75   PP.reset(Value);
76 }
77 
78 void CompilerInstance::setASTContext(ASTContext *Value) {
79   Context.reset(Value);
80 }
81 
82 void CompilerInstance::setASTConsumer(ASTConsumer *Value) {
83   Consumer.reset(Value);
84 }
85 
86 void CompilerInstance::setCodeCompletionConsumer(CodeCompleteConsumer *Value) {
87   CompletionConsumer.reset(Value);
88 }
89 
90 // Diagnostics
91 namespace {
92   class BinaryDiagnosticSerializer : public DiagnosticClient {
93     llvm::raw_ostream &OS;
94     SourceManager *SourceMgr;
95   public:
96     explicit BinaryDiagnosticSerializer(llvm::raw_ostream &OS)
97       : OS(OS), SourceMgr(0) { }
98 
99     virtual void HandleDiagnostic(Diagnostic::Level DiagLevel,
100                                   const DiagnosticInfo &Info);
101   };
102 }
103 
104 void BinaryDiagnosticSerializer::HandleDiagnostic(Diagnostic::Level DiagLevel,
105                                                   const DiagnosticInfo &Info) {
106   StoredDiagnostic(DiagLevel, Info).Serialize(OS);
107 }
108 
109 static void SetUpBuildDumpLog(const DiagnosticOptions &DiagOpts,
110                               unsigned argc, char **argv,
111                               Diagnostic &Diags) {
112   std::string ErrorInfo;
113   llvm::OwningPtr<llvm::raw_ostream> OS(
114     new llvm::raw_fd_ostream(DiagOpts.DumpBuildInformation.c_str(), ErrorInfo));
115   if (!ErrorInfo.empty()) {
116     Diags.Report(diag::err_fe_unable_to_open_logfile)
117                  << DiagOpts.DumpBuildInformation << ErrorInfo;
118     return;
119   }
120 
121   (*OS) << "clang -cc1 command line arguments: ";
122   for (unsigned i = 0; i != argc; ++i)
123     (*OS) << argv[i] << ' ';
124   (*OS) << '\n';
125 
126   // Chain in a diagnostic client which will log the diagnostics.
127   DiagnosticClient *Logger =
128     new TextDiagnosticPrinter(*OS.take(), DiagOpts, /*OwnsOutputStream=*/true);
129   Diags.setClient(new ChainedDiagnosticClient(Diags.getClient(), Logger));
130 }
131 
132 void CompilerInstance::createDiagnostics(int Argc, char **Argv) {
133   Diagnostics.reset(createDiagnostics(getDiagnosticOpts(), Argc, Argv));
134 
135   if (Diagnostics)
136     DiagClient.reset(Diagnostics->getClient());
137 }
138 
139 Diagnostic *CompilerInstance::createDiagnostics(const DiagnosticOptions &Opts,
140                                                 int Argc, char **Argv) {
141   llvm::OwningPtr<Diagnostic> Diags(new Diagnostic());
142 
143   // Create the diagnostic client for reporting errors or for
144   // implementing -verify.
145   llvm::OwningPtr<DiagnosticClient> DiagClient;
146   if (Opts.BinaryOutput) {
147     if (llvm::sys::Program::ChangeStderrToBinary()) {
148       // We weren't able to set standard error to binary, which is a
149       // bit of a problem. So, just create a text diagnostic printer
150       // to complain about this problem, and pretend that the user
151       // didn't try to use binary output.
152       DiagClient.reset(new TextDiagnosticPrinter(llvm::errs(), Opts));
153       Diags->setClient(DiagClient.take());
154       Diags->Report(diag::err_fe_stderr_binary);
155       return Diags.take();
156     } else {
157       DiagClient.reset(new BinaryDiagnosticSerializer(llvm::errs()));
158     }
159   } else {
160     DiagClient.reset(new TextDiagnosticPrinter(llvm::errs(), Opts));
161   }
162 
163   // Chain in -verify checker, if requested.
164   if (Opts.VerifyDiagnostics)
165     DiagClient.reset(new VerifyDiagnosticsClient(*Diags, DiagClient.take()));
166 
167   Diags->setClient(DiagClient.take());
168   if (!Opts.DumpBuildInformation.empty())
169     SetUpBuildDumpLog(Opts, Argc, Argv, *Diags);
170 
171   // Configure our handling of diagnostics.
172   ProcessWarningOptions(*Diags, Opts);
173 
174   return Diags.take();
175 }
176 
177 // File Manager
178 
179 void CompilerInstance::createFileManager() {
180   FileMgr.reset(new FileManager());
181 }
182 
183 // Source Manager
184 
185 void CompilerInstance::createSourceManager() {
186   SourceMgr.reset(new SourceManager(getDiagnostics()));
187 }
188 
189 // Preprocessor
190 
191 void CompilerInstance::createPreprocessor() {
192   PP.reset(createPreprocessor(getDiagnostics(), getLangOpts(),
193                               getPreprocessorOpts(), getHeaderSearchOpts(),
194                               getDependencyOutputOpts(), getTarget(),
195                               getFrontendOpts(), getSourceManager(),
196                               getFileManager()));
197 }
198 
199 Preprocessor *
200 CompilerInstance::createPreprocessor(Diagnostic &Diags,
201                                      const LangOptions &LangInfo,
202                                      const PreprocessorOptions &PPOpts,
203                                      const HeaderSearchOptions &HSOpts,
204                                      const DependencyOutputOptions &DepOpts,
205                                      const TargetInfo &Target,
206                                      const FrontendOptions &FEOpts,
207                                      SourceManager &SourceMgr,
208                                      FileManager &FileMgr) {
209   // Create a PTH manager if we are using some form of a token cache.
210   PTHManager *PTHMgr = 0;
211   if (!PPOpts.TokenCache.empty())
212     PTHMgr = PTHManager::Create(PPOpts.TokenCache, Diags);
213 
214   // Create the Preprocessor.
215   HeaderSearch *HeaderInfo = new HeaderSearch(FileMgr);
216   Preprocessor *PP = new Preprocessor(Diags, LangInfo, Target,
217                                       SourceMgr, *HeaderInfo, PTHMgr,
218                                       /*OwnsHeaderSearch=*/true);
219 
220   // Note that this is different then passing PTHMgr to Preprocessor's ctor.
221   // That argument is used as the IdentifierInfoLookup argument to
222   // IdentifierTable's ctor.
223   if (PTHMgr) {
224     PTHMgr->setPreprocessor(PP);
225     PP->setPTHManager(PTHMgr);
226   }
227 
228   if (PPOpts.DetailedRecord)
229     PP->createPreprocessingRecord();
230 
231   InitializePreprocessor(*PP, PPOpts, HSOpts, FEOpts);
232 
233   // Handle generating dependencies, if requested.
234   if (!DepOpts.OutputFile.empty())
235     AttachDependencyFileGen(*PP, DepOpts);
236 
237   return PP;
238 }
239 
240 // ASTContext
241 
242 void CompilerInstance::createASTContext() {
243   Preprocessor &PP = getPreprocessor();
244   Context.reset(new ASTContext(getLangOpts(), PP.getSourceManager(),
245                                getTarget(), PP.getIdentifierTable(),
246                                PP.getSelectorTable(), PP.getBuiltinInfo(),
247                                /*FreeMemory=*/ !getFrontendOpts().DisableFree,
248                                /*size_reserve=*/ 0));
249 }
250 
251 // ExternalASTSource
252 
253 void CompilerInstance::createPCHExternalASTSource(llvm::StringRef Path) {
254   llvm::OwningPtr<ExternalASTSource> Source;
255   Source.reset(createPCHExternalASTSource(Path, getHeaderSearchOpts().Sysroot,
256                                           getPreprocessor(), getASTContext()));
257   getASTContext().setExternalSource(Source);
258 }
259 
260 ExternalASTSource *
261 CompilerInstance::createPCHExternalASTSource(llvm::StringRef Path,
262                                              const std::string &Sysroot,
263                                              Preprocessor &PP,
264                                              ASTContext &Context) {
265   llvm::OwningPtr<PCHReader> Reader;
266   Reader.reset(new PCHReader(PP, &Context,
267                              Sysroot.empty() ? 0 : Sysroot.c_str()));
268 
269   switch (Reader->ReadPCH(Path)) {
270   case PCHReader::Success:
271     // Set the predefines buffer as suggested by the PCH reader. Typically, the
272     // predefines buffer will be empty.
273     PP.setPredefines(Reader->getSuggestedPredefines());
274     return Reader.take();
275 
276   case PCHReader::Failure:
277     // Unrecoverable failure: don't even try to process the input file.
278     break;
279 
280   case PCHReader::IgnorePCH:
281     // No suitable PCH file could be found. Return an error.
282     break;
283   }
284 
285   return 0;
286 }
287 
288 // Code Completion
289 
290 void CompilerInstance::createCodeCompletionConsumer() {
291   const ParsedSourceLocation &Loc = getFrontendOpts().CodeCompletionAt;
292   CompletionConsumer.reset(
293     createCodeCompletionConsumer(getPreprocessor(),
294                                  Loc.FileName, Loc.Line, Loc.Column,
295                                  getFrontendOpts().DebugCodeCompletionPrinter,
296                                  getFrontendOpts().ShowMacrosInCodeCompletion,
297                                  llvm::outs()));
298   if (!CompletionConsumer)
299     return;
300 
301   if (CompletionConsumer->isOutputBinary() &&
302       llvm::sys::Program::ChangeStdoutToBinary()) {
303     getPreprocessor().getDiagnostics().Report(diag::err_fe_stdout_binary);
304     CompletionConsumer.reset();
305   }
306 }
307 
308 void CompilerInstance::createFrontendTimer() {
309   FrontendTimer.reset(new llvm::Timer("Clang front-end timer"));
310 }
311 
312 CodeCompleteConsumer *
313 CompilerInstance::createCodeCompletionConsumer(Preprocessor &PP,
314                                                const std::string &Filename,
315                                                unsigned Line,
316                                                unsigned Column,
317                                                bool UseDebugPrinter,
318                                                bool ShowMacros,
319                                                llvm::raw_ostream &OS) {
320   // Tell the source manager to chop off the given file at a specific
321   // line and column.
322   const FileEntry *Entry = PP.getFileManager().getFile(Filename);
323   if (!Entry) {
324     PP.getDiagnostics().Report(diag::err_fe_invalid_code_complete_file)
325       << Filename;
326     return 0;
327   }
328 
329   // Truncate the named file at the given line/column.
330   PP.SetCodeCompletionPoint(Entry, Line, Column);
331 
332   // Set up the creation routine for code-completion.
333   if (UseDebugPrinter)
334     return new PrintingCodeCompleteConsumer(ShowMacros, OS);
335   else
336     return new CIndexCodeCompleteConsumer(ShowMacros, OS);
337 }
338 
339 // Output Files
340 
341 void CompilerInstance::addOutputFile(llvm::StringRef Path,
342                                      llvm::raw_ostream *OS) {
343   assert(OS && "Attempt to add empty stream to output list!");
344   OutputFiles.push_back(std::make_pair(Path, OS));
345 }
346 
347 void CompilerInstance::clearOutputFiles(bool EraseFiles) {
348   for (std::list< std::pair<std::string, llvm::raw_ostream*> >::iterator
349          it = OutputFiles.begin(), ie = OutputFiles.end(); it != ie; ++it) {
350     delete it->second;
351     if (EraseFiles && !it->first.empty())
352       llvm::sys::Path(it->first).eraseFromDisk();
353   }
354   OutputFiles.clear();
355 }
356 
357 llvm::raw_fd_ostream *
358 CompilerInstance::createDefaultOutputFile(bool Binary,
359                                           llvm::StringRef InFile,
360                                           llvm::StringRef Extension) {
361   return createOutputFile(getFrontendOpts().OutputFile, Binary,
362                           InFile, Extension);
363 }
364 
365 llvm::raw_fd_ostream *
366 CompilerInstance::createOutputFile(llvm::StringRef OutputPath,
367                                    bool Binary,
368                                    llvm::StringRef InFile,
369                                    llvm::StringRef Extension) {
370   std::string Error, OutputPathName;
371   llvm::raw_fd_ostream *OS = createOutputFile(OutputPath, Error, Binary,
372                                               InFile, Extension,
373                                               &OutputPathName);
374   if (!OS) {
375     getDiagnostics().Report(diag::err_fe_unable_to_open_output)
376       << OutputPath << Error;
377     return 0;
378   }
379 
380   // Add the output file -- but don't try to remove "-", since this means we are
381   // using stdin.
382   addOutputFile((OutputPathName != "-") ? OutputPathName : "", OS);
383 
384   return OS;
385 }
386 
387 llvm::raw_fd_ostream *
388 CompilerInstance::createOutputFile(llvm::StringRef OutputPath,
389                                    std::string &Error,
390                                    bool Binary,
391                                    llvm::StringRef InFile,
392                                    llvm::StringRef Extension,
393                                    std::string *ResultPathName) {
394   std::string OutFile;
395   if (!OutputPath.empty()) {
396     OutFile = OutputPath;
397   } else if (InFile == "-") {
398     OutFile = "-";
399   } else if (!Extension.empty()) {
400     llvm::sys::Path Path(InFile);
401     Path.eraseSuffix();
402     Path.appendSuffix(Extension);
403     OutFile = Path.str();
404   } else {
405     OutFile = "-";
406   }
407 
408   llvm::OwningPtr<llvm::raw_fd_ostream> OS(
409     new llvm::raw_fd_ostream(OutFile.c_str(), Error,
410                              (Binary ? llvm::raw_fd_ostream::F_Binary : 0)));
411   if (!Error.empty())
412     return 0;
413 
414   if (ResultPathName)
415     *ResultPathName = OutFile;
416 
417   return OS.take();
418 }
419 
420 // Initialization Utilities
421 
422 bool CompilerInstance::InitializeSourceManager(llvm::StringRef InputFile) {
423   return InitializeSourceManager(InputFile, getDiagnostics(), getFileManager(),
424                                  getSourceManager(), getFrontendOpts());
425 }
426 
427 bool CompilerInstance::InitializeSourceManager(llvm::StringRef InputFile,
428                                                Diagnostic &Diags,
429                                                FileManager &FileMgr,
430                                                SourceManager &SourceMgr,
431                                                const FrontendOptions &Opts) {
432   // Figure out where to get and map in the main file.
433   if (InputFile != "-") {
434     const FileEntry *File = FileMgr.getFile(InputFile);
435     if (File) SourceMgr.createMainFileID(File, SourceLocation());
436     if (SourceMgr.getMainFileID().isInvalid()) {
437       Diags.Report(diag::err_fe_error_reading) << InputFile;
438       return false;
439     }
440   } else {
441     llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
442     SourceMgr.createMainFileIDForMemBuffer(SB);
443     if (SourceMgr.getMainFileID().isInvalid()) {
444       Diags.Report(diag::err_fe_error_reading_stdin);
445       return false;
446     }
447   }
448 
449   return true;
450 }
451 
452 // High-Level Operations
453 
454 bool CompilerInstance::ExecuteAction(FrontendAction &Act) {
455   assert(hasDiagnostics() && "Diagnostics engine is not initialized!");
456   assert(!getFrontendOpts().ShowHelp && "Client must handle '-help'!");
457   assert(!getFrontendOpts().ShowVersion && "Client must handle '-version'!");
458 
459   // FIXME: Take this as an argument, once all the APIs we used have moved to
460   // taking it as an input instead of hard-coding llvm::errs.
461   llvm::raw_ostream &OS = llvm::errs();
462 
463   // Create the target instance.
464   setTarget(TargetInfo::CreateTargetInfo(getDiagnostics(), getTargetOpts()));
465   if (!hasTarget())
466     return false;
467 
468   // Inform the target of the language options.
469   //
470   // FIXME: We shouldn't need to do this, the target should be immutable once
471   // created. This complexity should be lifted elsewhere.
472   getTarget().setForcedLangOptions(getLangOpts());
473 
474   // Validate/process some options.
475   if (getHeaderSearchOpts().Verbose)
476     OS << "clang -cc1 version " CLANG_VERSION_STRING
477        << " based upon " << PACKAGE_STRING
478        << " hosted on " << llvm::sys::getHostTriple() << "\n";
479 
480   if (getFrontendOpts().ShowTimers)
481     createFrontendTimer();
482 
483   if (getFrontendOpts().ShowStats)
484     llvm::EnableStatistics();
485 
486   for (unsigned i = 0, e = getFrontendOpts().Inputs.size(); i != e; ++i) {
487     const std::string &InFile = getFrontendOpts().Inputs[i].second;
488 
489     // If we aren't using an AST file, setup the file and source managers and
490     // the preprocessor.
491     bool IsAST = getFrontendOpts().Inputs[i].first == FrontendOptions::IK_AST;
492     if (!IsAST) {
493       if (!i) {
494         // Create a file manager object to provide access to and cache the
495         // filesystem.
496         createFileManager();
497 
498         // Create the source manager.
499         createSourceManager();
500       } else {
501         // Reset the ID tables if we are reusing the SourceManager.
502         getSourceManager().clearIDTables();
503       }
504 
505       // Create the preprocessor.
506       createPreprocessor();
507     }
508 
509     if (Act.BeginSourceFile(*this, InFile, IsAST)) {
510       Act.Execute();
511       Act.EndSourceFile();
512     }
513   }
514 
515   if (getDiagnosticOpts().ShowCarets)
516     if (unsigned NumDiagnostics = getDiagnostics().getNumDiagnostics())
517       OS << NumDiagnostics << " diagnostic"
518          << (NumDiagnostics == 1 ? "" : "s")
519          << " generated.\n";
520 
521   if (getFrontendOpts().ShowStats) {
522     getFileManager().PrintStats();
523     OS << "\n";
524   }
525 
526   // Return the appropriate status when verifying diagnostics.
527   //
528   // FIXME: If we could make getNumErrors() do the right thing, we wouldn't need
529   // this.
530   if (getDiagnosticOpts().VerifyDiagnostics)
531     return !static_cast<VerifyDiagnosticsClient&>(
532       getDiagnosticClient()).HadErrors();
533 
534   return !getDiagnostics().getNumErrors();
535 }
536 
537 
538