CompilerInstance.cpp 62 KB

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