CompilerInstance.cpp 80 KB

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