CompilerInstance.cpp 80 KB

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