CompilerInstance.cpp revision aee526e77657afd1600276450e9c346953ad51d7
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/ChainedDiagnosticConsumer.h"
23#include "clang/Frontend/FrontendAction.h"
24#include "clang/Frontend/FrontendActions.h"
25#include "clang/Frontend/FrontendDiagnostic.h"
26#include "clang/Frontend/LogDiagnosticPrinter.h"
27#include "clang/Frontend/TextDiagnosticPrinter.h"
28#include "clang/Frontend/VerifyDiagnosticConsumer.h"
29#include "clang/Frontend/Utils.h"
30#include "clang/Serialization/ASTReader.h"
31#include "clang/Sema/CodeCompleteConsumer.h"
32#include "llvm/Support/FileSystem.h"
33#include "llvm/Support/MemoryBuffer.h"
34#include "llvm/Support/raw_ostream.h"
35#include "llvm/ADT/Statistic.h"
36#include "llvm/Support/Timer.h"
37#include "llvm/Support/Host.h"
38#include "llvm/Support/Path.h"
39#include "llvm/Support/Program.h"
40#include "llvm/Support/Signals.h"
41#include "llvm/Support/system_error.h"
42#include "llvm/Config/config.h"
43using namespace clang;
44
45CompilerInstance::CompilerInstance()
46  : Invocation(new CompilerInvocation()), ModuleManager(0) {
47}
48
49CompilerInstance::~CompilerInstance() {
50}
51
52void CompilerInstance::setInvocation(CompilerInvocation *Value) {
53  Invocation = Value;
54}
55
56void CompilerInstance::setDiagnostics(DiagnosticsEngine *Value) {
57  Diagnostics = Value;
58}
59
60void CompilerInstance::setTarget(TargetInfo *Value) {
61  Target = Value;
62}
63
64void CompilerInstance::setFileManager(FileManager *Value) {
65  FileMgr = Value;
66}
67
68void CompilerInstance::setSourceManager(SourceManager *Value) {
69  SourceMgr = Value;
70}
71
72void CompilerInstance::setPreprocessor(Preprocessor *Value) { PP = Value; }
73
74void CompilerInstance::setASTContext(ASTContext *Value) { Context = Value; }
75
76void CompilerInstance::setSema(Sema *S) {
77  TheSema.reset(S);
78}
79
80void CompilerInstance::setASTConsumer(ASTConsumer *Value) {
81  Consumer.reset(Value);
82}
83
84void CompilerInstance::setCodeCompletionConsumer(CodeCompleteConsumer *Value) {
85  CompletionConsumer.reset(Value);
86}
87
88// Diagnostics
89static void SetUpBuildDumpLog(const DiagnosticOptions &DiagOpts,
90                              unsigned argc, const char* const *argv,
91                              DiagnosticsEngine &Diags) {
92  std::string ErrorInfo;
93  llvm::OwningPtr<raw_ostream> OS(
94    new llvm::raw_fd_ostream(DiagOpts.DumpBuildInformation.c_str(), ErrorInfo));
95  if (!ErrorInfo.empty()) {
96    Diags.Report(diag::err_fe_unable_to_open_logfile)
97                 << DiagOpts.DumpBuildInformation << ErrorInfo;
98    return;
99  }
100
101  (*OS) << "clang -cc1 command line arguments: ";
102  for (unsigned i = 0; i != argc; ++i)
103    (*OS) << argv[i] << ' ';
104  (*OS) << '\n';
105
106  // Chain in a diagnostic client which will log the diagnostics.
107  DiagnosticConsumer *Logger =
108    new TextDiagnosticPrinter(*OS.take(), DiagOpts, /*OwnsOutputStream=*/true);
109  Diags.setClient(new ChainedDiagnosticConsumer(Diags.takeClient(), Logger));
110}
111
112static void SetUpDiagnosticLog(const DiagnosticOptions &DiagOpts,
113                               const CodeGenOptions *CodeGenOpts,
114                               DiagnosticsEngine &Diags) {
115  std::string ErrorInfo;
116  bool OwnsStream = false;
117  raw_ostream *OS = &llvm::errs();
118  if (DiagOpts.DiagnosticLogFile != "-") {
119    // Create the output stream.
120    llvm::raw_fd_ostream *FileOS(
121      new llvm::raw_fd_ostream(DiagOpts.DiagnosticLogFile.c_str(),
122                               ErrorInfo, llvm::raw_fd_ostream::F_Append));
123    if (!ErrorInfo.empty()) {
124      Diags.Report(diag::warn_fe_cc_log_diagnostics_failure)
125        << DiagOpts.DumpBuildInformation << ErrorInfo;
126    } else {
127      FileOS->SetUnbuffered();
128      FileOS->SetUseAtomicWrites(true);
129      OS = FileOS;
130      OwnsStream = true;
131    }
132  }
133
134  // Chain in the diagnostic client which will log the diagnostics.
135  LogDiagnosticPrinter *Logger = new LogDiagnosticPrinter(*OS, DiagOpts,
136                                                          OwnsStream);
137  if (CodeGenOpts)
138    Logger->setDwarfDebugFlags(CodeGenOpts->DwarfDebugFlags);
139  Diags.setClient(new ChainedDiagnosticConsumer(Diags.takeClient(), Logger));
140}
141
142void CompilerInstance::createDiagnostics(int Argc, const char* const *Argv,
143                                         DiagnosticConsumer *Client,
144                                         bool ShouldOwnClient,
145                                         bool ShouldCloneClient) {
146  Diagnostics = createDiagnostics(getDiagnosticOpts(), Argc, Argv, Client,
147                                  ShouldOwnClient, ShouldCloneClient,
148                                  &getCodeGenOpts());
149}
150
151llvm::IntrusiveRefCntPtr<DiagnosticsEngine>
152CompilerInstance::createDiagnostics(const DiagnosticOptions &Opts,
153                                    int Argc, const char* const *Argv,
154                                    DiagnosticConsumer *Client,
155                                    bool ShouldOwnClient,
156                                    bool ShouldCloneClient,
157                                    const CodeGenOptions *CodeGenOpts) {
158  llvm::IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
159  llvm::IntrusiveRefCntPtr<DiagnosticsEngine>
160      Diags(new DiagnosticsEngine(DiagID));
161
162  // Create the diagnostic client for reporting errors or for
163  // implementing -verify.
164  if (Client) {
165    if (ShouldCloneClient)
166      Diags->setClient(Client->clone(*Diags), ShouldOwnClient);
167    else
168      Diags->setClient(Client, ShouldOwnClient);
169  } else
170    Diags->setClient(new TextDiagnosticPrinter(llvm::errs(), Opts));
171
172  // Chain in -verify checker, if requested.
173  if (Opts.VerifyDiagnostics)
174    Diags->setClient(new VerifyDiagnosticConsumer(*Diags));
175
176  // Chain in -diagnostic-log-file dumper, if requested.
177  if (!Opts.DiagnosticLogFile.empty())
178    SetUpDiagnosticLog(Opts, CodeGenOpts, *Diags);
179
180  if (!Opts.DumpBuildInformation.empty())
181    SetUpBuildDumpLog(Opts, Argc, Argv, *Diags);
182
183  // Configure our handling of diagnostics.
184  ProcessWarningOptions(*Diags, Opts);
185
186  return Diags;
187}
188
189// File Manager
190
191void CompilerInstance::createFileManager() {
192  FileMgr = new FileManager(getFileSystemOpts());
193}
194
195// Source Manager
196
197void CompilerInstance::createSourceManager(FileManager &FileMgr) {
198  SourceMgr = new SourceManager(getDiagnostics(), FileMgr);
199}
200
201// Preprocessor
202
203void CompilerInstance::createPreprocessor() {
204  const PreprocessorOptions &PPOpts = getPreprocessorOpts();
205
206  // Create a PTH manager if we are using some form of a token cache.
207  PTHManager *PTHMgr = 0;
208  if (!PPOpts.TokenCache.empty())
209    PTHMgr = PTHManager::Create(PPOpts.TokenCache, getDiagnostics());
210
211  // Create the Preprocessor.
212  HeaderSearch *HeaderInfo = new HeaderSearch(getFileManager());
213  PP = new Preprocessor(getDiagnostics(), getLangOpts(), &getTarget(),
214                        getSourceManager(), *HeaderInfo, *this, PTHMgr,
215                        /*OwnsHeaderSearch=*/true);
216
217  // Note that this is different then passing PTHMgr to Preprocessor's ctor.
218  // That argument is used as the IdentifierInfoLookup argument to
219  // IdentifierTable's ctor.
220  if (PTHMgr) {
221    PTHMgr->setPreprocessor(&*PP);
222    PP->setPTHManager(PTHMgr);
223  }
224
225  if (PPOpts.DetailedRecord)
226    PP->createPreprocessingRecord(
227                                  PPOpts.DetailedRecordIncludesNestedMacroExpansions);
228
229  InitializePreprocessor(*PP, PPOpts, getHeaderSearchOpts(), getFrontendOpts());
230
231  // Set up the module path, including the hash for the
232  // module-creation options.
233  llvm::SmallString<256> SpecificModuleCache(
234                           getHeaderSearchOpts().ModuleCachePath);
235  if (!getHeaderSearchOpts().DisableModuleHash)
236    llvm::sys::path::append(SpecificModuleCache,
237                            getInvocation().getModuleHash());
238  PP->getHeaderSearchInfo().configureModules(SpecificModuleCache,
239    getPreprocessorOpts().ModuleBuildPath.empty()
240      ? std::string()
241      : getPreprocessorOpts().ModuleBuildPath.back());
242
243  // Handle generating dependencies, if requested.
244  const DependencyOutputOptions &DepOpts = getDependencyOutputOpts();
245  if (!DepOpts.OutputFile.empty())
246    AttachDependencyFileGen(*PP, DepOpts);
247
248  // Handle generating header include information, if requested.
249  if (DepOpts.ShowHeaderIncludes)
250    AttachHeaderIncludeGen(*PP);
251  if (!DepOpts.HeaderIncludeOutputFile.empty()) {
252    StringRef OutputPath = DepOpts.HeaderIncludeOutputFile;
253    if (OutputPath == "-")
254      OutputPath = "";
255    AttachHeaderIncludeGen(*PP, /*ShowAllHeaders=*/true, OutputPath,
256                           /*ShowDepth=*/false);
257  }
258}
259
260// ASTContext
261
262void CompilerInstance::createASTContext() {
263  Preprocessor &PP = getPreprocessor();
264  Context = new ASTContext(getLangOpts(), PP.getSourceManager(),
265                           &getTarget(), PP.getIdentifierTable(),
266                           PP.getSelectorTable(), PP.getBuiltinInfo(),
267                           /*size_reserve=*/ 0);
268}
269
270// ExternalASTSource
271
272void CompilerInstance::createPCHExternalASTSource(StringRef Path,
273                                                  bool DisablePCHValidation,
274                                                  bool DisableStatCache,
275                                                 void *DeserializationListener){
276  llvm::OwningPtr<ExternalASTSource> Source;
277  bool Preamble = getPreprocessorOpts().PrecompiledPreambleBytes.first != 0;
278  Source.reset(createPCHExternalASTSource(Path, getHeaderSearchOpts().Sysroot,
279                                          DisablePCHValidation,
280                                          DisableStatCache,
281                                          getPreprocessor(), getASTContext(),
282                                          DeserializationListener,
283                                          Preamble));
284  ModuleManager = static_cast<ASTReader*>(Source.get());
285  getASTContext().setExternalSource(Source);
286}
287
288ExternalASTSource *
289CompilerInstance::createPCHExternalASTSource(StringRef Path,
290                                             const std::string &Sysroot,
291                                             bool DisablePCHValidation,
292                                             bool DisableStatCache,
293                                             Preprocessor &PP,
294                                             ASTContext &Context,
295                                             void *DeserializationListener,
296                                             bool Preamble) {
297  llvm::OwningPtr<ASTReader> Reader;
298  Reader.reset(new ASTReader(PP, Context,
299                             Sysroot.empty() ? "" : Sysroot.c_str(),
300                             DisablePCHValidation, DisableStatCache));
301
302  Reader->setDeserializationListener(
303            static_cast<ASTDeserializationListener *>(DeserializationListener));
304  switch (Reader->ReadAST(Path,
305                          Preamble ? serialization::MK_Preamble
306                                   : serialization::MK_PCH)) {
307  case ASTReader::Success:
308    // Set the predefines buffer as suggested by the PCH reader. Typically, the
309    // predefines buffer will be empty.
310    PP.setPredefines(Reader->getSuggestedPredefines());
311    return Reader.take();
312
313  case ASTReader::Failure:
314    // Unrecoverable failure: don't even try to process the input file.
315    break;
316
317  case ASTReader::IgnorePCH:
318    // No suitable PCH file could be found. Return an error.
319    break;
320  }
321
322  return 0;
323}
324
325// Code Completion
326
327static bool EnableCodeCompletion(Preprocessor &PP,
328                                 const std::string &Filename,
329                                 unsigned Line,
330                                 unsigned Column) {
331  // Tell the source manager to chop off the given file at a specific
332  // line and column.
333  const FileEntry *Entry = PP.getFileManager().getFile(Filename);
334  if (!Entry) {
335    PP.getDiagnostics().Report(diag::err_fe_invalid_code_complete_file)
336      << Filename;
337    return true;
338  }
339
340  // Truncate the named file at the given line/column.
341  PP.SetCodeCompletionPoint(Entry, Line, Column);
342  return false;
343}
344
345void CompilerInstance::createCodeCompletionConsumer() {
346  const ParsedSourceLocation &Loc = getFrontendOpts().CodeCompletionAt;
347  if (!CompletionConsumer) {
348    CompletionConsumer.reset(
349      createCodeCompletionConsumer(getPreprocessor(),
350                                   Loc.FileName, Loc.Line, Loc.Column,
351                                   getFrontendOpts().ShowMacrosInCodeCompletion,
352                             getFrontendOpts().ShowCodePatternsInCodeCompletion,
353                           getFrontendOpts().ShowGlobalSymbolsInCodeCompletion,
354                                   llvm::outs()));
355    if (!CompletionConsumer)
356      return;
357  } else if (EnableCodeCompletion(getPreprocessor(), Loc.FileName,
358                                  Loc.Line, Loc.Column)) {
359    CompletionConsumer.reset();
360    return;
361  }
362
363  if (CompletionConsumer->isOutputBinary() &&
364      llvm::sys::Program::ChangeStdoutToBinary()) {
365    getPreprocessor().getDiagnostics().Report(diag::err_fe_stdout_binary);
366    CompletionConsumer.reset();
367  }
368}
369
370void CompilerInstance::createFrontendTimer() {
371  FrontendTimer.reset(new llvm::Timer("Clang front-end timer"));
372}
373
374CodeCompleteConsumer *
375CompilerInstance::createCodeCompletionConsumer(Preprocessor &PP,
376                                               const std::string &Filename,
377                                               unsigned Line,
378                                               unsigned Column,
379                                               bool ShowMacros,
380                                               bool ShowCodePatterns,
381                                               bool ShowGlobals,
382                                               raw_ostream &OS) {
383  if (EnableCodeCompletion(PP, Filename, Line, Column))
384    return 0;
385
386  // Set up the creation routine for code-completion.
387  return new PrintingCodeCompleteConsumer(ShowMacros, ShowCodePatterns,
388                                          ShowGlobals, OS);
389}
390
391void CompilerInstance::createSema(TranslationUnitKind TUKind,
392                                  CodeCompleteConsumer *CompletionConsumer) {
393  TheSema.reset(new Sema(getPreprocessor(), getASTContext(), getASTConsumer(),
394                         TUKind, CompletionConsumer));
395}
396
397// Output Files
398
399void CompilerInstance::addOutputFile(const OutputFile &OutFile) {
400  assert(OutFile.OS && "Attempt to add empty stream to output list!");
401  OutputFiles.push_back(OutFile);
402}
403
404void CompilerInstance::clearOutputFiles(bool EraseFiles) {
405  for (std::list<OutputFile>::iterator
406         it = OutputFiles.begin(), ie = OutputFiles.end(); it != ie; ++it) {
407    delete it->OS;
408    if (!it->TempFilename.empty()) {
409      if (EraseFiles) {
410        bool existed;
411        llvm::sys::fs::remove(it->TempFilename, existed);
412      } else {
413        llvm::SmallString<128> NewOutFile(it->Filename);
414
415        // If '-working-directory' was passed, the output filename should be
416        // relative to that.
417        FileMgr->FixupRelativePath(NewOutFile);
418        if (llvm::error_code ec = llvm::sys::fs::rename(it->TempFilename,
419                                                        NewOutFile.str())) {
420          getDiagnostics().Report(diag::err_fe_unable_to_rename_temp)
421            << it->TempFilename << it->Filename << ec.message();
422
423          bool existed;
424          llvm::sys::fs::remove(it->TempFilename, existed);
425        }
426      }
427    } else if (!it->Filename.empty() && EraseFiles)
428      llvm::sys::Path(it->Filename).eraseFromDisk();
429
430  }
431  OutputFiles.clear();
432}
433
434llvm::raw_fd_ostream *
435CompilerInstance::createDefaultOutputFile(bool Binary,
436                                          StringRef InFile,
437                                          StringRef Extension) {
438  return createOutputFile(getFrontendOpts().OutputFile, Binary,
439                          /*RemoveFileOnSignal=*/true, InFile, Extension);
440}
441
442llvm::raw_fd_ostream *
443CompilerInstance::createOutputFile(StringRef OutputPath,
444                                   bool Binary, bool RemoveFileOnSignal,
445                                   StringRef InFile,
446                                   StringRef Extension,
447                                   bool UseTemporary) {
448  std::string Error, OutputPathName, TempPathName;
449  llvm::raw_fd_ostream *OS = createOutputFile(OutputPath, Error, Binary,
450                                              RemoveFileOnSignal,
451                                              InFile, Extension,
452                                              UseTemporary,
453                                              &OutputPathName,
454                                              &TempPathName);
455  if (!OS) {
456    getDiagnostics().Report(diag::err_fe_unable_to_open_output)
457      << OutputPath << Error;
458    return 0;
459  }
460
461  // Add the output file -- but don't try to remove "-", since this means we are
462  // using stdin.
463  addOutputFile(OutputFile((OutputPathName != "-") ? OutputPathName : "",
464                TempPathName, OS));
465
466  return OS;
467}
468
469llvm::raw_fd_ostream *
470CompilerInstance::createOutputFile(StringRef OutputPath,
471                                   std::string &Error,
472                                   bool Binary,
473                                   bool RemoveFileOnSignal,
474                                   StringRef InFile,
475                                   StringRef Extension,
476                                   bool UseTemporary,
477                                   std::string *ResultPathName,
478                                   std::string *TempPathName) {
479  std::string OutFile, TempFile;
480  if (!OutputPath.empty()) {
481    OutFile = OutputPath;
482  } else if (InFile == "-") {
483    OutFile = "-";
484  } else if (!Extension.empty()) {
485    llvm::sys::Path Path(InFile);
486    Path.eraseSuffix();
487    Path.appendSuffix(Extension);
488    OutFile = Path.str();
489  } else {
490    OutFile = "-";
491  }
492
493  llvm::OwningPtr<llvm::raw_fd_ostream> OS;
494  std::string OSFile;
495
496  if (UseTemporary && OutFile != "-") {
497    llvm::sys::Path OutPath(OutFile);
498    // Only create the temporary if we can actually write to OutPath, otherwise
499    // we want to fail early.
500    bool Exists;
501    if ((llvm::sys::fs::exists(OutPath.str(), Exists) || !Exists) ||
502        (OutPath.isRegularFile() && OutPath.canWrite())) {
503      // Create a temporary file.
504      llvm::SmallString<128> TempPath;
505      TempPath = OutFile;
506      TempPath += "-%%%%%%%%";
507      int fd;
508      if (llvm::sys::fs::unique_file(TempPath.str(), fd, TempPath,
509                               /*makeAbsolute=*/false) == llvm::errc::success) {
510        OS.reset(new llvm::raw_fd_ostream(fd, /*shouldClose=*/true));
511        OSFile = TempFile = TempPath.str();
512      }
513    }
514  }
515
516  if (!OS) {
517    OSFile = OutFile;
518    OS.reset(
519      new llvm::raw_fd_ostream(OSFile.c_str(), Error,
520                               (Binary ? llvm::raw_fd_ostream::F_Binary : 0)));
521    if (!Error.empty())
522      return 0;
523  }
524
525  // Make sure the out stream file gets removed if we crash.
526  if (RemoveFileOnSignal)
527    llvm::sys::RemoveFileOnSignal(llvm::sys::Path(OSFile));
528
529  if (ResultPathName)
530    *ResultPathName = OutFile;
531  if (TempPathName)
532    *TempPathName = TempFile;
533
534  return OS.take();
535}
536
537// Initialization Utilities
538
539bool CompilerInstance::InitializeSourceManager(StringRef InputFile) {
540  return InitializeSourceManager(InputFile, getDiagnostics(), getFileManager(),
541                                 getSourceManager(), getFrontendOpts());
542}
543
544bool CompilerInstance::InitializeSourceManager(StringRef InputFile,
545                                               DiagnosticsEngine &Diags,
546                                               FileManager &FileMgr,
547                                               SourceManager &SourceMgr,
548                                               const FrontendOptions &Opts) {
549  // Figure out where to get and map in the main file.
550  if (InputFile != "-") {
551    const FileEntry *File = FileMgr.getFile(InputFile);
552    if (!File) {
553      Diags.Report(diag::err_fe_error_reading) << InputFile;
554      return false;
555    }
556    SourceMgr.createMainFileID(File);
557  } else {
558    llvm::OwningPtr<llvm::MemoryBuffer> SB;
559    if (llvm::MemoryBuffer::getSTDIN(SB)) {
560      // FIXME: Give ec.message() in this diag.
561      Diags.Report(diag::err_fe_error_reading_stdin);
562      return false;
563    }
564    const FileEntry *File = FileMgr.getVirtualFile(SB->getBufferIdentifier(),
565                                                   SB->getBufferSize(), 0);
566    SourceMgr.createMainFileID(File);
567    SourceMgr.overrideFileContents(File, SB.take());
568  }
569
570  assert(!SourceMgr.getMainFileID().isInvalid() &&
571         "Couldn't establish MainFileID!");
572  return true;
573}
574
575// High-Level Operations
576
577bool CompilerInstance::ExecuteAction(FrontendAction &Act) {
578  assert(hasDiagnostics() && "Diagnostics engine is not initialized!");
579  assert(!getFrontendOpts().ShowHelp && "Client must handle '-help'!");
580  assert(!getFrontendOpts().ShowVersion && "Client must handle '-version'!");
581
582  // FIXME: Take this as an argument, once all the APIs we used have moved to
583  // taking it as an input instead of hard-coding llvm::errs.
584  raw_ostream &OS = llvm::errs();
585
586  // Create the target instance.
587  setTarget(TargetInfo::CreateTargetInfo(getDiagnostics(), getTargetOpts()));
588  if (!hasTarget())
589    return false;
590
591  // Inform the target of the language options.
592  //
593  // FIXME: We shouldn't need to do this, the target should be immutable once
594  // created. This complexity should be lifted elsewhere.
595  getTarget().setForcedLangOptions(getLangOpts());
596
597  // Validate/process some options.
598  if (getHeaderSearchOpts().Verbose)
599    OS << "clang -cc1 version " CLANG_VERSION_STRING
600       << " based upon " << PACKAGE_STRING
601       << " hosted on " << llvm::sys::getHostTriple() << "\n";
602
603  if (getFrontendOpts().ShowTimers)
604    createFrontendTimer();
605
606  if (getFrontendOpts().ShowStats)
607    llvm::EnableStatistics();
608
609  for (unsigned i = 0, e = getFrontendOpts().Inputs.size(); i != e; ++i) {
610    const std::string &InFile = getFrontendOpts().Inputs[i].second;
611
612    // Reset the ID tables if we are reusing the SourceManager.
613    if (hasSourceManager())
614      getSourceManager().clearIDTables();
615
616    if (Act.BeginSourceFile(*this, InFile, getFrontendOpts().Inputs[i].first)) {
617      Act.Execute();
618      Act.EndSourceFile();
619    }
620  }
621
622  if (getDiagnosticOpts().ShowCarets) {
623    // We can have multiple diagnostics sharing one diagnostic client.
624    // Get the total number of warnings/errors from the client.
625    unsigned NumWarnings = getDiagnostics().getClient()->getNumWarnings();
626    unsigned NumErrors = getDiagnostics().getClient()->getNumErrors();
627
628    if (NumWarnings)
629      OS << NumWarnings << " warning" << (NumWarnings == 1 ? "" : "s");
630    if (NumWarnings && NumErrors)
631      OS << " and ";
632    if (NumErrors)
633      OS << NumErrors << " error" << (NumErrors == 1 ? "" : "s");
634    if (NumWarnings || NumErrors)
635      OS << " generated.\n";
636  }
637
638  if (getFrontendOpts().ShowStats && hasFileManager()) {
639    getFileManager().PrintStats();
640    OS << "\n";
641  }
642
643  return !getDiagnostics().getClient()->getNumErrors();
644}
645
646/// \brief Determine the appropriate source input kind based on language
647/// options.
648static InputKind getSourceInputKindFromOptions(const LangOptions &LangOpts) {
649  if (LangOpts.OpenCL)
650    return IK_OpenCL;
651  if (LangOpts.CUDA)
652    return IK_CUDA;
653  if (LangOpts.ObjC1)
654    return LangOpts.CPlusPlus? IK_ObjCXX : IK_ObjC;
655  return LangOpts.CPlusPlus? IK_CXX : IK_C;
656}
657
658/// \brief Compile a module file for the given module name with the given
659/// umbrella header, using the options provided by the importing compiler
660/// instance.
661static void compileModule(CompilerInstance &ImportingInstance,
662                          StringRef ModuleName,
663                          StringRef ModuleFileName,
664                          StringRef UmbrellaHeader) {
665  // Construct a compiler invocation for creating this module.
666  llvm::IntrusiveRefCntPtr<CompilerInvocation> Invocation
667    (new CompilerInvocation(ImportingInstance.getInvocation()));
668
669  // For any options that aren't intended to affect how a module is built,
670  // reset them to their default values.
671  Invocation->getLangOpts().resetNonModularOptions();
672  Invocation->getPreprocessorOpts().resetNonModularOptions();
673
674  // Note that this module is part of the module build path, so that we
675  // can detect cycles in the module graph.
676  Invocation->getPreprocessorOpts().ModuleBuildPath.push_back(ModuleName);
677
678  // Set up the inputs/outputs so that we build the module from its umbrella
679  // header.
680  FrontendOptions &FrontendOpts = Invocation->getFrontendOpts();
681  FrontendOpts.OutputFile = ModuleFileName.str();
682  FrontendOpts.DisableFree = false;
683  FrontendOpts.Inputs.clear();
684  FrontendOpts.Inputs.push_back(
685    std::make_pair(getSourceInputKindFromOptions(Invocation->getLangOpts()),
686                                                 UmbrellaHeader));
687
688  Invocation->getDiagnosticOpts().VerifyDiagnostics = 0;
689
690
691  assert(ImportingInstance.getInvocation().getModuleHash() ==
692           Invocation->getModuleHash() && "Module hash mismatch!");
693
694  // Construct a compiler instance that will be used to actually create the
695  // module.
696  CompilerInstance Instance;
697  Instance.setInvocation(&*Invocation);
698  Instance.createDiagnostics(/*argc=*/0, /*argv=*/0,
699                             &ImportingInstance.getDiagnosticClient(),
700                             /*ShouldOwnClient=*/true,
701                             /*ShouldCloneClient=*/true);
702
703  // Construct a module-generating action.
704  GeneratePCHAction CreateModuleAction(true);
705
706  // Execute the action to actually build the module in-place.
707  // FIXME: Need to synchronize when multiple processes do this.
708  Instance.ExecuteAction(CreateModuleAction);
709}
710
711ModuleKey CompilerInstance::loadModule(SourceLocation ImportLoc,
712                                       IdentifierInfo &ModuleName,
713                                       SourceLocation ModuleNameLoc) {
714  // Determine what file we're searching from.
715  SourceManager &SourceMgr = getSourceManager();
716  SourceLocation ExpandedImportLoc = SourceMgr.getExpansionLoc(ImportLoc);
717  const FileEntry *CurFile
718    = SourceMgr.getFileEntryForID(SourceMgr.getFileID(ExpandedImportLoc));
719  if (!CurFile)
720    CurFile = SourceMgr.getFileEntryForID(SourceMgr.getMainFileID());
721
722  // Search for a module with the given name.
723  std::string UmbrellaHeader;
724  std::string ModuleFileName;
725  const FileEntry *ModuleFile
726    = PP->getHeaderSearchInfo().lookupModule(ModuleName.getName(),
727                                             &ModuleFileName,
728                                             &UmbrellaHeader);
729
730  bool BuildingModule = false;
731  if (!ModuleFile && !UmbrellaHeader.empty()) {
732    // We didn't find the module, but there is an umbrella header that
733    // can be used to create the module file. Create a separate compilation
734    // module to do so.
735
736    // Check whether there is a cycle in the module graph.
737    SmallVectorImpl<std::string> &ModuleBuildPath
738      = getPreprocessorOpts().ModuleBuildPath;
739    SmallVectorImpl<std::string>::iterator Pos
740      = std::find(ModuleBuildPath.begin(), ModuleBuildPath.end(),
741                  ModuleName.getName());
742    if (Pos != ModuleBuildPath.end()) {
743      llvm::SmallString<256> CyclePath;
744      for (; Pos != ModuleBuildPath.end(); ++Pos) {
745        CyclePath += *Pos;
746        CyclePath += " -> ";
747      }
748      CyclePath += ModuleName.getName();
749
750      getDiagnostics().Report(ModuleNameLoc, diag::err_module_cycle)
751        << ModuleName.getName() << CyclePath;
752      return 0;
753    }
754
755    BuildingModule = true;
756    compileModule(*this, ModuleName.getName(), ModuleFileName, UmbrellaHeader);
757    ModuleFile = PP->getHeaderSearchInfo().lookupModule(ModuleName.getName());
758  }
759
760  if (!ModuleFile) {
761    getDiagnostics().Report(ModuleNameLoc,
762                            BuildingModule? diag::err_module_not_built
763                                          : diag::err_module_not_found)
764      << ModuleName.getName()
765      << SourceRange(ImportLoc, ModuleNameLoc);
766    return 0;
767  }
768
769  // If we don't already have an ASTReader, create one now.
770  if (!ModuleManager) {
771    if (!hasASTContext())
772      createASTContext();
773
774    std::string Sysroot = getHeaderSearchOpts().Sysroot;
775    const PreprocessorOptions &PPOpts = getPreprocessorOpts();
776    ModuleManager = new ASTReader(getPreprocessor(), *Context,
777                                  Sysroot.empty() ? "" : Sysroot.c_str(),
778                                  PPOpts.DisablePCHValidation,
779                                  PPOpts.DisableStatCache);
780    if (hasASTConsumer()) {
781      ModuleManager->setDeserializationListener(
782        getASTConsumer().GetASTDeserializationListener());
783      getASTContext().setASTMutationListener(
784        getASTConsumer().GetASTMutationListener());
785    }
786    llvm::OwningPtr<ExternalASTSource> Source;
787    Source.reset(ModuleManager);
788    getASTContext().setExternalSource(Source);
789    if (hasSema())
790      ModuleManager->InitializeSema(getSema());
791    if (hasASTConsumer())
792      ModuleManager->StartTranslationUnit(&getASTConsumer());
793  }
794
795  // Try to load the module we found.
796  switch (ModuleManager->ReadAST(ModuleFile->getName(),
797                                 serialization::MK_Module)) {
798  case ASTReader::Success:
799    break;
800
801  case ASTReader::IgnorePCH:
802    // FIXME: The ASTReader will already have complained, but can we showhorn
803    // that diagnostic information into a more useful form?
804    return 0;
805
806  case ASTReader::Failure:
807    // Already complained.
808    return 0;
809  }
810
811  // FIXME: The module file's FileEntry makes a poor key indeed!
812  return (ModuleKey)ModuleFile;
813}
814
815