CompilerInstance.cpp 82 KB

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