blob: f14c2e30bc2305e5f8f3064aef47ac08b8bf30f9 [file] [log] [blame]
Daniel Dunbar2a79e162009-11-13 03:51:44 +00001//===--- 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
10#include "clang/Frontend/CompilerInstance.h"
Douglas Gregorf18d0d82010-08-12 23:31:19 +000011#include "clang/Sema/Sema.h"
Daniel Dunbar12ce6942009-11-14 02:47:17 +000012#include "clang/AST/ASTConsumer.h"
Daniel Dunbar5eb81002009-11-13 08:20:47 +000013#include "clang/AST/ASTContext.h"
Daniel Dunbar2a79e162009-11-13 03:51:44 +000014#include "clang/Basic/Diagnostic.h"
Daniel Dunbar16b74492009-11-13 04:12:06 +000015#include "clang/Basic/FileManager.h"
16#include "clang/Basic/SourceManager.h"
Daniel Dunbar2a79e162009-11-13 03:51:44 +000017#include "clang/Basic/TargetInfo.h"
Daniel Dunbar0397af22010-01-13 00:48:06 +000018#include "clang/Basic/Version.h"
Daniel Dunbar22dacfa2009-11-13 05:52:11 +000019#include "clang/Lex/HeaderSearch.h"
20#include "clang/Lex/Preprocessor.h"
21#include "clang/Lex/PTHManager.h"
David Blaikie4e85b8a2011-09-26 00:21:47 +000022#include "clang/Frontend/ChainedDiagnosticConsumer.h"
Daniel Dunbar0397af22010-01-13 00:48:06 +000023#include "clang/Frontend/FrontendAction.h"
Douglas Gregor21cae202011-09-12 23:31:24 +000024#include "clang/Frontend/FrontendActions.h"
Daniel Dunbarc2f484f2009-11-13 09:36:05 +000025#include "clang/Frontend/FrontendDiagnostic.h"
Daniel Dunbar9df23492011-04-07 18:31:10 +000026#include "clang/Frontend/LogDiagnosticPrinter.h"
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +000027#include "clang/Frontend/TextDiagnosticPrinter.h"
David Blaikie621bc692011-09-26 00:38:03 +000028#include "clang/Frontend/VerifyDiagnosticConsumer.h"
Daniel Dunbar22dacfa2009-11-13 05:52:11 +000029#include "clang/Frontend/Utils.h"
Sebastian Redl6ab7cd82010-08-18 23:57:17 +000030#include "clang/Serialization/ASTReader.h"
Daniel Dunbarc2f484f2009-11-13 09:36:05 +000031#include "clang/Sema/CodeCompleteConsumer.h"
Michael J. Spencer32bef4e2011-01-10 02:34:13 +000032#include "llvm/Support/FileSystem.h"
Daniel Dunbarccb6cb62009-11-14 07:53:04 +000033#include "llvm/Support/MemoryBuffer.h"
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +000034#include "llvm/Support/raw_ostream.h"
Douglas Gregor95dd5582010-03-30 17:33:59 +000035#include "llvm/ADT/Statistic.h"
Kovarththanan Rajaratnamf79bafa2009-11-29 09:57:35 +000036#include "llvm/Support/Timer.h"
Michael J. Spencer03013fa2010-11-29 18:12:39 +000037#include "llvm/Support/Host.h"
38#include "llvm/Support/Path.h"
39#include "llvm/Support/Program.h"
40#include "llvm/Support/Signals.h"
Michael J. Spencer3a321e22010-12-09 17:36:38 +000041#include "llvm/Support/system_error.h"
Douglas Gregor0ced7992011-10-04 00:21:21 +000042#include "llvm/Support/CrashRecoveryContext.h"
Dylan Noblesmith16266012011-06-23 12:20:57 +000043#include "llvm/Config/config.h"
Douglas Gregor2bc75072011-10-05 14:53:30 +000044
45// Support for FileLockManager
46#include <fstream>
47#include <sys/types.h>
48#include <sys/stat.h>
49
50#if LLVM_ON_UNIX
51#include <unistd.h>
52#endif
53
Daniel Dunbar2a79e162009-11-13 03:51:44 +000054using namespace clang;
55
Daniel Dunbar42e9f8e42010-02-16 01:54:47 +000056CompilerInstance::CompilerInstance()
Douglas Gregorf62d43d2011-07-19 16:10:42 +000057 : Invocation(new CompilerInvocation()), ModuleManager(0) {
Daniel Dunbar6228ca02010-01-30 21:47:07 +000058}
Daniel Dunbar2a79e162009-11-13 03:51:44 +000059
60CompilerInstance::~CompilerInstance() {
Daniel Dunbar42e9f8e42010-02-16 01:54:47 +000061}
62
Daniel Dunbar6228ca02010-01-30 21:47:07 +000063void CompilerInstance::setInvocation(CompilerInvocation *Value) {
Ted Kremenek4f327862011-03-21 18:40:17 +000064 Invocation = Value;
Daniel Dunbar6228ca02010-01-30 21:47:07 +000065}
66
David Blaikied6471f72011-09-25 23:23:43 +000067void CompilerInstance::setDiagnostics(DiagnosticsEngine *Value) {
Douglas Gregor28019772010-04-05 23:52:57 +000068 Diagnostics = Value;
Daniel Dunbar8a9f5692009-11-14 01:20:40 +000069}
70
Daniel Dunbar8a9f5692009-11-14 01:20:40 +000071void CompilerInstance::setTarget(TargetInfo *Value) {
Ted Kremenek4f327862011-03-21 18:40:17 +000072 Target = Value;
Daniel Dunbar8a9f5692009-11-14 01:20:40 +000073}
74
75void CompilerInstance::setFileManager(FileManager *Value) {
Ted Kremenek4f327862011-03-21 18:40:17 +000076 FileMgr = Value;
Daniel Dunbar8a9f5692009-11-14 01:20:40 +000077}
78
Ted Kremenek4f327862011-03-21 18:40:17 +000079void CompilerInstance::setSourceManager(SourceManager *Value) {
80 SourceMgr = Value;
Daniel Dunbar8a9f5692009-11-14 01:20:40 +000081}
82
Ted Kremenek4f327862011-03-21 18:40:17 +000083void CompilerInstance::setPreprocessor(Preprocessor *Value) { PP = Value; }
Daniel Dunbar8a9f5692009-11-14 01:20:40 +000084
Ted Kremenek4f327862011-03-21 18:40:17 +000085void CompilerInstance::setASTContext(ASTContext *Value) { Context = Value; }
Daniel Dunbar8a9f5692009-11-14 01:20:40 +000086
Douglas Gregorf18d0d82010-08-12 23:31:19 +000087void CompilerInstance::setSema(Sema *S) {
88 TheSema.reset(S);
89}
90
Daniel Dunbar12ce6942009-11-14 02:47:17 +000091void CompilerInstance::setASTConsumer(ASTConsumer *Value) {
92 Consumer.reset(Value);
93}
94
Daniel Dunbar8a9f5692009-11-14 01:20:40 +000095void CompilerInstance::setCodeCompletionConsumer(CodeCompleteConsumer *Value) {
96 CompletionConsumer.reset(Value);
97}
98
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +000099// Diagnostics
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000100static void SetUpBuildDumpLog(const DiagnosticOptions &DiagOpts,
Axel Naumann7d0c4cc2010-10-11 09:13:46 +0000101 unsigned argc, const char* const *argv,
David Blaikied6471f72011-09-25 23:23:43 +0000102 DiagnosticsEngine &Diags) {
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000103 std::string ErrorInfo;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000104 llvm::OwningPtr<raw_ostream> OS(
Kovarththanan Rajaratnam69247132010-03-17 09:47:30 +0000105 new llvm::raw_fd_ostream(DiagOpts.DumpBuildInformation.c_str(), ErrorInfo));
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000106 if (!ErrorInfo.empty()) {
Kovarththanan Rajaratnam3d67b1e2010-03-17 09:24:48 +0000107 Diags.Report(diag::err_fe_unable_to_open_logfile)
108 << DiagOpts.DumpBuildInformation << ErrorInfo;
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000109 return;
110 }
111
Daniel Dunbardd63b282009-12-11 23:04:35 +0000112 (*OS) << "clang -cc1 command line arguments: ";
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000113 for (unsigned i = 0; i != argc; ++i)
114 (*OS) << argv[i] << ' ';
115 (*OS) << '\n';
116
117 // Chain in a diagnostic client which will log the diagnostics.
David Blaikie78ad0b92011-09-25 23:39:51 +0000118 DiagnosticConsumer *Logger =
Kovarththanan Rajaratnam69247132010-03-17 09:47:30 +0000119 new TextDiagnosticPrinter(*OS.take(), DiagOpts, /*OwnsOutputStream=*/true);
David Blaikie4e85b8a2011-09-26 00:21:47 +0000120 Diags.setClient(new ChainedDiagnosticConsumer(Diags.takeClient(), Logger));
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000121}
122
Daniel Dunbar9df23492011-04-07 18:31:10 +0000123static void SetUpDiagnosticLog(const DiagnosticOptions &DiagOpts,
Daniel Dunbarb6534bb2011-04-07 18:59:02 +0000124 const CodeGenOptions *CodeGenOpts,
David Blaikied6471f72011-09-25 23:23:43 +0000125 DiagnosticsEngine &Diags) {
Daniel Dunbar9df23492011-04-07 18:31:10 +0000126 std::string ErrorInfo;
127 bool OwnsStream = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000128 raw_ostream *OS = &llvm::errs();
Daniel Dunbar9df23492011-04-07 18:31:10 +0000129 if (DiagOpts.DiagnosticLogFile != "-") {
130 // Create the output stream.
131 llvm::raw_fd_ostream *FileOS(
132 new llvm::raw_fd_ostream(DiagOpts.DiagnosticLogFile.c_str(),
Daniel Dunbare01eceb2011-04-07 20:19:21 +0000133 ErrorInfo, llvm::raw_fd_ostream::F_Append));
Daniel Dunbar9df23492011-04-07 18:31:10 +0000134 if (!ErrorInfo.empty()) {
135 Diags.Report(diag::warn_fe_cc_log_diagnostics_failure)
136 << DiagOpts.DumpBuildInformation << ErrorInfo;
137 } else {
138 FileOS->SetUnbuffered();
139 FileOS->SetUseAtomicWrites(true);
140 OS = FileOS;
141 OwnsStream = true;
142 }
143 }
144
145 // Chain in the diagnostic client which will log the diagnostics.
Daniel Dunbarb6534bb2011-04-07 18:59:02 +0000146 LogDiagnosticPrinter *Logger = new LogDiagnosticPrinter(*OS, DiagOpts,
147 OwnsStream);
148 if (CodeGenOpts)
149 Logger->setDwarfDebugFlags(CodeGenOpts->DwarfDebugFlags);
David Blaikie4e85b8a2011-09-26 00:21:47 +0000150 Diags.setClient(new ChainedDiagnosticConsumer(Diags.takeClient(), Logger));
Daniel Dunbar9df23492011-04-07 18:31:10 +0000151}
152
Douglas Gregore47be3e2010-11-11 00:39:14 +0000153void CompilerInstance::createDiagnostics(int Argc, const char* const *Argv,
David Blaikie78ad0b92011-09-25 23:39:51 +0000154 DiagnosticConsumer *Client,
Douglas Gregoraee526e2011-09-29 00:38:00 +0000155 bool ShouldOwnClient,
156 bool ShouldCloneClient) {
Daniel Dunbarb6534bb2011-04-07 18:59:02 +0000157 Diagnostics = createDiagnostics(getDiagnosticOpts(), Argc, Argv, Client,
Douglas Gregoraee526e2011-09-29 00:38:00 +0000158 ShouldOwnClient, ShouldCloneClient,
159 &getCodeGenOpts());
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000160}
161
David Blaikied6471f72011-09-25 23:23:43 +0000162llvm::IntrusiveRefCntPtr<DiagnosticsEngine>
Douglas Gregor28019772010-04-05 23:52:57 +0000163CompilerInstance::createDiagnostics(const DiagnosticOptions &Opts,
Douglas Gregore47be3e2010-11-11 00:39:14 +0000164 int Argc, const char* const *Argv,
David Blaikie78ad0b92011-09-25 23:39:51 +0000165 DiagnosticConsumer *Client,
Douglas Gregor78243652011-09-13 01:26:44 +0000166 bool ShouldOwnClient,
Douglas Gregoraee526e2011-09-29 00:38:00 +0000167 bool ShouldCloneClient,
Daniel Dunbarb6534bb2011-04-07 18:59:02 +0000168 const CodeGenOptions *CodeGenOpts) {
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000169 llvm::IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
David Blaikied6471f72011-09-25 23:23:43 +0000170 llvm::IntrusiveRefCntPtr<DiagnosticsEngine>
171 Diags(new DiagnosticsEngine(DiagID));
Daniel Dunbar221c7212009-11-14 07:53:24 +0000172
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000173 // Create the diagnostic client for reporting errors or for
174 // implementing -verify.
Douglas Gregoraee526e2011-09-29 00:38:00 +0000175 if (Client) {
176 if (ShouldCloneClient)
177 Diags->setClient(Client->clone(*Diags), ShouldOwnClient);
178 else
179 Diags->setClient(Client, ShouldOwnClient);
180 } else
Douglas Gregore47be3e2010-11-11 00:39:14 +0000181 Diags->setClient(new TextDiagnosticPrinter(llvm::errs(), Opts));
Daniel Dunbarf79dced2009-11-14 03:24:39 +0000182
183 // Chain in -verify checker, if requested.
Douglas Gregor78243652011-09-13 01:26:44 +0000184 if (Opts.VerifyDiagnostics)
David Blaikie621bc692011-09-26 00:38:03 +0000185 Diags->setClient(new VerifyDiagnosticConsumer(*Diags));
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000186
Daniel Dunbar9df23492011-04-07 18:31:10 +0000187 // Chain in -diagnostic-log-file dumper, if requested.
188 if (!Opts.DiagnosticLogFile.empty())
Daniel Dunbarb6534bb2011-04-07 18:59:02 +0000189 SetUpDiagnosticLog(Opts, CodeGenOpts, *Diags);
Daniel Dunbar9df23492011-04-07 18:31:10 +0000190
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000191 if (!Opts.DumpBuildInformation.empty())
Kovarththanan Rajaratnam3d67b1e2010-03-17 09:24:48 +0000192 SetUpBuildDumpLog(Opts, Argc, Argv, *Diags);
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000193
194 // Configure our handling of diagnostics.
Kovarththanan Rajaratnam5bf932b2010-03-17 09:36:02 +0000195 ProcessWarningOptions(*Diags, Opts);
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000196
Douglas Gregor28019772010-04-05 23:52:57 +0000197 return Diags;
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000198}
199
200// File Manager
201
Daniel Dunbar16b74492009-11-13 04:12:06 +0000202void CompilerInstance::createFileManager() {
Ted Kremenek4f327862011-03-21 18:40:17 +0000203 FileMgr = new FileManager(getFileSystemOpts());
Daniel Dunbar16b74492009-11-13 04:12:06 +0000204}
205
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000206// Source Manager
207
Chris Lattner39b49bc2010-11-23 08:35:12 +0000208void CompilerInstance::createSourceManager(FileManager &FileMgr) {
Ted Kremenek4f327862011-03-21 18:40:17 +0000209 SourceMgr = new SourceManager(getDiagnostics(), FileMgr);
Daniel Dunbar16b74492009-11-13 04:12:06 +0000210}
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000211
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000212// Preprocessor
213
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000214void CompilerInstance::createPreprocessor() {
Douglas Gregor6aa52ec2011-08-26 23:56:07 +0000215 const PreprocessorOptions &PPOpts = getPreprocessorOpts();
216
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000217 // Create a PTH manager if we are using some form of a token cache.
218 PTHManager *PTHMgr = 0;
Daniel Dunbar049d3a02009-11-17 05:52:41 +0000219 if (!PPOpts.TokenCache.empty())
Douglas Gregor6aa52ec2011-08-26 23:56:07 +0000220 PTHMgr = PTHManager::Create(PPOpts.TokenCache, getDiagnostics());
221
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000222 // Create the Preprocessor.
Douglas Gregor6aa52ec2011-08-26 23:56:07 +0000223 HeaderSearch *HeaderInfo = new HeaderSearch(getFileManager());
Douglas Gregor998b3d32011-09-01 23:39:15 +0000224 PP = new Preprocessor(getDiagnostics(), getLangOpts(), &getTarget(),
Douglas Gregor6aa52ec2011-08-26 23:56:07 +0000225 getSourceManager(), *HeaderInfo, *this, PTHMgr,
226 /*OwnsHeaderSearch=*/true);
227
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000228 // Note that this is different then passing PTHMgr to Preprocessor's ctor.
229 // That argument is used as the IdentifierInfoLookup argument to
230 // IdentifierTable's ctor.
231 if (PTHMgr) {
Douglas Gregor6aa52ec2011-08-26 23:56:07 +0000232 PTHMgr->setPreprocessor(&*PP);
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000233 PP->setPTHManager(PTHMgr);
234 }
Douglas Gregor6aa52ec2011-08-26 23:56:07 +0000235
Douglas Gregor94dc8f62010-03-19 16:15:56 +0000236 if (PPOpts.DetailedRecord)
Douglas Gregordca8ee82011-05-06 16:33:08 +0000237 PP->createPreprocessingRecord(
Douglas Gregor6aa52ec2011-08-26 23:56:07 +0000238 PPOpts.DetailedRecordIncludesNestedMacroExpansions);
Douglas Gregor94dc8f62010-03-19 16:15:56 +0000239
Douglas Gregor6aa52ec2011-08-26 23:56:07 +0000240 InitializePreprocessor(*PP, PPOpts, getHeaderSearchOpts(), getFrontendOpts());
241
Douglas Gregor6e975c42011-09-13 23:15:45 +0000242 // Set up the module path, including the hash for the
243 // module-creation options.
244 llvm::SmallString<256> SpecificModuleCache(
245 getHeaderSearchOpts().ModuleCachePath);
246 if (!getHeaderSearchOpts().DisableModuleHash)
247 llvm::sys::path::append(SpecificModuleCache,
248 getInvocation().getModuleHash());
Douglas Gregorfba18aa2011-09-15 22:00:41 +0000249 PP->getHeaderSearchInfo().configureModules(SpecificModuleCache,
250 getPreprocessorOpts().ModuleBuildPath.empty()
251 ? std::string()
252 : getPreprocessorOpts().ModuleBuildPath.back());
Douglas Gregor6e975c42011-09-13 23:15:45 +0000253
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000254 // Handle generating dependencies, if requested.
Douglas Gregor6aa52ec2011-08-26 23:56:07 +0000255 const DependencyOutputOptions &DepOpts = getDependencyOutputOpts();
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000256 if (!DepOpts.OutputFile.empty())
257 AttachDependencyFileGen(*PP, DepOpts);
Douglas Gregor6aa52ec2011-08-26 23:56:07 +0000258
Daniel Dunbareef63e02011-02-02 15:41:17 +0000259 // Handle generating header include information, if requested.
260 if (DepOpts.ShowHeaderIncludes)
261 AttachHeaderIncludeGen(*PP);
Daniel Dunbarb34d69b2011-02-02 21:11:31 +0000262 if (!DepOpts.HeaderIncludeOutputFile.empty()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000263 StringRef OutputPath = DepOpts.HeaderIncludeOutputFile;
Daniel Dunbarb34d69b2011-02-02 21:11:31 +0000264 if (OutputPath == "-")
265 OutputPath = "";
Daniel Dunbarda608852011-03-21 19:37:38 +0000266 AttachHeaderIncludeGen(*PP, /*ShowAllHeaders=*/true, OutputPath,
267 /*ShowDepth=*/false);
Daniel Dunbarb34d69b2011-02-02 21:11:31 +0000268 }
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000269}
Daniel Dunbar5eb81002009-11-13 08:20:47 +0000270
271// ASTContext
272
273void CompilerInstance::createASTContext() {
274 Preprocessor &PP = getPreprocessor();
Ted Kremenek4f327862011-03-21 18:40:17 +0000275 Context = new ASTContext(getLangOpts(), PP.getSourceManager(),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000276 &getTarget(), PP.getIdentifierTable(),
Ted Kremenek4f327862011-03-21 18:40:17 +0000277 PP.getSelectorTable(), PP.getBuiltinInfo(),
278 /*size_reserve=*/ 0);
Daniel Dunbar5eb81002009-11-13 08:20:47 +0000279}
Daniel Dunbar0f800392009-11-13 08:21:10 +0000280
281// ExternalASTSource
282
Chris Lattner5f9e2722011-07-23 10:55:15 +0000283void CompilerInstance::createPCHExternalASTSource(StringRef Path,
Sebastian Redlffaab3e2010-07-30 00:29:29 +0000284 bool DisablePCHValidation,
Douglas Gregor8ef6c8c2011-02-05 19:42:43 +0000285 bool DisableStatCache,
Sebastian Redlffaab3e2010-07-30 00:29:29 +0000286 void *DeserializationListener){
Daniel Dunbar0f800392009-11-13 08:21:10 +0000287 llvm::OwningPtr<ExternalASTSource> Source;
Sebastian Redl1d9f1fe2010-10-05 16:15:19 +0000288 bool Preamble = getPreprocessorOpts().PrecompiledPreambleBytes.first != 0;
Daniel Dunbar0f800392009-11-13 08:21:10 +0000289 Source.reset(createPCHExternalASTSource(Path, getHeaderSearchOpts().Sysroot,
Douglas Gregor8ef6c8c2011-02-05 19:42:43 +0000290 DisablePCHValidation,
291 DisableStatCache,
Sebastian Redlffaab3e2010-07-30 00:29:29 +0000292 getPreprocessor(), getASTContext(),
Sebastian Redl1d9f1fe2010-10-05 16:15:19 +0000293 DeserializationListener,
294 Preamble));
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000295 ModuleManager = static_cast<ASTReader*>(Source.get());
Daniel Dunbar0f800392009-11-13 08:21:10 +0000296 getASTContext().setExternalSource(Source);
297}
298
299ExternalASTSource *
Chris Lattner5f9e2722011-07-23 10:55:15 +0000300CompilerInstance::createPCHExternalASTSource(StringRef Path,
Daniel Dunbar0f800392009-11-13 08:21:10 +0000301 const std::string &Sysroot,
Douglas Gregorfae3b2f2010-07-27 00:27:13 +0000302 bool DisablePCHValidation,
Douglas Gregor8ef6c8c2011-02-05 19:42:43 +0000303 bool DisableStatCache,
Daniel Dunbar0f800392009-11-13 08:21:10 +0000304 Preprocessor &PP,
Sebastian Redlffaab3e2010-07-30 00:29:29 +0000305 ASTContext &Context,
Sebastian Redl1d9f1fe2010-10-05 16:15:19 +0000306 void *DeserializationListener,
307 bool Preamble) {
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000308 llvm::OwningPtr<ASTReader> Reader;
Douglas Gregorf8a1e512011-09-02 00:26:20 +0000309 Reader.reset(new ASTReader(PP, Context,
Douglas Gregor832d6202011-07-22 16:35:34 +0000310 Sysroot.empty() ? "" : Sysroot.c_str(),
Douglas Gregor8ef6c8c2011-02-05 19:42:43 +0000311 DisablePCHValidation, DisableStatCache));
Daniel Dunbar0f800392009-11-13 08:21:10 +0000312
Sebastian Redlffaab3e2010-07-30 00:29:29 +0000313 Reader->setDeserializationListener(
Sebastian Redl571db7f2010-08-18 23:56:56 +0000314 static_cast<ASTDeserializationListener *>(DeserializationListener));
Douglas Gregor72a9ae12011-07-22 16:00:58 +0000315 switch (Reader->ReadAST(Path,
316 Preamble ? serialization::MK_Preamble
317 : serialization::MK_PCH)) {
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000318 case ASTReader::Success:
Daniel Dunbar0f800392009-11-13 08:21:10 +0000319 // Set the predefines buffer as suggested by the PCH reader. Typically, the
320 // predefines buffer will be empty.
321 PP.setPredefines(Reader->getSuggestedPredefines());
322 return Reader.take();
323
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000324 case ASTReader::Failure:
Daniel Dunbar0f800392009-11-13 08:21:10 +0000325 // Unrecoverable failure: don't even try to process the input file.
326 break;
327
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000328 case ASTReader::IgnorePCH:
Daniel Dunbar0f800392009-11-13 08:21:10 +0000329 // No suitable PCH file could be found. Return an error.
330 break;
331 }
332
333 return 0;
334}
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000335
336// Code Completion
337
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000338static bool EnableCodeCompletion(Preprocessor &PP,
339 const std::string &Filename,
340 unsigned Line,
341 unsigned Column) {
342 // Tell the source manager to chop off the given file at a specific
343 // line and column.
Chris Lattner39b49bc2010-11-23 08:35:12 +0000344 const FileEntry *Entry = PP.getFileManager().getFile(Filename);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000345 if (!Entry) {
346 PP.getDiagnostics().Report(diag::err_fe_invalid_code_complete_file)
347 << Filename;
348 return true;
349 }
350
351 // Truncate the named file at the given line/column.
352 PP.SetCodeCompletionPoint(Entry, Line, Column);
353 return false;
354}
355
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000356void CompilerInstance::createCodeCompletionConsumer() {
357 const ParsedSourceLocation &Loc = getFrontendOpts().CodeCompletionAt;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000358 if (!CompletionConsumer) {
359 CompletionConsumer.reset(
360 createCodeCompletionConsumer(getPreprocessor(),
361 Loc.FileName, Loc.Line, Loc.Column,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000362 getFrontendOpts().ShowMacrosInCodeCompletion,
Douglas Gregord8e8a582010-05-25 21:41:55 +0000363 getFrontendOpts().ShowCodePatternsInCodeCompletion,
Douglas Gregor8071e422010-08-15 06:18:01 +0000364 getFrontendOpts().ShowGlobalSymbolsInCodeCompletion,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000365 llvm::outs()));
366 if (!CompletionConsumer)
367 return;
368 } else if (EnableCodeCompletion(getPreprocessor(), Loc.FileName,
369 Loc.Line, Loc.Column)) {
370 CompletionConsumer.reset();
Douglas Gregorc3d43b72010-03-16 06:04:47 +0000371 return;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000372 }
Douglas Gregor2b4074f2009-12-01 05:55:20 +0000373
374 if (CompletionConsumer->isOutputBinary() &&
375 llvm::sys::Program::ChangeStdoutToBinary()) {
376 getPreprocessor().getDiagnostics().Report(diag::err_fe_stdout_binary);
377 CompletionConsumer.reset();
378 }
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000379}
380
Kovarththanan Rajaratnamf79bafa2009-11-29 09:57:35 +0000381void CompilerInstance::createFrontendTimer() {
382 FrontendTimer.reset(new llvm::Timer("Clang front-end timer"));
383}
384
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000385CodeCompleteConsumer *
386CompilerInstance::createCodeCompletionConsumer(Preprocessor &PP,
387 const std::string &Filename,
388 unsigned Line,
389 unsigned Column,
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000390 bool ShowMacros,
Douglas Gregord8e8a582010-05-25 21:41:55 +0000391 bool ShowCodePatterns,
Douglas Gregor8071e422010-08-15 06:18:01 +0000392 bool ShowGlobals,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000393 raw_ostream &OS) {
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000394 if (EnableCodeCompletion(PP, Filename, Line, Column))
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000395 return 0;
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000396
397 // Set up the creation routine for code-completion.
Douglas Gregora9f4f622010-10-11 22:12:15 +0000398 return new PrintingCodeCompleteConsumer(ShowMacros, ShowCodePatterns,
Douglas Gregor8071e422010-08-15 06:18:01 +0000399 ShowGlobals, OS);
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000400}
Daniel Dunbara9204832009-11-13 10:37:48 +0000401
Douglas Gregor467dc882011-08-25 22:30:56 +0000402void CompilerInstance::createSema(TranslationUnitKind TUKind,
Douglas Gregorf18d0d82010-08-12 23:31:19 +0000403 CodeCompleteConsumer *CompletionConsumer) {
404 TheSema.reset(new Sema(getPreprocessor(), getASTContext(), getASTConsumer(),
Douglas Gregor467dc882011-08-25 22:30:56 +0000405 TUKind, CompletionConsumer));
Douglas Gregorf18d0d82010-08-12 23:31:19 +0000406}
407
Daniel Dunbara9204832009-11-13 10:37:48 +0000408// Output Files
409
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000410void CompilerInstance::addOutputFile(const OutputFile &OutFile) {
411 assert(OutFile.OS && "Attempt to add empty stream to output list!");
412 OutputFiles.push_back(OutFile);
Daniel Dunbara9204832009-11-13 10:37:48 +0000413}
414
Kovarththanan Rajaratname51dd7b2010-03-06 12:07:48 +0000415void CompilerInstance::clearOutputFiles(bool EraseFiles) {
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000416 for (std::list<OutputFile>::iterator
Daniel Dunbara9204832009-11-13 10:37:48 +0000417 it = OutputFiles.begin(), ie = OutputFiles.end(); it != ie; ++it) {
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000418 delete it->OS;
419 if (!it->TempFilename.empty()) {
Anders Carlssonaf036a62011-03-06 22:25:35 +0000420 if (EraseFiles) {
421 bool existed;
422 llvm::sys::fs::remove(it->TempFilename, existed);
423 } else {
424 llvm::SmallString<128> NewOutFile(it->Filename);
425
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +0000426 // If '-working-directory' was passed, the output filename should be
427 // relative to that.
Anders Carlsson2e2468e2011-03-14 01:13:54 +0000428 FileMgr->FixupRelativePath(NewOutFile);
Anders Carlssonaf036a62011-03-06 22:25:35 +0000429 if (llvm::error_code ec = llvm::sys::fs::rename(it->TempFilename,
430 NewOutFile.str())) {
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000431 getDiagnostics().Report(diag::err_fe_unable_to_rename_temp)
Anders Carlssonaf036a62011-03-06 22:25:35 +0000432 << it->TempFilename << it->Filename << ec.message();
433
434 bool existed;
435 llvm::sys::fs::remove(it->TempFilename, existed);
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000436 }
437 }
438 } else if (!it->Filename.empty() && EraseFiles)
439 llvm::sys::Path(it->Filename).eraseFromDisk();
440
Daniel Dunbara9204832009-11-13 10:37:48 +0000441 }
442 OutputFiles.clear();
443}
444
Daniel Dunbarf482d592009-11-13 18:32:08 +0000445llvm::raw_fd_ostream *
446CompilerInstance::createDefaultOutputFile(bool Binary,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000447 StringRef InFile,
448 StringRef Extension) {
Daniel Dunbarf482d592009-11-13 18:32:08 +0000449 return createOutputFile(getFrontendOpts().OutputFile, Binary,
Daniel Dunbarff9cd962011-01-31 22:00:42 +0000450 /*RemoveFileOnSignal=*/true, InFile, Extension);
Daniel Dunbarf482d592009-11-13 18:32:08 +0000451}
452
453llvm::raw_fd_ostream *
Chris Lattner5f9e2722011-07-23 10:55:15 +0000454CompilerInstance::createOutputFile(StringRef OutputPath,
Daniel Dunbarff9cd962011-01-31 22:00:42 +0000455 bool Binary, bool RemoveFileOnSignal,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000456 StringRef InFile,
Argyrios Kyrtzidis7e909852011-07-28 00:45:10 +0000457 StringRef Extension,
458 bool UseTemporary) {
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000459 std::string Error, OutputPathName, TempPathName;
Daniel Dunbarf482d592009-11-13 18:32:08 +0000460 llvm::raw_fd_ostream *OS = createOutputFile(OutputPath, Error, Binary,
Daniel Dunbarff9cd962011-01-31 22:00:42 +0000461 RemoveFileOnSignal,
Daniel Dunbarf482d592009-11-13 18:32:08 +0000462 InFile, Extension,
Argyrios Kyrtzidis7e909852011-07-28 00:45:10 +0000463 UseTemporary,
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000464 &OutputPathName,
465 &TempPathName);
Daniel Dunbarf482d592009-11-13 18:32:08 +0000466 if (!OS) {
Daniel Dunbar36043592009-12-03 09:13:30 +0000467 getDiagnostics().Report(diag::err_fe_unable_to_open_output)
468 << OutputPath << Error;
469 return 0;
Daniel Dunbarf482d592009-11-13 18:32:08 +0000470 }
471
472 // Add the output file -- but don't try to remove "-", since this means we are
473 // using stdin.
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000474 addOutputFile(OutputFile((OutputPathName != "-") ? OutputPathName : "",
475 TempPathName, OS));
Daniel Dunbarf482d592009-11-13 18:32:08 +0000476
477 return OS;
478}
479
480llvm::raw_fd_ostream *
Chris Lattner5f9e2722011-07-23 10:55:15 +0000481CompilerInstance::createOutputFile(StringRef OutputPath,
Daniel Dunbarf482d592009-11-13 18:32:08 +0000482 std::string &Error,
483 bool Binary,
Daniel Dunbarff9cd962011-01-31 22:00:42 +0000484 bool RemoveFileOnSignal,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000485 StringRef InFile,
486 StringRef Extension,
Argyrios Kyrtzidis7e909852011-07-28 00:45:10 +0000487 bool UseTemporary,
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000488 std::string *ResultPathName,
489 std::string *TempPathName) {
490 std::string OutFile, TempFile;
Daniel Dunbarf482d592009-11-13 18:32:08 +0000491 if (!OutputPath.empty()) {
492 OutFile = OutputPath;
493 } else if (InFile == "-") {
494 OutFile = "-";
495 } else if (!Extension.empty()) {
496 llvm::sys::Path Path(InFile);
497 Path.eraseSuffix();
498 Path.appendSuffix(Extension);
499 OutFile = Path.str();
500 } else {
501 OutFile = "-";
502 }
Argyrios Kyrtzidis7e909852011-07-28 00:45:10 +0000503
504 llvm::OwningPtr<llvm::raw_fd_ostream> OS;
505 std::string OSFile;
506
507 if (UseTemporary && OutFile != "-") {
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000508 llvm::sys::Path OutPath(OutFile);
509 // Only create the temporary if we can actually write to OutPath, otherwise
510 // we want to fail early.
Michael J. Spencer32bef4e2011-01-10 02:34:13 +0000511 bool Exists;
512 if ((llvm::sys::fs::exists(OutPath.str(), Exists) || !Exists) ||
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000513 (OutPath.isRegularFile() && OutPath.canWrite())) {
514 // Create a temporary file.
Argyrios Kyrtzidis7e909852011-07-28 00:45:10 +0000515 llvm::SmallString<128> TempPath;
516 TempPath = OutFile;
517 TempPath += "-%%%%%%%%";
518 int fd;
519 if (llvm::sys::fs::unique_file(TempPath.str(), fd, TempPath,
520 /*makeAbsolute=*/false) == llvm::errc::success) {
521 OS.reset(new llvm::raw_fd_ostream(fd, /*shouldClose=*/true));
522 OSFile = TempFile = TempPath.str();
523 }
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000524 }
525 }
526
Argyrios Kyrtzidis7e909852011-07-28 00:45:10 +0000527 if (!OS) {
528 OSFile = OutFile;
529 OS.reset(
530 new llvm::raw_fd_ostream(OSFile.c_str(), Error,
531 (Binary ? llvm::raw_fd_ostream::F_Binary : 0)));
532 if (!Error.empty())
533 return 0;
534 }
Daniel Dunbarf482d592009-11-13 18:32:08 +0000535
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000536 // Make sure the out stream file gets removed if we crash.
Daniel Dunbarff9cd962011-01-31 22:00:42 +0000537 if (RemoveFileOnSignal)
538 llvm::sys::RemoveFileOnSignal(llvm::sys::Path(OSFile));
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000539
Daniel Dunbarf482d592009-11-13 18:32:08 +0000540 if (ResultPathName)
541 *ResultPathName = OutFile;
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000542 if (TempPathName)
543 *TempPathName = TempFile;
Daniel Dunbarf482d592009-11-13 18:32:08 +0000544
Daniel Dunbarfc971022009-11-20 22:32:38 +0000545 return OS.take();
Daniel Dunbarf482d592009-11-13 18:32:08 +0000546}
Daniel Dunbarccb6cb62009-11-14 07:53:04 +0000547
548// Initialization Utilities
549
Chris Lattner5f9e2722011-07-23 10:55:15 +0000550bool CompilerInstance::InitializeSourceManager(StringRef InputFile) {
Daniel Dunbarccb6cb62009-11-14 07:53:04 +0000551 return InitializeSourceManager(InputFile, getDiagnostics(), getFileManager(),
552 getSourceManager(), getFrontendOpts());
553}
554
Chris Lattner5f9e2722011-07-23 10:55:15 +0000555bool CompilerInstance::InitializeSourceManager(StringRef InputFile,
David Blaikied6471f72011-09-25 23:23:43 +0000556 DiagnosticsEngine &Diags,
Daniel Dunbarccb6cb62009-11-14 07:53:04 +0000557 FileManager &FileMgr,
558 SourceManager &SourceMgr,
559 const FrontendOptions &Opts) {
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +0000560 // Figure out where to get and map in the main file.
561 if (InputFile != "-") {
Chris Lattner39b49bc2010-11-23 08:35:12 +0000562 const FileEntry *File = FileMgr.getFile(InputFile);
Dan Gohman694137c2010-10-26 21:13:51 +0000563 if (!File) {
Daniel Dunbarccb6cb62009-11-14 07:53:04 +0000564 Diags.Report(diag::err_fe_error_reading) << InputFile;
565 return false;
566 }
Dan Gohman694137c2010-10-26 21:13:51 +0000567 SourceMgr.createMainFileID(File);
Daniel Dunbarccb6cb62009-11-14 07:53:04 +0000568 } else {
Michael J. Spencer4eeebc42010-12-16 03:28:14 +0000569 llvm::OwningPtr<llvm::MemoryBuffer> SB;
570 if (llvm::MemoryBuffer::getSTDIN(SB)) {
Michael J. Spencer3a321e22010-12-09 17:36:38 +0000571 // FIXME: Give ec.message() in this diag.
Daniel Dunbarccb6cb62009-11-14 07:53:04 +0000572 Diags.Report(diag::err_fe_error_reading_stdin);
573 return false;
574 }
Dan Gohman90d90812010-10-26 23:21:25 +0000575 const FileEntry *File = FileMgr.getVirtualFile(SB->getBufferIdentifier(),
Chris Lattner39b49bc2010-11-23 08:35:12 +0000576 SB->getBufferSize(), 0);
Dan Gohman90d90812010-10-26 23:21:25 +0000577 SourceMgr.createMainFileID(File);
Michael J. Spencer4eeebc42010-12-16 03:28:14 +0000578 SourceMgr.overrideFileContents(File, SB.take());
Daniel Dunbarccb6cb62009-11-14 07:53:04 +0000579 }
580
Dan Gohman694137c2010-10-26 21:13:51 +0000581 assert(!SourceMgr.getMainFileID().isInvalid() &&
582 "Couldn't establish MainFileID!");
Daniel Dunbarccb6cb62009-11-14 07:53:04 +0000583 return true;
584}
Daniel Dunbar0397af22010-01-13 00:48:06 +0000585
586// High-Level Operations
587
588bool CompilerInstance::ExecuteAction(FrontendAction &Act) {
589 assert(hasDiagnostics() && "Diagnostics engine is not initialized!");
590 assert(!getFrontendOpts().ShowHelp && "Client must handle '-help'!");
591 assert(!getFrontendOpts().ShowVersion && "Client must handle '-version'!");
592
593 // FIXME: Take this as an argument, once all the APIs we used have moved to
594 // taking it as an input instead of hard-coding llvm::errs.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000595 raw_ostream &OS = llvm::errs();
Daniel Dunbar0397af22010-01-13 00:48:06 +0000596
597 // Create the target instance.
598 setTarget(TargetInfo::CreateTargetInfo(getDiagnostics(), getTargetOpts()));
599 if (!hasTarget())
600 return false;
601
602 // Inform the target of the language options.
603 //
604 // FIXME: We shouldn't need to do this, the target should be immutable once
605 // created. This complexity should be lifted elsewhere.
606 getTarget().setForcedLangOptions(getLangOpts());
607
608 // Validate/process some options.
609 if (getHeaderSearchOpts().Verbose)
610 OS << "clang -cc1 version " CLANG_VERSION_STRING
611 << " based upon " << PACKAGE_STRING
612 << " hosted on " << llvm::sys::getHostTriple() << "\n";
613
614 if (getFrontendOpts().ShowTimers)
615 createFrontendTimer();
616
Douglas Gregor95dd5582010-03-30 17:33:59 +0000617 if (getFrontendOpts().ShowStats)
618 llvm::EnableStatistics();
619
Daniel Dunbar0397af22010-01-13 00:48:06 +0000620 for (unsigned i = 0, e = getFrontendOpts().Inputs.size(); i != e; ++i) {
621 const std::string &InFile = getFrontendOpts().Inputs[i].second;
622
Daniel Dunbar20560482010-06-07 23:23:50 +0000623 // Reset the ID tables if we are reusing the SourceManager.
624 if (hasSourceManager())
625 getSourceManager().clearIDTables();
Daniel Dunbar0397af22010-01-13 00:48:06 +0000626
Daniel Dunbard3598a62010-06-07 23:23:06 +0000627 if (Act.BeginSourceFile(*this, InFile, getFrontendOpts().Inputs[i].first)) {
Daniel Dunbar0397af22010-01-13 00:48:06 +0000628 Act.Execute();
629 Act.EndSourceFile();
630 }
631 }
632
Chris Lattner53eee7b2010-04-07 18:47:42 +0000633 if (getDiagnosticOpts().ShowCarets) {
Argyrios Kyrtzidisf2224d82010-11-18 20:06:46 +0000634 // We can have multiple diagnostics sharing one diagnostic client.
635 // Get the total number of warnings/errors from the client.
636 unsigned NumWarnings = getDiagnostics().getClient()->getNumWarnings();
637 unsigned NumErrors = getDiagnostics().getClient()->getNumErrors();
Chris Lattner53eee7b2010-04-07 18:47:42 +0000638
639 if (NumWarnings)
640 OS << NumWarnings << " warning" << (NumWarnings == 1 ? "" : "s");
641 if (NumWarnings && NumErrors)
642 OS << " and ";
643 if (NumErrors)
644 OS << NumErrors << " error" << (NumErrors == 1 ? "" : "s");
645 if (NumWarnings || NumErrors)
646 OS << " generated.\n";
647 }
Daniel Dunbar0397af22010-01-13 00:48:06 +0000648
Daniel Dunbar20560482010-06-07 23:23:50 +0000649 if (getFrontendOpts().ShowStats && hasFileManager()) {
Daniel Dunbar0397af22010-01-13 00:48:06 +0000650 getFileManager().PrintStats();
651 OS << "\n";
652 }
653
Argyrios Kyrtzidisab41b972010-11-18 21:13:57 +0000654 return !getDiagnostics().getClient()->getNumErrors();
Daniel Dunbar0397af22010-01-13 00:48:06 +0000655}
656
Douglas Gregor21cae202011-09-12 23:31:24 +0000657/// \brief Determine the appropriate source input kind based on language
658/// options.
659static InputKind getSourceInputKindFromOptions(const LangOptions &LangOpts) {
660 if (LangOpts.OpenCL)
661 return IK_OpenCL;
662 if (LangOpts.CUDA)
663 return IK_CUDA;
664 if (LangOpts.ObjC1)
665 return LangOpts.CPlusPlus? IK_ObjCXX : IK_ObjC;
666 return LangOpts.CPlusPlus? IK_CXX : IK_C;
667}
668
Douglas Gregor0ced7992011-10-04 00:21:21 +0000669namespace {
670 struct CompileModuleData {
671 CompilerInstance &Instance;
672 GeneratePCHAction &CreateModuleAction;
673 };
674}
675
676/// \brief Helper function that executes the module-generating action under
677/// a crash recovery context.
678static void doCompileModule(void *UserData) {
679 CompileModuleData &Data = *reinterpret_cast<CompileModuleData *>(UserData);
680 Data.Instance.ExecuteAction(Data.CreateModuleAction);
681}
682
Douglas Gregor2bc75072011-10-05 14:53:30 +0000683namespace {
684 /// \brief Class that manages the creation of a lock file to aid
685 /// implicit coordination between different processes.
686 ///
687 /// The implicit coordination works by creating a ".lock" file alongside
688 /// the file that we're coordinating for, using the atomicity of the file
689 /// system to ensure that only a single process can create that ".lock" file.
690 /// When the lock file is removed, the owning process has finished the
691 /// operation.
692 class LockFileManager {
693 public:
694 /// \brief Describes the state of a lock file.
695 enum LockFileState {
696 /// \brief The lock file has been created and is owned by this instance
697 /// of the object.
698 LFS_Owned,
699 /// \brief The lock file already exists and is owned by some other
700 /// instance.
701 LFS_Shared,
702 /// \brief An error occurred while trying to create or find the lock
703 /// file.
704 LFS_Error
705 };
706
707 private:
708 llvm::SmallString<128> LockFileName;
709 llvm::SmallString<128> UniqueLockFileName;
710
711 llvm::Optional<std::pair<std::string, int> > Owner;
712 llvm::Optional<llvm::error_code> Error;
713
714 LockFileManager(const LockFileManager &);
715 LockFileManager &operator=(const LockFileManager &);
716
717 static llvm::Optional<std::pair<std::string, int> >
718 readLockFile(StringRef LockFileName);
719
720 static bool processStillExecuting(StringRef Hostname, int PID);
721
722 public:
723
724 LockFileManager(StringRef FileName);
725 ~LockFileManager();
726
727 /// \brief Determine the state of the lock file.
728 LockFileState getState() const;
729
730 operator LockFileState() const { return getState(); }
731
732 /// \brief For a shared lock, wait until the owner releases the lock.
733 void waitForUnlock();
734 };
735}
736
737/// \brief Attempt to read the lock file with the given name, if it exists.
738///
739/// \param LockFileName The name of the lock file to read.
740///
741/// \returns The process ID of the process that owns this lock file
742llvm::Optional<std::pair<std::string, int> >
743LockFileManager::readLockFile(StringRef LockFileName) {
744 // Check whether the lock file exists. If not, clearly there's nothing
745 // to read, so we just return.
746 bool Exists = false;
747 if (llvm::sys::fs::exists(LockFileName, Exists) || !Exists)
748 return llvm::Optional<std::pair<std::string, int> >();
749
750 // Read the owning host and PID out of the lock file. If it appears that the
751 // owning process is dead, the lock file is invalid.
752 int PID = 0;
753 std::string Hostname;
754 std::ifstream Input(LockFileName.str().c_str());
755 if (Input >> Hostname >> PID && PID > 0 &&
756 processStillExecuting(Hostname, PID))
757 return std::make_pair(Hostname, PID);
758
759 // Delete the lock file. It's invalid anyway.
760 bool Existed;
761 llvm::sys::fs::remove(LockFileName, Existed);
762 return llvm::Optional<std::pair<std::string, int> >();
763}
764
765bool LockFileManager::processStillExecuting(StringRef Hostname, int PID) {
766#if LLVM_ON_UNIX
767 char MyHostname[256];
768 MyHostname[255] = 0;
769 MyHostname[0] = 0;
770 gethostname(MyHostname, 255);
771 // Check whether the process is dead. If so, we're done.
772 if (MyHostname == Hostname && getsid(PID) == -1 && errno == ESRCH)
773 return false;
774#endif
775
776 return true;
777}
778
779LockFileManager::LockFileManager(StringRef FileName)
780{
781 LockFileName = FileName;
782 LockFileName += ".lock";
783
784 // If the lock file already exists, don't bother to try to create our own
785 // lock file; it won't work anyway. Just figure out who owns this lock file.
786 if ((Owner = readLockFile(LockFileName)))
787 return;
788
789 // Create a lock file that is unique to this instance.
790 UniqueLockFileName = LockFileName;
791 UniqueLockFileName += "-%%%%%%%%";
792 int UniqueLockFileID;
793 if (llvm::error_code EC
794 = llvm::sys::fs::unique_file(UniqueLockFileName.str(),
795 UniqueLockFileID,
796 UniqueLockFileName,
797 /*makeAbsolute=*/false)) {
798 Error = EC;
799 return;
800 }
801
802 // Write our process ID to our unique lock file.
803 {
804 llvm::raw_fd_ostream Out(UniqueLockFileID, /*shouldClose=*/true);
805
806#if LLVM_ON_UNIX
807 // FIXME: move getpid() call into LLVM
808 char hostname[256];
809 hostname[255] = 0;
810 hostname[0] = 0;
811 gethostname(hostname, 255);
812 Out << hostname << ' ' << getpid();
813#else
814 Out << "localhost 1";
815#endif
816 Out.close();
817
818 if (Out.has_error()) {
819 // We failed to write out PID, so make up an excuse, remove the
820 // unique lock file, and fail.
821 Error = llvm::make_error_code(llvm::errc::no_space_on_device);
822 bool Existed;
823 llvm::sys::fs::remove(UniqueLockFileName.c_str(), Existed);
824 return;
825 }
826 }
827
828 // Create a hard link from the lock file name. If this succeeds, we're done.
829 llvm::error_code EC
830 = llvm::sys::fs::create_hard_link(UniqueLockFileName.str(),
831 LockFileName.str());
832 if (EC == llvm::errc::success)
833 return;
834
835 // Creating the hard link failed.
836
837#ifdef LLVM_ON_UNIX
838 // The creation of the hard link may appear to fail, but if stat'ing the
839 // unique file returns a link count of 2, then we can still declare success.
840 struct stat StatBuf;
841 if (stat(UniqueLockFileName.c_str(), &StatBuf) == 0 &&
842 StatBuf.st_nlink == 2)
843 return;
844#endif
845
846 // Someone else managed to create the lock file first. Wipe out our unique
847 // lock file (it's useless now) and read the process ID from the lock file.
848 bool Existed;
849 llvm::sys::fs::remove(UniqueLockFileName.str(), Existed);
850 if ((Owner = readLockFile(LockFileName)))
851 return;
852
853 // There is a lock file that nobody owns; try to clean it up and report
854 // an error.
855 llvm::sys::fs::remove(LockFileName.str(), Existed);
856 Error = EC;
857}
858
859LockFileManager::LockFileState LockFileManager::getState() const {
860 if (Owner)
861 return LFS_Shared;
862
863 if (Error)
864 return LFS_Error;
865
866 return LFS_Owned;
867}
868
869LockFileManager::~LockFileManager() {
870 if (getState() != LFS_Owned)
871 return;
872
873 // Since we own the lock, remove the lock file and our own unique lock file.
874 bool Existed;
875 llvm::sys::fs::remove(LockFileName.str(), Existed);
876 llvm::sys::fs::remove(UniqueLockFileName.str(), Existed);
877}
878
879void LockFileManager::waitForUnlock() {
880 if (getState() != LFS_Shared)
881 return;
882
Douglas Gregor1872e792011-10-05 14:58:46 +0000883#if LLVM_ON_WIN32
884 unsigned long Interval = 1;
885#else
Douglas Gregor2bc75072011-10-05 14:53:30 +0000886 struct timespec Interval;
887 Interval.tv_sec = 0;
888 Interval.tv_nsec = 1000000;
Douglas Gregor1872e792011-10-05 14:58:46 +0000889#endif
Douglas Gregor2bc75072011-10-05 14:53:30 +0000890 // Don't wait more than an hour for the file to appear.
891 const unsigned MaxSeconds = 3600;
892 do {
893 // Sleep for the designated interval, to allow the owning process time to
894 // finish up and
895 // FIXME: Should we hook in to system APIs to get a notification when the
896 // lock file is deleted?
897 nanosleep(&Interval, NULL);
898
899 // If the file no longer exists, we're done.
900 bool Exists = false;
901 if (!llvm::sys::fs::exists(LockFileName.str(), Exists) && !Exists)
902 return;
903
904 if (!processStillExecuting((*Owner).first, (*Owner).second))
905 return;
906
907 // Exponentially increase the time we wait for the lock to be removed.
Douglas Gregor1872e792011-10-05 14:58:46 +0000908#if LLVM_ON_WIN32
909 Interval *= 2;
910#else
Douglas Gregor2bc75072011-10-05 14:53:30 +0000911 Interval.tv_sec *= 2;
912 Interval.tv_nsec *= 2;
913 if (Interval.tv_nsec >= 1000000000) {
914 ++Interval.tv_sec;
915 Interval.tv_nsec -= 1000000000;
916 }
Douglas Gregor1872e792011-10-05 14:58:46 +0000917#endif
918 } while (
919#if LLVM_ON_WIN32
920 Interval < MaxSeconds * 1000
921#else
922 Interval.tv_sec < MaxSeconds
923#endif
924 );
Douglas Gregor2bc75072011-10-05 14:53:30 +0000925
926 // Give up.
927}
928
Douglas Gregor21cae202011-09-12 23:31:24 +0000929/// \brief Compile a module file for the given module name with the given
930/// umbrella header, using the options provided by the importing compiler
931/// instance.
932static void compileModule(CompilerInstance &ImportingInstance,
933 StringRef ModuleName,
Douglas Gregor6e975c42011-09-13 23:15:45 +0000934 StringRef ModuleFileName,
Douglas Gregor21cae202011-09-12 23:31:24 +0000935 StringRef UmbrellaHeader) {
Douglas Gregor2bc75072011-10-05 14:53:30 +0000936 LockFileManager Locked(ModuleFileName);
937 switch (Locked) {
938 case LockFileManager::LFS_Error:
939 return;
940
941 case LockFileManager::LFS_Owned:
942 // We're responsible for building the module ourselves. Do so below.
943 break;
944
945 case LockFileManager::LFS_Shared:
946 // Someone else is responsible for building the module. Wait for them to
947 // finish.
948 Locked.waitForUnlock();
949 break;
950 }
951
Douglas Gregor21cae202011-09-12 23:31:24 +0000952 // Construct a compiler invocation for creating this module.
953 llvm::IntrusiveRefCntPtr<CompilerInvocation> Invocation
954 (new CompilerInvocation(ImportingInstance.getInvocation()));
Douglas Gregorb2d39c22011-09-15 20:53:28 +0000955
956 // For any options that aren't intended to affect how a module is built,
957 // reset them to their default values.
Douglas Gregor1c7e0472011-09-13 20:44:41 +0000958 Invocation->getLangOpts().resetNonModularOptions();
959 Invocation->getPreprocessorOpts().resetNonModularOptions();
Douglas Gregorb2d39c22011-09-15 20:53:28 +0000960
961 // Note that this module is part of the module build path, so that we
962 // can detect cycles in the module graph.
Douglas Gregor4ebd45f2011-09-15 20:40:10 +0000963 Invocation->getPreprocessorOpts().ModuleBuildPath.push_back(ModuleName);
Douglas Gregor1c7e0472011-09-13 20:44:41 +0000964
Douglas Gregorb2d39c22011-09-15 20:53:28 +0000965 // Set up the inputs/outputs so that we build the module from its umbrella
966 // header.
Douglas Gregor21cae202011-09-12 23:31:24 +0000967 FrontendOptions &FrontendOpts = Invocation->getFrontendOpts();
Douglas Gregor6e975c42011-09-13 23:15:45 +0000968 FrontendOpts.OutputFile = ModuleFileName.str();
Douglas Gregor21cae202011-09-12 23:31:24 +0000969 FrontendOpts.DisableFree = false;
970 FrontendOpts.Inputs.clear();
971 FrontendOpts.Inputs.push_back(
972 std::make_pair(getSourceInputKindFromOptions(Invocation->getLangOpts()),
973 UmbrellaHeader));
Douglas Gregor78243652011-09-13 01:26:44 +0000974
975 Invocation->getDiagnosticOpts().VerifyDiagnostics = 0;
976
Douglas Gregor4ebd45f2011-09-15 20:40:10 +0000977
Douglas Gregor76d991e2011-09-13 23:20:27 +0000978 assert(ImportingInstance.getInvocation().getModuleHash() ==
979 Invocation->getModuleHash() && "Module hash mismatch!");
Douglas Gregor21cae202011-09-12 23:31:24 +0000980
981 // Construct a compiler instance that will be used to actually create the
982 // module.
983 CompilerInstance Instance;
984 Instance.setInvocation(&*Invocation);
Douglas Gregor78243652011-09-13 01:26:44 +0000985 Instance.createDiagnostics(/*argc=*/0, /*argv=*/0,
986 &ImportingInstance.getDiagnosticClient(),
Douglas Gregoraee526e2011-09-29 00:38:00 +0000987 /*ShouldOwnClient=*/true,
988 /*ShouldCloneClient=*/true);
Douglas Gregor21cae202011-09-12 23:31:24 +0000989
990 // Construct a module-generating action.
991 GeneratePCHAction CreateModuleAction(true);
992
Douglas Gregor0ced7992011-10-04 00:21:21 +0000993 // Execute the action to actually build the module in-place. Use a separate
994 // thread so that we get a stack large enough.
995 const unsigned ThreadStackSize = 8 << 20;
996 llvm::CrashRecoveryContext CRC;
997 CompileModuleData Data = { Instance, CreateModuleAction };
998 CRC.RunSafelyOnThread(&doCompileModule, &Data, ThreadStackSize);
Douglas Gregor78243652011-09-13 01:26:44 +0000999}
Douglas Gregor21cae202011-09-12 23:31:24 +00001000
Douglas Gregor6aa52ec2011-08-26 23:56:07 +00001001ModuleKey CompilerInstance::loadModule(SourceLocation ImportLoc,
1002 IdentifierInfo &ModuleName,
1003 SourceLocation ModuleNameLoc) {
1004 // Determine what file we're searching from.
1005 SourceManager &SourceMgr = getSourceManager();
1006 SourceLocation ExpandedImportLoc = SourceMgr.getExpansionLoc(ImportLoc);
1007 const FileEntry *CurFile
1008 = SourceMgr.getFileEntryForID(SourceMgr.getFileID(ExpandedImportLoc));
1009 if (!CurFile)
1010 CurFile = SourceMgr.getFileEntryForID(SourceMgr.getMainFileID());
1011
1012 // Search for a module with the given name.
Douglas Gregor21cae202011-09-12 23:31:24 +00001013 std::string UmbrellaHeader;
Douglas Gregor6e975c42011-09-13 23:15:45 +00001014 std::string ModuleFileName;
Douglas Gregor6aa52ec2011-08-26 23:56:07 +00001015 const FileEntry *ModuleFile
Douglas Gregor21cae202011-09-12 23:31:24 +00001016 = PP->getHeaderSearchInfo().lookupModule(ModuleName.getName(),
Douglas Gregor6e975c42011-09-13 23:15:45 +00001017 &ModuleFileName,
Douglas Gregor21cae202011-09-12 23:31:24 +00001018 &UmbrellaHeader);
1019
1020 bool BuildingModule = false;
1021 if (!ModuleFile && !UmbrellaHeader.empty()) {
1022 // We didn't find the module, but there is an umbrella header that
1023 // can be used to create the module file. Create a separate compilation
1024 // module to do so.
Douglas Gregor4ebd45f2011-09-15 20:40:10 +00001025
1026 // Check whether there is a cycle in the module graph.
1027 SmallVectorImpl<std::string> &ModuleBuildPath
1028 = getPreprocessorOpts().ModuleBuildPath;
1029 SmallVectorImpl<std::string>::iterator Pos
1030 = std::find(ModuleBuildPath.begin(), ModuleBuildPath.end(),
1031 ModuleName.getName());
1032 if (Pos != ModuleBuildPath.end()) {
1033 llvm::SmallString<256> CyclePath;
1034 for (; Pos != ModuleBuildPath.end(); ++Pos) {
1035 CyclePath += *Pos;
1036 CyclePath += " -> ";
1037 }
1038 CyclePath += ModuleName.getName();
1039
1040 getDiagnostics().Report(ModuleNameLoc, diag::err_module_cycle)
1041 << ModuleName.getName() << CyclePath;
1042 return 0;
1043 }
1044
Douglas Gregor08d6acf2011-09-29 00:52:27 +00001045 getDiagnostics().Report(ModuleNameLoc, diag::warn_module_build)
1046 << ModuleName.getName();
Douglas Gregor21cae202011-09-12 23:31:24 +00001047 BuildingModule = true;
Douglas Gregor6e975c42011-09-13 23:15:45 +00001048 compileModule(*this, ModuleName.getName(), ModuleFileName, UmbrellaHeader);
Douglas Gregor21cae202011-09-12 23:31:24 +00001049 ModuleFile = PP->getHeaderSearchInfo().lookupModule(ModuleName.getName());
1050 }
1051
Douglas Gregor6aa52ec2011-08-26 23:56:07 +00001052 if (!ModuleFile) {
Douglas Gregor21cae202011-09-12 23:31:24 +00001053 getDiagnostics().Report(ModuleNameLoc,
1054 BuildingModule? diag::err_module_not_built
1055 : diag::err_module_not_found)
Douglas Gregor6aa52ec2011-08-26 23:56:07 +00001056 << ModuleName.getName()
1057 << SourceRange(ImportLoc, ModuleNameLoc);
1058 return 0;
1059 }
1060
1061 // If we don't already have an ASTReader, create one now.
1062 if (!ModuleManager) {
Douglas Gregorde8a9052011-09-14 23:13:09 +00001063 if (!hasASTContext())
1064 createASTContext();
1065
Douglas Gregor6aa52ec2011-08-26 23:56:07 +00001066 std::string Sysroot = getHeaderSearchOpts().Sysroot;
1067 const PreprocessorOptions &PPOpts = getPreprocessorOpts();
Douglas Gregorf8a1e512011-09-02 00:26:20 +00001068 ModuleManager = new ASTReader(getPreprocessor(), *Context,
Douglas Gregor6aa52ec2011-08-26 23:56:07 +00001069 Sysroot.empty() ? "" : Sysroot.c_str(),
1070 PPOpts.DisablePCHValidation,
1071 PPOpts.DisableStatCache);
Douglas Gregorde8a9052011-09-14 23:13:09 +00001072 if (hasASTConsumer()) {
1073 ModuleManager->setDeserializationListener(
1074 getASTConsumer().GetASTDeserializationListener());
1075 getASTContext().setASTMutationListener(
1076 getASTConsumer().GetASTMutationListener());
1077 }
Douglas Gregor6aa52ec2011-08-26 23:56:07 +00001078 llvm::OwningPtr<ExternalASTSource> Source;
1079 Source.reset(ModuleManager);
1080 getASTContext().setExternalSource(Source);
Douglas Gregorde8a9052011-09-14 23:13:09 +00001081 if (hasSema())
1082 ModuleManager->InitializeSema(getSema());
Douglas Gregor1a995dd2011-09-15 18:47:32 +00001083 if (hasASTConsumer())
1084 ModuleManager->StartTranslationUnit(&getASTConsumer());
Douglas Gregor6aa52ec2011-08-26 23:56:07 +00001085 }
1086
1087 // Try to load the module we found.
1088 switch (ModuleManager->ReadAST(ModuleFile->getName(),
1089 serialization::MK_Module)) {
1090 case ASTReader::Success:
1091 break;
1092
1093 case ASTReader::IgnorePCH:
1094 // FIXME: The ASTReader will already have complained, but can we showhorn
1095 // that diagnostic information into a more useful form?
1096 return 0;
1097
1098 case ASTReader::Failure:
1099 // Already complained.
1100 return 0;
1101 }
1102
1103 // FIXME: The module file's FileEntry makes a poor key indeed!
1104 return (ModuleKey)ModuleFile;
1105}
Daniel Dunbar0397af22010-01-13 00:48:06 +00001106