CompilerInstance.cpp 72 KB

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