CompilerInstance.cpp 89 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296
  1. //===--- CompilerInstance.cpp ---------------------------------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. #include "clang/Frontend/CompilerInstance.h"
  9. #include "clang/AST/ASTConsumer.h"
  10. #include "clang/AST/ASTContext.h"
  11. #include "clang/AST/Decl.h"
  12. #include "clang/Basic/CharInfo.h"
  13. #include "clang/Basic/Diagnostic.h"
  14. #include "clang/Basic/DiagnosticOptions.h"
  15. #include "clang/Basic/FileManager.h"
  16. #include "clang/Basic/LangStandard.h"
  17. #include "clang/Basic/SourceManager.h"
  18. #include "clang/Basic/Stack.h"
  19. #include "clang/Basic/TargetInfo.h"
  20. #include "clang/Basic/Version.h"
  21. #include "clang/Config/config.h"
  22. #include "clang/Frontend/ChainedDiagnosticConsumer.h"
  23. #include "clang/Frontend/FrontendAction.h"
  24. #include "clang/Frontend/FrontendActions.h"
  25. #include "clang/Frontend/FrontendDiagnostic.h"
  26. #include "clang/Frontend/FrontendPluginRegistry.h"
  27. #include "clang/Frontend/LogDiagnosticPrinter.h"
  28. #include "clang/Frontend/SARIFDiagnosticPrinter.h"
  29. #include "clang/Frontend/SerializedDiagnosticPrinter.h"
  30. #include "clang/Frontend/TextDiagnosticPrinter.h"
  31. #include "clang/Frontend/Utils.h"
  32. #include "clang/Frontend/VerifyDiagnosticConsumer.h"
  33. #include "clang/Lex/HeaderSearch.h"
  34. #include "clang/Lex/Preprocessor.h"
  35. #include "clang/Lex/PreprocessorOptions.h"
  36. #include "clang/Sema/CodeCompleteConsumer.h"
  37. #include "clang/Sema/Sema.h"
  38. #include "clang/Serialization/ASTReader.h"
  39. #include "clang/Serialization/GlobalModuleIndex.h"
  40. #include "clang/Serialization/InMemoryModuleCache.h"
  41. #include "llvm/ADT/ScopeExit.h"
  42. #include "llvm/ADT/Statistic.h"
  43. #include "llvm/Config/llvm-config.h"
  44. #include "llvm/Support/BuryPointer.h"
  45. #include "llvm/Support/CrashRecoveryContext.h"
  46. #include "llvm/Support/Errc.h"
  47. #include "llvm/Support/FileSystem.h"
  48. #include "llvm/Support/Host.h"
  49. #include "llvm/Support/LockFileManager.h"
  50. #include "llvm/Support/MemoryBuffer.h"
  51. #include "llvm/Support/Path.h"
  52. #include "llvm/Support/Program.h"
  53. #include "llvm/Support/Signals.h"
  54. #include "llvm/Support/TimeProfiler.h"
  55. #include "llvm/Support/Timer.h"
  56. #include "llvm/Support/raw_ostream.h"
  57. #include <optional>
  58. #include <time.h>
  59. #include <utility>
  60. using namespace clang;
  61. CompilerInstance::CompilerInstance(
  62. std::shared_ptr<PCHContainerOperations> PCHContainerOps,
  63. InMemoryModuleCache *SharedModuleCache)
  64. : ModuleLoader(/* BuildingModule = */ SharedModuleCache),
  65. Invocation(new CompilerInvocation()),
  66. ModuleCache(SharedModuleCache ? SharedModuleCache
  67. : new InMemoryModuleCache),
  68. ThePCHContainerOperations(std::move(PCHContainerOps)) {}
  69. CompilerInstance::~CompilerInstance() {
  70. assert(OutputFiles.empty() && "Still output files in flight?");
  71. }
  72. void CompilerInstance::setInvocation(
  73. std::shared_ptr<CompilerInvocation> Value) {
  74. Invocation = std::move(Value);
  75. }
  76. bool CompilerInstance::shouldBuildGlobalModuleIndex() const {
  77. return (BuildGlobalModuleIndex ||
  78. (TheASTReader && TheASTReader->isGlobalIndexUnavailable() &&
  79. getFrontendOpts().GenerateGlobalModuleIndex)) &&
  80. !DisableGeneratingGlobalModuleIndex;
  81. }
  82. void CompilerInstance::setDiagnostics(DiagnosticsEngine *Value) {
  83. Diagnostics = Value;
  84. }
  85. void CompilerInstance::setVerboseOutputStream(raw_ostream &Value) {
  86. OwnedVerboseOutputStream.reset();
  87. VerboseOutputStream = &Value;
  88. }
  89. void CompilerInstance::setVerboseOutputStream(std::unique_ptr<raw_ostream> Value) {
  90. OwnedVerboseOutputStream.swap(Value);
  91. VerboseOutputStream = OwnedVerboseOutputStream.get();
  92. }
  93. void CompilerInstance::setTarget(TargetInfo *Value) { Target = Value; }
  94. void CompilerInstance::setAuxTarget(TargetInfo *Value) { AuxTarget = Value; }
  95. bool CompilerInstance::createTarget() {
  96. // Create the target instance.
  97. setTarget(TargetInfo::CreateTargetInfo(getDiagnostics(),
  98. getInvocation().TargetOpts));
  99. if (!hasTarget())
  100. return false;
  101. // Check whether AuxTarget exists, if not, then create TargetInfo for the
  102. // other side of CUDA/OpenMP/SYCL compilation.
  103. if (!getAuxTarget() &&
  104. (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice ||
  105. getLangOpts().SYCLIsDevice) &&
  106. !getFrontendOpts().AuxTriple.empty()) {
  107. auto TO = std::make_shared<TargetOptions>();
  108. TO->Triple = llvm::Triple::normalize(getFrontendOpts().AuxTriple);
  109. if (getFrontendOpts().AuxTargetCPU)
  110. TO->CPU = *getFrontendOpts().AuxTargetCPU;
  111. if (getFrontendOpts().AuxTargetFeatures)
  112. TO->FeaturesAsWritten = *getFrontendOpts().AuxTargetFeatures;
  113. TO->HostTriple = getTarget().getTriple().str();
  114. setAuxTarget(TargetInfo::CreateTargetInfo(getDiagnostics(), TO));
  115. }
  116. if (!getTarget().hasStrictFP() && !getLangOpts().ExpStrictFP) {
  117. if (getLangOpts().RoundingMath) {
  118. getDiagnostics().Report(diag::warn_fe_backend_unsupported_fp_rounding);
  119. getLangOpts().RoundingMath = false;
  120. }
  121. auto FPExc = getLangOpts().getFPExceptionMode();
  122. if (FPExc != LangOptions::FPE_Default && FPExc != LangOptions::FPE_Ignore) {
  123. getDiagnostics().Report(diag::warn_fe_backend_unsupported_fp_exceptions);
  124. getLangOpts().setFPExceptionMode(LangOptions::FPE_Ignore);
  125. }
  126. // FIXME: can we disable FEnvAccess?
  127. }
  128. // We should do it here because target knows nothing about
  129. // language options when it's being created.
  130. if (getLangOpts().OpenCL &&
  131. !getTarget().validateOpenCLTarget(getLangOpts(), getDiagnostics()))
  132. return false;
  133. // Inform the target of the language options.
  134. // FIXME: We shouldn't need to do this, the target should be immutable once
  135. // created. This complexity should be lifted elsewhere.
  136. getTarget().adjust(getDiagnostics(), getLangOpts());
  137. // Adjust target options based on codegen options.
  138. getTarget().adjustTargetOptions(getCodeGenOpts(), getTargetOpts());
  139. if (auto *Aux = getAuxTarget())
  140. getTarget().setAuxTarget(Aux);
  141. return true;
  142. }
  143. llvm::vfs::FileSystem &CompilerInstance::getVirtualFileSystem() const {
  144. return getFileManager().getVirtualFileSystem();
  145. }
  146. void CompilerInstance::setFileManager(FileManager *Value) {
  147. FileMgr = Value;
  148. }
  149. void CompilerInstance::setSourceManager(SourceManager *Value) {
  150. SourceMgr = Value;
  151. }
  152. void CompilerInstance::setPreprocessor(std::shared_ptr<Preprocessor> Value) {
  153. PP = std::move(Value);
  154. }
  155. void CompilerInstance::setASTContext(ASTContext *Value) {
  156. Context = Value;
  157. if (Context && Consumer)
  158. getASTConsumer().Initialize(getASTContext());
  159. }
  160. void CompilerInstance::setSema(Sema *S) {
  161. TheSema.reset(S);
  162. }
  163. void CompilerInstance::setASTConsumer(std::unique_ptr<ASTConsumer> Value) {
  164. Consumer = std::move(Value);
  165. if (Context && Consumer)
  166. getASTConsumer().Initialize(getASTContext());
  167. }
  168. void CompilerInstance::setCodeCompletionConsumer(CodeCompleteConsumer *Value) {
  169. CompletionConsumer.reset(Value);
  170. }
  171. std::unique_ptr<Sema> CompilerInstance::takeSema() {
  172. return std::move(TheSema);
  173. }
  174. IntrusiveRefCntPtr<ASTReader> CompilerInstance::getASTReader() const {
  175. return TheASTReader;
  176. }
  177. void CompilerInstance::setASTReader(IntrusiveRefCntPtr<ASTReader> Reader) {
  178. assert(ModuleCache.get() == &Reader->getModuleManager().getModuleCache() &&
  179. "Expected ASTReader to use the same PCM cache");
  180. TheASTReader = std::move(Reader);
  181. }
  182. std::shared_ptr<ModuleDependencyCollector>
  183. CompilerInstance::getModuleDepCollector() const {
  184. return ModuleDepCollector;
  185. }
  186. void CompilerInstance::setModuleDepCollector(
  187. std::shared_ptr<ModuleDependencyCollector> Collector) {
  188. ModuleDepCollector = std::move(Collector);
  189. }
  190. static void collectHeaderMaps(const HeaderSearch &HS,
  191. std::shared_ptr<ModuleDependencyCollector> MDC) {
  192. SmallVector<std::string, 4> HeaderMapFileNames;
  193. HS.getHeaderMapFileNames(HeaderMapFileNames);
  194. for (auto &Name : HeaderMapFileNames)
  195. MDC->addFile(Name);
  196. }
  197. static void collectIncludePCH(CompilerInstance &CI,
  198. std::shared_ptr<ModuleDependencyCollector> MDC) {
  199. const PreprocessorOptions &PPOpts = CI.getPreprocessorOpts();
  200. if (PPOpts.ImplicitPCHInclude.empty())
  201. return;
  202. StringRef PCHInclude = PPOpts.ImplicitPCHInclude;
  203. FileManager &FileMgr = CI.getFileManager();
  204. auto PCHDir = FileMgr.getOptionalDirectoryRef(PCHInclude);
  205. if (!PCHDir) {
  206. MDC->addFile(PCHInclude);
  207. return;
  208. }
  209. std::error_code EC;
  210. SmallString<128> DirNative;
  211. llvm::sys::path::native(PCHDir->getName(), DirNative);
  212. llvm::vfs::FileSystem &FS = FileMgr.getVirtualFileSystem();
  213. SimpleASTReaderListener Validator(CI.getPreprocessor());
  214. for (llvm::vfs::directory_iterator Dir = FS.dir_begin(DirNative, EC), DirEnd;
  215. Dir != DirEnd && !EC; Dir.increment(EC)) {
  216. // Check whether this is an AST file. ASTReader::isAcceptableASTFile is not
  217. // used here since we're not interested in validating the PCH at this time,
  218. // but only to check whether this is a file containing an AST.
  219. if (!ASTReader::readASTFileControlBlock(
  220. Dir->path(), FileMgr, CI.getModuleCache(),
  221. CI.getPCHContainerReader(),
  222. /*FindModuleFileExtensions=*/false, Validator,
  223. /*ValidateDiagnosticOptions=*/false))
  224. MDC->addFile(Dir->path());
  225. }
  226. }
  227. static void collectVFSEntries(CompilerInstance &CI,
  228. std::shared_ptr<ModuleDependencyCollector> MDC) {
  229. if (CI.getHeaderSearchOpts().VFSOverlayFiles.empty())
  230. return;
  231. // Collect all VFS found.
  232. SmallVector<llvm::vfs::YAMLVFSEntry, 16> VFSEntries;
  233. for (const std::string &VFSFile : CI.getHeaderSearchOpts().VFSOverlayFiles) {
  234. llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Buffer =
  235. llvm::MemoryBuffer::getFile(VFSFile);
  236. if (!Buffer)
  237. return;
  238. llvm::vfs::collectVFSFromYAML(std::move(Buffer.get()),
  239. /*DiagHandler*/ nullptr, VFSFile, VFSEntries);
  240. }
  241. for (auto &E : VFSEntries)
  242. MDC->addFile(E.VPath, E.RPath);
  243. }
  244. // Diagnostics
  245. static void SetUpDiagnosticLog(DiagnosticOptions *DiagOpts,
  246. const CodeGenOptions *CodeGenOpts,
  247. DiagnosticsEngine &Diags) {
  248. std::error_code EC;
  249. std::unique_ptr<raw_ostream> StreamOwner;
  250. raw_ostream *OS = &llvm::errs();
  251. if (DiagOpts->DiagnosticLogFile != "-") {
  252. // Create the output stream.
  253. auto FileOS = std::make_unique<llvm::raw_fd_ostream>(
  254. DiagOpts->DiagnosticLogFile, EC,
  255. llvm::sys::fs::OF_Append | llvm::sys::fs::OF_TextWithCRLF);
  256. if (EC) {
  257. Diags.Report(diag::warn_fe_cc_log_diagnostics_failure)
  258. << DiagOpts->DiagnosticLogFile << EC.message();
  259. } else {
  260. FileOS->SetUnbuffered();
  261. OS = FileOS.get();
  262. StreamOwner = std::move(FileOS);
  263. }
  264. }
  265. // Chain in the diagnostic client which will log the diagnostics.
  266. auto Logger = std::make_unique<LogDiagnosticPrinter>(*OS, DiagOpts,
  267. std::move(StreamOwner));
  268. if (CodeGenOpts)
  269. Logger->setDwarfDebugFlags(CodeGenOpts->DwarfDebugFlags);
  270. if (Diags.ownsClient()) {
  271. Diags.setClient(
  272. new ChainedDiagnosticConsumer(Diags.takeClient(), std::move(Logger)));
  273. } else {
  274. Diags.setClient(
  275. new ChainedDiagnosticConsumer(Diags.getClient(), std::move(Logger)));
  276. }
  277. }
  278. static void SetupSerializedDiagnostics(DiagnosticOptions *DiagOpts,
  279. DiagnosticsEngine &Diags,
  280. StringRef OutputFile) {
  281. auto SerializedConsumer =
  282. clang::serialized_diags::create(OutputFile, DiagOpts);
  283. if (Diags.ownsClient()) {
  284. Diags.setClient(new ChainedDiagnosticConsumer(
  285. Diags.takeClient(), std::move(SerializedConsumer)));
  286. } else {
  287. Diags.setClient(new ChainedDiagnosticConsumer(
  288. Diags.getClient(), std::move(SerializedConsumer)));
  289. }
  290. }
  291. void CompilerInstance::createDiagnostics(DiagnosticConsumer *Client,
  292. bool ShouldOwnClient) {
  293. Diagnostics = createDiagnostics(&getDiagnosticOpts(), Client,
  294. ShouldOwnClient, &getCodeGenOpts());
  295. }
  296. IntrusiveRefCntPtr<DiagnosticsEngine>
  297. CompilerInstance::createDiagnostics(DiagnosticOptions *Opts,
  298. DiagnosticConsumer *Client,
  299. bool ShouldOwnClient,
  300. const CodeGenOptions *CodeGenOpts) {
  301. IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
  302. IntrusiveRefCntPtr<DiagnosticsEngine>
  303. Diags(new DiagnosticsEngine(DiagID, Opts));
  304. // Create the diagnostic client for reporting errors or for
  305. // implementing -verify.
  306. if (Client) {
  307. Diags->setClient(Client, ShouldOwnClient);
  308. } else if (Opts->getFormat() == DiagnosticOptions::SARIF) {
  309. Diags->setClient(new SARIFDiagnosticPrinter(llvm::errs(), Opts));
  310. } else
  311. Diags->setClient(new TextDiagnosticPrinter(llvm::errs(), Opts));
  312. // Chain in -verify checker, if requested.
  313. if (Opts->VerifyDiagnostics)
  314. Diags->setClient(new VerifyDiagnosticConsumer(*Diags));
  315. // Chain in -diagnostic-log-file dumper, if requested.
  316. if (!Opts->DiagnosticLogFile.empty())
  317. SetUpDiagnosticLog(Opts, CodeGenOpts, *Diags);
  318. if (!Opts->DiagnosticSerializationFile.empty())
  319. SetupSerializedDiagnostics(Opts, *Diags,
  320. Opts->DiagnosticSerializationFile);
  321. // Configure our handling of diagnostics.
  322. ProcessWarningOptions(*Diags, *Opts);
  323. return Diags;
  324. }
  325. // File Manager
  326. FileManager *CompilerInstance::createFileManager(
  327. IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS) {
  328. if (!VFS)
  329. VFS = FileMgr ? &FileMgr->getVirtualFileSystem()
  330. : createVFSFromCompilerInvocation(getInvocation(),
  331. getDiagnostics());
  332. assert(VFS && "FileManager has no VFS?");
  333. FileMgr = new FileManager(getFileSystemOpts(), std::move(VFS));
  334. return FileMgr.get();
  335. }
  336. // Source Manager
  337. void CompilerInstance::createSourceManager(FileManager &FileMgr) {
  338. SourceMgr = new SourceManager(getDiagnostics(), FileMgr);
  339. }
  340. // Initialize the remapping of files to alternative contents, e.g.,
  341. // those specified through other files.
  342. static void InitializeFileRemapping(DiagnosticsEngine &Diags,
  343. SourceManager &SourceMgr,
  344. FileManager &FileMgr,
  345. const PreprocessorOptions &InitOpts) {
  346. // Remap files in the source manager (with buffers).
  347. for (const auto &RB : InitOpts.RemappedFileBuffers) {
  348. // Create the file entry for the file that we're mapping from.
  349. const FileEntry *FromFile =
  350. FileMgr.getVirtualFile(RB.first, RB.second->getBufferSize(), 0);
  351. if (!FromFile) {
  352. Diags.Report(diag::err_fe_remap_missing_from_file) << RB.first;
  353. if (!InitOpts.RetainRemappedFileBuffers)
  354. delete RB.second;
  355. continue;
  356. }
  357. // Override the contents of the "from" file with the contents of the
  358. // "to" file. If the caller owns the buffers, then pass a MemoryBufferRef;
  359. // otherwise, pass as a std::unique_ptr<MemoryBuffer> to transfer ownership
  360. // to the SourceManager.
  361. if (InitOpts.RetainRemappedFileBuffers)
  362. SourceMgr.overrideFileContents(FromFile, RB.second->getMemBufferRef());
  363. else
  364. SourceMgr.overrideFileContents(
  365. FromFile, std::unique_ptr<llvm::MemoryBuffer>(
  366. const_cast<llvm::MemoryBuffer *>(RB.second)));
  367. }
  368. // Remap files in the source manager (with other files).
  369. for (const auto &RF : InitOpts.RemappedFiles) {
  370. // Find the file that we're mapping to.
  371. OptionalFileEntryRef ToFile = FileMgr.getOptionalFileRef(RF.second);
  372. if (!ToFile) {
  373. Diags.Report(diag::err_fe_remap_missing_to_file) << RF.first << RF.second;
  374. continue;
  375. }
  376. // Create the file entry for the file that we're mapping from.
  377. const FileEntry *FromFile =
  378. FileMgr.getVirtualFile(RF.first, ToFile->getSize(), 0);
  379. if (!FromFile) {
  380. Diags.Report(diag::err_fe_remap_missing_from_file) << RF.first;
  381. continue;
  382. }
  383. // Override the contents of the "from" file with the contents of
  384. // the "to" file.
  385. SourceMgr.overrideFileContents(FromFile, *ToFile);
  386. }
  387. SourceMgr.setOverridenFilesKeepOriginalName(
  388. InitOpts.RemappedFilesKeepOriginalName);
  389. }
  390. // Preprocessor
  391. void CompilerInstance::createPreprocessor(TranslationUnitKind TUKind) {
  392. const PreprocessorOptions &PPOpts = getPreprocessorOpts();
  393. // The AST reader holds a reference to the old preprocessor (if any).
  394. TheASTReader.reset();
  395. // Create the Preprocessor.
  396. HeaderSearch *HeaderInfo =
  397. new HeaderSearch(getHeaderSearchOptsPtr(), getSourceManager(),
  398. getDiagnostics(), getLangOpts(), &getTarget());
  399. PP = std::make_shared<Preprocessor>(Invocation->getPreprocessorOptsPtr(),
  400. getDiagnostics(), getLangOpts(),
  401. getSourceManager(), *HeaderInfo, *this,
  402. /*IdentifierInfoLookup=*/nullptr,
  403. /*OwnsHeaderSearch=*/true, TUKind);
  404. getTarget().adjust(getDiagnostics(), getLangOpts());
  405. PP->Initialize(getTarget(), getAuxTarget());
  406. if (PPOpts.DetailedRecord)
  407. PP->createPreprocessingRecord();
  408. // Apply remappings to the source manager.
  409. InitializeFileRemapping(PP->getDiagnostics(), PP->getSourceManager(),
  410. PP->getFileManager(), PPOpts);
  411. // Predefine macros and configure the preprocessor.
  412. InitializePreprocessor(*PP, PPOpts, getPCHContainerReader(),
  413. getFrontendOpts());
  414. // Initialize the header search object. In CUDA compilations, we use the aux
  415. // triple (the host triple) to initialize our header search, since we need to
  416. // find the host headers in order to compile the CUDA code.
  417. const llvm::Triple *HeaderSearchTriple = &PP->getTargetInfo().getTriple();
  418. if (PP->getTargetInfo().getTriple().getOS() == llvm::Triple::CUDA &&
  419. PP->getAuxTargetInfo())
  420. HeaderSearchTriple = &PP->getAuxTargetInfo()->getTriple();
  421. ApplyHeaderSearchOptions(PP->getHeaderSearchInfo(), getHeaderSearchOpts(),
  422. PP->getLangOpts(), *HeaderSearchTriple);
  423. PP->setPreprocessedOutput(getPreprocessorOutputOpts().ShowCPP);
  424. if (PP->getLangOpts().Modules && PP->getLangOpts().ImplicitModules) {
  425. std::string ModuleHash = getInvocation().getModuleHash();
  426. PP->getHeaderSearchInfo().setModuleHash(ModuleHash);
  427. PP->getHeaderSearchInfo().setModuleCachePath(
  428. getSpecificModuleCachePath(ModuleHash));
  429. }
  430. // Handle generating dependencies, if requested.
  431. const DependencyOutputOptions &DepOpts = getDependencyOutputOpts();
  432. if (!DepOpts.OutputFile.empty())
  433. addDependencyCollector(std::make_shared<DependencyFileGenerator>(DepOpts));
  434. if (!DepOpts.DOTOutputFile.empty())
  435. AttachDependencyGraphGen(*PP, DepOpts.DOTOutputFile,
  436. getHeaderSearchOpts().Sysroot);
  437. // If we don't have a collector, but we are collecting module dependencies,
  438. // then we're the top level compiler instance and need to create one.
  439. if (!ModuleDepCollector && !DepOpts.ModuleDependencyOutputDir.empty()) {
  440. ModuleDepCollector = std::make_shared<ModuleDependencyCollector>(
  441. DepOpts.ModuleDependencyOutputDir);
  442. }
  443. // If there is a module dep collector, register with other dep collectors
  444. // and also (a) collect header maps and (b) TODO: input vfs overlay files.
  445. if (ModuleDepCollector) {
  446. addDependencyCollector(ModuleDepCollector);
  447. collectHeaderMaps(PP->getHeaderSearchInfo(), ModuleDepCollector);
  448. collectIncludePCH(*this, ModuleDepCollector);
  449. collectVFSEntries(*this, ModuleDepCollector);
  450. }
  451. for (auto &Listener : DependencyCollectors)
  452. Listener->attachToPreprocessor(*PP);
  453. // Handle generating header include information, if requested.
  454. if (DepOpts.ShowHeaderIncludes)
  455. AttachHeaderIncludeGen(*PP, DepOpts);
  456. if (!DepOpts.HeaderIncludeOutputFile.empty()) {
  457. StringRef OutputPath = DepOpts.HeaderIncludeOutputFile;
  458. if (OutputPath == "-")
  459. OutputPath = "";
  460. AttachHeaderIncludeGen(*PP, DepOpts,
  461. /*ShowAllHeaders=*/true, OutputPath,
  462. /*ShowDepth=*/false);
  463. }
  464. if (DepOpts.ShowIncludesDest != ShowIncludesDestination::None) {
  465. AttachHeaderIncludeGen(*PP, DepOpts,
  466. /*ShowAllHeaders=*/true, /*OutputPath=*/"",
  467. /*ShowDepth=*/true, /*MSStyle=*/true);
  468. }
  469. }
  470. std::string CompilerInstance::getSpecificModuleCachePath(StringRef ModuleHash) {
  471. // Set up the module path, including the hash for the module-creation options.
  472. SmallString<256> SpecificModuleCache(getHeaderSearchOpts().ModuleCachePath);
  473. if (!SpecificModuleCache.empty() && !getHeaderSearchOpts().DisableModuleHash)
  474. llvm::sys::path::append(SpecificModuleCache, ModuleHash);
  475. return std::string(SpecificModuleCache.str());
  476. }
  477. // ASTContext
  478. void CompilerInstance::createASTContext() {
  479. Preprocessor &PP = getPreprocessor();
  480. auto *Context = new ASTContext(getLangOpts(), PP.getSourceManager(),
  481. PP.getIdentifierTable(), PP.getSelectorTable(),
  482. PP.getBuiltinInfo(), PP.TUKind);
  483. Context->InitBuiltinTypes(getTarget(), getAuxTarget());
  484. setASTContext(Context);
  485. }
  486. // ExternalASTSource
  487. namespace {
  488. // Helper to recursively read the module names for all modules we're adding.
  489. // We mark these as known and redirect any attempt to load that module to
  490. // the files we were handed.
  491. struct ReadModuleNames : ASTReaderListener {
  492. Preprocessor &PP;
  493. llvm::SmallVector<std::string, 8> LoadedModules;
  494. ReadModuleNames(Preprocessor &PP) : PP(PP) {}
  495. void ReadModuleName(StringRef ModuleName) override {
  496. // Keep the module name as a string for now. It's not safe to create a new
  497. // IdentifierInfo from an ASTReader callback.
  498. LoadedModules.push_back(ModuleName.str());
  499. }
  500. void registerAll() {
  501. ModuleMap &MM = PP.getHeaderSearchInfo().getModuleMap();
  502. for (const std::string &LoadedModule : LoadedModules)
  503. MM.cacheModuleLoad(*PP.getIdentifierInfo(LoadedModule),
  504. MM.findModule(LoadedModule));
  505. LoadedModules.clear();
  506. }
  507. void markAllUnavailable() {
  508. for (const std::string &LoadedModule : LoadedModules) {
  509. if (Module *M = PP.getHeaderSearchInfo().getModuleMap().findModule(
  510. LoadedModule)) {
  511. M->HasIncompatibleModuleFile = true;
  512. // Mark module as available if the only reason it was unavailable
  513. // was missing headers.
  514. SmallVector<Module *, 2> Stack;
  515. Stack.push_back(M);
  516. while (!Stack.empty()) {
  517. Module *Current = Stack.pop_back_val();
  518. if (Current->IsUnimportable) continue;
  519. Current->IsAvailable = true;
  520. Stack.insert(Stack.end(),
  521. Current->submodule_begin(), Current->submodule_end());
  522. }
  523. }
  524. }
  525. LoadedModules.clear();
  526. }
  527. };
  528. } // namespace
  529. void CompilerInstance::createPCHExternalASTSource(
  530. StringRef Path, DisableValidationForModuleKind DisableValidation,
  531. bool AllowPCHWithCompilerErrors, void *DeserializationListener,
  532. bool OwnDeserializationListener) {
  533. bool Preamble = getPreprocessorOpts().PrecompiledPreambleBytes.first != 0;
  534. TheASTReader = createPCHExternalASTSource(
  535. Path, getHeaderSearchOpts().Sysroot, DisableValidation,
  536. AllowPCHWithCompilerErrors, getPreprocessor(), getModuleCache(),
  537. getASTContext(), getPCHContainerReader(),
  538. getFrontendOpts().ModuleFileExtensions, DependencyCollectors,
  539. DeserializationListener, OwnDeserializationListener, Preamble,
  540. getFrontendOpts().UseGlobalModuleIndex);
  541. }
  542. IntrusiveRefCntPtr<ASTReader> CompilerInstance::createPCHExternalASTSource(
  543. StringRef Path, StringRef Sysroot,
  544. DisableValidationForModuleKind DisableValidation,
  545. bool AllowPCHWithCompilerErrors, Preprocessor &PP,
  546. InMemoryModuleCache &ModuleCache, ASTContext &Context,
  547. const PCHContainerReader &PCHContainerRdr,
  548. ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
  549. ArrayRef<std::shared_ptr<DependencyCollector>> DependencyCollectors,
  550. void *DeserializationListener, bool OwnDeserializationListener,
  551. bool Preamble, bool UseGlobalModuleIndex) {
  552. HeaderSearchOptions &HSOpts = PP.getHeaderSearchInfo().getHeaderSearchOpts();
  553. IntrusiveRefCntPtr<ASTReader> Reader(new ASTReader(
  554. PP, ModuleCache, &Context, PCHContainerRdr, Extensions,
  555. Sysroot.empty() ? "" : Sysroot.data(), DisableValidation,
  556. AllowPCHWithCompilerErrors, /*AllowConfigurationMismatch*/ false,
  557. HSOpts.ModulesValidateSystemHeaders, HSOpts.ValidateASTInputFilesContent,
  558. UseGlobalModuleIndex));
  559. // We need the external source to be set up before we read the AST, because
  560. // eagerly-deserialized declarations may use it.
  561. Context.setExternalSource(Reader.get());
  562. Reader->setDeserializationListener(
  563. static_cast<ASTDeserializationListener *>(DeserializationListener),
  564. /*TakeOwnership=*/OwnDeserializationListener);
  565. for (auto &Listener : DependencyCollectors)
  566. Listener->attachToASTReader(*Reader);
  567. auto Listener = std::make_unique<ReadModuleNames>(PP);
  568. auto &ListenerRef = *Listener;
  569. ASTReader::ListenerScope ReadModuleNamesListener(*Reader,
  570. std::move(Listener));
  571. switch (Reader->ReadAST(Path,
  572. Preamble ? serialization::MK_Preamble
  573. : serialization::MK_PCH,
  574. SourceLocation(),
  575. ASTReader::ARR_None)) {
  576. case ASTReader::Success:
  577. // Set the predefines buffer as suggested by the PCH reader. Typically, the
  578. // predefines buffer will be empty.
  579. PP.setPredefines(Reader->getSuggestedPredefines());
  580. ListenerRef.registerAll();
  581. return Reader;
  582. case ASTReader::Failure:
  583. // Unrecoverable failure: don't even try to process the input file.
  584. break;
  585. case ASTReader::Missing:
  586. case ASTReader::OutOfDate:
  587. case ASTReader::VersionMismatch:
  588. case ASTReader::ConfigurationMismatch:
  589. case ASTReader::HadErrors:
  590. // No suitable PCH file could be found. Return an error.
  591. break;
  592. }
  593. ListenerRef.markAllUnavailable();
  594. Context.setExternalSource(nullptr);
  595. return nullptr;
  596. }
  597. // Code Completion
  598. static bool EnableCodeCompletion(Preprocessor &PP,
  599. StringRef Filename,
  600. unsigned Line,
  601. unsigned Column) {
  602. // Tell the source manager to chop off the given file at a specific
  603. // line and column.
  604. auto Entry = PP.getFileManager().getFile(Filename);
  605. if (!Entry) {
  606. PP.getDiagnostics().Report(diag::err_fe_invalid_code_complete_file)
  607. << Filename;
  608. return true;
  609. }
  610. // Truncate the named file at the given line/column.
  611. PP.SetCodeCompletionPoint(*Entry, Line, Column);
  612. return false;
  613. }
  614. void CompilerInstance::createCodeCompletionConsumer() {
  615. const ParsedSourceLocation &Loc = getFrontendOpts().CodeCompletionAt;
  616. if (!CompletionConsumer) {
  617. setCodeCompletionConsumer(createCodeCompletionConsumer(
  618. getPreprocessor(), Loc.FileName, Loc.Line, Loc.Column,
  619. getFrontendOpts().CodeCompleteOpts, llvm::outs()));
  620. return;
  621. } else if (EnableCodeCompletion(getPreprocessor(), Loc.FileName,
  622. Loc.Line, Loc.Column)) {
  623. setCodeCompletionConsumer(nullptr);
  624. return;
  625. }
  626. }
  627. void CompilerInstance::createFrontendTimer() {
  628. FrontendTimerGroup.reset(
  629. new llvm::TimerGroup("frontend", "Clang front-end time report"));
  630. FrontendTimer.reset(
  631. new llvm::Timer("frontend", "Clang front-end timer",
  632. *FrontendTimerGroup));
  633. }
  634. CodeCompleteConsumer *
  635. CompilerInstance::createCodeCompletionConsumer(Preprocessor &PP,
  636. StringRef Filename,
  637. unsigned Line,
  638. unsigned Column,
  639. const CodeCompleteOptions &Opts,
  640. raw_ostream &OS) {
  641. if (EnableCodeCompletion(PP, Filename, Line, Column))
  642. return nullptr;
  643. // Set up the creation routine for code-completion.
  644. return new PrintingCodeCompleteConsumer(Opts, OS);
  645. }
  646. void CompilerInstance::createSema(TranslationUnitKind TUKind,
  647. CodeCompleteConsumer *CompletionConsumer) {
  648. TheSema.reset(new Sema(getPreprocessor(), getASTContext(), getASTConsumer(),
  649. TUKind, CompletionConsumer));
  650. // Attach the external sema source if there is any.
  651. if (ExternalSemaSrc) {
  652. TheSema->addExternalSource(ExternalSemaSrc.get());
  653. ExternalSemaSrc->InitializeSema(*TheSema);
  654. }
  655. }
  656. // Output Files
  657. void CompilerInstance::clearOutputFiles(bool EraseFiles) {
  658. // The ASTConsumer can own streams that write to the output files.
  659. assert(!hasASTConsumer() && "ASTConsumer should be reset");
  660. // Ignore errors that occur when trying to discard the temp file.
  661. for (OutputFile &OF : OutputFiles) {
  662. if (EraseFiles) {
  663. if (OF.File)
  664. consumeError(OF.File->discard());
  665. if (!OF.Filename.empty())
  666. llvm::sys::fs::remove(OF.Filename);
  667. continue;
  668. }
  669. if (!OF.File)
  670. continue;
  671. if (OF.File->TmpName.empty()) {
  672. consumeError(OF.File->discard());
  673. continue;
  674. }
  675. llvm::Error E = OF.File->keep(OF.Filename);
  676. if (!E)
  677. continue;
  678. getDiagnostics().Report(diag::err_unable_to_rename_temp)
  679. << OF.File->TmpName << OF.Filename << std::move(E);
  680. llvm::sys::fs::remove(OF.File->TmpName);
  681. }
  682. OutputFiles.clear();
  683. if (DeleteBuiltModules) {
  684. for (auto &Module : BuiltModules)
  685. llvm::sys::fs::remove(Module.second);
  686. BuiltModules.clear();
  687. }
  688. }
  689. std::unique_ptr<raw_pwrite_stream> CompilerInstance::createDefaultOutputFile(
  690. bool Binary, StringRef InFile, StringRef Extension, bool RemoveFileOnSignal,
  691. bool CreateMissingDirectories, bool ForceUseTemporary) {
  692. StringRef OutputPath = getFrontendOpts().OutputFile;
  693. std::optional<SmallString<128>> PathStorage;
  694. if (OutputPath.empty()) {
  695. if (InFile == "-" || Extension.empty()) {
  696. OutputPath = "-";
  697. } else {
  698. PathStorage.emplace(InFile);
  699. llvm::sys::path::replace_extension(*PathStorage, Extension);
  700. OutputPath = *PathStorage;
  701. }
  702. }
  703. return createOutputFile(OutputPath, Binary, RemoveFileOnSignal,
  704. getFrontendOpts().UseTemporary || ForceUseTemporary,
  705. CreateMissingDirectories);
  706. }
  707. std::unique_ptr<raw_pwrite_stream> CompilerInstance::createNullOutputFile() {
  708. return std::make_unique<llvm::raw_null_ostream>();
  709. }
  710. std::unique_ptr<raw_pwrite_stream>
  711. CompilerInstance::createOutputFile(StringRef OutputPath, bool Binary,
  712. bool RemoveFileOnSignal, bool UseTemporary,
  713. bool CreateMissingDirectories) {
  714. Expected<std::unique_ptr<raw_pwrite_stream>> OS =
  715. createOutputFileImpl(OutputPath, Binary, RemoveFileOnSignal, UseTemporary,
  716. CreateMissingDirectories);
  717. if (OS)
  718. return std::move(*OS);
  719. getDiagnostics().Report(diag::err_fe_unable_to_open_output)
  720. << OutputPath << errorToErrorCode(OS.takeError()).message();
  721. return nullptr;
  722. }
  723. Expected<std::unique_ptr<llvm::raw_pwrite_stream>>
  724. CompilerInstance::createOutputFileImpl(StringRef OutputPath, bool Binary,
  725. bool RemoveFileOnSignal,
  726. bool UseTemporary,
  727. bool CreateMissingDirectories) {
  728. assert((!CreateMissingDirectories || UseTemporary) &&
  729. "CreateMissingDirectories is only allowed when using temporary files");
  730. // If '-working-directory' was passed, the output filename should be
  731. // relative to that.
  732. std::optional<SmallString<128>> AbsPath;
  733. if (OutputPath != "-" && !llvm::sys::path::is_absolute(OutputPath)) {
  734. AbsPath.emplace(OutputPath);
  735. FileMgr->FixupRelativePath(*AbsPath);
  736. OutputPath = *AbsPath;
  737. }
  738. std::unique_ptr<llvm::raw_fd_ostream> OS;
  739. std::optional<StringRef> OSFile;
  740. if (UseTemporary) {
  741. if (OutputPath == "-")
  742. UseTemporary = false;
  743. else {
  744. llvm::sys::fs::file_status Status;
  745. llvm::sys::fs::status(OutputPath, Status);
  746. if (llvm::sys::fs::exists(Status)) {
  747. // Fail early if we can't write to the final destination.
  748. if (!llvm::sys::fs::can_write(OutputPath))
  749. return llvm::errorCodeToError(
  750. make_error_code(llvm::errc::operation_not_permitted));
  751. // Don't use a temporary if the output is a special file. This handles
  752. // things like '-o /dev/null'
  753. if (!llvm::sys::fs::is_regular_file(Status))
  754. UseTemporary = false;
  755. }
  756. }
  757. }
  758. std::optional<llvm::sys::fs::TempFile> Temp;
  759. if (UseTemporary) {
  760. // Create a temporary file.
  761. // Insert -%%%%%%%% before the extension (if any), and because some tools
  762. // (noticeable, clang's own GlobalModuleIndex.cpp) glob for build
  763. // artifacts, also append .tmp.
  764. StringRef OutputExtension = llvm::sys::path::extension(OutputPath);
  765. SmallString<128> TempPath =
  766. StringRef(OutputPath).drop_back(OutputExtension.size());
  767. TempPath += "-%%%%%%%%";
  768. TempPath += OutputExtension;
  769. TempPath += ".tmp";
  770. Expected<llvm::sys::fs::TempFile> ExpectedFile =
  771. llvm::sys::fs::TempFile::create(
  772. TempPath, llvm::sys::fs::all_read | llvm::sys::fs::all_write,
  773. Binary ? llvm::sys::fs::OF_None : llvm::sys::fs::OF_Text);
  774. llvm::Error E = handleErrors(
  775. ExpectedFile.takeError(), [&](const llvm::ECError &E) -> llvm::Error {
  776. std::error_code EC = E.convertToErrorCode();
  777. if (CreateMissingDirectories &&
  778. EC == llvm::errc::no_such_file_or_directory) {
  779. StringRef Parent = llvm::sys::path::parent_path(OutputPath);
  780. EC = llvm::sys::fs::create_directories(Parent);
  781. if (!EC) {
  782. ExpectedFile = llvm::sys::fs::TempFile::create(TempPath);
  783. if (!ExpectedFile)
  784. return llvm::errorCodeToError(
  785. llvm::errc::no_such_file_or_directory);
  786. }
  787. }
  788. return llvm::errorCodeToError(EC);
  789. });
  790. if (E) {
  791. consumeError(std::move(E));
  792. } else {
  793. Temp = std::move(ExpectedFile.get());
  794. OS.reset(new llvm::raw_fd_ostream(Temp->FD, /*shouldClose=*/false));
  795. OSFile = Temp->TmpName;
  796. }
  797. // If we failed to create the temporary, fallback to writing to the file
  798. // directly. This handles the corner case where we cannot write to the
  799. // directory, but can write to the file.
  800. }
  801. if (!OS) {
  802. OSFile = OutputPath;
  803. std::error_code EC;
  804. OS.reset(new llvm::raw_fd_ostream(
  805. *OSFile, EC,
  806. (Binary ? llvm::sys::fs::OF_None : llvm::sys::fs::OF_TextWithCRLF)));
  807. if (EC)
  808. return llvm::errorCodeToError(EC);
  809. }
  810. // Add the output file -- but don't try to remove "-", since this means we are
  811. // using stdin.
  812. OutputFiles.emplace_back(((OutputPath != "-") ? OutputPath : "").str(),
  813. std::move(Temp));
  814. if (!Binary || OS->supportsSeeking())
  815. return std::move(OS);
  816. return std::make_unique<llvm::buffer_unique_ostream>(std::move(OS));
  817. }
  818. // Initialization Utilities
  819. bool CompilerInstance::InitializeSourceManager(const FrontendInputFile &Input){
  820. return InitializeSourceManager(Input, getDiagnostics(), getFileManager(),
  821. getSourceManager());
  822. }
  823. // static
  824. bool CompilerInstance::InitializeSourceManager(const FrontendInputFile &Input,
  825. DiagnosticsEngine &Diags,
  826. FileManager &FileMgr,
  827. SourceManager &SourceMgr) {
  828. SrcMgr::CharacteristicKind Kind =
  829. Input.getKind().getFormat() == InputKind::ModuleMap
  830. ? Input.isSystem() ? SrcMgr::C_System_ModuleMap
  831. : SrcMgr::C_User_ModuleMap
  832. : Input.isSystem() ? SrcMgr::C_System : SrcMgr::C_User;
  833. if (Input.isBuffer()) {
  834. SourceMgr.setMainFileID(SourceMgr.createFileID(Input.getBuffer(), Kind));
  835. assert(SourceMgr.getMainFileID().isValid() &&
  836. "Couldn't establish MainFileID!");
  837. return true;
  838. }
  839. StringRef InputFile = Input.getFile();
  840. // Figure out where to get and map in the main file.
  841. auto FileOrErr = InputFile == "-"
  842. ? FileMgr.getSTDIN()
  843. : FileMgr.getFileRef(InputFile, /*OpenFile=*/true);
  844. if (!FileOrErr) {
  845. // FIXME: include the error in the diagnostic even when it's not stdin.
  846. auto EC = llvm::errorToErrorCode(FileOrErr.takeError());
  847. if (InputFile != "-")
  848. Diags.Report(diag::err_fe_error_reading) << InputFile;
  849. else
  850. Diags.Report(diag::err_fe_error_reading_stdin) << EC.message();
  851. return false;
  852. }
  853. SourceMgr.setMainFileID(
  854. SourceMgr.createFileID(*FileOrErr, SourceLocation(), Kind));
  855. assert(SourceMgr.getMainFileID().isValid() &&
  856. "Couldn't establish MainFileID!");
  857. return true;
  858. }
  859. // High-Level Operations
  860. bool CompilerInstance::ExecuteAction(FrontendAction &Act) {
  861. assert(hasDiagnostics() && "Diagnostics engine is not initialized!");
  862. assert(!getFrontendOpts().ShowHelp && "Client must handle '-help'!");
  863. assert(!getFrontendOpts().ShowVersion && "Client must handle '-version'!");
  864. // Mark this point as the bottom of the stack if we don't have somewhere
  865. // better. We generally expect frontend actions to be invoked with (nearly)
  866. // DesiredStackSpace available.
  867. noteBottomOfStack();
  868. auto FinishDiagnosticClient = llvm::make_scope_exit([&]() {
  869. // Notify the diagnostic client that all files were processed.
  870. getDiagnosticClient().finish();
  871. });
  872. raw_ostream &OS = getVerboseOutputStream();
  873. if (!Act.PrepareToExecute(*this))
  874. return false;
  875. if (!createTarget())
  876. return false;
  877. // rewriter project will change target built-in bool type from its default.
  878. if (getFrontendOpts().ProgramAction == frontend::RewriteObjC)
  879. getTarget().noSignedCharForObjCBool();
  880. // Validate/process some options.
  881. if (getHeaderSearchOpts().Verbose)
  882. OS << "clang -cc1 version " CLANG_VERSION_STRING << " based upon LLVM "
  883. << LLVM_VERSION_STRING << " default target "
  884. << llvm::sys::getDefaultTargetTriple() << "\n";
  885. if (getCodeGenOpts().TimePasses)
  886. createFrontendTimer();
  887. if (getFrontendOpts().ShowStats || !getFrontendOpts().StatsFile.empty())
  888. llvm::EnableStatistics(false);
  889. for (const FrontendInputFile &FIF : getFrontendOpts().Inputs) {
  890. // Reset the ID tables if we are reusing the SourceManager and parsing
  891. // regular files.
  892. if (hasSourceManager() && !Act.isModelParsingAction())
  893. getSourceManager().clearIDTables();
  894. if (Act.BeginSourceFile(*this, FIF)) {
  895. if (llvm::Error Err = Act.Execute()) {
  896. consumeError(std::move(Err)); // FIXME this drops errors on the floor.
  897. }
  898. Act.EndSourceFile();
  899. }
  900. }
  901. if (getDiagnosticOpts().ShowCarets) {
  902. // We can have multiple diagnostics sharing one diagnostic client.
  903. // Get the total number of warnings/errors from the client.
  904. unsigned NumWarnings = getDiagnostics().getClient()->getNumWarnings();
  905. unsigned NumErrors = getDiagnostics().getClient()->getNumErrors();
  906. if (NumWarnings)
  907. OS << NumWarnings << " warning" << (NumWarnings == 1 ? "" : "s");
  908. if (NumWarnings && NumErrors)
  909. OS << " and ";
  910. if (NumErrors)
  911. OS << NumErrors << " error" << (NumErrors == 1 ? "" : "s");
  912. if (NumWarnings || NumErrors) {
  913. OS << " generated";
  914. if (getLangOpts().CUDA) {
  915. if (!getLangOpts().CUDAIsDevice) {
  916. OS << " when compiling for host";
  917. } else {
  918. OS << " when compiling for " << getTargetOpts().CPU;
  919. }
  920. }
  921. OS << ".\n";
  922. }
  923. }
  924. if (getFrontendOpts().ShowStats) {
  925. if (hasFileManager()) {
  926. getFileManager().PrintStats();
  927. OS << '\n';
  928. }
  929. llvm::PrintStatistics(OS);
  930. }
  931. StringRef StatsFile = getFrontendOpts().StatsFile;
  932. if (!StatsFile.empty()) {
  933. std::error_code EC;
  934. auto StatS = std::make_unique<llvm::raw_fd_ostream>(
  935. StatsFile, EC, llvm::sys::fs::OF_TextWithCRLF);
  936. if (EC) {
  937. getDiagnostics().Report(diag::warn_fe_unable_to_open_stats_file)
  938. << StatsFile << EC.message();
  939. } else {
  940. llvm::PrintStatisticsJSON(*StatS);
  941. }
  942. }
  943. return !getDiagnostics().getClient()->getNumErrors();
  944. }
  945. void CompilerInstance::LoadRequestedPlugins() {
  946. // Load any requested plugins.
  947. for (const std::string &Path : getFrontendOpts().Plugins) {
  948. std::string Error;
  949. if (llvm::sys::DynamicLibrary::LoadLibraryPermanently(Path.c_str(), &Error))
  950. getDiagnostics().Report(diag::err_fe_unable_to_load_plugin)
  951. << Path << Error;
  952. }
  953. // Check if any of the loaded plugins replaces the main AST action
  954. for (const FrontendPluginRegistry::entry &Plugin :
  955. FrontendPluginRegistry::entries()) {
  956. std::unique_ptr<PluginASTAction> P(Plugin.instantiate());
  957. if (P->getActionType() == PluginASTAction::ReplaceAction) {
  958. getFrontendOpts().ProgramAction = clang::frontend::PluginAction;
  959. getFrontendOpts().ActionName = Plugin.getName().str();
  960. break;
  961. }
  962. }
  963. }
  964. /// Determine the appropriate source input kind based on language
  965. /// options.
  966. static Language getLanguageFromOptions(const LangOptions &LangOpts) {
  967. if (LangOpts.OpenCL)
  968. return Language::OpenCL;
  969. if (LangOpts.CUDA)
  970. return Language::CUDA;
  971. if (LangOpts.ObjC)
  972. return LangOpts.CPlusPlus ? Language::ObjCXX : Language::ObjC;
  973. return LangOpts.CPlusPlus ? Language::CXX : Language::C;
  974. }
  975. /// Compile a module file for the given module, using the options
  976. /// provided by the importing compiler instance. Returns true if the module
  977. /// was built without errors.
  978. static bool
  979. compileModuleImpl(CompilerInstance &ImportingInstance, SourceLocation ImportLoc,
  980. StringRef ModuleName, FrontendInputFile Input,
  981. StringRef OriginalModuleMapFile, StringRef ModuleFileName,
  982. llvm::function_ref<void(CompilerInstance &)> PreBuildStep =
  983. [](CompilerInstance &) {},
  984. llvm::function_ref<void(CompilerInstance &)> PostBuildStep =
  985. [](CompilerInstance &) {}) {
  986. llvm::TimeTraceScope TimeScope("Module Compile", ModuleName);
  987. // Never compile a module that's already finalized - this would cause the
  988. // existing module to be freed, causing crashes if it is later referenced
  989. if (ImportingInstance.getModuleCache().isPCMFinal(ModuleFileName)) {
  990. ImportingInstance.getDiagnostics().Report(
  991. ImportLoc, diag::err_module_rebuild_finalized)
  992. << ModuleName;
  993. return false;
  994. }
  995. // Construct a compiler invocation for creating this module.
  996. auto Invocation =
  997. std::make_shared<CompilerInvocation>(ImportingInstance.getInvocation());
  998. PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
  999. // For any options that aren't intended to affect how a module is built,
  1000. // reset them to their default values.
  1001. Invocation->resetNonModularOptions();
  1002. // Remove any macro definitions that are explicitly ignored by the module.
  1003. // They aren't supposed to affect how the module is built anyway.
  1004. HeaderSearchOptions &HSOpts = Invocation->getHeaderSearchOpts();
  1005. llvm::erase_if(PPOpts.Macros,
  1006. [&HSOpts](const std::pair<std::string, bool> &def) {
  1007. StringRef MacroDef = def.first;
  1008. return HSOpts.ModulesIgnoreMacros.contains(
  1009. llvm::CachedHashString(MacroDef.split('=').first));
  1010. });
  1011. // If the original compiler invocation had -fmodule-name, pass it through.
  1012. Invocation->getLangOpts()->ModuleName =
  1013. ImportingInstance.getInvocation().getLangOpts()->ModuleName;
  1014. // Note the name of the module we're building.
  1015. Invocation->getLangOpts()->CurrentModule = std::string(ModuleName);
  1016. // Make sure that the failed-module structure has been allocated in
  1017. // the importing instance, and propagate the pointer to the newly-created
  1018. // instance.
  1019. PreprocessorOptions &ImportingPPOpts
  1020. = ImportingInstance.getInvocation().getPreprocessorOpts();
  1021. if (!ImportingPPOpts.FailedModules)
  1022. ImportingPPOpts.FailedModules =
  1023. std::make_shared<PreprocessorOptions::FailedModulesSet>();
  1024. PPOpts.FailedModules = ImportingPPOpts.FailedModules;
  1025. // If there is a module map file, build the module using the module map.
  1026. // Set up the inputs/outputs so that we build the module from its umbrella
  1027. // header.
  1028. FrontendOptions &FrontendOpts = Invocation->getFrontendOpts();
  1029. FrontendOpts.OutputFile = ModuleFileName.str();
  1030. FrontendOpts.DisableFree = false;
  1031. FrontendOpts.GenerateGlobalModuleIndex = false;
  1032. FrontendOpts.BuildingImplicitModule = true;
  1033. FrontendOpts.OriginalModuleMap = std::string(OriginalModuleMapFile);
  1034. // Force implicitly-built modules to hash the content of the module file.
  1035. HSOpts.ModulesHashContent = true;
  1036. FrontendOpts.Inputs = {Input};
  1037. // Don't free the remapped file buffers; they are owned by our caller.
  1038. PPOpts.RetainRemappedFileBuffers = true;
  1039. Invocation->getDiagnosticOpts().VerifyDiagnostics = 0;
  1040. assert(ImportingInstance.getInvocation().getModuleHash() ==
  1041. Invocation->getModuleHash() && "Module hash mismatch!");
  1042. // Construct a compiler instance that will be used to actually create the
  1043. // module. Since we're sharing an in-memory module cache,
  1044. // CompilerInstance::CompilerInstance is responsible for finalizing the
  1045. // buffers to prevent use-after-frees.
  1046. CompilerInstance Instance(ImportingInstance.getPCHContainerOperations(),
  1047. &ImportingInstance.getModuleCache());
  1048. auto &Inv = *Invocation;
  1049. Instance.setInvocation(std::move(Invocation));
  1050. Instance.createDiagnostics(new ForwardingDiagnosticConsumer(
  1051. ImportingInstance.getDiagnosticClient()),
  1052. /*ShouldOwnClient=*/true);
  1053. if (FrontendOpts.ModulesShareFileManager) {
  1054. Instance.setFileManager(&ImportingInstance.getFileManager());
  1055. } else {
  1056. Instance.createFileManager(&ImportingInstance.getVirtualFileSystem());
  1057. }
  1058. Instance.createSourceManager(Instance.getFileManager());
  1059. SourceManager &SourceMgr = Instance.getSourceManager();
  1060. // Note that this module is part of the module build stack, so that we
  1061. // can detect cycles in the module graph.
  1062. SourceMgr.setModuleBuildStack(
  1063. ImportingInstance.getSourceManager().getModuleBuildStack());
  1064. SourceMgr.pushModuleBuildStack(ModuleName,
  1065. FullSourceLoc(ImportLoc, ImportingInstance.getSourceManager()));
  1066. // If we're collecting module dependencies, we need to share a collector
  1067. // between all of the module CompilerInstances. Other than that, we don't
  1068. // want to produce any dependency output from the module build.
  1069. Instance.setModuleDepCollector(ImportingInstance.getModuleDepCollector());
  1070. Inv.getDependencyOutputOpts() = DependencyOutputOptions();
  1071. ImportingInstance.getDiagnostics().Report(ImportLoc,
  1072. diag::remark_module_build)
  1073. << ModuleName << ModuleFileName;
  1074. PreBuildStep(Instance);
  1075. // Execute the action to actually build the module in-place. Use a separate
  1076. // thread so that we get a stack large enough.
  1077. bool Crashed = !llvm::CrashRecoveryContext().RunSafelyOnThread(
  1078. [&]() {
  1079. GenerateModuleFromModuleMapAction Action;
  1080. Instance.ExecuteAction(Action);
  1081. },
  1082. DesiredStackSize);
  1083. PostBuildStep(Instance);
  1084. ImportingInstance.getDiagnostics().Report(ImportLoc,
  1085. diag::remark_module_build_done)
  1086. << ModuleName;
  1087. if (Crashed) {
  1088. // Clear the ASTConsumer if it hasn't been already, in case it owns streams
  1089. // that must be closed before clearing output files.
  1090. Instance.setSema(nullptr);
  1091. Instance.setASTConsumer(nullptr);
  1092. // Delete any remaining temporary files related to Instance.
  1093. Instance.clearOutputFiles(/*EraseFiles=*/true);
  1094. }
  1095. // If \p AllowPCMWithCompilerErrors is set return 'success' even if errors
  1096. // occurred.
  1097. return !Instance.getDiagnostics().hasErrorOccurred() ||
  1098. Instance.getFrontendOpts().AllowPCMWithCompilerErrors;
  1099. }
  1100. static OptionalFileEntryRef getPublicModuleMap(FileEntryRef File,
  1101. FileManager &FileMgr) {
  1102. StringRef Filename = llvm::sys::path::filename(File.getName());
  1103. SmallString<128> PublicFilename(File.getDir().getName());
  1104. if (Filename == "module_private.map")
  1105. llvm::sys::path::append(PublicFilename, "module.map");
  1106. else if (Filename == "module.private.modulemap")
  1107. llvm::sys::path::append(PublicFilename, "module.modulemap");
  1108. else
  1109. return std::nullopt;
  1110. return FileMgr.getOptionalFileRef(PublicFilename);
  1111. }
  1112. /// Compile a module file for the given module in a separate compiler instance,
  1113. /// using the options provided by the importing compiler instance. Returns true
  1114. /// if the module was built without errors.
  1115. static bool compileModule(CompilerInstance &ImportingInstance,
  1116. SourceLocation ImportLoc, Module *Module,
  1117. StringRef ModuleFileName) {
  1118. InputKind IK(getLanguageFromOptions(ImportingInstance.getLangOpts()),
  1119. InputKind::ModuleMap);
  1120. // Get or create the module map that we'll use to build this module.
  1121. ModuleMap &ModMap
  1122. = ImportingInstance.getPreprocessor().getHeaderSearchInfo().getModuleMap();
  1123. bool Result;
  1124. if (OptionalFileEntryRef ModuleMapFile =
  1125. ModMap.getContainingModuleMapFile(Module)) {
  1126. // Canonicalize compilation to start with the public module map. This is
  1127. // vital for submodules declarations in the private module maps to be
  1128. // correctly parsed when depending on a top level module in the public one.
  1129. if (OptionalFileEntryRef PublicMMFile = getPublicModuleMap(
  1130. *ModuleMapFile, ImportingInstance.getFileManager()))
  1131. ModuleMapFile = PublicMMFile;
  1132. StringRef ModuleMapFilePath = ModuleMapFile->getNameAsRequested();
  1133. // Use the module map where this module resides.
  1134. Result = compileModuleImpl(
  1135. ImportingInstance, ImportLoc, Module->getTopLevelModuleName(),
  1136. FrontendInputFile(ModuleMapFilePath, IK, +Module->IsSystem),
  1137. ModMap.getModuleMapFileForUniquing(Module)->getName(), ModuleFileName);
  1138. } else {
  1139. // FIXME: We only need to fake up an input file here as a way of
  1140. // transporting the module's directory to the module map parser. We should
  1141. // be able to do that more directly, and parse from a memory buffer without
  1142. // inventing this file.
  1143. SmallString<128> FakeModuleMapFile(Module->Directory->getName());
  1144. llvm::sys::path::append(FakeModuleMapFile, "__inferred_module.map");
  1145. std::string InferredModuleMapContent;
  1146. llvm::raw_string_ostream OS(InferredModuleMapContent);
  1147. Module->print(OS);
  1148. OS.flush();
  1149. Result = compileModuleImpl(
  1150. ImportingInstance, ImportLoc, Module->getTopLevelModuleName(),
  1151. FrontendInputFile(FakeModuleMapFile, IK, +Module->IsSystem),
  1152. ModMap.getModuleMapFileForUniquing(Module)->getName(),
  1153. ModuleFileName,
  1154. [&](CompilerInstance &Instance) {
  1155. std::unique_ptr<llvm::MemoryBuffer> ModuleMapBuffer =
  1156. llvm::MemoryBuffer::getMemBuffer(InferredModuleMapContent);
  1157. const FileEntry *ModuleMapFile = Instance.getFileManager().getVirtualFile(
  1158. FakeModuleMapFile, InferredModuleMapContent.size(), 0);
  1159. Instance.getSourceManager().overrideFileContents(
  1160. ModuleMapFile, std::move(ModuleMapBuffer));
  1161. });
  1162. }
  1163. // We've rebuilt a module. If we're allowed to generate or update the global
  1164. // module index, record that fact in the importing compiler instance.
  1165. if (ImportingInstance.getFrontendOpts().GenerateGlobalModuleIndex) {
  1166. ImportingInstance.setBuildGlobalModuleIndex(true);
  1167. }
  1168. return Result;
  1169. }
  1170. /// Read the AST right after compiling the module.
  1171. static bool readASTAfterCompileModule(CompilerInstance &ImportingInstance,
  1172. SourceLocation ImportLoc,
  1173. SourceLocation ModuleNameLoc,
  1174. Module *Module, StringRef ModuleFileName,
  1175. bool *OutOfDate) {
  1176. DiagnosticsEngine &Diags = ImportingInstance.getDiagnostics();
  1177. unsigned ModuleLoadCapabilities = ASTReader::ARR_Missing;
  1178. if (OutOfDate)
  1179. ModuleLoadCapabilities |= ASTReader::ARR_OutOfDate;
  1180. // Try to read the module file, now that we've compiled it.
  1181. ASTReader::ASTReadResult ReadResult =
  1182. ImportingInstance.getASTReader()->ReadAST(
  1183. ModuleFileName, serialization::MK_ImplicitModule, ImportLoc,
  1184. ModuleLoadCapabilities);
  1185. if (ReadResult == ASTReader::Success)
  1186. return true;
  1187. // The caller wants to handle out-of-date failures.
  1188. if (OutOfDate && ReadResult == ASTReader::OutOfDate) {
  1189. *OutOfDate = true;
  1190. return false;
  1191. }
  1192. // The ASTReader didn't diagnose the error, so conservatively report it.
  1193. if (ReadResult == ASTReader::Missing || !Diags.hasErrorOccurred())
  1194. Diags.Report(ModuleNameLoc, diag::err_module_not_built)
  1195. << Module->Name << SourceRange(ImportLoc, ModuleNameLoc);
  1196. return false;
  1197. }
  1198. /// Compile a module in a separate compiler instance and read the AST,
  1199. /// returning true if the module compiles without errors.
  1200. static bool compileModuleAndReadASTImpl(CompilerInstance &ImportingInstance,
  1201. SourceLocation ImportLoc,
  1202. SourceLocation ModuleNameLoc,
  1203. Module *Module,
  1204. StringRef ModuleFileName) {
  1205. if (!compileModule(ImportingInstance, ModuleNameLoc, Module,
  1206. ModuleFileName)) {
  1207. ImportingInstance.getDiagnostics().Report(ModuleNameLoc,
  1208. diag::err_module_not_built)
  1209. << Module->Name << SourceRange(ImportLoc, ModuleNameLoc);
  1210. return false;
  1211. }
  1212. return readASTAfterCompileModule(ImportingInstance, ImportLoc, ModuleNameLoc,
  1213. Module, ModuleFileName,
  1214. /*OutOfDate=*/nullptr);
  1215. }
  1216. /// Compile a module in a separate compiler instance and read the AST,
  1217. /// returning true if the module compiles without errors, using a lock manager
  1218. /// to avoid building the same module in multiple compiler instances.
  1219. ///
  1220. /// Uses a lock file manager and exponential backoff to reduce the chances that
  1221. /// multiple instances will compete to create the same module. On timeout,
  1222. /// deletes the lock file in order to avoid deadlock from crashing processes or
  1223. /// bugs in the lock file manager.
  1224. static bool compileModuleAndReadASTBehindLock(
  1225. CompilerInstance &ImportingInstance, SourceLocation ImportLoc,
  1226. SourceLocation ModuleNameLoc, Module *Module, StringRef ModuleFileName) {
  1227. DiagnosticsEngine &Diags = ImportingInstance.getDiagnostics();
  1228. Diags.Report(ModuleNameLoc, diag::remark_module_lock)
  1229. << ModuleFileName << Module->Name;
  1230. // FIXME: have LockFileManager return an error_code so that we can
  1231. // avoid the mkdir when the directory already exists.
  1232. StringRef Dir = llvm::sys::path::parent_path(ModuleFileName);
  1233. llvm::sys::fs::create_directories(Dir);
  1234. while (true) {
  1235. llvm::LockFileManager Locked(ModuleFileName);
  1236. switch (Locked) {
  1237. case llvm::LockFileManager::LFS_Error:
  1238. // ModuleCache takes care of correctness and locks are only necessary for
  1239. // performance. Fallback to building the module in case of any lock
  1240. // related errors.
  1241. Diags.Report(ModuleNameLoc, diag::remark_module_lock_failure)
  1242. << Module->Name << Locked.getErrorMessage();
  1243. // Clear out any potential leftover.
  1244. Locked.unsafeRemoveLockFile();
  1245. [[fallthrough]];
  1246. case llvm::LockFileManager::LFS_Owned:
  1247. // We're responsible for building the module ourselves.
  1248. return compileModuleAndReadASTImpl(ImportingInstance, ImportLoc,
  1249. ModuleNameLoc, Module, ModuleFileName);
  1250. case llvm::LockFileManager::LFS_Shared:
  1251. break; // The interesting case.
  1252. }
  1253. // Someone else is responsible for building the module. Wait for them to
  1254. // finish.
  1255. switch (Locked.waitForUnlock()) {
  1256. case llvm::LockFileManager::Res_Success:
  1257. break; // The interesting case.
  1258. case llvm::LockFileManager::Res_OwnerDied:
  1259. continue; // try again to get the lock.
  1260. case llvm::LockFileManager::Res_Timeout:
  1261. // Since ModuleCache takes care of correctness, we try waiting for
  1262. // another process to complete the build so clang does not do it done
  1263. // twice. If case of timeout, build it ourselves.
  1264. Diags.Report(ModuleNameLoc, diag::remark_module_lock_timeout)
  1265. << Module->Name;
  1266. // Clear the lock file so that future invocations can make progress.
  1267. Locked.unsafeRemoveLockFile();
  1268. continue;
  1269. }
  1270. // Read the module that was just written by someone else.
  1271. bool OutOfDate = false;
  1272. if (readASTAfterCompileModule(ImportingInstance, ImportLoc, ModuleNameLoc,
  1273. Module, ModuleFileName, &OutOfDate))
  1274. return true;
  1275. if (!OutOfDate)
  1276. return false;
  1277. // The module may be out of date in the presence of file system races,
  1278. // or if one of its imports depends on header search paths that are not
  1279. // consistent with this ImportingInstance. Try again...
  1280. }
  1281. }
  1282. /// Compile a module in a separate compiler instance and read the AST,
  1283. /// returning true if the module compiles without errors, potentially using a
  1284. /// lock manager to avoid building the same module in multiple compiler
  1285. /// instances.
  1286. static bool compileModuleAndReadAST(CompilerInstance &ImportingInstance,
  1287. SourceLocation ImportLoc,
  1288. SourceLocation ModuleNameLoc,
  1289. Module *Module, StringRef ModuleFileName) {
  1290. return ImportingInstance.getInvocation()
  1291. .getFrontendOpts()
  1292. .BuildingImplicitModuleUsesLock
  1293. ? compileModuleAndReadASTBehindLock(ImportingInstance, ImportLoc,
  1294. ModuleNameLoc, Module,
  1295. ModuleFileName)
  1296. : compileModuleAndReadASTImpl(ImportingInstance, ImportLoc,
  1297. ModuleNameLoc, Module,
  1298. ModuleFileName);
  1299. }
  1300. /// Diagnose differences between the current definition of the given
  1301. /// configuration macro and the definition provided on the command line.
  1302. static void checkConfigMacro(Preprocessor &PP, StringRef ConfigMacro,
  1303. Module *Mod, SourceLocation ImportLoc) {
  1304. IdentifierInfo *Id = PP.getIdentifierInfo(ConfigMacro);
  1305. SourceManager &SourceMgr = PP.getSourceManager();
  1306. // If this identifier has never had a macro definition, then it could
  1307. // not have changed.
  1308. if (!Id->hadMacroDefinition())
  1309. return;
  1310. auto *LatestLocalMD = PP.getLocalMacroDirectiveHistory(Id);
  1311. // Find the macro definition from the command line.
  1312. MacroInfo *CmdLineDefinition = nullptr;
  1313. for (auto *MD = LatestLocalMD; MD; MD = MD->getPrevious()) {
  1314. // We only care about the predefines buffer.
  1315. FileID FID = SourceMgr.getFileID(MD->getLocation());
  1316. if (FID.isInvalid() || FID != PP.getPredefinesFileID())
  1317. continue;
  1318. if (auto *DMD = dyn_cast<DefMacroDirective>(MD))
  1319. CmdLineDefinition = DMD->getMacroInfo();
  1320. break;
  1321. }
  1322. auto *CurrentDefinition = PP.getMacroInfo(Id);
  1323. if (CurrentDefinition == CmdLineDefinition) {
  1324. // Macro matches. Nothing to do.
  1325. } else if (!CurrentDefinition) {
  1326. // This macro was defined on the command line, then #undef'd later.
  1327. // Complain.
  1328. PP.Diag(ImportLoc, diag::warn_module_config_macro_undef)
  1329. << true << ConfigMacro << Mod->getFullModuleName();
  1330. auto LatestDef = LatestLocalMD->getDefinition();
  1331. assert(LatestDef.isUndefined() &&
  1332. "predefined macro went away with no #undef?");
  1333. PP.Diag(LatestDef.getUndefLocation(), diag::note_module_def_undef_here)
  1334. << true;
  1335. return;
  1336. } else if (!CmdLineDefinition) {
  1337. // There was no definition for this macro in the predefines buffer,
  1338. // but there was a local definition. Complain.
  1339. PP.Diag(ImportLoc, diag::warn_module_config_macro_undef)
  1340. << false << ConfigMacro << Mod->getFullModuleName();
  1341. PP.Diag(CurrentDefinition->getDefinitionLoc(),
  1342. diag::note_module_def_undef_here)
  1343. << false;
  1344. } else if (!CurrentDefinition->isIdenticalTo(*CmdLineDefinition, PP,
  1345. /*Syntactically=*/true)) {
  1346. // The macro definitions differ.
  1347. PP.Diag(ImportLoc, diag::warn_module_config_macro_undef)
  1348. << false << ConfigMacro << Mod->getFullModuleName();
  1349. PP.Diag(CurrentDefinition->getDefinitionLoc(),
  1350. diag::note_module_def_undef_here)
  1351. << false;
  1352. }
  1353. }
  1354. /// Write a new timestamp file with the given path.
  1355. static void writeTimestampFile(StringRef TimestampFile) {
  1356. std::error_code EC;
  1357. llvm::raw_fd_ostream Out(TimestampFile.str(), EC, llvm::sys::fs::OF_None);
  1358. }
  1359. /// Prune the module cache of modules that haven't been accessed in
  1360. /// a long time.
  1361. static void pruneModuleCache(const HeaderSearchOptions &HSOpts) {
  1362. llvm::sys::fs::file_status StatBuf;
  1363. llvm::SmallString<128> TimestampFile;
  1364. TimestampFile = HSOpts.ModuleCachePath;
  1365. assert(!TimestampFile.empty());
  1366. llvm::sys::path::append(TimestampFile, "modules.timestamp");
  1367. // Try to stat() the timestamp file.
  1368. if (std::error_code EC = llvm::sys::fs::status(TimestampFile, StatBuf)) {
  1369. // If the timestamp file wasn't there, create one now.
  1370. if (EC == std::errc::no_such_file_or_directory) {
  1371. writeTimestampFile(TimestampFile);
  1372. }
  1373. return;
  1374. }
  1375. // Check whether the time stamp is older than our pruning interval.
  1376. // If not, do nothing.
  1377. time_t TimeStampModTime =
  1378. llvm::sys::toTimeT(StatBuf.getLastModificationTime());
  1379. time_t CurrentTime = time(nullptr);
  1380. if (CurrentTime - TimeStampModTime <= time_t(HSOpts.ModuleCachePruneInterval))
  1381. return;
  1382. // Write a new timestamp file so that nobody else attempts to prune.
  1383. // There is a benign race condition here, if two Clang instances happen to
  1384. // notice at the same time that the timestamp is out-of-date.
  1385. writeTimestampFile(TimestampFile);
  1386. // Walk the entire module cache, looking for unused module files and module
  1387. // indices.
  1388. std::error_code EC;
  1389. SmallString<128> ModuleCachePathNative;
  1390. llvm::sys::path::native(HSOpts.ModuleCachePath, ModuleCachePathNative);
  1391. for (llvm::sys::fs::directory_iterator Dir(ModuleCachePathNative, EC), DirEnd;
  1392. Dir != DirEnd && !EC; Dir.increment(EC)) {
  1393. // If we don't have a directory, there's nothing to look into.
  1394. if (!llvm::sys::fs::is_directory(Dir->path()))
  1395. continue;
  1396. // Walk all of the files within this directory.
  1397. for (llvm::sys::fs::directory_iterator File(Dir->path(), EC), FileEnd;
  1398. File != FileEnd && !EC; File.increment(EC)) {
  1399. // We only care about module and global module index files.
  1400. StringRef Extension = llvm::sys::path::extension(File->path());
  1401. if (Extension != ".pcm" && Extension != ".timestamp" &&
  1402. llvm::sys::path::filename(File->path()) != "modules.idx")
  1403. continue;
  1404. // Look at this file. If we can't stat it, there's nothing interesting
  1405. // there.
  1406. if (llvm::sys::fs::status(File->path(), StatBuf))
  1407. continue;
  1408. // If the file has been used recently enough, leave it there.
  1409. time_t FileAccessTime = llvm::sys::toTimeT(StatBuf.getLastAccessedTime());
  1410. if (CurrentTime - FileAccessTime <=
  1411. time_t(HSOpts.ModuleCachePruneAfter)) {
  1412. continue;
  1413. }
  1414. // Remove the file.
  1415. llvm::sys::fs::remove(File->path());
  1416. // Remove the timestamp file.
  1417. std::string TimpestampFilename = File->path() + ".timestamp";
  1418. llvm::sys::fs::remove(TimpestampFilename);
  1419. }
  1420. // If we removed all of the files in the directory, remove the directory
  1421. // itself.
  1422. if (llvm::sys::fs::directory_iterator(Dir->path(), EC) ==
  1423. llvm::sys::fs::directory_iterator() && !EC)
  1424. llvm::sys::fs::remove(Dir->path());
  1425. }
  1426. }
  1427. void CompilerInstance::createASTReader() {
  1428. if (TheASTReader)
  1429. return;
  1430. if (!hasASTContext())
  1431. createASTContext();
  1432. // If we're implicitly building modules but not currently recursively
  1433. // building a module, check whether we need to prune the module cache.
  1434. if (getSourceManager().getModuleBuildStack().empty() &&
  1435. !getPreprocessor().getHeaderSearchInfo().getModuleCachePath().empty() &&
  1436. getHeaderSearchOpts().ModuleCachePruneInterval > 0 &&
  1437. getHeaderSearchOpts().ModuleCachePruneAfter > 0) {
  1438. pruneModuleCache(getHeaderSearchOpts());
  1439. }
  1440. HeaderSearchOptions &HSOpts = getHeaderSearchOpts();
  1441. std::string Sysroot = HSOpts.Sysroot;
  1442. const PreprocessorOptions &PPOpts = getPreprocessorOpts();
  1443. const FrontendOptions &FEOpts = getFrontendOpts();
  1444. std::unique_ptr<llvm::Timer> ReadTimer;
  1445. if (FrontendTimerGroup)
  1446. ReadTimer = std::make_unique<llvm::Timer>("reading_modules",
  1447. "Reading modules",
  1448. *FrontendTimerGroup);
  1449. TheASTReader = new ASTReader(
  1450. getPreprocessor(), getModuleCache(), &getASTContext(),
  1451. getPCHContainerReader(), getFrontendOpts().ModuleFileExtensions,
  1452. Sysroot.empty() ? "" : Sysroot.c_str(),
  1453. PPOpts.DisablePCHOrModuleValidation,
  1454. /*AllowASTWithCompilerErrors=*/FEOpts.AllowPCMWithCompilerErrors,
  1455. /*AllowConfigurationMismatch=*/false, HSOpts.ModulesValidateSystemHeaders,
  1456. HSOpts.ValidateASTInputFilesContent,
  1457. getFrontendOpts().UseGlobalModuleIndex, std::move(ReadTimer));
  1458. if (hasASTConsumer()) {
  1459. TheASTReader->setDeserializationListener(
  1460. getASTConsumer().GetASTDeserializationListener());
  1461. getASTContext().setASTMutationListener(
  1462. getASTConsumer().GetASTMutationListener());
  1463. }
  1464. getASTContext().setExternalSource(TheASTReader);
  1465. if (hasSema())
  1466. TheASTReader->InitializeSema(getSema());
  1467. if (hasASTConsumer())
  1468. TheASTReader->StartTranslationUnit(&getASTConsumer());
  1469. for (auto &Listener : DependencyCollectors)
  1470. Listener->attachToASTReader(*TheASTReader);
  1471. }
  1472. bool CompilerInstance::loadModuleFile(StringRef FileName) {
  1473. llvm::Timer Timer;
  1474. if (FrontendTimerGroup)
  1475. Timer.init("preloading." + FileName.str(), "Preloading " + FileName.str(),
  1476. *FrontendTimerGroup);
  1477. llvm::TimeRegion TimeLoading(FrontendTimerGroup ? &Timer : nullptr);
  1478. // If we don't already have an ASTReader, create one now.
  1479. if (!TheASTReader)
  1480. createASTReader();
  1481. // If -Wmodule-file-config-mismatch is mapped as an error or worse, allow the
  1482. // ASTReader to diagnose it, since it can produce better errors that we can.
  1483. bool ConfigMismatchIsRecoverable =
  1484. getDiagnostics().getDiagnosticLevel(diag::warn_module_config_mismatch,
  1485. SourceLocation())
  1486. <= DiagnosticsEngine::Warning;
  1487. auto Listener = std::make_unique<ReadModuleNames>(*PP);
  1488. auto &ListenerRef = *Listener;
  1489. ASTReader::ListenerScope ReadModuleNamesListener(*TheASTReader,
  1490. std::move(Listener));
  1491. // Try to load the module file.
  1492. switch (TheASTReader->ReadAST(
  1493. FileName, serialization::MK_ExplicitModule, SourceLocation(),
  1494. ConfigMismatchIsRecoverable ? ASTReader::ARR_ConfigurationMismatch : 0)) {
  1495. case ASTReader::Success:
  1496. // We successfully loaded the module file; remember the set of provided
  1497. // modules so that we don't try to load implicit modules for them.
  1498. ListenerRef.registerAll();
  1499. return true;
  1500. case ASTReader::ConfigurationMismatch:
  1501. // Ignore unusable module files.
  1502. getDiagnostics().Report(SourceLocation(), diag::warn_module_config_mismatch)
  1503. << FileName;
  1504. // All modules provided by any files we tried and failed to load are now
  1505. // unavailable; includes of those modules should now be handled textually.
  1506. ListenerRef.markAllUnavailable();
  1507. return true;
  1508. default:
  1509. return false;
  1510. }
  1511. }
  1512. namespace {
  1513. enum ModuleSource {
  1514. MS_ModuleNotFound,
  1515. MS_ModuleCache,
  1516. MS_PrebuiltModulePath,
  1517. MS_ModuleBuildPragma
  1518. };
  1519. } // end namespace
  1520. /// Select a source for loading the named module and compute the filename to
  1521. /// load it from.
  1522. static ModuleSource selectModuleSource(
  1523. Module *M, StringRef ModuleName, std::string &ModuleFilename,
  1524. const std::map<std::string, std::string, std::less<>> &BuiltModules,
  1525. HeaderSearch &HS) {
  1526. assert(ModuleFilename.empty() && "Already has a module source?");
  1527. // Check to see if the module has been built as part of this compilation
  1528. // via a module build pragma.
  1529. auto BuiltModuleIt = BuiltModules.find(ModuleName);
  1530. if (BuiltModuleIt != BuiltModules.end()) {
  1531. ModuleFilename = BuiltModuleIt->second;
  1532. return MS_ModuleBuildPragma;
  1533. }
  1534. // Try to load the module from the prebuilt module path.
  1535. const HeaderSearchOptions &HSOpts = HS.getHeaderSearchOpts();
  1536. if (!HSOpts.PrebuiltModuleFiles.empty() ||
  1537. !HSOpts.PrebuiltModulePaths.empty()) {
  1538. ModuleFilename = HS.getPrebuiltModuleFileName(ModuleName);
  1539. if (HSOpts.EnablePrebuiltImplicitModules && ModuleFilename.empty())
  1540. ModuleFilename = HS.getPrebuiltImplicitModuleFileName(M);
  1541. if (!ModuleFilename.empty())
  1542. return MS_PrebuiltModulePath;
  1543. }
  1544. // Try to load the module from the module cache.
  1545. if (M) {
  1546. ModuleFilename = HS.getCachedModuleFileName(M);
  1547. return MS_ModuleCache;
  1548. }
  1549. return MS_ModuleNotFound;
  1550. }
  1551. ModuleLoadResult CompilerInstance::findOrCompileModuleAndReadAST(
  1552. StringRef ModuleName, SourceLocation ImportLoc,
  1553. SourceLocation ModuleNameLoc, bool IsInclusionDirective) {
  1554. // Search for a module with the given name.
  1555. HeaderSearch &HS = PP->getHeaderSearchInfo();
  1556. Module *M =
  1557. HS.lookupModule(ModuleName, ImportLoc, true, !IsInclusionDirective);
  1558. // Select the source and filename for loading the named module.
  1559. std::string ModuleFilename;
  1560. ModuleSource Source =
  1561. selectModuleSource(M, ModuleName, ModuleFilename, BuiltModules, HS);
  1562. if (Source == MS_ModuleNotFound) {
  1563. // We can't find a module, error out here.
  1564. getDiagnostics().Report(ModuleNameLoc, diag::err_module_not_found)
  1565. << ModuleName << SourceRange(ImportLoc, ModuleNameLoc);
  1566. return nullptr;
  1567. }
  1568. if (ModuleFilename.empty()) {
  1569. if (M && M->HasIncompatibleModuleFile) {
  1570. // We tried and failed to load a module file for this module. Fall
  1571. // back to textual inclusion for its headers.
  1572. return ModuleLoadResult::ConfigMismatch;
  1573. }
  1574. getDiagnostics().Report(ModuleNameLoc, diag::err_module_build_disabled)
  1575. << ModuleName;
  1576. return nullptr;
  1577. }
  1578. // Create an ASTReader on demand.
  1579. if (!getASTReader())
  1580. createASTReader();
  1581. // Time how long it takes to load the module.
  1582. llvm::Timer Timer;
  1583. if (FrontendTimerGroup)
  1584. Timer.init("loading." + ModuleFilename, "Loading " + ModuleFilename,
  1585. *FrontendTimerGroup);
  1586. llvm::TimeRegion TimeLoading(FrontendTimerGroup ? &Timer : nullptr);
  1587. llvm::TimeTraceScope TimeScope("Module Load", ModuleName);
  1588. // Try to load the module file. If we are not trying to load from the
  1589. // module cache, we don't know how to rebuild modules.
  1590. unsigned ARRFlags = Source == MS_ModuleCache
  1591. ? ASTReader::ARR_OutOfDate | ASTReader::ARR_Missing |
  1592. ASTReader::ARR_TreatModuleWithErrorsAsOutOfDate
  1593. : Source == MS_PrebuiltModulePath
  1594. ? 0
  1595. : ASTReader::ARR_ConfigurationMismatch;
  1596. switch (getASTReader()->ReadAST(ModuleFilename,
  1597. Source == MS_PrebuiltModulePath
  1598. ? serialization::MK_PrebuiltModule
  1599. : Source == MS_ModuleBuildPragma
  1600. ? serialization::MK_ExplicitModule
  1601. : serialization::MK_ImplicitModule,
  1602. ImportLoc, ARRFlags)) {
  1603. case ASTReader::Success: {
  1604. if (M)
  1605. return M;
  1606. assert(Source != MS_ModuleCache &&
  1607. "missing module, but file loaded from cache");
  1608. // A prebuilt module is indexed as a ModuleFile; the Module does not exist
  1609. // until the first call to ReadAST. Look it up now.
  1610. M = HS.lookupModule(ModuleName, ImportLoc, true, !IsInclusionDirective);
  1611. // Check whether M refers to the file in the prebuilt module path.
  1612. if (M && M->getASTFile())
  1613. if (auto ModuleFile = FileMgr->getFile(ModuleFilename))
  1614. if (*ModuleFile == M->getASTFile())
  1615. return M;
  1616. getDiagnostics().Report(ModuleNameLoc, diag::err_module_prebuilt)
  1617. << ModuleName;
  1618. return ModuleLoadResult();
  1619. }
  1620. case ASTReader::OutOfDate:
  1621. case ASTReader::Missing:
  1622. // The most interesting case.
  1623. break;
  1624. case ASTReader::ConfigurationMismatch:
  1625. if (Source == MS_PrebuiltModulePath)
  1626. // FIXME: We shouldn't be setting HadFatalFailure below if we only
  1627. // produce a warning here!
  1628. getDiagnostics().Report(SourceLocation(),
  1629. diag::warn_module_config_mismatch)
  1630. << ModuleFilename;
  1631. // Fall through to error out.
  1632. [[fallthrough]];
  1633. case ASTReader::VersionMismatch:
  1634. case ASTReader::HadErrors:
  1635. ModuleLoader::HadFatalFailure = true;
  1636. // FIXME: The ASTReader will already have complained, but can we shoehorn
  1637. // that diagnostic information into a more useful form?
  1638. return ModuleLoadResult();
  1639. case ASTReader::Failure:
  1640. ModuleLoader::HadFatalFailure = true;
  1641. return ModuleLoadResult();
  1642. }
  1643. // ReadAST returned Missing or OutOfDate.
  1644. if (Source != MS_ModuleCache) {
  1645. // We don't know the desired configuration for this module and don't
  1646. // necessarily even have a module map. Since ReadAST already produces
  1647. // diagnostics for these two cases, we simply error out here.
  1648. return ModuleLoadResult();
  1649. }
  1650. // The module file is missing or out-of-date. Build it.
  1651. assert(M && "missing module, but trying to compile for cache");
  1652. // Check whether there is a cycle in the module graph.
  1653. ModuleBuildStack ModPath = getSourceManager().getModuleBuildStack();
  1654. ModuleBuildStack::iterator Pos = ModPath.begin(), PosEnd = ModPath.end();
  1655. for (; Pos != PosEnd; ++Pos) {
  1656. if (Pos->first == ModuleName)
  1657. break;
  1658. }
  1659. if (Pos != PosEnd) {
  1660. SmallString<256> CyclePath;
  1661. for (; Pos != PosEnd; ++Pos) {
  1662. CyclePath += Pos->first;
  1663. CyclePath += " -> ";
  1664. }
  1665. CyclePath += ModuleName;
  1666. getDiagnostics().Report(ModuleNameLoc, diag::err_module_cycle)
  1667. << ModuleName << CyclePath;
  1668. return nullptr;
  1669. }
  1670. // Check whether we have already attempted to build this module (but
  1671. // failed).
  1672. if (getPreprocessorOpts().FailedModules &&
  1673. getPreprocessorOpts().FailedModules->hasAlreadyFailed(ModuleName)) {
  1674. getDiagnostics().Report(ModuleNameLoc, diag::err_module_not_built)
  1675. << ModuleName << SourceRange(ImportLoc, ModuleNameLoc);
  1676. return nullptr;
  1677. }
  1678. // Try to compile and then read the AST.
  1679. if (!compileModuleAndReadAST(*this, ImportLoc, ModuleNameLoc, M,
  1680. ModuleFilename)) {
  1681. assert(getDiagnostics().hasErrorOccurred() &&
  1682. "undiagnosed error in compileModuleAndReadAST");
  1683. if (getPreprocessorOpts().FailedModules)
  1684. getPreprocessorOpts().FailedModules->addFailed(ModuleName);
  1685. return nullptr;
  1686. }
  1687. // Okay, we've rebuilt and now loaded the module.
  1688. return M;
  1689. }
  1690. ModuleLoadResult
  1691. CompilerInstance::loadModule(SourceLocation ImportLoc,
  1692. ModuleIdPath Path,
  1693. Module::NameVisibilityKind Visibility,
  1694. bool IsInclusionDirective) {
  1695. // Determine what file we're searching from.
  1696. StringRef ModuleName = Path[0].first->getName();
  1697. SourceLocation ModuleNameLoc = Path[0].second;
  1698. // If we've already handled this import, just return the cached result.
  1699. // This one-element cache is important to eliminate redundant diagnostics
  1700. // when both the preprocessor and parser see the same import declaration.
  1701. if (ImportLoc.isValid() && LastModuleImportLoc == ImportLoc) {
  1702. // Make the named module visible.
  1703. if (LastModuleImportResult && ModuleName != getLangOpts().CurrentModule)
  1704. TheASTReader->makeModuleVisible(LastModuleImportResult, Visibility,
  1705. ImportLoc);
  1706. return LastModuleImportResult;
  1707. }
  1708. // If we don't already have information on this module, load the module now.
  1709. Module *Module = nullptr;
  1710. ModuleMap &MM = getPreprocessor().getHeaderSearchInfo().getModuleMap();
  1711. if (auto MaybeModule = MM.getCachedModuleLoad(*Path[0].first)) {
  1712. // Use the cached result, which may be nullptr.
  1713. Module = *MaybeModule;
  1714. } else if (ModuleName == getLangOpts().CurrentModule) {
  1715. // This is the module we're building.
  1716. Module = PP->getHeaderSearchInfo().lookupModule(
  1717. ModuleName, ImportLoc, /*AllowSearch*/ true,
  1718. /*AllowExtraModuleMapSearch*/ !IsInclusionDirective);
  1719. MM.cacheModuleLoad(*Path[0].first, Module);
  1720. } else {
  1721. ModuleLoadResult Result = findOrCompileModuleAndReadAST(
  1722. ModuleName, ImportLoc, ModuleNameLoc, IsInclusionDirective);
  1723. if (!Result.isNormal())
  1724. return Result;
  1725. if (!Result)
  1726. DisableGeneratingGlobalModuleIndex = true;
  1727. Module = Result;
  1728. MM.cacheModuleLoad(*Path[0].first, Module);
  1729. }
  1730. // If we never found the module, fail. Otherwise, verify the module and link
  1731. // it up.
  1732. if (!Module)
  1733. return ModuleLoadResult();
  1734. // Verify that the rest of the module path actually corresponds to
  1735. // a submodule.
  1736. bool MapPrivateSubModToTopLevel = false;
  1737. for (unsigned I = 1, N = Path.size(); I != N; ++I) {
  1738. StringRef Name = Path[I].first->getName();
  1739. clang::Module *Sub = Module->findSubmodule(Name);
  1740. // If the user is requesting Foo.Private and it doesn't exist, try to
  1741. // match Foo_Private and emit a warning asking for the user to write
  1742. // @import Foo_Private instead. FIXME: remove this when existing clients
  1743. // migrate off of Foo.Private syntax.
  1744. if (!Sub && Name == "Private" && Module == Module->getTopLevelModule()) {
  1745. SmallString<128> PrivateModule(Module->Name);
  1746. PrivateModule.append("_Private");
  1747. SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> PrivPath;
  1748. auto &II = PP->getIdentifierTable().get(
  1749. PrivateModule, PP->getIdentifierInfo(Module->Name)->getTokenID());
  1750. PrivPath.push_back(std::make_pair(&II, Path[0].second));
  1751. if (PP->getHeaderSearchInfo().lookupModule(PrivateModule, ImportLoc, true,
  1752. !IsInclusionDirective))
  1753. Sub = loadModule(ImportLoc, PrivPath, Visibility, IsInclusionDirective);
  1754. if (Sub) {
  1755. MapPrivateSubModToTopLevel = true;
  1756. PP->markClangModuleAsAffecting(Module);
  1757. if (!getDiagnostics().isIgnored(
  1758. diag::warn_no_priv_submodule_use_toplevel, ImportLoc)) {
  1759. getDiagnostics().Report(Path[I].second,
  1760. diag::warn_no_priv_submodule_use_toplevel)
  1761. << Path[I].first << Module->getFullModuleName() << PrivateModule
  1762. << SourceRange(Path[0].second, Path[I].second)
  1763. << FixItHint::CreateReplacement(SourceRange(Path[0].second),
  1764. PrivateModule);
  1765. getDiagnostics().Report(Sub->DefinitionLoc,
  1766. diag::note_private_top_level_defined);
  1767. }
  1768. }
  1769. }
  1770. if (!Sub) {
  1771. // Attempt to perform typo correction to find a module name that works.
  1772. SmallVector<StringRef, 2> Best;
  1773. unsigned BestEditDistance = (std::numeric_limits<unsigned>::max)();
  1774. for (class Module *SubModule : Module->submodules()) {
  1775. unsigned ED =
  1776. Name.edit_distance(SubModule->Name,
  1777. /*AllowReplacements=*/true, BestEditDistance);
  1778. if (ED <= BestEditDistance) {
  1779. if (ED < BestEditDistance) {
  1780. Best.clear();
  1781. BestEditDistance = ED;
  1782. }
  1783. Best.push_back(SubModule->Name);
  1784. }
  1785. }
  1786. // If there was a clear winner, user it.
  1787. if (Best.size() == 1) {
  1788. getDiagnostics().Report(Path[I].second, diag::err_no_submodule_suggest)
  1789. << Path[I].first << Module->getFullModuleName() << Best[0]
  1790. << SourceRange(Path[0].second, Path[I - 1].second)
  1791. << FixItHint::CreateReplacement(SourceRange(Path[I].second),
  1792. Best[0]);
  1793. Sub = Module->findSubmodule(Best[0]);
  1794. }
  1795. }
  1796. if (!Sub) {
  1797. // No submodule by this name. Complain, and don't look for further
  1798. // submodules.
  1799. getDiagnostics().Report(Path[I].second, diag::err_no_submodule)
  1800. << Path[I].first << Module->getFullModuleName()
  1801. << SourceRange(Path[0].second, Path[I - 1].second);
  1802. break;
  1803. }
  1804. Module = Sub;
  1805. }
  1806. // Make the named module visible, if it's not already part of the module
  1807. // we are parsing.
  1808. if (ModuleName != getLangOpts().CurrentModule) {
  1809. if (!Module->IsFromModuleFile && !MapPrivateSubModToTopLevel) {
  1810. // We have an umbrella header or directory that doesn't actually include
  1811. // all of the headers within the directory it covers. Complain about
  1812. // this missing submodule and recover by forgetting that we ever saw
  1813. // this submodule.
  1814. // FIXME: Should we detect this at module load time? It seems fairly
  1815. // expensive (and rare).
  1816. getDiagnostics().Report(ImportLoc, diag::warn_missing_submodule)
  1817. << Module->getFullModuleName()
  1818. << SourceRange(Path.front().second, Path.back().second);
  1819. return ModuleLoadResult(Module, ModuleLoadResult::MissingExpected);
  1820. }
  1821. // Check whether this module is available.
  1822. if (Preprocessor::checkModuleIsAvailable(getLangOpts(), getTarget(),
  1823. getDiagnostics(), Module)) {
  1824. getDiagnostics().Report(ImportLoc, diag::note_module_import_here)
  1825. << SourceRange(Path.front().second, Path.back().second);
  1826. LastModuleImportLoc = ImportLoc;
  1827. LastModuleImportResult = ModuleLoadResult();
  1828. return ModuleLoadResult();
  1829. }
  1830. TheASTReader->makeModuleVisible(Module, Visibility, ImportLoc);
  1831. }
  1832. // Check for any configuration macros that have changed.
  1833. clang::Module *TopModule = Module->getTopLevelModule();
  1834. for (unsigned I = 0, N = TopModule->ConfigMacros.size(); I != N; ++I) {
  1835. checkConfigMacro(getPreprocessor(), TopModule->ConfigMacros[I],
  1836. Module, ImportLoc);
  1837. }
  1838. // Resolve any remaining module using export_as for this one.
  1839. getPreprocessor()
  1840. .getHeaderSearchInfo()
  1841. .getModuleMap()
  1842. .resolveLinkAsDependencies(TopModule);
  1843. LastModuleImportLoc = ImportLoc;
  1844. LastModuleImportResult = ModuleLoadResult(Module);
  1845. return LastModuleImportResult;
  1846. }
  1847. void CompilerInstance::createModuleFromSource(SourceLocation ImportLoc,
  1848. StringRef ModuleName,
  1849. StringRef Source) {
  1850. // Avoid creating filenames with special characters.
  1851. SmallString<128> CleanModuleName(ModuleName);
  1852. for (auto &C : CleanModuleName)
  1853. if (!isAlphanumeric(C))
  1854. C = '_';
  1855. // FIXME: Using a randomized filename here means that our intermediate .pcm
  1856. // output is nondeterministic (as .pcm files refer to each other by name).
  1857. // Can this affect the output in any way?
  1858. SmallString<128> ModuleFileName;
  1859. if (std::error_code EC = llvm::sys::fs::createTemporaryFile(
  1860. CleanModuleName, "pcm", ModuleFileName)) {
  1861. getDiagnostics().Report(ImportLoc, diag::err_fe_unable_to_open_output)
  1862. << ModuleFileName << EC.message();
  1863. return;
  1864. }
  1865. std::string ModuleMapFileName = (CleanModuleName + ".map").str();
  1866. FrontendInputFile Input(
  1867. ModuleMapFileName,
  1868. InputKind(getLanguageFromOptions(*Invocation->getLangOpts()),
  1869. InputKind::ModuleMap, /*Preprocessed*/true));
  1870. std::string NullTerminatedSource(Source.str());
  1871. auto PreBuildStep = [&](CompilerInstance &Other) {
  1872. // Create a virtual file containing our desired source.
  1873. // FIXME: We shouldn't need to do this.
  1874. const FileEntry *ModuleMapFile = Other.getFileManager().getVirtualFile(
  1875. ModuleMapFileName, NullTerminatedSource.size(), 0);
  1876. Other.getSourceManager().overrideFileContents(
  1877. ModuleMapFile, llvm::MemoryBuffer::getMemBuffer(NullTerminatedSource));
  1878. Other.BuiltModules = std::move(BuiltModules);
  1879. Other.DeleteBuiltModules = false;
  1880. };
  1881. auto PostBuildStep = [this](CompilerInstance &Other) {
  1882. BuiltModules = std::move(Other.BuiltModules);
  1883. };
  1884. // Build the module, inheriting any modules that we've built locally.
  1885. if (compileModuleImpl(*this, ImportLoc, ModuleName, Input, StringRef(),
  1886. ModuleFileName, PreBuildStep, PostBuildStep)) {
  1887. BuiltModules[std::string(ModuleName)] = std::string(ModuleFileName.str());
  1888. llvm::sys::RemoveFileOnSignal(ModuleFileName);
  1889. }
  1890. }
  1891. void CompilerInstance::makeModuleVisible(Module *Mod,
  1892. Module::NameVisibilityKind Visibility,
  1893. SourceLocation ImportLoc) {
  1894. if (!TheASTReader)
  1895. createASTReader();
  1896. if (!TheASTReader)
  1897. return;
  1898. TheASTReader->makeModuleVisible(Mod, Visibility, ImportLoc);
  1899. }
  1900. GlobalModuleIndex *CompilerInstance::loadGlobalModuleIndex(
  1901. SourceLocation TriggerLoc) {
  1902. if (getPreprocessor().getHeaderSearchInfo().getModuleCachePath().empty())
  1903. return nullptr;
  1904. if (!TheASTReader)
  1905. createASTReader();
  1906. // Can't do anything if we don't have the module manager.
  1907. if (!TheASTReader)
  1908. return nullptr;
  1909. // Get an existing global index. This loads it if not already
  1910. // loaded.
  1911. TheASTReader->loadGlobalIndex();
  1912. GlobalModuleIndex *GlobalIndex = TheASTReader->getGlobalIndex();
  1913. // If the global index doesn't exist, create it.
  1914. if (!GlobalIndex && shouldBuildGlobalModuleIndex() && hasFileManager() &&
  1915. hasPreprocessor()) {
  1916. llvm::sys::fs::create_directories(
  1917. getPreprocessor().getHeaderSearchInfo().getModuleCachePath());
  1918. if (llvm::Error Err = GlobalModuleIndex::writeIndex(
  1919. getFileManager(), getPCHContainerReader(),
  1920. getPreprocessor().getHeaderSearchInfo().getModuleCachePath())) {
  1921. // FIXME this drops the error on the floor. This code is only used for
  1922. // typo correction and drops more than just this one source of errors
  1923. // (such as the directory creation failure above). It should handle the
  1924. // error.
  1925. consumeError(std::move(Err));
  1926. return nullptr;
  1927. }
  1928. TheASTReader->resetForReload();
  1929. TheASTReader->loadGlobalIndex();
  1930. GlobalIndex = TheASTReader->getGlobalIndex();
  1931. }
  1932. // For finding modules needing to be imported for fixit messages,
  1933. // we need to make the global index cover all modules, so we do that here.
  1934. if (!HaveFullGlobalModuleIndex && GlobalIndex && !buildingModule()) {
  1935. ModuleMap &MMap = getPreprocessor().getHeaderSearchInfo().getModuleMap();
  1936. bool RecreateIndex = false;
  1937. for (ModuleMap::module_iterator I = MMap.module_begin(),
  1938. E = MMap.module_end(); I != E; ++I) {
  1939. Module *TheModule = I->second;
  1940. const FileEntry *Entry = TheModule->getASTFile();
  1941. if (!Entry) {
  1942. SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path;
  1943. Path.push_back(std::make_pair(
  1944. getPreprocessor().getIdentifierInfo(TheModule->Name), TriggerLoc));
  1945. std::reverse(Path.begin(), Path.end());
  1946. // Load a module as hidden. This also adds it to the global index.
  1947. loadModule(TheModule->DefinitionLoc, Path, Module::Hidden, false);
  1948. RecreateIndex = true;
  1949. }
  1950. }
  1951. if (RecreateIndex) {
  1952. if (llvm::Error Err = GlobalModuleIndex::writeIndex(
  1953. getFileManager(), getPCHContainerReader(),
  1954. getPreprocessor().getHeaderSearchInfo().getModuleCachePath())) {
  1955. // FIXME As above, this drops the error on the floor.
  1956. consumeError(std::move(Err));
  1957. return nullptr;
  1958. }
  1959. TheASTReader->resetForReload();
  1960. TheASTReader->loadGlobalIndex();
  1961. GlobalIndex = TheASTReader->getGlobalIndex();
  1962. }
  1963. HaveFullGlobalModuleIndex = true;
  1964. }
  1965. return GlobalIndex;
  1966. }
  1967. // Check global module index for missing imports.
  1968. bool
  1969. CompilerInstance::lookupMissingImports(StringRef Name,
  1970. SourceLocation TriggerLoc) {
  1971. // Look for the symbol in non-imported modules, but only if an error
  1972. // actually occurred.
  1973. if (!buildingModule()) {
  1974. // Load global module index, or retrieve a previously loaded one.
  1975. GlobalModuleIndex *GlobalIndex = loadGlobalModuleIndex(
  1976. TriggerLoc);
  1977. // Only if we have a global index.
  1978. if (GlobalIndex) {
  1979. GlobalModuleIndex::HitSet FoundModules;
  1980. // Find the modules that reference the identifier.
  1981. // Note that this only finds top-level modules.
  1982. // We'll let diagnoseTypo find the actual declaration module.
  1983. if (GlobalIndex->lookupIdentifier(Name, FoundModules))
  1984. return true;
  1985. }
  1986. }
  1987. return false;
  1988. }
  1989. void CompilerInstance::resetAndLeakSema() { llvm::BuryPointer(takeSema()); }
  1990. void CompilerInstance::setExternalSemaSource(
  1991. IntrusiveRefCntPtr<ExternalSemaSource> ESS) {
  1992. ExternalSemaSrc = std::move(ESS);
  1993. }