blob: b8075ed87a3da2fa75073196bfed3b800dcbf144 [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"
Douglas Gregor93ebfa62011-12-02 23:42:12 +000014#include "clang/AST/Decl.h"
Daniel Dunbar2a79e162009-11-13 03:51:44 +000015#include "clang/Basic/Diagnostic.h"
Daniel Dunbar16b74492009-11-13 04:12:06 +000016#include "clang/Basic/FileManager.h"
17#include "clang/Basic/SourceManager.h"
Daniel Dunbar2a79e162009-11-13 03:51:44 +000018#include "clang/Basic/TargetInfo.h"
Daniel Dunbar0397af22010-01-13 00:48:06 +000019#include "clang/Basic/Version.h"
Daniel Dunbar22dacfa2009-11-13 05:52:11 +000020#include "clang/Lex/HeaderSearch.h"
21#include "clang/Lex/Preprocessor.h"
22#include "clang/Lex/PTHManager.h"
David Blaikie4e85b8a2011-09-26 00:21:47 +000023#include "clang/Frontend/ChainedDiagnosticConsumer.h"
Daniel Dunbar0397af22010-01-13 00:48:06 +000024#include "clang/Frontend/FrontendAction.h"
Douglas Gregor21cae202011-09-12 23:31:24 +000025#include "clang/Frontend/FrontendActions.h"
Daniel Dunbarc2f484f2009-11-13 09:36:05 +000026#include "clang/Frontend/FrontendDiagnostic.h"
Daniel Dunbar9df23492011-04-07 18:31:10 +000027#include "clang/Frontend/LogDiagnosticPrinter.h"
Ted Kremenek78002122011-10-29 00:12:39 +000028#include "clang/Frontend/SerializedDiagnosticPrinter.h"
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +000029#include "clang/Frontend/TextDiagnosticPrinter.h"
David Blaikie621bc692011-09-26 00:38:03 +000030#include "clang/Frontend/VerifyDiagnosticConsumer.h"
Daniel Dunbar22dacfa2009-11-13 05:52:11 +000031#include "clang/Frontend/Utils.h"
Sebastian Redl6ab7cd82010-08-18 23:57:17 +000032#include "clang/Serialization/ASTReader.h"
Daniel Dunbarc2f484f2009-11-13 09:36:05 +000033#include "clang/Sema/CodeCompleteConsumer.h"
Michael J. Spencer32bef4e2011-01-10 02:34:13 +000034#include "llvm/Support/FileSystem.h"
Daniel Dunbarccb6cb62009-11-14 07:53:04 +000035#include "llvm/Support/MemoryBuffer.h"
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +000036#include "llvm/Support/raw_ostream.h"
Douglas Gregor95dd5582010-03-30 17:33:59 +000037#include "llvm/ADT/Statistic.h"
Kovarththanan Rajaratnamf79bafa2009-11-29 09:57:35 +000038#include "llvm/Support/Timer.h"
Michael J. Spencer03013fa2010-11-29 18:12:39 +000039#include "llvm/Support/Host.h"
40#include "llvm/Support/Path.h"
41#include "llvm/Support/Program.h"
42#include "llvm/Support/Signals.h"
Michael J. Spencer3a321e22010-12-09 17:36:38 +000043#include "llvm/Support/system_error.h"
Douglas Gregor0ced7992011-10-04 00:21:21 +000044#include "llvm/Support/CrashRecoveryContext.h"
Dylan Noblesmith16266012011-06-23 12:20:57 +000045#include "llvm/Config/config.h"
Douglas Gregor2bc75072011-10-05 14:53:30 +000046
47// Support for FileLockManager
48#include <fstream>
49#include <sys/types.h>
50#include <sys/stat.h>
51
Douglas Gregor25728492011-10-05 14:59:36 +000052#if LLVM_ON_WIN32
53#include <windows.h>
54#endif
Douglas Gregor2bc75072011-10-05 14:53:30 +000055#if LLVM_ON_UNIX
56#include <unistd.h>
57#endif
58
Daniel Dunbar2a79e162009-11-13 03:51:44 +000059using namespace clang;
60
Daniel Dunbar42e9f8e42010-02-16 01:54:47 +000061CompilerInstance::CompilerInstance()
Douglas Gregorf62d43d2011-07-19 16:10:42 +000062 : Invocation(new CompilerInvocation()), ModuleManager(0) {
Daniel Dunbar6228ca02010-01-30 21:47:07 +000063}
Daniel Dunbar2a79e162009-11-13 03:51:44 +000064
65CompilerInstance::~CompilerInstance() {
Daniel Dunbar42e9f8e42010-02-16 01:54:47 +000066}
67
Daniel Dunbar6228ca02010-01-30 21:47:07 +000068void CompilerInstance::setInvocation(CompilerInvocation *Value) {
Ted Kremenek4f327862011-03-21 18:40:17 +000069 Invocation = Value;
Daniel Dunbar6228ca02010-01-30 21:47:07 +000070}
71
David Blaikied6471f72011-09-25 23:23:43 +000072void CompilerInstance::setDiagnostics(DiagnosticsEngine *Value) {
Douglas Gregor28019772010-04-05 23:52:57 +000073 Diagnostics = Value;
Daniel Dunbar8a9f5692009-11-14 01:20:40 +000074}
75
Daniel Dunbar8a9f5692009-11-14 01:20:40 +000076void CompilerInstance::setTarget(TargetInfo *Value) {
Ted Kremenek4f327862011-03-21 18:40:17 +000077 Target = Value;
Daniel Dunbar8a9f5692009-11-14 01:20:40 +000078}
79
80void CompilerInstance::setFileManager(FileManager *Value) {
Ted Kremenek4f327862011-03-21 18:40:17 +000081 FileMgr = Value;
Daniel Dunbar8a9f5692009-11-14 01:20:40 +000082}
83
NAKAMURA Takumia789ca92011-10-08 11:31:46 +000084void CompilerInstance::setSourceManager(SourceManager *Value) {
Ted Kremenek4f327862011-03-21 18:40:17 +000085 SourceMgr = Value;
Daniel Dunbar8a9f5692009-11-14 01:20:40 +000086}
87
Ted Kremenek4f327862011-03-21 18:40:17 +000088void CompilerInstance::setPreprocessor(Preprocessor *Value) { PP = Value; }
Daniel Dunbar8a9f5692009-11-14 01:20:40 +000089
Ted Kremenek4f327862011-03-21 18:40:17 +000090void CompilerInstance::setASTContext(ASTContext *Value) { Context = Value; }
Daniel Dunbar8a9f5692009-11-14 01:20:40 +000091
Douglas Gregorf18d0d82010-08-12 23:31:19 +000092void CompilerInstance::setSema(Sema *S) {
93 TheSema.reset(S);
94}
95
Daniel Dunbar12ce6942009-11-14 02:47:17 +000096void CompilerInstance::setASTConsumer(ASTConsumer *Value) {
97 Consumer.reset(Value);
98}
99
Daniel Dunbar8a9f5692009-11-14 01:20:40 +0000100void CompilerInstance::setCodeCompletionConsumer(CodeCompleteConsumer *Value) {
101 CompletionConsumer.reset(Value);
102}
103
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000104// Diagnostics
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000105static void SetUpBuildDumpLog(const DiagnosticOptions &DiagOpts,
Axel Naumann7d0c4cc2010-10-11 09:13:46 +0000106 unsigned argc, const char* const *argv,
David Blaikied6471f72011-09-25 23:23:43 +0000107 DiagnosticsEngine &Diags) {
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000108 std::string ErrorInfo;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000109 llvm::OwningPtr<raw_ostream> OS(
Kovarththanan Rajaratnam69247132010-03-17 09:47:30 +0000110 new llvm::raw_fd_ostream(DiagOpts.DumpBuildInformation.c_str(), ErrorInfo));
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000111 if (!ErrorInfo.empty()) {
Kovarththanan Rajaratnam3d67b1e2010-03-17 09:24:48 +0000112 Diags.Report(diag::err_fe_unable_to_open_logfile)
113 << DiagOpts.DumpBuildInformation << ErrorInfo;
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000114 return;
115 }
116
Daniel Dunbardd63b282009-12-11 23:04:35 +0000117 (*OS) << "clang -cc1 command line arguments: ";
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000118 for (unsigned i = 0; i != argc; ++i)
119 (*OS) << argv[i] << ' ';
120 (*OS) << '\n';
121
122 // Chain in a diagnostic client which will log the diagnostics.
David Blaikie78ad0b92011-09-25 23:39:51 +0000123 DiagnosticConsumer *Logger =
Kovarththanan Rajaratnam69247132010-03-17 09:47:30 +0000124 new TextDiagnosticPrinter(*OS.take(), DiagOpts, /*OwnsOutputStream=*/true);
David Blaikie4e85b8a2011-09-26 00:21:47 +0000125 Diags.setClient(new ChainedDiagnosticConsumer(Diags.takeClient(), Logger));
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000126}
127
Daniel Dunbar9df23492011-04-07 18:31:10 +0000128static void SetUpDiagnosticLog(const DiagnosticOptions &DiagOpts,
Daniel Dunbarb6534bb2011-04-07 18:59:02 +0000129 const CodeGenOptions *CodeGenOpts,
David Blaikied6471f72011-09-25 23:23:43 +0000130 DiagnosticsEngine &Diags) {
Daniel Dunbar9df23492011-04-07 18:31:10 +0000131 std::string ErrorInfo;
132 bool OwnsStream = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000133 raw_ostream *OS = &llvm::errs();
Daniel Dunbar9df23492011-04-07 18:31:10 +0000134 if (DiagOpts.DiagnosticLogFile != "-") {
135 // Create the output stream.
136 llvm::raw_fd_ostream *FileOS(
137 new llvm::raw_fd_ostream(DiagOpts.DiagnosticLogFile.c_str(),
Daniel Dunbare01eceb2011-04-07 20:19:21 +0000138 ErrorInfo, llvm::raw_fd_ostream::F_Append));
Daniel Dunbar9df23492011-04-07 18:31:10 +0000139 if (!ErrorInfo.empty()) {
140 Diags.Report(diag::warn_fe_cc_log_diagnostics_failure)
141 << DiagOpts.DumpBuildInformation << ErrorInfo;
142 } else {
143 FileOS->SetUnbuffered();
144 FileOS->SetUseAtomicWrites(true);
145 OS = FileOS;
146 OwnsStream = true;
147 }
148 }
149
150 // Chain in the diagnostic client which will log the diagnostics.
Daniel Dunbarb6534bb2011-04-07 18:59:02 +0000151 LogDiagnosticPrinter *Logger = new LogDiagnosticPrinter(*OS, DiagOpts,
152 OwnsStream);
153 if (CodeGenOpts)
154 Logger->setDwarfDebugFlags(CodeGenOpts->DwarfDebugFlags);
David Blaikie4e85b8a2011-09-26 00:21:47 +0000155 Diags.setClient(new ChainedDiagnosticConsumer(Diags.takeClient(), Logger));
Daniel Dunbar9df23492011-04-07 18:31:10 +0000156}
157
Ted Kremenek78002122011-10-29 00:12:39 +0000158static void SetupSerializedDiagnostics(const DiagnosticOptions &DiagOpts,
159 DiagnosticsEngine &Diags,
160 StringRef OutputFile) {
161 std::string ErrorInfo;
162 llvm::OwningPtr<llvm::raw_fd_ostream> OS;
163 OS.reset(new llvm::raw_fd_ostream(OutputFile.str().c_str(), ErrorInfo,
164 llvm::raw_fd_ostream::F_Binary));
165
166 if (!ErrorInfo.empty()) {
167 Diags.Report(diag::warn_fe_serialized_diag_failure)
168 << OutputFile << ErrorInfo;
169 return;
170 }
171
172 DiagnosticConsumer *SerializedConsumer =
Ted Kremenek2a764102011-12-17 05:26:11 +0000173 clang::serialized_diags::create(OS.take(), DiagOpts);
Ted Kremenek78002122011-10-29 00:12:39 +0000174
175
176 Diags.setClient(new ChainedDiagnosticConsumer(Diags.takeClient(),
177 SerializedConsumer));
178}
179
Douglas Gregore47be3e2010-11-11 00:39:14 +0000180void CompilerInstance::createDiagnostics(int Argc, const char* const *Argv,
David Blaikie78ad0b92011-09-25 23:39:51 +0000181 DiagnosticConsumer *Client,
Douglas Gregoraee526e2011-09-29 00:38:00 +0000182 bool ShouldOwnClient,
183 bool ShouldCloneClient) {
Daniel Dunbarb6534bb2011-04-07 18:59:02 +0000184 Diagnostics = createDiagnostics(getDiagnosticOpts(), Argc, Argv, Client,
Douglas Gregoraee526e2011-09-29 00:38:00 +0000185 ShouldOwnClient, ShouldCloneClient,
186 &getCodeGenOpts());
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000187}
188
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000189llvm::IntrusiveRefCntPtr<DiagnosticsEngine>
Douglas Gregor28019772010-04-05 23:52:57 +0000190CompilerInstance::createDiagnostics(const DiagnosticOptions &Opts,
Douglas Gregore47be3e2010-11-11 00:39:14 +0000191 int Argc, const char* const *Argv,
David Blaikie78ad0b92011-09-25 23:39:51 +0000192 DiagnosticConsumer *Client,
Douglas Gregor78243652011-09-13 01:26:44 +0000193 bool ShouldOwnClient,
Douglas Gregoraee526e2011-09-29 00:38:00 +0000194 bool ShouldCloneClient,
Daniel Dunbarb6534bb2011-04-07 18:59:02 +0000195 const CodeGenOptions *CodeGenOpts) {
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000196 llvm::IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
David Blaikied6471f72011-09-25 23:23:43 +0000197 llvm::IntrusiveRefCntPtr<DiagnosticsEngine>
198 Diags(new DiagnosticsEngine(DiagID));
Daniel Dunbar221c7212009-11-14 07:53:24 +0000199
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000200 // Create the diagnostic client for reporting errors or for
201 // implementing -verify.
Douglas Gregoraee526e2011-09-29 00:38:00 +0000202 if (Client) {
203 if (ShouldCloneClient)
204 Diags->setClient(Client->clone(*Diags), ShouldOwnClient);
205 else
206 Diags->setClient(Client, ShouldOwnClient);
207 } else
Douglas Gregore47be3e2010-11-11 00:39:14 +0000208 Diags->setClient(new TextDiagnosticPrinter(llvm::errs(), Opts));
Daniel Dunbarf79dced2009-11-14 03:24:39 +0000209
210 // Chain in -verify checker, if requested.
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000211 if (Opts.VerifyDiagnostics)
David Blaikie621bc692011-09-26 00:38:03 +0000212 Diags->setClient(new VerifyDiagnosticConsumer(*Diags));
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000213
Daniel Dunbar9df23492011-04-07 18:31:10 +0000214 // Chain in -diagnostic-log-file dumper, if requested.
215 if (!Opts.DiagnosticLogFile.empty())
Daniel Dunbarb6534bb2011-04-07 18:59:02 +0000216 SetUpDiagnosticLog(Opts, CodeGenOpts, *Diags);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000217
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000218 if (!Opts.DumpBuildInformation.empty())
Kovarththanan Rajaratnam3d67b1e2010-03-17 09:24:48 +0000219 SetUpBuildDumpLog(Opts, Argc, Argv, *Diags);
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000220
Ted Kremenek78002122011-10-29 00:12:39 +0000221 if (!Opts.DiagnosticSerializationFile.empty())
222 SetupSerializedDiagnostics(Opts, *Diags,
223 Opts.DiagnosticSerializationFile);
224
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000225 // Configure our handling of diagnostics.
Kovarththanan Rajaratnam5bf932b2010-03-17 09:36:02 +0000226 ProcessWarningOptions(*Diags, Opts);
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000227
Douglas Gregor28019772010-04-05 23:52:57 +0000228 return Diags;
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000229}
230
231// File Manager
232
Daniel Dunbar16b74492009-11-13 04:12:06 +0000233void CompilerInstance::createFileManager() {
Ted Kremenek4f327862011-03-21 18:40:17 +0000234 FileMgr = new FileManager(getFileSystemOpts());
Daniel Dunbar16b74492009-11-13 04:12:06 +0000235}
236
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000237// Source Manager
238
Chris Lattner39b49bc2010-11-23 08:35:12 +0000239void CompilerInstance::createSourceManager(FileManager &FileMgr) {
Ted Kremenek4f327862011-03-21 18:40:17 +0000240 SourceMgr = new SourceManager(getDiagnostics(), FileMgr);
Daniel Dunbar16b74492009-11-13 04:12:06 +0000241}
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000242
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000243// Preprocessor
244
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000245void CompilerInstance::createPreprocessor() {
Douglas Gregor6aa52ec2011-08-26 23:56:07 +0000246 const PreprocessorOptions &PPOpts = getPreprocessorOpts();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000247
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000248 // Create a PTH manager if we are using some form of a token cache.
249 PTHManager *PTHMgr = 0;
Daniel Dunbar049d3a02009-11-17 05:52:41 +0000250 if (!PPOpts.TokenCache.empty())
Douglas Gregor6aa52ec2011-08-26 23:56:07 +0000251 PTHMgr = PTHManager::Create(PPOpts.TokenCache, getDiagnostics());
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000252
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000253 // Create the Preprocessor.
Douglas Gregor8e238062011-11-11 00:35:06 +0000254 HeaderSearch *HeaderInfo = new HeaderSearch(getFileManager(),
Douglas Gregor51f564f2011-12-31 04:05:44 +0000255 getDiagnostics(),
256 getLangOpts());
Douglas Gregor998b3d32011-09-01 23:39:15 +0000257 PP = new Preprocessor(getDiagnostics(), getLangOpts(), &getTarget(),
Douglas Gregor6aa52ec2011-08-26 23:56:07 +0000258 getSourceManager(), *HeaderInfo, *this, PTHMgr,
259 /*OwnsHeaderSearch=*/true);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000260
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000261 // Note that this is different then passing PTHMgr to Preprocessor's ctor.
262 // That argument is used as the IdentifierInfoLookup argument to
263 // IdentifierTable's ctor.
264 if (PTHMgr) {
Douglas Gregor6aa52ec2011-08-26 23:56:07 +0000265 PTHMgr->setPreprocessor(&*PP);
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000266 PP->setPTHManager(PTHMgr);
267 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000268
Douglas Gregor94dc8f62010-03-19 16:15:56 +0000269 if (PPOpts.DetailedRecord)
Douglas Gregordca8ee82011-05-06 16:33:08 +0000270 PP->createPreprocessingRecord(
Douglas Gregor6aa52ec2011-08-26 23:56:07 +0000271 PPOpts.DetailedRecordIncludesNestedMacroExpansions);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000272
Douglas Gregor6aa52ec2011-08-26 23:56:07 +0000273 InitializePreprocessor(*PP, PPOpts, getHeaderSearchOpts(), getFrontendOpts());
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000274
Douglas Gregor6e975c42011-09-13 23:15:45 +0000275 // Set up the module path, including the hash for the
276 // module-creation options.
277 llvm::SmallString<256> SpecificModuleCache(
278 getHeaderSearchOpts().ModuleCachePath);
279 if (!getHeaderSearchOpts().DisableModuleHash)
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000280 llvm::sys::path::append(SpecificModuleCache,
Douglas Gregor6e975c42011-09-13 23:15:45 +0000281 getInvocation().getModuleHash());
Douglas Gregor5e3f9222011-12-08 17:01:29 +0000282 PP->getHeaderSearchInfo().setModuleCachePath(SpecificModuleCache);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000283
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000284 // Handle generating dependencies, if requested.
Douglas Gregor6aa52ec2011-08-26 23:56:07 +0000285 const DependencyOutputOptions &DepOpts = getDependencyOutputOpts();
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000286 if (!DepOpts.OutputFile.empty())
287 AttachDependencyFileGen(*PP, DepOpts);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000288
Daniel Dunbareef63e02011-02-02 15:41:17 +0000289 // Handle generating header include information, if requested.
290 if (DepOpts.ShowHeaderIncludes)
291 AttachHeaderIncludeGen(*PP);
Daniel Dunbarb34d69b2011-02-02 21:11:31 +0000292 if (!DepOpts.HeaderIncludeOutputFile.empty()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000293 StringRef OutputPath = DepOpts.HeaderIncludeOutputFile;
Daniel Dunbarb34d69b2011-02-02 21:11:31 +0000294 if (OutputPath == "-")
295 OutputPath = "";
Daniel Dunbarda608852011-03-21 19:37:38 +0000296 AttachHeaderIncludeGen(*PP, /*ShowAllHeaders=*/true, OutputPath,
297 /*ShowDepth=*/false);
Daniel Dunbarb34d69b2011-02-02 21:11:31 +0000298 }
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000299}
Daniel Dunbar5eb81002009-11-13 08:20:47 +0000300
301// ASTContext
302
303void CompilerInstance::createASTContext() {
304 Preprocessor &PP = getPreprocessor();
Ted Kremenek4f327862011-03-21 18:40:17 +0000305 Context = new ASTContext(getLangOpts(), PP.getSourceManager(),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000306 &getTarget(), PP.getIdentifierTable(),
Ted Kremenek4f327862011-03-21 18:40:17 +0000307 PP.getSelectorTable(), PP.getBuiltinInfo(),
308 /*size_reserve=*/ 0);
Daniel Dunbar5eb81002009-11-13 08:20:47 +0000309}
Daniel Dunbar0f800392009-11-13 08:21:10 +0000310
311// ExternalASTSource
312
Chris Lattner5f9e2722011-07-23 10:55:15 +0000313void CompilerInstance::createPCHExternalASTSource(StringRef Path,
Sebastian Redlffaab3e2010-07-30 00:29:29 +0000314 bool DisablePCHValidation,
Douglas Gregor8ef6c8c2011-02-05 19:42:43 +0000315 bool DisableStatCache,
Sebastian Redlffaab3e2010-07-30 00:29:29 +0000316 void *DeserializationListener){
Daniel Dunbar0f800392009-11-13 08:21:10 +0000317 llvm::OwningPtr<ExternalASTSource> Source;
Sebastian Redl1d9f1fe2010-10-05 16:15:19 +0000318 bool Preamble = getPreprocessorOpts().PrecompiledPreambleBytes.first != 0;
Daniel Dunbar0f800392009-11-13 08:21:10 +0000319 Source.reset(createPCHExternalASTSource(Path, getHeaderSearchOpts().Sysroot,
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000320 DisablePCHValidation,
Douglas Gregor8ef6c8c2011-02-05 19:42:43 +0000321 DisableStatCache,
Sebastian Redlffaab3e2010-07-30 00:29:29 +0000322 getPreprocessor(), getASTContext(),
Sebastian Redl1d9f1fe2010-10-05 16:15:19 +0000323 DeserializationListener,
324 Preamble));
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000325 ModuleManager = static_cast<ASTReader*>(Source.get());
Daniel Dunbar0f800392009-11-13 08:21:10 +0000326 getASTContext().setExternalSource(Source);
327}
328
329ExternalASTSource *
Chris Lattner5f9e2722011-07-23 10:55:15 +0000330CompilerInstance::createPCHExternalASTSource(StringRef Path,
Daniel Dunbar0f800392009-11-13 08:21:10 +0000331 const std::string &Sysroot,
Douglas Gregorfae3b2f2010-07-27 00:27:13 +0000332 bool DisablePCHValidation,
Douglas Gregor8ef6c8c2011-02-05 19:42:43 +0000333 bool DisableStatCache,
Daniel Dunbar0f800392009-11-13 08:21:10 +0000334 Preprocessor &PP,
Sebastian Redlffaab3e2010-07-30 00:29:29 +0000335 ASTContext &Context,
Sebastian Redl1d9f1fe2010-10-05 16:15:19 +0000336 void *DeserializationListener,
337 bool Preamble) {
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000338 llvm::OwningPtr<ASTReader> Reader;
Douglas Gregorf8a1e512011-09-02 00:26:20 +0000339 Reader.reset(new ASTReader(PP, Context,
Douglas Gregor832d6202011-07-22 16:35:34 +0000340 Sysroot.empty() ? "" : Sysroot.c_str(),
Douglas Gregor8ef6c8c2011-02-05 19:42:43 +0000341 DisablePCHValidation, DisableStatCache));
Daniel Dunbar0f800392009-11-13 08:21:10 +0000342
Sebastian Redlffaab3e2010-07-30 00:29:29 +0000343 Reader->setDeserializationListener(
Sebastian Redl571db7f2010-08-18 23:56:56 +0000344 static_cast<ASTDeserializationListener *>(DeserializationListener));
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000345 switch (Reader->ReadAST(Path,
346 Preamble ? serialization::MK_Preamble
Douglas Gregor72a9ae12011-07-22 16:00:58 +0000347 : serialization::MK_PCH)) {
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000348 case ASTReader::Success:
Daniel Dunbar0f800392009-11-13 08:21:10 +0000349 // Set the predefines buffer as suggested by the PCH reader. Typically, the
350 // predefines buffer will be empty.
351 PP.setPredefines(Reader->getSuggestedPredefines());
352 return Reader.take();
353
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000354 case ASTReader::Failure:
Daniel Dunbar0f800392009-11-13 08:21:10 +0000355 // Unrecoverable failure: don't even try to process the input file.
356 break;
357
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000358 case ASTReader::IgnorePCH:
Daniel Dunbar0f800392009-11-13 08:21:10 +0000359 // No suitable PCH file could be found. Return an error.
360 break;
361 }
362
363 return 0;
364}
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000365
366// Code Completion
367
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000368static bool EnableCodeCompletion(Preprocessor &PP,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000369 const std::string &Filename,
370 unsigned Line,
371 unsigned Column) {
372 // Tell the source manager to chop off the given file at a specific
373 // line and column.
Chris Lattner39b49bc2010-11-23 08:35:12 +0000374 const FileEntry *Entry = PP.getFileManager().getFile(Filename);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000375 if (!Entry) {
376 PP.getDiagnostics().Report(diag::err_fe_invalid_code_complete_file)
377 << Filename;
378 return true;
379 }
380
381 // Truncate the named file at the given line/column.
382 PP.SetCodeCompletionPoint(Entry, Line, Column);
383 return false;
384}
385
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000386void CompilerInstance::createCodeCompletionConsumer() {
387 const ParsedSourceLocation &Loc = getFrontendOpts().CodeCompletionAt;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000388 if (!CompletionConsumer) {
389 CompletionConsumer.reset(
390 createCodeCompletionConsumer(getPreprocessor(),
391 Loc.FileName, Loc.Line, Loc.Column,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000392 getFrontendOpts().ShowMacrosInCodeCompletion,
Douglas Gregord8e8a582010-05-25 21:41:55 +0000393 getFrontendOpts().ShowCodePatternsInCodeCompletion,
Douglas Gregor8071e422010-08-15 06:18:01 +0000394 getFrontendOpts().ShowGlobalSymbolsInCodeCompletion,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000395 llvm::outs()));
396 if (!CompletionConsumer)
397 return;
398 } else if (EnableCodeCompletion(getPreprocessor(), Loc.FileName,
399 Loc.Line, Loc.Column)) {
400 CompletionConsumer.reset();
Douglas Gregorc3d43b72010-03-16 06:04:47 +0000401 return;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000402 }
Douglas Gregor2b4074f2009-12-01 05:55:20 +0000403
404 if (CompletionConsumer->isOutputBinary() &&
405 llvm::sys::Program::ChangeStdoutToBinary()) {
406 getPreprocessor().getDiagnostics().Report(diag::err_fe_stdout_binary);
407 CompletionConsumer.reset();
408 }
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000409}
410
Kovarththanan Rajaratnamf79bafa2009-11-29 09:57:35 +0000411void CompilerInstance::createFrontendTimer() {
412 FrontendTimer.reset(new llvm::Timer("Clang front-end timer"));
413}
414
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000415CodeCompleteConsumer *
416CompilerInstance::createCodeCompletionConsumer(Preprocessor &PP,
417 const std::string &Filename,
418 unsigned Line,
419 unsigned Column,
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000420 bool ShowMacros,
Douglas Gregord8e8a582010-05-25 21:41:55 +0000421 bool ShowCodePatterns,
Douglas Gregor8071e422010-08-15 06:18:01 +0000422 bool ShowGlobals,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000423 raw_ostream &OS) {
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000424 if (EnableCodeCompletion(PP, Filename, Line, Column))
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000425 return 0;
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000426
427 // Set up the creation routine for code-completion.
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000428 return new PrintingCodeCompleteConsumer(ShowMacros, ShowCodePatterns,
Douglas Gregor8071e422010-08-15 06:18:01 +0000429 ShowGlobals, OS);
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000430}
Daniel Dunbara9204832009-11-13 10:37:48 +0000431
Douglas Gregor467dc882011-08-25 22:30:56 +0000432void CompilerInstance::createSema(TranslationUnitKind TUKind,
Douglas Gregorf18d0d82010-08-12 23:31:19 +0000433 CodeCompleteConsumer *CompletionConsumer) {
434 TheSema.reset(new Sema(getPreprocessor(), getASTContext(), getASTConsumer(),
Douglas Gregor467dc882011-08-25 22:30:56 +0000435 TUKind, CompletionConsumer));
Douglas Gregorf18d0d82010-08-12 23:31:19 +0000436}
437
Daniel Dunbara9204832009-11-13 10:37:48 +0000438// Output Files
439
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000440void CompilerInstance::addOutputFile(const OutputFile &OutFile) {
441 assert(OutFile.OS && "Attempt to add empty stream to output list!");
442 OutputFiles.push_back(OutFile);
Daniel Dunbara9204832009-11-13 10:37:48 +0000443}
444
Kovarththanan Rajaratname51dd7b2010-03-06 12:07:48 +0000445void CompilerInstance::clearOutputFiles(bool EraseFiles) {
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000446 for (std::list<OutputFile>::iterator
Daniel Dunbara9204832009-11-13 10:37:48 +0000447 it = OutputFiles.begin(), ie = OutputFiles.end(); it != ie; ++it) {
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000448 delete it->OS;
449 if (!it->TempFilename.empty()) {
Anders Carlssonaf036a62011-03-06 22:25:35 +0000450 if (EraseFiles) {
451 bool existed;
452 llvm::sys::fs::remove(it->TempFilename, existed);
453 } else {
454 llvm::SmallString<128> NewOutFile(it->Filename);
455
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +0000456 // If '-working-directory' was passed, the output filename should be
457 // relative to that.
Anders Carlsson2e2468e2011-03-14 01:13:54 +0000458 FileMgr->FixupRelativePath(NewOutFile);
Anders Carlssonaf036a62011-03-06 22:25:35 +0000459 if (llvm::error_code ec = llvm::sys::fs::rename(it->TempFilename,
460 NewOutFile.str())) {
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000461 getDiagnostics().Report(diag::err_fe_unable_to_rename_temp)
Anders Carlssonaf036a62011-03-06 22:25:35 +0000462 << it->TempFilename << it->Filename << ec.message();
463
464 bool existed;
465 llvm::sys::fs::remove(it->TempFilename, existed);
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000466 }
467 }
468 } else if (!it->Filename.empty() && EraseFiles)
469 llvm::sys::Path(it->Filename).eraseFromDisk();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000470
Daniel Dunbara9204832009-11-13 10:37:48 +0000471 }
472 OutputFiles.clear();
473}
474
Daniel Dunbarf482d592009-11-13 18:32:08 +0000475llvm::raw_fd_ostream *
476CompilerInstance::createDefaultOutputFile(bool Binary,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000477 StringRef InFile,
478 StringRef Extension) {
Daniel Dunbarf482d592009-11-13 18:32:08 +0000479 return createOutputFile(getFrontendOpts().OutputFile, Binary,
Daniel Dunbarff9cd962011-01-31 22:00:42 +0000480 /*RemoveFileOnSignal=*/true, InFile, Extension);
Daniel Dunbarf482d592009-11-13 18:32:08 +0000481}
482
483llvm::raw_fd_ostream *
Chris Lattner5f9e2722011-07-23 10:55:15 +0000484CompilerInstance::createOutputFile(StringRef OutputPath,
Daniel Dunbarff9cd962011-01-31 22:00:42 +0000485 bool Binary, bool RemoveFileOnSignal,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000486 StringRef InFile,
Argyrios Kyrtzidis7e909852011-07-28 00:45:10 +0000487 StringRef Extension,
488 bool UseTemporary) {
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000489 std::string Error, OutputPathName, TempPathName;
Daniel Dunbarf482d592009-11-13 18:32:08 +0000490 llvm::raw_fd_ostream *OS = createOutputFile(OutputPath, Error, Binary,
Daniel Dunbarff9cd962011-01-31 22:00:42 +0000491 RemoveFileOnSignal,
Daniel Dunbarf482d592009-11-13 18:32:08 +0000492 InFile, Extension,
Argyrios Kyrtzidis7e909852011-07-28 00:45:10 +0000493 UseTemporary,
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000494 &OutputPathName,
495 &TempPathName);
Daniel Dunbarf482d592009-11-13 18:32:08 +0000496 if (!OS) {
Daniel Dunbar36043592009-12-03 09:13:30 +0000497 getDiagnostics().Report(diag::err_fe_unable_to_open_output)
498 << OutputPath << Error;
499 return 0;
Daniel Dunbarf482d592009-11-13 18:32:08 +0000500 }
501
502 // Add the output file -- but don't try to remove "-", since this means we are
503 // using stdin.
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000504 addOutputFile(OutputFile((OutputPathName != "-") ? OutputPathName : "",
505 TempPathName, OS));
Daniel Dunbarf482d592009-11-13 18:32:08 +0000506
507 return OS;
508}
509
510llvm::raw_fd_ostream *
Chris Lattner5f9e2722011-07-23 10:55:15 +0000511CompilerInstance::createOutputFile(StringRef OutputPath,
Daniel Dunbarf482d592009-11-13 18:32:08 +0000512 std::string &Error,
513 bool Binary,
Daniel Dunbarff9cd962011-01-31 22:00:42 +0000514 bool RemoveFileOnSignal,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000515 StringRef InFile,
516 StringRef Extension,
Argyrios Kyrtzidis7e909852011-07-28 00:45:10 +0000517 bool UseTemporary,
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000518 std::string *ResultPathName,
519 std::string *TempPathName) {
520 std::string OutFile, TempFile;
Daniel Dunbarf482d592009-11-13 18:32:08 +0000521 if (!OutputPath.empty()) {
522 OutFile = OutputPath;
523 } else if (InFile == "-") {
524 OutFile = "-";
525 } else if (!Extension.empty()) {
526 llvm::sys::Path Path(InFile);
527 Path.eraseSuffix();
528 Path.appendSuffix(Extension);
529 OutFile = Path.str();
530 } else {
531 OutFile = "-";
532 }
Argyrios Kyrtzidis7e909852011-07-28 00:45:10 +0000533
534 llvm::OwningPtr<llvm::raw_fd_ostream> OS;
535 std::string OSFile;
536
537 if (UseTemporary && OutFile != "-") {
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000538 llvm::sys::Path OutPath(OutFile);
539 // Only create the temporary if we can actually write to OutPath, otherwise
540 // we want to fail early.
Michael J. Spencer32bef4e2011-01-10 02:34:13 +0000541 bool Exists;
542 if ((llvm::sys::fs::exists(OutPath.str(), Exists) || !Exists) ||
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000543 (OutPath.isRegularFile() && OutPath.canWrite())) {
544 // Create a temporary file.
Argyrios Kyrtzidis7e909852011-07-28 00:45:10 +0000545 llvm::SmallString<128> TempPath;
546 TempPath = OutFile;
547 TempPath += "-%%%%%%%%";
548 int fd;
549 if (llvm::sys::fs::unique_file(TempPath.str(), fd, TempPath,
550 /*makeAbsolute=*/false) == llvm::errc::success) {
551 OS.reset(new llvm::raw_fd_ostream(fd, /*shouldClose=*/true));
552 OSFile = TempFile = TempPath.str();
553 }
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000554 }
555 }
556
Argyrios Kyrtzidis7e909852011-07-28 00:45:10 +0000557 if (!OS) {
558 OSFile = OutFile;
559 OS.reset(
560 new llvm::raw_fd_ostream(OSFile.c_str(), Error,
561 (Binary ? llvm::raw_fd_ostream::F_Binary : 0)));
562 if (!Error.empty())
563 return 0;
564 }
Daniel Dunbarf482d592009-11-13 18:32:08 +0000565
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000566 // Make sure the out stream file gets removed if we crash.
Daniel Dunbarff9cd962011-01-31 22:00:42 +0000567 if (RemoveFileOnSignal)
568 llvm::sys::RemoveFileOnSignal(llvm::sys::Path(OSFile));
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000569
Daniel Dunbarf482d592009-11-13 18:32:08 +0000570 if (ResultPathName)
571 *ResultPathName = OutFile;
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000572 if (TempPathName)
573 *TempPathName = TempFile;
Daniel Dunbarf482d592009-11-13 18:32:08 +0000574
Daniel Dunbarfc971022009-11-20 22:32:38 +0000575 return OS.take();
Daniel Dunbarf482d592009-11-13 18:32:08 +0000576}
Daniel Dunbarccb6cb62009-11-14 07:53:04 +0000577
578// Initialization Utilities
579
Douglas Gregora1f1fad2012-01-27 19:52:33 +0000580bool CompilerInstance::InitializeSourceManager(StringRef InputFile,
581 SrcMgr::CharacteristicKind Kind){
582 return InitializeSourceManager(InputFile, Kind, getDiagnostics(),
583 getFileManager(), getSourceManager(),
584 getFrontendOpts());
Daniel Dunbarccb6cb62009-11-14 07:53:04 +0000585}
586
Chris Lattner5f9e2722011-07-23 10:55:15 +0000587bool CompilerInstance::InitializeSourceManager(StringRef InputFile,
Douglas Gregora1f1fad2012-01-27 19:52:33 +0000588 SrcMgr::CharacteristicKind Kind,
David Blaikied6471f72011-09-25 23:23:43 +0000589 DiagnosticsEngine &Diags,
Daniel Dunbarccb6cb62009-11-14 07:53:04 +0000590 FileManager &FileMgr,
591 SourceManager &SourceMgr,
592 const FrontendOptions &Opts) {
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +0000593 // Figure out where to get and map in the main file.
594 if (InputFile != "-") {
Chris Lattner39b49bc2010-11-23 08:35:12 +0000595 const FileEntry *File = FileMgr.getFile(InputFile);
Dan Gohman694137c2010-10-26 21:13:51 +0000596 if (!File) {
Daniel Dunbarccb6cb62009-11-14 07:53:04 +0000597 Diags.Report(diag::err_fe_error_reading) << InputFile;
598 return false;
599 }
Douglas Gregora1f1fad2012-01-27 19:52:33 +0000600 SourceMgr.createMainFileID(File, Kind);
Daniel Dunbarccb6cb62009-11-14 07:53:04 +0000601 } else {
Michael J. Spencer4eeebc42010-12-16 03:28:14 +0000602 llvm::OwningPtr<llvm::MemoryBuffer> SB;
603 if (llvm::MemoryBuffer::getSTDIN(SB)) {
Michael J. Spencer3a321e22010-12-09 17:36:38 +0000604 // FIXME: Give ec.message() in this diag.
Daniel Dunbarccb6cb62009-11-14 07:53:04 +0000605 Diags.Report(diag::err_fe_error_reading_stdin);
606 return false;
607 }
Dan Gohman90d90812010-10-26 23:21:25 +0000608 const FileEntry *File = FileMgr.getVirtualFile(SB->getBufferIdentifier(),
Chris Lattner39b49bc2010-11-23 08:35:12 +0000609 SB->getBufferSize(), 0);
Douglas Gregora1f1fad2012-01-27 19:52:33 +0000610 SourceMgr.createMainFileID(File, Kind);
Michael J. Spencer4eeebc42010-12-16 03:28:14 +0000611 SourceMgr.overrideFileContents(File, SB.take());
Daniel Dunbarccb6cb62009-11-14 07:53:04 +0000612 }
613
Dan Gohman694137c2010-10-26 21:13:51 +0000614 assert(!SourceMgr.getMainFileID().isInvalid() &&
615 "Couldn't establish MainFileID!");
Daniel Dunbarccb6cb62009-11-14 07:53:04 +0000616 return true;
617}
Daniel Dunbar0397af22010-01-13 00:48:06 +0000618
619// High-Level Operations
620
621bool CompilerInstance::ExecuteAction(FrontendAction &Act) {
622 assert(hasDiagnostics() && "Diagnostics engine is not initialized!");
623 assert(!getFrontendOpts().ShowHelp && "Client must handle '-help'!");
624 assert(!getFrontendOpts().ShowVersion && "Client must handle '-version'!");
625
626 // FIXME: Take this as an argument, once all the APIs we used have moved to
627 // taking it as an input instead of hard-coding llvm::errs.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000628 raw_ostream &OS = llvm::errs();
Daniel Dunbar0397af22010-01-13 00:48:06 +0000629
630 // Create the target instance.
631 setTarget(TargetInfo::CreateTargetInfo(getDiagnostics(), getTargetOpts()));
632 if (!hasTarget())
633 return false;
634
635 // Inform the target of the language options.
636 //
637 // FIXME: We shouldn't need to do this, the target should be immutable once
638 // created. This complexity should be lifted elsewhere.
639 getTarget().setForcedLangOptions(getLangOpts());
640
641 // Validate/process some options.
642 if (getHeaderSearchOpts().Verbose)
643 OS << "clang -cc1 version " CLANG_VERSION_STRING
644 << " based upon " << PACKAGE_STRING
Sebastian Pop5d8b9542011-11-01 21:33:06 +0000645 << " default target " << llvm::sys::getDefaultTargetTriple() << "\n";
Daniel Dunbar0397af22010-01-13 00:48:06 +0000646
647 if (getFrontendOpts().ShowTimers)
648 createFrontendTimer();
649
Douglas Gregor95dd5582010-03-30 17:33:59 +0000650 if (getFrontendOpts().ShowStats)
651 llvm::EnableStatistics();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000652
Daniel Dunbar0397af22010-01-13 00:48:06 +0000653 for (unsigned i = 0, e = getFrontendOpts().Inputs.size(); i != e; ++i) {
Daniel Dunbar20560482010-06-07 23:23:50 +0000654 // Reset the ID tables if we are reusing the SourceManager.
655 if (hasSourceManager())
656 getSourceManager().clearIDTables();
Daniel Dunbar0397af22010-01-13 00:48:06 +0000657
Douglas Gregor1f6b2b52012-01-20 16:28:04 +0000658 if (Act.BeginSourceFile(*this, getFrontendOpts().Inputs[i])) {
Daniel Dunbar0397af22010-01-13 00:48:06 +0000659 Act.Execute();
660 Act.EndSourceFile();
661 }
662 }
663
Argyrios Kyrtzidis29f27872011-12-07 05:52:12 +0000664 // Notify the diagnostic client that all files were processed.
665 getDiagnostics().getClient()->finish();
666
Chris Lattner53eee7b2010-04-07 18:47:42 +0000667 if (getDiagnosticOpts().ShowCarets) {
Argyrios Kyrtzidisf2224d82010-11-18 20:06:46 +0000668 // We can have multiple diagnostics sharing one diagnostic client.
669 // Get the total number of warnings/errors from the client.
670 unsigned NumWarnings = getDiagnostics().getClient()->getNumWarnings();
671 unsigned NumErrors = getDiagnostics().getClient()->getNumErrors();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000672
Chris Lattner53eee7b2010-04-07 18:47:42 +0000673 if (NumWarnings)
674 OS << NumWarnings << " warning" << (NumWarnings == 1 ? "" : "s");
675 if (NumWarnings && NumErrors)
676 OS << " and ";
677 if (NumErrors)
678 OS << NumErrors << " error" << (NumErrors == 1 ? "" : "s");
679 if (NumWarnings || NumErrors)
680 OS << " generated.\n";
681 }
Daniel Dunbar0397af22010-01-13 00:48:06 +0000682
Daniel Dunbar20560482010-06-07 23:23:50 +0000683 if (getFrontendOpts().ShowStats && hasFileManager()) {
Daniel Dunbar0397af22010-01-13 00:48:06 +0000684 getFileManager().PrintStats();
685 OS << "\n";
686 }
687
Argyrios Kyrtzidisab41b972010-11-18 21:13:57 +0000688 return !getDiagnostics().getClient()->getNumErrors();
Daniel Dunbar0397af22010-01-13 00:48:06 +0000689}
690
Douglas Gregor21cae202011-09-12 23:31:24 +0000691/// \brief Determine the appropriate source input kind based on language
692/// options.
693static InputKind getSourceInputKindFromOptions(const LangOptions &LangOpts) {
694 if (LangOpts.OpenCL)
695 return IK_OpenCL;
696 if (LangOpts.CUDA)
697 return IK_CUDA;
698 if (LangOpts.ObjC1)
699 return LangOpts.CPlusPlus? IK_ObjCXX : IK_ObjC;
700 return LangOpts.CPlusPlus? IK_CXX : IK_C;
701}
702
Douglas Gregor0ced7992011-10-04 00:21:21 +0000703namespace {
Douglas Gregorf9e357d2011-11-29 19:06:37 +0000704 struct CompileModuleMapData {
705 CompilerInstance &Instance;
706 GenerateModuleAction &CreateModuleAction;
707 };
708}
709
710/// \brief Helper function that executes the module-generating action under
711/// a crash recovery context.
712static void doCompileMapModule(void *UserData) {
713 CompileModuleMapData &Data
714 = *reinterpret_cast<CompileModuleMapData *>(UserData);
715 Data.Instance.ExecuteAction(Data.CreateModuleAction);
716}
717
718namespace {
Douglas Gregor2bc75072011-10-05 14:53:30 +0000719 /// \brief Class that manages the creation of a lock file to aid
720 /// implicit coordination between different processes.
721 ///
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000722 /// The implicit coordination works by creating a ".lock" file alongside
Douglas Gregor2bc75072011-10-05 14:53:30 +0000723 /// the file that we're coordinating for, using the atomicity of the file
724 /// system to ensure that only a single process can create that ".lock" file.
725 /// When the lock file is removed, the owning process has finished the
726 /// operation.
727 class LockFileManager {
728 public:
729 /// \brief Describes the state of a lock file.
730 enum LockFileState {
731 /// \brief The lock file has been created and is owned by this instance
732 /// of the object.
733 LFS_Owned,
734 /// \brief The lock file already exists and is owned by some other
735 /// instance.
736 LFS_Shared,
737 /// \brief An error occurred while trying to create or find the lock
738 /// file.
739 LFS_Error
740 };
741
742 private:
743 llvm::SmallString<128> LockFileName;
744 llvm::SmallString<128> UniqueLockFileName;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000745
Douglas Gregor2bc75072011-10-05 14:53:30 +0000746 llvm::Optional<std::pair<std::string, int> > Owner;
747 llvm::Optional<llvm::error_code> Error;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000748
Douglas Gregor2bc75072011-10-05 14:53:30 +0000749 LockFileManager(const LockFileManager &);
750 LockFileManager &operator=(const LockFileManager &);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000751
752 static llvm::Optional<std::pair<std::string, int> >
Douglas Gregor2bc75072011-10-05 14:53:30 +0000753 readLockFile(StringRef LockFileName);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000754
Douglas Gregor2bc75072011-10-05 14:53:30 +0000755 static bool processStillExecuting(StringRef Hostname, int PID);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000756
Douglas Gregor2bc75072011-10-05 14:53:30 +0000757 public:
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000758
Douglas Gregor2bc75072011-10-05 14:53:30 +0000759 LockFileManager(StringRef FileName);
760 ~LockFileManager();
761
762 /// \brief Determine the state of the lock file.
763 LockFileState getState() const;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000764
Douglas Gregor2bc75072011-10-05 14:53:30 +0000765 operator LockFileState() const { return getState(); }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000766
Douglas Gregor2bc75072011-10-05 14:53:30 +0000767 /// \brief For a shared lock, wait until the owner releases the lock.
768 void waitForUnlock();
769 };
770}
771
772/// \brief Attempt to read the lock file with the given name, if it exists.
773///
774/// \param LockFileName The name of the lock file to read.
775///
776/// \returns The process ID of the process that owns this lock file
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000777llvm::Optional<std::pair<std::string, int> >
Douglas Gregor2bc75072011-10-05 14:53:30 +0000778LockFileManager::readLockFile(StringRef LockFileName) {
779 // Check whether the lock file exists. If not, clearly there's nothing
780 // to read, so we just return.
781 bool Exists = false;
782 if (llvm::sys::fs::exists(LockFileName, Exists) || !Exists)
783 return llvm::Optional<std::pair<std::string, int> >();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000784
Douglas Gregor2bc75072011-10-05 14:53:30 +0000785 // Read the owning host and PID out of the lock file. If it appears that the
786 // owning process is dead, the lock file is invalid.
787 int PID = 0;
788 std::string Hostname;
789 std::ifstream Input(LockFileName.str().c_str());
790 if (Input >> Hostname >> PID && PID > 0 &&
791 processStillExecuting(Hostname, PID))
792 return std::make_pair(Hostname, PID);
793
794 // Delete the lock file. It's invalid anyway.
795 bool Existed;
796 llvm::sys::fs::remove(LockFileName, Existed);
797 return llvm::Optional<std::pair<std::string, int> >();
798}
799
800bool LockFileManager::processStillExecuting(StringRef Hostname, int PID) {
801#if LLVM_ON_UNIX
802 char MyHostname[256];
803 MyHostname[255] = 0;
804 MyHostname[0] = 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000805 gethostname(MyHostname, 255);
Douglas Gregor2bc75072011-10-05 14:53:30 +0000806 // Check whether the process is dead. If so, we're done.
807 if (MyHostname == Hostname && getsid(PID) == -1 && errno == ESRCH)
808 return false;
809#endif
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000810
Douglas Gregor2bc75072011-10-05 14:53:30 +0000811 return true;
812}
813
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000814LockFileManager::LockFileManager(StringRef FileName)
Douglas Gregor2bc75072011-10-05 14:53:30 +0000815{
816 LockFileName = FileName;
817 LockFileName += ".lock";
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000818
Douglas Gregor2bc75072011-10-05 14:53:30 +0000819 // If the lock file already exists, don't bother to try to create our own
820 // lock file; it won't work anyway. Just figure out who owns this lock file.
821 if ((Owner = readLockFile(LockFileName)))
822 return;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000823
Douglas Gregor2bc75072011-10-05 14:53:30 +0000824 // Create a lock file that is unique to this instance.
825 UniqueLockFileName = LockFileName;
826 UniqueLockFileName += "-%%%%%%%%";
827 int UniqueLockFileID;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000828 if (llvm::error_code EC
829 = llvm::sys::fs::unique_file(UniqueLockFileName.str(),
Douglas Gregor2bc75072011-10-05 14:53:30 +0000830 UniqueLockFileID,
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000831 UniqueLockFileName,
Douglas Gregor2bc75072011-10-05 14:53:30 +0000832 /*makeAbsolute=*/false)) {
833 Error = EC;
834 return;
835 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000836
Douglas Gregor2bc75072011-10-05 14:53:30 +0000837 // Write our process ID to our unique lock file.
838 {
839 llvm::raw_fd_ostream Out(UniqueLockFileID, /*shouldClose=*/true);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000840
Douglas Gregor2bc75072011-10-05 14:53:30 +0000841#if LLVM_ON_UNIX
842 // FIXME: move getpid() call into LLVM
843 char hostname[256];
844 hostname[255] = 0;
845 hostname[0] = 0;
846 gethostname(hostname, 255);
847 Out << hostname << ' ' << getpid();
848#else
849 Out << "localhost 1";
850#endif
851 Out.close();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000852
Douglas Gregor2bc75072011-10-05 14:53:30 +0000853 if (Out.has_error()) {
854 // We failed to write out PID, so make up an excuse, remove the
855 // unique lock file, and fail.
856 Error = llvm::make_error_code(llvm::errc::no_space_on_device);
857 bool Existed;
858 llvm::sys::fs::remove(UniqueLockFileName.c_str(), Existed);
859 return;
860 }
861 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000862
Douglas Gregor2bc75072011-10-05 14:53:30 +0000863 // Create a hard link from the lock file name. If this succeeds, we're done.
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000864 llvm::error_code EC
865 = llvm::sys::fs::create_hard_link(UniqueLockFileName.str(),
Douglas Gregor2bc75072011-10-05 14:53:30 +0000866 LockFileName.str());
867 if (EC == llvm::errc::success)
868 return;
869
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000870 // Creating the hard link failed.
871
Douglas Gregor2bc75072011-10-05 14:53:30 +0000872#ifdef LLVM_ON_UNIX
873 // The creation of the hard link may appear to fail, but if stat'ing the
874 // unique file returns a link count of 2, then we can still declare success.
875 struct stat StatBuf;
876 if (stat(UniqueLockFileName.c_str(), &StatBuf) == 0 &&
877 StatBuf.st_nlink == 2)
878 return;
879#endif
880
881 // Someone else managed to create the lock file first. Wipe out our unique
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000882 // lock file (it's useless now) and read the process ID from the lock file.
Douglas Gregor2bc75072011-10-05 14:53:30 +0000883 bool Existed;
884 llvm::sys::fs::remove(UniqueLockFileName.str(), Existed);
885 if ((Owner = readLockFile(LockFileName)))
886 return;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000887
Douglas Gregor2bc75072011-10-05 14:53:30 +0000888 // There is a lock file that nobody owns; try to clean it up and report
889 // an error.
890 llvm::sys::fs::remove(LockFileName.str(), Existed);
891 Error = EC;
892}
893
894LockFileManager::LockFileState LockFileManager::getState() const {
895 if (Owner)
896 return LFS_Shared;
897
898 if (Error)
899 return LFS_Error;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000900
Douglas Gregor2bc75072011-10-05 14:53:30 +0000901 return LFS_Owned;
902}
903
904LockFileManager::~LockFileManager() {
905 if (getState() != LFS_Owned)
906 return;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000907
Douglas Gregor2bc75072011-10-05 14:53:30 +0000908 // Since we own the lock, remove the lock file and our own unique lock file.
909 bool Existed;
910 llvm::sys::fs::remove(LockFileName.str(), Existed);
911 llvm::sys::fs::remove(UniqueLockFileName.str(), Existed);
912}
913
914void LockFileManager::waitForUnlock() {
915 if (getState() != LFS_Shared)
916 return;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000917
Douglas Gregor1872e792011-10-05 14:58:46 +0000918#if LLVM_ON_WIN32
919 unsigned long Interval = 1;
920#else
Douglas Gregor2bc75072011-10-05 14:53:30 +0000921 struct timespec Interval;
922 Interval.tv_sec = 0;
923 Interval.tv_nsec = 1000000;
Douglas Gregor1872e792011-10-05 14:58:46 +0000924#endif
Douglas Gregor2bc75072011-10-05 14:53:30 +0000925 // Don't wait more than an hour for the file to appear.
926 const unsigned MaxSeconds = 3600;
927 do {
928 // Sleep for the designated interval, to allow the owning process time to
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000929 // finish up and
Douglas Gregor2bc75072011-10-05 14:53:30 +0000930 // FIXME: Should we hook in to system APIs to get a notification when the
931 // lock file is deleted?
Douglas Gregor25728492011-10-05 14:59:36 +0000932#if LLVM_ON_WIN32
933 Sleep(Interval);
934#else
Douglas Gregor2bc75072011-10-05 14:53:30 +0000935 nanosleep(&Interval, NULL);
Douglas Gregor25728492011-10-05 14:59:36 +0000936#endif
Douglas Gregor2bc75072011-10-05 14:53:30 +0000937 // If the file no longer exists, we're done.
938 bool Exists = false;
939 if (!llvm::sys::fs::exists(LockFileName.str(), Exists) && !Exists)
940 return;
941
942 if (!processStillExecuting((*Owner).first, (*Owner).second))
943 return;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000944
Douglas Gregor2bc75072011-10-05 14:53:30 +0000945 // Exponentially increase the time we wait for the lock to be removed.
Douglas Gregor1872e792011-10-05 14:58:46 +0000946#if LLVM_ON_WIN32
947 Interval *= 2;
948#else
Douglas Gregor2bc75072011-10-05 14:53:30 +0000949 Interval.tv_sec *= 2;
950 Interval.tv_nsec *= 2;
951 if (Interval.tv_nsec >= 1000000000) {
952 ++Interval.tv_sec;
953 Interval.tv_nsec -= 1000000000;
954 }
Douglas Gregor1872e792011-10-05 14:58:46 +0000955#endif
956 } while (
957#if LLVM_ON_WIN32
958 Interval < MaxSeconds * 1000
959#else
NAKAMURA Takumi0caed282011-10-08 11:31:58 +0000960 Interval.tv_sec < (time_t)MaxSeconds
Douglas Gregor1872e792011-10-05 14:58:46 +0000961#endif
962 );
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000963
Douglas Gregor2bc75072011-10-05 14:53:30 +0000964 // Give up.
965}
966
Douglas Gregorf9e357d2011-11-29 19:06:37 +0000967/// \brief Compile a module file for the given module, using the options
968/// provided by the importing compiler instance.
Douglas Gregor21cae202011-09-12 23:31:24 +0000969static void compileModule(CompilerInstance &ImportingInstance,
Douglas Gregor1a4761e2011-11-30 23:21:26 +0000970 Module *Module,
Douglas Gregor933e7a62011-11-29 18:31:39 +0000971 StringRef ModuleFileName) {
Douglas Gregor2bc75072011-10-05 14:53:30 +0000972 LockFileManager Locked(ModuleFileName);
973 switch (Locked) {
974 case LockFileManager::LFS_Error:
975 return;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000976
Douglas Gregor2bc75072011-10-05 14:53:30 +0000977 case LockFileManager::LFS_Owned:
978 // We're responsible for building the module ourselves. Do so below.
979 break;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000980
Douglas Gregor2bc75072011-10-05 14:53:30 +0000981 case LockFileManager::LFS_Shared:
982 // Someone else is responsible for building the module. Wait for them to
983 // finish.
984 Locked.waitForUnlock();
985 break;
986 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000987
Douglas Gregorf9e357d2011-11-29 19:06:37 +0000988 ModuleMap &ModMap
989 = ImportingInstance.getPreprocessor().getHeaderSearchInfo().getModuleMap();
990
Douglas Gregor21cae202011-09-12 23:31:24 +0000991 // Construct a compiler invocation for creating this module.
992 llvm::IntrusiveRefCntPtr<CompilerInvocation> Invocation
993 (new CompilerInvocation(ImportingInstance.getInvocation()));
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000994
Douglas Gregor18ee5472011-11-29 21:59:16 +0000995 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
996
Douglas Gregorb2d39c22011-09-15 20:53:28 +0000997 // For any options that aren't intended to affect how a module is built,
998 // reset them to their default values.
Ted Kremenekd3b74d92011-11-17 23:01:24 +0000999 Invocation->getLangOpts()->resetNonModularOptions();
Douglas Gregor18ee5472011-11-29 21:59:16 +00001000 PPOpts.resetNonModularOptions();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001001
Douglas Gregorb86b8dc2011-11-15 19:35:01 +00001002 // Note the name of the module we're building.
Douglas Gregor933e7a62011-11-29 18:31:39 +00001003 Invocation->getLangOpts()->CurrentModule = Module->getTopLevelModuleName();
Douglas Gregorb86b8dc2011-11-15 19:35:01 +00001004
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001005 // Note that this module is part of the module build path, so that we
Douglas Gregorb2d39c22011-09-15 20:53:28 +00001006 // can detect cycles in the module graph.
Douglas Gregor18ee5472011-11-29 21:59:16 +00001007 PPOpts.ModuleBuildPath.push_back(Module->getTopLevelModuleName());
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001008
Douglas Gregor18ee5472011-11-29 21:59:16 +00001009 // If there is a module map file, build the module using the module map.
Douglas Gregorb2d39c22011-09-15 20:53:28 +00001010 // Set up the inputs/outputs so that we build the module from its umbrella
1011 // header.
Douglas Gregor21cae202011-09-12 23:31:24 +00001012 FrontendOptions &FrontendOpts = Invocation->getFrontendOpts();
Douglas Gregor6e975c42011-09-13 23:15:45 +00001013 FrontendOpts.OutputFile = ModuleFileName.str();
Douglas Gregor21cae202011-09-12 23:31:24 +00001014 FrontendOpts.DisableFree = false;
1015 FrontendOpts.Inputs.clear();
Douglas Gregor18ee5472011-11-29 21:59:16 +00001016 InputKind IK = getSourceInputKindFromOptions(*Invocation->getLangOpts());
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001017
Douglas Gregor18ee5472011-11-29 21:59:16 +00001018 // Get or create the module map that we'll use to build this module.
1019 llvm::SmallString<128> TempModuleMapFileName;
1020 if (const FileEntry *ModuleMapFile
1021 = ModMap.getContainingModuleMapFile(Module)) {
1022 // Use the module map where this module resides.
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001023 FrontendOpts.Inputs.push_back(FrontendInputFile(ModuleMapFile->getName(),
1024 IK));
Douglas Gregor18ee5472011-11-29 21:59:16 +00001025 } else {
1026 // Create a temporary module map file.
1027 TempModuleMapFileName = Module->Name;
1028 TempModuleMapFileName += "-%%%%%%%%.map";
1029 int FD;
1030 if (llvm::sys::fs::unique_file(TempModuleMapFileName.str(), FD,
1031 TempModuleMapFileName,
Douglas Gregor1e821e92011-12-06 22:05:29 +00001032 /*makeAbsolute=*/true)
Douglas Gregore9120292011-12-06 23:04:08 +00001033 != llvm::errc::success) {
Douglas Gregorf64114b2011-12-07 00:54:14 +00001034 ImportingInstance.getDiagnostics().Report(diag::err_module_map_temp_file)
1035 << TempModuleMapFileName;
Douglas Gregor18ee5472011-11-29 21:59:16 +00001036 return;
Douglas Gregore9120292011-12-06 23:04:08 +00001037 }
Douglas Gregor18ee5472011-11-29 21:59:16 +00001038 // Print the module map to this file.
1039 llvm::raw_fd_ostream OS(FD, /*shouldClose=*/true);
1040 Module->print(OS);
1041 FrontendOpts.Inputs.push_back(
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001042 FrontendInputFile(TempModuleMapFileName.str().str(), IK));
Douglas Gregor18ee5472011-11-29 21:59:16 +00001043 }
1044
1045 // Don't free the remapped file buffers; they are owned by our caller.
1046 PPOpts.RetainRemappedFileBuffers = true;
1047
Douglas Gregor78243652011-09-13 01:26:44 +00001048 Invocation->getDiagnosticOpts().VerifyDiagnostics = 0;
Douglas Gregor76d991e2011-09-13 23:20:27 +00001049 assert(ImportingInstance.getInvocation().getModuleHash() ==
Douglas Gregor18ee5472011-11-29 21:59:16 +00001050 Invocation->getModuleHash() && "Module hash mismatch!");
1051
Douglas Gregor21cae202011-09-12 23:31:24 +00001052 // Construct a compiler instance that will be used to actually create the
1053 // module.
1054 CompilerInstance Instance;
1055 Instance.setInvocation(&*Invocation);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001056 Instance.createDiagnostics(/*argc=*/0, /*argv=*/0,
Douglas Gregor78243652011-09-13 01:26:44 +00001057 &ImportingInstance.getDiagnosticClient(),
Douglas Gregoraee526e2011-09-29 00:38:00 +00001058 /*ShouldOwnClient=*/true,
1059 /*ShouldCloneClient=*/true);
Douglas Gregor18ee5472011-11-29 21:59:16 +00001060
Douglas Gregor21cae202011-09-12 23:31:24 +00001061 // Construct a module-generating action.
Douglas Gregor18ee5472011-11-29 21:59:16 +00001062 GenerateModuleAction CreateModuleAction;
1063
Douglas Gregor0ced7992011-10-04 00:21:21 +00001064 // Execute the action to actually build the module in-place. Use a separate
1065 // thread so that we get a stack large enough.
1066 const unsigned ThreadStackSize = 8 << 20;
1067 llvm::CrashRecoveryContext CRC;
Douglas Gregor18ee5472011-11-29 21:59:16 +00001068 CompileModuleMapData Data = { Instance, CreateModuleAction };
1069 CRC.RunSafelyOnThread(&doCompileMapModule, &Data, ThreadStackSize);
1070
1071 // Delete the temporary module map file.
1072 // FIXME: Even though we're executing under crash protection, it would still
1073 // be nice to do this with RemoveFileOnSignal when we can. However, that
1074 // doesn't make sense for all clients, so clean this up manually.
1075 if (!TempModuleMapFileName.empty())
1076 llvm::sys::Path(TempModuleMapFileName).eraseFromDisk();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001077}
Douglas Gregor21cae202011-09-12 23:31:24 +00001078
Douglas Gregor1a4761e2011-11-30 23:21:26 +00001079Module *CompilerInstance::loadModule(SourceLocation ImportLoc,
Douglas Gregor5e356932011-12-01 17:11:21 +00001080 ModuleIdPath Path,
Douglas Gregor93ebfa62011-12-02 23:42:12 +00001081 Module::NameVisibilityKind Visibility,
1082 bool IsInclusionDirective) {
Douglas Gregorb514c792011-11-30 04:26:53 +00001083 // If we've already handled this import, just return the cached result.
1084 // This one-element cache is important to eliminate redundant diagnostics
1085 // when both the preprocessor and parser see the same import declaration.
Douglas Gregor5e356932011-12-01 17:11:21 +00001086 if (!ImportLoc.isInvalid() && LastModuleImportLoc == ImportLoc) {
1087 // Make the named module visible.
1088 if (LastModuleImportResult)
1089 ModuleManager->makeModuleVisible(LastModuleImportResult, Visibility);
Douglas Gregor392ed2b2011-11-30 17:33:56 +00001090 return LastModuleImportResult;
Douglas Gregor5e356932011-12-01 17:11:21 +00001091 }
Douglas Gregorb514c792011-11-30 04:26:53 +00001092
Douglas Gregor6aa52ec2011-08-26 23:56:07 +00001093 // Determine what file we're searching from.
1094 SourceManager &SourceMgr = getSourceManager();
1095 SourceLocation ExpandedImportLoc = SourceMgr.getExpansionLoc(ImportLoc);
1096 const FileEntry *CurFile
1097 = SourceMgr.getFileEntryForID(SourceMgr.getFileID(ExpandedImportLoc));
1098 if (!CurFile)
1099 CurFile = SourceMgr.getFileEntryForID(SourceMgr.getMainFileID());
1100
Douglas Gregor3d3589d2011-11-30 00:36:36 +00001101 StringRef ModuleName = Path[0].first->getName();
1102 SourceLocation ModuleNameLoc = Path[0].second;
Douglas Gregor49009ec2011-11-30 04:03:44 +00001103
Douglas Gregor1a4761e2011-11-30 23:21:26 +00001104 clang::Module *Module = 0;
Douglas Gregor49009ec2011-11-30 04:03:44 +00001105 const FileEntry *ModuleFile = 0;
Douglas Gregor3d3589d2011-11-30 00:36:36 +00001106
Douglas Gregor49009ec2011-11-30 04:03:44 +00001107 // If we don't already have information on this module, load the module now.
Douglas Gregor1a4761e2011-11-30 23:21:26 +00001108 llvm::DenseMap<const IdentifierInfo *, clang::Module *>::iterator Known
Douglas Gregor392ed2b2011-11-30 17:33:56 +00001109 = KnownModules.find(Path[0].first);
Douglas Gregor5e3f9222011-12-08 17:01:29 +00001110 if (Known != KnownModules.end()) {
1111 // Retrieve the cached top-level module.
1112 Module = Known->second;
1113 } else if (ModuleName == getLangOpts().CurrentModule) {
1114 // This is the module we're building.
1115 Module = PP->getHeaderSearchInfo().getModuleMap().findModule(ModuleName);
1116 Known = KnownModules.insert(std::make_pair(Path[0].first, Module)).first;
1117 } else {
Douglas Gregor49009ec2011-11-30 04:03:44 +00001118 // Search for a module with the given name.
1119 std::string ModuleFileName;
1120 ModuleFile
1121 = PP->getHeaderSearchInfo().lookupModule(ModuleName, Module,
1122 &ModuleFileName);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001123
Douglas Gregor49009ec2011-11-30 04:03:44 +00001124 bool BuildingModule = false;
1125 if (!ModuleFile && Module) {
1126 // The module is not cached, but we have a module map from which we can
1127 // build the module.
1128
1129 // Check whether there is a cycle in the module graph.
1130 SmallVectorImpl<std::string> &ModuleBuildPath
1131 = getPreprocessorOpts().ModuleBuildPath;
1132 SmallVectorImpl<std::string>::iterator Pos
1133 = std::find(ModuleBuildPath.begin(), ModuleBuildPath.end(), ModuleName);
1134 if (Pos != ModuleBuildPath.end()) {
1135 llvm::SmallString<256> CyclePath;
1136 for (; Pos != ModuleBuildPath.end(); ++Pos) {
1137 CyclePath += *Pos;
1138 CyclePath += " -> ";
1139 }
1140 CyclePath += ModuleName;
1141
1142 getDiagnostics().Report(ModuleNameLoc, diag::err_module_cycle)
1143 << ModuleName << CyclePath;
1144 return 0;
Douglas Gregor4ebd45f2011-09-15 20:40:10 +00001145 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001146
Douglas Gregor49009ec2011-11-30 04:03:44 +00001147 getDiagnostics().Report(ModuleNameLoc, diag::warn_module_build)
1148 << ModuleName;
1149 BuildingModule = true;
1150 compileModule(*this, Module, ModuleFileName);
1151 ModuleFile = FileMgr->getFile(ModuleFileName);
1152 }
1153
1154 if (!ModuleFile) {
1155 getDiagnostics().Report(ModuleNameLoc,
1156 BuildingModule? diag::err_module_not_built
1157 : diag::err_module_not_found)
1158 << ModuleName
1159 << SourceRange(ImportLoc, ModuleNameLoc);
Douglas Gregor4ebd45f2011-09-15 20:40:10 +00001160 return 0;
1161 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001162
Douglas Gregor49009ec2011-11-30 04:03:44 +00001163 // If we don't already have an ASTReader, create one now.
1164 if (!ModuleManager) {
1165 if (!hasASTContext())
1166 createASTContext();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001167
Douglas Gregor49009ec2011-11-30 04:03:44 +00001168 std::string Sysroot = getHeaderSearchOpts().Sysroot;
1169 const PreprocessorOptions &PPOpts = getPreprocessorOpts();
1170 ModuleManager = new ASTReader(getPreprocessor(), *Context,
1171 Sysroot.empty() ? "" : Sysroot.c_str(),
1172 PPOpts.DisablePCHValidation,
1173 PPOpts.DisableStatCache);
1174 if (hasASTConsumer()) {
1175 ModuleManager->setDeserializationListener(
1176 getASTConsumer().GetASTDeserializationListener());
1177 getASTContext().setASTMutationListener(
1178 getASTConsumer().GetASTMutationListener());
1179 }
1180 llvm::OwningPtr<ExternalASTSource> Source;
1181 Source.reset(ModuleManager);
1182 getASTContext().setExternalSource(Source);
1183 if (hasSema())
1184 ModuleManager->InitializeSema(getSema());
1185 if (hasASTConsumer())
1186 ModuleManager->StartTranslationUnit(&getASTConsumer());
Douglas Gregorde8a9052011-09-14 23:13:09 +00001187 }
Douglas Gregor49009ec2011-11-30 04:03:44 +00001188
1189 // Try to load the module we found.
1190 switch (ModuleManager->ReadAST(ModuleFile->getName(),
1191 serialization::MK_Module)) {
1192 case ASTReader::Success:
1193 break;
1194
1195 case ASTReader::IgnorePCH:
1196 // FIXME: The ASTReader will already have complained, but can we showhorn
1197 // that diagnostic information into a more useful form?
Douglas Gregor392ed2b2011-11-30 17:33:56 +00001198 KnownModules[Path[0].first] = 0;
Douglas Gregor49009ec2011-11-30 04:03:44 +00001199 return 0;
1200
1201 case ASTReader::Failure:
Douglas Gregor392ed2b2011-11-30 17:33:56 +00001202 // Already complained, but note now that we failed.
1203 KnownModules[Path[0].first] = 0;
Douglas Gregor49009ec2011-11-30 04:03:44 +00001204 return 0;
1205 }
1206
Douglas Gregor392ed2b2011-11-30 17:33:56 +00001207 if (!Module) {
1208 // If we loaded the module directly, without finding a module map first,
1209 // we'll have loaded the module's information from the module itself.
1210 Module = PP->getHeaderSearchInfo().getModuleMap()
1211 .findModule((Path[0].first->getName()));
1212 }
1213
1214 // Cache the result of this top-level module lookup for later.
1215 Known = KnownModules.insert(std::make_pair(Path[0].first, Module)).first;
Douglas Gregor6aa52ec2011-08-26 23:56:07 +00001216 }
Douglas Gregor49009ec2011-11-30 04:03:44 +00001217
Douglas Gregor392ed2b2011-11-30 17:33:56 +00001218 // If we never found the module, fail.
1219 if (!Module)
1220 return 0;
1221
Douglas Gregor49009ec2011-11-30 04:03:44 +00001222 // Verify that the rest of the module path actually corresponds to
1223 // a submodule.
Douglas Gregor392ed2b2011-11-30 17:33:56 +00001224 if (Path.size() > 1) {
Douglas Gregor49009ec2011-11-30 04:03:44 +00001225 for (unsigned I = 1, N = Path.size(); I != N; ++I) {
1226 StringRef Name = Path[I].first->getName();
Douglas Gregorb7a78192012-01-04 23:32:19 +00001227 clang::Module *Sub = Module->findSubmodule(Name);
Douglas Gregor49009ec2011-11-30 04:03:44 +00001228
Douglas Gregorb7a78192012-01-04 23:32:19 +00001229 if (!Sub) {
Douglas Gregor49009ec2011-11-30 04:03:44 +00001230 // Attempt to perform typo correction to find a module name that works.
1231 llvm::SmallVector<StringRef, 2> Best;
1232 unsigned BestEditDistance = (std::numeric_limits<unsigned>::max)();
1233
Douglas Gregorb7a78192012-01-04 23:32:19 +00001234 for (clang::Module::submodule_iterator J = Module->submodule_begin(),
1235 JEnd = Module->submodule_end();
Matt Beaumont-Gaye25633f2011-11-30 19:41:21 +00001236 J != JEnd; ++J) {
Douglas Gregorb7a78192012-01-04 23:32:19 +00001237 unsigned ED = Name.edit_distance((*J)->Name,
Douglas Gregor49009ec2011-11-30 04:03:44 +00001238 /*AllowReplacements=*/true,
1239 BestEditDistance);
1240 if (ED <= BestEditDistance) {
Douglas Gregorb7a78192012-01-04 23:32:19 +00001241 if (ED < BestEditDistance) {
Douglas Gregor49009ec2011-11-30 04:03:44 +00001242 Best.clear();
Douglas Gregorb7a78192012-01-04 23:32:19 +00001243 BestEditDistance = ED;
1244 }
1245
1246 Best.push_back((*J)->Name);
Douglas Gregor49009ec2011-11-30 04:03:44 +00001247 }
1248 }
1249
1250 // If there was a clear winner, user it.
1251 if (Best.size() == 1) {
1252 getDiagnostics().Report(Path[I].second,
1253 diag::err_no_submodule_suggest)
Douglas Gregor392ed2b2011-11-30 17:33:56 +00001254 << Path[I].first << Module->getFullModuleName() << Best[0]
Douglas Gregor49009ec2011-11-30 04:03:44 +00001255 << SourceRange(Path[0].second, Path[I-1].second)
1256 << FixItHint::CreateReplacement(SourceRange(Path[I].second),
1257 Best[0]);
Douglas Gregorb7a78192012-01-04 23:32:19 +00001258
1259 Sub = Module->findSubmodule(Best[0]);
Douglas Gregor49009ec2011-11-30 04:03:44 +00001260 }
1261 }
1262
Douglas Gregorb7a78192012-01-04 23:32:19 +00001263 if (!Sub) {
Douglas Gregor49009ec2011-11-30 04:03:44 +00001264 // No submodule by this name. Complain, and don't look for further
1265 // submodules.
1266 getDiagnostics().Report(Path[I].second, diag::err_no_submodule)
Douglas Gregor392ed2b2011-11-30 17:33:56 +00001267 << Path[I].first << Module->getFullModuleName()
Douglas Gregor49009ec2011-11-30 04:03:44 +00001268 << SourceRange(Path[0].second, Path[I-1].second);
1269 break;
1270 }
1271
Douglas Gregorb7a78192012-01-04 23:32:19 +00001272 Module = Sub;
Douglas Gregor49009ec2011-11-30 04:03:44 +00001273 }
Douglas Gregor6aa52ec2011-08-26 23:56:07 +00001274 }
Douglas Gregor49009ec2011-11-30 04:03:44 +00001275
Douglas Gregor5e3f9222011-12-08 17:01:29 +00001276 // Make the named module visible, if it's not already part of the module
1277 // we are parsing.
Douglas Gregor305dc3e2011-12-20 00:28:52 +00001278 if (ModuleName != getLangOpts().CurrentModule) {
1279 if (!Module->IsFromModuleFile) {
1280 // We have an umbrella header or directory that doesn't actually include
1281 // all of the headers within the directory it covers. Complain about
1282 // this missing submodule and recover by forgetting that we ever saw
1283 // this submodule.
1284 // FIXME: Should we detect this at module load time? It seems fairly
1285 // expensive (and rare).
1286 getDiagnostics().Report(ImportLoc, diag::warn_missing_submodule)
1287 << Module->getFullModuleName()
1288 << SourceRange(Path.front().second, Path.back().second);
1289
1290 return 0;
1291 }
Douglas Gregor51f564f2011-12-31 04:05:44 +00001292
1293 // Check whether this module is available.
1294 StringRef Feature;
1295 if (!Module->isAvailable(getLangOpts(), Feature)) {
1296 getDiagnostics().Report(ImportLoc, diag::err_module_unavailable)
1297 << Module->getFullModuleName()
1298 << Feature
1299 << SourceRange(Path.front().second, Path.back().second);
1300 LastModuleImportLoc = ImportLoc;
1301 LastModuleImportResult = 0;
1302 return 0;
1303 }
1304
Douglas Gregor5e3f9222011-12-08 17:01:29 +00001305 ModuleManager->makeModuleVisible(Module, Visibility);
Douglas Gregor305dc3e2011-12-20 00:28:52 +00001306 }
1307
Douglas Gregor93ebfa62011-12-02 23:42:12 +00001308 // If this module import was due to an inclusion directive, create an
1309 // implicit import declaration to capture it in the AST.
1310 if (IsInclusionDirective && hasASTContext()) {
1311 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
1312 TU->addDecl(ImportDecl::CreateImplicit(getASTContext(), TU,
1313 ImportLoc, Module,
1314 Path.back().second));
1315 }
Douglas Gregor49009ec2011-11-30 04:03:44 +00001316
Douglas Gregorb514c792011-11-30 04:26:53 +00001317 LastModuleImportLoc = ImportLoc;
Douglas Gregor392ed2b2011-11-30 17:33:56 +00001318 LastModuleImportResult = Module;
1319 return Module;
Douglas Gregor6aa52ec2011-08-26 23:56:07 +00001320}