CompilerInstance.cpp revision 3d67b1e25847319a5a271f9d5a8d607ef18d804a
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/Basic/Diagnostic.h" 14#include "clang/Basic/FileManager.h" 15#include "clang/Basic/SourceManager.h" 16#include "clang/Basic/TargetInfo.h" 17#include "clang/Basic/Version.h" 18#include "clang/Lex/HeaderSearch.h" 19#include "clang/Lex/Preprocessor.h" 20#include "clang/Lex/PTHManager.h" 21#include "clang/Frontend/ChainedDiagnosticClient.h" 22#include "clang/Frontend/FrontendAction.h" 23#include "clang/Frontend/PCHReader.h" 24#include "clang/Frontend/FrontendDiagnostic.h" 25#include "clang/Frontend/TextDiagnosticPrinter.h" 26#include "clang/Frontend/VerifyDiagnosticsClient.h" 27#include "clang/Frontend/Utils.h" 28#include "clang/Sema/CodeCompleteConsumer.h" 29#include "llvm/LLVMContext.h" 30#include "llvm/Support/MemoryBuffer.h" 31#include "llvm/Support/raw_ostream.h" 32#include "llvm/Support/Timer.h" 33#include "llvm/System/Host.h" 34#include "llvm/System/Path.h" 35#include "llvm/System/Program.h" 36using namespace clang; 37 38CompilerInstance::CompilerInstance() 39 : Invocation(new CompilerInvocation()) { 40} 41 42CompilerInstance::~CompilerInstance() { 43} 44 45void CompilerInstance::setLLVMContext(llvm::LLVMContext *Value) { 46 LLVMContext.reset(Value); 47} 48 49void CompilerInstance::setInvocation(CompilerInvocation *Value) { 50 Invocation.reset(Value); 51} 52 53void CompilerInstance::setDiagnostics(Diagnostic *Value) { 54 Diagnostics.reset(Value); 55} 56 57void CompilerInstance::setDiagnosticClient(DiagnosticClient *Value) { 58 DiagClient.reset(Value); 59} 60 61void CompilerInstance::setTarget(TargetInfo *Value) { 62 Target.reset(Value); 63} 64 65void CompilerInstance::setFileManager(FileManager *Value) { 66 FileMgr.reset(Value); 67} 68 69void CompilerInstance::setSourceManager(SourceManager *Value) { 70 SourceMgr.reset(Value); 71} 72 73void CompilerInstance::setPreprocessor(Preprocessor *Value) { 74 PP.reset(Value); 75} 76 77void CompilerInstance::setASTContext(ASTContext *Value) { 78 Context.reset(Value); 79} 80 81void CompilerInstance::setASTConsumer(ASTConsumer *Value) { 82 Consumer.reset(Value); 83} 84 85void CompilerInstance::setCodeCompletionConsumer(CodeCompleteConsumer *Value) { 86 CompletionConsumer.reset(Value); 87} 88 89// Diagnostics 90namespace { 91 class BinaryDiagnosticSerializer : public DiagnosticClient { 92 llvm::raw_ostream &OS; 93 SourceManager *SourceMgr; 94 public: 95 explicit BinaryDiagnosticSerializer(llvm::raw_ostream &OS) 96 : OS(OS), SourceMgr(0) { } 97 98 virtual void HandleDiagnostic(Diagnostic::Level DiagLevel, 99 const DiagnosticInfo &Info); 100 }; 101} 102 103void BinaryDiagnosticSerializer::HandleDiagnostic(Diagnostic::Level DiagLevel, 104 const DiagnosticInfo &Info) { 105 StoredDiagnostic(DiagLevel, Info).Serialize(OS); 106} 107 108static void SetUpBuildDumpLog(const DiagnosticOptions &DiagOpts, 109 unsigned argc, char **argv, 110 Diagnostic &Diags) { 111 std::string ErrorInfo; 112 llvm::raw_ostream *OS = 113 new llvm::raw_fd_ostream(DiagOpts.DumpBuildInformation.c_str(), ErrorInfo); 114 if (!ErrorInfo.empty()) { 115 Diags.Report(diag::err_fe_unable_to_open_logfile) 116 << DiagOpts.DumpBuildInformation << ErrorInfo; 117 delete OS; 118 return; 119 } 120 121 (*OS) << "clang -cc1 command line arguments: "; 122 for (unsigned i = 0; i != argc; ++i) 123 (*OS) << argv[i] << ' '; 124 (*OS) << '\n'; 125 126 // Chain in a diagnostic client which will log the diagnostics. 127 DiagnosticClient *Logger = 128 new TextDiagnosticPrinter(*OS, DiagOpts, /*OwnsOutputStream=*/true); 129 Diags.setClient(new ChainedDiagnosticClient(Diags.getClient(), Logger)); 130} 131 132void CompilerInstance::createDiagnostics(int Argc, char **Argv) { 133 Diagnostics.reset(createDiagnostics(getDiagnosticOpts(), Argc, Argv)); 134 135 if (Diagnostics) 136 DiagClient.reset(Diagnostics->getClient()); 137} 138 139Diagnostic *CompilerInstance::createDiagnostics(const DiagnosticOptions &Opts, 140 int Argc, char **Argv) { 141 llvm::OwningPtr<Diagnostic> Diags(new Diagnostic()); 142 143 // Create the diagnostic client for reporting errors or for 144 // implementing -verify. 145 llvm::OwningPtr<DiagnosticClient> DiagClient; 146 if (Opts.BinaryOutput) { 147 if (llvm::sys::Program::ChangeStderrToBinary()) { 148 // We weren't able to set standard error to binary, which is a 149 // bit of a problem. So, just create a text diagnostic printer 150 // to complain about this problem, and pretend that the user 151 // didn't try to use binary output. 152 DiagClient.reset(new TextDiagnosticPrinter(llvm::errs(), Opts)); 153 Diags->setClient(DiagClient.take()); 154 Diags->Report(diag::err_fe_stderr_binary); 155 return Diags.take(); 156 } else { 157 DiagClient.reset(new BinaryDiagnosticSerializer(llvm::errs())); 158 } 159 } else { 160 DiagClient.reset(new TextDiagnosticPrinter(llvm::errs(), Opts)); 161 } 162 163 // Chain in -verify checker, if requested. 164 if (Opts.VerifyDiagnostics) 165 DiagClient.reset(new VerifyDiagnosticsClient(*Diags, DiagClient.take())); 166 167 Diags->setClient(DiagClient.take()); 168 if (!Opts.DumpBuildInformation.empty()) 169 SetUpBuildDumpLog(Opts, Argc, Argv, *Diags); 170 171 // Configure our handling of diagnostics. 172 if (ProcessWarningOptions(*Diags, Opts)) 173 return 0; 174 175 return Diags.take(); 176} 177 178// File Manager 179 180void CompilerInstance::createFileManager() { 181 FileMgr.reset(new FileManager()); 182} 183 184// Source Manager 185 186void CompilerInstance::createSourceManager() { 187 SourceMgr.reset(new SourceManager(getDiagnostics())); 188} 189 190// Preprocessor 191 192void CompilerInstance::createPreprocessor() { 193 PP.reset(createPreprocessor(getDiagnostics(), getLangOpts(), 194 getPreprocessorOpts(), getHeaderSearchOpts(), 195 getDependencyOutputOpts(), getTarget(), 196 getFrontendOpts(), getSourceManager(), 197 getFileManager())); 198} 199 200Preprocessor * 201CompilerInstance::createPreprocessor(Diagnostic &Diags, 202 const LangOptions &LangInfo, 203 const PreprocessorOptions &PPOpts, 204 const HeaderSearchOptions &HSOpts, 205 const DependencyOutputOptions &DepOpts, 206 const TargetInfo &Target, 207 const FrontendOptions &FEOpts, 208 SourceManager &SourceMgr, 209 FileManager &FileMgr) { 210 // Create a PTH manager if we are using some form of a token cache. 211 PTHManager *PTHMgr = 0; 212 if (!PPOpts.TokenCache.empty()) 213 PTHMgr = PTHManager::Create(PPOpts.TokenCache, Diags); 214 215 // Create the Preprocessor. 216 HeaderSearch *HeaderInfo = new HeaderSearch(FileMgr); 217 Preprocessor *PP = new Preprocessor(Diags, LangInfo, Target, 218 SourceMgr, *HeaderInfo, PTHMgr, 219 /*OwnsHeaderSearch=*/true); 220 221 // Note that this is different then passing PTHMgr to Preprocessor's ctor. 222 // That argument is used as the IdentifierInfoLookup argument to 223 // IdentifierTable's ctor. 224 if (PTHMgr) { 225 PTHMgr->setPreprocessor(PP); 226 PP->setPTHManager(PTHMgr); 227 } 228 229 InitializePreprocessor(*PP, PPOpts, HSOpts, FEOpts); 230 231 // Handle generating dependencies, if requested. 232 if (!DepOpts.OutputFile.empty()) 233 AttachDependencyFileGen(*PP, DepOpts); 234 235 return PP; 236} 237 238// ASTContext 239 240void CompilerInstance::createASTContext() { 241 Preprocessor &PP = getPreprocessor(); 242 Context.reset(new ASTContext(getLangOpts(), PP.getSourceManager(), 243 getTarget(), PP.getIdentifierTable(), 244 PP.getSelectorTable(), PP.getBuiltinInfo(), 245 /*FreeMemory=*/ !getFrontendOpts().DisableFree, 246 /*size_reserve=*/ 0)); 247} 248 249// ExternalASTSource 250 251void CompilerInstance::createPCHExternalASTSource(llvm::StringRef Path) { 252 llvm::OwningPtr<ExternalASTSource> Source; 253 Source.reset(createPCHExternalASTSource(Path, getHeaderSearchOpts().Sysroot, 254 getPreprocessor(), getASTContext())); 255 getASTContext().setExternalSource(Source); 256} 257 258ExternalASTSource * 259CompilerInstance::createPCHExternalASTSource(llvm::StringRef Path, 260 const std::string &Sysroot, 261 Preprocessor &PP, 262 ASTContext &Context) { 263 llvm::OwningPtr<PCHReader> Reader; 264 Reader.reset(new PCHReader(PP, &Context, 265 Sysroot.empty() ? 0 : Sysroot.c_str())); 266 267 switch (Reader->ReadPCH(Path)) { 268 case PCHReader::Success: 269 // Set the predefines buffer as suggested by the PCH reader. Typically, the 270 // predefines buffer will be empty. 271 PP.setPredefines(Reader->getSuggestedPredefines()); 272 return Reader.take(); 273 274 case PCHReader::Failure: 275 // Unrecoverable failure: don't even try to process the input file. 276 break; 277 278 case PCHReader::IgnorePCH: 279 // No suitable PCH file could be found. Return an error. 280 break; 281 } 282 283 return 0; 284} 285 286// Code Completion 287 288void CompilerInstance::createCodeCompletionConsumer() { 289 const ParsedSourceLocation &Loc = getFrontendOpts().CodeCompletionAt; 290 CompletionConsumer.reset( 291 createCodeCompletionConsumer(getPreprocessor(), 292 Loc.FileName, Loc.Line, Loc.Column, 293 getFrontendOpts().DebugCodeCompletionPrinter, 294 getFrontendOpts().ShowMacrosInCodeCompletion, 295 llvm::outs())); 296 if (!CompletionConsumer) 297 return; 298 299 if (CompletionConsumer->isOutputBinary() && 300 llvm::sys::Program::ChangeStdoutToBinary()) { 301 getPreprocessor().getDiagnostics().Report(diag::err_fe_stdout_binary); 302 CompletionConsumer.reset(); 303 } 304} 305 306void CompilerInstance::createFrontendTimer() { 307 FrontendTimer.reset(new llvm::Timer("Clang front-end timer")); 308} 309 310CodeCompleteConsumer * 311CompilerInstance::createCodeCompletionConsumer(Preprocessor &PP, 312 const std::string &Filename, 313 unsigned Line, 314 unsigned Column, 315 bool UseDebugPrinter, 316 bool ShowMacros, 317 llvm::raw_ostream &OS) { 318 // Tell the source manager to chop off the given file at a specific 319 // line and column. 320 const FileEntry *Entry = PP.getFileManager().getFile(Filename); 321 if (!Entry) { 322 PP.getDiagnostics().Report(diag::err_fe_invalid_code_complete_file) 323 << Filename; 324 return 0; 325 } 326 327 // Truncate the named file at the given line/column. 328 PP.SetCodeCompletionPoint(Entry, Line, Column); 329 330 // Set up the creation routine for code-completion. 331 if (UseDebugPrinter) 332 return new PrintingCodeCompleteConsumer(ShowMacros, OS); 333 else 334 return new CIndexCodeCompleteConsumer(ShowMacros, OS); 335} 336 337// Output Files 338 339void CompilerInstance::addOutputFile(llvm::StringRef Path, 340 llvm::raw_ostream *OS) { 341 assert(OS && "Attempt to add empty stream to output list!"); 342 OutputFiles.push_back(std::make_pair(Path, OS)); 343} 344 345void CompilerInstance::clearOutputFiles(bool EraseFiles) { 346 for (std::list< std::pair<std::string, llvm::raw_ostream*> >::iterator 347 it = OutputFiles.begin(), ie = OutputFiles.end(); it != ie; ++it) { 348 delete it->second; 349 if (EraseFiles && !it->first.empty()) 350 llvm::sys::Path(it->first).eraseFromDisk(); 351 } 352 OutputFiles.clear(); 353} 354 355llvm::raw_fd_ostream * 356CompilerInstance::createDefaultOutputFile(bool Binary, 357 llvm::StringRef InFile, 358 llvm::StringRef Extension) { 359 return createOutputFile(getFrontendOpts().OutputFile, Binary, 360 InFile, Extension); 361} 362 363llvm::raw_fd_ostream * 364CompilerInstance::createOutputFile(llvm::StringRef OutputPath, 365 bool Binary, 366 llvm::StringRef InFile, 367 llvm::StringRef Extension) { 368 std::string Error, OutputPathName; 369 llvm::raw_fd_ostream *OS = createOutputFile(OutputPath, Error, Binary, 370 InFile, Extension, 371 &OutputPathName); 372 if (!OS) { 373 getDiagnostics().Report(diag::err_fe_unable_to_open_output) 374 << OutputPath << Error; 375 return 0; 376 } 377 378 // Add the output file -- but don't try to remove "-", since this means we are 379 // using stdin. 380 addOutputFile((OutputPathName != "-") ? OutputPathName : "", OS); 381 382 return OS; 383} 384 385llvm::raw_fd_ostream * 386CompilerInstance::createOutputFile(llvm::StringRef OutputPath, 387 std::string &Error, 388 bool Binary, 389 llvm::StringRef InFile, 390 llvm::StringRef Extension, 391 std::string *ResultPathName) { 392 std::string OutFile; 393 if (!OutputPath.empty()) { 394 OutFile = OutputPath; 395 } else if (InFile == "-") { 396 OutFile = "-"; 397 } else if (!Extension.empty()) { 398 llvm::sys::Path Path(InFile); 399 Path.eraseSuffix(); 400 Path.appendSuffix(Extension); 401 OutFile = Path.str(); 402 } else { 403 OutFile = "-"; 404 } 405 406 llvm::OwningPtr<llvm::raw_fd_ostream> OS( 407 new llvm::raw_fd_ostream(OutFile.c_str(), Error, 408 (Binary ? llvm::raw_fd_ostream::F_Binary : 0))); 409 if (!Error.empty()) 410 return 0; 411 412 if (ResultPathName) 413 *ResultPathName = OutFile; 414 415 return OS.take(); 416} 417 418// Initialization Utilities 419 420bool CompilerInstance::InitializeSourceManager(llvm::StringRef InputFile) { 421 return InitializeSourceManager(InputFile, getDiagnostics(), getFileManager(), 422 getSourceManager(), getFrontendOpts()); 423} 424 425bool CompilerInstance::InitializeSourceManager(llvm::StringRef InputFile, 426 Diagnostic &Diags, 427 FileManager &FileMgr, 428 SourceManager &SourceMgr, 429 const FrontendOptions &Opts) { 430 // Figure out where to get and map in the main file. 431 if (Opts.EmptyInputOnly) { 432 const char *EmptyStr = ""; 433 llvm::MemoryBuffer *SB = 434 llvm::MemoryBuffer::getMemBuffer(EmptyStr, EmptyStr, "<empty input>"); 435 SourceMgr.createMainFileIDForMemBuffer(SB); 436 } else if (InputFile != "-") { 437 const FileEntry *File = FileMgr.getFile(InputFile); 438 if (File) SourceMgr.createMainFileID(File, SourceLocation()); 439 if (SourceMgr.getMainFileID().isInvalid()) { 440 Diags.Report(diag::err_fe_error_reading) << InputFile; 441 return false; 442 } 443 } else { 444 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN(); 445 SourceMgr.createMainFileIDForMemBuffer(SB); 446 if (SourceMgr.getMainFileID().isInvalid()) { 447 Diags.Report(diag::err_fe_error_reading_stdin); 448 return false; 449 } 450 } 451 452 return true; 453} 454 455// High-Level Operations 456 457bool CompilerInstance::ExecuteAction(FrontendAction &Act) { 458 assert(hasDiagnostics() && "Diagnostics engine is not initialized!"); 459 assert(!getFrontendOpts().ShowHelp && "Client must handle '-help'!"); 460 assert(!getFrontendOpts().ShowVersion && "Client must handle '-version'!"); 461 462 // FIXME: Take this as an argument, once all the APIs we used have moved to 463 // taking it as an input instead of hard-coding llvm::errs. 464 llvm::raw_ostream &OS = llvm::errs(); 465 466 // Create the target instance. 467 setTarget(TargetInfo::CreateTargetInfo(getDiagnostics(), getTargetOpts())); 468 if (!hasTarget()) 469 return false; 470 471 // Inform the target of the language options. 472 // 473 // FIXME: We shouldn't need to do this, the target should be immutable once 474 // created. This complexity should be lifted elsewhere. 475 getTarget().setForcedLangOptions(getLangOpts()); 476 477 // Validate/process some options. 478 if (getHeaderSearchOpts().Verbose) 479 OS << "clang -cc1 version " CLANG_VERSION_STRING 480 << " based upon " << PACKAGE_STRING 481 << " hosted on " << llvm::sys::getHostTriple() << "\n"; 482 483 if (getFrontendOpts().ShowTimers) 484 createFrontendTimer(); 485 486 for (unsigned i = 0, e = getFrontendOpts().Inputs.size(); i != e; ++i) { 487 const std::string &InFile = getFrontendOpts().Inputs[i].second; 488 489 // If we aren't using an AST file, setup the file and source managers and 490 // the preprocessor. 491 bool IsAST = getFrontendOpts().Inputs[i].first == FrontendOptions::IK_AST; 492 if (!IsAST) { 493 if (!i) { 494 // Create a file manager object to provide access to and cache the 495 // filesystem. 496 createFileManager(); 497 498 // Create the source manager. 499 createSourceManager(); 500 } else { 501 // Reset the ID tables if we are reusing the SourceManager. 502 getSourceManager().clearIDTables(); 503 } 504 505 // Create the preprocessor. 506 createPreprocessor(); 507 } 508 509 if (Act.BeginSourceFile(*this, InFile, IsAST)) { 510 Act.Execute(); 511 Act.EndSourceFile(); 512 } 513 } 514 515 if (getDiagnosticOpts().ShowCarets) 516 if (unsigned NumDiagnostics = getDiagnostics().getNumDiagnostics()) 517 OS << NumDiagnostics << " diagnostic" 518 << (NumDiagnostics == 1 ? "" : "s") 519 << " generated.\n"; 520 521 if (getFrontendOpts().ShowStats) { 522 getFileManager().PrintStats(); 523 OS << "\n"; 524 } 525 526 // Return the appropriate status when verifying diagnostics. 527 // 528 // FIXME: If we could make getNumErrors() do the right thing, we wouldn't need 529 // this. 530 if (getDiagnosticOpts().VerifyDiagnostics) 531 return !static_cast<VerifyDiagnosticsClient&>( 532 getDiagnosticClient()).HadErrors(); 533 534 return !getDiagnostics().getNumErrors(); 535} 536 537 538