blob: c2cbeacc021c73966d19601829b2b7fab33ad6dc [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"
Daniel Dunbar2a79e162009-11-13 03:51:44 +000044using namespace clang;
45
Daniel Dunbar42e9f8e42010-02-16 01:54:47 +000046CompilerInstance::CompilerInstance()
Douglas Gregorf62d43d2011-07-19 16:10:42 +000047 : Invocation(new CompilerInvocation()), ModuleManager(0) {
Daniel Dunbar6228ca02010-01-30 21:47:07 +000048}
Daniel Dunbar2a79e162009-11-13 03:51:44 +000049
50CompilerInstance::~CompilerInstance() {
Daniel Dunbar42e9f8e42010-02-16 01:54:47 +000051}
52
Daniel Dunbar6228ca02010-01-30 21:47:07 +000053void CompilerInstance::setInvocation(CompilerInvocation *Value) {
Ted Kremenek4f327862011-03-21 18:40:17 +000054 Invocation = Value;
Daniel Dunbar6228ca02010-01-30 21:47:07 +000055}
56
David Blaikied6471f72011-09-25 23:23:43 +000057void CompilerInstance::setDiagnostics(DiagnosticsEngine *Value) {
Douglas Gregor28019772010-04-05 23:52:57 +000058 Diagnostics = Value;
Daniel Dunbar8a9f5692009-11-14 01:20:40 +000059}
60
Daniel Dunbar8a9f5692009-11-14 01:20:40 +000061void CompilerInstance::setTarget(TargetInfo *Value) {
Ted Kremenek4f327862011-03-21 18:40:17 +000062 Target = Value;
Daniel Dunbar8a9f5692009-11-14 01:20:40 +000063}
64
65void CompilerInstance::setFileManager(FileManager *Value) {
Ted Kremenek4f327862011-03-21 18:40:17 +000066 FileMgr = Value;
Daniel Dunbar8a9f5692009-11-14 01:20:40 +000067}
68
Ted Kremenek4f327862011-03-21 18:40:17 +000069void CompilerInstance::setSourceManager(SourceManager *Value) {
70 SourceMgr = Value;
Daniel Dunbar8a9f5692009-11-14 01:20:40 +000071}
72
Ted Kremenek4f327862011-03-21 18:40:17 +000073void CompilerInstance::setPreprocessor(Preprocessor *Value) { PP = Value; }
Daniel Dunbar8a9f5692009-11-14 01:20:40 +000074
Ted Kremenek4f327862011-03-21 18:40:17 +000075void CompilerInstance::setASTContext(ASTContext *Value) { Context = Value; }
Daniel Dunbar8a9f5692009-11-14 01:20:40 +000076
Douglas Gregorf18d0d82010-08-12 23:31:19 +000077void CompilerInstance::setSema(Sema *S) {
78 TheSema.reset(S);
79}
80
Daniel Dunbar12ce6942009-11-14 02:47:17 +000081void CompilerInstance::setASTConsumer(ASTConsumer *Value) {
82 Consumer.reset(Value);
83}
84
Daniel Dunbar8a9f5692009-11-14 01:20:40 +000085void CompilerInstance::setCodeCompletionConsumer(CodeCompleteConsumer *Value) {
86 CompletionConsumer.reset(Value);
87}
88
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +000089// Diagnostics
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +000090static void SetUpBuildDumpLog(const DiagnosticOptions &DiagOpts,
Axel Naumann7d0c4cc2010-10-11 09:13:46 +000091 unsigned argc, const char* const *argv,
David Blaikied6471f72011-09-25 23:23:43 +000092 DiagnosticsEngine &Diags) {
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +000093 std::string ErrorInfo;
Chris Lattner5f9e2722011-07-23 10:55:15 +000094 llvm::OwningPtr<raw_ostream> OS(
Kovarththanan Rajaratnam69247132010-03-17 09:47:30 +000095 new llvm::raw_fd_ostream(DiagOpts.DumpBuildInformation.c_str(), ErrorInfo));
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +000096 if (!ErrorInfo.empty()) {
Kovarththanan Rajaratnam3d67b1e2010-03-17 09:24:48 +000097 Diags.Report(diag::err_fe_unable_to_open_logfile)
98 << DiagOpts.DumpBuildInformation << ErrorInfo;
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +000099 return;
100 }
101
Daniel Dunbardd63b282009-12-11 23:04:35 +0000102 (*OS) << "clang -cc1 command line arguments: ";
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000103 for (unsigned i = 0; i != argc; ++i)
104 (*OS) << argv[i] << ' ';
105 (*OS) << '\n';
106
107 // Chain in a diagnostic client which will log the diagnostics.
David Blaikie78ad0b92011-09-25 23:39:51 +0000108 DiagnosticConsumer *Logger =
Kovarththanan Rajaratnam69247132010-03-17 09:47:30 +0000109 new TextDiagnosticPrinter(*OS.take(), DiagOpts, /*OwnsOutputStream=*/true);
David Blaikie4e85b8a2011-09-26 00:21:47 +0000110 Diags.setClient(new ChainedDiagnosticConsumer(Diags.takeClient(), Logger));
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000111}
112
Daniel Dunbar9df23492011-04-07 18:31:10 +0000113static void SetUpDiagnosticLog(const DiagnosticOptions &DiagOpts,
Daniel Dunbarb6534bb2011-04-07 18:59:02 +0000114 const CodeGenOptions *CodeGenOpts,
David Blaikied6471f72011-09-25 23:23:43 +0000115 DiagnosticsEngine &Diags) {
Daniel Dunbar9df23492011-04-07 18:31:10 +0000116 std::string ErrorInfo;
117 bool OwnsStream = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000118 raw_ostream *OS = &llvm::errs();
Daniel Dunbar9df23492011-04-07 18:31:10 +0000119 if (DiagOpts.DiagnosticLogFile != "-") {
120 // Create the output stream.
121 llvm::raw_fd_ostream *FileOS(
122 new llvm::raw_fd_ostream(DiagOpts.DiagnosticLogFile.c_str(),
Daniel Dunbare01eceb2011-04-07 20:19:21 +0000123 ErrorInfo, llvm::raw_fd_ostream::F_Append));
Daniel Dunbar9df23492011-04-07 18:31:10 +0000124 if (!ErrorInfo.empty()) {
125 Diags.Report(diag::warn_fe_cc_log_diagnostics_failure)
126 << DiagOpts.DumpBuildInformation << ErrorInfo;
127 } else {
128 FileOS->SetUnbuffered();
129 FileOS->SetUseAtomicWrites(true);
130 OS = FileOS;
131 OwnsStream = true;
132 }
133 }
134
135 // Chain in the diagnostic client which will log the diagnostics.
Daniel Dunbarb6534bb2011-04-07 18:59:02 +0000136 LogDiagnosticPrinter *Logger = new LogDiagnosticPrinter(*OS, DiagOpts,
137 OwnsStream);
138 if (CodeGenOpts)
139 Logger->setDwarfDebugFlags(CodeGenOpts->DwarfDebugFlags);
David Blaikie4e85b8a2011-09-26 00:21:47 +0000140 Diags.setClient(new ChainedDiagnosticConsumer(Diags.takeClient(), Logger));
Daniel Dunbar9df23492011-04-07 18:31:10 +0000141}
142
Douglas Gregore47be3e2010-11-11 00:39:14 +0000143void CompilerInstance::createDiagnostics(int Argc, const char* const *Argv,
David Blaikie78ad0b92011-09-25 23:39:51 +0000144 DiagnosticConsumer *Client,
Douglas Gregoraee526e2011-09-29 00:38:00 +0000145 bool ShouldOwnClient,
146 bool ShouldCloneClient) {
Daniel Dunbarb6534bb2011-04-07 18:59:02 +0000147 Diagnostics = createDiagnostics(getDiagnosticOpts(), Argc, Argv, Client,
Douglas Gregoraee526e2011-09-29 00:38:00 +0000148 ShouldOwnClient, ShouldCloneClient,
149 &getCodeGenOpts());
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000150}
151
David Blaikied6471f72011-09-25 23:23:43 +0000152llvm::IntrusiveRefCntPtr<DiagnosticsEngine>
Douglas Gregor28019772010-04-05 23:52:57 +0000153CompilerInstance::createDiagnostics(const DiagnosticOptions &Opts,
Douglas Gregore47be3e2010-11-11 00:39:14 +0000154 int Argc, const char* const *Argv,
David Blaikie78ad0b92011-09-25 23:39:51 +0000155 DiagnosticConsumer *Client,
Douglas Gregor78243652011-09-13 01:26:44 +0000156 bool ShouldOwnClient,
Douglas Gregoraee526e2011-09-29 00:38:00 +0000157 bool ShouldCloneClient,
Daniel Dunbarb6534bb2011-04-07 18:59:02 +0000158 const CodeGenOptions *CodeGenOpts) {
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000159 llvm::IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
David Blaikied6471f72011-09-25 23:23:43 +0000160 llvm::IntrusiveRefCntPtr<DiagnosticsEngine>
161 Diags(new DiagnosticsEngine(DiagID));
Daniel Dunbar221c7212009-11-14 07:53:24 +0000162
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000163 // Create the diagnostic client for reporting errors or for
164 // implementing -verify.
Douglas Gregoraee526e2011-09-29 00:38:00 +0000165 if (Client) {
166 if (ShouldCloneClient)
167 Diags->setClient(Client->clone(*Diags), ShouldOwnClient);
168 else
169 Diags->setClient(Client, ShouldOwnClient);
170 } else
Douglas Gregore47be3e2010-11-11 00:39:14 +0000171 Diags->setClient(new TextDiagnosticPrinter(llvm::errs(), Opts));
Daniel Dunbarf79dced2009-11-14 03:24:39 +0000172
173 // Chain in -verify checker, if requested.
Douglas Gregor78243652011-09-13 01:26:44 +0000174 if (Opts.VerifyDiagnostics)
David Blaikie621bc692011-09-26 00:38:03 +0000175 Diags->setClient(new VerifyDiagnosticConsumer(*Diags));
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000176
Daniel Dunbar9df23492011-04-07 18:31:10 +0000177 // Chain in -diagnostic-log-file dumper, if requested.
178 if (!Opts.DiagnosticLogFile.empty())
Daniel Dunbarb6534bb2011-04-07 18:59:02 +0000179 SetUpDiagnosticLog(Opts, CodeGenOpts, *Diags);
Daniel Dunbar9df23492011-04-07 18:31:10 +0000180
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000181 if (!Opts.DumpBuildInformation.empty())
Kovarththanan Rajaratnam3d67b1e2010-03-17 09:24:48 +0000182 SetUpBuildDumpLog(Opts, Argc, Argv, *Diags);
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000183
184 // Configure our handling of diagnostics.
Kovarththanan Rajaratnam5bf932b2010-03-17 09:36:02 +0000185 ProcessWarningOptions(*Diags, Opts);
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000186
Douglas Gregor28019772010-04-05 23:52:57 +0000187 return Diags;
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000188}
189
190// File Manager
191
Daniel Dunbar16b74492009-11-13 04:12:06 +0000192void CompilerInstance::createFileManager() {
Ted Kremenek4f327862011-03-21 18:40:17 +0000193 FileMgr = new FileManager(getFileSystemOpts());
Daniel Dunbar16b74492009-11-13 04:12:06 +0000194}
195
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000196// Source Manager
197
Chris Lattner39b49bc2010-11-23 08:35:12 +0000198void CompilerInstance::createSourceManager(FileManager &FileMgr) {
Ted Kremenek4f327862011-03-21 18:40:17 +0000199 SourceMgr = new SourceManager(getDiagnostics(), FileMgr);
Daniel Dunbar16b74492009-11-13 04:12:06 +0000200}
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000201
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000202// Preprocessor
203
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000204void CompilerInstance::createPreprocessor() {
Douglas Gregor6aa52ec2011-08-26 23:56:07 +0000205 const PreprocessorOptions &PPOpts = getPreprocessorOpts();
206
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000207 // Create a PTH manager if we are using some form of a token cache.
208 PTHManager *PTHMgr = 0;
Daniel Dunbar049d3a02009-11-17 05:52:41 +0000209 if (!PPOpts.TokenCache.empty())
Douglas Gregor6aa52ec2011-08-26 23:56:07 +0000210 PTHMgr = PTHManager::Create(PPOpts.TokenCache, getDiagnostics());
211
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000212 // Create the Preprocessor.
Douglas Gregor6aa52ec2011-08-26 23:56:07 +0000213 HeaderSearch *HeaderInfo = new HeaderSearch(getFileManager());
Douglas Gregor998b3d32011-09-01 23:39:15 +0000214 PP = new Preprocessor(getDiagnostics(), getLangOpts(), &getTarget(),
Douglas Gregor6aa52ec2011-08-26 23:56:07 +0000215 getSourceManager(), *HeaderInfo, *this, PTHMgr,
216 /*OwnsHeaderSearch=*/true);
217
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000218 // Note that this is different then passing PTHMgr to Preprocessor's ctor.
219 // That argument is used as the IdentifierInfoLookup argument to
220 // IdentifierTable's ctor.
221 if (PTHMgr) {
Douglas Gregor6aa52ec2011-08-26 23:56:07 +0000222 PTHMgr->setPreprocessor(&*PP);
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000223 PP->setPTHManager(PTHMgr);
224 }
Douglas Gregor6aa52ec2011-08-26 23:56:07 +0000225
Douglas Gregor94dc8f62010-03-19 16:15:56 +0000226 if (PPOpts.DetailedRecord)
Douglas Gregordca8ee82011-05-06 16:33:08 +0000227 PP->createPreprocessingRecord(
Douglas Gregor6aa52ec2011-08-26 23:56:07 +0000228 PPOpts.DetailedRecordIncludesNestedMacroExpansions);
Douglas Gregor94dc8f62010-03-19 16:15:56 +0000229
Douglas Gregor6aa52ec2011-08-26 23:56:07 +0000230 InitializePreprocessor(*PP, PPOpts, getHeaderSearchOpts(), getFrontendOpts());
231
Douglas Gregor6e975c42011-09-13 23:15:45 +0000232 // Set up the module path, including the hash for the
233 // module-creation options.
234 llvm::SmallString<256> SpecificModuleCache(
235 getHeaderSearchOpts().ModuleCachePath);
236 if (!getHeaderSearchOpts().DisableModuleHash)
237 llvm::sys::path::append(SpecificModuleCache,
238 getInvocation().getModuleHash());
Douglas Gregorfba18aa2011-09-15 22:00:41 +0000239 PP->getHeaderSearchInfo().configureModules(SpecificModuleCache,
240 getPreprocessorOpts().ModuleBuildPath.empty()
241 ? std::string()
242 : getPreprocessorOpts().ModuleBuildPath.back());
Douglas Gregor6e975c42011-09-13 23:15:45 +0000243
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000244 // Handle generating dependencies, if requested.
Douglas Gregor6aa52ec2011-08-26 23:56:07 +0000245 const DependencyOutputOptions &DepOpts = getDependencyOutputOpts();
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000246 if (!DepOpts.OutputFile.empty())
247 AttachDependencyFileGen(*PP, DepOpts);
Douglas Gregor6aa52ec2011-08-26 23:56:07 +0000248
Daniel Dunbareef63e02011-02-02 15:41:17 +0000249 // Handle generating header include information, if requested.
250 if (DepOpts.ShowHeaderIncludes)
251 AttachHeaderIncludeGen(*PP);
Daniel Dunbarb34d69b2011-02-02 21:11:31 +0000252 if (!DepOpts.HeaderIncludeOutputFile.empty()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000253 StringRef OutputPath = DepOpts.HeaderIncludeOutputFile;
Daniel Dunbarb34d69b2011-02-02 21:11:31 +0000254 if (OutputPath == "-")
255 OutputPath = "";
Daniel Dunbarda608852011-03-21 19:37:38 +0000256 AttachHeaderIncludeGen(*PP, /*ShowAllHeaders=*/true, OutputPath,
257 /*ShowDepth=*/false);
Daniel Dunbarb34d69b2011-02-02 21:11:31 +0000258 }
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000259}
Daniel Dunbar5eb81002009-11-13 08:20:47 +0000260
261// ASTContext
262
263void CompilerInstance::createASTContext() {
264 Preprocessor &PP = getPreprocessor();
Ted Kremenek4f327862011-03-21 18:40:17 +0000265 Context = new ASTContext(getLangOpts(), PP.getSourceManager(),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000266 &getTarget(), PP.getIdentifierTable(),
Ted Kremenek4f327862011-03-21 18:40:17 +0000267 PP.getSelectorTable(), PP.getBuiltinInfo(),
268 /*size_reserve=*/ 0);
Daniel Dunbar5eb81002009-11-13 08:20:47 +0000269}
Daniel Dunbar0f800392009-11-13 08:21:10 +0000270
271// ExternalASTSource
272
Chris Lattner5f9e2722011-07-23 10:55:15 +0000273void CompilerInstance::createPCHExternalASTSource(StringRef Path,
Sebastian Redlffaab3e2010-07-30 00:29:29 +0000274 bool DisablePCHValidation,
Douglas Gregor8ef6c8c2011-02-05 19:42:43 +0000275 bool DisableStatCache,
Sebastian Redlffaab3e2010-07-30 00:29:29 +0000276 void *DeserializationListener){
Daniel Dunbar0f800392009-11-13 08:21:10 +0000277 llvm::OwningPtr<ExternalASTSource> Source;
Sebastian Redl1d9f1fe2010-10-05 16:15:19 +0000278 bool Preamble = getPreprocessorOpts().PrecompiledPreambleBytes.first != 0;
Daniel Dunbar0f800392009-11-13 08:21:10 +0000279 Source.reset(createPCHExternalASTSource(Path, getHeaderSearchOpts().Sysroot,
Douglas Gregor8ef6c8c2011-02-05 19:42:43 +0000280 DisablePCHValidation,
281 DisableStatCache,
Sebastian Redlffaab3e2010-07-30 00:29:29 +0000282 getPreprocessor(), getASTContext(),
Sebastian Redl1d9f1fe2010-10-05 16:15:19 +0000283 DeserializationListener,
284 Preamble));
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000285 ModuleManager = static_cast<ASTReader*>(Source.get());
Daniel Dunbar0f800392009-11-13 08:21:10 +0000286 getASTContext().setExternalSource(Source);
287}
288
289ExternalASTSource *
Chris Lattner5f9e2722011-07-23 10:55:15 +0000290CompilerInstance::createPCHExternalASTSource(StringRef Path,
Daniel Dunbar0f800392009-11-13 08:21:10 +0000291 const std::string &Sysroot,
Douglas Gregorfae3b2f2010-07-27 00:27:13 +0000292 bool DisablePCHValidation,
Douglas Gregor8ef6c8c2011-02-05 19:42:43 +0000293 bool DisableStatCache,
Daniel Dunbar0f800392009-11-13 08:21:10 +0000294 Preprocessor &PP,
Sebastian Redlffaab3e2010-07-30 00:29:29 +0000295 ASTContext &Context,
Sebastian Redl1d9f1fe2010-10-05 16:15:19 +0000296 void *DeserializationListener,
297 bool Preamble) {
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000298 llvm::OwningPtr<ASTReader> Reader;
Douglas Gregorf8a1e512011-09-02 00:26:20 +0000299 Reader.reset(new ASTReader(PP, Context,
Douglas Gregor832d6202011-07-22 16:35:34 +0000300 Sysroot.empty() ? "" : Sysroot.c_str(),
Douglas Gregor8ef6c8c2011-02-05 19:42:43 +0000301 DisablePCHValidation, DisableStatCache));
Daniel Dunbar0f800392009-11-13 08:21:10 +0000302
Sebastian Redlffaab3e2010-07-30 00:29:29 +0000303 Reader->setDeserializationListener(
Sebastian Redl571db7f2010-08-18 23:56:56 +0000304 static_cast<ASTDeserializationListener *>(DeserializationListener));
Douglas Gregor72a9ae12011-07-22 16:00:58 +0000305 switch (Reader->ReadAST(Path,
306 Preamble ? serialization::MK_Preamble
307 : serialization::MK_PCH)) {
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000308 case ASTReader::Success:
Daniel Dunbar0f800392009-11-13 08:21:10 +0000309 // Set the predefines buffer as suggested by the PCH reader. Typically, the
310 // predefines buffer will be empty.
311 PP.setPredefines(Reader->getSuggestedPredefines());
312 return Reader.take();
313
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000314 case ASTReader::Failure:
Daniel Dunbar0f800392009-11-13 08:21:10 +0000315 // Unrecoverable failure: don't even try to process the input file.
316 break;
317
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000318 case ASTReader::IgnorePCH:
Daniel Dunbar0f800392009-11-13 08:21:10 +0000319 // No suitable PCH file could be found. Return an error.
320 break;
321 }
322
323 return 0;
324}
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000325
326// Code Completion
327
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000328static bool EnableCodeCompletion(Preprocessor &PP,
329 const std::string &Filename,
330 unsigned Line,
331 unsigned Column) {
332 // Tell the source manager to chop off the given file at a specific
333 // line and column.
Chris Lattner39b49bc2010-11-23 08:35:12 +0000334 const FileEntry *Entry = PP.getFileManager().getFile(Filename);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000335 if (!Entry) {
336 PP.getDiagnostics().Report(diag::err_fe_invalid_code_complete_file)
337 << Filename;
338 return true;
339 }
340
341 // Truncate the named file at the given line/column.
342 PP.SetCodeCompletionPoint(Entry, Line, Column);
343 return false;
344}
345
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000346void CompilerInstance::createCodeCompletionConsumer() {
347 const ParsedSourceLocation &Loc = getFrontendOpts().CodeCompletionAt;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000348 if (!CompletionConsumer) {
349 CompletionConsumer.reset(
350 createCodeCompletionConsumer(getPreprocessor(),
351 Loc.FileName, Loc.Line, Loc.Column,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000352 getFrontendOpts().ShowMacrosInCodeCompletion,
Douglas Gregord8e8a582010-05-25 21:41:55 +0000353 getFrontendOpts().ShowCodePatternsInCodeCompletion,
Douglas Gregor8071e422010-08-15 06:18:01 +0000354 getFrontendOpts().ShowGlobalSymbolsInCodeCompletion,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000355 llvm::outs()));
356 if (!CompletionConsumer)
357 return;
358 } else if (EnableCodeCompletion(getPreprocessor(), Loc.FileName,
359 Loc.Line, Loc.Column)) {
360 CompletionConsumer.reset();
Douglas Gregorc3d43b72010-03-16 06:04:47 +0000361 return;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000362 }
Douglas Gregor2b4074f2009-12-01 05:55:20 +0000363
364 if (CompletionConsumer->isOutputBinary() &&
365 llvm::sys::Program::ChangeStdoutToBinary()) {
366 getPreprocessor().getDiagnostics().Report(diag::err_fe_stdout_binary);
367 CompletionConsumer.reset();
368 }
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000369}
370
Kovarththanan Rajaratnamf79bafa2009-11-29 09:57:35 +0000371void CompilerInstance::createFrontendTimer() {
372 FrontendTimer.reset(new llvm::Timer("Clang front-end timer"));
373}
374
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000375CodeCompleteConsumer *
376CompilerInstance::createCodeCompletionConsumer(Preprocessor &PP,
377 const std::string &Filename,
378 unsigned Line,
379 unsigned Column,
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000380 bool ShowMacros,
Douglas Gregord8e8a582010-05-25 21:41:55 +0000381 bool ShowCodePatterns,
Douglas Gregor8071e422010-08-15 06:18:01 +0000382 bool ShowGlobals,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000383 raw_ostream &OS) {
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000384 if (EnableCodeCompletion(PP, Filename, Line, Column))
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000385 return 0;
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000386
387 // Set up the creation routine for code-completion.
Douglas Gregora9f4f622010-10-11 22:12:15 +0000388 return new PrintingCodeCompleteConsumer(ShowMacros, ShowCodePatterns,
Douglas Gregor8071e422010-08-15 06:18:01 +0000389 ShowGlobals, OS);
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000390}
Daniel Dunbara9204832009-11-13 10:37:48 +0000391
Douglas Gregor467dc882011-08-25 22:30:56 +0000392void CompilerInstance::createSema(TranslationUnitKind TUKind,
Douglas Gregorf18d0d82010-08-12 23:31:19 +0000393 CodeCompleteConsumer *CompletionConsumer) {
394 TheSema.reset(new Sema(getPreprocessor(), getASTContext(), getASTConsumer(),
Douglas Gregor467dc882011-08-25 22:30:56 +0000395 TUKind, CompletionConsumer));
Douglas Gregorf18d0d82010-08-12 23:31:19 +0000396}
397
Daniel Dunbara9204832009-11-13 10:37:48 +0000398// Output Files
399
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000400void CompilerInstance::addOutputFile(const OutputFile &OutFile) {
401 assert(OutFile.OS && "Attempt to add empty stream to output list!");
402 OutputFiles.push_back(OutFile);
Daniel Dunbara9204832009-11-13 10:37:48 +0000403}
404
Kovarththanan Rajaratname51dd7b2010-03-06 12:07:48 +0000405void CompilerInstance::clearOutputFiles(bool EraseFiles) {
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000406 for (std::list<OutputFile>::iterator
Daniel Dunbara9204832009-11-13 10:37:48 +0000407 it = OutputFiles.begin(), ie = OutputFiles.end(); it != ie; ++it) {
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000408 delete it->OS;
409 if (!it->TempFilename.empty()) {
Anders Carlssonaf036a62011-03-06 22:25:35 +0000410 if (EraseFiles) {
411 bool existed;
412 llvm::sys::fs::remove(it->TempFilename, existed);
413 } else {
414 llvm::SmallString<128> NewOutFile(it->Filename);
415
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +0000416 // If '-working-directory' was passed, the output filename should be
417 // relative to that.
Anders Carlsson2e2468e2011-03-14 01:13:54 +0000418 FileMgr->FixupRelativePath(NewOutFile);
Anders Carlssonaf036a62011-03-06 22:25:35 +0000419 if (llvm::error_code ec = llvm::sys::fs::rename(it->TempFilename,
420 NewOutFile.str())) {
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000421 getDiagnostics().Report(diag::err_fe_unable_to_rename_temp)
Anders Carlssonaf036a62011-03-06 22:25:35 +0000422 << it->TempFilename << it->Filename << ec.message();
423
424 bool existed;
425 llvm::sys::fs::remove(it->TempFilename, existed);
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000426 }
427 }
428 } else if (!it->Filename.empty() && EraseFiles)
429 llvm::sys::Path(it->Filename).eraseFromDisk();
430
Daniel Dunbara9204832009-11-13 10:37:48 +0000431 }
432 OutputFiles.clear();
433}
434
Daniel Dunbarf482d592009-11-13 18:32:08 +0000435llvm::raw_fd_ostream *
436CompilerInstance::createDefaultOutputFile(bool Binary,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000437 StringRef InFile,
438 StringRef Extension) {
Daniel Dunbarf482d592009-11-13 18:32:08 +0000439 return createOutputFile(getFrontendOpts().OutputFile, Binary,
Daniel Dunbarff9cd962011-01-31 22:00:42 +0000440 /*RemoveFileOnSignal=*/true, InFile, Extension);
Daniel Dunbarf482d592009-11-13 18:32:08 +0000441}
442
443llvm::raw_fd_ostream *
Chris Lattner5f9e2722011-07-23 10:55:15 +0000444CompilerInstance::createOutputFile(StringRef OutputPath,
Daniel Dunbarff9cd962011-01-31 22:00:42 +0000445 bool Binary, bool RemoveFileOnSignal,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000446 StringRef InFile,
Argyrios Kyrtzidis7e909852011-07-28 00:45:10 +0000447 StringRef Extension,
448 bool UseTemporary) {
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000449 std::string Error, OutputPathName, TempPathName;
Daniel Dunbarf482d592009-11-13 18:32:08 +0000450 llvm::raw_fd_ostream *OS = createOutputFile(OutputPath, Error, Binary,
Daniel Dunbarff9cd962011-01-31 22:00:42 +0000451 RemoveFileOnSignal,
Daniel Dunbarf482d592009-11-13 18:32:08 +0000452 InFile, Extension,
Argyrios Kyrtzidis7e909852011-07-28 00:45:10 +0000453 UseTemporary,
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000454 &OutputPathName,
455 &TempPathName);
Daniel Dunbarf482d592009-11-13 18:32:08 +0000456 if (!OS) {
Daniel Dunbar36043592009-12-03 09:13:30 +0000457 getDiagnostics().Report(diag::err_fe_unable_to_open_output)
458 << OutputPath << Error;
459 return 0;
Daniel Dunbarf482d592009-11-13 18:32:08 +0000460 }
461
462 // Add the output file -- but don't try to remove "-", since this means we are
463 // using stdin.
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000464 addOutputFile(OutputFile((OutputPathName != "-") ? OutputPathName : "",
465 TempPathName, OS));
Daniel Dunbarf482d592009-11-13 18:32:08 +0000466
467 return OS;
468}
469
470llvm::raw_fd_ostream *
Chris Lattner5f9e2722011-07-23 10:55:15 +0000471CompilerInstance::createOutputFile(StringRef OutputPath,
Daniel Dunbarf482d592009-11-13 18:32:08 +0000472 std::string &Error,
473 bool Binary,
Daniel Dunbarff9cd962011-01-31 22:00:42 +0000474 bool RemoveFileOnSignal,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000475 StringRef InFile,
476 StringRef Extension,
Argyrios Kyrtzidis7e909852011-07-28 00:45:10 +0000477 bool UseTemporary,
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000478 std::string *ResultPathName,
479 std::string *TempPathName) {
480 std::string OutFile, TempFile;
Daniel Dunbarf482d592009-11-13 18:32:08 +0000481 if (!OutputPath.empty()) {
482 OutFile = OutputPath;
483 } else if (InFile == "-") {
484 OutFile = "-";
485 } else if (!Extension.empty()) {
486 llvm::sys::Path Path(InFile);
487 Path.eraseSuffix();
488 Path.appendSuffix(Extension);
489 OutFile = Path.str();
490 } else {
491 OutFile = "-";
492 }
Argyrios Kyrtzidis7e909852011-07-28 00:45:10 +0000493
494 llvm::OwningPtr<llvm::raw_fd_ostream> OS;
495 std::string OSFile;
496
497 if (UseTemporary && OutFile != "-") {
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000498 llvm::sys::Path OutPath(OutFile);
499 // Only create the temporary if we can actually write to OutPath, otherwise
500 // we want to fail early.
Michael J. Spencer32bef4e2011-01-10 02:34:13 +0000501 bool Exists;
502 if ((llvm::sys::fs::exists(OutPath.str(), Exists) || !Exists) ||
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000503 (OutPath.isRegularFile() && OutPath.canWrite())) {
504 // Create a temporary file.
Argyrios Kyrtzidis7e909852011-07-28 00:45:10 +0000505 llvm::SmallString<128> TempPath;
506 TempPath = OutFile;
507 TempPath += "-%%%%%%%%";
508 int fd;
509 if (llvm::sys::fs::unique_file(TempPath.str(), fd, TempPath,
510 /*makeAbsolute=*/false) == llvm::errc::success) {
511 OS.reset(new llvm::raw_fd_ostream(fd, /*shouldClose=*/true));
512 OSFile = TempFile = TempPath.str();
513 }
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000514 }
515 }
516
Argyrios Kyrtzidis7e909852011-07-28 00:45:10 +0000517 if (!OS) {
518 OSFile = OutFile;
519 OS.reset(
520 new llvm::raw_fd_ostream(OSFile.c_str(), Error,
521 (Binary ? llvm::raw_fd_ostream::F_Binary : 0)));
522 if (!Error.empty())
523 return 0;
524 }
Daniel Dunbarf482d592009-11-13 18:32:08 +0000525
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000526 // Make sure the out stream file gets removed if we crash.
Daniel Dunbarff9cd962011-01-31 22:00:42 +0000527 if (RemoveFileOnSignal)
528 llvm::sys::RemoveFileOnSignal(llvm::sys::Path(OSFile));
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000529
Daniel Dunbarf482d592009-11-13 18:32:08 +0000530 if (ResultPathName)
531 *ResultPathName = OutFile;
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000532 if (TempPathName)
533 *TempPathName = TempFile;
Daniel Dunbarf482d592009-11-13 18:32:08 +0000534
Daniel Dunbarfc971022009-11-20 22:32:38 +0000535 return OS.take();
Daniel Dunbarf482d592009-11-13 18:32:08 +0000536}
Daniel Dunbarccb6cb62009-11-14 07:53:04 +0000537
538// Initialization Utilities
539
Chris Lattner5f9e2722011-07-23 10:55:15 +0000540bool CompilerInstance::InitializeSourceManager(StringRef InputFile) {
Daniel Dunbarccb6cb62009-11-14 07:53:04 +0000541 return InitializeSourceManager(InputFile, getDiagnostics(), getFileManager(),
542 getSourceManager(), getFrontendOpts());
543}
544
Chris Lattner5f9e2722011-07-23 10:55:15 +0000545bool CompilerInstance::InitializeSourceManager(StringRef InputFile,
David Blaikied6471f72011-09-25 23:23:43 +0000546 DiagnosticsEngine &Diags,
Daniel Dunbarccb6cb62009-11-14 07:53:04 +0000547 FileManager &FileMgr,
548 SourceManager &SourceMgr,
549 const FrontendOptions &Opts) {
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +0000550 // Figure out where to get and map in the main file.
551 if (InputFile != "-") {
Chris Lattner39b49bc2010-11-23 08:35:12 +0000552 const FileEntry *File = FileMgr.getFile(InputFile);
Dan Gohman694137c2010-10-26 21:13:51 +0000553 if (!File) {
Daniel Dunbarccb6cb62009-11-14 07:53:04 +0000554 Diags.Report(diag::err_fe_error_reading) << InputFile;
555 return false;
556 }
Dan Gohman694137c2010-10-26 21:13:51 +0000557 SourceMgr.createMainFileID(File);
Daniel Dunbarccb6cb62009-11-14 07:53:04 +0000558 } else {
Michael J. Spencer4eeebc42010-12-16 03:28:14 +0000559 llvm::OwningPtr<llvm::MemoryBuffer> SB;
560 if (llvm::MemoryBuffer::getSTDIN(SB)) {
Michael J. Spencer3a321e22010-12-09 17:36:38 +0000561 // FIXME: Give ec.message() in this diag.
Daniel Dunbarccb6cb62009-11-14 07:53:04 +0000562 Diags.Report(diag::err_fe_error_reading_stdin);
563 return false;
564 }
Dan Gohman90d90812010-10-26 23:21:25 +0000565 const FileEntry *File = FileMgr.getVirtualFile(SB->getBufferIdentifier(),
Chris Lattner39b49bc2010-11-23 08:35:12 +0000566 SB->getBufferSize(), 0);
Dan Gohman90d90812010-10-26 23:21:25 +0000567 SourceMgr.createMainFileID(File);
Michael J. Spencer4eeebc42010-12-16 03:28:14 +0000568 SourceMgr.overrideFileContents(File, SB.take());
Daniel Dunbarccb6cb62009-11-14 07:53:04 +0000569 }
570
Dan Gohman694137c2010-10-26 21:13:51 +0000571 assert(!SourceMgr.getMainFileID().isInvalid() &&
572 "Couldn't establish MainFileID!");
Daniel Dunbarccb6cb62009-11-14 07:53:04 +0000573 return true;
574}
Daniel Dunbar0397af22010-01-13 00:48:06 +0000575
576// High-Level Operations
577
578bool CompilerInstance::ExecuteAction(FrontendAction &Act) {
579 assert(hasDiagnostics() && "Diagnostics engine is not initialized!");
580 assert(!getFrontendOpts().ShowHelp && "Client must handle '-help'!");
581 assert(!getFrontendOpts().ShowVersion && "Client must handle '-version'!");
582
583 // FIXME: Take this as an argument, once all the APIs we used have moved to
584 // taking it as an input instead of hard-coding llvm::errs.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000585 raw_ostream &OS = llvm::errs();
Daniel Dunbar0397af22010-01-13 00:48:06 +0000586
587 // Create the target instance.
588 setTarget(TargetInfo::CreateTargetInfo(getDiagnostics(), getTargetOpts()));
589 if (!hasTarget())
590 return false;
591
592 // Inform the target of the language options.
593 //
594 // FIXME: We shouldn't need to do this, the target should be immutable once
595 // created. This complexity should be lifted elsewhere.
596 getTarget().setForcedLangOptions(getLangOpts());
597
598 // Validate/process some options.
599 if (getHeaderSearchOpts().Verbose)
600 OS << "clang -cc1 version " CLANG_VERSION_STRING
601 << " based upon " << PACKAGE_STRING
602 << " hosted on " << llvm::sys::getHostTriple() << "\n";
603
604 if (getFrontendOpts().ShowTimers)
605 createFrontendTimer();
606
Douglas Gregor95dd5582010-03-30 17:33:59 +0000607 if (getFrontendOpts().ShowStats)
608 llvm::EnableStatistics();
609
Daniel Dunbar0397af22010-01-13 00:48:06 +0000610 for (unsigned i = 0, e = getFrontendOpts().Inputs.size(); i != e; ++i) {
611 const std::string &InFile = getFrontendOpts().Inputs[i].second;
612
Daniel Dunbar20560482010-06-07 23:23:50 +0000613 // Reset the ID tables if we are reusing the SourceManager.
614 if (hasSourceManager())
615 getSourceManager().clearIDTables();
Daniel Dunbar0397af22010-01-13 00:48:06 +0000616
Daniel Dunbard3598a62010-06-07 23:23:06 +0000617 if (Act.BeginSourceFile(*this, InFile, getFrontendOpts().Inputs[i].first)) {
Daniel Dunbar0397af22010-01-13 00:48:06 +0000618 Act.Execute();
619 Act.EndSourceFile();
620 }
621 }
622
Chris Lattner53eee7b2010-04-07 18:47:42 +0000623 if (getDiagnosticOpts().ShowCarets) {
Argyrios Kyrtzidisf2224d82010-11-18 20:06:46 +0000624 // We can have multiple diagnostics sharing one diagnostic client.
625 // Get the total number of warnings/errors from the client.
626 unsigned NumWarnings = getDiagnostics().getClient()->getNumWarnings();
627 unsigned NumErrors = getDiagnostics().getClient()->getNumErrors();
Chris Lattner53eee7b2010-04-07 18:47:42 +0000628
629 if (NumWarnings)
630 OS << NumWarnings << " warning" << (NumWarnings == 1 ? "" : "s");
631 if (NumWarnings && NumErrors)
632 OS << " and ";
633 if (NumErrors)
634 OS << NumErrors << " error" << (NumErrors == 1 ? "" : "s");
635 if (NumWarnings || NumErrors)
636 OS << " generated.\n";
637 }
Daniel Dunbar0397af22010-01-13 00:48:06 +0000638
Daniel Dunbar20560482010-06-07 23:23:50 +0000639 if (getFrontendOpts().ShowStats && hasFileManager()) {
Daniel Dunbar0397af22010-01-13 00:48:06 +0000640 getFileManager().PrintStats();
641 OS << "\n";
642 }
643
Argyrios Kyrtzidisab41b972010-11-18 21:13:57 +0000644 return !getDiagnostics().getClient()->getNumErrors();
Daniel Dunbar0397af22010-01-13 00:48:06 +0000645}
646
Douglas Gregor21cae202011-09-12 23:31:24 +0000647/// \brief Determine the appropriate source input kind based on language
648/// options.
649static InputKind getSourceInputKindFromOptions(const LangOptions &LangOpts) {
650 if (LangOpts.OpenCL)
651 return IK_OpenCL;
652 if (LangOpts.CUDA)
653 return IK_CUDA;
654 if (LangOpts.ObjC1)
655 return LangOpts.CPlusPlus? IK_ObjCXX : IK_ObjC;
656 return LangOpts.CPlusPlus? IK_CXX : IK_C;
657}
658
Douglas Gregor0ced7992011-10-04 00:21:21 +0000659namespace {
660 struct CompileModuleData {
661 CompilerInstance &Instance;
662 GeneratePCHAction &CreateModuleAction;
663 };
664}
665
666/// \brief Helper function that executes the module-generating action under
667/// a crash recovery context.
668static void doCompileModule(void *UserData) {
669 CompileModuleData &Data = *reinterpret_cast<CompileModuleData *>(UserData);
670 Data.Instance.ExecuteAction(Data.CreateModuleAction);
671}
672
Douglas Gregor21cae202011-09-12 23:31:24 +0000673/// \brief Compile a module file for the given module name with the given
674/// umbrella header, using the options provided by the importing compiler
675/// instance.
676static void compileModule(CompilerInstance &ImportingInstance,
677 StringRef ModuleName,
Douglas Gregor6e975c42011-09-13 23:15:45 +0000678 StringRef ModuleFileName,
Douglas Gregor21cae202011-09-12 23:31:24 +0000679 StringRef UmbrellaHeader) {
Douglas Gregor21cae202011-09-12 23:31:24 +0000680 // Construct a compiler invocation for creating this module.
681 llvm::IntrusiveRefCntPtr<CompilerInvocation> Invocation
682 (new CompilerInvocation(ImportingInstance.getInvocation()));
Douglas Gregorb2d39c22011-09-15 20:53:28 +0000683
684 // For any options that aren't intended to affect how a module is built,
685 // reset them to their default values.
Douglas Gregor1c7e0472011-09-13 20:44:41 +0000686 Invocation->getLangOpts().resetNonModularOptions();
687 Invocation->getPreprocessorOpts().resetNonModularOptions();
Douglas Gregorb2d39c22011-09-15 20:53:28 +0000688
689 // Note that this module is part of the module build path, so that we
690 // can detect cycles in the module graph.
Douglas Gregor4ebd45f2011-09-15 20:40:10 +0000691 Invocation->getPreprocessorOpts().ModuleBuildPath.push_back(ModuleName);
Douglas Gregor1c7e0472011-09-13 20:44:41 +0000692
Douglas Gregorb2d39c22011-09-15 20:53:28 +0000693 // Set up the inputs/outputs so that we build the module from its umbrella
694 // header.
Douglas Gregor21cae202011-09-12 23:31:24 +0000695 FrontendOptions &FrontendOpts = Invocation->getFrontendOpts();
Douglas Gregor6e975c42011-09-13 23:15:45 +0000696 FrontendOpts.OutputFile = ModuleFileName.str();
Douglas Gregor21cae202011-09-12 23:31:24 +0000697 FrontendOpts.DisableFree = false;
698 FrontendOpts.Inputs.clear();
699 FrontendOpts.Inputs.push_back(
700 std::make_pair(getSourceInputKindFromOptions(Invocation->getLangOpts()),
701 UmbrellaHeader));
Douglas Gregor78243652011-09-13 01:26:44 +0000702
703 Invocation->getDiagnosticOpts().VerifyDiagnostics = 0;
704
Douglas Gregor4ebd45f2011-09-15 20:40:10 +0000705
Douglas Gregor76d991e2011-09-13 23:20:27 +0000706 assert(ImportingInstance.getInvocation().getModuleHash() ==
707 Invocation->getModuleHash() && "Module hash mismatch!");
Douglas Gregor21cae202011-09-12 23:31:24 +0000708
709 // Construct a compiler instance that will be used to actually create the
710 // module.
711 CompilerInstance Instance;
712 Instance.setInvocation(&*Invocation);
Douglas Gregor78243652011-09-13 01:26:44 +0000713 Instance.createDiagnostics(/*argc=*/0, /*argv=*/0,
714 &ImportingInstance.getDiagnosticClient(),
Douglas Gregoraee526e2011-09-29 00:38:00 +0000715 /*ShouldOwnClient=*/true,
716 /*ShouldCloneClient=*/true);
Douglas Gregor21cae202011-09-12 23:31:24 +0000717
718 // Construct a module-generating action.
719 GeneratePCHAction CreateModuleAction(true);
720
Douglas Gregor0ced7992011-10-04 00:21:21 +0000721 // Execute the action to actually build the module in-place. Use a separate
722 // thread so that we get a stack large enough.
723 const unsigned ThreadStackSize = 8 << 20;
724 llvm::CrashRecoveryContext CRC;
725 CompileModuleData Data = { Instance, CreateModuleAction };
726 CRC.RunSafelyOnThread(&doCompileModule, &Data, ThreadStackSize);
Douglas Gregor78243652011-09-13 01:26:44 +0000727}
Douglas Gregor21cae202011-09-12 23:31:24 +0000728
Douglas Gregor6aa52ec2011-08-26 23:56:07 +0000729ModuleKey CompilerInstance::loadModule(SourceLocation ImportLoc,
730 IdentifierInfo &ModuleName,
731 SourceLocation ModuleNameLoc) {
732 // Determine what file we're searching from.
733 SourceManager &SourceMgr = getSourceManager();
734 SourceLocation ExpandedImportLoc = SourceMgr.getExpansionLoc(ImportLoc);
735 const FileEntry *CurFile
736 = SourceMgr.getFileEntryForID(SourceMgr.getFileID(ExpandedImportLoc));
737 if (!CurFile)
738 CurFile = SourceMgr.getFileEntryForID(SourceMgr.getMainFileID());
739
740 // Search for a module with the given name.
Douglas Gregor21cae202011-09-12 23:31:24 +0000741 std::string UmbrellaHeader;
Douglas Gregor6e975c42011-09-13 23:15:45 +0000742 std::string ModuleFileName;
Douglas Gregor6aa52ec2011-08-26 23:56:07 +0000743 const FileEntry *ModuleFile
Douglas Gregor21cae202011-09-12 23:31:24 +0000744 = PP->getHeaderSearchInfo().lookupModule(ModuleName.getName(),
Douglas Gregor6e975c42011-09-13 23:15:45 +0000745 &ModuleFileName,
Douglas Gregor21cae202011-09-12 23:31:24 +0000746 &UmbrellaHeader);
747
748 bool BuildingModule = false;
749 if (!ModuleFile && !UmbrellaHeader.empty()) {
750 // We didn't find the module, but there is an umbrella header that
751 // can be used to create the module file. Create a separate compilation
752 // module to do so.
Douglas Gregor4ebd45f2011-09-15 20:40:10 +0000753
754 // Check whether there is a cycle in the module graph.
755 SmallVectorImpl<std::string> &ModuleBuildPath
756 = getPreprocessorOpts().ModuleBuildPath;
757 SmallVectorImpl<std::string>::iterator Pos
758 = std::find(ModuleBuildPath.begin(), ModuleBuildPath.end(),
759 ModuleName.getName());
760 if (Pos != ModuleBuildPath.end()) {
761 llvm::SmallString<256> CyclePath;
762 for (; Pos != ModuleBuildPath.end(); ++Pos) {
763 CyclePath += *Pos;
764 CyclePath += " -> ";
765 }
766 CyclePath += ModuleName.getName();
767
768 getDiagnostics().Report(ModuleNameLoc, diag::err_module_cycle)
769 << ModuleName.getName() << CyclePath;
770 return 0;
771 }
772
Douglas Gregor08d6acf2011-09-29 00:52:27 +0000773 getDiagnostics().Report(ModuleNameLoc, diag::warn_module_build)
774 << ModuleName.getName();
Douglas Gregor21cae202011-09-12 23:31:24 +0000775 BuildingModule = true;
Douglas Gregor6e975c42011-09-13 23:15:45 +0000776 compileModule(*this, ModuleName.getName(), ModuleFileName, UmbrellaHeader);
Douglas Gregor21cae202011-09-12 23:31:24 +0000777 ModuleFile = PP->getHeaderSearchInfo().lookupModule(ModuleName.getName());
778 }
779
Douglas Gregor6aa52ec2011-08-26 23:56:07 +0000780 if (!ModuleFile) {
Douglas Gregor21cae202011-09-12 23:31:24 +0000781 getDiagnostics().Report(ModuleNameLoc,
782 BuildingModule? diag::err_module_not_built
783 : diag::err_module_not_found)
Douglas Gregor6aa52ec2011-08-26 23:56:07 +0000784 << ModuleName.getName()
785 << SourceRange(ImportLoc, ModuleNameLoc);
786 return 0;
787 }
788
789 // If we don't already have an ASTReader, create one now.
790 if (!ModuleManager) {
Douglas Gregorde8a9052011-09-14 23:13:09 +0000791 if (!hasASTContext())
792 createASTContext();
793
Douglas Gregor6aa52ec2011-08-26 23:56:07 +0000794 std::string Sysroot = getHeaderSearchOpts().Sysroot;
795 const PreprocessorOptions &PPOpts = getPreprocessorOpts();
Douglas Gregorf8a1e512011-09-02 00:26:20 +0000796 ModuleManager = new ASTReader(getPreprocessor(), *Context,
Douglas Gregor6aa52ec2011-08-26 23:56:07 +0000797 Sysroot.empty() ? "" : Sysroot.c_str(),
798 PPOpts.DisablePCHValidation,
799 PPOpts.DisableStatCache);
Douglas Gregorde8a9052011-09-14 23:13:09 +0000800 if (hasASTConsumer()) {
801 ModuleManager->setDeserializationListener(
802 getASTConsumer().GetASTDeserializationListener());
803 getASTContext().setASTMutationListener(
804 getASTConsumer().GetASTMutationListener());
805 }
Douglas Gregor6aa52ec2011-08-26 23:56:07 +0000806 llvm::OwningPtr<ExternalASTSource> Source;
807 Source.reset(ModuleManager);
808 getASTContext().setExternalSource(Source);
Douglas Gregorde8a9052011-09-14 23:13:09 +0000809 if (hasSema())
810 ModuleManager->InitializeSema(getSema());
Douglas Gregor1a995dd2011-09-15 18:47:32 +0000811 if (hasASTConsumer())
812 ModuleManager->StartTranslationUnit(&getASTConsumer());
Douglas Gregor6aa52ec2011-08-26 23:56:07 +0000813 }
814
815 // Try to load the module we found.
816 switch (ModuleManager->ReadAST(ModuleFile->getName(),
817 serialization::MK_Module)) {
818 case ASTReader::Success:
819 break;
820
821 case ASTReader::IgnorePCH:
822 // FIXME: The ASTReader will already have complained, but can we showhorn
823 // that diagnostic information into a more useful form?
824 return 0;
825
826 case ASTReader::Failure:
827 // Already complained.
828 return 0;
829 }
830
831 // FIXME: The module file's FileEntry makes a poor key indeed!
832 return (ModuleKey)ModuleFile;
833}
Daniel Dunbar0397af22010-01-13 00:48:06 +0000834