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