CompilerInstance.cpp 60 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615
  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::string ErrorInfo;
  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.c_str(), ErrorInfo,
  124. llvm::sys::fs::F_Append | llvm::sys::fs::F_Text));
  125. if (!ErrorInfo.empty()) {
  126. Diags.Report(diag::warn_fe_cc_log_diagnostics_failure)
  127. << DiagOpts->DiagnosticLogFile << ErrorInfo;
  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::string ErrorInfo;
  146. std::unique_ptr<llvm::raw_fd_ostream> OS;
  147. OS.reset(new llvm::raw_fd_ostream(OutputFile.str().c_str(), ErrorInfo,
  148. llvm::sys::fs::F_None));
  149. if (!ErrorInfo.empty()) {
  150. Diags.Report(diag::warn_fe_serialized_diag_failure)
  151. << OutputFile << ErrorInfo;
  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 Error, OutputPathName, TempPathName;
  490. llvm::raw_fd_ostream *OS = createOutputFile(OutputPath, Error, Binary,
  491. RemoveFileOnSignal,
  492. InFile, Extension,
  493. UseTemporary,
  494. CreateMissingDirectories,
  495. &OutputPathName,
  496. &TempPathName);
  497. if (!OS) {
  498. getDiagnostics().Report(diag::err_fe_unable_to_open_output)
  499. << OutputPath << Error;
  500. return nullptr;
  501. }
  502. // Add the output file -- but don't try to remove "-", since this means we are
  503. // using stdin.
  504. addOutputFile(OutputFile((OutputPathName != "-") ? OutputPathName : "",
  505. TempPathName, OS));
  506. return OS;
  507. }
  508. llvm::raw_fd_ostream *
  509. CompilerInstance::createOutputFile(StringRef OutputPath,
  510. std::string &Error,
  511. bool Binary,
  512. bool RemoveFileOnSignal,
  513. StringRef InFile,
  514. StringRef Extension,
  515. bool UseTemporary,
  516. bool CreateMissingDirectories,
  517. std::string *ResultPathName,
  518. std::string *TempPathName) {
  519. assert((!CreateMissingDirectories || UseTemporary) &&
  520. "CreateMissingDirectories is only allowed when using temporary files");
  521. std::string OutFile, TempFile;
  522. if (!OutputPath.empty()) {
  523. OutFile = OutputPath;
  524. } else if (InFile == "-") {
  525. OutFile = "-";
  526. } else if (!Extension.empty()) {
  527. SmallString<128> Path(InFile);
  528. llvm::sys::path::replace_extension(Path, Extension);
  529. OutFile = Path.str();
  530. } else {
  531. OutFile = "-";
  532. }
  533. std::unique_ptr<llvm::raw_fd_ostream> OS;
  534. std::string OSFile;
  535. if (UseTemporary) {
  536. if (OutFile == "-")
  537. UseTemporary = false;
  538. else {
  539. llvm::sys::fs::file_status Status;
  540. llvm::sys::fs::status(OutputPath, Status);
  541. if (llvm::sys::fs::exists(Status)) {
  542. // Fail early if we can't write to the final destination.
  543. if (!llvm::sys::fs::can_write(OutputPath))
  544. return nullptr;
  545. // Don't use a temporary if the output is a special file. This handles
  546. // things like '-o /dev/null'
  547. if (!llvm::sys::fs::is_regular_file(Status))
  548. UseTemporary = false;
  549. }
  550. }
  551. }
  552. if (UseTemporary) {
  553. // Create a temporary file.
  554. SmallString<128> TempPath;
  555. TempPath = OutFile;
  556. TempPath += "-%%%%%%%%";
  557. int fd;
  558. std::error_code EC =
  559. llvm::sys::fs::createUniqueFile(TempPath.str(), fd, TempPath);
  560. if (CreateMissingDirectories &&
  561. EC == llvm::errc::no_such_file_or_directory) {
  562. StringRef Parent = llvm::sys::path::parent_path(OutputPath);
  563. EC = llvm::sys::fs::create_directories(Parent);
  564. if (!EC) {
  565. EC = llvm::sys::fs::createUniqueFile(TempPath.str(), fd, TempPath);
  566. }
  567. }
  568. if (!EC) {
  569. OS.reset(new llvm::raw_fd_ostream(fd, /*shouldClose=*/true));
  570. OSFile = TempFile = TempPath.str();
  571. }
  572. // If we failed to create the temporary, fallback to writing to the file
  573. // directly. This handles the corner case where we cannot write to the
  574. // directory, but can write to the file.
  575. }
  576. if (!OS) {
  577. OSFile = OutFile;
  578. OS.reset(new llvm::raw_fd_ostream(
  579. OSFile.c_str(), Error,
  580. (Binary ? llvm::sys::fs::F_None : llvm::sys::fs::F_Text)));
  581. if (!Error.empty())
  582. return nullptr;
  583. }
  584. // Make sure the out stream file gets removed if we crash.
  585. if (RemoveFileOnSignal)
  586. llvm::sys::RemoveFileOnSignal(OSFile);
  587. if (ResultPathName)
  588. *ResultPathName = OutFile;
  589. if (TempPathName)
  590. *TempPathName = TempFile;
  591. return OS.release();
  592. }
  593. // Initialization Utilities
  594. bool CompilerInstance::InitializeSourceManager(const FrontendInputFile &Input){
  595. return InitializeSourceManager(Input, getDiagnostics(),
  596. getFileManager(), getSourceManager(),
  597. getFrontendOpts());
  598. }
  599. bool CompilerInstance::InitializeSourceManager(const FrontendInputFile &Input,
  600. DiagnosticsEngine &Diags,
  601. FileManager &FileMgr,
  602. SourceManager &SourceMgr,
  603. const FrontendOptions &Opts) {
  604. SrcMgr::CharacteristicKind
  605. Kind = Input.isSystem() ? SrcMgr::C_System : SrcMgr::C_User;
  606. if (Input.isBuffer()) {
  607. SourceMgr.setMainFileID(SourceMgr.createFileID(Input.getBuffer(), Kind));
  608. assert(!SourceMgr.getMainFileID().isInvalid() &&
  609. "Couldn't establish MainFileID!");
  610. return true;
  611. }
  612. StringRef InputFile = Input.getFile();
  613. // Figure out where to get and map in the main file.
  614. if (InputFile != "-") {
  615. const FileEntry *File = FileMgr.getFile(InputFile, /*OpenFile=*/true);
  616. if (!File) {
  617. Diags.Report(diag::err_fe_error_reading) << InputFile;
  618. return false;
  619. }
  620. // The natural SourceManager infrastructure can't currently handle named
  621. // pipes, but we would at least like to accept them for the main
  622. // file. Detect them here, read them with the volatile flag so FileMgr will
  623. // pick up the correct size, and simply override their contents as we do for
  624. // STDIN.
  625. if (File->isNamedPipe()) {
  626. std::string ErrorStr;
  627. if (llvm::MemoryBuffer *MB =
  628. FileMgr.getBufferForFile(File, &ErrorStr, /*isVolatile=*/true)) {
  629. // Create a new virtual file that will have the correct size.
  630. File = FileMgr.getVirtualFile(InputFile, MB->getBufferSize(), 0);
  631. SourceMgr.overrideFileContents(File, MB);
  632. } else {
  633. Diags.Report(diag::err_cannot_open_file) << InputFile << ErrorStr;
  634. return false;
  635. }
  636. }
  637. SourceMgr.setMainFileID(
  638. SourceMgr.createFileID(File, SourceLocation(), Kind));
  639. } else {
  640. llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> SBOrErr =
  641. llvm::MemoryBuffer::getSTDIN();
  642. if (std::error_code EC = SBOrErr.getError()) {
  643. Diags.Report(diag::err_fe_error_reading_stdin) << EC.message();
  644. return false;
  645. }
  646. std::unique_ptr<llvm::MemoryBuffer> SB = std::move(SBOrErr.get());
  647. const FileEntry *File = FileMgr.getVirtualFile(SB->getBufferIdentifier(),
  648. SB->getBufferSize(), 0);
  649. SourceMgr.setMainFileID(
  650. SourceMgr.createFileID(File, SourceLocation(), Kind));
  651. SourceMgr.overrideFileContents(File, SB.release());
  652. }
  653. assert(!SourceMgr.getMainFileID().isInvalid() &&
  654. "Couldn't establish MainFileID!");
  655. return true;
  656. }
  657. // High-Level Operations
  658. bool CompilerInstance::ExecuteAction(FrontendAction &Act) {
  659. assert(hasDiagnostics() && "Diagnostics engine is not initialized!");
  660. assert(!getFrontendOpts().ShowHelp && "Client must handle '-help'!");
  661. assert(!getFrontendOpts().ShowVersion && "Client must handle '-version'!");
  662. // FIXME: Take this as an argument, once all the APIs we used have moved to
  663. // taking it as an input instead of hard-coding llvm::errs.
  664. raw_ostream &OS = llvm::errs();
  665. // Create the target instance.
  666. setTarget(TargetInfo::CreateTargetInfo(getDiagnostics(),
  667. getInvocation().TargetOpts));
  668. if (!hasTarget())
  669. return false;
  670. // Inform the target of the language options.
  671. //
  672. // FIXME: We shouldn't need to do this, the target should be immutable once
  673. // created. This complexity should be lifted elsewhere.
  674. getTarget().adjust(getLangOpts());
  675. // rewriter project will change target built-in bool type from its default.
  676. if (getFrontendOpts().ProgramAction == frontend::RewriteObjC)
  677. getTarget().noSignedCharForObjCBool();
  678. // Validate/process some options.
  679. if (getHeaderSearchOpts().Verbose)
  680. OS << "clang -cc1 version " CLANG_VERSION_STRING
  681. << " based upon " << BACKEND_PACKAGE_STRING
  682. << " default target " << llvm::sys::getDefaultTargetTriple() << "\n";
  683. if (getFrontendOpts().ShowTimers)
  684. createFrontendTimer();
  685. if (getFrontendOpts().ShowStats)
  686. llvm::EnableStatistics();
  687. for (unsigned i = 0, e = getFrontendOpts().Inputs.size(); i != e; ++i) {
  688. // Reset the ID tables if we are reusing the SourceManager.
  689. if (hasSourceManager())
  690. getSourceManager().clearIDTables();
  691. if (Act.BeginSourceFile(*this, getFrontendOpts().Inputs[i])) {
  692. Act.Execute();
  693. Act.EndSourceFile();
  694. }
  695. }
  696. // Notify the diagnostic client that all files were processed.
  697. getDiagnostics().getClient()->finish();
  698. if (getDiagnosticOpts().ShowCarets) {
  699. // We can have multiple diagnostics sharing one diagnostic client.
  700. // Get the total number of warnings/errors from the client.
  701. unsigned NumWarnings = getDiagnostics().getClient()->getNumWarnings();
  702. unsigned NumErrors = getDiagnostics().getClient()->getNumErrors();
  703. if (NumWarnings)
  704. OS << NumWarnings << " warning" << (NumWarnings == 1 ? "" : "s");
  705. if (NumWarnings && NumErrors)
  706. OS << " and ";
  707. if (NumErrors)
  708. OS << NumErrors << " error" << (NumErrors == 1 ? "" : "s");
  709. if (NumWarnings || NumErrors)
  710. OS << " generated.\n";
  711. }
  712. if (getFrontendOpts().ShowStats && hasFileManager()) {
  713. getFileManager().PrintStats();
  714. OS << "\n";
  715. }
  716. return !getDiagnostics().getClient()->getNumErrors();
  717. }
  718. /// \brief Determine the appropriate source input kind based on language
  719. /// options.
  720. static InputKind getSourceInputKindFromOptions(const LangOptions &LangOpts) {
  721. if (LangOpts.OpenCL)
  722. return IK_OpenCL;
  723. if (LangOpts.CUDA)
  724. return IK_CUDA;
  725. if (LangOpts.ObjC1)
  726. return LangOpts.CPlusPlus? IK_ObjCXX : IK_ObjC;
  727. return LangOpts.CPlusPlus? IK_CXX : IK_C;
  728. }
  729. /// \brief Compile a module file for the given module, using the options
  730. /// provided by the importing compiler instance. Returns true if the module
  731. /// was built without errors.
  732. static bool compileModuleImpl(CompilerInstance &ImportingInstance,
  733. SourceLocation ImportLoc,
  734. Module *Module,
  735. StringRef ModuleFileName) {
  736. ModuleMap &ModMap
  737. = ImportingInstance.getPreprocessor().getHeaderSearchInfo().getModuleMap();
  738. // Construct a compiler invocation for creating this module.
  739. IntrusiveRefCntPtr<CompilerInvocation> Invocation
  740. (new CompilerInvocation(ImportingInstance.getInvocation()));
  741. PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
  742. // For any options that aren't intended to affect how a module is built,
  743. // reset them to their default values.
  744. Invocation->getLangOpts()->resetNonModularOptions();
  745. PPOpts.resetNonModularOptions();
  746. // Remove any macro definitions that are explicitly ignored by the module.
  747. // They aren't supposed to affect how the module is built anyway.
  748. const HeaderSearchOptions &HSOpts = Invocation->getHeaderSearchOpts();
  749. PPOpts.Macros.erase(
  750. std::remove_if(PPOpts.Macros.begin(), PPOpts.Macros.end(),
  751. [&HSOpts](const std::pair<std::string, bool> &def) {
  752. StringRef MacroDef = def.first;
  753. return HSOpts.ModulesIgnoreMacros.count(MacroDef.split('=').first) > 0;
  754. }),
  755. PPOpts.Macros.end());
  756. // Note the name of the module we're building.
  757. Invocation->getLangOpts()->CurrentModule = Module->getTopLevelModuleName();
  758. // Make sure that the failed-module structure has been allocated in
  759. // the importing instance, and propagate the pointer to the newly-created
  760. // instance.
  761. PreprocessorOptions &ImportingPPOpts
  762. = ImportingInstance.getInvocation().getPreprocessorOpts();
  763. if (!ImportingPPOpts.FailedModules)
  764. ImportingPPOpts.FailedModules = new PreprocessorOptions::FailedModulesSet;
  765. PPOpts.FailedModules = ImportingPPOpts.FailedModules;
  766. // If there is a module map file, build the module using the module map.
  767. // Set up the inputs/outputs so that we build the module from its umbrella
  768. // header.
  769. FrontendOptions &FrontendOpts = Invocation->getFrontendOpts();
  770. FrontendOpts.OutputFile = ModuleFileName.str();
  771. FrontendOpts.DisableFree = false;
  772. FrontendOpts.GenerateGlobalModuleIndex = false;
  773. FrontendOpts.Inputs.clear();
  774. InputKind IK = getSourceInputKindFromOptions(*Invocation->getLangOpts());
  775. // Don't free the remapped file buffers; they are owned by our caller.
  776. PPOpts.RetainRemappedFileBuffers = true;
  777. Invocation->getDiagnosticOpts().VerifyDiagnostics = 0;
  778. assert(ImportingInstance.getInvocation().getModuleHash() ==
  779. Invocation->getModuleHash() && "Module hash mismatch!");
  780. // Construct a compiler instance that will be used to actually create the
  781. // module.
  782. CompilerInstance Instance(/*BuildingModule=*/true);
  783. Instance.setInvocation(&*Invocation);
  784. Instance.createDiagnostics(new ForwardingDiagnosticConsumer(
  785. ImportingInstance.getDiagnosticClient()),
  786. /*ShouldOwnClient=*/true);
  787. Instance.setVirtualFileSystem(&ImportingInstance.getVirtualFileSystem());
  788. // Note that this module is part of the module build stack, so that we
  789. // can detect cycles in the module graph.
  790. Instance.setFileManager(&ImportingInstance.getFileManager());
  791. Instance.createSourceManager(Instance.getFileManager());
  792. SourceManager &SourceMgr = Instance.getSourceManager();
  793. SourceMgr.setModuleBuildStack(
  794. ImportingInstance.getSourceManager().getModuleBuildStack());
  795. SourceMgr.pushModuleBuildStack(Module->getTopLevelModuleName(),
  796. FullSourceLoc(ImportLoc, ImportingInstance.getSourceManager()));
  797. // If we're collecting module dependencies, we need to share a collector
  798. // between all of the module CompilerInstances.
  799. Instance.setModuleDepCollector(ImportingInstance.getModuleDepCollector());
  800. // Get or create the module map that we'll use to build this module.
  801. std::string InferredModuleMapContent;
  802. if (const FileEntry *ModuleMapFile =
  803. ModMap.getContainingModuleMapFile(Module)) {
  804. // Use the module map where this module resides.
  805. FrontendOpts.Inputs.push_back(
  806. FrontendInputFile(ModuleMapFile->getName(), IK));
  807. } else {
  808. llvm::raw_string_ostream OS(InferredModuleMapContent);
  809. Module->print(OS);
  810. OS.flush();
  811. FrontendOpts.Inputs.push_back(
  812. FrontendInputFile("__inferred_module.map", IK));
  813. llvm::MemoryBuffer *ModuleMapBuffer =
  814. llvm::MemoryBuffer::getMemBuffer(InferredModuleMapContent);
  815. ModuleMapFile = Instance.getFileManager().getVirtualFile(
  816. "__inferred_module.map", InferredModuleMapContent.size(), 0);
  817. SourceMgr.overrideFileContents(ModuleMapFile, ModuleMapBuffer);
  818. }
  819. // Construct a module-generating action. Passing through the module map is
  820. // safe because the FileManager is shared between the compiler instances.
  821. GenerateModuleAction CreateModuleAction(
  822. ModMap.getModuleMapFileForUniquing(Module), Module->IsSystem);
  823. // Execute the action to actually build the module in-place. Use a separate
  824. // thread so that we get a stack large enough.
  825. const unsigned ThreadStackSize = 8 << 20;
  826. llvm::CrashRecoveryContext CRC;
  827. CRC.RunSafelyOnThread([&]() { Instance.ExecuteAction(CreateModuleAction); },
  828. ThreadStackSize);
  829. // Delete the temporary module map file.
  830. // FIXME: Even though we're executing under crash protection, it would still
  831. // be nice to do this with RemoveFileOnSignal when we can. However, that
  832. // doesn't make sense for all clients, so clean this up manually.
  833. Instance.clearOutputFiles(/*EraseFiles=*/true);
  834. // We've rebuilt a module. If we're allowed to generate or update the global
  835. // module index, record that fact in the importing compiler instance.
  836. if (ImportingInstance.getFrontendOpts().GenerateGlobalModuleIndex) {
  837. ImportingInstance.setBuildGlobalModuleIndex(true);
  838. }
  839. return !Instance.getDiagnostics().hasErrorOccurred();
  840. }
  841. static bool compileAndLoadModule(CompilerInstance &ImportingInstance,
  842. SourceLocation ImportLoc,
  843. SourceLocation ModuleNameLoc, Module *Module,
  844. StringRef ModuleFileName) {
  845. auto diagnoseBuildFailure = [&] {
  846. ImportingInstance.getDiagnostics().Report(ModuleNameLoc,
  847. diag::err_module_not_built)
  848. << Module->Name << SourceRange(ImportLoc, ModuleNameLoc);
  849. };
  850. // FIXME: have LockFileManager return an error_code so that we can
  851. // avoid the mkdir when the directory already exists.
  852. StringRef Dir = llvm::sys::path::parent_path(ModuleFileName);
  853. llvm::sys::fs::create_directories(Dir);
  854. while (1) {
  855. unsigned ModuleLoadCapabilities = ASTReader::ARR_Missing;
  856. llvm::LockFileManager Locked(ModuleFileName);
  857. switch (Locked) {
  858. case llvm::LockFileManager::LFS_Error:
  859. return false;
  860. case llvm::LockFileManager::LFS_Owned:
  861. // We're responsible for building the module ourselves.
  862. if (!compileModuleImpl(ImportingInstance, ModuleNameLoc, Module,
  863. ModuleFileName)) {
  864. diagnoseBuildFailure();
  865. return false;
  866. }
  867. break;
  868. case llvm::LockFileManager::LFS_Shared:
  869. // Someone else is responsible for building the module. Wait for them to
  870. // finish.
  871. if (Locked.waitForUnlock() == llvm::LockFileManager::Res_OwnerDied)
  872. continue; // try again to get the lock.
  873. ModuleLoadCapabilities |= ASTReader::ARR_OutOfDate;
  874. break;
  875. }
  876. // Try to read the module file, now that we've compiled it.
  877. ASTReader::ASTReadResult ReadResult =
  878. ImportingInstance.getModuleManager()->ReadAST(
  879. ModuleFileName, serialization::MK_Module, ImportLoc,
  880. ModuleLoadCapabilities);
  881. if (ReadResult == ASTReader::OutOfDate &&
  882. Locked == llvm::LockFileManager::LFS_Shared) {
  883. // The module may be out of date in the presence of file system races,
  884. // or if one of its imports depends on header search paths that are not
  885. // consistent with this ImportingInstance. Try again...
  886. continue;
  887. } else if (ReadResult == ASTReader::Missing) {
  888. diagnoseBuildFailure();
  889. }
  890. return ReadResult == ASTReader::Success;
  891. }
  892. }
  893. /// \brief Diagnose differences between the current definition of the given
  894. /// configuration macro and the definition provided on the command line.
  895. static void checkConfigMacro(Preprocessor &PP, StringRef ConfigMacro,
  896. Module *Mod, SourceLocation ImportLoc) {
  897. IdentifierInfo *Id = PP.getIdentifierInfo(ConfigMacro);
  898. SourceManager &SourceMgr = PP.getSourceManager();
  899. // If this identifier has never had a macro definition, then it could
  900. // not have changed.
  901. if (!Id->hadMacroDefinition())
  902. return;
  903. // If this identifier does not currently have a macro definition,
  904. // check whether it had one on the command line.
  905. if (!Id->hasMacroDefinition()) {
  906. MacroDirective::DefInfo LatestDef =
  907. PP.getMacroDirectiveHistory(Id)->getDefinition();
  908. for (MacroDirective::DefInfo Def = LatestDef; Def;
  909. Def = Def.getPreviousDefinition()) {
  910. FileID FID = SourceMgr.getFileID(Def.getLocation());
  911. if (FID.isInvalid())
  912. continue;
  913. // We only care about the predefines buffer.
  914. if (FID != PP.getPredefinesFileID())
  915. continue;
  916. // This macro was defined on the command line, then #undef'd later.
  917. // Complain.
  918. PP.Diag(ImportLoc, diag::warn_module_config_macro_undef)
  919. << true << ConfigMacro << Mod->getFullModuleName();
  920. if (LatestDef.isUndefined())
  921. PP.Diag(LatestDef.getUndefLocation(), diag::note_module_def_undef_here)
  922. << true;
  923. return;
  924. }
  925. // Okay: no definition in the predefines buffer.
  926. return;
  927. }
  928. // This identifier has a macro definition. Check whether we had a definition
  929. // on the command line.
  930. MacroDirective::DefInfo LatestDef =
  931. PP.getMacroDirectiveHistory(Id)->getDefinition();
  932. MacroDirective::DefInfo PredefinedDef;
  933. for (MacroDirective::DefInfo Def = LatestDef; Def;
  934. Def = Def.getPreviousDefinition()) {
  935. FileID FID = SourceMgr.getFileID(Def.getLocation());
  936. if (FID.isInvalid())
  937. continue;
  938. // We only care about the predefines buffer.
  939. if (FID != PP.getPredefinesFileID())
  940. continue;
  941. PredefinedDef = Def;
  942. break;
  943. }
  944. // If there was no definition for this macro in the predefines buffer,
  945. // complain.
  946. if (!PredefinedDef ||
  947. (!PredefinedDef.getLocation().isValid() &&
  948. PredefinedDef.getUndefLocation().isValid())) {
  949. PP.Diag(ImportLoc, diag::warn_module_config_macro_undef)
  950. << false << ConfigMacro << Mod->getFullModuleName();
  951. PP.Diag(LatestDef.getLocation(), diag::note_module_def_undef_here)
  952. << false;
  953. return;
  954. }
  955. // If the current macro definition is the same as the predefined macro
  956. // definition, it's okay.
  957. if (LatestDef.getMacroInfo() == PredefinedDef.getMacroInfo() ||
  958. LatestDef.getMacroInfo()->isIdenticalTo(*PredefinedDef.getMacroInfo(),PP,
  959. /*Syntactically=*/true))
  960. return;
  961. // The macro definitions differ.
  962. PP.Diag(ImportLoc, diag::warn_module_config_macro_undef)
  963. << false << ConfigMacro << Mod->getFullModuleName();
  964. PP.Diag(LatestDef.getLocation(), diag::note_module_def_undef_here)
  965. << false;
  966. }
  967. /// \brief Write a new timestamp file with the given path.
  968. static void writeTimestampFile(StringRef TimestampFile) {
  969. std::string ErrorInfo;
  970. llvm::raw_fd_ostream Out(TimestampFile.str().c_str(), ErrorInfo,
  971. llvm::sys::fs::F_None);
  972. }
  973. /// \brief Prune the module cache of modules that haven't been accessed in
  974. /// a long time.
  975. static void pruneModuleCache(const HeaderSearchOptions &HSOpts) {
  976. struct stat StatBuf;
  977. llvm::SmallString<128> TimestampFile;
  978. TimestampFile = HSOpts.ModuleCachePath;
  979. llvm::sys::path::append(TimestampFile, "modules.timestamp");
  980. // Try to stat() the timestamp file.
  981. if (::stat(TimestampFile.c_str(), &StatBuf)) {
  982. // If the timestamp file wasn't there, create one now.
  983. if (errno == ENOENT) {
  984. writeTimestampFile(TimestampFile);
  985. }
  986. return;
  987. }
  988. // Check whether the time stamp is older than our pruning interval.
  989. // If not, do nothing.
  990. time_t TimeStampModTime = StatBuf.st_mtime;
  991. time_t CurrentTime = time(nullptr);
  992. if (CurrentTime - TimeStampModTime <= time_t(HSOpts.ModuleCachePruneInterval))
  993. return;
  994. // Write a new timestamp file so that nobody else attempts to prune.
  995. // There is a benign race condition here, if two Clang instances happen to
  996. // notice at the same time that the timestamp is out-of-date.
  997. writeTimestampFile(TimestampFile);
  998. // Walk the entire module cache, looking for unused module files and module
  999. // indices.
  1000. std::error_code EC;
  1001. SmallString<128> ModuleCachePathNative;
  1002. llvm::sys::path::native(HSOpts.ModuleCachePath, ModuleCachePathNative);
  1003. for (llvm::sys::fs::directory_iterator
  1004. Dir(ModuleCachePathNative.str(), EC), DirEnd;
  1005. Dir != DirEnd && !EC; Dir.increment(EC)) {
  1006. // If we don't have a directory, there's nothing to look into.
  1007. if (!llvm::sys::fs::is_directory(Dir->path()))
  1008. continue;
  1009. // Walk all of the files within this directory.
  1010. for (llvm::sys::fs::directory_iterator File(Dir->path(), EC), FileEnd;
  1011. File != FileEnd && !EC; File.increment(EC)) {
  1012. // We only care about module and global module index files.
  1013. StringRef Extension = llvm::sys::path::extension(File->path());
  1014. if (Extension != ".pcm" && Extension != ".timestamp" &&
  1015. llvm::sys::path::filename(File->path()) != "modules.idx")
  1016. continue;
  1017. // Look at this file. If we can't stat it, there's nothing interesting
  1018. // there.
  1019. if (::stat(File->path().c_str(), &StatBuf))
  1020. continue;
  1021. // If the file has been used recently enough, leave it there.
  1022. time_t FileAccessTime = StatBuf.st_atime;
  1023. if (CurrentTime - FileAccessTime <=
  1024. time_t(HSOpts.ModuleCachePruneAfter)) {
  1025. continue;
  1026. }
  1027. // Remove the file.
  1028. llvm::sys::fs::remove(File->path());
  1029. // Remove the timestamp file.
  1030. std::string TimpestampFilename = File->path() + ".timestamp";
  1031. llvm::sys::fs::remove(TimpestampFilename);
  1032. }
  1033. // If we removed all of the files in the directory, remove the directory
  1034. // itself.
  1035. if (llvm::sys::fs::directory_iterator(Dir->path(), EC) ==
  1036. llvm::sys::fs::directory_iterator() && !EC)
  1037. llvm::sys::fs::remove(Dir->path());
  1038. }
  1039. }
  1040. void CompilerInstance::createModuleManager() {
  1041. if (!ModuleManager) {
  1042. if (!hasASTContext())
  1043. createASTContext();
  1044. // If we're not recursively building a module, check whether we
  1045. // need to prune the module cache.
  1046. if (getSourceManager().getModuleBuildStack().empty() &&
  1047. getHeaderSearchOpts().ModuleCachePruneInterval > 0 &&
  1048. getHeaderSearchOpts().ModuleCachePruneAfter > 0) {
  1049. pruneModuleCache(getHeaderSearchOpts());
  1050. }
  1051. HeaderSearchOptions &HSOpts = getHeaderSearchOpts();
  1052. std::string Sysroot = HSOpts.Sysroot;
  1053. const PreprocessorOptions &PPOpts = getPreprocessorOpts();
  1054. ModuleManager = new ASTReader(getPreprocessor(), *Context,
  1055. Sysroot.empty() ? "" : Sysroot.c_str(),
  1056. PPOpts.DisablePCHValidation,
  1057. /*AllowASTWithCompilerErrors=*/false,
  1058. /*AllowConfigurationMismatch=*/false,
  1059. HSOpts.ModulesValidateSystemHeaders,
  1060. getFrontendOpts().UseGlobalModuleIndex);
  1061. if (hasASTConsumer()) {
  1062. ModuleManager->setDeserializationListener(
  1063. getASTConsumer().GetASTDeserializationListener());
  1064. getASTContext().setASTMutationListener(
  1065. getASTConsumer().GetASTMutationListener());
  1066. }
  1067. getASTContext().setExternalSource(ModuleManager);
  1068. if (hasSema())
  1069. ModuleManager->InitializeSema(getSema());
  1070. if (hasASTConsumer())
  1071. ModuleManager->StartTranslationUnit(&getASTConsumer());
  1072. }
  1073. }
  1074. ModuleLoadResult
  1075. CompilerInstance::loadModule(SourceLocation ImportLoc,
  1076. ModuleIdPath Path,
  1077. Module::NameVisibilityKind Visibility,
  1078. bool IsInclusionDirective) {
  1079. // Determine what file we're searching from.
  1080. StringRef ModuleName = Path[0].first->getName();
  1081. SourceLocation ModuleNameLoc = Path[0].second;
  1082. // If we've already handled this import, just return the cached result.
  1083. // This one-element cache is important to eliminate redundant diagnostics
  1084. // when both the preprocessor and parser see the same import declaration.
  1085. if (!ImportLoc.isInvalid() && LastModuleImportLoc == ImportLoc) {
  1086. // Make the named module visible.
  1087. if (LastModuleImportResult && ModuleName != getLangOpts().CurrentModule &&
  1088. ModuleName != getLangOpts().ImplementationOfModule)
  1089. ModuleManager->makeModuleVisible(LastModuleImportResult, Visibility,
  1090. ImportLoc, /*Complain=*/false);
  1091. return LastModuleImportResult;
  1092. }
  1093. clang::Module *Module = nullptr;
  1094. // If we don't already have information on this module, load the module now.
  1095. llvm::DenseMap<const IdentifierInfo *, clang::Module *>::iterator Known
  1096. = KnownModules.find(Path[0].first);
  1097. if (Known != KnownModules.end()) {
  1098. // Retrieve the cached top-level module.
  1099. Module = Known->second;
  1100. } else if (ModuleName == getLangOpts().CurrentModule ||
  1101. ModuleName == getLangOpts().ImplementationOfModule) {
  1102. // This is the module we're building.
  1103. Module = PP->getHeaderSearchInfo().lookupModule(ModuleName);
  1104. Known = KnownModules.insert(std::make_pair(Path[0].first, Module)).first;
  1105. } else {
  1106. // Search for a module with the given name.
  1107. Module = PP->getHeaderSearchInfo().lookupModule(ModuleName);
  1108. if (!Module) {
  1109. getDiagnostics().Report(ModuleNameLoc, diag::err_module_not_found)
  1110. << ModuleName
  1111. << SourceRange(ImportLoc, ModuleNameLoc);
  1112. ModuleBuildFailed = true;
  1113. return ModuleLoadResult();
  1114. }
  1115. std::string ModuleFileName =
  1116. PP->getHeaderSearchInfo().getModuleFileName(Module);
  1117. // If we don't already have an ASTReader, create one now.
  1118. if (!ModuleManager)
  1119. createModuleManager();
  1120. if (TheDependencyFileGenerator)
  1121. TheDependencyFileGenerator->AttachToASTReader(*ModuleManager);
  1122. if (ModuleDepCollector)
  1123. ModuleDepCollector->attachToASTReader(*ModuleManager);
  1124. for (auto &Listener : DependencyCollectors)
  1125. Listener->attachToASTReader(*ModuleManager);
  1126. // Try to load the module file.
  1127. unsigned ARRFlags = ASTReader::ARR_OutOfDate | ASTReader::ARR_Missing;
  1128. switch (ModuleManager->ReadAST(ModuleFileName, serialization::MK_Module,
  1129. ImportLoc, ARRFlags)) {
  1130. case ASTReader::Success:
  1131. break;
  1132. case ASTReader::OutOfDate:
  1133. case ASTReader::Missing: {
  1134. // The module file is missing or out-of-date. Build it.
  1135. assert(Module && "missing module file");
  1136. // Check whether there is a cycle in the module graph.
  1137. ModuleBuildStack ModPath = getSourceManager().getModuleBuildStack();
  1138. ModuleBuildStack::iterator Pos = ModPath.begin(), PosEnd = ModPath.end();
  1139. for (; Pos != PosEnd; ++Pos) {
  1140. if (Pos->first == ModuleName)
  1141. break;
  1142. }
  1143. if (Pos != PosEnd) {
  1144. SmallString<256> CyclePath;
  1145. for (; Pos != PosEnd; ++Pos) {
  1146. CyclePath += Pos->first;
  1147. CyclePath += " -> ";
  1148. }
  1149. CyclePath += ModuleName;
  1150. getDiagnostics().Report(ModuleNameLoc, diag::err_module_cycle)
  1151. << ModuleName << CyclePath;
  1152. return ModuleLoadResult();
  1153. }
  1154. getDiagnostics().Report(ImportLoc, diag::remark_module_build)
  1155. << ModuleName << ModuleFileName;
  1156. // Check whether we have already attempted to build this module (but
  1157. // failed).
  1158. if (getPreprocessorOpts().FailedModules &&
  1159. getPreprocessorOpts().FailedModules->hasAlreadyFailed(ModuleName)) {
  1160. getDiagnostics().Report(ModuleNameLoc, diag::err_module_not_built)
  1161. << ModuleName
  1162. << SourceRange(ImportLoc, ModuleNameLoc);
  1163. ModuleBuildFailed = true;
  1164. return ModuleLoadResult();
  1165. }
  1166. // Try to compile and then load the module.
  1167. if (!compileAndLoadModule(*this, ImportLoc, ModuleNameLoc, Module,
  1168. ModuleFileName)) {
  1169. if (getPreprocessorOpts().FailedModules)
  1170. getPreprocessorOpts().FailedModules->addFailed(ModuleName);
  1171. KnownModules[Path[0].first] = nullptr;
  1172. ModuleBuildFailed = true;
  1173. return ModuleLoadResult();
  1174. }
  1175. // Okay, we've rebuilt and now loaded the module.
  1176. break;
  1177. }
  1178. case ASTReader::VersionMismatch:
  1179. case ASTReader::ConfigurationMismatch:
  1180. case ASTReader::HadErrors:
  1181. ModuleLoader::HadFatalFailure = true;
  1182. // FIXME: The ASTReader will already have complained, but can we showhorn
  1183. // that diagnostic information into a more useful form?
  1184. KnownModules[Path[0].first] = nullptr;
  1185. return ModuleLoadResult();
  1186. case ASTReader::Failure:
  1187. ModuleLoader::HadFatalFailure = true;
  1188. // Already complained, but note now that we failed.
  1189. KnownModules[Path[0].first] = nullptr;
  1190. ModuleBuildFailed = true;
  1191. return ModuleLoadResult();
  1192. }
  1193. // Cache the result of this top-level module lookup for later.
  1194. Known = KnownModules.insert(std::make_pair(Path[0].first, Module)).first;
  1195. }
  1196. // If we never found the module, fail.
  1197. if (!Module)
  1198. return ModuleLoadResult();
  1199. // Verify that the rest of the module path actually corresponds to
  1200. // a submodule.
  1201. if (Path.size() > 1) {
  1202. for (unsigned I = 1, N = Path.size(); I != N; ++I) {
  1203. StringRef Name = Path[I].first->getName();
  1204. clang::Module *Sub = Module->findSubmodule(Name);
  1205. if (!Sub) {
  1206. // Attempt to perform typo correction to find a module name that works.
  1207. SmallVector<StringRef, 2> Best;
  1208. unsigned BestEditDistance = (std::numeric_limits<unsigned>::max)();
  1209. for (clang::Module::submodule_iterator J = Module->submodule_begin(),
  1210. JEnd = Module->submodule_end();
  1211. J != JEnd; ++J) {
  1212. unsigned ED = Name.edit_distance((*J)->Name,
  1213. /*AllowReplacements=*/true,
  1214. BestEditDistance);
  1215. if (ED <= BestEditDistance) {
  1216. if (ED < BestEditDistance) {
  1217. Best.clear();
  1218. BestEditDistance = ED;
  1219. }
  1220. Best.push_back((*J)->Name);
  1221. }
  1222. }
  1223. // If there was a clear winner, user it.
  1224. if (Best.size() == 1) {
  1225. getDiagnostics().Report(Path[I].second,
  1226. diag::err_no_submodule_suggest)
  1227. << Path[I].first << Module->getFullModuleName() << Best[0]
  1228. << SourceRange(Path[0].second, Path[I-1].second)
  1229. << FixItHint::CreateReplacement(SourceRange(Path[I].second),
  1230. Best[0]);
  1231. Sub = Module->findSubmodule(Best[0]);
  1232. }
  1233. }
  1234. if (!Sub) {
  1235. // No submodule by this name. Complain, and don't look for further
  1236. // submodules.
  1237. getDiagnostics().Report(Path[I].second, diag::err_no_submodule)
  1238. << Path[I].first << Module->getFullModuleName()
  1239. << SourceRange(Path[0].second, Path[I-1].second);
  1240. break;
  1241. }
  1242. Module = Sub;
  1243. }
  1244. }
  1245. // Don't make the module visible if we are in the implementation.
  1246. if (ModuleName == getLangOpts().ImplementationOfModule)
  1247. return ModuleLoadResult(Module, false);
  1248. // Make the named module visible, if it's not already part of the module
  1249. // we are parsing.
  1250. if (ModuleName != getLangOpts().CurrentModule) {
  1251. if (!Module->IsFromModuleFile) {
  1252. // We have an umbrella header or directory that doesn't actually include
  1253. // all of the headers within the directory it covers. Complain about
  1254. // this missing submodule and recover by forgetting that we ever saw
  1255. // this submodule.
  1256. // FIXME: Should we detect this at module load time? It seems fairly
  1257. // expensive (and rare).
  1258. getDiagnostics().Report(ImportLoc, diag::warn_missing_submodule)
  1259. << Module->getFullModuleName()
  1260. << SourceRange(Path.front().second, Path.back().second);
  1261. return ModuleLoadResult(nullptr, true);
  1262. }
  1263. // Check whether this module is available.
  1264. clang::Module::Requirement Requirement;
  1265. clang::Module::HeaderDirective MissingHeader;
  1266. if (!Module->isAvailable(getLangOpts(), getTarget(), Requirement,
  1267. MissingHeader)) {
  1268. if (MissingHeader.FileNameLoc.isValid()) {
  1269. getDiagnostics().Report(MissingHeader.FileNameLoc,
  1270. diag::err_module_header_missing)
  1271. << MissingHeader.IsUmbrella << MissingHeader.FileName;
  1272. } else {
  1273. getDiagnostics().Report(ImportLoc, diag::err_module_unavailable)
  1274. << Module->getFullModuleName()
  1275. << Requirement.second << Requirement.first
  1276. << SourceRange(Path.front().second, Path.back().second);
  1277. }
  1278. LastModuleImportLoc = ImportLoc;
  1279. LastModuleImportResult = ModuleLoadResult();
  1280. return ModuleLoadResult();
  1281. }
  1282. ModuleManager->makeModuleVisible(Module, Visibility, ImportLoc,
  1283. /*Complain=*/true);
  1284. }
  1285. // Check for any configuration macros that have changed.
  1286. clang::Module *TopModule = Module->getTopLevelModule();
  1287. for (unsigned I = 0, N = TopModule->ConfigMacros.size(); I != N; ++I) {
  1288. checkConfigMacro(getPreprocessor(), TopModule->ConfigMacros[I],
  1289. Module, ImportLoc);
  1290. }
  1291. // If this module import was due to an inclusion directive, create an
  1292. // implicit import declaration to capture it in the AST.
  1293. if (IsInclusionDirective && hasASTContext()) {
  1294. TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
  1295. ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
  1296. ImportLoc, Module,
  1297. Path.back().second);
  1298. TU->addDecl(ImportD);
  1299. if (Consumer)
  1300. Consumer->HandleImplicitImportDecl(ImportD);
  1301. }
  1302. LastModuleImportLoc = ImportLoc;
  1303. LastModuleImportResult = ModuleLoadResult(Module, false);
  1304. return LastModuleImportResult;
  1305. }
  1306. void CompilerInstance::makeModuleVisible(Module *Mod,
  1307. Module::NameVisibilityKind Visibility,
  1308. SourceLocation ImportLoc,
  1309. bool Complain){
  1310. ModuleManager->makeModuleVisible(Mod, Visibility, ImportLoc, Complain);
  1311. }
  1312. GlobalModuleIndex *CompilerInstance::loadGlobalModuleIndex(
  1313. SourceLocation TriggerLoc) {
  1314. if (!ModuleManager)
  1315. createModuleManager();
  1316. // Can't do anything if we don't have the module manager.
  1317. if (!ModuleManager)
  1318. return nullptr;
  1319. // Get an existing global index. This loads it if not already
  1320. // loaded.
  1321. ModuleManager->loadGlobalIndex();
  1322. GlobalModuleIndex *GlobalIndex = ModuleManager->getGlobalIndex();
  1323. // If the global index doesn't exist, create it.
  1324. if (!GlobalIndex && shouldBuildGlobalModuleIndex() && hasFileManager() &&
  1325. hasPreprocessor()) {
  1326. llvm::sys::fs::create_directories(
  1327. getPreprocessor().getHeaderSearchInfo().getModuleCachePath());
  1328. GlobalModuleIndex::writeIndex(
  1329. getFileManager(),
  1330. getPreprocessor().getHeaderSearchInfo().getModuleCachePath());
  1331. ModuleManager->resetForReload();
  1332. ModuleManager->loadGlobalIndex();
  1333. GlobalIndex = ModuleManager->getGlobalIndex();
  1334. }
  1335. // For finding modules needing to be imported for fixit messages,
  1336. // we need to make the global index cover all modules, so we do that here.
  1337. if (!HaveFullGlobalModuleIndex && GlobalIndex && !buildingModule()) {
  1338. ModuleMap &MMap = getPreprocessor().getHeaderSearchInfo().getModuleMap();
  1339. bool RecreateIndex = false;
  1340. for (ModuleMap::module_iterator I = MMap.module_begin(),
  1341. E = MMap.module_end(); I != E; ++I) {
  1342. Module *TheModule = I->second;
  1343. const FileEntry *Entry = TheModule->getASTFile();
  1344. if (!Entry) {
  1345. SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path;
  1346. Path.push_back(std::make_pair(
  1347. getPreprocessor().getIdentifierInfo(TheModule->Name), TriggerLoc));
  1348. std::reverse(Path.begin(), Path.end());
  1349. // Load a module as hidden. This also adds it to the global index.
  1350. loadModule(TheModule->DefinitionLoc, Path,
  1351. Module::Hidden, false);
  1352. RecreateIndex = true;
  1353. }
  1354. }
  1355. if (RecreateIndex) {
  1356. GlobalModuleIndex::writeIndex(
  1357. getFileManager(),
  1358. getPreprocessor().getHeaderSearchInfo().getModuleCachePath());
  1359. ModuleManager->resetForReload();
  1360. ModuleManager->loadGlobalIndex();
  1361. GlobalIndex = ModuleManager->getGlobalIndex();
  1362. }
  1363. HaveFullGlobalModuleIndex = true;
  1364. }
  1365. return GlobalIndex;
  1366. }
  1367. // Check global module index for missing imports.
  1368. bool
  1369. CompilerInstance::lookupMissingImports(StringRef Name,
  1370. SourceLocation TriggerLoc) {
  1371. // Look for the symbol in non-imported modules, but only if an error
  1372. // actually occurred.
  1373. if (!buildingModule()) {
  1374. // Load global module index, or retrieve a previously loaded one.
  1375. GlobalModuleIndex *GlobalIndex = loadGlobalModuleIndex(
  1376. TriggerLoc);
  1377. // Only if we have a global index.
  1378. if (GlobalIndex) {
  1379. GlobalModuleIndex::HitSet FoundModules;
  1380. // Find the modules that reference the identifier.
  1381. // Note that this only finds top-level modules.
  1382. // We'll let diagnoseTypo find the actual declaration module.
  1383. if (GlobalIndex->lookupIdentifier(Name, FoundModules))
  1384. return true;
  1385. }
  1386. }
  1387. return false;
  1388. }