CompilerInstance.cpp 65 KB

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