blob: 38fcfe3c4711fe16f1ffa22c72edec60469f4027 [file] [log] [blame]
Daniel Dunbar636404a2009-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 Gregor0e93f012010-08-12 23:31:19 +000011#include "clang/Sema/Sema.h"
Daniel Dunbar56d9c292009-11-14 02:47:17 +000012#include "clang/AST/ASTConsumer.h"
Daniel Dunbardf3e30c2009-11-13 08:20:47 +000013#include "clang/AST/ASTContext.h"
Daniel Dunbar636404a2009-11-13 03:51:44 +000014#include "clang/Basic/Diagnostic.h"
Daniel Dunbar546a6762009-11-13 04:12:06 +000015#include "clang/Basic/FileManager.h"
16#include "clang/Basic/SourceManager.h"
Daniel Dunbar636404a2009-11-13 03:51:44 +000017#include "clang/Basic/TargetInfo.h"
Daniel Dunbar4f2bc552010-01-13 00:48:06 +000018#include "clang/Basic/Version.h"
Daniel Dunbaraaa148f2009-11-13 05:52:11 +000019#include "clang/Lex/HeaderSearch.h"
20#include "clang/Lex/Preprocessor.h"
21#include "clang/Lex/PTHManager.h"
Daniel Dunbar7d75afc2009-11-13 05:52:34 +000022#include "clang/Frontend/ChainedDiagnosticClient.h"
Daniel Dunbar4f2bc552010-01-13 00:48:06 +000023#include "clang/Frontend/FrontendAction.h"
Daniel Dunbarf7093b52009-11-13 09:36:05 +000024#include "clang/Frontend/FrontendDiagnostic.h"
Daniel Dunbar2083c322011-04-07 18:31:10 +000025#include "clang/Frontend/LogDiagnosticPrinter.h"
Daniel Dunbar7d75afc2009-11-13 05:52:34 +000026#include "clang/Frontend/TextDiagnosticPrinter.h"
Daniel Dunbar50ec0da2009-11-14 03:24:39 +000027#include "clang/Frontend/VerifyDiagnosticsClient.h"
Daniel Dunbaraaa148f2009-11-13 05:52:11 +000028#include "clang/Frontend/Utils.h"
Sebastian Redlf5b13462010-08-18 23:57:17 +000029#include "clang/Serialization/ASTReader.h"
Daniel Dunbarf7093b52009-11-13 09:36:05 +000030#include "clang/Sema/CodeCompleteConsumer.h"
Michael J. Spencerf6efe582011-01-10 02:34:13 +000031#include "llvm/Support/FileSystem.h"
Daniel Dunbar409e8902009-11-14 07:53:04 +000032#include "llvm/Support/MemoryBuffer.h"
Daniel Dunbar7d75afc2009-11-13 05:52:34 +000033#include "llvm/Support/raw_ostream.h"
Douglas Gregor171b7802010-03-30 17:33:59 +000034#include "llvm/ADT/Statistic.h"
Kovarththanan Rajaratnam5505dff2009-11-29 09:57:35 +000035#include "llvm/Support/Timer.h"
Michael J. Spencer8aaf4992010-11-29 18:12:39 +000036#include "llvm/Support/Host.h"
37#include "llvm/Support/Path.h"
38#include "llvm/Support/Program.h"
39#include "llvm/Support/Signals.h"
Michael J. Spencerf25faaa2010-12-09 17:36:38 +000040#include "llvm/Support/system_error.h"
Daniel Dunbar636404a2009-11-13 03:51:44 +000041using namespace clang;
42
Daniel Dunbare922d9b2010-02-16 01:54:47 +000043CompilerInstance::CompilerInstance()
Sebastian Redl07a89a82010-07-30 00:29:29 +000044 : Invocation(new CompilerInvocation()) {
Daniel Dunbar68242252010-01-30 21:47:07 +000045}
Daniel Dunbar636404a2009-11-13 03:51:44 +000046
47CompilerInstance::~CompilerInstance() {
Daniel Dunbare922d9b2010-02-16 01:54:47 +000048}
49
Daniel Dunbar68242252010-01-30 21:47:07 +000050void CompilerInstance::setInvocation(CompilerInvocation *Value) {
Ted Kremenek5e14d392011-03-21 18:40:17 +000051 Invocation = Value;
Daniel Dunbar68242252010-01-30 21:47:07 +000052}
53
Daniel Dunbare01dc862009-11-14 01:20:40 +000054void CompilerInstance::setDiagnostics(Diagnostic *Value) {
Douglas Gregor7f95d262010-04-05 23:52:57 +000055 Diagnostics = Value;
Daniel Dunbare01dc862009-11-14 01:20:40 +000056}
57
Daniel Dunbare01dc862009-11-14 01:20:40 +000058void CompilerInstance::setTarget(TargetInfo *Value) {
Ted Kremenek5e14d392011-03-21 18:40:17 +000059 Target = Value;
Daniel Dunbare01dc862009-11-14 01:20:40 +000060}
61
62void CompilerInstance::setFileManager(FileManager *Value) {
Ted Kremenek5e14d392011-03-21 18:40:17 +000063 FileMgr = Value;
Daniel Dunbare01dc862009-11-14 01:20:40 +000064}
65
Ted Kremenek5e14d392011-03-21 18:40:17 +000066void CompilerInstance::setSourceManager(SourceManager *Value) {
67 SourceMgr = Value;
Daniel Dunbare01dc862009-11-14 01:20:40 +000068}
69
Ted Kremenek5e14d392011-03-21 18:40:17 +000070void CompilerInstance::setPreprocessor(Preprocessor *Value) { PP = Value; }
Daniel Dunbare01dc862009-11-14 01:20:40 +000071
Ted Kremenek5e14d392011-03-21 18:40:17 +000072void CompilerInstance::setASTContext(ASTContext *Value) { Context = Value; }
Daniel Dunbare01dc862009-11-14 01:20:40 +000073
Douglas Gregor0e93f012010-08-12 23:31:19 +000074void CompilerInstance::setSema(Sema *S) {
75 TheSema.reset(S);
76}
77
Daniel Dunbar56d9c292009-11-14 02:47:17 +000078void CompilerInstance::setASTConsumer(ASTConsumer *Value) {
79 Consumer.reset(Value);
80}
81
Daniel Dunbare01dc862009-11-14 01:20:40 +000082void CompilerInstance::setCodeCompletionConsumer(CodeCompleteConsumer *Value) {
83 CompletionConsumer.reset(Value);
84}
85
Daniel Dunbar7d75afc2009-11-13 05:52:34 +000086// Diagnostics
Daniel Dunbar7d75afc2009-11-13 05:52:34 +000087static void SetUpBuildDumpLog(const DiagnosticOptions &DiagOpts,
Axel Naumann89c31492010-10-11 09:13:46 +000088 unsigned argc, const char* const *argv,
Kovarththanan Rajaratnam4a94ba52010-03-17 09:24:48 +000089 Diagnostic &Diags) {
Daniel Dunbar7d75afc2009-11-13 05:52:34 +000090 std::string ErrorInfo;
Kovarththanan Rajaratnameeed0cc2010-03-17 09:47:30 +000091 llvm::OwningPtr<llvm::raw_ostream> OS(
92 new llvm::raw_fd_ostream(DiagOpts.DumpBuildInformation.c_str(), ErrorInfo));
Daniel Dunbar7d75afc2009-11-13 05:52:34 +000093 if (!ErrorInfo.empty()) {
Kovarththanan Rajaratnam4a94ba52010-03-17 09:24:48 +000094 Diags.Report(diag::err_fe_unable_to_open_logfile)
95 << DiagOpts.DumpBuildInformation << ErrorInfo;
Daniel Dunbar7d75afc2009-11-13 05:52:34 +000096 return;
97 }
98
Daniel Dunbar520d1e62009-12-11 23:04:35 +000099 (*OS) << "clang -cc1 command line arguments: ";
Daniel Dunbar7d75afc2009-11-13 05:52:34 +0000100 for (unsigned i = 0; i != argc; ++i)
101 (*OS) << argv[i] << ' ';
102 (*OS) << '\n';
103
104 // Chain in a diagnostic client which will log the diagnostics.
105 DiagnosticClient *Logger =
Kovarththanan Rajaratnameeed0cc2010-03-17 09:47:30 +0000106 new TextDiagnosticPrinter(*OS.take(), DiagOpts, /*OwnsOutputStream=*/true);
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000107 Diags.setClient(new ChainedDiagnosticClient(Diags.takeClient(), Logger));
Daniel Dunbar7d75afc2009-11-13 05:52:34 +0000108}
109
Daniel Dunbar2083c322011-04-07 18:31:10 +0000110static void SetUpDiagnosticLog(const DiagnosticOptions &DiagOpts,
Daniel Dunbar7b833062011-04-07 18:59:02 +0000111 const CodeGenOptions *CodeGenOpts,
Daniel Dunbar2083c322011-04-07 18:31:10 +0000112 Diagnostic &Diags) {
113 std::string ErrorInfo;
114 bool OwnsStream = false;
115 llvm::raw_ostream *OS = &llvm::errs();
116 if (DiagOpts.DiagnosticLogFile != "-") {
117 // Create the output stream.
118 llvm::raw_fd_ostream *FileOS(
119 new llvm::raw_fd_ostream(DiagOpts.DiagnosticLogFile.c_str(),
Daniel Dunbar44d9ef72011-04-07 20:19:21 +0000120 ErrorInfo, llvm::raw_fd_ostream::F_Append));
Daniel Dunbar2083c322011-04-07 18:31:10 +0000121 if (!ErrorInfo.empty()) {
122 Diags.Report(diag::warn_fe_cc_log_diagnostics_failure)
123 << DiagOpts.DumpBuildInformation << ErrorInfo;
124 } else {
125 FileOS->SetUnbuffered();
126 FileOS->SetUseAtomicWrites(true);
127 OS = FileOS;
128 OwnsStream = true;
129 }
130 }
131
132 // Chain in the diagnostic client which will log the diagnostics.
Daniel Dunbar7b833062011-04-07 18:59:02 +0000133 LogDiagnosticPrinter *Logger = new LogDiagnosticPrinter(*OS, DiagOpts,
134 OwnsStream);
135 if (CodeGenOpts)
136 Logger->setDwarfDebugFlags(CodeGenOpts->DwarfDebugFlags);
Daniel Dunbar2083c322011-04-07 18:31:10 +0000137 Diags.setClient(new ChainedDiagnosticClient(Diags.takeClient(), Logger));
138}
139
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000140void CompilerInstance::createDiagnostics(int Argc, const char* const *Argv,
141 DiagnosticClient *Client) {
Daniel Dunbar7b833062011-04-07 18:59:02 +0000142 Diagnostics = createDiagnostics(getDiagnosticOpts(), Argc, Argv, Client,
143 &getCodeGenOpts());
Daniel Dunbar7d75afc2009-11-13 05:52:34 +0000144}
145
Douglas Gregor7f95d262010-04-05 23:52:57 +0000146llvm::IntrusiveRefCntPtr<Diagnostic>
147CompilerInstance::createDiagnostics(const DiagnosticOptions &Opts,
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000148 int Argc, const char* const *Argv,
Daniel Dunbar7b833062011-04-07 18:59:02 +0000149 DiagnosticClient *Client,
150 const CodeGenOptions *CodeGenOpts) {
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000151 llvm::IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
152 llvm::IntrusiveRefCntPtr<Diagnostic> Diags(new Diagnostic(DiagID));
Daniel Dunbar1b39a2e2009-11-14 07:53:24 +0000153
Daniel Dunbar7d75afc2009-11-13 05:52:34 +0000154 // Create the diagnostic client for reporting errors or for
155 // implementing -verify.
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000156 if (Client)
157 Diags->setClient(Client);
158 else
159 Diags->setClient(new TextDiagnosticPrinter(llvm::errs(), Opts));
Daniel Dunbar50ec0da2009-11-14 03:24:39 +0000160
161 // Chain in -verify checker, if requested.
162 if (Opts.VerifyDiagnostics)
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000163 Diags->setClient(new VerifyDiagnosticsClient(*Diags, Diags->takeClient()));
Daniel Dunbar7d75afc2009-11-13 05:52:34 +0000164
Daniel Dunbar2083c322011-04-07 18:31:10 +0000165 // Chain in -diagnostic-log-file dumper, if requested.
166 if (!Opts.DiagnosticLogFile.empty())
Daniel Dunbar7b833062011-04-07 18:59:02 +0000167 SetUpDiagnosticLog(Opts, CodeGenOpts, *Diags);
Daniel Dunbar2083c322011-04-07 18:31:10 +0000168
Daniel Dunbar7d75afc2009-11-13 05:52:34 +0000169 if (!Opts.DumpBuildInformation.empty())
Kovarththanan Rajaratnam4a94ba52010-03-17 09:24:48 +0000170 SetUpBuildDumpLog(Opts, Argc, Argv, *Diags);
Daniel Dunbar7d75afc2009-11-13 05:52:34 +0000171
172 // Configure our handling of diagnostics.
Kovarththanan Rajaratnam9ff84d92010-03-17 09:36:02 +0000173 ProcessWarningOptions(*Diags, Opts);
Daniel Dunbar7d75afc2009-11-13 05:52:34 +0000174
Douglas Gregor7f95d262010-04-05 23:52:57 +0000175 return Diags;
Daniel Dunbar7d75afc2009-11-13 05:52:34 +0000176}
177
178// File Manager
179
Daniel Dunbar546a6762009-11-13 04:12:06 +0000180void CompilerInstance::createFileManager() {
Ted Kremenek5e14d392011-03-21 18:40:17 +0000181 FileMgr = new FileManager(getFileSystemOpts());
Daniel Dunbar546a6762009-11-13 04:12:06 +0000182}
183
Daniel Dunbar7d75afc2009-11-13 05:52:34 +0000184// Source Manager
185
Chris Lattner5159f612010-11-23 08:35:12 +0000186void CompilerInstance::createSourceManager(FileManager &FileMgr) {
Ted Kremenek5e14d392011-03-21 18:40:17 +0000187 SourceMgr = new SourceManager(getDiagnostics(), FileMgr);
Daniel Dunbar546a6762009-11-13 04:12:06 +0000188}
Daniel Dunbaraaa148f2009-11-13 05:52:11 +0000189
Daniel Dunbar7d75afc2009-11-13 05:52:34 +0000190// Preprocessor
191
Daniel Dunbaraaa148f2009-11-13 05:52:11 +0000192void CompilerInstance::createPreprocessor() {
Ted Kremenek5e14d392011-03-21 18:40:17 +0000193 PP = createPreprocessor(getDiagnostics(), getLangOpts(),
194 getPreprocessorOpts(), getHeaderSearchOpts(),
195 getDependencyOutputOpts(), getTarget(),
196 getFrontendOpts(), getSourceManager(),
197 getFileManager());
Daniel Dunbaraaa148f2009-11-13 05:52:11 +0000198}
199
200Preprocessor *
201CompilerInstance::createPreprocessor(Diagnostic &Diags,
202 const LangOptions &LangInfo,
203 const PreprocessorOptions &PPOpts,
204 const HeaderSearchOptions &HSOpts,
205 const DependencyOutputOptions &DepOpts,
206 const TargetInfo &Target,
Fariborz Jahanian3f7b8b22010-01-13 18:51:17 +0000207 const FrontendOptions &FEOpts,
Daniel Dunbaraaa148f2009-11-13 05:52:11 +0000208 SourceManager &SourceMgr,
209 FileManager &FileMgr) {
210 // Create a PTH manager if we are using some form of a token cache.
211 PTHManager *PTHMgr = 0;
Daniel Dunbard6ea9022009-11-17 05:52:41 +0000212 if (!PPOpts.TokenCache.empty())
Chris Lattner7219a5d2010-11-23 09:01:31 +0000213 PTHMgr = PTHManager::Create(PPOpts.TokenCache, Diags);
Daniel Dunbaraaa148f2009-11-13 05:52:11 +0000214
Daniel Dunbaraaa148f2009-11-13 05:52:11 +0000215 // Create the Preprocessor.
Chris Lattner5159f612010-11-23 08:35:12 +0000216 HeaderSearch *HeaderInfo = new HeaderSearch(FileMgr);
Daniel Dunbaraaa148f2009-11-13 05:52:11 +0000217 Preprocessor *PP = new Preprocessor(Diags, LangInfo, Target,
218 SourceMgr, *HeaderInfo, PTHMgr,
219 /*OwnsHeaderSearch=*/true);
220
221 // Note that this is different then passing PTHMgr to Preprocessor's ctor.
222 // That argument is used as the IdentifierInfoLookup argument to
223 // IdentifierTable's ctor.
224 if (PTHMgr) {
225 PTHMgr->setPreprocessor(PP);
226 PP->setPTHManager(PTHMgr);
227 }
228
Douglas Gregor7f6d60d2010-03-19 16:15:56 +0000229 if (PPOpts.DetailedRecord)
Douglas Gregor998caea2011-05-06 16:33:08 +0000230 PP->createPreprocessingRecord(
231 PPOpts.DetailedRecordIncludesNestedMacroInstantiations);
Douglas Gregor7f6d60d2010-03-19 16:15:56 +0000232
Chris Lattner5159f612010-11-23 08:35:12 +0000233 InitializePreprocessor(*PP, PPOpts, HSOpts, FEOpts);
Daniel Dunbaraaa148f2009-11-13 05:52:11 +0000234
235 // Handle generating dependencies, if requested.
236 if (!DepOpts.OutputFile.empty())
237 AttachDependencyFileGen(*PP, DepOpts);
238
Daniel Dunbar27734fd2011-02-02 15:41:17 +0000239 // Handle generating header include information, if requested.
240 if (DepOpts.ShowHeaderIncludes)
241 AttachHeaderIncludeGen(*PP);
Daniel Dunbar1af1d27512011-02-02 21:11:31 +0000242 if (!DepOpts.HeaderIncludeOutputFile.empty()) {
243 llvm::StringRef OutputPath = DepOpts.HeaderIncludeOutputFile;
244 if (OutputPath == "-")
245 OutputPath = "";
Daniel Dunbarfe908a82011-03-21 19:37:38 +0000246 AttachHeaderIncludeGen(*PP, /*ShowAllHeaders=*/true, OutputPath,
247 /*ShowDepth=*/false);
Daniel Dunbar1af1d27512011-02-02 21:11:31 +0000248 }
Daniel Dunbar27734fd2011-02-02 15:41:17 +0000249
Daniel Dunbaraaa148f2009-11-13 05:52:11 +0000250 return PP;
251}
Daniel Dunbardf3e30c2009-11-13 08:20:47 +0000252
253// ASTContext
254
255void CompilerInstance::createASTContext() {
256 Preprocessor &PP = getPreprocessor();
Ted Kremenek5e14d392011-03-21 18:40:17 +0000257 Context = new ASTContext(getLangOpts(), PP.getSourceManager(),
258 getTarget(), PP.getIdentifierTable(),
259 PP.getSelectorTable(), PP.getBuiltinInfo(),
260 /*size_reserve=*/ 0);
Daniel Dunbardf3e30c2009-11-13 08:20:47 +0000261}
Daniel Dunbar599313e2009-11-13 08:21:10 +0000262
263// ExternalASTSource
264
Douglas Gregorce3a8292010-07-27 00:27:13 +0000265void CompilerInstance::createPCHExternalASTSource(llvm::StringRef Path,
Sebastian Redl07a89a82010-07-30 00:29:29 +0000266 bool DisablePCHValidation,
Douglas Gregor606c4ac2011-02-05 19:42:43 +0000267 bool DisableStatCache,
Sebastian Redl07a89a82010-07-30 00:29:29 +0000268 void *DeserializationListener){
Daniel Dunbar599313e2009-11-13 08:21:10 +0000269 llvm::OwningPtr<ExternalASTSource> Source;
Sebastian Redl009e7f22010-10-05 16:15:19 +0000270 bool Preamble = getPreprocessorOpts().PrecompiledPreambleBytes.first != 0;
Daniel Dunbar599313e2009-11-13 08:21:10 +0000271 Source.reset(createPCHExternalASTSource(Path, getHeaderSearchOpts().Sysroot,
Douglas Gregor606c4ac2011-02-05 19:42:43 +0000272 DisablePCHValidation,
273 DisableStatCache,
Sebastian Redl07a89a82010-07-30 00:29:29 +0000274 getPreprocessor(), getASTContext(),
Sebastian Redl009e7f22010-10-05 16:15:19 +0000275 DeserializationListener,
276 Preamble));
Daniel Dunbar599313e2009-11-13 08:21:10 +0000277 getASTContext().setExternalSource(Source);
278}
279
280ExternalASTSource *
281CompilerInstance::createPCHExternalASTSource(llvm::StringRef Path,
282 const std::string &Sysroot,
Douglas Gregorce3a8292010-07-27 00:27:13 +0000283 bool DisablePCHValidation,
Douglas Gregor606c4ac2011-02-05 19:42:43 +0000284 bool DisableStatCache,
Daniel Dunbar599313e2009-11-13 08:21:10 +0000285 Preprocessor &PP,
Sebastian Redl07a89a82010-07-30 00:29:29 +0000286 ASTContext &Context,
Sebastian Redl009e7f22010-10-05 16:15:19 +0000287 void *DeserializationListener,
288 bool Preamble) {
Sebastian Redl2c499f62010-08-18 23:56:43 +0000289 llvm::OwningPtr<ASTReader> Reader;
290 Reader.reset(new ASTReader(PP, &Context,
Douglas Gregorce3a8292010-07-27 00:27:13 +0000291 Sysroot.empty() ? 0 : Sysroot.c_str(),
Douglas Gregor606c4ac2011-02-05 19:42:43 +0000292 DisablePCHValidation, DisableStatCache));
Daniel Dunbar599313e2009-11-13 08:21:10 +0000293
Sebastian Redl07a89a82010-07-30 00:29:29 +0000294 Reader->setDeserializationListener(
Sebastian Redl3e31c722010-08-18 23:56:56 +0000295 static_cast<ASTDeserializationListener *>(DeserializationListener));
Sebastian Redl009e7f22010-10-05 16:15:19 +0000296 switch (Reader->ReadAST(Path,
297 Preamble ? ASTReader::Preamble : ASTReader::PCH)) {
Sebastian Redl2c499f62010-08-18 23:56:43 +0000298 case ASTReader::Success:
Daniel Dunbar599313e2009-11-13 08:21:10 +0000299 // Set the predefines buffer as suggested by the PCH reader. Typically, the
300 // predefines buffer will be empty.
301 PP.setPredefines(Reader->getSuggestedPredefines());
302 return Reader.take();
303
Sebastian Redl2c499f62010-08-18 23:56:43 +0000304 case ASTReader::Failure:
Daniel Dunbar599313e2009-11-13 08:21:10 +0000305 // Unrecoverable failure: don't even try to process the input file.
306 break;
307
Sebastian Redl2c499f62010-08-18 23:56:43 +0000308 case ASTReader::IgnorePCH:
Daniel Dunbar599313e2009-11-13 08:21:10 +0000309 // No suitable PCH file could be found. Return an error.
310 break;
311 }
312
313 return 0;
314}
Daniel Dunbarf7093b52009-11-13 09:36:05 +0000315
316// Code Completion
317
Douglas Gregor8e984da2010-08-04 16:47:14 +0000318static bool EnableCodeCompletion(Preprocessor &PP,
319 const std::string &Filename,
320 unsigned Line,
321 unsigned Column) {
322 // Tell the source manager to chop off the given file at a specific
323 // line and column.
Chris Lattner5159f612010-11-23 08:35:12 +0000324 const FileEntry *Entry = PP.getFileManager().getFile(Filename);
Douglas Gregor8e984da2010-08-04 16:47:14 +0000325 if (!Entry) {
326 PP.getDiagnostics().Report(diag::err_fe_invalid_code_complete_file)
327 << Filename;
328 return true;
329 }
330
331 // Truncate the named file at the given line/column.
332 PP.SetCodeCompletionPoint(Entry, Line, Column);
333 return false;
334}
335
Daniel Dunbarf7093b52009-11-13 09:36:05 +0000336void CompilerInstance::createCodeCompletionConsumer() {
337 const ParsedSourceLocation &Loc = getFrontendOpts().CodeCompletionAt;
Douglas Gregor8e984da2010-08-04 16:47:14 +0000338 if (!CompletionConsumer) {
339 CompletionConsumer.reset(
340 createCodeCompletionConsumer(getPreprocessor(),
341 Loc.FileName, Loc.Line, Loc.Column,
Douglas Gregor8e984da2010-08-04 16:47:14 +0000342 getFrontendOpts().ShowMacrosInCodeCompletion,
Douglas Gregorf64acca2010-05-25 21:41:55 +0000343 getFrontendOpts().ShowCodePatternsInCodeCompletion,
Douglas Gregor39982192010-08-15 06:18:01 +0000344 getFrontendOpts().ShowGlobalSymbolsInCodeCompletion,
Douglas Gregor8e984da2010-08-04 16:47:14 +0000345 llvm::outs()));
346 if (!CompletionConsumer)
347 return;
348 } else if (EnableCodeCompletion(getPreprocessor(), Loc.FileName,
349 Loc.Line, Loc.Column)) {
350 CompletionConsumer.reset();
Douglas Gregor00a0cf72010-03-16 06:04:47 +0000351 return;
Douglas Gregor8e984da2010-08-04 16:47:14 +0000352 }
Douglas Gregorf09935f2009-12-01 05:55:20 +0000353
354 if (CompletionConsumer->isOutputBinary() &&
355 llvm::sys::Program::ChangeStdoutToBinary()) {
356 getPreprocessor().getDiagnostics().Report(diag::err_fe_stdout_binary);
357 CompletionConsumer.reset();
358 }
Daniel Dunbarf7093b52009-11-13 09:36:05 +0000359}
360
Kovarththanan Rajaratnam5505dff2009-11-29 09:57:35 +0000361void CompilerInstance::createFrontendTimer() {
362 FrontendTimer.reset(new llvm::Timer("Clang front-end timer"));
363}
364
Daniel Dunbarf7093b52009-11-13 09:36:05 +0000365CodeCompleteConsumer *
366CompilerInstance::createCodeCompletionConsumer(Preprocessor &PP,
367 const std::string &Filename,
368 unsigned Line,
369 unsigned Column,
Daniel Dunbarf7093b52009-11-13 09:36:05 +0000370 bool ShowMacros,
Douglas Gregorf64acca2010-05-25 21:41:55 +0000371 bool ShowCodePatterns,
Douglas Gregor39982192010-08-15 06:18:01 +0000372 bool ShowGlobals,
Daniel Dunbarf7093b52009-11-13 09:36:05 +0000373 llvm::raw_ostream &OS) {
Douglas Gregor8e984da2010-08-04 16:47:14 +0000374 if (EnableCodeCompletion(PP, Filename, Line, Column))
Daniel Dunbarf7093b52009-11-13 09:36:05 +0000375 return 0;
Daniel Dunbarf7093b52009-11-13 09:36:05 +0000376
377 // Set up the creation routine for code-completion.
Douglas Gregorb9ab0ed2010-10-11 22:12:15 +0000378 return new PrintingCodeCompleteConsumer(ShowMacros, ShowCodePatterns,
Douglas Gregor39982192010-08-15 06:18:01 +0000379 ShowGlobals, OS);
Daniel Dunbarf7093b52009-11-13 09:36:05 +0000380}
Daniel Dunbar566eeb22009-11-13 10:37:48 +0000381
Douglas Gregor0e93f012010-08-12 23:31:19 +0000382void CompilerInstance::createSema(bool CompleteTranslationUnit,
383 CodeCompleteConsumer *CompletionConsumer) {
384 TheSema.reset(new Sema(getPreprocessor(), getASTContext(), getASTConsumer(),
385 CompleteTranslationUnit, CompletionConsumer));
386}
387
Daniel Dunbar566eeb22009-11-13 10:37:48 +0000388// Output Files
389
Argyrios Kyrtzidisd0599972010-09-17 17:38:48 +0000390void CompilerInstance::addOutputFile(const OutputFile &OutFile) {
391 assert(OutFile.OS && "Attempt to add empty stream to output list!");
392 OutputFiles.push_back(OutFile);
Daniel Dunbar566eeb22009-11-13 10:37:48 +0000393}
394
Kovarththanan Rajaratnam1c558cd2010-03-06 12:07:48 +0000395void CompilerInstance::clearOutputFiles(bool EraseFiles) {
Argyrios Kyrtzidisd0599972010-09-17 17:38:48 +0000396 for (std::list<OutputFile>::iterator
Daniel Dunbar566eeb22009-11-13 10:37:48 +0000397 it = OutputFiles.begin(), ie = OutputFiles.end(); it != ie; ++it) {
Argyrios Kyrtzidisd0599972010-09-17 17:38:48 +0000398 delete it->OS;
399 if (!it->TempFilename.empty()) {
Anders Carlssonb5c356a2011-03-06 22:25:35 +0000400 if (EraseFiles) {
401 bool existed;
402 llvm::sys::fs::remove(it->TempFilename, existed);
403 } else {
404 llvm::SmallString<128> NewOutFile(it->Filename);
405
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000406 // If '-working-directory' was passed, the output filename should be
407 // relative to that.
Anders Carlsson9ba8fb12011-03-14 01:13:54 +0000408 FileMgr->FixupRelativePath(NewOutFile);
Anders Carlssonb5c356a2011-03-06 22:25:35 +0000409 if (llvm::error_code ec = llvm::sys::fs::rename(it->TempFilename,
410 NewOutFile.str())) {
Argyrios Kyrtzidisd0599972010-09-17 17:38:48 +0000411 getDiagnostics().Report(diag::err_fe_unable_to_rename_temp)
Anders Carlssonb5c356a2011-03-06 22:25:35 +0000412 << it->TempFilename << it->Filename << ec.message();
413
414 bool existed;
415 llvm::sys::fs::remove(it->TempFilename, existed);
Argyrios Kyrtzidisd0599972010-09-17 17:38:48 +0000416 }
417 }
418 } else if (!it->Filename.empty() && EraseFiles)
419 llvm::sys::Path(it->Filename).eraseFromDisk();
420
Daniel Dunbar566eeb22009-11-13 10:37:48 +0000421 }
422 OutputFiles.clear();
423}
424
Daniel Dunbar420b0f12009-11-13 18:32:08 +0000425llvm::raw_fd_ostream *
426CompilerInstance::createDefaultOutputFile(bool Binary,
427 llvm::StringRef InFile,
428 llvm::StringRef Extension) {
429 return createOutputFile(getFrontendOpts().OutputFile, Binary,
Daniel Dunbare326f9b2011-01-31 22:00:42 +0000430 /*RemoveFileOnSignal=*/true, InFile, Extension);
Daniel Dunbar420b0f12009-11-13 18:32:08 +0000431}
432
433llvm::raw_fd_ostream *
434CompilerInstance::createOutputFile(llvm::StringRef OutputPath,
Daniel Dunbare326f9b2011-01-31 22:00:42 +0000435 bool Binary, bool RemoveFileOnSignal,
Daniel Dunbar420b0f12009-11-13 18:32:08 +0000436 llvm::StringRef InFile,
437 llvm::StringRef Extension) {
Argyrios Kyrtzidisd0599972010-09-17 17:38:48 +0000438 std::string Error, OutputPathName, TempPathName;
Daniel Dunbar420b0f12009-11-13 18:32:08 +0000439 llvm::raw_fd_ostream *OS = createOutputFile(OutputPath, Error, Binary,
Daniel Dunbare326f9b2011-01-31 22:00:42 +0000440 RemoveFileOnSignal,
Daniel Dunbar420b0f12009-11-13 18:32:08 +0000441 InFile, Extension,
Argyrios Kyrtzidisd0599972010-09-17 17:38:48 +0000442 &OutputPathName,
443 &TempPathName);
Daniel Dunbar420b0f12009-11-13 18:32:08 +0000444 if (!OS) {
Daniel Dunbar75546992009-12-03 09:13:30 +0000445 getDiagnostics().Report(diag::err_fe_unable_to_open_output)
446 << OutputPath << Error;
447 return 0;
Daniel Dunbar420b0f12009-11-13 18:32:08 +0000448 }
449
450 // Add the output file -- but don't try to remove "-", since this means we are
451 // using stdin.
Argyrios Kyrtzidisd0599972010-09-17 17:38:48 +0000452 addOutputFile(OutputFile((OutputPathName != "-") ? OutputPathName : "",
453 TempPathName, OS));
Daniel Dunbar420b0f12009-11-13 18:32:08 +0000454
455 return OS;
456}
457
458llvm::raw_fd_ostream *
459CompilerInstance::createOutputFile(llvm::StringRef OutputPath,
460 std::string &Error,
461 bool Binary,
Daniel Dunbare326f9b2011-01-31 22:00:42 +0000462 bool RemoveFileOnSignal,
Daniel Dunbar420b0f12009-11-13 18:32:08 +0000463 llvm::StringRef InFile,
464 llvm::StringRef Extension,
Argyrios Kyrtzidisd0599972010-09-17 17:38:48 +0000465 std::string *ResultPathName,
466 std::string *TempPathName) {
467 std::string OutFile, TempFile;
Daniel Dunbar420b0f12009-11-13 18:32:08 +0000468 if (!OutputPath.empty()) {
469 OutFile = OutputPath;
470 } else if (InFile == "-") {
471 OutFile = "-";
472 } else if (!Extension.empty()) {
473 llvm::sys::Path Path(InFile);
474 Path.eraseSuffix();
475 Path.appendSuffix(Extension);
476 OutFile = Path.str();
477 } else {
478 OutFile = "-";
479 }
Argyrios Kyrtzidisd0599972010-09-17 17:38:48 +0000480
481 if (OutFile != "-") {
482 llvm::sys::Path OutPath(OutFile);
483 // Only create the temporary if we can actually write to OutPath, otherwise
484 // we want to fail early.
Michael J. Spencerf6efe582011-01-10 02:34:13 +0000485 bool Exists;
486 if ((llvm::sys::fs::exists(OutPath.str(), Exists) || !Exists) ||
Argyrios Kyrtzidisd0599972010-09-17 17:38:48 +0000487 (OutPath.isRegularFile() && OutPath.canWrite())) {
488 // Create a temporary file.
489 llvm::sys::Path TempPath(OutFile);
490 if (!TempPath.createTemporaryFileOnDisk())
491 TempFile = TempPath.str();
492 }
493 }
494
495 std::string OSFile = OutFile;
496 if (!TempFile.empty())
497 OSFile = TempFile;
Daniel Dunbar420b0f12009-11-13 18:32:08 +0000498
Daniel Dunbar2eaef182009-11-20 22:32:38 +0000499 llvm::OwningPtr<llvm::raw_fd_ostream> OS(
Argyrios Kyrtzidisd0599972010-09-17 17:38:48 +0000500 new llvm::raw_fd_ostream(OSFile.c_str(), Error,
Daniel Dunbar2eaef182009-11-20 22:32:38 +0000501 (Binary ? llvm::raw_fd_ostream::F_Binary : 0)));
502 if (!Error.empty())
Daniel Dunbar420b0f12009-11-13 18:32:08 +0000503 return 0;
504
Argyrios Kyrtzidisd0599972010-09-17 17:38:48 +0000505 // Make sure the out stream file gets removed if we crash.
Daniel Dunbare326f9b2011-01-31 22:00:42 +0000506 if (RemoveFileOnSignal)
507 llvm::sys::RemoveFileOnSignal(llvm::sys::Path(OSFile));
Argyrios Kyrtzidisd0599972010-09-17 17:38:48 +0000508
Daniel Dunbar420b0f12009-11-13 18:32:08 +0000509 if (ResultPathName)
510 *ResultPathName = OutFile;
Argyrios Kyrtzidisd0599972010-09-17 17:38:48 +0000511 if (TempPathName)
512 *TempPathName = TempFile;
Daniel Dunbar420b0f12009-11-13 18:32:08 +0000513
Daniel Dunbar2eaef182009-11-20 22:32:38 +0000514 return OS.take();
Daniel Dunbar420b0f12009-11-13 18:32:08 +0000515}
Daniel Dunbar409e8902009-11-14 07:53:04 +0000516
517// Initialization Utilities
518
519bool CompilerInstance::InitializeSourceManager(llvm::StringRef InputFile) {
520 return InitializeSourceManager(InputFile, getDiagnostics(), getFileManager(),
521 getSourceManager(), getFrontendOpts());
522}
523
524bool CompilerInstance::InitializeSourceManager(llvm::StringRef InputFile,
525 Diagnostic &Diags,
526 FileManager &FileMgr,
527 SourceManager &SourceMgr,
528 const FrontendOptions &Opts) {
Douglas Gregor936a5b42010-11-30 05:23:00 +0000529 // Figure out where to get and map in the main file, unless it's already
530 // been created (e.g., by a precompiled preamble).
531 if (!SourceMgr.getMainFileID().isInvalid()) {
532 // Do nothing: the main file has already been set.
533 } else if (InputFile != "-") {
Chris Lattner5159f612010-11-23 08:35:12 +0000534 const FileEntry *File = FileMgr.getFile(InputFile);
Dan Gohman52765212010-10-26 21:13:51 +0000535 if (!File) {
Daniel Dunbar409e8902009-11-14 07:53:04 +0000536 Diags.Report(diag::err_fe_error_reading) << InputFile;
537 return false;
538 }
Dan Gohman52765212010-10-26 21:13:51 +0000539 SourceMgr.createMainFileID(File);
Daniel Dunbar409e8902009-11-14 07:53:04 +0000540 } else {
Michael J. Spencerd9da7a12010-12-16 03:28:14 +0000541 llvm::OwningPtr<llvm::MemoryBuffer> SB;
542 if (llvm::MemoryBuffer::getSTDIN(SB)) {
Michael J. Spencerf25faaa2010-12-09 17:36:38 +0000543 // FIXME: Give ec.message() in this diag.
Daniel Dunbar409e8902009-11-14 07:53:04 +0000544 Diags.Report(diag::err_fe_error_reading_stdin);
545 return false;
546 }
Dan Gohman2f76cd72010-10-26 23:21:25 +0000547 const FileEntry *File = FileMgr.getVirtualFile(SB->getBufferIdentifier(),
Chris Lattner5159f612010-11-23 08:35:12 +0000548 SB->getBufferSize(), 0);
Dan Gohman2f76cd72010-10-26 23:21:25 +0000549 SourceMgr.createMainFileID(File);
Michael J. Spencerd9da7a12010-12-16 03:28:14 +0000550 SourceMgr.overrideFileContents(File, SB.take());
Daniel Dunbar409e8902009-11-14 07:53:04 +0000551 }
552
Dan Gohman52765212010-10-26 21:13:51 +0000553 assert(!SourceMgr.getMainFileID().isInvalid() &&
554 "Couldn't establish MainFileID!");
Daniel Dunbar409e8902009-11-14 07:53:04 +0000555 return true;
556}
Daniel Dunbar4f2bc552010-01-13 00:48:06 +0000557
558// High-Level Operations
559
560bool CompilerInstance::ExecuteAction(FrontendAction &Act) {
561 assert(hasDiagnostics() && "Diagnostics engine is not initialized!");
562 assert(!getFrontendOpts().ShowHelp && "Client must handle '-help'!");
563 assert(!getFrontendOpts().ShowVersion && "Client must handle '-version'!");
564
565 // FIXME: Take this as an argument, once all the APIs we used have moved to
566 // taking it as an input instead of hard-coding llvm::errs.
567 llvm::raw_ostream &OS = llvm::errs();
568
569 // Create the target instance.
570 setTarget(TargetInfo::CreateTargetInfo(getDiagnostics(), getTargetOpts()));
571 if (!hasTarget())
572 return false;
573
574 // Inform the target of the language options.
575 //
576 // FIXME: We shouldn't need to do this, the target should be immutable once
577 // created. This complexity should be lifted elsewhere.
578 getTarget().setForcedLangOptions(getLangOpts());
579
580 // Validate/process some options.
581 if (getHeaderSearchOpts().Verbose)
582 OS << "clang -cc1 version " CLANG_VERSION_STRING
583 << " based upon " << PACKAGE_STRING
584 << " hosted on " << llvm::sys::getHostTriple() << "\n";
585
586 if (getFrontendOpts().ShowTimers)
587 createFrontendTimer();
588
Douglas Gregor171b7802010-03-30 17:33:59 +0000589 if (getFrontendOpts().ShowStats)
590 llvm::EnableStatistics();
591
Daniel Dunbar4f2bc552010-01-13 00:48:06 +0000592 for (unsigned i = 0, e = getFrontendOpts().Inputs.size(); i != e; ++i) {
593 const std::string &InFile = getFrontendOpts().Inputs[i].second;
594
Daniel Dunbaraed46fc2010-06-07 23:23:50 +0000595 // Reset the ID tables if we are reusing the SourceManager.
596 if (hasSourceManager())
597 getSourceManager().clearIDTables();
Daniel Dunbar4f2bc552010-01-13 00:48:06 +0000598
Daniel Dunbar86546382010-06-07 23:23:06 +0000599 if (Act.BeginSourceFile(*this, InFile, getFrontendOpts().Inputs[i].first)) {
Daniel Dunbar4f2bc552010-01-13 00:48:06 +0000600 Act.Execute();
601 Act.EndSourceFile();
602 }
603 }
604
Chris Lattner198cb4d2010-04-07 18:47:42 +0000605 if (getDiagnosticOpts().ShowCarets) {
Argyrios Kyrtzidisc79346a2010-11-18 20:06:46 +0000606 // We can have multiple diagnostics sharing one diagnostic client.
607 // Get the total number of warnings/errors from the client.
608 unsigned NumWarnings = getDiagnostics().getClient()->getNumWarnings();
609 unsigned NumErrors = getDiagnostics().getClient()->getNumErrors();
Chris Lattner198cb4d2010-04-07 18:47:42 +0000610
611 if (NumWarnings)
612 OS << NumWarnings << " warning" << (NumWarnings == 1 ? "" : "s");
613 if (NumWarnings && NumErrors)
614 OS << " and ";
615 if (NumErrors)
616 OS << NumErrors << " error" << (NumErrors == 1 ? "" : "s");
617 if (NumWarnings || NumErrors)
618 OS << " generated.\n";
619 }
Daniel Dunbar4f2bc552010-01-13 00:48:06 +0000620
Daniel Dunbaraed46fc2010-06-07 23:23:50 +0000621 if (getFrontendOpts().ShowStats && hasFileManager()) {
Daniel Dunbar4f2bc552010-01-13 00:48:06 +0000622 getFileManager().PrintStats();
623 OS << "\n";
624 }
625
Argyrios Kyrtzidisbc467932010-11-18 21:13:57 +0000626 return !getDiagnostics().getClient()->getNumErrors();
Daniel Dunbar4f2bc552010-01-13 00:48:06 +0000627}
628
629