CompilerInstance.cpp 60 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596
  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/Sema/CodeCompleteConsumer.h"
  32. #include "clang/Sema/Sema.h"
  33. #include "clang/Serialization/ASTReader.h"
  34. #include "clang/Serialization/GlobalModuleIndex.h"
  35. #include "llvm/ADT/Statistic.h"
  36. #include "llvm/Support/CrashRecoveryContext.h"
  37. #include "llvm/Support/Errc.h"
  38. #include "llvm/Support/FileSystem.h"
  39. #include "llvm/Support/Host.h"
  40. #include "llvm/Support/LockFileManager.h"
  41. #include "llvm/Support/MemoryBuffer.h"
  42. #include "llvm/Support/Path.h"
  43. #include "llvm/Support/Program.h"
  44. #include "llvm/Support/Signals.h"
  45. #include "llvm/Support/Timer.h"
  46. #include "llvm/Support/raw_ostream.h"
  47. #include <sys/stat.h>
  48. #include <system_error>
  49. #include <time.h>
  50. using namespace clang;
  51. CompilerInstance::CompilerInstance(bool BuildingModule)
  52. : ModuleLoader(BuildingModule),
  53. Invocation(new CompilerInvocation()), ModuleManager(nullptr),
  54. BuildGlobalModuleIndex(false), HaveFullGlobalModuleIndex(false),
  55. ModuleBuildFailed(false) {
  56. }
  57. CompilerInstance::~CompilerInstance() {
  58. assert(OutputFiles.empty() && "Still output files in flight?");
  59. }
  60. void CompilerInstance::setInvocation(CompilerInvocation *Value) {
  61. Invocation = Value;
  62. }
  63. bool CompilerInstance::shouldBuildGlobalModuleIndex() const {
  64. return (BuildGlobalModuleIndex ||
  65. (ModuleManager && ModuleManager->isGlobalIndexUnavailable() &&
  66. getFrontendOpts().GenerateGlobalModuleIndex)) &&
  67. !ModuleBuildFailed;
  68. }
  69. void CompilerInstance::setDiagnostics(DiagnosticsEngine *Value) {
  70. Diagnostics = Value;
  71. }
  72. void CompilerInstance::setTarget(TargetInfo *Value) {
  73. Target = Value;
  74. }
  75. void CompilerInstance::setFileManager(FileManager *Value) {
  76. FileMgr = Value;
  77. if (Value)
  78. VirtualFileSystem = Value->getVirtualFileSystem();
  79. else
  80. VirtualFileSystem.reset();
  81. }
  82. void CompilerInstance::setSourceManager(SourceManager *Value) {
  83. SourceMgr = Value;
  84. }
  85. void CompilerInstance::setPreprocessor(Preprocessor *Value) { PP = Value; }
  86. void CompilerInstance::setASTContext(ASTContext *Value) { Context = Value; }
  87. void CompilerInstance::setSema(Sema *S) {
  88. TheSema.reset(S);
  89. }
  90. void CompilerInstance::setASTConsumer(std::unique_ptr<ASTConsumer> Value) {
  91. Consumer = std::move(Value);
  92. }
  93. void CompilerInstance::setCodeCompletionConsumer(CodeCompleteConsumer *Value) {
  94. CompletionConsumer.reset(Value);
  95. }
  96. IntrusiveRefCntPtr<ASTReader> CompilerInstance::getModuleManager() const {
  97. return ModuleManager;
  98. }
  99. void CompilerInstance::setModuleManager(IntrusiveRefCntPtr<ASTReader> Reader) {
  100. ModuleManager = Reader;
  101. }
  102. std::shared_ptr<ModuleDependencyCollector>
  103. CompilerInstance::getModuleDepCollector() const {
  104. return ModuleDepCollector;
  105. }
  106. void CompilerInstance::setModuleDepCollector(
  107. std::shared_ptr<ModuleDependencyCollector> Collector) {
  108. ModuleDepCollector = Collector;
  109. }
  110. // Diagnostics
  111. static void SetUpDiagnosticLog(DiagnosticOptions *DiagOpts,
  112. const CodeGenOptions *CodeGenOpts,
  113. DiagnosticsEngine &Diags) {
  114. std::string ErrorInfo;
  115. bool OwnsStream = false;
  116. raw_ostream *OS = &llvm::errs();
  117. if (DiagOpts->DiagnosticLogFile != "-") {
  118. // Create the output stream.
  119. llvm::raw_fd_ostream *FileOS(new llvm::raw_fd_ostream(
  120. DiagOpts->DiagnosticLogFile.c_str(), ErrorInfo,
  121. llvm::sys::fs::F_Append | llvm::sys::fs::F_Text));
  122. if (!ErrorInfo.empty()) {
  123. Diags.Report(diag::warn_fe_cc_log_diagnostics_failure)
  124. << DiagOpts->DiagnosticLogFile << ErrorInfo;
  125. } else {
  126. FileOS->SetUnbuffered();
  127. FileOS->SetUseAtomicWrites(true);
  128. OS = FileOS;
  129. OwnsStream = true;
  130. }
  131. }
  132. // Chain in the diagnostic client which will log the diagnostics.
  133. LogDiagnosticPrinter *Logger = new LogDiagnosticPrinter(*OS, DiagOpts,
  134. OwnsStream);
  135. if (CodeGenOpts)
  136. Logger->setDwarfDebugFlags(CodeGenOpts->DwarfDebugFlags);
  137. Diags.setClient(new ChainedDiagnosticConsumer(Diags.takeClient(), Logger));
  138. }
  139. static void SetupSerializedDiagnostics(DiagnosticOptions *DiagOpts,
  140. DiagnosticsEngine &Diags,
  141. StringRef OutputFile) {
  142. std::string ErrorInfo;
  143. std::unique_ptr<llvm::raw_fd_ostream> OS;
  144. OS.reset(new llvm::raw_fd_ostream(OutputFile.str().c_str(), ErrorInfo,
  145. llvm::sys::fs::F_None));
  146. if (!ErrorInfo.empty()) {
  147. Diags.Report(diag::warn_fe_serialized_diag_failure)
  148. << OutputFile << ErrorInfo;
  149. return;
  150. }
  151. DiagnosticConsumer *SerializedConsumer =
  152. clang::serialized_diags::create(OS.release(), DiagOpts);
  153. Diags.setClient(new ChainedDiagnosticConsumer(Diags.takeClient(),
  154. SerializedConsumer));
  155. }
  156. void CompilerInstance::createDiagnostics(DiagnosticConsumer *Client,
  157. bool ShouldOwnClient) {
  158. Diagnostics = createDiagnostics(&getDiagnosticOpts(), Client,
  159. ShouldOwnClient, &getCodeGenOpts());
  160. }
  161. IntrusiveRefCntPtr<DiagnosticsEngine>
  162. CompilerInstance::createDiagnostics(DiagnosticOptions *Opts,
  163. DiagnosticConsumer *Client,
  164. bool ShouldOwnClient,
  165. const CodeGenOptions *CodeGenOpts) {
  166. IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
  167. IntrusiveRefCntPtr<DiagnosticsEngine>
  168. Diags(new DiagnosticsEngine(DiagID, Opts));
  169. // Create the diagnostic client for reporting errors or for
  170. // implementing -verify.
  171. if (Client) {
  172. Diags->setClient(Client, ShouldOwnClient);
  173. } else
  174. Diags->setClient(new TextDiagnosticPrinter(llvm::errs(), Opts));
  175. // Chain in -verify checker, if requested.
  176. if (Opts->VerifyDiagnostics)
  177. Diags->setClient(new VerifyDiagnosticConsumer(*Diags));
  178. // Chain in -diagnostic-log-file dumper, if requested.
  179. if (!Opts->DiagnosticLogFile.empty())
  180. SetUpDiagnosticLog(Opts, CodeGenOpts, *Diags);
  181. if (!Opts->DiagnosticSerializationFile.empty())
  182. SetupSerializedDiagnostics(Opts, *Diags,
  183. Opts->DiagnosticSerializationFile);
  184. // Configure our handling of diagnostics.
  185. ProcessWarningOptions(*Diags, *Opts);
  186. return Diags;
  187. }
  188. // File Manager
  189. void CompilerInstance::createFileManager() {
  190. if (!hasVirtualFileSystem()) {
  191. // TODO: choose the virtual file system based on the CompilerInvocation.
  192. setVirtualFileSystem(vfs::getRealFileSystem());
  193. }
  194. FileMgr = new FileManager(getFileSystemOpts(), VirtualFileSystem);
  195. }
  196. // Source Manager
  197. void CompilerInstance::createSourceManager(FileManager &FileMgr) {
  198. SourceMgr = new SourceManager(getDiagnostics(), FileMgr);
  199. }
  200. // Initialize the remapping of files to alternative contents, e.g.,
  201. // those specified through other files.
  202. static void InitializeFileRemapping(DiagnosticsEngine &Diags,
  203. SourceManager &SourceMgr,
  204. FileManager &FileMgr,
  205. const PreprocessorOptions &InitOpts) {
  206. // Remap files in the source manager (with buffers).
  207. for (const auto &RB : InitOpts.RemappedFileBuffers) {
  208. // Create the file entry for the file that we're mapping from.
  209. const FileEntry *FromFile =
  210. FileMgr.getVirtualFile(RB.first, RB.second->getBufferSize(), 0);
  211. if (!FromFile) {
  212. Diags.Report(diag::err_fe_remap_missing_from_file) << RB.first;
  213. if (!InitOpts.RetainRemappedFileBuffers)
  214. delete RB.second;
  215. continue;
  216. }
  217. // Override the contents of the "from" file with the contents of
  218. // the "to" file.
  219. SourceMgr.overrideFileContents(FromFile, RB.second,
  220. InitOpts.RetainRemappedFileBuffers);
  221. }
  222. // Remap files in the source manager (with other files).
  223. for (const auto &RF : InitOpts.RemappedFiles) {
  224. // Find the file that we're mapping to.
  225. const FileEntry *ToFile = FileMgr.getFile(RF.second);
  226. if (!ToFile) {
  227. Diags.Report(diag::err_fe_remap_missing_to_file) << RF.first << RF.second;
  228. continue;
  229. }
  230. // Create the file entry for the file that we're mapping from.
  231. const FileEntry *FromFile =
  232. FileMgr.getVirtualFile(RF.first, ToFile->getSize(), 0);
  233. if (!FromFile) {
  234. Diags.Report(diag::err_fe_remap_missing_from_file) << RF.first;
  235. continue;
  236. }
  237. // Override the contents of the "from" file with the contents of
  238. // the "to" file.
  239. SourceMgr.overrideFileContents(FromFile, ToFile);
  240. }
  241. SourceMgr.setOverridenFilesKeepOriginalName(
  242. InitOpts.RemappedFilesKeepOriginalName);
  243. }
  244. // Preprocessor
  245. void CompilerInstance::createPreprocessor(TranslationUnitKind TUKind) {
  246. const PreprocessorOptions &PPOpts = getPreprocessorOpts();
  247. // Create a PTH manager if we are using some form of a token cache.
  248. PTHManager *PTHMgr = nullptr;
  249. if (!PPOpts.TokenCache.empty())
  250. PTHMgr = PTHManager::Create(PPOpts.TokenCache, getDiagnostics());
  251. // Create the Preprocessor.
  252. HeaderSearch *HeaderInfo = new HeaderSearch(&getHeaderSearchOpts(),
  253. getSourceManager(),
  254. getDiagnostics(),
  255. getLangOpts(),
  256. &getTarget());
  257. PP = new Preprocessor(&getPreprocessorOpts(), getDiagnostics(), getLangOpts(),
  258. getSourceManager(), *HeaderInfo, *this, PTHMgr,
  259. /*OwnsHeaderSearch=*/true, TUKind);
  260. PP->Initialize(getTarget());
  261. // Note that this is different then passing PTHMgr to Preprocessor's ctor.
  262. // That argument is used as the IdentifierInfoLookup argument to
  263. // IdentifierTable's ctor.
  264. if (PTHMgr) {
  265. PTHMgr->setPreprocessor(&*PP);
  266. PP->setPTHManager(PTHMgr);
  267. }
  268. if (PPOpts.DetailedRecord)
  269. PP->createPreprocessingRecord();
  270. // Apply remappings to the source manager.
  271. InitializeFileRemapping(PP->getDiagnostics(), PP->getSourceManager(),
  272. PP->getFileManager(), PPOpts);
  273. // Predefine macros and configure the preprocessor.
  274. InitializePreprocessor(*PP, PPOpts, getFrontendOpts());
  275. // Initialize the header search object.
  276. ApplyHeaderSearchOptions(PP->getHeaderSearchInfo(), getHeaderSearchOpts(),
  277. PP->getLangOpts(), PP->getTargetInfo().getTriple());
  278. PP->setPreprocessedOutput(getPreprocessorOutputOpts().ShowCPP);
  279. // Set up the module path, including the hash for the
  280. // module-creation options.
  281. SmallString<256> SpecificModuleCache(
  282. getHeaderSearchOpts().ModuleCachePath);
  283. if (!getHeaderSearchOpts().DisableModuleHash)
  284. llvm::sys::path::append(SpecificModuleCache,
  285. getInvocation().getModuleHash());
  286. PP->getHeaderSearchInfo().setModuleCachePath(SpecificModuleCache);
  287. // Handle generating dependencies, if requested.
  288. const DependencyOutputOptions &DepOpts = getDependencyOutputOpts();
  289. if (!DepOpts.OutputFile.empty())
  290. TheDependencyFileGenerator.reset(
  291. DependencyFileGenerator::CreateAndAttachToPreprocessor(*PP, DepOpts));
  292. if (!DepOpts.DOTOutputFile.empty())
  293. AttachDependencyGraphGen(*PP, DepOpts.DOTOutputFile,
  294. getHeaderSearchOpts().Sysroot);
  295. for (auto &Listener : DependencyCollectors)
  296. Listener->attachToPreprocessor(*PP);
  297. // If we don't have a collector, but we are collecting module dependencies,
  298. // then we're the top level compiler instance and need to create one.
  299. if (!ModuleDepCollector && !DepOpts.ModuleDependencyOutputDir.empty())
  300. ModuleDepCollector = std::make_shared<ModuleDependencyCollector>(
  301. DepOpts.ModuleDependencyOutputDir);
  302. // Handle generating header include information, if requested.
  303. if (DepOpts.ShowHeaderIncludes)
  304. AttachHeaderIncludeGen(*PP);
  305. if (!DepOpts.HeaderIncludeOutputFile.empty()) {
  306. StringRef OutputPath = DepOpts.HeaderIncludeOutputFile;
  307. if (OutputPath == "-")
  308. OutputPath = "";
  309. AttachHeaderIncludeGen(*PP, /*ShowAllHeaders=*/true, OutputPath,
  310. /*ShowDepth=*/false);
  311. }
  312. if (DepOpts.PrintShowIncludes) {
  313. AttachHeaderIncludeGen(*PP, /*ShowAllHeaders=*/false, /*OutputPath=*/"",
  314. /*ShowDepth=*/true, /*MSStyle=*/true);
  315. }
  316. }
  317. // ASTContext
  318. void CompilerInstance::createASTContext() {
  319. Preprocessor &PP = getPreprocessor();
  320. Context = new ASTContext(getLangOpts(), PP.getSourceManager(),
  321. PP.getIdentifierTable(), PP.getSelectorTable(),
  322. PP.getBuiltinInfo());
  323. Context->InitBuiltinTypes(getTarget());
  324. }
  325. // ExternalASTSource
  326. void CompilerInstance::createPCHExternalASTSource(
  327. StringRef Path, bool DisablePCHValidation, bool AllowPCHWithCompilerErrors,
  328. void *DeserializationListener, bool OwnDeserializationListener) {
  329. IntrusiveRefCntPtr<ExternalASTSource> Source;
  330. bool Preamble = getPreprocessorOpts().PrecompiledPreambleBytes.first != 0;
  331. Source = createPCHExternalASTSource(
  332. Path, getHeaderSearchOpts().Sysroot, DisablePCHValidation,
  333. AllowPCHWithCompilerErrors, getPreprocessor(), getASTContext(),
  334. DeserializationListener, OwnDeserializationListener, Preamble,
  335. getFrontendOpts().UseGlobalModuleIndex);
  336. ModuleManager = static_cast<ASTReader*>(Source.get());
  337. getASTContext().setExternalSource(Source);
  338. }
  339. ExternalASTSource *CompilerInstance::createPCHExternalASTSource(
  340. StringRef Path, const std::string &Sysroot, bool DisablePCHValidation,
  341. bool AllowPCHWithCompilerErrors, Preprocessor &PP, ASTContext &Context,
  342. void *DeserializationListener, bool OwnDeserializationListener,
  343. bool Preamble, bool UseGlobalModuleIndex) {
  344. HeaderSearchOptions &HSOpts = PP.getHeaderSearchInfo().getHeaderSearchOpts();
  345. std::unique_ptr<ASTReader> Reader;
  346. Reader.reset(new ASTReader(PP, Context,
  347. Sysroot.empty() ? "" : Sysroot.c_str(),
  348. DisablePCHValidation,
  349. AllowPCHWithCompilerErrors,
  350. /*AllowConfigurationMismatch*/false,
  351. HSOpts.ModulesValidateSystemHeaders,
  352. UseGlobalModuleIndex));
  353. Reader->setDeserializationListener(
  354. static_cast<ASTDeserializationListener *>(DeserializationListener),
  355. /*TakeOwnership=*/OwnDeserializationListener);
  356. switch (Reader->ReadAST(Path,
  357. Preamble ? serialization::MK_Preamble
  358. : serialization::MK_PCH,
  359. SourceLocation(),
  360. ASTReader::ARR_None)) {
  361. case ASTReader::Success:
  362. // Set the predefines buffer as suggested by the PCH reader. Typically, the
  363. // predefines buffer will be empty.
  364. PP.setPredefines(Reader->getSuggestedPredefines());
  365. return Reader.release();
  366. case ASTReader::Failure:
  367. // Unrecoverable failure: don't even try to process the input file.
  368. break;
  369. case ASTReader::Missing:
  370. case ASTReader::OutOfDate:
  371. case ASTReader::VersionMismatch:
  372. case ASTReader::ConfigurationMismatch:
  373. case ASTReader::HadErrors:
  374. // No suitable PCH file could be found. Return an error.
  375. break;
  376. }
  377. return nullptr;
  378. }
  379. // Code Completion
  380. static bool EnableCodeCompletion(Preprocessor &PP,
  381. const std::string &Filename,
  382. unsigned Line,
  383. unsigned Column) {
  384. // Tell the source manager to chop off the given file at a specific
  385. // line and column.
  386. const FileEntry *Entry = PP.getFileManager().getFile(Filename);
  387. if (!Entry) {
  388. PP.getDiagnostics().Report(diag::err_fe_invalid_code_complete_file)
  389. << Filename;
  390. return true;
  391. }
  392. // Truncate the named file at the given line/column.
  393. PP.SetCodeCompletionPoint(Entry, Line, Column);
  394. return false;
  395. }
  396. void CompilerInstance::createCodeCompletionConsumer() {
  397. const ParsedSourceLocation &Loc = getFrontendOpts().CodeCompletionAt;
  398. if (!CompletionConsumer) {
  399. setCodeCompletionConsumer(
  400. createCodeCompletionConsumer(getPreprocessor(),
  401. Loc.FileName, Loc.Line, Loc.Column,
  402. getFrontendOpts().CodeCompleteOpts,
  403. llvm::outs()));
  404. if (!CompletionConsumer)
  405. return;
  406. } else if (EnableCodeCompletion(getPreprocessor(), Loc.FileName,
  407. Loc.Line, Loc.Column)) {
  408. setCodeCompletionConsumer(nullptr);
  409. return;
  410. }
  411. if (CompletionConsumer->isOutputBinary() &&
  412. llvm::sys::ChangeStdoutToBinary()) {
  413. getPreprocessor().getDiagnostics().Report(diag::err_fe_stdout_binary);
  414. setCodeCompletionConsumer(nullptr);
  415. }
  416. }
  417. void CompilerInstance::createFrontendTimer() {
  418. FrontendTimer.reset(new llvm::Timer("Clang front-end timer"));
  419. }
  420. CodeCompleteConsumer *
  421. CompilerInstance::createCodeCompletionConsumer(Preprocessor &PP,
  422. const std::string &Filename,
  423. unsigned Line,
  424. unsigned Column,
  425. const CodeCompleteOptions &Opts,
  426. raw_ostream &OS) {
  427. if (EnableCodeCompletion(PP, Filename, Line, Column))
  428. return nullptr;
  429. // Set up the creation routine for code-completion.
  430. return new PrintingCodeCompleteConsumer(Opts, OS);
  431. }
  432. void CompilerInstance::createSema(TranslationUnitKind TUKind,
  433. CodeCompleteConsumer *CompletionConsumer) {
  434. TheSema.reset(new Sema(getPreprocessor(), getASTContext(), getASTConsumer(),
  435. TUKind, CompletionConsumer));
  436. }
  437. // Output Files
  438. void CompilerInstance::addOutputFile(const OutputFile &OutFile) {
  439. assert(OutFile.OS && "Attempt to add empty stream to output list!");
  440. OutputFiles.push_back(OutFile);
  441. }
  442. void CompilerInstance::clearOutputFiles(bool EraseFiles) {
  443. for (std::list<OutputFile>::iterator
  444. it = OutputFiles.begin(), ie = OutputFiles.end(); it != ie; ++it) {
  445. delete it->OS;
  446. if (!it->TempFilename.empty()) {
  447. if (EraseFiles) {
  448. llvm::sys::fs::remove(it->TempFilename);
  449. } else {
  450. SmallString<128> NewOutFile(it->Filename);
  451. // If '-working-directory' was passed, the output filename should be
  452. // relative to that.
  453. FileMgr->FixupRelativePath(NewOutFile);
  454. if (std::error_code ec =
  455. llvm::sys::fs::rename(it->TempFilename, NewOutFile.str())) {
  456. getDiagnostics().Report(diag::err_unable_to_rename_temp)
  457. << it->TempFilename << it->Filename << ec.message();
  458. llvm::sys::fs::remove(it->TempFilename);
  459. }
  460. }
  461. } else if (!it->Filename.empty() && EraseFiles)
  462. llvm::sys::fs::remove(it->Filename);
  463. }
  464. OutputFiles.clear();
  465. }
  466. llvm::raw_fd_ostream *
  467. CompilerInstance::createDefaultOutputFile(bool Binary,
  468. StringRef InFile,
  469. StringRef Extension) {
  470. return createOutputFile(getFrontendOpts().OutputFile, Binary,
  471. /*RemoveFileOnSignal=*/true, InFile, Extension,
  472. /*UseTemporary=*/true);
  473. }
  474. llvm::raw_null_ostream *CompilerInstance::createNullOutputFile() {
  475. llvm::raw_null_ostream *OS = new llvm::raw_null_ostream();
  476. addOutputFile(OutputFile("", "", OS));
  477. return OS;
  478. }
  479. llvm::raw_fd_ostream *
  480. CompilerInstance::createOutputFile(StringRef OutputPath,
  481. bool Binary, bool RemoveFileOnSignal,
  482. StringRef InFile,
  483. StringRef Extension,
  484. bool UseTemporary,
  485. bool CreateMissingDirectories) {
  486. std::string Error, OutputPathName, TempPathName;
  487. llvm::raw_fd_ostream *OS = createOutputFile(OutputPath, Error, Binary,
  488. RemoveFileOnSignal,
  489. InFile, Extension,
  490. UseTemporary,
  491. CreateMissingDirectories,
  492. &OutputPathName,
  493. &TempPathName);
  494. if (!OS) {
  495. getDiagnostics().Report(diag::err_fe_unable_to_open_output)
  496. << OutputPath << Error;
  497. return nullptr;
  498. }
  499. // Add the output file -- but don't try to remove "-", since this means we are
  500. // using stdin.
  501. addOutputFile(OutputFile((OutputPathName != "-") ? OutputPathName : "",
  502. TempPathName, OS));
  503. return OS;
  504. }
  505. llvm::raw_fd_ostream *
  506. CompilerInstance::createOutputFile(StringRef OutputPath,
  507. std::string &Error,
  508. bool Binary,
  509. bool RemoveFileOnSignal,
  510. StringRef InFile,
  511. StringRef Extension,
  512. bool UseTemporary,
  513. bool CreateMissingDirectories,
  514. std::string *ResultPathName,
  515. std::string *TempPathName) {
  516. assert((!CreateMissingDirectories || UseTemporary) &&
  517. "CreateMissingDirectories is only allowed when using temporary files");
  518. std::string OutFile, TempFile;
  519. if (!OutputPath.empty()) {
  520. OutFile = OutputPath;
  521. } else if (InFile == "-") {
  522. OutFile = "-";
  523. } else if (!Extension.empty()) {
  524. SmallString<128> Path(InFile);
  525. llvm::sys::path::replace_extension(Path, Extension);
  526. OutFile = Path.str();
  527. } else {
  528. OutFile = "-";
  529. }
  530. std::unique_ptr<llvm::raw_fd_ostream> OS;
  531. std::string OSFile;
  532. if (UseTemporary) {
  533. if (OutFile == "-")
  534. UseTemporary = false;
  535. else {
  536. llvm::sys::fs::file_status Status;
  537. llvm::sys::fs::status(OutputPath, Status);
  538. if (llvm::sys::fs::exists(Status)) {
  539. // Fail early if we can't write to the final destination.
  540. if (!llvm::sys::fs::can_write(OutputPath))
  541. return nullptr;
  542. // Don't use a temporary if the output is a special file. This handles
  543. // things like '-o /dev/null'
  544. if (!llvm::sys::fs::is_regular_file(Status))
  545. UseTemporary = false;
  546. }
  547. }
  548. }
  549. if (UseTemporary) {
  550. // Create a temporary file.
  551. SmallString<128> TempPath;
  552. TempPath = OutFile;
  553. TempPath += "-%%%%%%%%";
  554. int fd;
  555. std::error_code EC =
  556. llvm::sys::fs::createUniqueFile(TempPath.str(), fd, TempPath);
  557. if (CreateMissingDirectories &&
  558. EC == llvm::errc::no_such_file_or_directory) {
  559. StringRef Parent = llvm::sys::path::parent_path(OutputPath);
  560. EC = llvm::sys::fs::create_directories(Parent);
  561. if (!EC) {
  562. EC = llvm::sys::fs::createUniqueFile(TempPath.str(), fd, TempPath);
  563. }
  564. }
  565. if (!EC) {
  566. OS.reset(new llvm::raw_fd_ostream(fd, /*shouldClose=*/true));
  567. OSFile = TempFile = TempPath.str();
  568. }
  569. // If we failed to create the temporary, fallback to writing to the file
  570. // directly. This handles the corner case where we cannot write to the
  571. // directory, but can write to the file.
  572. }
  573. if (!OS) {
  574. OSFile = OutFile;
  575. OS.reset(new llvm::raw_fd_ostream(
  576. OSFile.c_str(), Error,
  577. (Binary ? llvm::sys::fs::F_None : llvm::sys::fs::F_Text)));
  578. if (!Error.empty())
  579. return nullptr;
  580. }
  581. // Make sure the out stream file gets removed if we crash.
  582. if (RemoveFileOnSignal)
  583. llvm::sys::RemoveFileOnSignal(OSFile);
  584. if (ResultPathName)
  585. *ResultPathName = OutFile;
  586. if (TempPathName)
  587. *TempPathName = TempFile;
  588. return OS.release();
  589. }
  590. // Initialization Utilities
  591. bool CompilerInstance::InitializeSourceManager(const FrontendInputFile &Input){
  592. return InitializeSourceManager(Input, getDiagnostics(),
  593. getFileManager(), getSourceManager(),
  594. getFrontendOpts());
  595. }
  596. bool CompilerInstance::InitializeSourceManager(const FrontendInputFile &Input,
  597. DiagnosticsEngine &Diags,
  598. FileManager &FileMgr,
  599. SourceManager &SourceMgr,
  600. const FrontendOptions &Opts) {
  601. SrcMgr::CharacteristicKind
  602. Kind = Input.isSystem() ? SrcMgr::C_System : SrcMgr::C_User;
  603. if (Input.isBuffer()) {
  604. SourceMgr.setMainFileID(SourceMgr.createFileID(Input.getBuffer(), Kind));
  605. assert(!SourceMgr.getMainFileID().isInvalid() &&
  606. "Couldn't establish MainFileID!");
  607. return true;
  608. }
  609. StringRef InputFile = Input.getFile();
  610. // Figure out where to get and map in the main file.
  611. if (InputFile != "-") {
  612. const FileEntry *File = FileMgr.getFile(InputFile, /*OpenFile=*/true);
  613. if (!File) {
  614. Diags.Report(diag::err_fe_error_reading) << InputFile;
  615. return false;
  616. }
  617. // The natural SourceManager infrastructure can't currently handle named
  618. // pipes, but we would at least like to accept them for the main
  619. // file. Detect them here, read them with the volatile flag so FileMgr will
  620. // pick up the correct size, and simply override their contents as we do for
  621. // STDIN.
  622. if (File->isNamedPipe()) {
  623. std::string ErrorStr;
  624. if (llvm::MemoryBuffer *MB =
  625. FileMgr.getBufferForFile(File, &ErrorStr, /*isVolatile=*/true)) {
  626. // Create a new virtual file that will have the correct size.
  627. File = FileMgr.getVirtualFile(InputFile, MB->getBufferSize(), 0);
  628. SourceMgr.overrideFileContents(File, MB);
  629. } else {
  630. Diags.Report(diag::err_cannot_open_file) << InputFile << ErrorStr;
  631. return false;
  632. }
  633. }
  634. SourceMgr.setMainFileID(
  635. SourceMgr.createFileID(File, SourceLocation(), Kind));
  636. } else {
  637. llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> SBOrErr =
  638. llvm::MemoryBuffer::getSTDIN();
  639. if (std::error_code EC = SBOrErr.getError()) {
  640. Diags.Report(diag::err_fe_error_reading_stdin) << EC.message();
  641. return false;
  642. }
  643. std::unique_ptr<llvm::MemoryBuffer> SB = std::move(SBOrErr.get());
  644. const FileEntry *File = FileMgr.getVirtualFile(SB->getBufferIdentifier(),
  645. SB->getBufferSize(), 0);
  646. SourceMgr.setMainFileID(
  647. SourceMgr.createFileID(File, SourceLocation(), Kind));
  648. SourceMgr.overrideFileContents(File, SB.release());
  649. }
  650. assert(!SourceMgr.getMainFileID().isInvalid() &&
  651. "Couldn't establish MainFileID!");
  652. return true;
  653. }
  654. // High-Level Operations
  655. bool CompilerInstance::ExecuteAction(FrontendAction &Act) {
  656. assert(hasDiagnostics() && "Diagnostics engine is not initialized!");
  657. assert(!getFrontendOpts().ShowHelp && "Client must handle '-help'!");
  658. assert(!getFrontendOpts().ShowVersion && "Client must handle '-version'!");
  659. // FIXME: Take this as an argument, once all the APIs we used have moved to
  660. // taking it as an input instead of hard-coding llvm::errs.
  661. raw_ostream &OS = llvm::errs();
  662. // Create the target instance.
  663. setTarget(TargetInfo::CreateTargetInfo(getDiagnostics(),
  664. getInvocation().TargetOpts));
  665. if (!hasTarget())
  666. return false;
  667. // Inform the target of the language options.
  668. //
  669. // FIXME: We shouldn't need to do this, the target should be immutable once
  670. // created. This complexity should be lifted elsewhere.
  671. getTarget().adjust(getLangOpts());
  672. // rewriter project will change target built-in bool type from its default.
  673. if (getFrontendOpts().ProgramAction == frontend::RewriteObjC)
  674. getTarget().noSignedCharForObjCBool();
  675. // Validate/process some options.
  676. if (getHeaderSearchOpts().Verbose)
  677. OS << "clang -cc1 version " CLANG_VERSION_STRING
  678. << " based upon " << BACKEND_PACKAGE_STRING
  679. << " default target " << llvm::sys::getDefaultTargetTriple() << "\n";
  680. if (getFrontendOpts().ShowTimers)
  681. createFrontendTimer();
  682. if (getFrontendOpts().ShowStats)
  683. llvm::EnableStatistics();
  684. for (unsigned i = 0, e = getFrontendOpts().Inputs.size(); i != e; ++i) {
  685. // Reset the ID tables if we are reusing the SourceManager.
  686. if (hasSourceManager())
  687. getSourceManager().clearIDTables();
  688. if (Act.BeginSourceFile(*this, getFrontendOpts().Inputs[i])) {
  689. Act.Execute();
  690. Act.EndSourceFile();
  691. }
  692. }
  693. // Notify the diagnostic client that all files were processed.
  694. getDiagnostics().getClient()->finish();
  695. if (getDiagnosticOpts().ShowCarets) {
  696. // We can have multiple diagnostics sharing one diagnostic client.
  697. // Get the total number of warnings/errors from the client.
  698. unsigned NumWarnings = getDiagnostics().getClient()->getNumWarnings();
  699. unsigned NumErrors = getDiagnostics().getClient()->getNumErrors();
  700. if (NumWarnings)
  701. OS << NumWarnings << " warning" << (NumWarnings == 1 ? "" : "s");
  702. if (NumWarnings && NumErrors)
  703. OS << " and ";
  704. if (NumErrors)
  705. OS << NumErrors << " error" << (NumErrors == 1 ? "" : "s");
  706. if (NumWarnings || NumErrors)
  707. OS << " generated.\n";
  708. }
  709. if (getFrontendOpts().ShowStats && hasFileManager()) {
  710. getFileManager().PrintStats();
  711. OS << "\n";
  712. }
  713. return !getDiagnostics().getClient()->getNumErrors();
  714. }
  715. /// \brief Determine the appropriate source input kind based on language
  716. /// options.
  717. static InputKind getSourceInputKindFromOptions(const LangOptions &LangOpts) {
  718. if (LangOpts.OpenCL)
  719. return IK_OpenCL;
  720. if (LangOpts.CUDA)
  721. return IK_CUDA;
  722. if (LangOpts.ObjC1)
  723. return LangOpts.CPlusPlus? IK_ObjCXX : IK_ObjC;
  724. return LangOpts.CPlusPlus? IK_CXX : IK_C;
  725. }
  726. /// \brief Compile a module file for the given module, using the options
  727. /// provided by the importing compiler instance.
  728. static void compileModuleImpl(CompilerInstance &ImportingInstance,
  729. SourceLocation ImportLoc,
  730. Module *Module,
  731. StringRef ModuleFileName) {
  732. ModuleMap &ModMap
  733. = ImportingInstance.getPreprocessor().getHeaderSearchInfo().getModuleMap();
  734. // Construct a compiler invocation for creating this module.
  735. IntrusiveRefCntPtr<CompilerInvocation> Invocation
  736. (new CompilerInvocation(ImportingInstance.getInvocation()));
  737. PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
  738. // For any options that aren't intended to affect how a module is built,
  739. // reset them to their default values.
  740. Invocation->getLangOpts()->resetNonModularOptions();
  741. PPOpts.resetNonModularOptions();
  742. // Remove any macro definitions that are explicitly ignored by the module.
  743. // They aren't supposed to affect how the module is built anyway.
  744. const HeaderSearchOptions &HSOpts = Invocation->getHeaderSearchOpts();
  745. PPOpts.Macros.erase(
  746. std::remove_if(PPOpts.Macros.begin(), PPOpts.Macros.end(),
  747. [&HSOpts](const std::pair<std::string, bool> &def) {
  748. StringRef MacroDef = def.first;
  749. return HSOpts.ModulesIgnoreMacros.count(MacroDef.split('=').first) > 0;
  750. }),
  751. PPOpts.Macros.end());
  752. // Note the name of the module we're building.
  753. Invocation->getLangOpts()->CurrentModule = Module->getTopLevelModuleName();
  754. // Make sure that the failed-module structure has been allocated in
  755. // the importing instance, and propagate the pointer to the newly-created
  756. // instance.
  757. PreprocessorOptions &ImportingPPOpts
  758. = ImportingInstance.getInvocation().getPreprocessorOpts();
  759. if (!ImportingPPOpts.FailedModules)
  760. ImportingPPOpts.FailedModules = new PreprocessorOptions::FailedModulesSet;
  761. PPOpts.FailedModules = ImportingPPOpts.FailedModules;
  762. // If there is a module map file, build the module using the module map.
  763. // Set up the inputs/outputs so that we build the module from its umbrella
  764. // header.
  765. FrontendOptions &FrontendOpts = Invocation->getFrontendOpts();
  766. FrontendOpts.OutputFile = ModuleFileName.str();
  767. FrontendOpts.DisableFree = false;
  768. FrontendOpts.GenerateGlobalModuleIndex = false;
  769. FrontendOpts.Inputs.clear();
  770. InputKind IK = getSourceInputKindFromOptions(*Invocation->getLangOpts());
  771. // Don't free the remapped file buffers; they are owned by our caller.
  772. PPOpts.RetainRemappedFileBuffers = true;
  773. Invocation->getDiagnosticOpts().VerifyDiagnostics = 0;
  774. assert(ImportingInstance.getInvocation().getModuleHash() ==
  775. Invocation->getModuleHash() && "Module hash mismatch!");
  776. // Construct a compiler instance that will be used to actually create the
  777. // module.
  778. CompilerInstance Instance(/*BuildingModule=*/true);
  779. Instance.setInvocation(&*Invocation);
  780. Instance.createDiagnostics(new ForwardingDiagnosticConsumer(
  781. ImportingInstance.getDiagnosticClient()),
  782. /*ShouldOwnClient=*/true);
  783. Instance.setVirtualFileSystem(&ImportingInstance.getVirtualFileSystem());
  784. // Note that this module is part of the module build stack, so that we
  785. // can detect cycles in the module graph.
  786. Instance.setFileManager(&ImportingInstance.getFileManager());
  787. Instance.createSourceManager(Instance.getFileManager());
  788. SourceManager &SourceMgr = Instance.getSourceManager();
  789. SourceMgr.setModuleBuildStack(
  790. ImportingInstance.getSourceManager().getModuleBuildStack());
  791. SourceMgr.pushModuleBuildStack(Module->getTopLevelModuleName(),
  792. FullSourceLoc(ImportLoc, ImportingInstance.getSourceManager()));
  793. // If we're collecting module dependencies, we need to share a collector
  794. // between all of the module CompilerInstances.
  795. Instance.setModuleDepCollector(ImportingInstance.getModuleDepCollector());
  796. // Get or create the module map that we'll use to build this module.
  797. std::string InferredModuleMapContent;
  798. if (const FileEntry *ModuleMapFile =
  799. ModMap.getContainingModuleMapFile(Module)) {
  800. // Use the module map where this module resides.
  801. FrontendOpts.Inputs.push_back(
  802. FrontendInputFile(ModuleMapFile->getName(), IK));
  803. } else {
  804. llvm::raw_string_ostream OS(InferredModuleMapContent);
  805. Module->print(OS);
  806. OS.flush();
  807. FrontendOpts.Inputs.push_back(
  808. FrontendInputFile("__inferred_module.map", IK));
  809. llvm::MemoryBuffer *ModuleMapBuffer =
  810. llvm::MemoryBuffer::getMemBuffer(InferredModuleMapContent);
  811. ModuleMapFile = Instance.getFileManager().getVirtualFile(
  812. "__inferred_module.map", InferredModuleMapContent.size(), 0);
  813. SourceMgr.overrideFileContents(ModuleMapFile, ModuleMapBuffer);
  814. }
  815. // Construct a module-generating action. Passing through Module->ModuleMap is
  816. // safe because the FileManager is shared between the compiler instances.
  817. GenerateModuleAction CreateModuleAction(Module->ModuleMap, Module->IsSystem);
  818. // Execute the action to actually build the module in-place. Use a separate
  819. // thread so that we get a stack large enough.
  820. const unsigned ThreadStackSize = 8 << 20;
  821. llvm::CrashRecoveryContext CRC;
  822. CRC.RunSafelyOnThread([&]() { Instance.ExecuteAction(CreateModuleAction); },
  823. ThreadStackSize);
  824. // Delete the temporary module map file.
  825. // FIXME: Even though we're executing under crash protection, it would still
  826. // be nice to do this with RemoveFileOnSignal when we can. However, that
  827. // doesn't make sense for all clients, so clean this up manually.
  828. Instance.clearOutputFiles(/*EraseFiles=*/true);
  829. // We've rebuilt a module. If we're allowed to generate or update the global
  830. // module index, record that fact in the importing compiler instance.
  831. if (ImportingInstance.getFrontendOpts().GenerateGlobalModuleIndex) {
  832. ImportingInstance.setBuildGlobalModuleIndex(true);
  833. }
  834. }
  835. static bool compileAndLoadModule(CompilerInstance &ImportingInstance,
  836. SourceLocation ImportLoc,
  837. SourceLocation ModuleNameLoc,
  838. Module *Module,
  839. StringRef ModuleFileName) {
  840. // FIXME: have LockFileManager return an error_code so that we can
  841. // avoid the mkdir when the directory already exists.
  842. StringRef Dir = llvm::sys::path::parent_path(ModuleFileName);
  843. llvm::sys::fs::create_directories(Dir);
  844. while (1) {
  845. unsigned ModuleLoadCapabilities = ASTReader::ARR_Missing;
  846. llvm::LockFileManager Locked(ModuleFileName);
  847. switch (Locked) {
  848. case llvm::LockFileManager::LFS_Error:
  849. return false;
  850. case llvm::LockFileManager::LFS_Owned:
  851. // We're responsible for building the module ourselves.
  852. // FIXME: if there are errors, don't attempt to load the module.
  853. compileModuleImpl(ImportingInstance, ModuleNameLoc, Module,
  854. ModuleFileName);
  855. break;
  856. case llvm::LockFileManager::LFS_Shared:
  857. // Someone else is responsible for building the module. Wait for them to
  858. // finish.
  859. if (Locked.waitForUnlock() == llvm::LockFileManager::Res_OwnerDied)
  860. continue; // try again to get the lock.
  861. ModuleLoadCapabilities |= ASTReader::ARR_OutOfDate;
  862. break;
  863. }
  864. // Try to read the module file, now that we've compiled it.
  865. ASTReader::ASTReadResult ReadResult =
  866. ImportingInstance.getModuleManager()->ReadAST(
  867. ModuleFileName, serialization::MK_Module, ImportLoc,
  868. ModuleLoadCapabilities);
  869. if (ReadResult == ASTReader::OutOfDate &&
  870. Locked == llvm::LockFileManager::LFS_Shared) {
  871. // The module may be out of date in the presence of file system races,
  872. // or if one of its imports depends on header search paths that are not
  873. // consistent with this ImportingInstance. Try again...
  874. continue;
  875. } else if (ReadResult == ASTReader::Missing) {
  876. ImportingInstance.getDiagnostics().Report(ModuleNameLoc,
  877. diag::err_module_not_built)
  878. << Module->Name << SourceRange(ImportLoc, ModuleNameLoc);
  879. }
  880. return ReadResult == ASTReader::Success;
  881. }
  882. }
  883. /// \brief Diagnose differences between the current definition of the given
  884. /// configuration macro and the definition provided on the command line.
  885. static void checkConfigMacro(Preprocessor &PP, StringRef ConfigMacro,
  886. Module *Mod, SourceLocation ImportLoc) {
  887. IdentifierInfo *Id = PP.getIdentifierInfo(ConfigMacro);
  888. SourceManager &SourceMgr = PP.getSourceManager();
  889. // If this identifier has never had a macro definition, then it could
  890. // not have changed.
  891. if (!Id->hadMacroDefinition())
  892. return;
  893. // If this identifier does not currently have a macro definition,
  894. // check whether it had one on the command line.
  895. if (!Id->hasMacroDefinition()) {
  896. MacroDirective::DefInfo LatestDef =
  897. PP.getMacroDirectiveHistory(Id)->getDefinition();
  898. for (MacroDirective::DefInfo Def = LatestDef; Def;
  899. Def = Def.getPreviousDefinition()) {
  900. FileID FID = SourceMgr.getFileID(Def.getLocation());
  901. if (FID.isInvalid())
  902. continue;
  903. // We only care about the predefines buffer.
  904. if (FID != PP.getPredefinesFileID())
  905. continue;
  906. // This macro was defined on the command line, then #undef'd later.
  907. // Complain.
  908. PP.Diag(ImportLoc, diag::warn_module_config_macro_undef)
  909. << true << ConfigMacro << Mod->getFullModuleName();
  910. if (LatestDef.isUndefined())
  911. PP.Diag(LatestDef.getUndefLocation(), diag::note_module_def_undef_here)
  912. << true;
  913. return;
  914. }
  915. // Okay: no definition in the predefines buffer.
  916. return;
  917. }
  918. // This identifier has a macro definition. Check whether we had a definition
  919. // on the command line.
  920. MacroDirective::DefInfo LatestDef =
  921. PP.getMacroDirectiveHistory(Id)->getDefinition();
  922. MacroDirective::DefInfo PredefinedDef;
  923. for (MacroDirective::DefInfo Def = LatestDef; Def;
  924. Def = Def.getPreviousDefinition()) {
  925. FileID FID = SourceMgr.getFileID(Def.getLocation());
  926. if (FID.isInvalid())
  927. continue;
  928. // We only care about the predefines buffer.
  929. if (FID != PP.getPredefinesFileID())
  930. continue;
  931. PredefinedDef = Def;
  932. break;
  933. }
  934. // If there was no definition for this macro in the predefines buffer,
  935. // complain.
  936. if (!PredefinedDef ||
  937. (!PredefinedDef.getLocation().isValid() &&
  938. PredefinedDef.getUndefLocation().isValid())) {
  939. PP.Diag(ImportLoc, diag::warn_module_config_macro_undef)
  940. << false << ConfigMacro << Mod->getFullModuleName();
  941. PP.Diag(LatestDef.getLocation(), diag::note_module_def_undef_here)
  942. << false;
  943. return;
  944. }
  945. // If the current macro definition is the same as the predefined macro
  946. // definition, it's okay.
  947. if (LatestDef.getMacroInfo() == PredefinedDef.getMacroInfo() ||
  948. LatestDef.getMacroInfo()->isIdenticalTo(*PredefinedDef.getMacroInfo(),PP,
  949. /*Syntactically=*/true))
  950. return;
  951. // The macro definitions differ.
  952. PP.Diag(ImportLoc, diag::warn_module_config_macro_undef)
  953. << false << ConfigMacro << Mod->getFullModuleName();
  954. PP.Diag(LatestDef.getLocation(), diag::note_module_def_undef_here)
  955. << false;
  956. }
  957. /// \brief Write a new timestamp file with the given path.
  958. static void writeTimestampFile(StringRef TimestampFile) {
  959. std::string ErrorInfo;
  960. llvm::raw_fd_ostream Out(TimestampFile.str().c_str(), ErrorInfo,
  961. llvm::sys::fs::F_None);
  962. }
  963. /// \brief Prune the module cache of modules that haven't been accessed in
  964. /// a long time.
  965. static void pruneModuleCache(const HeaderSearchOptions &HSOpts) {
  966. struct stat StatBuf;
  967. llvm::SmallString<128> TimestampFile;
  968. TimestampFile = HSOpts.ModuleCachePath;
  969. llvm::sys::path::append(TimestampFile, "modules.timestamp");
  970. // Try to stat() the timestamp file.
  971. if (::stat(TimestampFile.c_str(), &StatBuf)) {
  972. // If the timestamp file wasn't there, create one now.
  973. if (errno == ENOENT) {
  974. writeTimestampFile(TimestampFile);
  975. }
  976. return;
  977. }
  978. // Check whether the time stamp is older than our pruning interval.
  979. // If not, do nothing.
  980. time_t TimeStampModTime = StatBuf.st_mtime;
  981. time_t CurrentTime = time(nullptr);
  982. if (CurrentTime - TimeStampModTime <= time_t(HSOpts.ModuleCachePruneInterval))
  983. return;
  984. // Write a new timestamp file so that nobody else attempts to prune.
  985. // There is a benign race condition here, if two Clang instances happen to
  986. // notice at the same time that the timestamp is out-of-date.
  987. writeTimestampFile(TimestampFile);
  988. // Walk the entire module cache, looking for unused module files and module
  989. // indices.
  990. std::error_code EC;
  991. SmallString<128> ModuleCachePathNative;
  992. llvm::sys::path::native(HSOpts.ModuleCachePath, ModuleCachePathNative);
  993. for (llvm::sys::fs::directory_iterator
  994. Dir(ModuleCachePathNative.str(), EC), DirEnd;
  995. Dir != DirEnd && !EC; Dir.increment(EC)) {
  996. // If we don't have a directory, there's nothing to look into.
  997. if (!llvm::sys::fs::is_directory(Dir->path()))
  998. continue;
  999. // Walk all of the files within this directory.
  1000. for (llvm::sys::fs::directory_iterator File(Dir->path(), EC), FileEnd;
  1001. File != FileEnd && !EC; File.increment(EC)) {
  1002. // We only care about module and global module index files.
  1003. StringRef Extension = llvm::sys::path::extension(File->path());
  1004. if (Extension != ".pcm" && Extension != ".timestamp" &&
  1005. llvm::sys::path::filename(File->path()) != "modules.idx")
  1006. continue;
  1007. // Look at this file. If we can't stat it, there's nothing interesting
  1008. // there.
  1009. if (::stat(File->path().c_str(), &StatBuf))
  1010. continue;
  1011. // If the file has been used recently enough, leave it there.
  1012. time_t FileAccessTime = StatBuf.st_atime;
  1013. if (CurrentTime - FileAccessTime <=
  1014. time_t(HSOpts.ModuleCachePruneAfter)) {
  1015. continue;
  1016. }
  1017. // Remove the file.
  1018. llvm::sys::fs::remove(File->path());
  1019. // Remove the timestamp file.
  1020. std::string TimpestampFilename = File->path() + ".timestamp";
  1021. llvm::sys::fs::remove(TimpestampFilename);
  1022. }
  1023. // If we removed all of the files in the directory, remove the directory
  1024. // itself.
  1025. if (llvm::sys::fs::directory_iterator(Dir->path(), EC) ==
  1026. llvm::sys::fs::directory_iterator() && !EC)
  1027. llvm::sys::fs::remove(Dir->path());
  1028. }
  1029. }
  1030. void CompilerInstance::createModuleManager() {
  1031. if (!ModuleManager) {
  1032. if (!hasASTContext())
  1033. createASTContext();
  1034. // If we're not recursively building a module, check whether we
  1035. // need to prune the module cache.
  1036. if (getSourceManager().getModuleBuildStack().empty() &&
  1037. getHeaderSearchOpts().ModuleCachePruneInterval > 0 &&
  1038. getHeaderSearchOpts().ModuleCachePruneAfter > 0) {
  1039. pruneModuleCache(getHeaderSearchOpts());
  1040. }
  1041. HeaderSearchOptions &HSOpts = getHeaderSearchOpts();
  1042. std::string Sysroot = HSOpts.Sysroot;
  1043. const PreprocessorOptions &PPOpts = getPreprocessorOpts();
  1044. ModuleManager = new ASTReader(getPreprocessor(), *Context,
  1045. Sysroot.empty() ? "" : Sysroot.c_str(),
  1046. PPOpts.DisablePCHValidation,
  1047. /*AllowASTWithCompilerErrors=*/false,
  1048. /*AllowConfigurationMismatch=*/false,
  1049. HSOpts.ModulesValidateSystemHeaders,
  1050. getFrontendOpts().UseGlobalModuleIndex);
  1051. if (hasASTConsumer()) {
  1052. ModuleManager->setDeserializationListener(
  1053. getASTConsumer().GetASTDeserializationListener());
  1054. getASTContext().setASTMutationListener(
  1055. getASTConsumer().GetASTMutationListener());
  1056. }
  1057. getASTContext().setExternalSource(ModuleManager);
  1058. if (hasSema())
  1059. ModuleManager->InitializeSema(getSema());
  1060. if (hasASTConsumer())
  1061. ModuleManager->StartTranslationUnit(&getASTConsumer());
  1062. }
  1063. }
  1064. ModuleLoadResult
  1065. CompilerInstance::loadModule(SourceLocation ImportLoc,
  1066. ModuleIdPath Path,
  1067. Module::NameVisibilityKind Visibility,
  1068. bool IsInclusionDirective) {
  1069. // Determine what file we're searching from.
  1070. StringRef ModuleName = Path[0].first->getName();
  1071. SourceLocation ModuleNameLoc = Path[0].second;
  1072. // If we've already handled this import, just return the cached result.
  1073. // This one-element cache is important to eliminate redundant diagnostics
  1074. // when both the preprocessor and parser see the same import declaration.
  1075. if (!ImportLoc.isInvalid() && LastModuleImportLoc == ImportLoc) {
  1076. // Make the named module visible.
  1077. if (LastModuleImportResult && ModuleName != getLangOpts().CurrentModule)
  1078. ModuleManager->makeModuleVisible(LastModuleImportResult, Visibility,
  1079. ImportLoc, /*Complain=*/false);
  1080. return LastModuleImportResult;
  1081. }
  1082. clang::Module *Module = nullptr;
  1083. // If we don't already have information on this module, load the module now.
  1084. llvm::DenseMap<const IdentifierInfo *, clang::Module *>::iterator Known
  1085. = KnownModules.find(Path[0].first);
  1086. if (Known != KnownModules.end()) {
  1087. // Retrieve the cached top-level module.
  1088. Module = Known->second;
  1089. } else if (ModuleName == getLangOpts().CurrentModule) {
  1090. // This is the module we're building.
  1091. Module = PP->getHeaderSearchInfo().lookupModule(ModuleName);
  1092. Known = KnownModules.insert(std::make_pair(Path[0].first, Module)).first;
  1093. } else {
  1094. // Search for a module with the given name.
  1095. Module = PP->getHeaderSearchInfo().lookupModule(ModuleName);
  1096. if (!Module) {
  1097. getDiagnostics().Report(ModuleNameLoc, diag::err_module_not_found)
  1098. << ModuleName
  1099. << SourceRange(ImportLoc, ModuleNameLoc);
  1100. ModuleBuildFailed = true;
  1101. return ModuleLoadResult();
  1102. }
  1103. std::string ModuleFileName =
  1104. PP->getHeaderSearchInfo().getModuleFileName(Module);
  1105. // If we don't already have an ASTReader, create one now.
  1106. if (!ModuleManager)
  1107. createModuleManager();
  1108. if (TheDependencyFileGenerator)
  1109. TheDependencyFileGenerator->AttachToASTReader(*ModuleManager);
  1110. if (ModuleDepCollector)
  1111. ModuleDepCollector->attachToASTReader(*ModuleManager);
  1112. for (auto &Listener : DependencyCollectors)
  1113. Listener->attachToASTReader(*ModuleManager);
  1114. // Try to load the module file.
  1115. unsigned ARRFlags = ASTReader::ARR_OutOfDate | ASTReader::ARR_Missing;
  1116. switch (ModuleManager->ReadAST(ModuleFileName, serialization::MK_Module,
  1117. ImportLoc, ARRFlags)) {
  1118. case ASTReader::Success:
  1119. break;
  1120. case ASTReader::OutOfDate:
  1121. case ASTReader::Missing: {
  1122. // The module file is missing or out-of-date. Build it.
  1123. assert(Module && "missing module file");
  1124. // Check whether there is a cycle in the module graph.
  1125. ModuleBuildStack ModPath = getSourceManager().getModuleBuildStack();
  1126. ModuleBuildStack::iterator Pos = ModPath.begin(), PosEnd = ModPath.end();
  1127. for (; Pos != PosEnd; ++Pos) {
  1128. if (Pos->first == ModuleName)
  1129. break;
  1130. }
  1131. if (Pos != PosEnd) {
  1132. SmallString<256> CyclePath;
  1133. for (; Pos != PosEnd; ++Pos) {
  1134. CyclePath += Pos->first;
  1135. CyclePath += " -> ";
  1136. }
  1137. CyclePath += ModuleName;
  1138. getDiagnostics().Report(ModuleNameLoc, diag::err_module_cycle)
  1139. << ModuleName << CyclePath;
  1140. return ModuleLoadResult();
  1141. }
  1142. getDiagnostics().Report(ImportLoc, diag::remark_module_build)
  1143. << ModuleName << ModuleFileName;
  1144. // Check whether we have already attempted to build this module (but
  1145. // failed).
  1146. if (getPreprocessorOpts().FailedModules &&
  1147. getPreprocessorOpts().FailedModules->hasAlreadyFailed(ModuleName)) {
  1148. getDiagnostics().Report(ModuleNameLoc, diag::err_module_not_built)
  1149. << ModuleName
  1150. << SourceRange(ImportLoc, ModuleNameLoc);
  1151. ModuleBuildFailed = true;
  1152. return ModuleLoadResult();
  1153. }
  1154. // Try to compile and then load the module.
  1155. if (!compileAndLoadModule(*this, ImportLoc, ModuleNameLoc, Module,
  1156. ModuleFileName)) {
  1157. if (getPreprocessorOpts().FailedModules)
  1158. getPreprocessorOpts().FailedModules->addFailed(ModuleName);
  1159. KnownModules[Path[0].first] = nullptr;
  1160. ModuleBuildFailed = true;
  1161. return ModuleLoadResult();
  1162. }
  1163. // Okay, we've rebuilt and now loaded the module.
  1164. break;
  1165. }
  1166. case ASTReader::VersionMismatch:
  1167. case ASTReader::ConfigurationMismatch:
  1168. case ASTReader::HadErrors:
  1169. ModuleLoader::HadFatalFailure = true;
  1170. // FIXME: The ASTReader will already have complained, but can we showhorn
  1171. // that diagnostic information into a more useful form?
  1172. KnownModules[Path[0].first] = nullptr;
  1173. return ModuleLoadResult();
  1174. case ASTReader::Failure:
  1175. ModuleLoader::HadFatalFailure = true;
  1176. // Already complained, but note now that we failed.
  1177. KnownModules[Path[0].first] = nullptr;
  1178. ModuleBuildFailed = true;
  1179. return ModuleLoadResult();
  1180. }
  1181. // Cache the result of this top-level module lookup for later.
  1182. Known = KnownModules.insert(std::make_pair(Path[0].first, Module)).first;
  1183. }
  1184. // If we never found the module, fail.
  1185. if (!Module)
  1186. return ModuleLoadResult();
  1187. // Verify that the rest of the module path actually corresponds to
  1188. // a submodule.
  1189. if (Path.size() > 1) {
  1190. for (unsigned I = 1, N = Path.size(); I != N; ++I) {
  1191. StringRef Name = Path[I].first->getName();
  1192. clang::Module *Sub = Module->findSubmodule(Name);
  1193. if (!Sub) {
  1194. // Attempt to perform typo correction to find a module name that works.
  1195. SmallVector<StringRef, 2> Best;
  1196. unsigned BestEditDistance = (std::numeric_limits<unsigned>::max)();
  1197. for (clang::Module::submodule_iterator J = Module->submodule_begin(),
  1198. JEnd = Module->submodule_end();
  1199. J != JEnd; ++J) {
  1200. unsigned ED = Name.edit_distance((*J)->Name,
  1201. /*AllowReplacements=*/true,
  1202. BestEditDistance);
  1203. if (ED <= BestEditDistance) {
  1204. if (ED < BestEditDistance) {
  1205. Best.clear();
  1206. BestEditDistance = ED;
  1207. }
  1208. Best.push_back((*J)->Name);
  1209. }
  1210. }
  1211. // If there was a clear winner, user it.
  1212. if (Best.size() == 1) {
  1213. getDiagnostics().Report(Path[I].second,
  1214. diag::err_no_submodule_suggest)
  1215. << Path[I].first << Module->getFullModuleName() << Best[0]
  1216. << SourceRange(Path[0].second, Path[I-1].second)
  1217. << FixItHint::CreateReplacement(SourceRange(Path[I].second),
  1218. Best[0]);
  1219. Sub = Module->findSubmodule(Best[0]);
  1220. }
  1221. }
  1222. if (!Sub) {
  1223. // No submodule by this name. Complain, and don't look for further
  1224. // submodules.
  1225. getDiagnostics().Report(Path[I].second, diag::err_no_submodule)
  1226. << Path[I].first << Module->getFullModuleName()
  1227. << SourceRange(Path[0].second, Path[I-1].second);
  1228. break;
  1229. }
  1230. Module = Sub;
  1231. }
  1232. }
  1233. // Make the named module visible, if it's not already part of the module
  1234. // we are parsing.
  1235. if (ModuleName != getLangOpts().CurrentModule) {
  1236. if (!Module->IsFromModuleFile) {
  1237. // We have an umbrella header or directory that doesn't actually include
  1238. // all of the headers within the directory it covers. Complain about
  1239. // this missing submodule and recover by forgetting that we ever saw
  1240. // this submodule.
  1241. // FIXME: Should we detect this at module load time? It seems fairly
  1242. // expensive (and rare).
  1243. getDiagnostics().Report(ImportLoc, diag::warn_missing_submodule)
  1244. << Module->getFullModuleName()
  1245. << SourceRange(Path.front().second, Path.back().second);
  1246. return ModuleLoadResult(nullptr, true);
  1247. }
  1248. // Check whether this module is available.
  1249. clang::Module::Requirement Requirement;
  1250. clang::Module::HeaderDirective MissingHeader;
  1251. if (!Module->isAvailable(getLangOpts(), getTarget(), Requirement,
  1252. MissingHeader)) {
  1253. if (MissingHeader.FileNameLoc.isValid()) {
  1254. getDiagnostics().Report(MissingHeader.FileNameLoc,
  1255. diag::err_module_header_missing)
  1256. << MissingHeader.IsUmbrella << MissingHeader.FileName;
  1257. } else {
  1258. getDiagnostics().Report(ImportLoc, diag::err_module_unavailable)
  1259. << Module->getFullModuleName()
  1260. << Requirement.second << Requirement.first
  1261. << SourceRange(Path.front().second, Path.back().second);
  1262. }
  1263. LastModuleImportLoc = ImportLoc;
  1264. LastModuleImportResult = ModuleLoadResult();
  1265. return ModuleLoadResult();
  1266. }
  1267. ModuleManager->makeModuleVisible(Module, Visibility, ImportLoc,
  1268. /*Complain=*/true);
  1269. }
  1270. // Check for any configuration macros that have changed.
  1271. clang::Module *TopModule = Module->getTopLevelModule();
  1272. for (unsigned I = 0, N = TopModule->ConfigMacros.size(); I != N; ++I) {
  1273. checkConfigMacro(getPreprocessor(), TopModule->ConfigMacros[I],
  1274. Module, ImportLoc);
  1275. }
  1276. // If this module import was due to an inclusion directive, create an
  1277. // implicit import declaration to capture it in the AST.
  1278. if (IsInclusionDirective && hasASTContext()) {
  1279. TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
  1280. ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
  1281. ImportLoc, Module,
  1282. Path.back().second);
  1283. TU->addDecl(ImportD);
  1284. if (Consumer)
  1285. Consumer->HandleImplicitImportDecl(ImportD);
  1286. }
  1287. LastModuleImportLoc = ImportLoc;
  1288. LastModuleImportResult = ModuleLoadResult(Module, false);
  1289. return LastModuleImportResult;
  1290. }
  1291. void CompilerInstance::makeModuleVisible(Module *Mod,
  1292. Module::NameVisibilityKind Visibility,
  1293. SourceLocation ImportLoc,
  1294. bool Complain){
  1295. ModuleManager->makeModuleVisible(Mod, Visibility, ImportLoc, Complain);
  1296. }
  1297. GlobalModuleIndex *CompilerInstance::loadGlobalModuleIndex(
  1298. SourceLocation TriggerLoc) {
  1299. if (!ModuleManager)
  1300. createModuleManager();
  1301. // Can't do anything if we don't have the module manager.
  1302. if (!ModuleManager)
  1303. return nullptr;
  1304. // Get an existing global index. This loads it if not already
  1305. // loaded.
  1306. ModuleManager->loadGlobalIndex();
  1307. GlobalModuleIndex *GlobalIndex = ModuleManager->getGlobalIndex();
  1308. // If the global index doesn't exist, create it.
  1309. if (!GlobalIndex && shouldBuildGlobalModuleIndex() && hasFileManager() &&
  1310. hasPreprocessor()) {
  1311. llvm::sys::fs::create_directories(
  1312. getPreprocessor().getHeaderSearchInfo().getModuleCachePath());
  1313. GlobalModuleIndex::writeIndex(
  1314. getFileManager(),
  1315. getPreprocessor().getHeaderSearchInfo().getModuleCachePath());
  1316. ModuleManager->resetForReload();
  1317. ModuleManager->loadGlobalIndex();
  1318. GlobalIndex = ModuleManager->getGlobalIndex();
  1319. }
  1320. // For finding modules needing to be imported for fixit messages,
  1321. // we need to make the global index cover all modules, so we do that here.
  1322. if (!HaveFullGlobalModuleIndex && GlobalIndex && !buildingModule()) {
  1323. ModuleMap &MMap = getPreprocessor().getHeaderSearchInfo().getModuleMap();
  1324. bool RecreateIndex = false;
  1325. for (ModuleMap::module_iterator I = MMap.module_begin(),
  1326. E = MMap.module_end(); I != E; ++I) {
  1327. Module *TheModule = I->second;
  1328. const FileEntry *Entry = TheModule->getASTFile();
  1329. if (!Entry) {
  1330. SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path;
  1331. Path.push_back(std::make_pair(
  1332. getPreprocessor().getIdentifierInfo(TheModule->Name), TriggerLoc));
  1333. std::reverse(Path.begin(), Path.end());
  1334. // Load a module as hidden. This also adds it to the global index.
  1335. loadModule(TheModule->DefinitionLoc, Path,
  1336. Module::Hidden, false);
  1337. RecreateIndex = true;
  1338. }
  1339. }
  1340. if (RecreateIndex) {
  1341. GlobalModuleIndex::writeIndex(
  1342. getFileManager(),
  1343. getPreprocessor().getHeaderSearchInfo().getModuleCachePath());
  1344. ModuleManager->resetForReload();
  1345. ModuleManager->loadGlobalIndex();
  1346. GlobalIndex = ModuleManager->getGlobalIndex();
  1347. }
  1348. HaveFullGlobalModuleIndex = true;
  1349. }
  1350. return GlobalIndex;
  1351. }
  1352. // Check global module index for missing imports.
  1353. bool
  1354. CompilerInstance::lookupMissingImports(StringRef Name,
  1355. SourceLocation TriggerLoc) {
  1356. // Look for the symbol in non-imported modules, but only if an error
  1357. // actually occurred.
  1358. if (!buildingModule()) {
  1359. // Load global module index, or retrieve a previously loaded one.
  1360. GlobalModuleIndex *GlobalIndex = loadGlobalModuleIndex(
  1361. TriggerLoc);
  1362. // Only if we have a global index.
  1363. if (GlobalIndex) {
  1364. GlobalModuleIndex::HitSet FoundModules;
  1365. // Find the modules that reference the identifier.
  1366. // Note that this only finds top-level modules.
  1367. // We'll let diagnoseTypo find the actual declaration module.
  1368. if (GlobalIndex->lookupIdentifier(Name, FoundModules))
  1369. return true;
  1370. }
  1371. }
  1372. return false;
  1373. }