CompilerInstance.cpp 66 KB

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