CompilerInstance.cpp 82 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133
  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 = llvm::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 = llvm::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 llvm::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 = llvm::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.getFile(InputFile, /*OpenFile=*/true);
  717. if (!FileOrErr) {
  718. Diags.Report(diag::err_fe_error_reading) << InputFile;
  719. return false;
  720. }
  721. auto 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->isNamedPipe()) {
  728. auto MB = FileMgr.getBufferForFile(File, /*isVolatile=*/true);
  729. if (MB) {
  730. // Create a new virtual file that will have the correct size.
  731. File = FileMgr.getVirtualFile(InputFile, (*MB)->getBufferSize(), 0);
  732. SourceMgr.overrideFileContents(File, std::move(*MB));
  733. } else {
  734. Diags.Report(diag::err_cannot_open_file) << InputFile
  735. << MB.getError().message();
  736. return false;
  737. }
  738. }
  739. SourceMgr.setMainFileID(
  740. SourceMgr.createFileID(File, SourceLocation(), Kind));
  741. } else {
  742. llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> SBOrErr =
  743. llvm::MemoryBuffer::getSTDIN();
  744. if (std::error_code EC = SBOrErr.getError()) {
  745. Diags.Report(diag::err_fe_error_reading_stdin) << EC.message();
  746. return false;
  747. }
  748. std::unique_ptr<llvm::MemoryBuffer> SB = std::move(SBOrErr.get());
  749. const FileEntry *File = FileMgr.getVirtualFile(SB->getBufferIdentifier(),
  750. SB->getBufferSize(), 0);
  751. SourceMgr.setMainFileID(
  752. SourceMgr.createFileID(File, SourceLocation(), Kind));
  753. SourceMgr.overrideFileContents(File, std::move(SB));
  754. }
  755. assert(SourceMgr.getMainFileID().isValid() &&
  756. "Couldn't establish MainFileID!");
  757. return true;
  758. }
  759. // High-Level Operations
  760. bool CompilerInstance::ExecuteAction(FrontendAction &Act) {
  761. assert(hasDiagnostics() && "Diagnostics engine is not initialized!");
  762. assert(!getFrontendOpts().ShowHelp && "Client must handle '-help'!");
  763. assert(!getFrontendOpts().ShowVersion && "Client must handle '-version'!");
  764. // FIXME: Take this as an argument, once all the APIs we used have moved to
  765. // taking it as an input instead of hard-coding llvm::errs.
  766. raw_ostream &OS = llvm::errs();
  767. if (!Act.PrepareToExecute(*this))
  768. return false;
  769. // Create the target instance.
  770. setTarget(TargetInfo::CreateTargetInfo(getDiagnostics(),
  771. getInvocation().TargetOpts));
  772. if (!hasTarget())
  773. return false;
  774. // Create TargetInfo for the other side of CUDA and OpenMP compilation.
  775. if ((getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) &&
  776. !getFrontendOpts().AuxTriple.empty()) {
  777. auto TO = std::make_shared<TargetOptions>();
  778. TO->Triple = llvm::Triple::normalize(getFrontendOpts().AuxTriple);
  779. TO->HostTriple = getTarget().getTriple().str();
  780. setAuxTarget(TargetInfo::CreateTargetInfo(getDiagnostics(), TO));
  781. }
  782. // Inform the target of the language options.
  783. //
  784. // FIXME: We shouldn't need to do this, the target should be immutable once
  785. // created. This complexity should be lifted elsewhere.
  786. getTarget().adjust(getLangOpts());
  787. // Adjust target options based on codegen options.
  788. getTarget().adjustTargetOptions(getCodeGenOpts(), getTargetOpts());
  789. if (auto *Aux = getAuxTarget())
  790. getTarget().setAuxTarget(Aux);
  791. // rewriter project will change target built-in bool type from its default.
  792. if (getFrontendOpts().ProgramAction == frontend::RewriteObjC)
  793. getTarget().noSignedCharForObjCBool();
  794. // Validate/process some options.
  795. if (getHeaderSearchOpts().Verbose)
  796. OS << "clang -cc1 version " CLANG_VERSION_STRING
  797. << " based upon " << BACKEND_PACKAGE_STRING
  798. << " default target " << llvm::sys::getDefaultTargetTriple() << "\n";
  799. if (getFrontendOpts().ShowTimers)
  800. createFrontendTimer();
  801. if (getFrontendOpts().ShowStats || !getFrontendOpts().StatsFile.empty())
  802. llvm::EnableStatistics(false);
  803. for (const FrontendInputFile &FIF : getFrontendOpts().Inputs) {
  804. // Reset the ID tables if we are reusing the SourceManager and parsing
  805. // regular files.
  806. if (hasSourceManager() && !Act.isModelParsingAction())
  807. getSourceManager().clearIDTables();
  808. if (Act.BeginSourceFile(*this, FIF)) {
  809. if (llvm::Error Err = Act.Execute()) {
  810. consumeError(std::move(Err)); // FIXME this drops errors on the floor.
  811. }
  812. Act.EndSourceFile();
  813. }
  814. }
  815. // Notify the diagnostic client that all files were processed.
  816. getDiagnostics().getClient()->finish();
  817. if (getDiagnosticOpts().ShowCarets) {
  818. // We can have multiple diagnostics sharing one diagnostic client.
  819. // Get the total number of warnings/errors from the client.
  820. unsigned NumWarnings = getDiagnostics().getClient()->getNumWarnings();
  821. unsigned NumErrors = getDiagnostics().getClient()->getNumErrors();
  822. if (NumWarnings)
  823. OS << NumWarnings << " warning" << (NumWarnings == 1 ? "" : "s");
  824. if (NumWarnings && NumErrors)
  825. OS << " and ";
  826. if (NumErrors)
  827. OS << NumErrors << " error" << (NumErrors == 1 ? "" : "s");
  828. if (NumWarnings || NumErrors) {
  829. OS << " generated";
  830. if (getLangOpts().CUDA) {
  831. if (!getLangOpts().CUDAIsDevice) {
  832. OS << " when compiling for host";
  833. } else {
  834. OS << " when compiling for " << getTargetOpts().CPU;
  835. }
  836. }
  837. OS << ".\n";
  838. }
  839. }
  840. if (getFrontendOpts().ShowStats) {
  841. if (hasFileManager()) {
  842. getFileManager().PrintStats();
  843. OS << '\n';
  844. }
  845. llvm::PrintStatistics(OS);
  846. }
  847. StringRef StatsFile = getFrontendOpts().StatsFile;
  848. if (!StatsFile.empty()) {
  849. std::error_code EC;
  850. auto StatS = llvm::make_unique<llvm::raw_fd_ostream>(
  851. StatsFile, EC, llvm::sys::fs::OF_Text);
  852. if (EC) {
  853. getDiagnostics().Report(diag::warn_fe_unable_to_open_stats_file)
  854. << StatsFile << EC.message();
  855. } else {
  856. llvm::PrintStatisticsJSON(*StatS);
  857. }
  858. }
  859. return !getDiagnostics().getClient()->getNumErrors();
  860. }
  861. /// Determine the appropriate source input kind based on language
  862. /// options.
  863. static Language getLanguageFromOptions(const LangOptions &LangOpts) {
  864. if (LangOpts.OpenCL)
  865. return Language::OpenCL;
  866. if (LangOpts.CUDA)
  867. return Language::CUDA;
  868. if (LangOpts.ObjC)
  869. return LangOpts.CPlusPlus ? Language::ObjCXX : Language::ObjC;
  870. return LangOpts.CPlusPlus ? Language::CXX : Language::C;
  871. }
  872. /// Compile a module file for the given module, using the options
  873. /// provided by the importing compiler instance. Returns true if the module
  874. /// was built without errors.
  875. static bool
  876. compileModuleImpl(CompilerInstance &ImportingInstance, SourceLocation ImportLoc,
  877. StringRef ModuleName, FrontendInputFile Input,
  878. StringRef OriginalModuleMapFile, StringRef ModuleFileName,
  879. llvm::function_ref<void(CompilerInstance &)> PreBuildStep =
  880. [](CompilerInstance &) {},
  881. llvm::function_ref<void(CompilerInstance &)> PostBuildStep =
  882. [](CompilerInstance &) {}) {
  883. llvm::TimeTraceScope TimeScope("Module Compile", ModuleName);
  884. // Construct a compiler invocation for creating this module.
  885. auto Invocation =
  886. std::make_shared<CompilerInvocation>(ImportingInstance.getInvocation());
  887. PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
  888. // For any options that aren't intended to affect how a module is built,
  889. // reset them to their default values.
  890. Invocation->getLangOpts()->resetNonModularOptions();
  891. PPOpts.resetNonModularOptions();
  892. // Remove any macro definitions that are explicitly ignored by the module.
  893. // They aren't supposed to affect how the module is built anyway.
  894. HeaderSearchOptions &HSOpts = Invocation->getHeaderSearchOpts();
  895. PPOpts.Macros.erase(
  896. std::remove_if(PPOpts.Macros.begin(), PPOpts.Macros.end(),
  897. [&HSOpts](const std::pair<std::string, bool> &def) {
  898. StringRef MacroDef = def.first;
  899. return HSOpts.ModulesIgnoreMacros.count(
  900. llvm::CachedHashString(MacroDef.split('=').first)) > 0;
  901. }),
  902. PPOpts.Macros.end());
  903. // If the original compiler invocation had -fmodule-name, pass it through.
  904. Invocation->getLangOpts()->ModuleName =
  905. ImportingInstance.getInvocation().getLangOpts()->ModuleName;
  906. // Note the name of the module we're building.
  907. Invocation->getLangOpts()->CurrentModule = ModuleName;
  908. // Make sure that the failed-module structure has been allocated in
  909. // the importing instance, and propagate the pointer to the newly-created
  910. // instance.
  911. PreprocessorOptions &ImportingPPOpts
  912. = ImportingInstance.getInvocation().getPreprocessorOpts();
  913. if (!ImportingPPOpts.FailedModules)
  914. ImportingPPOpts.FailedModules =
  915. std::make_shared<PreprocessorOptions::FailedModulesSet>();
  916. PPOpts.FailedModules = ImportingPPOpts.FailedModules;
  917. // If there is a module map file, build the module using the module map.
  918. // Set up the inputs/outputs so that we build the module from its umbrella
  919. // header.
  920. FrontendOptions &FrontendOpts = Invocation->getFrontendOpts();
  921. FrontendOpts.OutputFile = ModuleFileName.str();
  922. FrontendOpts.DisableFree = false;
  923. FrontendOpts.GenerateGlobalModuleIndex = false;
  924. FrontendOpts.BuildingImplicitModule = true;
  925. FrontendOpts.OriginalModuleMap = OriginalModuleMapFile;
  926. // Force implicitly-built modules to hash the content of the module file.
  927. HSOpts.ModulesHashContent = true;
  928. FrontendOpts.Inputs = {Input};
  929. // Don't free the remapped file buffers; they are owned by our caller.
  930. PPOpts.RetainRemappedFileBuffers = true;
  931. Invocation->getDiagnosticOpts().VerifyDiagnostics = 0;
  932. assert(ImportingInstance.getInvocation().getModuleHash() ==
  933. Invocation->getModuleHash() && "Module hash mismatch!");
  934. // Construct a compiler instance that will be used to actually create the
  935. // module. Since we're sharing an in-memory module cache,
  936. // CompilerInstance::CompilerInstance is responsible for finalizing the
  937. // buffers to prevent use-after-frees.
  938. CompilerInstance Instance(ImportingInstance.getPCHContainerOperations(),
  939. &ImportingInstance.getModuleCache());
  940. auto &Inv = *Invocation;
  941. Instance.setInvocation(std::move(Invocation));
  942. Instance.createDiagnostics(new ForwardingDiagnosticConsumer(
  943. ImportingInstance.getDiagnosticClient()),
  944. /*ShouldOwnClient=*/true);
  945. // Note that this module is part of the module build stack, so that we
  946. // can detect cycles in the module graph.
  947. Instance.setFileManager(&ImportingInstance.getFileManager());
  948. Instance.createSourceManager(Instance.getFileManager());
  949. SourceManager &SourceMgr = Instance.getSourceManager();
  950. SourceMgr.setModuleBuildStack(
  951. ImportingInstance.getSourceManager().getModuleBuildStack());
  952. SourceMgr.pushModuleBuildStack(ModuleName,
  953. FullSourceLoc(ImportLoc, ImportingInstance.getSourceManager()));
  954. // If we're collecting module dependencies, we need to share a collector
  955. // between all of the module CompilerInstances. Other than that, we don't
  956. // want to produce any dependency output from the module build.
  957. Instance.setModuleDepCollector(ImportingInstance.getModuleDepCollector());
  958. Inv.getDependencyOutputOpts() = DependencyOutputOptions();
  959. ImportingInstance.getDiagnostics().Report(ImportLoc,
  960. diag::remark_module_build)
  961. << ModuleName << ModuleFileName;
  962. PreBuildStep(Instance);
  963. // Execute the action to actually build the module in-place. Use a separate
  964. // thread so that we get a stack large enough.
  965. llvm::CrashRecoveryContext CRC;
  966. CRC.RunSafelyOnThread(
  967. [&]() {
  968. GenerateModuleFromModuleMapAction Action;
  969. Instance.ExecuteAction(Action);
  970. },
  971. DesiredStackSize);
  972. PostBuildStep(Instance);
  973. ImportingInstance.getDiagnostics().Report(ImportLoc,
  974. diag::remark_module_build_done)
  975. << ModuleName;
  976. // Delete the temporary module map file.
  977. // FIXME: Even though we're executing under crash protection, it would still
  978. // be nice to do this with RemoveFileOnSignal when we can. However, that
  979. // doesn't make sense for all clients, so clean this up manually.
  980. Instance.clearOutputFiles(/*EraseFiles=*/true);
  981. return !Instance.getDiagnostics().hasErrorOccurred();
  982. }
  983. static const FileEntry *getPublicModuleMap(const FileEntry *File,
  984. FileManager &FileMgr) {
  985. StringRef Filename = llvm::sys::path::filename(File->getName());
  986. SmallString<128> PublicFilename(File->getDir()->getName());
  987. if (Filename == "module_private.map")
  988. llvm::sys::path::append(PublicFilename, "module.map");
  989. else if (Filename == "module.private.modulemap")
  990. llvm::sys::path::append(PublicFilename, "module.modulemap");
  991. else
  992. return nullptr;
  993. if (auto FE = FileMgr.getFile(PublicFilename))
  994. return *FE;
  995. return nullptr;
  996. }
  997. /// Compile a module file for the given module, using the options
  998. /// provided by the importing compiler instance. Returns true if the module
  999. /// was built without errors.
  1000. static bool compileModuleImpl(CompilerInstance &ImportingInstance,
  1001. SourceLocation ImportLoc,
  1002. Module *Module,
  1003. StringRef ModuleFileName) {
  1004. InputKind IK(getLanguageFromOptions(ImportingInstance.getLangOpts()),
  1005. InputKind::ModuleMap);
  1006. // Get or create the module map that we'll use to build this module.
  1007. ModuleMap &ModMap
  1008. = ImportingInstance.getPreprocessor().getHeaderSearchInfo().getModuleMap();
  1009. bool Result;
  1010. if (const FileEntry *ModuleMapFile =
  1011. ModMap.getContainingModuleMapFile(Module)) {
  1012. // Canonicalize compilation to start with the public module map. This is
  1013. // vital for submodules declarations in the private module maps to be
  1014. // correctly parsed when depending on a top level module in the public one.
  1015. if (const FileEntry *PublicMMFile = getPublicModuleMap(
  1016. ModuleMapFile, ImportingInstance.getFileManager()))
  1017. ModuleMapFile = PublicMMFile;
  1018. // Use the module map where this module resides.
  1019. Result = compileModuleImpl(
  1020. ImportingInstance, ImportLoc, Module->getTopLevelModuleName(),
  1021. FrontendInputFile(ModuleMapFile->getName(), IK, +Module->IsSystem),
  1022. ModMap.getModuleMapFileForUniquing(Module)->getName(),
  1023. ModuleFileName);
  1024. } else {
  1025. // FIXME: We only need to fake up an input file here as a way of
  1026. // transporting the module's directory to the module map parser. We should
  1027. // be able to do that more directly, and parse from a memory buffer without
  1028. // inventing this file.
  1029. SmallString<128> FakeModuleMapFile(Module->Directory->getName());
  1030. llvm::sys::path::append(FakeModuleMapFile, "__inferred_module.map");
  1031. std::string InferredModuleMapContent;
  1032. llvm::raw_string_ostream OS(InferredModuleMapContent);
  1033. Module->print(OS);
  1034. OS.flush();
  1035. Result = compileModuleImpl(
  1036. ImportingInstance, ImportLoc, Module->getTopLevelModuleName(),
  1037. FrontendInputFile(FakeModuleMapFile, IK, +Module->IsSystem),
  1038. ModMap.getModuleMapFileForUniquing(Module)->getName(),
  1039. ModuleFileName,
  1040. [&](CompilerInstance &Instance) {
  1041. std::unique_ptr<llvm::MemoryBuffer> ModuleMapBuffer =
  1042. llvm::MemoryBuffer::getMemBuffer(InferredModuleMapContent);
  1043. ModuleMapFile = Instance.getFileManager().getVirtualFile(
  1044. FakeModuleMapFile, InferredModuleMapContent.size(), 0);
  1045. Instance.getSourceManager().overrideFileContents(
  1046. ModuleMapFile, std::move(ModuleMapBuffer));
  1047. });
  1048. }
  1049. // We've rebuilt a module. If we're allowed to generate or update the global
  1050. // module index, record that fact in the importing compiler instance.
  1051. if (ImportingInstance.getFrontendOpts().GenerateGlobalModuleIndex) {
  1052. ImportingInstance.setBuildGlobalModuleIndex(true);
  1053. }
  1054. return Result;
  1055. }
  1056. static bool compileAndLoadModule(CompilerInstance &ImportingInstance,
  1057. SourceLocation ImportLoc,
  1058. SourceLocation ModuleNameLoc, Module *Module,
  1059. StringRef ModuleFileName) {
  1060. DiagnosticsEngine &Diags = ImportingInstance.getDiagnostics();
  1061. auto diagnoseBuildFailure = [&] {
  1062. Diags.Report(ModuleNameLoc, diag::err_module_not_built)
  1063. << Module->Name << SourceRange(ImportLoc, ModuleNameLoc);
  1064. };
  1065. // FIXME: have LockFileManager return an error_code so that we can
  1066. // avoid the mkdir when the directory already exists.
  1067. StringRef Dir = llvm::sys::path::parent_path(ModuleFileName);
  1068. llvm::sys::fs::create_directories(Dir);
  1069. while (1) {
  1070. unsigned ModuleLoadCapabilities = ASTReader::ARR_Missing;
  1071. llvm::LockFileManager Locked(ModuleFileName);
  1072. switch (Locked) {
  1073. case llvm::LockFileManager::LFS_Error:
  1074. // ModuleCache takes care of correctness and locks are only necessary for
  1075. // performance. Fallback to building the module in case of any lock
  1076. // related errors.
  1077. Diags.Report(ModuleNameLoc, diag::remark_module_lock_failure)
  1078. << Module->Name << Locked.getErrorMessage();
  1079. // Clear out any potential leftover.
  1080. Locked.unsafeRemoveLockFile();
  1081. LLVM_FALLTHROUGH;
  1082. case llvm::LockFileManager::LFS_Owned:
  1083. // We're responsible for building the module ourselves.
  1084. if (!compileModuleImpl(ImportingInstance, ModuleNameLoc, Module,
  1085. ModuleFileName)) {
  1086. diagnoseBuildFailure();
  1087. return false;
  1088. }
  1089. break;
  1090. case llvm::LockFileManager::LFS_Shared:
  1091. // Someone else is responsible for building the module. Wait for them to
  1092. // finish.
  1093. switch (Locked.waitForUnlock()) {
  1094. case llvm::LockFileManager::Res_Success:
  1095. ModuleLoadCapabilities |= ASTReader::ARR_OutOfDate;
  1096. break;
  1097. case llvm::LockFileManager::Res_OwnerDied:
  1098. continue; // try again to get the lock.
  1099. case llvm::LockFileManager::Res_Timeout:
  1100. // Since ModuleCache takes care of correctness, we try waiting for
  1101. // another process to complete the build so clang does not do it done
  1102. // twice. If case of timeout, build it ourselves.
  1103. Diags.Report(ModuleNameLoc, diag::remark_module_lock_timeout)
  1104. << Module->Name;
  1105. // Clear the lock file so that future invocations can make progress.
  1106. Locked.unsafeRemoveLockFile();
  1107. continue;
  1108. }
  1109. break;
  1110. }
  1111. // Try to read the module file, now that we've compiled it.
  1112. ASTReader::ASTReadResult ReadResult =
  1113. ImportingInstance.getModuleManager()->ReadAST(
  1114. ModuleFileName, serialization::MK_ImplicitModule, ImportLoc,
  1115. ModuleLoadCapabilities);
  1116. if (ReadResult == ASTReader::OutOfDate &&
  1117. Locked == llvm::LockFileManager::LFS_Shared) {
  1118. // The module may be out of date in the presence of file system races,
  1119. // or if one of its imports depends on header search paths that are not
  1120. // consistent with this ImportingInstance. Try again...
  1121. continue;
  1122. } else if (ReadResult == ASTReader::Missing) {
  1123. diagnoseBuildFailure();
  1124. } else if (ReadResult != ASTReader::Success &&
  1125. !Diags.hasErrorOccurred()) {
  1126. // The ASTReader didn't diagnose the error, so conservatively report it.
  1127. diagnoseBuildFailure();
  1128. }
  1129. return ReadResult == ASTReader::Success;
  1130. }
  1131. }
  1132. /// Diagnose differences between the current definition of the given
  1133. /// configuration macro and the definition provided on the command line.
  1134. static void checkConfigMacro(Preprocessor &PP, StringRef ConfigMacro,
  1135. Module *Mod, SourceLocation ImportLoc) {
  1136. IdentifierInfo *Id = PP.getIdentifierInfo(ConfigMacro);
  1137. SourceManager &SourceMgr = PP.getSourceManager();
  1138. // If this identifier has never had a macro definition, then it could
  1139. // not have changed.
  1140. if (!Id->hadMacroDefinition())
  1141. return;
  1142. auto *LatestLocalMD = PP.getLocalMacroDirectiveHistory(Id);
  1143. // Find the macro definition from the command line.
  1144. MacroInfo *CmdLineDefinition = nullptr;
  1145. for (auto *MD = LatestLocalMD; MD; MD = MD->getPrevious()) {
  1146. // We only care about the predefines buffer.
  1147. FileID FID = SourceMgr.getFileID(MD->getLocation());
  1148. if (FID.isInvalid() || FID != PP.getPredefinesFileID())
  1149. continue;
  1150. if (auto *DMD = dyn_cast<DefMacroDirective>(MD))
  1151. CmdLineDefinition = DMD->getMacroInfo();
  1152. break;
  1153. }
  1154. auto *CurrentDefinition = PP.getMacroInfo(Id);
  1155. if (CurrentDefinition == CmdLineDefinition) {
  1156. // Macro matches. Nothing to do.
  1157. } else if (!CurrentDefinition) {
  1158. // This macro was defined on the command line, then #undef'd later.
  1159. // Complain.
  1160. PP.Diag(ImportLoc, diag::warn_module_config_macro_undef)
  1161. << true << ConfigMacro << Mod->getFullModuleName();
  1162. auto LatestDef = LatestLocalMD->getDefinition();
  1163. assert(LatestDef.isUndefined() &&
  1164. "predefined macro went away with no #undef?");
  1165. PP.Diag(LatestDef.getUndefLocation(), diag::note_module_def_undef_here)
  1166. << true;
  1167. return;
  1168. } else if (!CmdLineDefinition) {
  1169. // There was no definition for this macro in the predefines buffer,
  1170. // but there was a local definition. Complain.
  1171. PP.Diag(ImportLoc, diag::warn_module_config_macro_undef)
  1172. << false << ConfigMacro << Mod->getFullModuleName();
  1173. PP.Diag(CurrentDefinition->getDefinitionLoc(),
  1174. diag::note_module_def_undef_here)
  1175. << false;
  1176. } else if (!CurrentDefinition->isIdenticalTo(*CmdLineDefinition, PP,
  1177. /*Syntactically=*/true)) {
  1178. // The macro definitions differ.
  1179. PP.Diag(ImportLoc, diag::warn_module_config_macro_undef)
  1180. << false << ConfigMacro << Mod->getFullModuleName();
  1181. PP.Diag(CurrentDefinition->getDefinitionLoc(),
  1182. diag::note_module_def_undef_here)
  1183. << false;
  1184. }
  1185. }
  1186. /// Write a new timestamp file with the given path.
  1187. static void writeTimestampFile(StringRef TimestampFile) {
  1188. std::error_code EC;
  1189. llvm::raw_fd_ostream Out(TimestampFile.str(), EC, llvm::sys::fs::OF_None);
  1190. }
  1191. /// Prune the module cache of modules that haven't been accessed in
  1192. /// a long time.
  1193. static void pruneModuleCache(const HeaderSearchOptions &HSOpts) {
  1194. struct stat StatBuf;
  1195. llvm::SmallString<128> TimestampFile;
  1196. TimestampFile = HSOpts.ModuleCachePath;
  1197. assert(!TimestampFile.empty());
  1198. llvm::sys::path::append(TimestampFile, "modules.timestamp");
  1199. // Try to stat() the timestamp file.
  1200. if (::stat(TimestampFile.c_str(), &StatBuf)) {
  1201. // If the timestamp file wasn't there, create one now.
  1202. if (errno == ENOENT) {
  1203. writeTimestampFile(TimestampFile);
  1204. }
  1205. return;
  1206. }
  1207. // Check whether the time stamp is older than our pruning interval.
  1208. // If not, do nothing.
  1209. time_t TimeStampModTime = StatBuf.st_mtime;
  1210. time_t CurrentTime = time(nullptr);
  1211. if (CurrentTime - TimeStampModTime <= time_t(HSOpts.ModuleCachePruneInterval))
  1212. return;
  1213. // Write a new timestamp file so that nobody else attempts to prune.
  1214. // There is a benign race condition here, if two Clang instances happen to
  1215. // notice at the same time that the timestamp is out-of-date.
  1216. writeTimestampFile(TimestampFile);
  1217. // Walk the entire module cache, looking for unused module files and module
  1218. // indices.
  1219. std::error_code EC;
  1220. SmallString<128> ModuleCachePathNative;
  1221. llvm::sys::path::native(HSOpts.ModuleCachePath, ModuleCachePathNative);
  1222. for (llvm::sys::fs::directory_iterator Dir(ModuleCachePathNative, EC), DirEnd;
  1223. Dir != DirEnd && !EC; Dir.increment(EC)) {
  1224. // If we don't have a directory, there's nothing to look into.
  1225. if (!llvm::sys::fs::is_directory(Dir->path()))
  1226. continue;
  1227. // Walk all of the files within this directory.
  1228. for (llvm::sys::fs::directory_iterator File(Dir->path(), EC), FileEnd;
  1229. File != FileEnd && !EC; File.increment(EC)) {
  1230. // We only care about module and global module index files.
  1231. StringRef Extension = llvm::sys::path::extension(File->path());
  1232. if (Extension != ".pcm" && Extension != ".timestamp" &&
  1233. llvm::sys::path::filename(File->path()) != "modules.idx")
  1234. continue;
  1235. // Look at this file. If we can't stat it, there's nothing interesting
  1236. // there.
  1237. if (::stat(File->path().c_str(), &StatBuf))
  1238. continue;
  1239. // If the file has been used recently enough, leave it there.
  1240. time_t FileAccessTime = StatBuf.st_atime;
  1241. if (CurrentTime - FileAccessTime <=
  1242. time_t(HSOpts.ModuleCachePruneAfter)) {
  1243. continue;
  1244. }
  1245. // Remove the file.
  1246. llvm::sys::fs::remove(File->path());
  1247. // Remove the timestamp file.
  1248. std::string TimpestampFilename = File->path() + ".timestamp";
  1249. llvm::sys::fs::remove(TimpestampFilename);
  1250. }
  1251. // If we removed all of the files in the directory, remove the directory
  1252. // itself.
  1253. if (llvm::sys::fs::directory_iterator(Dir->path(), EC) ==
  1254. llvm::sys::fs::directory_iterator() && !EC)
  1255. llvm::sys::fs::remove(Dir->path());
  1256. }
  1257. }
  1258. void CompilerInstance::createModuleManager() {
  1259. if (!ModuleManager) {
  1260. if (!hasASTContext())
  1261. createASTContext();
  1262. // If we're implicitly building modules but not currently recursively
  1263. // building a module, check whether we need to prune the module cache.
  1264. if (getSourceManager().getModuleBuildStack().empty() &&
  1265. !getPreprocessor().getHeaderSearchInfo().getModuleCachePath().empty() &&
  1266. getHeaderSearchOpts().ModuleCachePruneInterval > 0 &&
  1267. getHeaderSearchOpts().ModuleCachePruneAfter > 0) {
  1268. pruneModuleCache(getHeaderSearchOpts());
  1269. }
  1270. HeaderSearchOptions &HSOpts = getHeaderSearchOpts();
  1271. std::string Sysroot = HSOpts.Sysroot;
  1272. const PreprocessorOptions &PPOpts = getPreprocessorOpts();
  1273. std::unique_ptr<llvm::Timer> ReadTimer;
  1274. if (FrontendTimerGroup)
  1275. ReadTimer = llvm::make_unique<llvm::Timer>("reading_modules",
  1276. "Reading modules",
  1277. *FrontendTimerGroup);
  1278. ModuleManager = new ASTReader(
  1279. getPreprocessor(), getModuleCache(), &getASTContext(),
  1280. getPCHContainerReader(), getFrontendOpts().ModuleFileExtensions,
  1281. Sysroot.empty() ? "" : Sysroot.c_str(), PPOpts.DisablePCHValidation,
  1282. /*AllowASTWithCompilerErrors=*/false,
  1283. /*AllowConfigurationMismatch=*/false,
  1284. HSOpts.ModulesValidateSystemHeaders,
  1285. getFrontendOpts().UseGlobalModuleIndex, std::move(ReadTimer));
  1286. if (hasASTConsumer()) {
  1287. ModuleManager->setDeserializationListener(
  1288. getASTConsumer().GetASTDeserializationListener());
  1289. getASTContext().setASTMutationListener(
  1290. getASTConsumer().GetASTMutationListener());
  1291. }
  1292. getASTContext().setExternalSource(ModuleManager);
  1293. if (hasSema())
  1294. ModuleManager->InitializeSema(getSema());
  1295. if (hasASTConsumer())
  1296. ModuleManager->StartTranslationUnit(&getASTConsumer());
  1297. for (auto &Listener : DependencyCollectors)
  1298. Listener->attachToASTReader(*ModuleManager);
  1299. }
  1300. }
  1301. bool CompilerInstance::loadModuleFile(StringRef FileName) {
  1302. llvm::Timer Timer;
  1303. if (FrontendTimerGroup)
  1304. Timer.init("preloading." + FileName.str(), "Preloading " + FileName.str(),
  1305. *FrontendTimerGroup);
  1306. llvm::TimeRegion TimeLoading(FrontendTimerGroup ? &Timer : nullptr);
  1307. // Helper to recursively read the module names for all modules we're adding.
  1308. // We mark these as known and redirect any attempt to load that module to
  1309. // the files we were handed.
  1310. struct ReadModuleNames : ASTReaderListener {
  1311. CompilerInstance &CI;
  1312. llvm::SmallVector<IdentifierInfo*, 8> LoadedModules;
  1313. ReadModuleNames(CompilerInstance &CI) : CI(CI) {}
  1314. void ReadModuleName(StringRef ModuleName) override {
  1315. LoadedModules.push_back(
  1316. CI.getPreprocessor().getIdentifierInfo(ModuleName));
  1317. }
  1318. void registerAll() {
  1319. for (auto *II : LoadedModules) {
  1320. CI.KnownModules[II] = CI.getPreprocessor()
  1321. .getHeaderSearchInfo()
  1322. .getModuleMap()
  1323. .findModule(II->getName());
  1324. }
  1325. LoadedModules.clear();
  1326. }
  1327. void markAllUnavailable() {
  1328. for (auto *II : LoadedModules) {
  1329. if (Module *M = CI.getPreprocessor()
  1330. .getHeaderSearchInfo()
  1331. .getModuleMap()
  1332. .findModule(II->getName())) {
  1333. M->HasIncompatibleModuleFile = true;
  1334. // Mark module as available if the only reason it was unavailable
  1335. // was missing headers.
  1336. SmallVector<Module *, 2> Stack;
  1337. Stack.push_back(M);
  1338. while (!Stack.empty()) {
  1339. Module *Current = Stack.pop_back_val();
  1340. if (Current->IsMissingRequirement) continue;
  1341. Current->IsAvailable = true;
  1342. Stack.insert(Stack.end(),
  1343. Current->submodule_begin(), Current->submodule_end());
  1344. }
  1345. }
  1346. }
  1347. LoadedModules.clear();
  1348. }
  1349. };
  1350. // If we don't already have an ASTReader, create one now.
  1351. if (!ModuleManager)
  1352. createModuleManager();
  1353. // If -Wmodule-file-config-mismatch is mapped as an error or worse, allow the
  1354. // ASTReader to diagnose it, since it can produce better errors that we can.
  1355. bool ConfigMismatchIsRecoverable =
  1356. getDiagnostics().getDiagnosticLevel(diag::warn_module_config_mismatch,
  1357. SourceLocation())
  1358. <= DiagnosticsEngine::Warning;
  1359. auto Listener = llvm::make_unique<ReadModuleNames>(*this);
  1360. auto &ListenerRef = *Listener;
  1361. ASTReader::ListenerScope ReadModuleNamesListener(*ModuleManager,
  1362. std::move(Listener));
  1363. // Try to load the module file.
  1364. switch (ModuleManager->ReadAST(
  1365. FileName, serialization::MK_ExplicitModule, SourceLocation(),
  1366. ConfigMismatchIsRecoverable ? ASTReader::ARR_ConfigurationMismatch : 0)) {
  1367. case ASTReader::Success:
  1368. // We successfully loaded the module file; remember the set of provided
  1369. // modules so that we don't try to load implicit modules for them.
  1370. ListenerRef.registerAll();
  1371. return true;
  1372. case ASTReader::ConfigurationMismatch:
  1373. // Ignore unusable module files.
  1374. getDiagnostics().Report(SourceLocation(), diag::warn_module_config_mismatch)
  1375. << FileName;
  1376. // All modules provided by any files we tried and failed to load are now
  1377. // unavailable; includes of those modules should now be handled textually.
  1378. ListenerRef.markAllUnavailable();
  1379. return true;
  1380. default:
  1381. return false;
  1382. }
  1383. }
  1384. ModuleLoadResult
  1385. CompilerInstance::loadModule(SourceLocation ImportLoc,
  1386. ModuleIdPath Path,
  1387. Module::NameVisibilityKind Visibility,
  1388. bool IsInclusionDirective) {
  1389. // Determine what file we're searching from.
  1390. StringRef ModuleName = Path[0].first->getName();
  1391. SourceLocation ModuleNameLoc = Path[0].second;
  1392. // If we've already handled this import, just return the cached result.
  1393. // This one-element cache is important to eliminate redundant diagnostics
  1394. // when both the preprocessor and parser see the same import declaration.
  1395. if (ImportLoc.isValid() && LastModuleImportLoc == ImportLoc) {
  1396. // Make the named module visible.
  1397. if (LastModuleImportResult && ModuleName != getLangOpts().CurrentModule)
  1398. ModuleManager->makeModuleVisible(LastModuleImportResult, Visibility,
  1399. ImportLoc);
  1400. return LastModuleImportResult;
  1401. }
  1402. clang::Module *Module = nullptr;
  1403. // If we don't already have information on this module, load the module now.
  1404. llvm::DenseMap<const IdentifierInfo *, clang::Module *>::iterator Known
  1405. = KnownModules.find(Path[0].first);
  1406. if (Known != KnownModules.end()) {
  1407. // Retrieve the cached top-level module.
  1408. Module = Known->second;
  1409. } else if (ModuleName == getLangOpts().CurrentModule) {
  1410. // This is the module we're building.
  1411. Module = PP->getHeaderSearchInfo().lookupModule(
  1412. ModuleName, /*AllowSearch*/ true,
  1413. /*AllowExtraModuleMapSearch*/ !IsInclusionDirective);
  1414. /// FIXME: perhaps we should (a) look for a module using the module name
  1415. // to file map (PrebuiltModuleFiles) and (b) diagnose if still not found?
  1416. //if (Module == nullptr) {
  1417. // getDiagnostics().Report(ModuleNameLoc, diag::err_module_not_found)
  1418. // << ModuleName;
  1419. // ModuleBuildFailed = true;
  1420. // return ModuleLoadResult();
  1421. //}
  1422. Known = KnownModules.insert(std::make_pair(Path[0].first, Module)).first;
  1423. } else {
  1424. // Search for a module with the given name.
  1425. Module = PP->getHeaderSearchInfo().lookupModule(ModuleName, true,
  1426. !IsInclusionDirective);
  1427. HeaderSearchOptions &HSOpts =
  1428. PP->getHeaderSearchInfo().getHeaderSearchOpts();
  1429. std::string ModuleFileName;
  1430. enum ModuleSource {
  1431. ModuleNotFound, ModuleCache, PrebuiltModulePath, ModuleBuildPragma
  1432. } Source = ModuleNotFound;
  1433. // Check to see if the module has been built as part of this compilation
  1434. // via a module build pragma.
  1435. auto BuiltModuleIt = BuiltModules.find(ModuleName);
  1436. if (BuiltModuleIt != BuiltModules.end()) {
  1437. ModuleFileName = BuiltModuleIt->second;
  1438. Source = ModuleBuildPragma;
  1439. }
  1440. // Try to load the module from the prebuilt module path.
  1441. if (Source == ModuleNotFound && (!HSOpts.PrebuiltModuleFiles.empty() ||
  1442. !HSOpts.PrebuiltModulePaths.empty())) {
  1443. ModuleFileName =
  1444. PP->getHeaderSearchInfo().getPrebuiltModuleFileName(ModuleName);
  1445. if (!ModuleFileName.empty())
  1446. Source = PrebuiltModulePath;
  1447. }
  1448. // Try to load the module from the module cache.
  1449. if (Source == ModuleNotFound && Module) {
  1450. ModuleFileName = PP->getHeaderSearchInfo().getCachedModuleFileName(Module);
  1451. Source = ModuleCache;
  1452. }
  1453. if (Source == ModuleNotFound) {
  1454. // We can't find a module, error out here.
  1455. getDiagnostics().Report(ModuleNameLoc, diag::err_module_not_found)
  1456. << ModuleName << SourceRange(ImportLoc, ModuleNameLoc);
  1457. ModuleBuildFailed = true;
  1458. return ModuleLoadResult();
  1459. }
  1460. if (ModuleFileName.empty()) {
  1461. if (Module && Module->HasIncompatibleModuleFile) {
  1462. // We tried and failed to load a module file for this module. Fall
  1463. // back to textual inclusion for its headers.
  1464. return ModuleLoadResult::ConfigMismatch;
  1465. }
  1466. getDiagnostics().Report(ModuleNameLoc, diag::err_module_build_disabled)
  1467. << ModuleName;
  1468. ModuleBuildFailed = true;
  1469. return ModuleLoadResult();
  1470. }
  1471. // If we don't already have an ASTReader, create one now.
  1472. if (!ModuleManager)
  1473. createModuleManager();
  1474. llvm::Timer Timer;
  1475. if (FrontendTimerGroup)
  1476. Timer.init("loading." + ModuleFileName, "Loading " + ModuleFileName,
  1477. *FrontendTimerGroup);
  1478. llvm::TimeRegion TimeLoading(FrontendTimerGroup ? &Timer : nullptr);
  1479. llvm::TimeTraceScope TimeScope("Module Load", ModuleName);
  1480. // Try to load the module file. If we are not trying to load from the
  1481. // module cache, we don't know how to rebuild modules.
  1482. unsigned ARRFlags = Source == ModuleCache ?
  1483. ASTReader::ARR_OutOfDate | ASTReader::ARR_Missing :
  1484. Source == PrebuiltModulePath ?
  1485. 0 :
  1486. ASTReader::ARR_ConfigurationMismatch;
  1487. switch (ModuleManager->ReadAST(ModuleFileName,
  1488. Source == PrebuiltModulePath
  1489. ? serialization::MK_PrebuiltModule
  1490. : Source == ModuleBuildPragma
  1491. ? serialization::MK_ExplicitModule
  1492. : serialization::MK_ImplicitModule,
  1493. ImportLoc, ARRFlags)) {
  1494. case ASTReader::Success: {
  1495. if (Source != ModuleCache && !Module) {
  1496. Module = PP->getHeaderSearchInfo().lookupModule(ModuleName, true,
  1497. !IsInclusionDirective);
  1498. auto ModuleFile = FileMgr->getFile(ModuleFileName);
  1499. if (!Module || !Module->getASTFile() ||
  1500. !ModuleFile || (*ModuleFile != Module->getASTFile())) {
  1501. // Error out if Module does not refer to the file in the prebuilt
  1502. // module path.
  1503. getDiagnostics().Report(ModuleNameLoc, diag::err_module_prebuilt)
  1504. << ModuleName;
  1505. ModuleBuildFailed = true;
  1506. KnownModules[Path[0].first] = nullptr;
  1507. return ModuleLoadResult();
  1508. }
  1509. }
  1510. break;
  1511. }
  1512. case ASTReader::OutOfDate:
  1513. case ASTReader::Missing: {
  1514. if (Source != ModuleCache) {
  1515. // We don't know the desired configuration for this module and don't
  1516. // necessarily even have a module map. Since ReadAST already produces
  1517. // diagnostics for these two cases, we simply error out here.
  1518. ModuleBuildFailed = true;
  1519. KnownModules[Path[0].first] = nullptr;
  1520. return ModuleLoadResult();
  1521. }
  1522. // The module file is missing or out-of-date. Build it.
  1523. assert(Module && "missing module file");
  1524. // Check whether there is a cycle in the module graph.
  1525. ModuleBuildStack ModPath = getSourceManager().getModuleBuildStack();
  1526. ModuleBuildStack::iterator Pos = ModPath.begin(), PosEnd = ModPath.end();
  1527. for (; Pos != PosEnd; ++Pos) {
  1528. if (Pos->first == ModuleName)
  1529. break;
  1530. }
  1531. if (Pos != PosEnd) {
  1532. SmallString<256> CyclePath;
  1533. for (; Pos != PosEnd; ++Pos) {
  1534. CyclePath += Pos->first;
  1535. CyclePath += " -> ";
  1536. }
  1537. CyclePath += ModuleName;
  1538. getDiagnostics().Report(ModuleNameLoc, diag::err_module_cycle)
  1539. << ModuleName << CyclePath;
  1540. return ModuleLoadResult();
  1541. }
  1542. // Check whether we have already attempted to build this module (but
  1543. // failed).
  1544. if (getPreprocessorOpts().FailedModules &&
  1545. getPreprocessorOpts().FailedModules->hasAlreadyFailed(ModuleName)) {
  1546. getDiagnostics().Report(ModuleNameLoc, diag::err_module_not_built)
  1547. << ModuleName
  1548. << SourceRange(ImportLoc, ModuleNameLoc);
  1549. ModuleBuildFailed = true;
  1550. return ModuleLoadResult();
  1551. }
  1552. // Try to compile and then load the module.
  1553. if (!compileAndLoadModule(*this, ImportLoc, ModuleNameLoc, Module,
  1554. ModuleFileName)) {
  1555. assert(getDiagnostics().hasErrorOccurred() &&
  1556. "undiagnosed error in compileAndLoadModule");
  1557. if (getPreprocessorOpts().FailedModules)
  1558. getPreprocessorOpts().FailedModules->addFailed(ModuleName);
  1559. KnownModules[Path[0].first] = nullptr;
  1560. ModuleBuildFailed = true;
  1561. return ModuleLoadResult();
  1562. }
  1563. // Okay, we've rebuilt and now loaded the module.
  1564. break;
  1565. }
  1566. case ASTReader::ConfigurationMismatch:
  1567. if (Source == PrebuiltModulePath)
  1568. // FIXME: We shouldn't be setting HadFatalFailure below if we only
  1569. // produce a warning here!
  1570. getDiagnostics().Report(SourceLocation(),
  1571. diag::warn_module_config_mismatch)
  1572. << ModuleFileName;
  1573. // Fall through to error out.
  1574. LLVM_FALLTHROUGH;
  1575. case ASTReader::VersionMismatch:
  1576. case ASTReader::HadErrors:
  1577. ModuleLoader::HadFatalFailure = true;
  1578. // FIXME: The ASTReader will already have complained, but can we shoehorn
  1579. // that diagnostic information into a more useful form?
  1580. KnownModules[Path[0].first] = nullptr;
  1581. return ModuleLoadResult();
  1582. case ASTReader::Failure:
  1583. ModuleLoader::HadFatalFailure = true;
  1584. // Already complained, but note now that we failed.
  1585. KnownModules[Path[0].first] = nullptr;
  1586. ModuleBuildFailed = true;
  1587. return ModuleLoadResult();
  1588. }
  1589. // Cache the result of this top-level module lookup for later.
  1590. Known = KnownModules.insert(std::make_pair(Path[0].first, Module)).first;
  1591. }
  1592. // If we never found the module, fail.
  1593. if (!Module)
  1594. return ModuleLoadResult();
  1595. // Verify that the rest of the module path actually corresponds to
  1596. // a submodule.
  1597. bool MapPrivateSubModToTopLevel = false;
  1598. if (Path.size() > 1) {
  1599. for (unsigned I = 1, N = Path.size(); I != N; ++I) {
  1600. StringRef Name = Path[I].first->getName();
  1601. clang::Module *Sub = Module->findSubmodule(Name);
  1602. // If the user is requesting Foo.Private and it doesn't exist, try to
  1603. // match Foo_Private and emit a warning asking for the user to write
  1604. // @import Foo_Private instead. FIXME: remove this when existing clients
  1605. // migrate off of Foo.Private syntax.
  1606. if (!Sub && PP->getLangOpts().ImplicitModules && Name == "Private" &&
  1607. Module == Module->getTopLevelModule()) {
  1608. SmallString<128> PrivateModule(Module->Name);
  1609. PrivateModule.append("_Private");
  1610. SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> PrivPath;
  1611. auto &II = PP->getIdentifierTable().get(
  1612. PrivateModule, PP->getIdentifierInfo(Module->Name)->getTokenID());
  1613. PrivPath.push_back(std::make_pair(&II, Path[0].second));
  1614. if (PP->getHeaderSearchInfo().lookupModule(PrivateModule, true,
  1615. !IsInclusionDirective))
  1616. Sub =
  1617. loadModule(ImportLoc, PrivPath, Visibility, IsInclusionDirective);
  1618. if (Sub) {
  1619. MapPrivateSubModToTopLevel = true;
  1620. if (!getDiagnostics().isIgnored(
  1621. diag::warn_no_priv_submodule_use_toplevel, ImportLoc)) {
  1622. getDiagnostics().Report(Path[I].second,
  1623. diag::warn_no_priv_submodule_use_toplevel)
  1624. << Path[I].first << Module->getFullModuleName() << PrivateModule
  1625. << SourceRange(Path[0].second, Path[I].second)
  1626. << FixItHint::CreateReplacement(SourceRange(Path[0].second),
  1627. PrivateModule);
  1628. getDiagnostics().Report(Sub->DefinitionLoc,
  1629. diag::note_private_top_level_defined);
  1630. }
  1631. }
  1632. }
  1633. if (!Sub) {
  1634. // Attempt to perform typo correction to find a module name that works.
  1635. SmallVector<StringRef, 2> Best;
  1636. unsigned BestEditDistance = (std::numeric_limits<unsigned>::max)();
  1637. for (clang::Module::submodule_iterator J = Module->submodule_begin(),
  1638. JEnd = Module->submodule_end();
  1639. J != JEnd; ++J) {
  1640. unsigned ED = Name.edit_distance((*J)->Name,
  1641. /*AllowReplacements=*/true,
  1642. BestEditDistance);
  1643. if (ED <= BestEditDistance) {
  1644. if (ED < BestEditDistance) {
  1645. Best.clear();
  1646. BestEditDistance = ED;
  1647. }
  1648. Best.push_back((*J)->Name);
  1649. }
  1650. }
  1651. // If there was a clear winner, user it.
  1652. if (Best.size() == 1) {
  1653. getDiagnostics().Report(Path[I].second,
  1654. diag::err_no_submodule_suggest)
  1655. << Path[I].first << Module->getFullModuleName() << Best[0]
  1656. << SourceRange(Path[0].second, Path[I-1].second)
  1657. << FixItHint::CreateReplacement(SourceRange(Path[I].second),
  1658. Best[0]);
  1659. Sub = Module->findSubmodule(Best[0]);
  1660. }
  1661. }
  1662. if (!Sub) {
  1663. // No submodule by this name. Complain, and don't look for further
  1664. // submodules.
  1665. getDiagnostics().Report(Path[I].second, diag::err_no_submodule)
  1666. << Path[I].first << Module->getFullModuleName()
  1667. << SourceRange(Path[0].second, Path[I-1].second);
  1668. break;
  1669. }
  1670. Module = Sub;
  1671. }
  1672. }
  1673. // Make the named module visible, if it's not already part of the module
  1674. // we are parsing.
  1675. if (ModuleName != getLangOpts().CurrentModule) {
  1676. if (!Module->IsFromModuleFile && !MapPrivateSubModToTopLevel) {
  1677. // We have an umbrella header or directory that doesn't actually include
  1678. // all of the headers within the directory it covers. Complain about
  1679. // this missing submodule and recover by forgetting that we ever saw
  1680. // this submodule.
  1681. // FIXME: Should we detect this at module load time? It seems fairly
  1682. // expensive (and rare).
  1683. getDiagnostics().Report(ImportLoc, diag::warn_missing_submodule)
  1684. << Module->getFullModuleName()
  1685. << SourceRange(Path.front().second, Path.back().second);
  1686. return ModuleLoadResult::MissingExpected;
  1687. }
  1688. // Check whether this module is available.
  1689. if (Preprocessor::checkModuleIsAvailable(getLangOpts(), getTarget(),
  1690. getDiagnostics(), Module)) {
  1691. getDiagnostics().Report(ImportLoc, diag::note_module_import_here)
  1692. << SourceRange(Path.front().second, Path.back().second);
  1693. LastModuleImportLoc = ImportLoc;
  1694. LastModuleImportResult = ModuleLoadResult();
  1695. return ModuleLoadResult();
  1696. }
  1697. ModuleManager->makeModuleVisible(Module, Visibility, ImportLoc);
  1698. }
  1699. // Check for any configuration macros that have changed.
  1700. clang::Module *TopModule = Module->getTopLevelModule();
  1701. for (unsigned I = 0, N = TopModule->ConfigMacros.size(); I != N; ++I) {
  1702. checkConfigMacro(getPreprocessor(), TopModule->ConfigMacros[I],
  1703. Module, ImportLoc);
  1704. }
  1705. // Resolve any remaining module using export_as for this one.
  1706. getPreprocessor()
  1707. .getHeaderSearchInfo()
  1708. .getModuleMap()
  1709. .resolveLinkAsDependencies(TopModule);
  1710. LastModuleImportLoc = ImportLoc;
  1711. LastModuleImportResult = ModuleLoadResult(Module);
  1712. return LastModuleImportResult;
  1713. }
  1714. void CompilerInstance::loadModuleFromSource(SourceLocation ImportLoc,
  1715. StringRef ModuleName,
  1716. StringRef Source) {
  1717. // Avoid creating filenames with special characters.
  1718. SmallString<128> CleanModuleName(ModuleName);
  1719. for (auto &C : CleanModuleName)
  1720. if (!isAlphanumeric(C))
  1721. C = '_';
  1722. // FIXME: Using a randomized filename here means that our intermediate .pcm
  1723. // output is nondeterministic (as .pcm files refer to each other by name).
  1724. // Can this affect the output in any way?
  1725. SmallString<128> ModuleFileName;
  1726. if (std::error_code EC = llvm::sys::fs::createTemporaryFile(
  1727. CleanModuleName, "pcm", ModuleFileName)) {
  1728. getDiagnostics().Report(ImportLoc, diag::err_fe_unable_to_open_output)
  1729. << ModuleFileName << EC.message();
  1730. return;
  1731. }
  1732. std::string ModuleMapFileName = (CleanModuleName + ".map").str();
  1733. FrontendInputFile Input(
  1734. ModuleMapFileName,
  1735. InputKind(getLanguageFromOptions(*Invocation->getLangOpts()),
  1736. InputKind::ModuleMap, /*Preprocessed*/true));
  1737. std::string NullTerminatedSource(Source.str());
  1738. auto PreBuildStep = [&](CompilerInstance &Other) {
  1739. // Create a virtual file containing our desired source.
  1740. // FIXME: We shouldn't need to do this.
  1741. const FileEntry *ModuleMapFile = Other.getFileManager().getVirtualFile(
  1742. ModuleMapFileName, NullTerminatedSource.size(), 0);
  1743. Other.getSourceManager().overrideFileContents(
  1744. ModuleMapFile,
  1745. llvm::MemoryBuffer::getMemBuffer(NullTerminatedSource.c_str()));
  1746. Other.BuiltModules = std::move(BuiltModules);
  1747. Other.DeleteBuiltModules = false;
  1748. };
  1749. auto PostBuildStep = [this](CompilerInstance &Other) {
  1750. BuiltModules = std::move(Other.BuiltModules);
  1751. };
  1752. // Build the module, inheriting any modules that we've built locally.
  1753. if (compileModuleImpl(*this, ImportLoc, ModuleName, Input, StringRef(),
  1754. ModuleFileName, PreBuildStep, PostBuildStep)) {
  1755. BuiltModules[ModuleName] = ModuleFileName.str();
  1756. llvm::sys::RemoveFileOnSignal(ModuleFileName);
  1757. }
  1758. }
  1759. void CompilerInstance::makeModuleVisible(Module *Mod,
  1760. Module::NameVisibilityKind Visibility,
  1761. SourceLocation ImportLoc) {
  1762. if (!ModuleManager)
  1763. createModuleManager();
  1764. if (!ModuleManager)
  1765. return;
  1766. ModuleManager->makeModuleVisible(Mod, Visibility, ImportLoc);
  1767. }
  1768. GlobalModuleIndex *CompilerInstance::loadGlobalModuleIndex(
  1769. SourceLocation TriggerLoc) {
  1770. if (getPreprocessor().getHeaderSearchInfo().getModuleCachePath().empty())
  1771. return nullptr;
  1772. if (!ModuleManager)
  1773. createModuleManager();
  1774. // Can't do anything if we don't have the module manager.
  1775. if (!ModuleManager)
  1776. return nullptr;
  1777. // Get an existing global index. This loads it if not already
  1778. // loaded.
  1779. ModuleManager->loadGlobalIndex();
  1780. GlobalModuleIndex *GlobalIndex = ModuleManager->getGlobalIndex();
  1781. // If the global index doesn't exist, create it.
  1782. if (!GlobalIndex && shouldBuildGlobalModuleIndex() && hasFileManager() &&
  1783. hasPreprocessor()) {
  1784. llvm::sys::fs::create_directories(
  1785. getPreprocessor().getHeaderSearchInfo().getModuleCachePath());
  1786. if (llvm::Error Err = GlobalModuleIndex::writeIndex(
  1787. getFileManager(), getPCHContainerReader(),
  1788. getPreprocessor().getHeaderSearchInfo().getModuleCachePath())) {
  1789. // FIXME this drops the error on the floor. This code is only used for
  1790. // typo correction and drops more than just this one source of errors
  1791. // (such as the directory creation failure above). It should handle the
  1792. // error.
  1793. consumeError(std::move(Err));
  1794. return nullptr;
  1795. }
  1796. ModuleManager->resetForReload();
  1797. ModuleManager->loadGlobalIndex();
  1798. GlobalIndex = ModuleManager->getGlobalIndex();
  1799. }
  1800. // For finding modules needing to be imported for fixit messages,
  1801. // we need to make the global index cover all modules, so we do that here.
  1802. if (!HaveFullGlobalModuleIndex && GlobalIndex && !buildingModule()) {
  1803. ModuleMap &MMap = getPreprocessor().getHeaderSearchInfo().getModuleMap();
  1804. bool RecreateIndex = false;
  1805. for (ModuleMap::module_iterator I = MMap.module_begin(),
  1806. E = MMap.module_end(); I != E; ++I) {
  1807. Module *TheModule = I->second;
  1808. const FileEntry *Entry = TheModule->getASTFile();
  1809. if (!Entry) {
  1810. SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path;
  1811. Path.push_back(std::make_pair(
  1812. getPreprocessor().getIdentifierInfo(TheModule->Name), TriggerLoc));
  1813. std::reverse(Path.begin(), Path.end());
  1814. // Load a module as hidden. This also adds it to the global index.
  1815. loadModule(TheModule->DefinitionLoc, Path, Module::Hidden, false);
  1816. RecreateIndex = true;
  1817. }
  1818. }
  1819. if (RecreateIndex) {
  1820. if (llvm::Error Err = GlobalModuleIndex::writeIndex(
  1821. getFileManager(), getPCHContainerReader(),
  1822. getPreprocessor().getHeaderSearchInfo().getModuleCachePath())) {
  1823. // FIXME As above, this drops the error on the floor.
  1824. consumeError(std::move(Err));
  1825. return nullptr;
  1826. }
  1827. ModuleManager->resetForReload();
  1828. ModuleManager->loadGlobalIndex();
  1829. GlobalIndex = ModuleManager->getGlobalIndex();
  1830. }
  1831. HaveFullGlobalModuleIndex = true;
  1832. }
  1833. return GlobalIndex;
  1834. }
  1835. // Check global module index for missing imports.
  1836. bool
  1837. CompilerInstance::lookupMissingImports(StringRef Name,
  1838. SourceLocation TriggerLoc) {
  1839. // Look for the symbol in non-imported modules, but only if an error
  1840. // actually occurred.
  1841. if (!buildingModule()) {
  1842. // Load global module index, or retrieve a previously loaded one.
  1843. GlobalModuleIndex *GlobalIndex = loadGlobalModuleIndex(
  1844. TriggerLoc);
  1845. // Only if we have a global index.
  1846. if (GlobalIndex) {
  1847. GlobalModuleIndex::HitSet FoundModules;
  1848. // Find the modules that reference the identifier.
  1849. // Note that this only finds top-level modules.
  1850. // We'll let diagnoseTypo find the actual declaration module.
  1851. if (GlobalIndex->lookupIdentifier(Name, FoundModules))
  1852. return true;
  1853. }
  1854. }
  1855. return false;
  1856. }
  1857. void CompilerInstance::resetAndLeakSema() { llvm::BuryPointer(takeSema()); }
  1858. void CompilerInstance::setExternalSemaSource(
  1859. IntrusiveRefCntPtr<ExternalSemaSource> ESS) {
  1860. ExternalSemaSrc = std::move(ESS);
  1861. }