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