CompilerInstance.cpp 52 KB

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