CompilerInstance.cpp 20 KB

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