CompilerInstance.cpp 40 KB

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