CompilerInstance.cpp 18 KB

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