CompilerInstance.cpp 66 KB

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