CompilerInstance.cpp 82 KB

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