CompilerInstance.cpp 82 KB

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