CompilerInstance.cpp 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288
  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/Sema/Sema.h"
  11. #include "clang/AST/ASTConsumer.h"
  12. #include "clang/AST/ASTContext.h"
  13. #include "clang/AST/Decl.h"
  14. #include "clang/Basic/Diagnostic.h"
  15. #include "clang/Basic/FileManager.h"
  16. #include "clang/Basic/SourceManager.h"
  17. #include "clang/Basic/TargetInfo.h"
  18. #include "clang/Basic/Version.h"
  19. #include "clang/Lex/HeaderSearch.h"
  20. #include "clang/Lex/Preprocessor.h"
  21. #include "clang/Lex/PTHManager.h"
  22. #include "clang/Frontend/ChainedDiagnosticConsumer.h"
  23. #include "clang/Frontend/FrontendAction.h"
  24. #include "clang/Frontend/FrontendActions.h"
  25. #include "clang/Frontend/FrontendDiagnostic.h"
  26. #include "clang/Frontend/LogDiagnosticPrinter.h"
  27. #include "clang/Frontend/SerializedDiagnosticPrinter.h"
  28. #include "clang/Frontend/TextDiagnosticPrinter.h"
  29. #include "clang/Frontend/VerifyDiagnosticConsumer.h"
  30. #include "clang/Frontend/Utils.h"
  31. #include "clang/Serialization/ASTReader.h"
  32. #include "clang/Sema/CodeCompleteConsumer.h"
  33. #include "llvm/Support/FileSystem.h"
  34. #include "llvm/Support/MemoryBuffer.h"
  35. #include "llvm/Support/raw_ostream.h"
  36. #include "llvm/ADT/Statistic.h"
  37. #include "llvm/Support/Timer.h"
  38. #include "llvm/Support/Host.h"
  39. #include "llvm/Support/Path.h"
  40. #include "llvm/Support/Program.h"
  41. #include "llvm/Support/Signals.h"
  42. #include "llvm/Support/system_error.h"
  43. #include "llvm/Support/CrashRecoveryContext.h"
  44. #include "llvm/Config/config.h"
  45. // Support for FileLockManager
  46. #include <fstream>
  47. #include <sys/types.h>
  48. #include <sys/stat.h>
  49. #if LLVM_ON_WIN32
  50. #include <windows.h>
  51. #endif
  52. #if LLVM_ON_UNIX
  53. #include <unistd.h>
  54. #endif
  55. using namespace clang;
  56. CompilerInstance::CompilerInstance()
  57. : Invocation(new CompilerInvocation()), ModuleManager(0) {
  58. }
  59. CompilerInstance::~CompilerInstance() {
  60. }
  61. void CompilerInstance::setInvocation(CompilerInvocation *Value) {
  62. Invocation = Value;
  63. }
  64. void CompilerInstance::setDiagnostics(DiagnosticsEngine *Value) {
  65. Diagnostics = Value;
  66. }
  67. void CompilerInstance::setTarget(TargetInfo *Value) {
  68. Target = Value;
  69. }
  70. void CompilerInstance::setFileManager(FileManager *Value) {
  71. FileMgr = Value;
  72. }
  73. void CompilerInstance::setSourceManager(SourceManager *Value) {
  74. SourceMgr = Value;
  75. }
  76. void CompilerInstance::setPreprocessor(Preprocessor *Value) { PP = Value; }
  77. void CompilerInstance::setASTContext(ASTContext *Value) { Context = Value; }
  78. void CompilerInstance::setSema(Sema *S) {
  79. TheSema.reset(S);
  80. }
  81. void CompilerInstance::setASTConsumer(ASTConsumer *Value) {
  82. Consumer.reset(Value);
  83. }
  84. void CompilerInstance::setCodeCompletionConsumer(CodeCompleteConsumer *Value) {
  85. CompletionConsumer.reset(Value);
  86. }
  87. // Diagnostics
  88. static void SetUpBuildDumpLog(const DiagnosticOptions &DiagOpts,
  89. unsigned argc, const char* const *argv,
  90. DiagnosticsEngine &Diags) {
  91. std::string ErrorInfo;
  92. llvm::OwningPtr<raw_ostream> OS(
  93. new llvm::raw_fd_ostream(DiagOpts.DumpBuildInformation.c_str(), ErrorInfo));
  94. if (!ErrorInfo.empty()) {
  95. Diags.Report(diag::err_fe_unable_to_open_logfile)
  96. << DiagOpts.DumpBuildInformation << ErrorInfo;
  97. return;
  98. }
  99. (*OS) << "clang -cc1 command line arguments: ";
  100. for (unsigned i = 0; i != argc; ++i)
  101. (*OS) << argv[i] << ' ';
  102. (*OS) << '\n';
  103. // Chain in a diagnostic client which will log the diagnostics.
  104. DiagnosticConsumer *Logger =
  105. new TextDiagnosticPrinter(*OS.take(), DiagOpts, /*OwnsOutputStream=*/true);
  106. Diags.setClient(new ChainedDiagnosticConsumer(Diags.takeClient(), Logger));
  107. }
  108. static void SetUpDiagnosticLog(const DiagnosticOptions &DiagOpts,
  109. const CodeGenOptions *CodeGenOpts,
  110. DiagnosticsEngine &Diags) {
  111. std::string ErrorInfo;
  112. bool OwnsStream = false;
  113. raw_ostream *OS = &llvm::errs();
  114. if (DiagOpts.DiagnosticLogFile != "-") {
  115. // Create the output stream.
  116. llvm::raw_fd_ostream *FileOS(
  117. new llvm::raw_fd_ostream(DiagOpts.DiagnosticLogFile.c_str(),
  118. ErrorInfo, llvm::raw_fd_ostream::F_Append));
  119. if (!ErrorInfo.empty()) {
  120. Diags.Report(diag::warn_fe_cc_log_diagnostics_failure)
  121. << DiagOpts.DumpBuildInformation << ErrorInfo;
  122. } else {
  123. FileOS->SetUnbuffered();
  124. FileOS->SetUseAtomicWrites(true);
  125. OS = FileOS;
  126. OwnsStream = true;
  127. }
  128. }
  129. // Chain in the diagnostic client which will log the diagnostics.
  130. LogDiagnosticPrinter *Logger = new LogDiagnosticPrinter(*OS, DiagOpts,
  131. OwnsStream);
  132. if (CodeGenOpts)
  133. Logger->setDwarfDebugFlags(CodeGenOpts->DwarfDebugFlags);
  134. Diags.setClient(new ChainedDiagnosticConsumer(Diags.takeClient(), Logger));
  135. }
  136. static void SetupSerializedDiagnostics(const DiagnosticOptions &DiagOpts,
  137. DiagnosticsEngine &Diags,
  138. StringRef OutputFile) {
  139. std::string ErrorInfo;
  140. llvm::OwningPtr<llvm::raw_fd_ostream> OS;
  141. OS.reset(new llvm::raw_fd_ostream(OutputFile.str().c_str(), ErrorInfo,
  142. llvm::raw_fd_ostream::F_Binary));
  143. if (!ErrorInfo.empty()) {
  144. Diags.Report(diag::warn_fe_serialized_diag_failure)
  145. << OutputFile << ErrorInfo;
  146. return;
  147. }
  148. DiagnosticConsumer *SerializedConsumer =
  149. clang::serialized_diags::create(OS.take(), DiagOpts);
  150. Diags.setClient(new ChainedDiagnosticConsumer(Diags.takeClient(),
  151. SerializedConsumer));
  152. }
  153. void CompilerInstance::createDiagnostics(int Argc, const char* const *Argv,
  154. DiagnosticConsumer *Client,
  155. bool ShouldOwnClient,
  156. bool ShouldCloneClient) {
  157. Diagnostics = createDiagnostics(getDiagnosticOpts(), Argc, Argv, Client,
  158. ShouldOwnClient, ShouldCloneClient,
  159. &getCodeGenOpts());
  160. }
  161. llvm::IntrusiveRefCntPtr<DiagnosticsEngine>
  162. CompilerInstance::createDiagnostics(const DiagnosticOptions &Opts,
  163. int Argc, const char* const *Argv,
  164. DiagnosticConsumer *Client,
  165. bool ShouldOwnClient,
  166. bool ShouldCloneClient,
  167. const CodeGenOptions *CodeGenOpts) {
  168. llvm::IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
  169. llvm::IntrusiveRefCntPtr<DiagnosticsEngine>
  170. Diags(new DiagnosticsEngine(DiagID));
  171. // Create the diagnostic client for reporting errors or for
  172. // implementing -verify.
  173. if (Client) {
  174. if (ShouldCloneClient)
  175. Diags->setClient(Client->clone(*Diags), ShouldOwnClient);
  176. else
  177. Diags->setClient(Client, ShouldOwnClient);
  178. } else
  179. Diags->setClient(new TextDiagnosticPrinter(llvm::errs(), Opts));
  180. // Chain in -verify checker, if requested.
  181. if (Opts.VerifyDiagnostics)
  182. Diags->setClient(new VerifyDiagnosticConsumer(*Diags));
  183. // Chain in -diagnostic-log-file dumper, if requested.
  184. if (!Opts.DiagnosticLogFile.empty())
  185. SetUpDiagnosticLog(Opts, CodeGenOpts, *Diags);
  186. if (!Opts.DumpBuildInformation.empty())
  187. SetUpBuildDumpLog(Opts, Argc, Argv, *Diags);
  188. if (!Opts.DiagnosticSerializationFile.empty())
  189. SetupSerializedDiagnostics(Opts, *Diags,
  190. Opts.DiagnosticSerializationFile);
  191. // Configure our handling of diagnostics.
  192. ProcessWarningOptions(*Diags, Opts);
  193. return Diags;
  194. }
  195. // File Manager
  196. void CompilerInstance::createFileManager() {
  197. FileMgr = new FileManager(getFileSystemOpts());
  198. }
  199. // Source Manager
  200. void CompilerInstance::createSourceManager(FileManager &FileMgr) {
  201. SourceMgr = new SourceManager(getDiagnostics(), FileMgr);
  202. }
  203. // Preprocessor
  204. void CompilerInstance::createPreprocessor() {
  205. const PreprocessorOptions &PPOpts = getPreprocessorOpts();
  206. // Create a PTH manager if we are using some form of a token cache.
  207. PTHManager *PTHMgr = 0;
  208. if (!PPOpts.TokenCache.empty())
  209. PTHMgr = PTHManager::Create(PPOpts.TokenCache, getDiagnostics());
  210. // Create the Preprocessor.
  211. HeaderSearch *HeaderInfo = new HeaderSearch(getFileManager(),
  212. getDiagnostics());
  213. PP = new Preprocessor(getDiagnostics(), getLangOpts(), &getTarget(),
  214. getSourceManager(), *HeaderInfo, *this, PTHMgr,
  215. /*OwnsHeaderSearch=*/true);
  216. // Note that this is different then passing PTHMgr to Preprocessor's ctor.
  217. // That argument is used as the IdentifierInfoLookup argument to
  218. // IdentifierTable's ctor.
  219. if (PTHMgr) {
  220. PTHMgr->setPreprocessor(&*PP);
  221. PP->setPTHManager(PTHMgr);
  222. }
  223. if (PPOpts.DetailedRecord)
  224. PP->createPreprocessingRecord(
  225. PPOpts.DetailedRecordIncludesNestedMacroExpansions);
  226. InitializePreprocessor(*PP, PPOpts, getHeaderSearchOpts(), getFrontendOpts());
  227. // Set up the module path, including the hash for the
  228. // module-creation options.
  229. llvm::SmallString<256> SpecificModuleCache(
  230. getHeaderSearchOpts().ModuleCachePath);
  231. if (!getHeaderSearchOpts().DisableModuleHash)
  232. llvm::sys::path::append(SpecificModuleCache,
  233. getInvocation().getModuleHash());
  234. PP->getHeaderSearchInfo().setModuleCachePath(SpecificModuleCache);
  235. // Handle generating dependencies, if requested.
  236. const DependencyOutputOptions &DepOpts = getDependencyOutputOpts();
  237. if (!DepOpts.OutputFile.empty())
  238. AttachDependencyFileGen(*PP, DepOpts);
  239. // Handle generating header include information, if requested.
  240. if (DepOpts.ShowHeaderIncludes)
  241. AttachHeaderIncludeGen(*PP);
  242. if (!DepOpts.HeaderIncludeOutputFile.empty()) {
  243. StringRef OutputPath = DepOpts.HeaderIncludeOutputFile;
  244. if (OutputPath == "-")
  245. OutputPath = "";
  246. AttachHeaderIncludeGen(*PP, /*ShowAllHeaders=*/true, OutputPath,
  247. /*ShowDepth=*/false);
  248. }
  249. }
  250. // ASTContext
  251. void CompilerInstance::createASTContext() {
  252. Preprocessor &PP = getPreprocessor();
  253. Context = new ASTContext(getLangOpts(), PP.getSourceManager(),
  254. &getTarget(), PP.getIdentifierTable(),
  255. PP.getSelectorTable(), PP.getBuiltinInfo(),
  256. /*size_reserve=*/ 0);
  257. }
  258. // ExternalASTSource
  259. void CompilerInstance::createPCHExternalASTSource(StringRef Path,
  260. bool DisablePCHValidation,
  261. bool DisableStatCache,
  262. void *DeserializationListener){
  263. llvm::OwningPtr<ExternalASTSource> Source;
  264. bool Preamble = getPreprocessorOpts().PrecompiledPreambleBytes.first != 0;
  265. Source.reset(createPCHExternalASTSource(Path, getHeaderSearchOpts().Sysroot,
  266. DisablePCHValidation,
  267. DisableStatCache,
  268. getPreprocessor(), getASTContext(),
  269. DeserializationListener,
  270. Preamble));
  271. ModuleManager = static_cast<ASTReader*>(Source.get());
  272. getASTContext().setExternalSource(Source);
  273. }
  274. ExternalASTSource *
  275. CompilerInstance::createPCHExternalASTSource(StringRef Path,
  276. const std::string &Sysroot,
  277. bool DisablePCHValidation,
  278. bool DisableStatCache,
  279. Preprocessor &PP,
  280. ASTContext &Context,
  281. void *DeserializationListener,
  282. bool Preamble) {
  283. llvm::OwningPtr<ASTReader> Reader;
  284. Reader.reset(new ASTReader(PP, Context,
  285. Sysroot.empty() ? "" : Sysroot.c_str(),
  286. DisablePCHValidation, DisableStatCache));
  287. Reader->setDeserializationListener(
  288. static_cast<ASTDeserializationListener *>(DeserializationListener));
  289. switch (Reader->ReadAST(Path,
  290. Preamble ? serialization::MK_Preamble
  291. : serialization::MK_PCH)) {
  292. case ASTReader::Success:
  293. // Set the predefines buffer as suggested by the PCH reader. Typically, the
  294. // predefines buffer will be empty.
  295. PP.setPredefines(Reader->getSuggestedPredefines());
  296. return Reader.take();
  297. case ASTReader::Failure:
  298. // Unrecoverable failure: don't even try to process the input file.
  299. break;
  300. case ASTReader::IgnorePCH:
  301. // No suitable PCH file could be found. Return an error.
  302. break;
  303. }
  304. return 0;
  305. }
  306. // Code Completion
  307. static bool EnableCodeCompletion(Preprocessor &PP,
  308. const std::string &Filename,
  309. unsigned Line,
  310. unsigned Column) {
  311. // Tell the source manager to chop off the given file at a specific
  312. // line and column.
  313. const FileEntry *Entry = PP.getFileManager().getFile(Filename);
  314. if (!Entry) {
  315. PP.getDiagnostics().Report(diag::err_fe_invalid_code_complete_file)
  316. << Filename;
  317. return true;
  318. }
  319. // Truncate the named file at the given line/column.
  320. PP.SetCodeCompletionPoint(Entry, Line, Column);
  321. return false;
  322. }
  323. void CompilerInstance::createCodeCompletionConsumer() {
  324. const ParsedSourceLocation &Loc = getFrontendOpts().CodeCompletionAt;
  325. if (!CompletionConsumer) {
  326. CompletionConsumer.reset(
  327. createCodeCompletionConsumer(getPreprocessor(),
  328. Loc.FileName, Loc.Line, Loc.Column,
  329. getFrontendOpts().ShowMacrosInCodeCompletion,
  330. getFrontendOpts().ShowCodePatternsInCodeCompletion,
  331. getFrontendOpts().ShowGlobalSymbolsInCodeCompletion,
  332. llvm::outs()));
  333. if (!CompletionConsumer)
  334. return;
  335. } else if (EnableCodeCompletion(getPreprocessor(), Loc.FileName,
  336. Loc.Line, Loc.Column)) {
  337. CompletionConsumer.reset();
  338. return;
  339. }
  340. if (CompletionConsumer->isOutputBinary() &&
  341. llvm::sys::Program::ChangeStdoutToBinary()) {
  342. getPreprocessor().getDiagnostics().Report(diag::err_fe_stdout_binary);
  343. CompletionConsumer.reset();
  344. }
  345. }
  346. void CompilerInstance::createFrontendTimer() {
  347. FrontendTimer.reset(new llvm::Timer("Clang front-end timer"));
  348. }
  349. CodeCompleteConsumer *
  350. CompilerInstance::createCodeCompletionConsumer(Preprocessor &PP,
  351. const std::string &Filename,
  352. unsigned Line,
  353. unsigned Column,
  354. bool ShowMacros,
  355. bool ShowCodePatterns,
  356. bool ShowGlobals,
  357. raw_ostream &OS) {
  358. if (EnableCodeCompletion(PP, Filename, Line, Column))
  359. return 0;
  360. // Set up the creation routine for code-completion.
  361. return new PrintingCodeCompleteConsumer(ShowMacros, ShowCodePatterns,
  362. ShowGlobals, OS);
  363. }
  364. void CompilerInstance::createSema(TranslationUnitKind TUKind,
  365. CodeCompleteConsumer *CompletionConsumer) {
  366. TheSema.reset(new Sema(getPreprocessor(), getASTContext(), getASTConsumer(),
  367. TUKind, CompletionConsumer));
  368. }
  369. // Output Files
  370. void CompilerInstance::addOutputFile(const OutputFile &OutFile) {
  371. assert(OutFile.OS && "Attempt to add empty stream to output list!");
  372. OutputFiles.push_back(OutFile);
  373. }
  374. void CompilerInstance::clearOutputFiles(bool EraseFiles) {
  375. for (std::list<OutputFile>::iterator
  376. it = OutputFiles.begin(), ie = OutputFiles.end(); it != ie; ++it) {
  377. delete it->OS;
  378. if (!it->TempFilename.empty()) {
  379. if (EraseFiles) {
  380. bool existed;
  381. llvm::sys::fs::remove(it->TempFilename, existed);
  382. } else {
  383. llvm::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_fe_unable_to_rename_temp)
  390. << it->TempFilename << it->Filename << ec.message();
  391. bool existed;
  392. llvm::sys::fs::remove(it->TempFilename, existed);
  393. }
  394. }
  395. } else if (!it->Filename.empty() && EraseFiles)
  396. llvm::sys::Path(it->Filename).eraseFromDisk();
  397. }
  398. OutputFiles.clear();
  399. }
  400. llvm::raw_fd_ostream *
  401. CompilerInstance::createDefaultOutputFile(bool Binary,
  402. StringRef InFile,
  403. StringRef Extension) {
  404. return createOutputFile(getFrontendOpts().OutputFile, Binary,
  405. /*RemoveFileOnSignal=*/true, InFile, Extension);
  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. std::string Error, OutputPathName, TempPathName;
  414. llvm::raw_fd_ostream *OS = createOutputFile(OutputPath, Error, Binary,
  415. RemoveFileOnSignal,
  416. InFile, Extension,
  417. UseTemporary,
  418. &OutputPathName,
  419. &TempPathName);
  420. if (!OS) {
  421. getDiagnostics().Report(diag::err_fe_unable_to_open_output)
  422. << OutputPath << Error;
  423. return 0;
  424. }
  425. // Add the output file -- but don't try to remove "-", since this means we are
  426. // using stdin.
  427. addOutputFile(OutputFile((OutputPathName != "-") ? OutputPathName : "",
  428. TempPathName, OS));
  429. return OS;
  430. }
  431. llvm::raw_fd_ostream *
  432. CompilerInstance::createOutputFile(StringRef OutputPath,
  433. std::string &Error,
  434. bool Binary,
  435. bool RemoveFileOnSignal,
  436. StringRef InFile,
  437. StringRef Extension,
  438. bool UseTemporary,
  439. std::string *ResultPathName,
  440. std::string *TempPathName) {
  441. std::string OutFile, TempFile;
  442. if (!OutputPath.empty()) {
  443. OutFile = OutputPath;
  444. } else if (InFile == "-") {
  445. OutFile = "-";
  446. } else if (!Extension.empty()) {
  447. llvm::sys::Path Path(InFile);
  448. Path.eraseSuffix();
  449. Path.appendSuffix(Extension);
  450. OutFile = Path.str();
  451. } else {
  452. OutFile = "-";
  453. }
  454. llvm::OwningPtr<llvm::raw_fd_ostream> OS;
  455. std::string OSFile;
  456. if (UseTemporary && OutFile != "-") {
  457. llvm::sys::Path OutPath(OutFile);
  458. // Only create the temporary if we can actually write to OutPath, otherwise
  459. // we want to fail early.
  460. bool Exists;
  461. if ((llvm::sys::fs::exists(OutPath.str(), Exists) || !Exists) ||
  462. (OutPath.isRegularFile() && OutPath.canWrite())) {
  463. // Create a temporary file.
  464. llvm::SmallString<128> TempPath;
  465. TempPath = OutFile;
  466. TempPath += "-%%%%%%%%";
  467. int fd;
  468. if (llvm::sys::fs::unique_file(TempPath.str(), fd, TempPath,
  469. /*makeAbsolute=*/false) == llvm::errc::success) {
  470. OS.reset(new llvm::raw_fd_ostream(fd, /*shouldClose=*/true));
  471. OSFile = TempFile = TempPath.str();
  472. }
  473. }
  474. }
  475. if (!OS) {
  476. OSFile = OutFile;
  477. OS.reset(
  478. new llvm::raw_fd_ostream(OSFile.c_str(), Error,
  479. (Binary ? llvm::raw_fd_ostream::F_Binary : 0)));
  480. if (!Error.empty())
  481. return 0;
  482. }
  483. // Make sure the out stream file gets removed if we crash.
  484. if (RemoveFileOnSignal)
  485. llvm::sys::RemoveFileOnSignal(llvm::sys::Path(OSFile));
  486. if (ResultPathName)
  487. *ResultPathName = OutFile;
  488. if (TempPathName)
  489. *TempPathName = TempFile;
  490. return OS.take();
  491. }
  492. // Initialization Utilities
  493. bool CompilerInstance::InitializeSourceManager(StringRef InputFile) {
  494. return InitializeSourceManager(InputFile, getDiagnostics(), getFileManager(),
  495. getSourceManager(), getFrontendOpts());
  496. }
  497. bool CompilerInstance::InitializeSourceManager(StringRef InputFile,
  498. DiagnosticsEngine &Diags,
  499. FileManager &FileMgr,
  500. SourceManager &SourceMgr,
  501. const FrontendOptions &Opts) {
  502. // Figure out where to get and map in the main file.
  503. if (InputFile != "-") {
  504. const FileEntry *File = FileMgr.getFile(InputFile);
  505. if (!File) {
  506. Diags.Report(diag::err_fe_error_reading) << InputFile;
  507. return false;
  508. }
  509. SourceMgr.createMainFileID(File);
  510. } else {
  511. llvm::OwningPtr<llvm::MemoryBuffer> SB;
  512. if (llvm::MemoryBuffer::getSTDIN(SB)) {
  513. // FIXME: Give ec.message() in this diag.
  514. Diags.Report(diag::err_fe_error_reading_stdin);
  515. return false;
  516. }
  517. const FileEntry *File = FileMgr.getVirtualFile(SB->getBufferIdentifier(),
  518. SB->getBufferSize(), 0);
  519. SourceMgr.createMainFileID(File);
  520. SourceMgr.overrideFileContents(File, SB.take());
  521. }
  522. assert(!SourceMgr.getMainFileID().isInvalid() &&
  523. "Couldn't establish MainFileID!");
  524. return true;
  525. }
  526. // High-Level Operations
  527. bool CompilerInstance::ExecuteAction(FrontendAction &Act) {
  528. assert(hasDiagnostics() && "Diagnostics engine is not initialized!");
  529. assert(!getFrontendOpts().ShowHelp && "Client must handle '-help'!");
  530. assert(!getFrontendOpts().ShowVersion && "Client must handle '-version'!");
  531. // FIXME: Take this as an argument, once all the APIs we used have moved to
  532. // taking it as an input instead of hard-coding llvm::errs.
  533. raw_ostream &OS = llvm::errs();
  534. // Create the target instance.
  535. setTarget(TargetInfo::CreateTargetInfo(getDiagnostics(), getTargetOpts()));
  536. if (!hasTarget())
  537. return false;
  538. // Inform the target of the language options.
  539. //
  540. // FIXME: We shouldn't need to do this, the target should be immutable once
  541. // created. This complexity should be lifted elsewhere.
  542. getTarget().setForcedLangOptions(getLangOpts());
  543. // Validate/process some options.
  544. if (getHeaderSearchOpts().Verbose)
  545. OS << "clang -cc1 version " CLANG_VERSION_STRING
  546. << " based upon " << PACKAGE_STRING
  547. << " default target " << llvm::sys::getDefaultTargetTriple() << "\n";
  548. if (getFrontendOpts().ShowTimers)
  549. createFrontendTimer();
  550. if (getFrontendOpts().ShowStats)
  551. llvm::EnableStatistics();
  552. for (unsigned i = 0, e = getFrontendOpts().Inputs.size(); i != e; ++i) {
  553. const std::string &InFile = getFrontendOpts().Inputs[i].second;
  554. // Reset the ID tables if we are reusing the SourceManager.
  555. if (hasSourceManager())
  556. getSourceManager().clearIDTables();
  557. if (Act.BeginSourceFile(*this, InFile, getFrontendOpts().Inputs[i].first)) {
  558. Act.Execute();
  559. Act.EndSourceFile();
  560. }
  561. }
  562. // Notify the diagnostic client that all files were processed.
  563. getDiagnostics().getClient()->finish();
  564. if (getDiagnosticOpts().ShowCarets) {
  565. // We can have multiple diagnostics sharing one diagnostic client.
  566. // Get the total number of warnings/errors from the client.
  567. unsigned NumWarnings = getDiagnostics().getClient()->getNumWarnings();
  568. unsigned NumErrors = getDiagnostics().getClient()->getNumErrors();
  569. if (NumWarnings)
  570. OS << NumWarnings << " warning" << (NumWarnings == 1 ? "" : "s");
  571. if (NumWarnings && NumErrors)
  572. OS << " and ";
  573. if (NumErrors)
  574. OS << NumErrors << " error" << (NumErrors == 1 ? "" : "s");
  575. if (NumWarnings || NumErrors)
  576. OS << " generated.\n";
  577. }
  578. if (getFrontendOpts().ShowStats && hasFileManager()) {
  579. getFileManager().PrintStats();
  580. OS << "\n";
  581. }
  582. return !getDiagnostics().getClient()->getNumErrors();
  583. }
  584. /// \brief Determine the appropriate source input kind based on language
  585. /// options.
  586. static InputKind getSourceInputKindFromOptions(const LangOptions &LangOpts) {
  587. if (LangOpts.OpenCL)
  588. return IK_OpenCL;
  589. if (LangOpts.CUDA)
  590. return IK_CUDA;
  591. if (LangOpts.ObjC1)
  592. return LangOpts.CPlusPlus? IK_ObjCXX : IK_ObjC;
  593. return LangOpts.CPlusPlus? IK_CXX : IK_C;
  594. }
  595. namespace {
  596. struct CompileModuleMapData {
  597. CompilerInstance &Instance;
  598. GenerateModuleAction &CreateModuleAction;
  599. };
  600. }
  601. /// \brief Helper function that executes the module-generating action under
  602. /// a crash recovery context.
  603. static void doCompileMapModule(void *UserData) {
  604. CompileModuleMapData &Data
  605. = *reinterpret_cast<CompileModuleMapData *>(UserData);
  606. Data.Instance.ExecuteAction(Data.CreateModuleAction);
  607. }
  608. namespace {
  609. /// \brief Class that manages the creation of a lock file to aid
  610. /// implicit coordination between different processes.
  611. ///
  612. /// The implicit coordination works by creating a ".lock" file alongside
  613. /// the file that we're coordinating for, using the atomicity of the file
  614. /// system to ensure that only a single process can create that ".lock" file.
  615. /// When the lock file is removed, the owning process has finished the
  616. /// operation.
  617. class LockFileManager {
  618. public:
  619. /// \brief Describes the state of a lock file.
  620. enum LockFileState {
  621. /// \brief The lock file has been created and is owned by this instance
  622. /// of the object.
  623. LFS_Owned,
  624. /// \brief The lock file already exists and is owned by some other
  625. /// instance.
  626. LFS_Shared,
  627. /// \brief An error occurred while trying to create or find the lock
  628. /// file.
  629. LFS_Error
  630. };
  631. private:
  632. llvm::SmallString<128> LockFileName;
  633. llvm::SmallString<128> UniqueLockFileName;
  634. llvm::Optional<std::pair<std::string, int> > Owner;
  635. llvm::Optional<llvm::error_code> Error;
  636. LockFileManager(const LockFileManager &);
  637. LockFileManager &operator=(const LockFileManager &);
  638. static llvm::Optional<std::pair<std::string, int> >
  639. readLockFile(StringRef LockFileName);
  640. static bool processStillExecuting(StringRef Hostname, int PID);
  641. public:
  642. LockFileManager(StringRef FileName);
  643. ~LockFileManager();
  644. /// \brief Determine the state of the lock file.
  645. LockFileState getState() const;
  646. operator LockFileState() const { return getState(); }
  647. /// \brief For a shared lock, wait until the owner releases the lock.
  648. void waitForUnlock();
  649. };
  650. }
  651. /// \brief Attempt to read the lock file with the given name, if it exists.
  652. ///
  653. /// \param LockFileName The name of the lock file to read.
  654. ///
  655. /// \returns The process ID of the process that owns this lock file
  656. llvm::Optional<std::pair<std::string, int> >
  657. LockFileManager::readLockFile(StringRef LockFileName) {
  658. // Check whether the lock file exists. If not, clearly there's nothing
  659. // to read, so we just return.
  660. bool Exists = false;
  661. if (llvm::sys::fs::exists(LockFileName, Exists) || !Exists)
  662. return llvm::Optional<std::pair<std::string, int> >();
  663. // Read the owning host and PID out of the lock file. If it appears that the
  664. // owning process is dead, the lock file is invalid.
  665. int PID = 0;
  666. std::string Hostname;
  667. std::ifstream Input(LockFileName.str().c_str());
  668. if (Input >> Hostname >> PID && PID > 0 &&
  669. processStillExecuting(Hostname, PID))
  670. return std::make_pair(Hostname, PID);
  671. // Delete the lock file. It's invalid anyway.
  672. bool Existed;
  673. llvm::sys::fs::remove(LockFileName, Existed);
  674. return llvm::Optional<std::pair<std::string, int> >();
  675. }
  676. bool LockFileManager::processStillExecuting(StringRef Hostname, int PID) {
  677. #if LLVM_ON_UNIX
  678. char MyHostname[256];
  679. MyHostname[255] = 0;
  680. MyHostname[0] = 0;
  681. gethostname(MyHostname, 255);
  682. // Check whether the process is dead. If so, we're done.
  683. if (MyHostname == Hostname && getsid(PID) == -1 && errno == ESRCH)
  684. return false;
  685. #endif
  686. return true;
  687. }
  688. LockFileManager::LockFileManager(StringRef FileName)
  689. {
  690. LockFileName = FileName;
  691. LockFileName += ".lock";
  692. // If the lock file already exists, don't bother to try to create our own
  693. // lock file; it won't work anyway. Just figure out who owns this lock file.
  694. if ((Owner = readLockFile(LockFileName)))
  695. return;
  696. // Create a lock file that is unique to this instance.
  697. UniqueLockFileName = LockFileName;
  698. UniqueLockFileName += "-%%%%%%%%";
  699. int UniqueLockFileID;
  700. if (llvm::error_code EC
  701. = llvm::sys::fs::unique_file(UniqueLockFileName.str(),
  702. UniqueLockFileID,
  703. UniqueLockFileName,
  704. /*makeAbsolute=*/false)) {
  705. Error = EC;
  706. return;
  707. }
  708. // Write our process ID to our unique lock file.
  709. {
  710. llvm::raw_fd_ostream Out(UniqueLockFileID, /*shouldClose=*/true);
  711. #if LLVM_ON_UNIX
  712. // FIXME: move getpid() call into LLVM
  713. char hostname[256];
  714. hostname[255] = 0;
  715. hostname[0] = 0;
  716. gethostname(hostname, 255);
  717. Out << hostname << ' ' << getpid();
  718. #else
  719. Out << "localhost 1";
  720. #endif
  721. Out.close();
  722. if (Out.has_error()) {
  723. // We failed to write out PID, so make up an excuse, remove the
  724. // unique lock file, and fail.
  725. Error = llvm::make_error_code(llvm::errc::no_space_on_device);
  726. bool Existed;
  727. llvm::sys::fs::remove(UniqueLockFileName.c_str(), Existed);
  728. return;
  729. }
  730. }
  731. // Create a hard link from the lock file name. If this succeeds, we're done.
  732. llvm::error_code EC
  733. = llvm::sys::fs::create_hard_link(UniqueLockFileName.str(),
  734. LockFileName.str());
  735. if (EC == llvm::errc::success)
  736. return;
  737. // Creating the hard link failed.
  738. #ifdef LLVM_ON_UNIX
  739. // The creation of the hard link may appear to fail, but if stat'ing the
  740. // unique file returns a link count of 2, then we can still declare success.
  741. struct stat StatBuf;
  742. if (stat(UniqueLockFileName.c_str(), &StatBuf) == 0 &&
  743. StatBuf.st_nlink == 2)
  744. return;
  745. #endif
  746. // Someone else managed to create the lock file first. Wipe out our unique
  747. // lock file (it's useless now) and read the process ID from the lock file.
  748. bool Existed;
  749. llvm::sys::fs::remove(UniqueLockFileName.str(), Existed);
  750. if ((Owner = readLockFile(LockFileName)))
  751. return;
  752. // There is a lock file that nobody owns; try to clean it up and report
  753. // an error.
  754. llvm::sys::fs::remove(LockFileName.str(), Existed);
  755. Error = EC;
  756. }
  757. LockFileManager::LockFileState LockFileManager::getState() const {
  758. if (Owner)
  759. return LFS_Shared;
  760. if (Error)
  761. return LFS_Error;
  762. return LFS_Owned;
  763. }
  764. LockFileManager::~LockFileManager() {
  765. if (getState() != LFS_Owned)
  766. return;
  767. // Since we own the lock, remove the lock file and our own unique lock file.
  768. bool Existed;
  769. llvm::sys::fs::remove(LockFileName.str(), Existed);
  770. llvm::sys::fs::remove(UniqueLockFileName.str(), Existed);
  771. }
  772. void LockFileManager::waitForUnlock() {
  773. if (getState() != LFS_Shared)
  774. return;
  775. #if LLVM_ON_WIN32
  776. unsigned long Interval = 1;
  777. #else
  778. struct timespec Interval;
  779. Interval.tv_sec = 0;
  780. Interval.tv_nsec = 1000000;
  781. #endif
  782. // Don't wait more than an hour for the file to appear.
  783. const unsigned MaxSeconds = 3600;
  784. do {
  785. // Sleep for the designated interval, to allow the owning process time to
  786. // finish up and
  787. // FIXME: Should we hook in to system APIs to get a notification when the
  788. // lock file is deleted?
  789. #if LLVM_ON_WIN32
  790. Sleep(Interval);
  791. #else
  792. nanosleep(&Interval, NULL);
  793. #endif
  794. // If the file no longer exists, we're done.
  795. bool Exists = false;
  796. if (!llvm::sys::fs::exists(LockFileName.str(), Exists) && !Exists)
  797. return;
  798. if (!processStillExecuting((*Owner).first, (*Owner).second))
  799. return;
  800. // Exponentially increase the time we wait for the lock to be removed.
  801. #if LLVM_ON_WIN32
  802. Interval *= 2;
  803. #else
  804. Interval.tv_sec *= 2;
  805. Interval.tv_nsec *= 2;
  806. if (Interval.tv_nsec >= 1000000000) {
  807. ++Interval.tv_sec;
  808. Interval.tv_nsec -= 1000000000;
  809. }
  810. #endif
  811. } while (
  812. #if LLVM_ON_WIN32
  813. Interval < MaxSeconds * 1000
  814. #else
  815. Interval.tv_sec < (time_t)MaxSeconds
  816. #endif
  817. );
  818. // Give up.
  819. }
  820. /// \brief Compile a module file for the given module, using the options
  821. /// provided by the importing compiler instance.
  822. static void compileModule(CompilerInstance &ImportingInstance,
  823. Module *Module,
  824. StringRef ModuleFileName) {
  825. LockFileManager Locked(ModuleFileName);
  826. switch (Locked) {
  827. case LockFileManager::LFS_Error:
  828. return;
  829. case LockFileManager::LFS_Owned:
  830. // We're responsible for building the module ourselves. Do so below.
  831. break;
  832. case LockFileManager::LFS_Shared:
  833. // Someone else is responsible for building the module. Wait for them to
  834. // finish.
  835. Locked.waitForUnlock();
  836. break;
  837. }
  838. ModuleMap &ModMap
  839. = ImportingInstance.getPreprocessor().getHeaderSearchInfo().getModuleMap();
  840. // Construct a compiler invocation for creating this module.
  841. llvm::IntrusiveRefCntPtr<CompilerInvocation> Invocation
  842. (new CompilerInvocation(ImportingInstance.getInvocation()));
  843. PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
  844. // For any options that aren't intended to affect how a module is built,
  845. // reset them to their default values.
  846. Invocation->getLangOpts()->resetNonModularOptions();
  847. PPOpts.resetNonModularOptions();
  848. // Note the name of the module we're building.
  849. Invocation->getLangOpts()->CurrentModule = Module->getTopLevelModuleName();
  850. // Note that this module is part of the module build path, so that we
  851. // can detect cycles in the module graph.
  852. PPOpts.ModuleBuildPath.push_back(Module->getTopLevelModuleName());
  853. // If there is a module map file, build the module using the module map.
  854. // Set up the inputs/outputs so that we build the module from its umbrella
  855. // header.
  856. FrontendOptions &FrontendOpts = Invocation->getFrontendOpts();
  857. FrontendOpts.OutputFile = ModuleFileName.str();
  858. FrontendOpts.DisableFree = false;
  859. FrontendOpts.Inputs.clear();
  860. InputKind IK = getSourceInputKindFromOptions(*Invocation->getLangOpts());
  861. // Get or create the module map that we'll use to build this module.
  862. llvm::SmallString<128> TempModuleMapFileName;
  863. if (const FileEntry *ModuleMapFile
  864. = ModMap.getContainingModuleMapFile(Module)) {
  865. // Use the module map where this module resides.
  866. FrontendOpts.Inputs.push_back(std::make_pair(IK, ModuleMapFile->getName()));
  867. } else {
  868. // Create a temporary module map file.
  869. TempModuleMapFileName = Module->Name;
  870. TempModuleMapFileName += "-%%%%%%%%.map";
  871. int FD;
  872. if (llvm::sys::fs::unique_file(TempModuleMapFileName.str(), FD,
  873. TempModuleMapFileName,
  874. /*makeAbsolute=*/true)
  875. != llvm::errc::success) {
  876. ImportingInstance.getDiagnostics().Report(diag::err_module_map_temp_file)
  877. << TempModuleMapFileName;
  878. return;
  879. }
  880. // Print the module map to this file.
  881. llvm::raw_fd_ostream OS(FD, /*shouldClose=*/true);
  882. Module->print(OS);
  883. FrontendOpts.Inputs.push_back(
  884. std::make_pair(IK, TempModuleMapFileName.str().str()));
  885. }
  886. // Don't free the remapped file buffers; they are owned by our caller.
  887. PPOpts.RetainRemappedFileBuffers = true;
  888. Invocation->getDiagnosticOpts().VerifyDiagnostics = 0;
  889. assert(ImportingInstance.getInvocation().getModuleHash() ==
  890. Invocation->getModuleHash() && "Module hash mismatch!");
  891. // Construct a compiler instance that will be used to actually create the
  892. // module.
  893. CompilerInstance Instance;
  894. Instance.setInvocation(&*Invocation);
  895. Instance.createDiagnostics(/*argc=*/0, /*argv=*/0,
  896. &ImportingInstance.getDiagnosticClient(),
  897. /*ShouldOwnClient=*/true,
  898. /*ShouldCloneClient=*/true);
  899. // Construct a module-generating action.
  900. GenerateModuleAction CreateModuleAction;
  901. // Execute the action to actually build the module in-place. Use a separate
  902. // thread so that we get a stack large enough.
  903. const unsigned ThreadStackSize = 8 << 20;
  904. llvm::CrashRecoveryContext CRC;
  905. CompileModuleMapData Data = { Instance, CreateModuleAction };
  906. CRC.RunSafelyOnThread(&doCompileMapModule, &Data, ThreadStackSize);
  907. // Delete the temporary module map file.
  908. // FIXME: Even though we're executing under crash protection, it would still
  909. // be nice to do this with RemoveFileOnSignal when we can. However, that
  910. // doesn't make sense for all clients, so clean this up manually.
  911. if (!TempModuleMapFileName.empty())
  912. llvm::sys::Path(TempModuleMapFileName).eraseFromDisk();
  913. }
  914. Module *CompilerInstance::loadModule(SourceLocation ImportLoc,
  915. ModuleIdPath Path,
  916. Module::NameVisibilityKind Visibility,
  917. bool IsInclusionDirective) {
  918. // If we've already handled this import, just return the cached result.
  919. // This one-element cache is important to eliminate redundant diagnostics
  920. // when both the preprocessor and parser see the same import declaration.
  921. if (!ImportLoc.isInvalid() && LastModuleImportLoc == ImportLoc) {
  922. // Make the named module visible.
  923. if (LastModuleImportResult)
  924. ModuleManager->makeModuleVisible(LastModuleImportResult, Visibility);
  925. return LastModuleImportResult;
  926. }
  927. // Determine what file we're searching from.
  928. SourceManager &SourceMgr = getSourceManager();
  929. SourceLocation ExpandedImportLoc = SourceMgr.getExpansionLoc(ImportLoc);
  930. const FileEntry *CurFile
  931. = SourceMgr.getFileEntryForID(SourceMgr.getFileID(ExpandedImportLoc));
  932. if (!CurFile)
  933. CurFile = SourceMgr.getFileEntryForID(SourceMgr.getMainFileID());
  934. StringRef ModuleName = Path[0].first->getName();
  935. SourceLocation ModuleNameLoc = Path[0].second;
  936. clang::Module *Module = 0;
  937. const FileEntry *ModuleFile = 0;
  938. // If we don't already have information on this module, load the module now.
  939. llvm::DenseMap<const IdentifierInfo *, clang::Module *>::iterator Known
  940. = KnownModules.find(Path[0].first);
  941. if (Known != KnownModules.end()) {
  942. // Retrieve the cached top-level module.
  943. Module = Known->second;
  944. } else if (ModuleName == getLangOpts().CurrentModule) {
  945. // This is the module we're building.
  946. Module = PP->getHeaderSearchInfo().getModuleMap().findModule(ModuleName);
  947. Known = KnownModules.insert(std::make_pair(Path[0].first, Module)).first;
  948. } else {
  949. // Search for a module with the given name.
  950. std::string ModuleFileName;
  951. ModuleFile
  952. = PP->getHeaderSearchInfo().lookupModule(ModuleName, Module,
  953. &ModuleFileName);
  954. bool BuildingModule = false;
  955. if (!ModuleFile && Module) {
  956. // The module is not cached, but we have a module map from which we can
  957. // build the module.
  958. // Check whether there is a cycle in the module graph.
  959. SmallVectorImpl<std::string> &ModuleBuildPath
  960. = getPreprocessorOpts().ModuleBuildPath;
  961. SmallVectorImpl<std::string>::iterator Pos
  962. = std::find(ModuleBuildPath.begin(), ModuleBuildPath.end(), ModuleName);
  963. if (Pos != ModuleBuildPath.end()) {
  964. llvm::SmallString<256> CyclePath;
  965. for (; Pos != ModuleBuildPath.end(); ++Pos) {
  966. CyclePath += *Pos;
  967. CyclePath += " -> ";
  968. }
  969. CyclePath += ModuleName;
  970. getDiagnostics().Report(ModuleNameLoc, diag::err_module_cycle)
  971. << ModuleName << CyclePath;
  972. return 0;
  973. }
  974. getDiagnostics().Report(ModuleNameLoc, diag::warn_module_build)
  975. << ModuleName;
  976. BuildingModule = true;
  977. compileModule(*this, Module, ModuleFileName);
  978. ModuleFile = FileMgr->getFile(ModuleFileName);
  979. }
  980. if (!ModuleFile) {
  981. getDiagnostics().Report(ModuleNameLoc,
  982. BuildingModule? diag::err_module_not_built
  983. : diag::err_module_not_found)
  984. << ModuleName
  985. << SourceRange(ImportLoc, ModuleNameLoc);
  986. return 0;
  987. }
  988. // If we don't already have an ASTReader, create one now.
  989. if (!ModuleManager) {
  990. if (!hasASTContext())
  991. createASTContext();
  992. std::string Sysroot = getHeaderSearchOpts().Sysroot;
  993. const PreprocessorOptions &PPOpts = getPreprocessorOpts();
  994. ModuleManager = new ASTReader(getPreprocessor(), *Context,
  995. Sysroot.empty() ? "" : Sysroot.c_str(),
  996. PPOpts.DisablePCHValidation,
  997. PPOpts.DisableStatCache);
  998. if (hasASTConsumer()) {
  999. ModuleManager->setDeserializationListener(
  1000. getASTConsumer().GetASTDeserializationListener());
  1001. getASTContext().setASTMutationListener(
  1002. getASTConsumer().GetASTMutationListener());
  1003. }
  1004. llvm::OwningPtr<ExternalASTSource> Source;
  1005. Source.reset(ModuleManager);
  1006. getASTContext().setExternalSource(Source);
  1007. if (hasSema())
  1008. ModuleManager->InitializeSema(getSema());
  1009. if (hasASTConsumer())
  1010. ModuleManager->StartTranslationUnit(&getASTConsumer());
  1011. }
  1012. // Try to load the module we found.
  1013. switch (ModuleManager->ReadAST(ModuleFile->getName(),
  1014. serialization::MK_Module)) {
  1015. case ASTReader::Success:
  1016. break;
  1017. case ASTReader::IgnorePCH:
  1018. // FIXME: The ASTReader will already have complained, but can we showhorn
  1019. // that diagnostic information into a more useful form?
  1020. KnownModules[Path[0].first] = 0;
  1021. return 0;
  1022. case ASTReader::Failure:
  1023. // Already complained, but note now that we failed.
  1024. KnownModules[Path[0].first] = 0;
  1025. return 0;
  1026. }
  1027. if (!Module) {
  1028. // If we loaded the module directly, without finding a module map first,
  1029. // we'll have loaded the module's information from the module itself.
  1030. Module = PP->getHeaderSearchInfo().getModuleMap()
  1031. .findModule((Path[0].first->getName()));
  1032. }
  1033. // Cache the result of this top-level module lookup for later.
  1034. Known = KnownModules.insert(std::make_pair(Path[0].first, Module)).first;
  1035. }
  1036. // If we never found the module, fail.
  1037. if (!Module)
  1038. return 0;
  1039. // Verify that the rest of the module path actually corresponds to
  1040. // a submodule.
  1041. if (Path.size() > 1) {
  1042. for (unsigned I = 1, N = Path.size(); I != N; ++I) {
  1043. StringRef Name = Path[I].first->getName();
  1044. llvm::StringMap<clang::Module *>::iterator Pos
  1045. = Module->SubModules.find(Name);
  1046. if (Pos == Module->SubModules.end()) {
  1047. // Attempt to perform typo correction to find a module name that works.
  1048. llvm::SmallVector<StringRef, 2> Best;
  1049. unsigned BestEditDistance = (std::numeric_limits<unsigned>::max)();
  1050. for (llvm::StringMap<clang::Module *>::iterator
  1051. J = Module->SubModules.begin(),
  1052. JEnd = Module->SubModules.end();
  1053. J != JEnd; ++J) {
  1054. unsigned ED = Name.edit_distance(J->getValue()->Name,
  1055. /*AllowReplacements=*/true,
  1056. BestEditDistance);
  1057. if (ED <= BestEditDistance) {
  1058. if (ED < BestEditDistance)
  1059. Best.clear();
  1060. Best.push_back(J->getValue()->Name);
  1061. }
  1062. }
  1063. // If there was a clear winner, user it.
  1064. if (Best.size() == 1) {
  1065. getDiagnostics().Report(Path[I].second,
  1066. diag::err_no_submodule_suggest)
  1067. << Path[I].first << Module->getFullModuleName() << Best[0]
  1068. << SourceRange(Path[0].second, Path[I-1].second)
  1069. << FixItHint::CreateReplacement(SourceRange(Path[I].second),
  1070. Best[0]);
  1071. Pos = Module->SubModules.find(Best[0]);
  1072. }
  1073. }
  1074. if (Pos == Module->SubModules.end()) {
  1075. // No submodule by this name. Complain, and don't look for further
  1076. // submodules.
  1077. getDiagnostics().Report(Path[I].second, diag::err_no_submodule)
  1078. << Path[I].first << Module->getFullModuleName()
  1079. << SourceRange(Path[0].second, Path[I-1].second);
  1080. break;
  1081. }
  1082. Module = Pos->getValue();
  1083. }
  1084. }
  1085. // Make the named module visible, if it's not already part of the module
  1086. // we are parsing.
  1087. if (ModuleName != getLangOpts().CurrentModule)
  1088. ModuleManager->makeModuleVisible(Module, Visibility);
  1089. // If this module import was due to an inclusion directive, create an
  1090. // implicit import declaration to capture it in the AST.
  1091. if (IsInclusionDirective && hasASTContext()) {
  1092. TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
  1093. TU->addDecl(ImportDecl::CreateImplicit(getASTContext(), TU,
  1094. ImportLoc, Module,
  1095. Path.back().second));
  1096. }
  1097. LastModuleImportLoc = ImportLoc;
  1098. LastModuleImportResult = Module;
  1099. return Module;
  1100. }