CompilerInstance.cpp 60 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606
  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/AST/Decl.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/Config/config.h"
  19. #include "clang/Frontend/ChainedDiagnosticConsumer.h"
  20. #include "clang/Frontend/FrontendAction.h"
  21. #include "clang/Frontend/FrontendActions.h"
  22. #include "clang/Frontend/FrontendDiagnostic.h"
  23. #include "clang/Frontend/LogDiagnosticPrinter.h"
  24. #include "clang/Frontend/SerializedDiagnosticPrinter.h"
  25. #include "clang/Frontend/TextDiagnosticPrinter.h"
  26. #include "clang/Frontend/Utils.h"
  27. #include "clang/Frontend/VerifyDiagnosticConsumer.h"
  28. #include "clang/Lex/HeaderSearch.h"
  29. #include "clang/Lex/PTHManager.h"
  30. #include "clang/Lex/Preprocessor.h"
  31. #include "clang/Sema/CodeCompleteConsumer.h"
  32. #include "clang/Sema/Sema.h"
  33. #include "clang/Serialization/ASTReader.h"
  34. #include "clang/Serialization/GlobalModuleIndex.h"
  35. #include "llvm/ADT/Statistic.h"
  36. #include "llvm/Support/CrashRecoveryContext.h"
  37. #include "llvm/Support/Errc.h"
  38. #include "llvm/Support/FileSystem.h"
  39. #include "llvm/Support/Host.h"
  40. #include "llvm/Support/LockFileManager.h"
  41. #include "llvm/Support/MemoryBuffer.h"
  42. #include "llvm/Support/Path.h"
  43. #include "llvm/Support/Program.h"
  44. #include "llvm/Support/Signals.h"
  45. #include "llvm/Support/Timer.h"
  46. #include "llvm/Support/raw_ostream.h"
  47. #include <sys/stat.h>
  48. #include <system_error>
  49. #include <time.h>
  50. using namespace clang;
  51. CompilerInstance::CompilerInstance(bool BuildingModule)
  52. : ModuleLoader(BuildingModule),
  53. Invocation(new CompilerInvocation()), ModuleManager(nullptr),
  54. BuildGlobalModuleIndex(false), HaveFullGlobalModuleIndex(false),
  55. ModuleBuildFailed(false) {
  56. }
  57. CompilerInstance::~CompilerInstance() {
  58. assert(OutputFiles.empty() && "Still output files in flight?");
  59. }
  60. void CompilerInstance::setInvocation(CompilerInvocation *Value) {
  61. Invocation = Value;
  62. }
  63. bool CompilerInstance::shouldBuildGlobalModuleIndex() const {
  64. return (BuildGlobalModuleIndex ||
  65. (ModuleManager && ModuleManager->isGlobalIndexUnavailable() &&
  66. getFrontendOpts().GenerateGlobalModuleIndex)) &&
  67. !ModuleBuildFailed;
  68. }
  69. void CompilerInstance::setDiagnostics(DiagnosticsEngine *Value) {
  70. Diagnostics = Value;
  71. }
  72. void CompilerInstance::setTarget(TargetInfo *Value) {
  73. Target = Value;
  74. }
  75. void CompilerInstance::setFileManager(FileManager *Value) {
  76. FileMgr = Value;
  77. if (Value)
  78. VirtualFileSystem = Value->getVirtualFileSystem();
  79. else
  80. VirtualFileSystem.reset();
  81. }
  82. void CompilerInstance::setSourceManager(SourceManager *Value) {
  83. SourceMgr = Value;
  84. }
  85. void CompilerInstance::setPreprocessor(Preprocessor *Value) { PP = Value; }
  86. void CompilerInstance::setASTContext(ASTContext *Value) { Context = Value; }
  87. void CompilerInstance::setSema(Sema *S) {
  88. TheSema.reset(S);
  89. }
  90. void CompilerInstance::setASTConsumer(std::unique_ptr<ASTConsumer> Value) {
  91. Consumer = std::move(Value);
  92. }
  93. void CompilerInstance::setCodeCompletionConsumer(CodeCompleteConsumer *Value) {
  94. CompletionConsumer.reset(Value);
  95. }
  96. std::unique_ptr<Sema> CompilerInstance::takeSema() {
  97. return std::move(TheSema);
  98. }
  99. IntrusiveRefCntPtr<ASTReader> CompilerInstance::getModuleManager() const {
  100. return ModuleManager;
  101. }
  102. void CompilerInstance::setModuleManager(IntrusiveRefCntPtr<ASTReader> Reader) {
  103. ModuleManager = Reader;
  104. }
  105. std::shared_ptr<ModuleDependencyCollector>
  106. CompilerInstance::getModuleDepCollector() const {
  107. return ModuleDepCollector;
  108. }
  109. void CompilerInstance::setModuleDepCollector(
  110. std::shared_ptr<ModuleDependencyCollector> Collector) {
  111. ModuleDepCollector = Collector;
  112. }
  113. // Diagnostics
  114. static void SetUpDiagnosticLog(DiagnosticOptions *DiagOpts,
  115. const CodeGenOptions *CodeGenOpts,
  116. DiagnosticsEngine &Diags) {
  117. std::error_code EC;
  118. bool OwnsStream = false;
  119. raw_ostream *OS = &llvm::errs();
  120. if (DiagOpts->DiagnosticLogFile != "-") {
  121. // Create the output stream.
  122. llvm::raw_fd_ostream *FileOS(new llvm::raw_fd_ostream(
  123. DiagOpts->DiagnosticLogFile, EC,
  124. llvm::sys::fs::F_Append | llvm::sys::fs::F_Text));
  125. if (EC) {
  126. Diags.Report(diag::warn_fe_cc_log_diagnostics_failure)
  127. << DiagOpts->DiagnosticLogFile << EC.message();
  128. } else {
  129. FileOS->SetUnbuffered();
  130. FileOS->SetUseAtomicWrites(true);
  131. OS = FileOS;
  132. OwnsStream = true;
  133. }
  134. }
  135. // Chain in the diagnostic client which will log the diagnostics.
  136. LogDiagnosticPrinter *Logger = new LogDiagnosticPrinter(*OS, DiagOpts,
  137. OwnsStream);
  138. if (CodeGenOpts)
  139. Logger->setDwarfDebugFlags(CodeGenOpts->DwarfDebugFlags);
  140. Diags.setClient(new ChainedDiagnosticConsumer(Diags.takeClient(), Logger));
  141. }
  142. static void SetupSerializedDiagnostics(DiagnosticOptions *DiagOpts,
  143. DiagnosticsEngine &Diags,
  144. StringRef OutputFile) {
  145. std::error_code EC;
  146. std::unique_ptr<llvm::raw_fd_ostream> OS;
  147. OS.reset(
  148. new llvm::raw_fd_ostream(OutputFile.str(), EC, llvm::sys::fs::F_None));
  149. if (EC) {
  150. Diags.Report(diag::warn_fe_serialized_diag_failure) << OutputFile
  151. << EC.message();
  152. return;
  153. }
  154. DiagnosticConsumer *SerializedConsumer =
  155. clang::serialized_diags::create(OS.release(), DiagOpts);
  156. Diags.setClient(new ChainedDiagnosticConsumer(Diags.takeClient(),
  157. SerializedConsumer));
  158. }
  159. void CompilerInstance::createDiagnostics(DiagnosticConsumer *Client,
  160. bool ShouldOwnClient) {
  161. Diagnostics = createDiagnostics(&getDiagnosticOpts(), Client,
  162. ShouldOwnClient, &getCodeGenOpts());
  163. }
  164. IntrusiveRefCntPtr<DiagnosticsEngine>
  165. CompilerInstance::createDiagnostics(DiagnosticOptions *Opts,
  166. DiagnosticConsumer *Client,
  167. bool ShouldOwnClient,
  168. const CodeGenOptions *CodeGenOpts) {
  169. IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
  170. IntrusiveRefCntPtr<DiagnosticsEngine>
  171. Diags(new DiagnosticsEngine(DiagID, Opts));
  172. // Create the diagnostic client for reporting errors or for
  173. // implementing -verify.
  174. if (Client) {
  175. Diags->setClient(Client, ShouldOwnClient);
  176. } else
  177. Diags->setClient(new TextDiagnosticPrinter(llvm::errs(), Opts));
  178. // Chain in -verify checker, if requested.
  179. if (Opts->VerifyDiagnostics)
  180. Diags->setClient(new VerifyDiagnosticConsumer(*Diags));
  181. // Chain in -diagnostic-log-file dumper, if requested.
  182. if (!Opts->DiagnosticLogFile.empty())
  183. SetUpDiagnosticLog(Opts, CodeGenOpts, *Diags);
  184. if (!Opts->DiagnosticSerializationFile.empty())
  185. SetupSerializedDiagnostics(Opts, *Diags,
  186. Opts->DiagnosticSerializationFile);
  187. // Configure our handling of diagnostics.
  188. ProcessWarningOptions(*Diags, *Opts);
  189. return Diags;
  190. }
  191. // File Manager
  192. void CompilerInstance::createFileManager() {
  193. if (!hasVirtualFileSystem()) {
  194. // TODO: choose the virtual file system based on the CompilerInvocation.
  195. setVirtualFileSystem(vfs::getRealFileSystem());
  196. }
  197. FileMgr = new FileManager(getFileSystemOpts(), VirtualFileSystem);
  198. }
  199. // Source Manager
  200. void CompilerInstance::createSourceManager(FileManager &FileMgr) {
  201. SourceMgr = new SourceManager(getDiagnostics(), FileMgr);
  202. }
  203. // Initialize the remapping of files to alternative contents, e.g.,
  204. // those specified through other files.
  205. static void InitializeFileRemapping(DiagnosticsEngine &Diags,
  206. SourceManager &SourceMgr,
  207. FileManager &FileMgr,
  208. const PreprocessorOptions &InitOpts) {
  209. // Remap files in the source manager (with buffers).
  210. for (const auto &RB : InitOpts.RemappedFileBuffers) {
  211. // Create the file entry for the file that we're mapping from.
  212. const FileEntry *FromFile =
  213. FileMgr.getVirtualFile(RB.first, RB.second->getBufferSize(), 0);
  214. if (!FromFile) {
  215. Diags.Report(diag::err_fe_remap_missing_from_file) << RB.first;
  216. if (!InitOpts.RetainRemappedFileBuffers)
  217. delete RB.second;
  218. continue;
  219. }
  220. // Override the contents of the "from" file with the contents of
  221. // the "to" file.
  222. SourceMgr.overrideFileContents(FromFile, RB.second,
  223. InitOpts.RetainRemappedFileBuffers);
  224. }
  225. // Remap files in the source manager (with other files).
  226. for (const auto &RF : InitOpts.RemappedFiles) {
  227. // Find the file that we're mapping to.
  228. const FileEntry *ToFile = FileMgr.getFile(RF.second);
  229. if (!ToFile) {
  230. Diags.Report(diag::err_fe_remap_missing_to_file) << RF.first << RF.second;
  231. continue;
  232. }
  233. // Create the file entry for the file that we're mapping from.
  234. const FileEntry *FromFile =
  235. FileMgr.getVirtualFile(RF.first, ToFile->getSize(), 0);
  236. if (!FromFile) {
  237. Diags.Report(diag::err_fe_remap_missing_from_file) << RF.first;
  238. continue;
  239. }
  240. // Override the contents of the "from" file with the contents of
  241. // the "to" file.
  242. SourceMgr.overrideFileContents(FromFile, ToFile);
  243. }
  244. SourceMgr.setOverridenFilesKeepOriginalName(
  245. InitOpts.RemappedFilesKeepOriginalName);
  246. }
  247. // Preprocessor
  248. void CompilerInstance::createPreprocessor(TranslationUnitKind TUKind) {
  249. const PreprocessorOptions &PPOpts = getPreprocessorOpts();
  250. // Create a PTH manager if we are using some form of a token cache.
  251. PTHManager *PTHMgr = nullptr;
  252. if (!PPOpts.TokenCache.empty())
  253. PTHMgr = PTHManager::Create(PPOpts.TokenCache, getDiagnostics());
  254. // Create the Preprocessor.
  255. HeaderSearch *HeaderInfo = new HeaderSearch(&getHeaderSearchOpts(),
  256. getSourceManager(),
  257. getDiagnostics(),
  258. getLangOpts(),
  259. &getTarget());
  260. PP = new Preprocessor(&getPreprocessorOpts(), getDiagnostics(), getLangOpts(),
  261. getSourceManager(), *HeaderInfo, *this, PTHMgr,
  262. /*OwnsHeaderSearch=*/true, TUKind);
  263. PP->Initialize(getTarget());
  264. // Note that this is different then passing PTHMgr to Preprocessor's ctor.
  265. // That argument is used as the IdentifierInfoLookup argument to
  266. // IdentifierTable's ctor.
  267. if (PTHMgr) {
  268. PTHMgr->setPreprocessor(&*PP);
  269. PP->setPTHManager(PTHMgr);
  270. }
  271. if (PPOpts.DetailedRecord)
  272. PP->createPreprocessingRecord();
  273. // Apply remappings to the source manager.
  274. InitializeFileRemapping(PP->getDiagnostics(), PP->getSourceManager(),
  275. PP->getFileManager(), PPOpts);
  276. // Predefine macros and configure the preprocessor.
  277. InitializePreprocessor(*PP, PPOpts, getFrontendOpts());
  278. // Initialize the header search object.
  279. ApplyHeaderSearchOptions(PP->getHeaderSearchInfo(), getHeaderSearchOpts(),
  280. PP->getLangOpts(), PP->getTargetInfo().getTriple());
  281. PP->setPreprocessedOutput(getPreprocessorOutputOpts().ShowCPP);
  282. // Set up the module path, including the hash for the
  283. // module-creation options.
  284. SmallString<256> SpecificModuleCache(
  285. getHeaderSearchOpts().ModuleCachePath);
  286. if (!getHeaderSearchOpts().DisableModuleHash)
  287. llvm::sys::path::append(SpecificModuleCache,
  288. getInvocation().getModuleHash());
  289. PP->getHeaderSearchInfo().setModuleCachePath(SpecificModuleCache);
  290. // Handle generating dependencies, if requested.
  291. const DependencyOutputOptions &DepOpts = getDependencyOutputOpts();
  292. if (!DepOpts.OutputFile.empty())
  293. TheDependencyFileGenerator.reset(
  294. DependencyFileGenerator::CreateAndAttachToPreprocessor(*PP, DepOpts));
  295. if (!DepOpts.DOTOutputFile.empty())
  296. AttachDependencyGraphGen(*PP, DepOpts.DOTOutputFile,
  297. getHeaderSearchOpts().Sysroot);
  298. for (auto &Listener : DependencyCollectors)
  299. Listener->attachToPreprocessor(*PP);
  300. // If we don't have a collector, but we are collecting module dependencies,
  301. // then we're the top level compiler instance and need to create one.
  302. if (!ModuleDepCollector && !DepOpts.ModuleDependencyOutputDir.empty())
  303. ModuleDepCollector = std::make_shared<ModuleDependencyCollector>(
  304. DepOpts.ModuleDependencyOutputDir);
  305. // Handle generating header include information, if requested.
  306. if (DepOpts.ShowHeaderIncludes)
  307. AttachHeaderIncludeGen(*PP);
  308. if (!DepOpts.HeaderIncludeOutputFile.empty()) {
  309. StringRef OutputPath = DepOpts.HeaderIncludeOutputFile;
  310. if (OutputPath == "-")
  311. OutputPath = "";
  312. AttachHeaderIncludeGen(*PP, /*ShowAllHeaders=*/true, OutputPath,
  313. /*ShowDepth=*/false);
  314. }
  315. if (DepOpts.PrintShowIncludes) {
  316. AttachHeaderIncludeGen(*PP, /*ShowAllHeaders=*/false, /*OutputPath=*/"",
  317. /*ShowDepth=*/true, /*MSStyle=*/true);
  318. }
  319. }
  320. // ASTContext
  321. void CompilerInstance::createASTContext() {
  322. Preprocessor &PP = getPreprocessor();
  323. Context = new ASTContext(getLangOpts(), PP.getSourceManager(),
  324. PP.getIdentifierTable(), PP.getSelectorTable(),
  325. PP.getBuiltinInfo());
  326. Context->InitBuiltinTypes(getTarget());
  327. }
  328. // ExternalASTSource
  329. void CompilerInstance::createPCHExternalASTSource(
  330. StringRef Path, bool DisablePCHValidation, bool AllowPCHWithCompilerErrors,
  331. void *DeserializationListener, bool OwnDeserializationListener) {
  332. IntrusiveRefCntPtr<ExternalASTSource> Source;
  333. bool Preamble = getPreprocessorOpts().PrecompiledPreambleBytes.first != 0;
  334. Source = createPCHExternalASTSource(
  335. Path, getHeaderSearchOpts().Sysroot, DisablePCHValidation,
  336. AllowPCHWithCompilerErrors, getPreprocessor(), getASTContext(),
  337. DeserializationListener, OwnDeserializationListener, Preamble,
  338. getFrontendOpts().UseGlobalModuleIndex);
  339. ModuleManager = static_cast<ASTReader*>(Source.get());
  340. getASTContext().setExternalSource(Source);
  341. }
  342. ExternalASTSource *CompilerInstance::createPCHExternalASTSource(
  343. StringRef Path, const std::string &Sysroot, bool DisablePCHValidation,
  344. bool AllowPCHWithCompilerErrors, Preprocessor &PP, ASTContext &Context,
  345. void *DeserializationListener, bool OwnDeserializationListener,
  346. bool Preamble, bool UseGlobalModuleIndex) {
  347. HeaderSearchOptions &HSOpts = PP.getHeaderSearchInfo().getHeaderSearchOpts();
  348. std::unique_ptr<ASTReader> Reader;
  349. Reader.reset(new ASTReader(PP, Context,
  350. Sysroot.empty() ? "" : Sysroot.c_str(),
  351. DisablePCHValidation,
  352. AllowPCHWithCompilerErrors,
  353. /*AllowConfigurationMismatch*/false,
  354. HSOpts.ModulesValidateSystemHeaders,
  355. UseGlobalModuleIndex));
  356. Reader->setDeserializationListener(
  357. static_cast<ASTDeserializationListener *>(DeserializationListener),
  358. /*TakeOwnership=*/OwnDeserializationListener);
  359. switch (Reader->ReadAST(Path,
  360. Preamble ? serialization::MK_Preamble
  361. : serialization::MK_PCH,
  362. SourceLocation(),
  363. ASTReader::ARR_None)) {
  364. case ASTReader::Success:
  365. // Set the predefines buffer as suggested by the PCH reader. Typically, the
  366. // predefines buffer will be empty.
  367. PP.setPredefines(Reader->getSuggestedPredefines());
  368. return Reader.release();
  369. case ASTReader::Failure:
  370. // Unrecoverable failure: don't even try to process the input file.
  371. break;
  372. case ASTReader::Missing:
  373. case ASTReader::OutOfDate:
  374. case ASTReader::VersionMismatch:
  375. case ASTReader::ConfigurationMismatch:
  376. case ASTReader::HadErrors:
  377. // No suitable PCH file could be found. Return an error.
  378. break;
  379. }
  380. return nullptr;
  381. }
  382. // Code Completion
  383. static bool EnableCodeCompletion(Preprocessor &PP,
  384. const std::string &Filename,
  385. unsigned Line,
  386. unsigned Column) {
  387. // Tell the source manager to chop off the given file at a specific
  388. // line and column.
  389. const FileEntry *Entry = PP.getFileManager().getFile(Filename);
  390. if (!Entry) {
  391. PP.getDiagnostics().Report(diag::err_fe_invalid_code_complete_file)
  392. << Filename;
  393. return true;
  394. }
  395. // Truncate the named file at the given line/column.
  396. PP.SetCodeCompletionPoint(Entry, Line, Column);
  397. return false;
  398. }
  399. void CompilerInstance::createCodeCompletionConsumer() {
  400. const ParsedSourceLocation &Loc = getFrontendOpts().CodeCompletionAt;
  401. if (!CompletionConsumer) {
  402. setCodeCompletionConsumer(
  403. createCodeCompletionConsumer(getPreprocessor(),
  404. Loc.FileName, Loc.Line, Loc.Column,
  405. getFrontendOpts().CodeCompleteOpts,
  406. llvm::outs()));
  407. if (!CompletionConsumer)
  408. return;
  409. } else if (EnableCodeCompletion(getPreprocessor(), Loc.FileName,
  410. Loc.Line, Loc.Column)) {
  411. setCodeCompletionConsumer(nullptr);
  412. return;
  413. }
  414. if (CompletionConsumer->isOutputBinary() &&
  415. llvm::sys::ChangeStdoutToBinary()) {
  416. getPreprocessor().getDiagnostics().Report(diag::err_fe_stdout_binary);
  417. setCodeCompletionConsumer(nullptr);
  418. }
  419. }
  420. void CompilerInstance::createFrontendTimer() {
  421. FrontendTimer.reset(new llvm::Timer("Clang front-end timer"));
  422. }
  423. CodeCompleteConsumer *
  424. CompilerInstance::createCodeCompletionConsumer(Preprocessor &PP,
  425. const std::string &Filename,
  426. unsigned Line,
  427. unsigned Column,
  428. const CodeCompleteOptions &Opts,
  429. raw_ostream &OS) {
  430. if (EnableCodeCompletion(PP, Filename, Line, Column))
  431. return nullptr;
  432. // Set up the creation routine for code-completion.
  433. return new PrintingCodeCompleteConsumer(Opts, OS);
  434. }
  435. void CompilerInstance::createSema(TranslationUnitKind TUKind,
  436. CodeCompleteConsumer *CompletionConsumer) {
  437. TheSema.reset(new Sema(getPreprocessor(), getASTContext(), getASTConsumer(),
  438. TUKind, CompletionConsumer));
  439. }
  440. // Output Files
  441. void CompilerInstance::addOutputFile(const OutputFile &OutFile) {
  442. assert(OutFile.OS && "Attempt to add empty stream to output list!");
  443. OutputFiles.push_back(OutFile);
  444. }
  445. void CompilerInstance::clearOutputFiles(bool EraseFiles) {
  446. for (std::list<OutputFile>::iterator
  447. it = OutputFiles.begin(), ie = OutputFiles.end(); it != ie; ++it) {
  448. delete it->OS;
  449. if (!it->TempFilename.empty()) {
  450. if (EraseFiles) {
  451. llvm::sys::fs::remove(it->TempFilename);
  452. } else {
  453. SmallString<128> NewOutFile(it->Filename);
  454. // If '-working-directory' was passed, the output filename should be
  455. // relative to that.
  456. FileMgr->FixupRelativePath(NewOutFile);
  457. if (std::error_code ec =
  458. llvm::sys::fs::rename(it->TempFilename, NewOutFile.str())) {
  459. getDiagnostics().Report(diag::err_unable_to_rename_temp)
  460. << it->TempFilename << it->Filename << ec.message();
  461. llvm::sys::fs::remove(it->TempFilename);
  462. }
  463. }
  464. } else if (!it->Filename.empty() && EraseFiles)
  465. llvm::sys::fs::remove(it->Filename);
  466. }
  467. OutputFiles.clear();
  468. }
  469. llvm::raw_fd_ostream *
  470. CompilerInstance::createDefaultOutputFile(bool Binary,
  471. StringRef InFile,
  472. StringRef Extension) {
  473. return createOutputFile(getFrontendOpts().OutputFile, Binary,
  474. /*RemoveFileOnSignal=*/true, InFile, Extension,
  475. /*UseTemporary=*/true);
  476. }
  477. llvm::raw_null_ostream *CompilerInstance::createNullOutputFile() {
  478. llvm::raw_null_ostream *OS = new llvm::raw_null_ostream();
  479. addOutputFile(OutputFile("", "", OS));
  480. return OS;
  481. }
  482. llvm::raw_fd_ostream *
  483. CompilerInstance::createOutputFile(StringRef OutputPath,
  484. bool Binary, bool RemoveFileOnSignal,
  485. StringRef InFile,
  486. StringRef Extension,
  487. bool UseTemporary,
  488. bool CreateMissingDirectories) {
  489. std::string OutputPathName, TempPathName;
  490. std::error_code EC;
  491. llvm::raw_fd_ostream *OS = createOutputFile(
  492. OutputPath, EC, Binary, RemoveFileOnSignal, InFile, Extension,
  493. UseTemporary, CreateMissingDirectories, &OutputPathName, &TempPathName);
  494. if (!OS) {
  495. getDiagnostics().Report(diag::err_fe_unable_to_open_output) << OutputPath
  496. << EC.message();
  497. return nullptr;
  498. }
  499. // Add the output file -- but don't try to remove "-", since this means we are
  500. // using stdin.
  501. addOutputFile(OutputFile((OutputPathName != "-") ? OutputPathName : "",
  502. TempPathName, OS));
  503. return OS;
  504. }
  505. llvm::raw_fd_ostream *CompilerInstance::createOutputFile(
  506. StringRef OutputPath, std::error_code &Error, bool Binary,
  507. bool RemoveFileOnSignal, StringRef InFile, StringRef Extension,
  508. bool UseTemporary, bool CreateMissingDirectories,
  509. std::string *ResultPathName, std::string *TempPathName) {
  510. assert((!CreateMissingDirectories || UseTemporary) &&
  511. "CreateMissingDirectories is only allowed when using temporary files");
  512. std::string OutFile, TempFile;
  513. if (!OutputPath.empty()) {
  514. OutFile = OutputPath;
  515. } else if (InFile == "-") {
  516. OutFile = "-";
  517. } else if (!Extension.empty()) {
  518. SmallString<128> Path(InFile);
  519. llvm::sys::path::replace_extension(Path, Extension);
  520. OutFile = Path.str();
  521. } else {
  522. OutFile = "-";
  523. }
  524. std::unique_ptr<llvm::raw_fd_ostream> OS;
  525. std::string OSFile;
  526. if (UseTemporary) {
  527. if (OutFile == "-")
  528. UseTemporary = false;
  529. else {
  530. llvm::sys::fs::file_status Status;
  531. llvm::sys::fs::status(OutputPath, Status);
  532. if (llvm::sys::fs::exists(Status)) {
  533. // Fail early if we can't write to the final destination.
  534. if (!llvm::sys::fs::can_write(OutputPath))
  535. return nullptr;
  536. // Don't use a temporary if the output is a special file. This handles
  537. // things like '-o /dev/null'
  538. if (!llvm::sys::fs::is_regular_file(Status))
  539. UseTemporary = false;
  540. }
  541. }
  542. }
  543. if (UseTemporary) {
  544. // Create a temporary file.
  545. SmallString<128> TempPath;
  546. TempPath = OutFile;
  547. TempPath += "-%%%%%%%%";
  548. int fd;
  549. std::error_code EC =
  550. llvm::sys::fs::createUniqueFile(TempPath.str(), fd, TempPath);
  551. if (CreateMissingDirectories &&
  552. EC == llvm::errc::no_such_file_or_directory) {
  553. StringRef Parent = llvm::sys::path::parent_path(OutputPath);
  554. EC = llvm::sys::fs::create_directories(Parent);
  555. if (!EC) {
  556. EC = llvm::sys::fs::createUniqueFile(TempPath.str(), fd, TempPath);
  557. }
  558. }
  559. if (!EC) {
  560. OS.reset(new llvm::raw_fd_ostream(fd, /*shouldClose=*/true));
  561. OSFile = TempFile = TempPath.str();
  562. }
  563. // If we failed to create the temporary, fallback to writing to the file
  564. // directly. This handles the corner case where we cannot write to the
  565. // directory, but can write to the file.
  566. }
  567. if (!OS) {
  568. OSFile = OutFile;
  569. OS.reset(new llvm::raw_fd_ostream(
  570. OSFile, Error,
  571. (Binary ? llvm::sys::fs::F_None : llvm::sys::fs::F_Text)));
  572. if (Error)
  573. return nullptr;
  574. }
  575. // Make sure the out stream file gets removed if we crash.
  576. if (RemoveFileOnSignal)
  577. llvm::sys::RemoveFileOnSignal(OSFile);
  578. if (ResultPathName)
  579. *ResultPathName = OutFile;
  580. if (TempPathName)
  581. *TempPathName = TempFile;
  582. return OS.release();
  583. }
  584. // Initialization Utilities
  585. bool CompilerInstance::InitializeSourceManager(const FrontendInputFile &Input){
  586. return InitializeSourceManager(Input, getDiagnostics(),
  587. getFileManager(), getSourceManager(),
  588. getFrontendOpts());
  589. }
  590. bool CompilerInstance::InitializeSourceManager(const FrontendInputFile &Input,
  591. DiagnosticsEngine &Diags,
  592. FileManager &FileMgr,
  593. SourceManager &SourceMgr,
  594. const FrontendOptions &Opts) {
  595. SrcMgr::CharacteristicKind
  596. Kind = Input.isSystem() ? SrcMgr::C_System : SrcMgr::C_User;
  597. if (Input.isBuffer()) {
  598. SourceMgr.setMainFileID(SourceMgr.createFileID(Input.getBuffer(), Kind));
  599. assert(!SourceMgr.getMainFileID().isInvalid() &&
  600. "Couldn't establish MainFileID!");
  601. return true;
  602. }
  603. StringRef InputFile = Input.getFile();
  604. // Figure out where to get and map in the main file.
  605. if (InputFile != "-") {
  606. const FileEntry *File = FileMgr.getFile(InputFile, /*OpenFile=*/true);
  607. if (!File) {
  608. Diags.Report(diag::err_fe_error_reading) << InputFile;
  609. return false;
  610. }
  611. // The natural SourceManager infrastructure can't currently handle named
  612. // pipes, but we would at least like to accept them for the main
  613. // file. Detect them here, read them with the volatile flag so FileMgr will
  614. // pick up the correct size, and simply override their contents as we do for
  615. // STDIN.
  616. if (File->isNamedPipe()) {
  617. std::string ErrorStr;
  618. if (std::unique_ptr<llvm::MemoryBuffer> MB =
  619. FileMgr.getBufferForFile(File, &ErrorStr, /*isVolatile=*/true)) {
  620. // Create a new virtual file that will have the correct size.
  621. File = FileMgr.getVirtualFile(InputFile, MB->getBufferSize(), 0);
  622. SourceMgr.overrideFileContents(File, MB.release());
  623. } else {
  624. Diags.Report(diag::err_cannot_open_file) << InputFile << ErrorStr;
  625. return false;
  626. }
  627. }
  628. SourceMgr.setMainFileID(
  629. SourceMgr.createFileID(File, SourceLocation(), Kind));
  630. } else {
  631. llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> SBOrErr =
  632. llvm::MemoryBuffer::getSTDIN();
  633. if (std::error_code EC = SBOrErr.getError()) {
  634. Diags.Report(diag::err_fe_error_reading_stdin) << EC.message();
  635. return false;
  636. }
  637. std::unique_ptr<llvm::MemoryBuffer> SB = std::move(SBOrErr.get());
  638. const FileEntry *File = FileMgr.getVirtualFile(SB->getBufferIdentifier(),
  639. SB->getBufferSize(), 0);
  640. SourceMgr.setMainFileID(
  641. SourceMgr.createFileID(File, SourceLocation(), Kind));
  642. SourceMgr.overrideFileContents(File, SB.release());
  643. }
  644. assert(!SourceMgr.getMainFileID().isInvalid() &&
  645. "Couldn't establish MainFileID!");
  646. return true;
  647. }
  648. // High-Level Operations
  649. bool CompilerInstance::ExecuteAction(FrontendAction &Act) {
  650. assert(hasDiagnostics() && "Diagnostics engine is not initialized!");
  651. assert(!getFrontendOpts().ShowHelp && "Client must handle '-help'!");
  652. assert(!getFrontendOpts().ShowVersion && "Client must handle '-version'!");
  653. // FIXME: Take this as an argument, once all the APIs we used have moved to
  654. // taking it as an input instead of hard-coding llvm::errs.
  655. raw_ostream &OS = llvm::errs();
  656. // Create the target instance.
  657. setTarget(TargetInfo::CreateTargetInfo(getDiagnostics(),
  658. getInvocation().TargetOpts));
  659. if (!hasTarget())
  660. return false;
  661. // Inform the target of the language options.
  662. //
  663. // FIXME: We shouldn't need to do this, the target should be immutable once
  664. // created. This complexity should be lifted elsewhere.
  665. getTarget().adjust(getLangOpts());
  666. // rewriter project will change target built-in bool type from its default.
  667. if (getFrontendOpts().ProgramAction == frontend::RewriteObjC)
  668. getTarget().noSignedCharForObjCBool();
  669. // Validate/process some options.
  670. if (getHeaderSearchOpts().Verbose)
  671. OS << "clang -cc1 version " CLANG_VERSION_STRING
  672. << " based upon " << BACKEND_PACKAGE_STRING
  673. << " default target " << llvm::sys::getDefaultTargetTriple() << "\n";
  674. if (getFrontendOpts().ShowTimers)
  675. createFrontendTimer();
  676. if (getFrontendOpts().ShowStats)
  677. llvm::EnableStatistics();
  678. for (unsigned i = 0, e = getFrontendOpts().Inputs.size(); i != e; ++i) {
  679. // Reset the ID tables if we are reusing the SourceManager and parsing
  680. // regular files.
  681. if (hasSourceManager() && !Act.isModelParsingAction())
  682. getSourceManager().clearIDTables();
  683. if (Act.BeginSourceFile(*this, getFrontendOpts().Inputs[i])) {
  684. Act.Execute();
  685. Act.EndSourceFile();
  686. }
  687. }
  688. // Notify the diagnostic client that all files were processed.
  689. getDiagnostics().getClient()->finish();
  690. if (getDiagnosticOpts().ShowCarets) {
  691. // We can have multiple diagnostics sharing one diagnostic client.
  692. // Get the total number of warnings/errors from the client.
  693. unsigned NumWarnings = getDiagnostics().getClient()->getNumWarnings();
  694. unsigned NumErrors = getDiagnostics().getClient()->getNumErrors();
  695. if (NumWarnings)
  696. OS << NumWarnings << " warning" << (NumWarnings == 1 ? "" : "s");
  697. if (NumWarnings && NumErrors)
  698. OS << " and ";
  699. if (NumErrors)
  700. OS << NumErrors << " error" << (NumErrors == 1 ? "" : "s");
  701. if (NumWarnings || NumErrors)
  702. OS << " generated.\n";
  703. }
  704. if (getFrontendOpts().ShowStats && hasFileManager()) {
  705. getFileManager().PrintStats();
  706. OS << "\n";
  707. }
  708. return !getDiagnostics().getClient()->getNumErrors();
  709. }
  710. /// \brief Determine the appropriate source input kind based on language
  711. /// options.
  712. static InputKind getSourceInputKindFromOptions(const LangOptions &LangOpts) {
  713. if (LangOpts.OpenCL)
  714. return IK_OpenCL;
  715. if (LangOpts.CUDA)
  716. return IK_CUDA;
  717. if (LangOpts.ObjC1)
  718. return LangOpts.CPlusPlus? IK_ObjCXX : IK_ObjC;
  719. return LangOpts.CPlusPlus? IK_CXX : IK_C;
  720. }
  721. /// \brief Compile a module file for the given module, using the options
  722. /// provided by the importing compiler instance. Returns true if the module
  723. /// was built without errors.
  724. static bool compileModuleImpl(CompilerInstance &ImportingInstance,
  725. SourceLocation ImportLoc,
  726. Module *Module,
  727. StringRef ModuleFileName) {
  728. ModuleMap &ModMap
  729. = ImportingInstance.getPreprocessor().getHeaderSearchInfo().getModuleMap();
  730. // Construct a compiler invocation for creating this module.
  731. IntrusiveRefCntPtr<CompilerInvocation> Invocation
  732. (new CompilerInvocation(ImportingInstance.getInvocation()));
  733. PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
  734. // For any options that aren't intended to affect how a module is built,
  735. // reset them to their default values.
  736. Invocation->getLangOpts()->resetNonModularOptions();
  737. PPOpts.resetNonModularOptions();
  738. // Remove any macro definitions that are explicitly ignored by the module.
  739. // They aren't supposed to affect how the module is built anyway.
  740. const HeaderSearchOptions &HSOpts = Invocation->getHeaderSearchOpts();
  741. PPOpts.Macros.erase(
  742. std::remove_if(PPOpts.Macros.begin(), PPOpts.Macros.end(),
  743. [&HSOpts](const std::pair<std::string, bool> &def) {
  744. StringRef MacroDef = def.first;
  745. return HSOpts.ModulesIgnoreMacros.count(MacroDef.split('=').first) > 0;
  746. }),
  747. PPOpts.Macros.end());
  748. // Note the name of the module we're building.
  749. Invocation->getLangOpts()->CurrentModule = Module->getTopLevelModuleName();
  750. // Make sure that the failed-module structure has been allocated in
  751. // the importing instance, and propagate the pointer to the newly-created
  752. // instance.
  753. PreprocessorOptions &ImportingPPOpts
  754. = ImportingInstance.getInvocation().getPreprocessorOpts();
  755. if (!ImportingPPOpts.FailedModules)
  756. ImportingPPOpts.FailedModules = new PreprocessorOptions::FailedModulesSet;
  757. PPOpts.FailedModules = ImportingPPOpts.FailedModules;
  758. // If there is a module map file, build the module using the module map.
  759. // Set up the inputs/outputs so that we build the module from its umbrella
  760. // header.
  761. FrontendOptions &FrontendOpts = Invocation->getFrontendOpts();
  762. FrontendOpts.OutputFile = ModuleFileName.str();
  763. FrontendOpts.DisableFree = false;
  764. FrontendOpts.GenerateGlobalModuleIndex = false;
  765. FrontendOpts.Inputs.clear();
  766. InputKind IK = getSourceInputKindFromOptions(*Invocation->getLangOpts());
  767. // Don't free the remapped file buffers; they are owned by our caller.
  768. PPOpts.RetainRemappedFileBuffers = true;
  769. Invocation->getDiagnosticOpts().VerifyDiagnostics = 0;
  770. assert(ImportingInstance.getInvocation().getModuleHash() ==
  771. Invocation->getModuleHash() && "Module hash mismatch!");
  772. // Construct a compiler instance that will be used to actually create the
  773. // module.
  774. CompilerInstance Instance(/*BuildingModule=*/true);
  775. Instance.setInvocation(&*Invocation);
  776. Instance.createDiagnostics(new ForwardingDiagnosticConsumer(
  777. ImportingInstance.getDiagnosticClient()),
  778. /*ShouldOwnClient=*/true);
  779. Instance.setVirtualFileSystem(&ImportingInstance.getVirtualFileSystem());
  780. // Note that this module is part of the module build stack, so that we
  781. // can detect cycles in the module graph.
  782. Instance.setFileManager(&ImportingInstance.getFileManager());
  783. Instance.createSourceManager(Instance.getFileManager());
  784. SourceManager &SourceMgr = Instance.getSourceManager();
  785. SourceMgr.setModuleBuildStack(
  786. ImportingInstance.getSourceManager().getModuleBuildStack());
  787. SourceMgr.pushModuleBuildStack(Module->getTopLevelModuleName(),
  788. FullSourceLoc(ImportLoc, ImportingInstance.getSourceManager()));
  789. // If we're collecting module dependencies, we need to share a collector
  790. // between all of the module CompilerInstances.
  791. Instance.setModuleDepCollector(ImportingInstance.getModuleDepCollector());
  792. // Get or create the module map that we'll use to build this module.
  793. std::string InferredModuleMapContent;
  794. if (const FileEntry *ModuleMapFile =
  795. ModMap.getContainingModuleMapFile(Module)) {
  796. // Use the module map where this module resides.
  797. FrontendOpts.Inputs.push_back(
  798. FrontendInputFile(ModuleMapFile->getName(), IK));
  799. } else {
  800. llvm::raw_string_ostream OS(InferredModuleMapContent);
  801. Module->print(OS);
  802. OS.flush();
  803. FrontendOpts.Inputs.push_back(
  804. FrontendInputFile("__inferred_module.map", IK));
  805. std::unique_ptr<llvm::MemoryBuffer> ModuleMapBuffer =
  806. llvm::MemoryBuffer::getMemBuffer(InferredModuleMapContent);
  807. ModuleMapFile = Instance.getFileManager().getVirtualFile(
  808. "__inferred_module.map", InferredModuleMapContent.size(), 0);
  809. SourceMgr.overrideFileContents(ModuleMapFile, ModuleMapBuffer.release());
  810. }
  811. // Construct a module-generating action. Passing through the module map is
  812. // safe because the FileManager is shared between the compiler instances.
  813. GenerateModuleAction CreateModuleAction(
  814. ModMap.getModuleMapFileForUniquing(Module), Module->IsSystem);
  815. // Execute the action to actually build the module in-place. Use a separate
  816. // thread so that we get a stack large enough.
  817. const unsigned ThreadStackSize = 8 << 20;
  818. llvm::CrashRecoveryContext CRC;
  819. CRC.RunSafelyOnThread([&]() { Instance.ExecuteAction(CreateModuleAction); },
  820. ThreadStackSize);
  821. // Delete the temporary module map file.
  822. // FIXME: Even though we're executing under crash protection, it would still
  823. // be nice to do this with RemoveFileOnSignal when we can. However, that
  824. // doesn't make sense for all clients, so clean this up manually.
  825. Instance.clearOutputFiles(/*EraseFiles=*/true);
  826. // We've rebuilt a module. If we're allowed to generate or update the global
  827. // module index, record that fact in the importing compiler instance.
  828. if (ImportingInstance.getFrontendOpts().GenerateGlobalModuleIndex) {
  829. ImportingInstance.setBuildGlobalModuleIndex(true);
  830. }
  831. return !Instance.getDiagnostics().hasErrorOccurred();
  832. }
  833. static bool compileAndLoadModule(CompilerInstance &ImportingInstance,
  834. SourceLocation ImportLoc,
  835. SourceLocation ModuleNameLoc, Module *Module,
  836. StringRef ModuleFileName) {
  837. auto diagnoseBuildFailure = [&] {
  838. ImportingInstance.getDiagnostics().Report(ModuleNameLoc,
  839. diag::err_module_not_built)
  840. << Module->Name << SourceRange(ImportLoc, ModuleNameLoc);
  841. };
  842. // FIXME: have LockFileManager return an error_code so that we can
  843. // avoid the mkdir when the directory already exists.
  844. StringRef Dir = llvm::sys::path::parent_path(ModuleFileName);
  845. llvm::sys::fs::create_directories(Dir);
  846. while (1) {
  847. unsigned ModuleLoadCapabilities = ASTReader::ARR_Missing;
  848. llvm::LockFileManager Locked(ModuleFileName);
  849. switch (Locked) {
  850. case llvm::LockFileManager::LFS_Error:
  851. return false;
  852. case llvm::LockFileManager::LFS_Owned:
  853. // We're responsible for building the module ourselves.
  854. if (!compileModuleImpl(ImportingInstance, ModuleNameLoc, Module,
  855. ModuleFileName)) {
  856. diagnoseBuildFailure();
  857. return false;
  858. }
  859. break;
  860. case llvm::LockFileManager::LFS_Shared:
  861. // Someone else is responsible for building the module. Wait for them to
  862. // finish.
  863. if (Locked.waitForUnlock() == llvm::LockFileManager::Res_OwnerDied)
  864. continue; // try again to get the lock.
  865. ModuleLoadCapabilities |= ASTReader::ARR_OutOfDate;
  866. break;
  867. }
  868. // Try to read the module file, now that we've compiled it.
  869. ASTReader::ASTReadResult ReadResult =
  870. ImportingInstance.getModuleManager()->ReadAST(
  871. ModuleFileName, serialization::MK_Module, ImportLoc,
  872. ModuleLoadCapabilities);
  873. if (ReadResult == ASTReader::OutOfDate &&
  874. Locked == llvm::LockFileManager::LFS_Shared) {
  875. // The module may be out of date in the presence of file system races,
  876. // or if one of its imports depends on header search paths that are not
  877. // consistent with this ImportingInstance. Try again...
  878. continue;
  879. } else if (ReadResult == ASTReader::Missing) {
  880. diagnoseBuildFailure();
  881. }
  882. return ReadResult == ASTReader::Success;
  883. }
  884. }
  885. /// \brief Diagnose differences between the current definition of the given
  886. /// configuration macro and the definition provided on the command line.
  887. static void checkConfigMacro(Preprocessor &PP, StringRef ConfigMacro,
  888. Module *Mod, SourceLocation ImportLoc) {
  889. IdentifierInfo *Id = PP.getIdentifierInfo(ConfigMacro);
  890. SourceManager &SourceMgr = PP.getSourceManager();
  891. // If this identifier has never had a macro definition, then it could
  892. // not have changed.
  893. if (!Id->hadMacroDefinition())
  894. return;
  895. // If this identifier does not currently have a macro definition,
  896. // check whether it had one on the command line.
  897. if (!Id->hasMacroDefinition()) {
  898. MacroDirective::DefInfo LatestDef =
  899. PP.getMacroDirectiveHistory(Id)->getDefinition();
  900. for (MacroDirective::DefInfo Def = LatestDef; Def;
  901. Def = Def.getPreviousDefinition()) {
  902. FileID FID = SourceMgr.getFileID(Def.getLocation());
  903. if (FID.isInvalid())
  904. continue;
  905. // We only care about the predefines buffer.
  906. if (FID != PP.getPredefinesFileID())
  907. continue;
  908. // This macro was defined on the command line, then #undef'd later.
  909. // Complain.
  910. PP.Diag(ImportLoc, diag::warn_module_config_macro_undef)
  911. << true << ConfigMacro << Mod->getFullModuleName();
  912. if (LatestDef.isUndefined())
  913. PP.Diag(LatestDef.getUndefLocation(), diag::note_module_def_undef_here)
  914. << true;
  915. return;
  916. }
  917. // Okay: no definition in the predefines buffer.
  918. return;
  919. }
  920. // This identifier has a macro definition. Check whether we had a definition
  921. // on the command line.
  922. MacroDirective::DefInfo LatestDef =
  923. PP.getMacroDirectiveHistory(Id)->getDefinition();
  924. MacroDirective::DefInfo PredefinedDef;
  925. for (MacroDirective::DefInfo Def = LatestDef; Def;
  926. Def = Def.getPreviousDefinition()) {
  927. FileID FID = SourceMgr.getFileID(Def.getLocation());
  928. if (FID.isInvalid())
  929. continue;
  930. // We only care about the predefines buffer.
  931. if (FID != PP.getPredefinesFileID())
  932. continue;
  933. PredefinedDef = Def;
  934. break;
  935. }
  936. // If there was no definition for this macro in the predefines buffer,
  937. // complain.
  938. if (!PredefinedDef ||
  939. (!PredefinedDef.getLocation().isValid() &&
  940. PredefinedDef.getUndefLocation().isValid())) {
  941. PP.Diag(ImportLoc, diag::warn_module_config_macro_undef)
  942. << false << ConfigMacro << Mod->getFullModuleName();
  943. PP.Diag(LatestDef.getLocation(), diag::note_module_def_undef_here)
  944. << false;
  945. return;
  946. }
  947. // If the current macro definition is the same as the predefined macro
  948. // definition, it's okay.
  949. if (LatestDef.getMacroInfo() == PredefinedDef.getMacroInfo() ||
  950. LatestDef.getMacroInfo()->isIdenticalTo(*PredefinedDef.getMacroInfo(),PP,
  951. /*Syntactically=*/true))
  952. return;
  953. // The macro definitions differ.
  954. PP.Diag(ImportLoc, diag::warn_module_config_macro_undef)
  955. << false << ConfigMacro << Mod->getFullModuleName();
  956. PP.Diag(LatestDef.getLocation(), diag::note_module_def_undef_here)
  957. << false;
  958. }
  959. /// \brief Write a new timestamp file with the given path.
  960. static void writeTimestampFile(StringRef TimestampFile) {
  961. std::error_code EC;
  962. llvm::raw_fd_ostream Out(TimestampFile.str(), EC, llvm::sys::fs::F_None);
  963. }
  964. /// \brief Prune the module cache of modules that haven't been accessed in
  965. /// a long time.
  966. static void pruneModuleCache(const HeaderSearchOptions &HSOpts) {
  967. struct stat StatBuf;
  968. llvm::SmallString<128> TimestampFile;
  969. TimestampFile = HSOpts.ModuleCachePath;
  970. llvm::sys::path::append(TimestampFile, "modules.timestamp");
  971. // Try to stat() the timestamp file.
  972. if (::stat(TimestampFile.c_str(), &StatBuf)) {
  973. // If the timestamp file wasn't there, create one now.
  974. if (errno == ENOENT) {
  975. writeTimestampFile(TimestampFile);
  976. }
  977. return;
  978. }
  979. // Check whether the time stamp is older than our pruning interval.
  980. // If not, do nothing.
  981. time_t TimeStampModTime = StatBuf.st_mtime;
  982. time_t CurrentTime = time(nullptr);
  983. if (CurrentTime - TimeStampModTime <= time_t(HSOpts.ModuleCachePruneInterval))
  984. return;
  985. // Write a new timestamp file so that nobody else attempts to prune.
  986. // There is a benign race condition here, if two Clang instances happen to
  987. // notice at the same time that the timestamp is out-of-date.
  988. writeTimestampFile(TimestampFile);
  989. // Walk the entire module cache, looking for unused module files and module
  990. // indices.
  991. std::error_code EC;
  992. SmallString<128> ModuleCachePathNative;
  993. llvm::sys::path::native(HSOpts.ModuleCachePath, ModuleCachePathNative);
  994. for (llvm::sys::fs::directory_iterator
  995. Dir(ModuleCachePathNative.str(), EC), DirEnd;
  996. Dir != DirEnd && !EC; Dir.increment(EC)) {
  997. // If we don't have a directory, there's nothing to look into.
  998. if (!llvm::sys::fs::is_directory(Dir->path()))
  999. continue;
  1000. // Walk all of the files within this directory.
  1001. for (llvm::sys::fs::directory_iterator File(Dir->path(), EC), FileEnd;
  1002. File != FileEnd && !EC; File.increment(EC)) {
  1003. // We only care about module and global module index files.
  1004. StringRef Extension = llvm::sys::path::extension(File->path());
  1005. if (Extension != ".pcm" && Extension != ".timestamp" &&
  1006. llvm::sys::path::filename(File->path()) != "modules.idx")
  1007. continue;
  1008. // Look at this file. If we can't stat it, there's nothing interesting
  1009. // there.
  1010. if (::stat(File->path().c_str(), &StatBuf))
  1011. continue;
  1012. // If the file has been used recently enough, leave it there.
  1013. time_t FileAccessTime = StatBuf.st_atime;
  1014. if (CurrentTime - FileAccessTime <=
  1015. time_t(HSOpts.ModuleCachePruneAfter)) {
  1016. continue;
  1017. }
  1018. // Remove the file.
  1019. llvm::sys::fs::remove(File->path());
  1020. // Remove the timestamp file.
  1021. std::string TimpestampFilename = File->path() + ".timestamp";
  1022. llvm::sys::fs::remove(TimpestampFilename);
  1023. }
  1024. // If we removed all of the files in the directory, remove the directory
  1025. // itself.
  1026. if (llvm::sys::fs::directory_iterator(Dir->path(), EC) ==
  1027. llvm::sys::fs::directory_iterator() && !EC)
  1028. llvm::sys::fs::remove(Dir->path());
  1029. }
  1030. }
  1031. void CompilerInstance::createModuleManager() {
  1032. if (!ModuleManager) {
  1033. if (!hasASTContext())
  1034. createASTContext();
  1035. // If we're not recursively building a module, check whether we
  1036. // need to prune the module cache.
  1037. if (getSourceManager().getModuleBuildStack().empty() &&
  1038. getHeaderSearchOpts().ModuleCachePruneInterval > 0 &&
  1039. getHeaderSearchOpts().ModuleCachePruneAfter > 0) {
  1040. pruneModuleCache(getHeaderSearchOpts());
  1041. }
  1042. HeaderSearchOptions &HSOpts = getHeaderSearchOpts();
  1043. std::string Sysroot = HSOpts.Sysroot;
  1044. const PreprocessorOptions &PPOpts = getPreprocessorOpts();
  1045. ModuleManager = new ASTReader(getPreprocessor(), *Context,
  1046. Sysroot.empty() ? "" : Sysroot.c_str(),
  1047. PPOpts.DisablePCHValidation,
  1048. /*AllowASTWithCompilerErrors=*/false,
  1049. /*AllowConfigurationMismatch=*/false,
  1050. HSOpts.ModulesValidateSystemHeaders,
  1051. getFrontendOpts().UseGlobalModuleIndex);
  1052. if (hasASTConsumer()) {
  1053. ModuleManager->setDeserializationListener(
  1054. getASTConsumer().GetASTDeserializationListener());
  1055. getASTContext().setASTMutationListener(
  1056. getASTConsumer().GetASTMutationListener());
  1057. }
  1058. getASTContext().setExternalSource(ModuleManager);
  1059. if (hasSema())
  1060. ModuleManager->InitializeSema(getSema());
  1061. if (hasASTConsumer())
  1062. ModuleManager->StartTranslationUnit(&getASTConsumer());
  1063. }
  1064. }
  1065. ModuleLoadResult
  1066. CompilerInstance::loadModule(SourceLocation ImportLoc,
  1067. ModuleIdPath Path,
  1068. Module::NameVisibilityKind Visibility,
  1069. bool IsInclusionDirective) {
  1070. // Determine what file we're searching from.
  1071. StringRef ModuleName = Path[0].first->getName();
  1072. SourceLocation ModuleNameLoc = Path[0].second;
  1073. // If we've already handled this import, just return the cached result.
  1074. // This one-element cache is important to eliminate redundant diagnostics
  1075. // when both the preprocessor and parser see the same import declaration.
  1076. if (!ImportLoc.isInvalid() && LastModuleImportLoc == ImportLoc) {
  1077. // Make the named module visible.
  1078. if (LastModuleImportResult && ModuleName != getLangOpts().CurrentModule &&
  1079. ModuleName != getLangOpts().ImplementationOfModule)
  1080. ModuleManager->makeModuleVisible(LastModuleImportResult, Visibility,
  1081. ImportLoc, /*Complain=*/false);
  1082. return LastModuleImportResult;
  1083. }
  1084. clang::Module *Module = nullptr;
  1085. // If we don't already have information on this module, load the module now.
  1086. llvm::DenseMap<const IdentifierInfo *, clang::Module *>::iterator Known
  1087. = KnownModules.find(Path[0].first);
  1088. if (Known != KnownModules.end()) {
  1089. // Retrieve the cached top-level module.
  1090. Module = Known->second;
  1091. } else if (ModuleName == getLangOpts().CurrentModule ||
  1092. ModuleName == getLangOpts().ImplementationOfModule) {
  1093. // This is the module we're building.
  1094. Module = PP->getHeaderSearchInfo().lookupModule(ModuleName);
  1095. Known = KnownModules.insert(std::make_pair(Path[0].first, Module)).first;
  1096. } else {
  1097. // Search for a module with the given name.
  1098. Module = PP->getHeaderSearchInfo().lookupModule(ModuleName);
  1099. if (!Module) {
  1100. getDiagnostics().Report(ModuleNameLoc, diag::err_module_not_found)
  1101. << ModuleName
  1102. << SourceRange(ImportLoc, ModuleNameLoc);
  1103. ModuleBuildFailed = true;
  1104. return ModuleLoadResult();
  1105. }
  1106. std::string ModuleFileName =
  1107. PP->getHeaderSearchInfo().getModuleFileName(Module);
  1108. // If we don't already have an ASTReader, create one now.
  1109. if (!ModuleManager)
  1110. createModuleManager();
  1111. if (TheDependencyFileGenerator)
  1112. TheDependencyFileGenerator->AttachToASTReader(*ModuleManager);
  1113. if (ModuleDepCollector)
  1114. ModuleDepCollector->attachToASTReader(*ModuleManager);
  1115. for (auto &Listener : DependencyCollectors)
  1116. Listener->attachToASTReader(*ModuleManager);
  1117. // Try to load the module file.
  1118. unsigned ARRFlags = ASTReader::ARR_OutOfDate | ASTReader::ARR_Missing;
  1119. switch (ModuleManager->ReadAST(ModuleFileName, serialization::MK_Module,
  1120. ImportLoc, ARRFlags)) {
  1121. case ASTReader::Success:
  1122. break;
  1123. case ASTReader::OutOfDate:
  1124. case ASTReader::Missing: {
  1125. // The module file is missing or out-of-date. Build it.
  1126. assert(Module && "missing module file");
  1127. // Check whether there is a cycle in the module graph.
  1128. ModuleBuildStack ModPath = getSourceManager().getModuleBuildStack();
  1129. ModuleBuildStack::iterator Pos = ModPath.begin(), PosEnd = ModPath.end();
  1130. for (; Pos != PosEnd; ++Pos) {
  1131. if (Pos->first == ModuleName)
  1132. break;
  1133. }
  1134. if (Pos != PosEnd) {
  1135. SmallString<256> CyclePath;
  1136. for (; Pos != PosEnd; ++Pos) {
  1137. CyclePath += Pos->first;
  1138. CyclePath += " -> ";
  1139. }
  1140. CyclePath += ModuleName;
  1141. getDiagnostics().Report(ModuleNameLoc, diag::err_module_cycle)
  1142. << ModuleName << CyclePath;
  1143. return ModuleLoadResult();
  1144. }
  1145. getDiagnostics().Report(ImportLoc, diag::remark_module_build)
  1146. << ModuleName << ModuleFileName;
  1147. // Check whether we have already attempted to build this module (but
  1148. // failed).
  1149. if (getPreprocessorOpts().FailedModules &&
  1150. getPreprocessorOpts().FailedModules->hasAlreadyFailed(ModuleName)) {
  1151. getDiagnostics().Report(ModuleNameLoc, diag::err_module_not_built)
  1152. << ModuleName
  1153. << SourceRange(ImportLoc, ModuleNameLoc);
  1154. ModuleBuildFailed = true;
  1155. return ModuleLoadResult();
  1156. }
  1157. // Try to compile and then load the module.
  1158. if (!compileAndLoadModule(*this, ImportLoc, ModuleNameLoc, Module,
  1159. ModuleFileName)) {
  1160. if (getPreprocessorOpts().FailedModules)
  1161. getPreprocessorOpts().FailedModules->addFailed(ModuleName);
  1162. KnownModules[Path[0].first] = nullptr;
  1163. ModuleBuildFailed = true;
  1164. return ModuleLoadResult();
  1165. }
  1166. // Okay, we've rebuilt and now loaded the module.
  1167. break;
  1168. }
  1169. case ASTReader::VersionMismatch:
  1170. case ASTReader::ConfigurationMismatch:
  1171. case ASTReader::HadErrors:
  1172. ModuleLoader::HadFatalFailure = true;
  1173. // FIXME: The ASTReader will already have complained, but can we showhorn
  1174. // that diagnostic information into a more useful form?
  1175. KnownModules[Path[0].first] = nullptr;
  1176. return ModuleLoadResult();
  1177. case ASTReader::Failure:
  1178. ModuleLoader::HadFatalFailure = true;
  1179. // Already complained, but note now that we failed.
  1180. KnownModules[Path[0].first] = nullptr;
  1181. ModuleBuildFailed = true;
  1182. return ModuleLoadResult();
  1183. }
  1184. // Cache the result of this top-level module lookup for later.
  1185. Known = KnownModules.insert(std::make_pair(Path[0].first, Module)).first;
  1186. }
  1187. // If we never found the module, fail.
  1188. if (!Module)
  1189. return ModuleLoadResult();
  1190. // Verify that the rest of the module path actually corresponds to
  1191. // a submodule.
  1192. if (Path.size() > 1) {
  1193. for (unsigned I = 1, N = Path.size(); I != N; ++I) {
  1194. StringRef Name = Path[I].first->getName();
  1195. clang::Module *Sub = Module->findSubmodule(Name);
  1196. if (!Sub) {
  1197. // Attempt to perform typo correction to find a module name that works.
  1198. SmallVector<StringRef, 2> Best;
  1199. unsigned BestEditDistance = (std::numeric_limits<unsigned>::max)();
  1200. for (clang::Module::submodule_iterator J = Module->submodule_begin(),
  1201. JEnd = Module->submodule_end();
  1202. J != JEnd; ++J) {
  1203. unsigned ED = Name.edit_distance((*J)->Name,
  1204. /*AllowReplacements=*/true,
  1205. BestEditDistance);
  1206. if (ED <= BestEditDistance) {
  1207. if (ED < BestEditDistance) {
  1208. Best.clear();
  1209. BestEditDistance = ED;
  1210. }
  1211. Best.push_back((*J)->Name);
  1212. }
  1213. }
  1214. // If there was a clear winner, user it.
  1215. if (Best.size() == 1) {
  1216. getDiagnostics().Report(Path[I].second,
  1217. diag::err_no_submodule_suggest)
  1218. << Path[I].first << Module->getFullModuleName() << Best[0]
  1219. << SourceRange(Path[0].second, Path[I-1].second)
  1220. << FixItHint::CreateReplacement(SourceRange(Path[I].second),
  1221. Best[0]);
  1222. Sub = Module->findSubmodule(Best[0]);
  1223. }
  1224. }
  1225. if (!Sub) {
  1226. // No submodule by this name. Complain, and don't look for further
  1227. // submodules.
  1228. getDiagnostics().Report(Path[I].second, diag::err_no_submodule)
  1229. << Path[I].first << Module->getFullModuleName()
  1230. << SourceRange(Path[0].second, Path[I-1].second);
  1231. break;
  1232. }
  1233. Module = Sub;
  1234. }
  1235. }
  1236. // Don't make the module visible if we are in the implementation.
  1237. if (ModuleName == getLangOpts().ImplementationOfModule)
  1238. return ModuleLoadResult(Module, false);
  1239. // Make the named module visible, if it's not already part of the module
  1240. // we are parsing.
  1241. if (ModuleName != getLangOpts().CurrentModule) {
  1242. if (!Module->IsFromModuleFile) {
  1243. // We have an umbrella header or directory that doesn't actually include
  1244. // all of the headers within the directory it covers. Complain about
  1245. // this missing submodule and recover by forgetting that we ever saw
  1246. // this submodule.
  1247. // FIXME: Should we detect this at module load time? It seems fairly
  1248. // expensive (and rare).
  1249. getDiagnostics().Report(ImportLoc, diag::warn_missing_submodule)
  1250. << Module->getFullModuleName()
  1251. << SourceRange(Path.front().second, Path.back().second);
  1252. return ModuleLoadResult(nullptr, true);
  1253. }
  1254. // Check whether this module is available.
  1255. clang::Module::Requirement Requirement;
  1256. clang::Module::HeaderDirective MissingHeader;
  1257. if (!Module->isAvailable(getLangOpts(), getTarget(), Requirement,
  1258. MissingHeader)) {
  1259. if (MissingHeader.FileNameLoc.isValid()) {
  1260. getDiagnostics().Report(MissingHeader.FileNameLoc,
  1261. diag::err_module_header_missing)
  1262. << MissingHeader.IsUmbrella << MissingHeader.FileName;
  1263. } else {
  1264. getDiagnostics().Report(ImportLoc, diag::err_module_unavailable)
  1265. << Module->getFullModuleName()
  1266. << Requirement.second << Requirement.first
  1267. << SourceRange(Path.front().second, Path.back().second);
  1268. }
  1269. LastModuleImportLoc = ImportLoc;
  1270. LastModuleImportResult = ModuleLoadResult();
  1271. return ModuleLoadResult();
  1272. }
  1273. ModuleManager->makeModuleVisible(Module, Visibility, ImportLoc,
  1274. /*Complain=*/true);
  1275. }
  1276. // Check for any configuration macros that have changed.
  1277. clang::Module *TopModule = Module->getTopLevelModule();
  1278. for (unsigned I = 0, N = TopModule->ConfigMacros.size(); I != N; ++I) {
  1279. checkConfigMacro(getPreprocessor(), TopModule->ConfigMacros[I],
  1280. Module, ImportLoc);
  1281. }
  1282. // If this module import was due to an inclusion directive, create an
  1283. // implicit import declaration to capture it in the AST.
  1284. if (IsInclusionDirective && hasASTContext()) {
  1285. TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
  1286. ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
  1287. ImportLoc, Module,
  1288. Path.back().second);
  1289. TU->addDecl(ImportD);
  1290. if (Consumer)
  1291. Consumer->HandleImplicitImportDecl(ImportD);
  1292. }
  1293. LastModuleImportLoc = ImportLoc;
  1294. LastModuleImportResult = ModuleLoadResult(Module, false);
  1295. return LastModuleImportResult;
  1296. }
  1297. void CompilerInstance::makeModuleVisible(Module *Mod,
  1298. Module::NameVisibilityKind Visibility,
  1299. SourceLocation ImportLoc,
  1300. bool Complain){
  1301. ModuleManager->makeModuleVisible(Mod, Visibility, ImportLoc, Complain);
  1302. }
  1303. GlobalModuleIndex *CompilerInstance::loadGlobalModuleIndex(
  1304. SourceLocation TriggerLoc) {
  1305. if (!ModuleManager)
  1306. createModuleManager();
  1307. // Can't do anything if we don't have the module manager.
  1308. if (!ModuleManager)
  1309. return nullptr;
  1310. // Get an existing global index. This loads it if not already
  1311. // loaded.
  1312. ModuleManager->loadGlobalIndex();
  1313. GlobalModuleIndex *GlobalIndex = ModuleManager->getGlobalIndex();
  1314. // If the global index doesn't exist, create it.
  1315. if (!GlobalIndex && shouldBuildGlobalModuleIndex() && hasFileManager() &&
  1316. hasPreprocessor()) {
  1317. llvm::sys::fs::create_directories(
  1318. getPreprocessor().getHeaderSearchInfo().getModuleCachePath());
  1319. GlobalModuleIndex::writeIndex(
  1320. getFileManager(),
  1321. getPreprocessor().getHeaderSearchInfo().getModuleCachePath());
  1322. ModuleManager->resetForReload();
  1323. ModuleManager->loadGlobalIndex();
  1324. GlobalIndex = ModuleManager->getGlobalIndex();
  1325. }
  1326. // For finding modules needing to be imported for fixit messages,
  1327. // we need to make the global index cover all modules, so we do that here.
  1328. if (!HaveFullGlobalModuleIndex && GlobalIndex && !buildingModule()) {
  1329. ModuleMap &MMap = getPreprocessor().getHeaderSearchInfo().getModuleMap();
  1330. bool RecreateIndex = false;
  1331. for (ModuleMap::module_iterator I = MMap.module_begin(),
  1332. E = MMap.module_end(); I != E; ++I) {
  1333. Module *TheModule = I->second;
  1334. const FileEntry *Entry = TheModule->getASTFile();
  1335. if (!Entry) {
  1336. SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path;
  1337. Path.push_back(std::make_pair(
  1338. getPreprocessor().getIdentifierInfo(TheModule->Name), TriggerLoc));
  1339. std::reverse(Path.begin(), Path.end());
  1340. // Load a module as hidden. This also adds it to the global index.
  1341. loadModule(TheModule->DefinitionLoc, Path,
  1342. Module::Hidden, false);
  1343. RecreateIndex = true;
  1344. }
  1345. }
  1346. if (RecreateIndex) {
  1347. GlobalModuleIndex::writeIndex(
  1348. getFileManager(),
  1349. getPreprocessor().getHeaderSearchInfo().getModuleCachePath());
  1350. ModuleManager->resetForReload();
  1351. ModuleManager->loadGlobalIndex();
  1352. GlobalIndex = ModuleManager->getGlobalIndex();
  1353. }
  1354. HaveFullGlobalModuleIndex = true;
  1355. }
  1356. return GlobalIndex;
  1357. }
  1358. // Check global module index for missing imports.
  1359. bool
  1360. CompilerInstance::lookupMissingImports(StringRef Name,
  1361. SourceLocation TriggerLoc) {
  1362. // Look for the symbol in non-imported modules, but only if an error
  1363. // actually occurred.
  1364. if (!buildingModule()) {
  1365. // Load global module index, or retrieve a previously loaded one.
  1366. GlobalModuleIndex *GlobalIndex = loadGlobalModuleIndex(
  1367. TriggerLoc);
  1368. // Only if we have a global index.
  1369. if (GlobalIndex) {
  1370. GlobalModuleIndex::HitSet FoundModules;
  1371. // Find the modules that reference the identifier.
  1372. // Note that this only finds top-level modules.
  1373. // We'll let diagnoseTypo find the actual declaration module.
  1374. if (GlobalIndex->lookupIdentifier(Name, FoundModules))
  1375. return true;
  1376. }
  1377. }
  1378. return false;
  1379. }