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