CompilerInstance.cpp 40 KB

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