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