CompilerInstance.cpp 52 KB

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