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