CompilerInstance.cpp 56 KB

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