CompilerInstance.cpp 82 KB

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