CompilerInstance.cpp 52 KB

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