CompilerInstance.cpp 44 KB

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