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