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