CompilerInstance.cpp 20 KB

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