CompilerInstance.cpp 73 KB

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