CompilerInstance.cpp revision 12f28ab8a53d7743081d607617309891fa8156f3
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/AST/Decl.h"
15#include "clang/Basic/Diagnostic.h"
16#include "clang/Basic/FileManager.h"
17#include "clang/Basic/SourceManager.h"
18#include "clang/Basic/TargetInfo.h"
19#include "clang/Basic/Version.h"
20#include "clang/Lex/HeaderSearch.h"
21#include "clang/Lex/Preprocessor.h"
22#include "clang/Lex/PTHManager.h"
23#include "clang/Frontend/ChainedDiagnosticConsumer.h"
24#include "clang/Frontend/FrontendAction.h"
25#include "clang/Frontend/FrontendActions.h"
26#include "clang/Frontend/FrontendDiagnostic.h"
27#include "clang/Frontend/LogDiagnosticPrinter.h"
28#include "clang/Frontend/SerializedDiagnosticPrinter.h"
29#include "clang/Frontend/TextDiagnosticPrinter.h"
30#include "clang/Frontend/VerifyDiagnosticConsumer.h"
31#include "clang/Frontend/Utils.h"
32#include "clang/Serialization/ASTReader.h"
33#include "clang/Sema/CodeCompleteConsumer.h"
34#include "llvm/Support/FileSystem.h"
35#include "llvm/Support/MemoryBuffer.h"
36#include "llvm/Support/raw_ostream.h"
37#include "llvm/ADT/Statistic.h"
38#include "llvm/Support/Timer.h"
39#include "llvm/Support/Host.h"
40#include "llvm/Support/LockFileManager.h"
41#include "llvm/Support/Path.h"
42#include "llvm/Support/Program.h"
43#include "llvm/Support/Signals.h"
44#include "llvm/Support/system_error.h"
45#include "llvm/Support/CrashRecoveryContext.h"
46#include "llvm/Config/config.h"
47
48using namespace clang;
49
50CompilerInstance::CompilerInstance()
51  : Invocation(new CompilerInvocation()), ModuleManager(0) {
52}
53
54CompilerInstance::~CompilerInstance() {
55}
56
57void CompilerInstance::setInvocation(CompilerInvocation *Value) {
58  Invocation = Value;
59}
60
61void CompilerInstance::setDiagnostics(DiagnosticsEngine *Value) {
62  Diagnostics = Value;
63}
64
65void CompilerInstance::setTarget(TargetInfo *Value) {
66  Target = Value;
67}
68
69void CompilerInstance::setFileManager(FileManager *Value) {
70  FileMgr = Value;
71}
72
73void CompilerInstance::setSourceManager(SourceManager *Value) {
74  SourceMgr = Value;
75}
76
77void CompilerInstance::setPreprocessor(Preprocessor *Value) { PP = Value; }
78
79void CompilerInstance::setASTContext(ASTContext *Value) { Context = Value; }
80
81void CompilerInstance::setSema(Sema *S) {
82  TheSema.reset(S);
83}
84
85void CompilerInstance::setASTConsumer(ASTConsumer *Value) {
86  Consumer.reset(Value);
87}
88
89void CompilerInstance::setCodeCompletionConsumer(CodeCompleteConsumer *Value) {
90  CompletionConsumer.reset(Value);
91}
92
93// Diagnostics
94static void SetUpBuildDumpLog(const DiagnosticOptions &DiagOpts,
95                              unsigned argc, const char* const *argv,
96                              DiagnosticsEngine &Diags) {
97  std::string ErrorInfo;
98  OwningPtr<raw_ostream> OS(
99    new llvm::raw_fd_ostream(DiagOpts.DumpBuildInformation.c_str(), ErrorInfo));
100  if (!ErrorInfo.empty()) {
101    Diags.Report(diag::err_fe_unable_to_open_logfile)
102                 << DiagOpts.DumpBuildInformation << ErrorInfo;
103    return;
104  }
105
106  (*OS) << "clang -cc1 command line arguments: ";
107  for (unsigned i = 0; i != argc; ++i)
108    (*OS) << argv[i] << ' ';
109  (*OS) << '\n';
110
111  // Chain in a diagnostic client which will log the diagnostics.
112  DiagnosticConsumer *Logger =
113    new TextDiagnosticPrinter(*OS.take(), DiagOpts, /*OwnsOutputStream=*/true);
114  Diags.setClient(new ChainedDiagnosticConsumer(Diags.takeClient(), Logger));
115}
116
117static void SetUpDiagnosticLog(const DiagnosticOptions &DiagOpts,
118                               const CodeGenOptions *CodeGenOpts,
119                               DiagnosticsEngine &Diags) {
120  std::string ErrorInfo;
121  bool OwnsStream = false;
122  raw_ostream *OS = &llvm::errs();
123  if (DiagOpts.DiagnosticLogFile != "-") {
124    // Create the output stream.
125    llvm::raw_fd_ostream *FileOS(
126      new llvm::raw_fd_ostream(DiagOpts.DiagnosticLogFile.c_str(),
127                               ErrorInfo, llvm::raw_fd_ostream::F_Append));
128    if (!ErrorInfo.empty()) {
129      Diags.Report(diag::warn_fe_cc_log_diagnostics_failure)
130        << DiagOpts.DumpBuildInformation << ErrorInfo;
131    } else {
132      FileOS->SetUnbuffered();
133      FileOS->SetUseAtomicWrites(true);
134      OS = FileOS;
135      OwnsStream = true;
136    }
137  }
138
139  // Chain in the diagnostic client which will log the diagnostics.
140  LogDiagnosticPrinter *Logger = new LogDiagnosticPrinter(*OS, DiagOpts,
141                                                          OwnsStream);
142  if (CodeGenOpts)
143    Logger->setDwarfDebugFlags(CodeGenOpts->DwarfDebugFlags);
144  Diags.setClient(new ChainedDiagnosticConsumer(Diags.takeClient(), Logger));
145}
146
147static void SetupSerializedDiagnostics(const DiagnosticOptions &DiagOpts,
148                                       DiagnosticsEngine &Diags,
149                                       StringRef OutputFile) {
150  std::string ErrorInfo;
151  OwningPtr<llvm::raw_fd_ostream> OS;
152  OS.reset(new llvm::raw_fd_ostream(OutputFile.str().c_str(), ErrorInfo,
153                                    llvm::raw_fd_ostream::F_Binary));
154
155  if (!ErrorInfo.empty()) {
156    Diags.Report(diag::warn_fe_serialized_diag_failure)
157      << OutputFile << ErrorInfo;
158    return;
159  }
160
161  DiagnosticConsumer *SerializedConsumer =
162    clang::serialized_diags::create(OS.take(), DiagOpts);
163
164
165  Diags.setClient(new ChainedDiagnosticConsumer(Diags.takeClient(),
166                                                SerializedConsumer));
167}
168
169void CompilerInstance::createDiagnostics(int Argc, const char* const *Argv,
170                                         DiagnosticConsumer *Client,
171                                         bool ShouldOwnClient,
172                                         bool ShouldCloneClient) {
173  Diagnostics = createDiagnostics(getDiagnosticOpts(), Argc, Argv, Client,
174                                  ShouldOwnClient, ShouldCloneClient,
175                                  &getCodeGenOpts());
176}
177
178IntrusiveRefCntPtr<DiagnosticsEngine>
179CompilerInstance::createDiagnostics(const DiagnosticOptions &Opts,
180                                    int Argc, const char* const *Argv,
181                                    DiagnosticConsumer *Client,
182                                    bool ShouldOwnClient,
183                                    bool ShouldCloneClient,
184                                    const CodeGenOptions *CodeGenOpts) {
185  IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
186  IntrusiveRefCntPtr<DiagnosticsEngine>
187      Diags(new DiagnosticsEngine(DiagID));
188
189  // Create the diagnostic client for reporting errors or for
190  // implementing -verify.
191  if (Client) {
192    if (ShouldCloneClient)
193      Diags->setClient(Client->clone(*Diags), ShouldOwnClient);
194    else
195      Diags->setClient(Client, ShouldOwnClient);
196  } else
197    Diags->setClient(new TextDiagnosticPrinter(llvm::errs(), Opts));
198
199  // Chain in -verify checker, if requested.
200  if (Opts.VerifyDiagnostics)
201    Diags->setClient(new VerifyDiagnosticConsumer(*Diags));
202
203  // Chain in -diagnostic-log-file dumper, if requested.
204  if (!Opts.DiagnosticLogFile.empty())
205    SetUpDiagnosticLog(Opts, CodeGenOpts, *Diags);
206
207  if (!Opts.DumpBuildInformation.empty())
208    SetUpBuildDumpLog(Opts, Argc, Argv, *Diags);
209
210  if (!Opts.DiagnosticSerializationFile.empty())
211    SetupSerializedDiagnostics(Opts, *Diags,
212                               Opts.DiagnosticSerializationFile);
213
214  // Configure our handling of diagnostics.
215  ProcessWarningOptions(*Diags, Opts);
216
217  return Diags;
218}
219
220// File Manager
221
222void CompilerInstance::createFileManager() {
223  FileMgr = new FileManager(getFileSystemOpts());
224}
225
226// Source Manager
227
228void CompilerInstance::createSourceManager(FileManager &FileMgr) {
229  SourceMgr = new SourceManager(getDiagnostics(), FileMgr);
230}
231
232// Preprocessor
233
234void CompilerInstance::createPreprocessor() {
235  const PreprocessorOptions &PPOpts = getPreprocessorOpts();
236
237  // Create a PTH manager if we are using some form of a token cache.
238  PTHManager *PTHMgr = 0;
239  if (!PPOpts.TokenCache.empty())
240    PTHMgr = PTHManager::Create(PPOpts.TokenCache, getDiagnostics());
241
242  // Create the Preprocessor.
243  HeaderSearch *HeaderInfo = new HeaderSearch(getFileManager(),
244                                              getDiagnostics(),
245                                              getLangOpts(),
246                                              &getTarget());
247  PP = new Preprocessor(getDiagnostics(), getLangOpts(), &getTarget(),
248                        getSourceManager(), *HeaderInfo, *this, PTHMgr,
249                        /*OwnsHeaderSearch=*/true);
250
251  // Note that this is different then passing PTHMgr to Preprocessor's ctor.
252  // That argument is used as the IdentifierInfoLookup argument to
253  // IdentifierTable's ctor.
254  if (PTHMgr) {
255    PTHMgr->setPreprocessor(&*PP);
256    PP->setPTHManager(PTHMgr);
257  }
258
259  if (PPOpts.DetailedRecord)
260    PP->createPreprocessingRecord();
261
262  InitializePreprocessor(*PP, PPOpts, getHeaderSearchOpts(), getFrontendOpts());
263
264  // Set up the module path, including the hash for the
265  // module-creation options.
266  SmallString<256> SpecificModuleCache(
267                           getHeaderSearchOpts().ModuleCachePath);
268  if (!getHeaderSearchOpts().DisableModuleHash)
269    llvm::sys::path::append(SpecificModuleCache,
270                            getInvocation().getModuleHash());
271  PP->getHeaderSearchInfo().setModuleCachePath(SpecificModuleCache);
272
273  // Handle generating dependencies, if requested.
274  const DependencyOutputOptions &DepOpts = getDependencyOutputOpts();
275  if (!DepOpts.OutputFile.empty())
276    AttachDependencyFileGen(*PP, DepOpts);
277  if (!DepOpts.DOTOutputFile.empty())
278    AttachDependencyGraphGen(*PP, DepOpts.DOTOutputFile,
279                             getHeaderSearchOpts().Sysroot);
280
281
282  // Handle generating header include information, if requested.
283  if (DepOpts.ShowHeaderIncludes)
284    AttachHeaderIncludeGen(*PP);
285  if (!DepOpts.HeaderIncludeOutputFile.empty()) {
286    StringRef OutputPath = DepOpts.HeaderIncludeOutputFile;
287    if (OutputPath == "-")
288      OutputPath = "";
289    AttachHeaderIncludeGen(*PP, /*ShowAllHeaders=*/true, OutputPath,
290                           /*ShowDepth=*/false);
291  }
292}
293
294// ASTContext
295
296void CompilerInstance::createASTContext() {
297  Preprocessor &PP = getPreprocessor();
298  Context = new ASTContext(getLangOpts(), PP.getSourceManager(),
299                           &getTarget(), PP.getIdentifierTable(),
300                           PP.getSelectorTable(), PP.getBuiltinInfo(),
301                           /*size_reserve=*/ 0);
302}
303
304// ExternalASTSource
305
306void CompilerInstance::createPCHExternalASTSource(StringRef Path,
307                                                  bool DisablePCHValidation,
308                                                  bool DisableStatCache,
309                                                 void *DeserializationListener){
310  OwningPtr<ExternalASTSource> Source;
311  bool Preamble = getPreprocessorOpts().PrecompiledPreambleBytes.first != 0;
312  Source.reset(createPCHExternalASTSource(Path, getHeaderSearchOpts().Sysroot,
313                                          DisablePCHValidation,
314                                          DisableStatCache,
315                                          getPreprocessor(), getASTContext(),
316                                          DeserializationListener,
317                                          Preamble));
318  ModuleManager = static_cast<ASTReader*>(Source.get());
319  getASTContext().setExternalSource(Source);
320}
321
322ExternalASTSource *
323CompilerInstance::createPCHExternalASTSource(StringRef Path,
324                                             const std::string &Sysroot,
325                                             bool DisablePCHValidation,
326                                             bool DisableStatCache,
327                                             Preprocessor &PP,
328                                             ASTContext &Context,
329                                             void *DeserializationListener,
330                                             bool Preamble) {
331  OwningPtr<ASTReader> Reader;
332  Reader.reset(new ASTReader(PP, Context,
333                             Sysroot.empty() ? "" : Sysroot.c_str(),
334                             DisablePCHValidation, DisableStatCache));
335
336  Reader->setDeserializationListener(
337            static_cast<ASTDeserializationListener *>(DeserializationListener));
338  switch (Reader->ReadAST(Path,
339                          Preamble ? serialization::MK_Preamble
340                                   : serialization::MK_PCH)) {
341  case ASTReader::Success:
342    // Set the predefines buffer as suggested by the PCH reader. Typically, the
343    // predefines buffer will be empty.
344    PP.setPredefines(Reader->getSuggestedPredefines());
345    return Reader.take();
346
347  case ASTReader::Failure:
348    // Unrecoverable failure: don't even try to process the input file.
349    break;
350
351  case ASTReader::IgnorePCH:
352    // No suitable PCH file could be found. Return an error.
353    break;
354  }
355
356  return 0;
357}
358
359// Code Completion
360
361static bool EnableCodeCompletion(Preprocessor &PP,
362                                 const std::string &Filename,
363                                 unsigned Line,
364                                 unsigned Column) {
365  // Tell the source manager to chop off the given file at a specific
366  // line and column.
367  const FileEntry *Entry = PP.getFileManager().getFile(Filename);
368  if (!Entry) {
369    PP.getDiagnostics().Report(diag::err_fe_invalid_code_complete_file)
370      << Filename;
371    return true;
372  }
373
374  // Truncate the named file at the given line/column.
375  PP.SetCodeCompletionPoint(Entry, Line, Column);
376  return false;
377}
378
379void CompilerInstance::createCodeCompletionConsumer() {
380  const ParsedSourceLocation &Loc = getFrontendOpts().CodeCompletionAt;
381  if (!CompletionConsumer) {
382    CompletionConsumer.reset(
383      createCodeCompletionConsumer(getPreprocessor(),
384                                   Loc.FileName, Loc.Line, Loc.Column,
385                                   getFrontendOpts().ShowMacrosInCodeCompletion,
386                             getFrontendOpts().ShowCodePatternsInCodeCompletion,
387                           getFrontendOpts().ShowGlobalSymbolsInCodeCompletion,
388                                   llvm::outs()));
389    if (!CompletionConsumer)
390      return;
391  } else if (EnableCodeCompletion(getPreprocessor(), Loc.FileName,
392                                  Loc.Line, Loc.Column)) {
393    CompletionConsumer.reset();
394    return;
395  }
396
397  if (CompletionConsumer->isOutputBinary() &&
398      llvm::sys::Program::ChangeStdoutToBinary()) {
399    getPreprocessor().getDiagnostics().Report(diag::err_fe_stdout_binary);
400    CompletionConsumer.reset();
401  }
402}
403
404void CompilerInstance::createFrontendTimer() {
405  FrontendTimer.reset(new llvm::Timer("Clang front-end timer"));
406}
407
408CodeCompleteConsumer *
409CompilerInstance::createCodeCompletionConsumer(Preprocessor &PP,
410                                               const std::string &Filename,
411                                               unsigned Line,
412                                               unsigned Column,
413                                               bool ShowMacros,
414                                               bool ShowCodePatterns,
415                                               bool ShowGlobals,
416                                               raw_ostream &OS) {
417  if (EnableCodeCompletion(PP, Filename, Line, Column))
418    return 0;
419
420  // Set up the creation routine for code-completion.
421  return new PrintingCodeCompleteConsumer(ShowMacros, ShowCodePatterns,
422                                          ShowGlobals, OS);
423}
424
425void CompilerInstance::createSema(TranslationUnitKind TUKind,
426                                  CodeCompleteConsumer *CompletionConsumer) {
427  TheSema.reset(new Sema(getPreprocessor(), getASTContext(), getASTConsumer(),
428                         TUKind, CompletionConsumer));
429}
430
431// Output Files
432
433void CompilerInstance::addOutputFile(const OutputFile &OutFile) {
434  assert(OutFile.OS && "Attempt to add empty stream to output list!");
435  OutputFiles.push_back(OutFile);
436}
437
438void CompilerInstance::clearOutputFiles(bool EraseFiles) {
439  for (std::list<OutputFile>::iterator
440         it = OutputFiles.begin(), ie = OutputFiles.end(); it != ie; ++it) {
441    delete it->OS;
442    if (!it->TempFilename.empty()) {
443      if (EraseFiles) {
444        bool existed;
445        llvm::sys::fs::remove(it->TempFilename, existed);
446      } else {
447        SmallString<128> NewOutFile(it->Filename);
448
449        // If '-working-directory' was passed, the output filename should be
450        // relative to that.
451        FileMgr->FixupRelativePath(NewOutFile);
452        if (llvm::error_code ec = llvm::sys::fs::rename(it->TempFilename,
453                                                        NewOutFile.str())) {
454          getDiagnostics().Report(diag::err_fe_unable_to_rename_temp)
455            << it->TempFilename << it->Filename << ec.message();
456
457          bool existed;
458          llvm::sys::fs::remove(it->TempFilename, existed);
459        }
460      }
461    } else if (!it->Filename.empty() && EraseFiles)
462      llvm::sys::Path(it->Filename).eraseFromDisk();
463
464  }
465  OutputFiles.clear();
466}
467
468llvm::raw_fd_ostream *
469CompilerInstance::createDefaultOutputFile(bool Binary,
470                                          StringRef InFile,
471                                          StringRef Extension) {
472  return createOutputFile(getFrontendOpts().OutputFile, Binary,
473                          /*RemoveFileOnSignal=*/true, InFile, Extension);
474}
475
476llvm::raw_fd_ostream *
477CompilerInstance::createOutputFile(StringRef OutputPath,
478                                   bool Binary, bool RemoveFileOnSignal,
479                                   StringRef InFile,
480                                   StringRef Extension,
481                                   bool UseTemporary,
482                                   bool CreateMissingDirectories) {
483  std::string Error, OutputPathName, TempPathName;
484  llvm::raw_fd_ostream *OS = createOutputFile(OutputPath, Error, Binary,
485                                              RemoveFileOnSignal,
486                                              InFile, Extension,
487                                              UseTemporary,
488                                              CreateMissingDirectories,
489                                              &OutputPathName,
490                                              &TempPathName);
491  if (!OS) {
492    getDiagnostics().Report(diag::err_fe_unable_to_open_output)
493      << OutputPath << Error;
494    return 0;
495  }
496
497  // Add the output file -- but don't try to remove "-", since this means we are
498  // using stdin.
499  addOutputFile(OutputFile((OutputPathName != "-") ? OutputPathName : "",
500                TempPathName, OS));
501
502  return OS;
503}
504
505llvm::raw_fd_ostream *
506CompilerInstance::createOutputFile(StringRef OutputPath,
507                                   std::string &Error,
508                                   bool Binary,
509                                   bool RemoveFileOnSignal,
510                                   StringRef InFile,
511                                   StringRef Extension,
512                                   bool UseTemporary,
513                                   bool CreateMissingDirectories,
514                                   std::string *ResultPathName,
515                                   std::string *TempPathName) {
516  assert((!CreateMissingDirectories || UseTemporary) &&
517         "CreateMissingDirectories is only allowed when using temporary files");
518
519  std::string OutFile, TempFile;
520  if (!OutputPath.empty()) {
521    OutFile = OutputPath;
522  } else if (InFile == "-") {
523    OutFile = "-";
524  } else if (!Extension.empty()) {
525    llvm::sys::Path Path(InFile);
526    Path.eraseSuffix();
527    Path.appendSuffix(Extension);
528    OutFile = Path.str();
529  } else {
530    OutFile = "-";
531  }
532
533  OwningPtr<llvm::raw_fd_ostream> OS;
534  std::string OSFile;
535
536  if (UseTemporary && OutFile != "-") {
537    // Only create the temporary if the parent directory exists (or create
538    // missing directories is true) and we can actually write to OutPath,
539    // otherwise we want to fail early.
540    SmallString<256> AbsPath(OutputPath);
541    llvm::sys::fs::make_absolute(AbsPath);
542    llvm::sys::Path OutPath(AbsPath);
543    bool ParentExists = false;
544    if (llvm::sys::fs::exists(llvm::sys::path::parent_path(AbsPath.str()),
545                              ParentExists))
546      ParentExists = false;
547    bool Exists;
548    if ((CreateMissingDirectories || ParentExists) &&
549        ((llvm::sys::fs::exists(AbsPath.str(), Exists) || !Exists) ||
550         (OutPath.isRegularFile() && OutPath.canWrite()))) {
551      // Create a temporary file.
552      SmallString<128> TempPath;
553      TempPath = OutFile;
554      TempPath += "-%%%%%%%%";
555      int fd;
556      if (llvm::sys::fs::unique_file(TempPath.str(), fd, TempPath,
557                               /*makeAbsolute=*/false) == llvm::errc::success) {
558        OS.reset(new llvm::raw_fd_ostream(fd, /*shouldClose=*/true));
559        OSFile = TempFile = TempPath.str();
560      }
561    }
562  }
563
564  if (!OS) {
565    OSFile = OutFile;
566    OS.reset(
567      new llvm::raw_fd_ostream(OSFile.c_str(), Error,
568                               (Binary ? llvm::raw_fd_ostream::F_Binary : 0)));
569    if (!Error.empty())
570      return 0;
571  }
572
573  // Make sure the out stream file gets removed if we crash.
574  if (RemoveFileOnSignal)
575    llvm::sys::RemoveFileOnSignal(llvm::sys::Path(OSFile));
576
577  if (ResultPathName)
578    *ResultPathName = OutFile;
579  if (TempPathName)
580    *TempPathName = TempFile;
581
582  return OS.take();
583}
584
585// Initialization Utilities
586
587bool CompilerInstance::InitializeSourceManager(StringRef InputFile,
588                                               SrcMgr::CharacteristicKind Kind){
589  return InitializeSourceManager(InputFile, Kind, getDiagnostics(),
590                                 getFileManager(), getSourceManager(),
591                                 getFrontendOpts());
592}
593
594bool CompilerInstance::InitializeSourceManager(StringRef InputFile,
595                                               SrcMgr::CharacteristicKind Kind,
596                                               DiagnosticsEngine &Diags,
597                                               FileManager &FileMgr,
598                                               SourceManager &SourceMgr,
599                                               const FrontendOptions &Opts) {
600  // Figure out where to get and map in the main file.
601  if (InputFile != "-") {
602    const FileEntry *File = FileMgr.getFile(InputFile);
603    if (!File) {
604      Diags.Report(diag::err_fe_error_reading) << InputFile;
605      return false;
606    }
607    SourceMgr.createMainFileID(File, Kind);
608  } else {
609    OwningPtr<llvm::MemoryBuffer> SB;
610    if (llvm::MemoryBuffer::getSTDIN(SB)) {
611      // FIXME: Give ec.message() in this diag.
612      Diags.Report(diag::err_fe_error_reading_stdin);
613      return false;
614    }
615    const FileEntry *File = FileMgr.getVirtualFile(SB->getBufferIdentifier(),
616                                                   SB->getBufferSize(), 0);
617    SourceMgr.createMainFileID(File, Kind);
618    SourceMgr.overrideFileContents(File, SB.take());
619  }
620
621  assert(!SourceMgr.getMainFileID().isInvalid() &&
622         "Couldn't establish MainFileID!");
623  return true;
624}
625
626// High-Level Operations
627
628bool CompilerInstance::ExecuteAction(FrontendAction &Act) {
629  assert(hasDiagnostics() && "Diagnostics engine is not initialized!");
630  assert(!getFrontendOpts().ShowHelp && "Client must handle '-help'!");
631  assert(!getFrontendOpts().ShowVersion && "Client must handle '-version'!");
632
633  // FIXME: Take this as an argument, once all the APIs we used have moved to
634  // taking it as an input instead of hard-coding llvm::errs.
635  raw_ostream &OS = llvm::errs();
636
637  // Create the target instance.
638  setTarget(TargetInfo::CreateTargetInfo(getDiagnostics(), getTargetOpts()));
639  if (!hasTarget())
640    return false;
641
642  // Inform the target of the language options.
643  //
644  // FIXME: We shouldn't need to do this, the target should be immutable once
645  // created. This complexity should be lifted elsewhere.
646  getTarget().setForcedLangOptions(getLangOpts());
647
648  // Validate/process some options.
649  if (getHeaderSearchOpts().Verbose)
650    OS << "clang -cc1 version " CLANG_VERSION_STRING
651       << " based upon " << PACKAGE_STRING
652       << " default target " << llvm::sys::getDefaultTargetTriple() << "\n";
653
654  if (getFrontendOpts().ShowTimers)
655    createFrontendTimer();
656
657  if (getFrontendOpts().ShowStats)
658    llvm::EnableStatistics();
659
660  for (unsigned i = 0, e = getFrontendOpts().Inputs.size(); i != e; ++i) {
661    // Reset the ID tables if we are reusing the SourceManager.
662    if (hasSourceManager())
663      getSourceManager().clearIDTables();
664
665    if (Act.BeginSourceFile(*this, getFrontendOpts().Inputs[i])) {
666      Act.Execute();
667      Act.EndSourceFile();
668    }
669  }
670
671  // Notify the diagnostic client that all files were processed.
672  getDiagnostics().getClient()->finish();
673
674  if (getDiagnosticOpts().ShowCarets) {
675    // We can have multiple diagnostics sharing one diagnostic client.
676    // Get the total number of warnings/errors from the client.
677    unsigned NumWarnings = getDiagnostics().getClient()->getNumWarnings();
678    unsigned NumErrors = getDiagnostics().getClient()->getNumErrors();
679
680    if (NumWarnings)
681      OS << NumWarnings << " warning" << (NumWarnings == 1 ? "" : "s");
682    if (NumWarnings && NumErrors)
683      OS << " and ";
684    if (NumErrors)
685      OS << NumErrors << " error" << (NumErrors == 1 ? "" : "s");
686    if (NumWarnings || NumErrors)
687      OS << " generated.\n";
688  }
689
690  if (getFrontendOpts().ShowStats && hasFileManager()) {
691    getFileManager().PrintStats();
692    OS << "\n";
693  }
694
695  return !getDiagnostics().getClient()->getNumErrors();
696}
697
698/// \brief Determine the appropriate source input kind based on language
699/// options.
700static InputKind getSourceInputKindFromOptions(const LangOptions &LangOpts) {
701  if (LangOpts.OpenCL)
702    return IK_OpenCL;
703  if (LangOpts.CUDA)
704    return IK_CUDA;
705  if (LangOpts.ObjC1)
706    return LangOpts.CPlusPlus? IK_ObjCXX : IK_ObjC;
707  return LangOpts.CPlusPlus? IK_CXX : IK_C;
708}
709
710namespace {
711  struct CompileModuleMapData {
712    CompilerInstance &Instance;
713    GenerateModuleAction &CreateModuleAction;
714  };
715}
716
717/// \brief Helper function that executes the module-generating action under
718/// a crash recovery context.
719static void doCompileMapModule(void *UserData) {
720  CompileModuleMapData &Data
721    = *reinterpret_cast<CompileModuleMapData *>(UserData);
722  Data.Instance.ExecuteAction(Data.CreateModuleAction);
723}
724
725/// \brief Compile a module file for the given module, using the options
726/// provided by the importing compiler instance.
727static void compileModule(CompilerInstance &ImportingInstance,
728                          Module *Module,
729                          StringRef ModuleFileName) {
730  llvm::LockFileManager Locked(ModuleFileName);
731  switch (Locked) {
732  case llvm::LockFileManager::LFS_Error:
733    return;
734
735  case llvm::LockFileManager::LFS_Owned:
736    // We're responsible for building the module ourselves. Do so below.
737    break;
738
739  case llvm::LockFileManager::LFS_Shared:
740    // Someone else is responsible for building the module. Wait for them to
741    // finish.
742    Locked.waitForUnlock();
743    break;
744  }
745
746  ModuleMap &ModMap
747    = ImportingInstance.getPreprocessor().getHeaderSearchInfo().getModuleMap();
748
749  // Construct a compiler invocation for creating this module.
750  IntrusiveRefCntPtr<CompilerInvocation> Invocation
751    (new CompilerInvocation(ImportingInstance.getInvocation()));
752
753  PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
754
755  // For any options that aren't intended to affect how a module is built,
756  // reset them to their default values.
757  Invocation->getLangOpts()->resetNonModularOptions();
758  PPOpts.resetNonModularOptions();
759
760  // Note the name of the module we're building.
761  Invocation->getLangOpts()->CurrentModule = Module->getTopLevelModuleName();
762
763  // Note that this module is part of the module build path, so that we
764  // can detect cycles in the module graph.
765  PPOpts.ModuleBuildPath.push_back(Module->getTopLevelModuleName());
766
767  // If there is a module map file, build the module using the module map.
768  // Set up the inputs/outputs so that we build the module from its umbrella
769  // header.
770  FrontendOptions &FrontendOpts = Invocation->getFrontendOpts();
771  FrontendOpts.OutputFile = ModuleFileName.str();
772  FrontendOpts.DisableFree = false;
773  FrontendOpts.Inputs.clear();
774  InputKind IK = getSourceInputKindFromOptions(*Invocation->getLangOpts());
775
776  // Get or create the module map that we'll use to build this module.
777  SmallString<128> TempModuleMapFileName;
778  if (const FileEntry *ModuleMapFile
779                                  = ModMap.getContainingModuleMapFile(Module)) {
780    // Use the module map where this module resides.
781    FrontendOpts.Inputs.push_back(FrontendInputFile(ModuleMapFile->getName(),
782                                                    IK));
783  } else {
784    // Create a temporary module map file.
785    TempModuleMapFileName = Module->Name;
786    TempModuleMapFileName += "-%%%%%%%%.map";
787    int FD;
788    if (llvm::sys::fs::unique_file(TempModuleMapFileName.str(), FD,
789                                   TempModuleMapFileName,
790                                   /*makeAbsolute=*/true)
791          != llvm::errc::success) {
792      ImportingInstance.getDiagnostics().Report(diag::err_module_map_temp_file)
793        << TempModuleMapFileName;
794      return;
795    }
796    // Print the module map to this file.
797    llvm::raw_fd_ostream OS(FD, /*shouldClose=*/true);
798    Module->print(OS);
799    FrontendOpts.Inputs.push_back(
800      FrontendInputFile(TempModuleMapFileName.str().str(), IK));
801  }
802
803  // Don't free the remapped file buffers; they are owned by our caller.
804  PPOpts.RetainRemappedFileBuffers = true;
805
806  Invocation->getDiagnosticOpts().VerifyDiagnostics = 0;
807  assert(ImportingInstance.getInvocation().getModuleHash() ==
808         Invocation->getModuleHash() && "Module hash mismatch!");
809
810  // Construct a compiler instance that will be used to actually create the
811  // module.
812  CompilerInstance Instance;
813  Instance.setInvocation(&*Invocation);
814  Instance.createDiagnostics(/*argc=*/0, /*argv=*/0,
815                             &ImportingInstance.getDiagnosticClient(),
816                             /*ShouldOwnClient=*/true,
817                             /*ShouldCloneClient=*/true);
818
819  // Construct a module-generating action.
820  GenerateModuleAction CreateModuleAction;
821
822  // Execute the action to actually build the module in-place. Use a separate
823  // thread so that we get a stack large enough.
824  const unsigned ThreadStackSize = 8 << 20;
825  llvm::CrashRecoveryContext CRC;
826  CompileModuleMapData Data = { Instance, CreateModuleAction };
827  CRC.RunSafelyOnThread(&doCompileMapModule, &Data, ThreadStackSize);
828
829  // Delete the temporary module map file.
830  // FIXME: Even though we're executing under crash protection, it would still
831  // be nice to do this with RemoveFileOnSignal when we can. However, that
832  // doesn't make sense for all clients, so clean this up manually.
833  if (!TempModuleMapFileName.empty())
834    llvm::sys::Path(TempModuleMapFileName).eraseFromDisk();
835}
836
837Module *CompilerInstance::loadModule(SourceLocation ImportLoc,
838                                     ModuleIdPath Path,
839                                     Module::NameVisibilityKind Visibility,
840                                     bool IsInclusionDirective) {
841  // If we've already handled this import, just return the cached result.
842  // This one-element cache is important to eliminate redundant diagnostics
843  // when both the preprocessor and parser see the same import declaration.
844  if (!ImportLoc.isInvalid() && LastModuleImportLoc == ImportLoc) {
845    // Make the named module visible.
846    if (LastModuleImportResult)
847      ModuleManager->makeModuleVisible(LastModuleImportResult, Visibility);
848    return LastModuleImportResult;
849  }
850
851  // Determine what file we're searching from.
852  SourceManager &SourceMgr = getSourceManager();
853  SourceLocation ExpandedImportLoc = SourceMgr.getExpansionLoc(ImportLoc);
854  const FileEntry *CurFile
855    = SourceMgr.getFileEntryForID(SourceMgr.getFileID(ExpandedImportLoc));
856  if (!CurFile)
857    CurFile = SourceMgr.getFileEntryForID(SourceMgr.getMainFileID());
858
859  StringRef ModuleName = Path[0].first->getName();
860  SourceLocation ModuleNameLoc = Path[0].second;
861
862  clang::Module *Module = 0;
863
864  // If we don't already have information on this module, load the module now.
865  llvm::DenseMap<const IdentifierInfo *, clang::Module *>::iterator Known
866    = KnownModules.find(Path[0].first);
867  if (Known != KnownModules.end()) {
868    // Retrieve the cached top-level module.
869    Module = Known->second;
870  } else if (ModuleName == getLangOpts().CurrentModule) {
871    // This is the module we're building.
872    Module = PP->getHeaderSearchInfo().getModuleMap().findModule(ModuleName);
873    Known = KnownModules.insert(std::make_pair(Path[0].first, Module)).first;
874  } else {
875    // Search for a module with the given name.
876    Module = PP->getHeaderSearchInfo().lookupModule(ModuleName);
877    std::string ModuleFileName;
878    if (Module)
879      ModuleFileName = PP->getHeaderSearchInfo().getModuleFileName(Module);
880    else
881      ModuleFileName = PP->getHeaderSearchInfo().getModuleFileName(ModuleName);
882
883    if (ModuleFileName.empty()) {
884      getDiagnostics().Report(ModuleNameLoc, diag::err_module_not_found)
885        << ModuleName
886        << SourceRange(ImportLoc, ModuleNameLoc);
887      LastModuleImportLoc = ImportLoc;
888      LastModuleImportResult = 0;
889      return 0;
890    }
891
892    const FileEntry *ModuleFile
893      = getFileManager().getFile(ModuleFileName, /*OpenFile=*/false,
894                                 /*CacheFailure=*/false);
895    bool BuildingModule = false;
896    if (!ModuleFile && Module) {
897      // The module is not cached, but we have a module map from which we can
898      // build the module.
899
900      // Check whether there is a cycle in the module graph.
901      SmallVectorImpl<std::string> &ModuleBuildPath
902        = getPreprocessorOpts().ModuleBuildPath;
903      SmallVectorImpl<std::string>::iterator Pos
904        = std::find(ModuleBuildPath.begin(), ModuleBuildPath.end(), ModuleName);
905      if (Pos != ModuleBuildPath.end()) {
906        SmallString<256> CyclePath;
907        for (; Pos != ModuleBuildPath.end(); ++Pos) {
908          CyclePath += *Pos;
909          CyclePath += " -> ";
910        }
911        CyclePath += ModuleName;
912
913        getDiagnostics().Report(ModuleNameLoc, diag::err_module_cycle)
914          << ModuleName << CyclePath;
915        return 0;
916      }
917
918      getDiagnostics().Report(ModuleNameLoc, diag::warn_module_build)
919        << ModuleName;
920      BuildingModule = true;
921      compileModule(*this, Module, ModuleFileName);
922      ModuleFile = FileMgr->getFile(ModuleFileName);
923    }
924
925    if (!ModuleFile) {
926      getDiagnostics().Report(ModuleNameLoc,
927                              BuildingModule? diag::err_module_not_built
928                                            : diag::err_module_not_found)
929        << ModuleName
930        << SourceRange(ImportLoc, ModuleNameLoc);
931      return 0;
932    }
933
934    // If we don't already have an ASTReader, create one now.
935    if (!ModuleManager) {
936      if (!hasASTContext())
937        createASTContext();
938
939      std::string Sysroot = getHeaderSearchOpts().Sysroot;
940      const PreprocessorOptions &PPOpts = getPreprocessorOpts();
941      ModuleManager = new ASTReader(getPreprocessor(), *Context,
942                                    Sysroot.empty() ? "" : Sysroot.c_str(),
943                                    PPOpts.DisablePCHValidation,
944                                    PPOpts.DisableStatCache);
945      if (hasASTConsumer()) {
946        ModuleManager->setDeserializationListener(
947          getASTConsumer().GetASTDeserializationListener());
948        getASTContext().setASTMutationListener(
949          getASTConsumer().GetASTMutationListener());
950      }
951      OwningPtr<ExternalASTSource> Source;
952      Source.reset(ModuleManager);
953      getASTContext().setExternalSource(Source);
954      if (hasSema())
955        ModuleManager->InitializeSema(getSema());
956      if (hasASTConsumer())
957        ModuleManager->StartTranslationUnit(&getASTConsumer());
958    }
959
960    // Try to load the module we found.
961    switch (ModuleManager->ReadAST(ModuleFile->getName(),
962                                   serialization::MK_Module)) {
963    case ASTReader::Success:
964      break;
965
966    case ASTReader::IgnorePCH:
967      // FIXME: The ASTReader will already have complained, but can we showhorn
968      // that diagnostic information into a more useful form?
969      KnownModules[Path[0].first] = 0;
970      return 0;
971
972    case ASTReader::Failure:
973      // Already complained, but note now that we failed.
974      KnownModules[Path[0].first] = 0;
975      return 0;
976    }
977
978    if (!Module) {
979      // If we loaded the module directly, without finding a module map first,
980      // we'll have loaded the module's information from the module itself.
981      Module = PP->getHeaderSearchInfo().getModuleMap()
982                 .findModule((Path[0].first->getName()));
983    }
984
985    // Cache the result of this top-level module lookup for later.
986    Known = KnownModules.insert(std::make_pair(Path[0].first, Module)).first;
987  }
988
989  // If we never found the module, fail.
990  if (!Module)
991    return 0;
992
993  // Verify that the rest of the module path actually corresponds to
994  // a submodule.
995  if (Path.size() > 1) {
996    for (unsigned I = 1, N = Path.size(); I != N; ++I) {
997      StringRef Name = Path[I].first->getName();
998      clang::Module *Sub = Module->findSubmodule(Name);
999
1000      if (!Sub) {
1001        // Attempt to perform typo correction to find a module name that works.
1002        llvm::SmallVector<StringRef, 2> Best;
1003        unsigned BestEditDistance = (std::numeric_limits<unsigned>::max)();
1004
1005        for (clang::Module::submodule_iterator J = Module->submodule_begin(),
1006                                            JEnd = Module->submodule_end();
1007             J != JEnd; ++J) {
1008          unsigned ED = Name.edit_distance((*J)->Name,
1009                                           /*AllowReplacements=*/true,
1010                                           BestEditDistance);
1011          if (ED <= BestEditDistance) {
1012            if (ED < BestEditDistance) {
1013              Best.clear();
1014              BestEditDistance = ED;
1015            }
1016
1017            Best.push_back((*J)->Name);
1018          }
1019        }
1020
1021        // If there was a clear winner, user it.
1022        if (Best.size() == 1) {
1023          getDiagnostics().Report(Path[I].second,
1024                                  diag::err_no_submodule_suggest)
1025            << Path[I].first << Module->getFullModuleName() << Best[0]
1026            << SourceRange(Path[0].second, Path[I-1].second)
1027            << FixItHint::CreateReplacement(SourceRange(Path[I].second),
1028                                            Best[0]);
1029
1030          Sub = Module->findSubmodule(Best[0]);
1031        }
1032      }
1033
1034      if (!Sub) {
1035        // No submodule by this name. Complain, and don't look for further
1036        // submodules.
1037        getDiagnostics().Report(Path[I].second, diag::err_no_submodule)
1038          << Path[I].first << Module->getFullModuleName()
1039          << SourceRange(Path[0].second, Path[I-1].second);
1040        break;
1041      }
1042
1043      Module = Sub;
1044    }
1045  }
1046
1047  // Make the named module visible, if it's not already part of the module
1048  // we are parsing.
1049  if (ModuleName != getLangOpts().CurrentModule) {
1050    if (!Module->IsFromModuleFile) {
1051      // We have an umbrella header or directory that doesn't actually include
1052      // all of the headers within the directory it covers. Complain about
1053      // this missing submodule and recover by forgetting that we ever saw
1054      // this submodule.
1055      // FIXME: Should we detect this at module load time? It seems fairly
1056      // expensive (and rare).
1057      getDiagnostics().Report(ImportLoc, diag::warn_missing_submodule)
1058        << Module->getFullModuleName()
1059        << SourceRange(Path.front().second, Path.back().second);
1060
1061      return 0;
1062    }
1063
1064    // Check whether this module is available.
1065    StringRef Feature;
1066    if (!Module->isAvailable(getLangOpts(), getTarget(), Feature)) {
1067      getDiagnostics().Report(ImportLoc, diag::err_module_unavailable)
1068        << Module->getFullModuleName()
1069        << Feature
1070        << SourceRange(Path.front().second, Path.back().second);
1071      LastModuleImportLoc = ImportLoc;
1072      LastModuleImportResult = 0;
1073      return 0;
1074    }
1075
1076    ModuleManager->makeModuleVisible(Module, Visibility);
1077  }
1078
1079  // If this module import was due to an inclusion directive, create an
1080  // implicit import declaration to capture it in the AST.
1081  if (IsInclusionDirective && hasASTContext()) {
1082    TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
1083    TU->addDecl(ImportDecl::CreateImplicit(getASTContext(), TU,
1084                                           ImportLoc, Module,
1085                                           Path.back().second));
1086  }
1087
1088  LastModuleImportLoc = ImportLoc;
1089  LastModuleImportResult = Module;
1090  return Module;
1091}
1092