blob: 026cb5a3d51b4ea7bfd2abdcbc75a55dad91de04 [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"
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +000022#include "clang/Frontend/ChainedDiagnosticClient.h"
Daniel Dunbar0397af22010-01-13 00:48:06 +000023#include "clang/Frontend/FrontendAction.h"
Daniel Dunbarc2f484f2009-11-13 09:36:05 +000024#include "clang/Frontend/FrontendDiagnostic.h"
Daniel Dunbar9df23492011-04-07 18:31:10 +000025#include "clang/Frontend/LogDiagnosticPrinter.h"
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +000026#include "clang/Frontend/TextDiagnosticPrinter.h"
Daniel Dunbarf79dced2009-11-14 03:24:39 +000027#include "clang/Frontend/VerifyDiagnosticsClient.h"
Daniel Dunbar22dacfa2009-11-13 05:52:11 +000028#include "clang/Frontend/Utils.h"
Sebastian Redl6ab7cd82010-08-18 23:57:17 +000029#include "clang/Serialization/ASTReader.h"
Daniel Dunbarc2f484f2009-11-13 09:36:05 +000030#include "clang/Sema/CodeCompleteConsumer.h"
Michael J. Spencer32bef4e2011-01-10 02:34:13 +000031#include "llvm/Support/FileSystem.h"
Daniel Dunbarccb6cb62009-11-14 07:53:04 +000032#include "llvm/Support/MemoryBuffer.h"
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +000033#include "llvm/Support/raw_ostream.h"
Douglas Gregor95dd5582010-03-30 17:33:59 +000034#include "llvm/ADT/Statistic.h"
Kovarththanan Rajaratnamf79bafa2009-11-29 09:57:35 +000035#include "llvm/Support/Timer.h"
Michael J. Spencer03013fa2010-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. Spencer3a321e22010-12-09 17:36:38 +000040#include "llvm/Support/system_error.h"
Dylan Noblesmith16266012011-06-23 12:20:57 +000041#include "llvm/Config/config.h"
Daniel Dunbar2a79e162009-11-13 03:51:44 +000042using namespace clang;
43
Daniel Dunbar42e9f8e42010-02-16 01:54:47 +000044CompilerInstance::CompilerInstance()
Douglas Gregorf62d43d2011-07-19 16:10:42 +000045 : Invocation(new CompilerInvocation()), ModuleManager(0) {
Daniel Dunbar6228ca02010-01-30 21:47:07 +000046}
Daniel Dunbar2a79e162009-11-13 03:51:44 +000047
48CompilerInstance::~CompilerInstance() {
Daniel Dunbar42e9f8e42010-02-16 01:54:47 +000049}
50
Daniel Dunbar6228ca02010-01-30 21:47:07 +000051void CompilerInstance::setInvocation(CompilerInvocation *Value) {
Ted Kremenek4f327862011-03-21 18:40:17 +000052 Invocation = Value;
Daniel Dunbar6228ca02010-01-30 21:47:07 +000053}
54
Daniel Dunbar8a9f5692009-11-14 01:20:40 +000055void CompilerInstance::setDiagnostics(Diagnostic *Value) {
Douglas Gregor28019772010-04-05 23:52:57 +000056 Diagnostics = Value;
Daniel Dunbar8a9f5692009-11-14 01:20:40 +000057}
58
Daniel Dunbar8a9f5692009-11-14 01:20:40 +000059void CompilerInstance::setTarget(TargetInfo *Value) {
Ted Kremenek4f327862011-03-21 18:40:17 +000060 Target = Value;
Daniel Dunbar8a9f5692009-11-14 01:20:40 +000061}
62
63void CompilerInstance::setFileManager(FileManager *Value) {
Ted Kremenek4f327862011-03-21 18:40:17 +000064 FileMgr = Value;
Daniel Dunbar8a9f5692009-11-14 01:20:40 +000065}
66
Ted Kremenek4f327862011-03-21 18:40:17 +000067void CompilerInstance::setSourceManager(SourceManager *Value) {
68 SourceMgr = Value;
Daniel Dunbar8a9f5692009-11-14 01:20:40 +000069}
70
Ted Kremenek4f327862011-03-21 18:40:17 +000071void CompilerInstance::setPreprocessor(Preprocessor *Value) { PP = Value; }
Daniel Dunbar8a9f5692009-11-14 01:20:40 +000072
Ted Kremenek4f327862011-03-21 18:40:17 +000073void CompilerInstance::setASTContext(ASTContext *Value) { Context = Value; }
Daniel Dunbar8a9f5692009-11-14 01:20:40 +000074
Douglas Gregorf18d0d82010-08-12 23:31:19 +000075void CompilerInstance::setSema(Sema *S) {
76 TheSema.reset(S);
77}
78
Daniel Dunbar12ce6942009-11-14 02:47:17 +000079void CompilerInstance::setASTConsumer(ASTConsumer *Value) {
80 Consumer.reset(Value);
81}
82
Daniel Dunbar8a9f5692009-11-14 01:20:40 +000083void CompilerInstance::setCodeCompletionConsumer(CodeCompleteConsumer *Value) {
84 CompletionConsumer.reset(Value);
85}
86
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +000087// Diagnostics
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +000088static void SetUpBuildDumpLog(const DiagnosticOptions &DiagOpts,
Axel Naumann7d0c4cc2010-10-11 09:13:46 +000089 unsigned argc, const char* const *argv,
Kovarththanan Rajaratnam3d67b1e2010-03-17 09:24:48 +000090 Diagnostic &Diags) {
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +000091 std::string ErrorInfo;
Chris Lattner5f9e2722011-07-23 10:55:15 +000092 llvm::OwningPtr<raw_ostream> OS(
Kovarththanan Rajaratnam69247132010-03-17 09:47:30 +000093 new llvm::raw_fd_ostream(DiagOpts.DumpBuildInformation.c_str(), ErrorInfo));
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +000094 if (!ErrorInfo.empty()) {
Kovarththanan Rajaratnam3d67b1e2010-03-17 09:24:48 +000095 Diags.Report(diag::err_fe_unable_to_open_logfile)
96 << DiagOpts.DumpBuildInformation << ErrorInfo;
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +000097 return;
98 }
99
Daniel Dunbardd63b282009-12-11 23:04:35 +0000100 (*OS) << "clang -cc1 command line arguments: ";
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000101 for (unsigned i = 0; i != argc; ++i)
102 (*OS) << argv[i] << ' ';
103 (*OS) << '\n';
104
105 // Chain in a diagnostic client which will log the diagnostics.
106 DiagnosticClient *Logger =
Kovarththanan Rajaratnam69247132010-03-17 09:47:30 +0000107 new TextDiagnosticPrinter(*OS.take(), DiagOpts, /*OwnsOutputStream=*/true);
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000108 Diags.setClient(new ChainedDiagnosticClient(Diags.takeClient(), Logger));
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000109}
110
Daniel Dunbar9df23492011-04-07 18:31:10 +0000111static void SetUpDiagnosticLog(const DiagnosticOptions &DiagOpts,
Daniel Dunbarb6534bb2011-04-07 18:59:02 +0000112 const CodeGenOptions *CodeGenOpts,
Daniel Dunbar9df23492011-04-07 18:31:10 +0000113 Diagnostic &Diags) {
114 std::string ErrorInfo;
115 bool OwnsStream = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000116 raw_ostream *OS = &llvm::errs();
Daniel Dunbar9df23492011-04-07 18:31:10 +0000117 if (DiagOpts.DiagnosticLogFile != "-") {
118 // Create the output stream.
119 llvm::raw_fd_ostream *FileOS(
120 new llvm::raw_fd_ostream(DiagOpts.DiagnosticLogFile.c_str(),
Daniel Dunbare01eceb2011-04-07 20:19:21 +0000121 ErrorInfo, llvm::raw_fd_ostream::F_Append));
Daniel Dunbar9df23492011-04-07 18:31:10 +0000122 if (!ErrorInfo.empty()) {
123 Diags.Report(diag::warn_fe_cc_log_diagnostics_failure)
124 << DiagOpts.DumpBuildInformation << ErrorInfo;
125 } else {
126 FileOS->SetUnbuffered();
127 FileOS->SetUseAtomicWrites(true);
128 OS = FileOS;
129 OwnsStream = true;
130 }
131 }
132
133 // Chain in the diagnostic client which will log the diagnostics.
Daniel Dunbarb6534bb2011-04-07 18:59:02 +0000134 LogDiagnosticPrinter *Logger = new LogDiagnosticPrinter(*OS, DiagOpts,
135 OwnsStream);
136 if (CodeGenOpts)
137 Logger->setDwarfDebugFlags(CodeGenOpts->DwarfDebugFlags);
Daniel Dunbar9df23492011-04-07 18:31:10 +0000138 Diags.setClient(new ChainedDiagnosticClient(Diags.takeClient(), Logger));
139}
140
Douglas Gregore47be3e2010-11-11 00:39:14 +0000141void CompilerInstance::createDiagnostics(int Argc, const char* const *Argv,
142 DiagnosticClient *Client) {
Daniel Dunbarb6534bb2011-04-07 18:59:02 +0000143 Diagnostics = createDiagnostics(getDiagnosticOpts(), Argc, Argv, Client,
144 &getCodeGenOpts());
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000145}
146
Douglas Gregor28019772010-04-05 23:52:57 +0000147llvm::IntrusiveRefCntPtr<Diagnostic>
148CompilerInstance::createDiagnostics(const DiagnosticOptions &Opts,
Douglas Gregore47be3e2010-11-11 00:39:14 +0000149 int Argc, const char* const *Argv,
Daniel Dunbarb6534bb2011-04-07 18:59:02 +0000150 DiagnosticClient *Client,
151 const CodeGenOptions *CodeGenOpts) {
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000152 llvm::IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
153 llvm::IntrusiveRefCntPtr<Diagnostic> Diags(new Diagnostic(DiagID));
Daniel Dunbar221c7212009-11-14 07:53:24 +0000154
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000155 // Create the diagnostic client for reporting errors or for
156 // implementing -verify.
Douglas Gregore47be3e2010-11-11 00:39:14 +0000157 if (Client)
158 Diags->setClient(Client);
159 else
160 Diags->setClient(new TextDiagnosticPrinter(llvm::errs(), Opts));
Daniel Dunbarf79dced2009-11-14 03:24:39 +0000161
162 // Chain in -verify checker, if requested.
163 if (Opts.VerifyDiagnostics)
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000164 Diags->setClient(new VerifyDiagnosticsClient(*Diags, Diags->takeClient()));
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000165
Daniel Dunbar9df23492011-04-07 18:31:10 +0000166 // Chain in -diagnostic-log-file dumper, if requested.
167 if (!Opts.DiagnosticLogFile.empty())
Daniel Dunbarb6534bb2011-04-07 18:59:02 +0000168 SetUpDiagnosticLog(Opts, CodeGenOpts, *Diags);
Daniel Dunbar9df23492011-04-07 18:31:10 +0000169
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000170 if (!Opts.DumpBuildInformation.empty())
Kovarththanan Rajaratnam3d67b1e2010-03-17 09:24:48 +0000171 SetUpBuildDumpLog(Opts, Argc, Argv, *Diags);
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000172
173 // Configure our handling of diagnostics.
Kovarththanan Rajaratnam5bf932b2010-03-17 09:36:02 +0000174 ProcessWarningOptions(*Diags, Opts);
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000175
Douglas Gregor28019772010-04-05 23:52:57 +0000176 return Diags;
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000177}
178
179// File Manager
180
Daniel Dunbar16b74492009-11-13 04:12:06 +0000181void CompilerInstance::createFileManager() {
Ted Kremenek4f327862011-03-21 18:40:17 +0000182 FileMgr = new FileManager(getFileSystemOpts());
Daniel Dunbar16b74492009-11-13 04:12:06 +0000183}
184
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000185// Source Manager
186
Chris Lattner39b49bc2010-11-23 08:35:12 +0000187void CompilerInstance::createSourceManager(FileManager &FileMgr) {
Ted Kremenek4f327862011-03-21 18:40:17 +0000188 SourceMgr = new SourceManager(getDiagnostics(), FileMgr);
Daniel Dunbar16b74492009-11-13 04:12:06 +0000189}
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000190
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000191// Preprocessor
192
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000193void CompilerInstance::createPreprocessor() {
Ted Kremenek4f327862011-03-21 18:40:17 +0000194 PP = createPreprocessor(getDiagnostics(), getLangOpts(),
195 getPreprocessorOpts(), getHeaderSearchOpts(),
196 getDependencyOutputOpts(), getTarget(),
197 getFrontendOpts(), getSourceManager(),
198 getFileManager());
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000199}
200
201Preprocessor *
202CompilerInstance::createPreprocessor(Diagnostic &Diags,
203 const LangOptions &LangInfo,
204 const PreprocessorOptions &PPOpts,
205 const HeaderSearchOptions &HSOpts,
206 const DependencyOutputOptions &DepOpts,
207 const TargetInfo &Target,
Fariborz Jahanian7d957472010-01-13 18:51:17 +0000208 const FrontendOptions &FEOpts,
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000209 SourceManager &SourceMgr,
210 FileManager &FileMgr) {
211 // Create a PTH manager if we are using some form of a token cache.
212 PTHManager *PTHMgr = 0;
Daniel Dunbar049d3a02009-11-17 05:52:41 +0000213 if (!PPOpts.TokenCache.empty())
Chris Lattner681c74a2010-11-23 09:01:31 +0000214 PTHMgr = PTHManager::Create(PPOpts.TokenCache, Diags);
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000215
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000216 // Create the Preprocessor.
Chris Lattner39b49bc2010-11-23 08:35:12 +0000217 HeaderSearch *HeaderInfo = new HeaderSearch(FileMgr);
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000218 Preprocessor *PP = new Preprocessor(Diags, LangInfo, Target,
219 SourceMgr, *HeaderInfo, PTHMgr,
220 /*OwnsHeaderSearch=*/true);
221
222 // Note that this is different then passing PTHMgr to Preprocessor's ctor.
223 // That argument is used as the IdentifierInfoLookup argument to
224 // IdentifierTable's ctor.
225 if (PTHMgr) {
226 PTHMgr->setPreprocessor(PP);
227 PP->setPTHManager(PTHMgr);
228 }
229
Douglas Gregor94dc8f62010-03-19 16:15:56 +0000230 if (PPOpts.DetailedRecord)
Douglas Gregordca8ee82011-05-06 16:33:08 +0000231 PP->createPreprocessingRecord(
Chandler Carruthba7537f2011-07-14 09:02:10 +0000232 PPOpts.DetailedRecordIncludesNestedMacroExpansions);
Douglas Gregor94dc8f62010-03-19 16:15:56 +0000233
Chris Lattner39b49bc2010-11-23 08:35:12 +0000234 InitializePreprocessor(*PP, PPOpts, HSOpts, FEOpts);
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000235
236 // Handle generating dependencies, if requested.
237 if (!DepOpts.OutputFile.empty())
238 AttachDependencyFileGen(*PP, DepOpts);
239
Daniel Dunbareef63e02011-02-02 15:41:17 +0000240 // Handle generating header include information, if requested.
241 if (DepOpts.ShowHeaderIncludes)
242 AttachHeaderIncludeGen(*PP);
Daniel Dunbarb34d69b2011-02-02 21:11:31 +0000243 if (!DepOpts.HeaderIncludeOutputFile.empty()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000244 StringRef OutputPath = DepOpts.HeaderIncludeOutputFile;
Daniel Dunbarb34d69b2011-02-02 21:11:31 +0000245 if (OutputPath == "-")
246 OutputPath = "";
Daniel Dunbarda608852011-03-21 19:37:38 +0000247 AttachHeaderIncludeGen(*PP, /*ShowAllHeaders=*/true, OutputPath,
248 /*ShowDepth=*/false);
Daniel Dunbarb34d69b2011-02-02 21:11:31 +0000249 }
Daniel Dunbareef63e02011-02-02 15:41:17 +0000250
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000251 return PP;
252}
Daniel Dunbar5eb81002009-11-13 08:20:47 +0000253
254// ASTContext
255
256void CompilerInstance::createASTContext() {
257 Preprocessor &PP = getPreprocessor();
Ted Kremenek4f327862011-03-21 18:40:17 +0000258 Context = new ASTContext(getLangOpts(), PP.getSourceManager(),
259 getTarget(), PP.getIdentifierTable(),
260 PP.getSelectorTable(), PP.getBuiltinInfo(),
261 /*size_reserve=*/ 0);
Daniel Dunbar5eb81002009-11-13 08:20:47 +0000262}
Daniel Dunbar0f800392009-11-13 08:21:10 +0000263
264// ExternalASTSource
265
Chris Lattner5f9e2722011-07-23 10:55:15 +0000266void CompilerInstance::createPCHExternalASTSource(StringRef Path,
Sebastian Redlffaab3e2010-07-30 00:29:29 +0000267 bool DisablePCHValidation,
Douglas Gregor8ef6c8c2011-02-05 19:42:43 +0000268 bool DisableStatCache,
Sebastian Redlffaab3e2010-07-30 00:29:29 +0000269 void *DeserializationListener){
Daniel Dunbar0f800392009-11-13 08:21:10 +0000270 llvm::OwningPtr<ExternalASTSource> Source;
Sebastian Redl1d9f1fe2010-10-05 16:15:19 +0000271 bool Preamble = getPreprocessorOpts().PrecompiledPreambleBytes.first != 0;
Daniel Dunbar0f800392009-11-13 08:21:10 +0000272 Source.reset(createPCHExternalASTSource(Path, getHeaderSearchOpts().Sysroot,
Douglas Gregor8ef6c8c2011-02-05 19:42:43 +0000273 DisablePCHValidation,
274 DisableStatCache,
Sebastian Redlffaab3e2010-07-30 00:29:29 +0000275 getPreprocessor(), getASTContext(),
Sebastian Redl1d9f1fe2010-10-05 16:15:19 +0000276 DeserializationListener,
277 Preamble));
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000278 ModuleManager = static_cast<ASTReader*>(Source.get());
Daniel Dunbar0f800392009-11-13 08:21:10 +0000279 getASTContext().setExternalSource(Source);
280}
281
282ExternalASTSource *
Chris Lattner5f9e2722011-07-23 10:55:15 +0000283CompilerInstance::createPCHExternalASTSource(StringRef Path,
Daniel Dunbar0f800392009-11-13 08:21:10 +0000284 const std::string &Sysroot,
Douglas Gregorfae3b2f2010-07-27 00:27:13 +0000285 bool DisablePCHValidation,
Douglas Gregor8ef6c8c2011-02-05 19:42:43 +0000286 bool DisableStatCache,
Daniel Dunbar0f800392009-11-13 08:21:10 +0000287 Preprocessor &PP,
Sebastian Redlffaab3e2010-07-30 00:29:29 +0000288 ASTContext &Context,
Sebastian Redl1d9f1fe2010-10-05 16:15:19 +0000289 void *DeserializationListener,
290 bool Preamble) {
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000291 llvm::OwningPtr<ASTReader> Reader;
292 Reader.reset(new ASTReader(PP, &Context,
Douglas Gregor832d6202011-07-22 16:35:34 +0000293 Sysroot.empty() ? "" : Sysroot.c_str(),
Douglas Gregor8ef6c8c2011-02-05 19:42:43 +0000294 DisablePCHValidation, DisableStatCache));
Daniel Dunbar0f800392009-11-13 08:21:10 +0000295
Sebastian Redlffaab3e2010-07-30 00:29:29 +0000296 Reader->setDeserializationListener(
Sebastian Redl571db7f2010-08-18 23:56:56 +0000297 static_cast<ASTDeserializationListener *>(DeserializationListener));
Douglas Gregor72a9ae12011-07-22 16:00:58 +0000298 switch (Reader->ReadAST(Path,
299 Preamble ? serialization::MK_Preamble
300 : serialization::MK_PCH)) {
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000301 case ASTReader::Success:
Daniel Dunbar0f800392009-11-13 08:21:10 +0000302 // Set the predefines buffer as suggested by the PCH reader. Typically, the
303 // predefines buffer will be empty.
304 PP.setPredefines(Reader->getSuggestedPredefines());
305 return Reader.take();
306
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000307 case ASTReader::Failure:
Daniel Dunbar0f800392009-11-13 08:21:10 +0000308 // Unrecoverable failure: don't even try to process the input file.
309 break;
310
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000311 case ASTReader::IgnorePCH:
Daniel Dunbar0f800392009-11-13 08:21:10 +0000312 // No suitable PCH file could be found. Return an error.
313 break;
314 }
315
316 return 0;
317}
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000318
319// Code Completion
320
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000321static bool EnableCodeCompletion(Preprocessor &PP,
322 const std::string &Filename,
323 unsigned Line,
324 unsigned Column) {
325 // Tell the source manager to chop off the given file at a specific
326 // line and column.
Chris Lattner39b49bc2010-11-23 08:35:12 +0000327 const FileEntry *Entry = PP.getFileManager().getFile(Filename);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000328 if (!Entry) {
329 PP.getDiagnostics().Report(diag::err_fe_invalid_code_complete_file)
330 << Filename;
331 return true;
332 }
333
334 // Truncate the named file at the given line/column.
335 PP.SetCodeCompletionPoint(Entry, Line, Column);
336 return false;
337}
338
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000339void CompilerInstance::createCodeCompletionConsumer() {
340 const ParsedSourceLocation &Loc = getFrontendOpts().CodeCompletionAt;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000341 if (!CompletionConsumer) {
342 CompletionConsumer.reset(
343 createCodeCompletionConsumer(getPreprocessor(),
344 Loc.FileName, Loc.Line, Loc.Column,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000345 getFrontendOpts().ShowMacrosInCodeCompletion,
Douglas Gregord8e8a582010-05-25 21:41:55 +0000346 getFrontendOpts().ShowCodePatternsInCodeCompletion,
Douglas Gregor8071e422010-08-15 06:18:01 +0000347 getFrontendOpts().ShowGlobalSymbolsInCodeCompletion,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000348 llvm::outs()));
349 if (!CompletionConsumer)
350 return;
351 } else if (EnableCodeCompletion(getPreprocessor(), Loc.FileName,
352 Loc.Line, Loc.Column)) {
353 CompletionConsumer.reset();
Douglas Gregorc3d43b72010-03-16 06:04:47 +0000354 return;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000355 }
Douglas Gregor2b4074f2009-12-01 05:55:20 +0000356
357 if (CompletionConsumer->isOutputBinary() &&
358 llvm::sys::Program::ChangeStdoutToBinary()) {
359 getPreprocessor().getDiagnostics().Report(diag::err_fe_stdout_binary);
360 CompletionConsumer.reset();
361 }
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000362}
363
Kovarththanan Rajaratnamf79bafa2009-11-29 09:57:35 +0000364void CompilerInstance::createFrontendTimer() {
365 FrontendTimer.reset(new llvm::Timer("Clang front-end timer"));
366}
367
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000368CodeCompleteConsumer *
369CompilerInstance::createCodeCompletionConsumer(Preprocessor &PP,
370 const std::string &Filename,
371 unsigned Line,
372 unsigned Column,
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000373 bool ShowMacros,
Douglas Gregord8e8a582010-05-25 21:41:55 +0000374 bool ShowCodePatterns,
Douglas Gregor8071e422010-08-15 06:18:01 +0000375 bool ShowGlobals,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000376 raw_ostream &OS) {
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000377 if (EnableCodeCompletion(PP, Filename, Line, Column))
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000378 return 0;
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000379
380 // Set up the creation routine for code-completion.
Douglas Gregora9f4f622010-10-11 22:12:15 +0000381 return new PrintingCodeCompleteConsumer(ShowMacros, ShowCodePatterns,
Douglas Gregor8071e422010-08-15 06:18:01 +0000382 ShowGlobals, OS);
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000383}
Daniel Dunbara9204832009-11-13 10:37:48 +0000384
Douglas Gregorf18d0d82010-08-12 23:31:19 +0000385void CompilerInstance::createSema(bool CompleteTranslationUnit,
386 CodeCompleteConsumer *CompletionConsumer) {
387 TheSema.reset(new Sema(getPreprocessor(), getASTContext(), getASTConsumer(),
388 CompleteTranslationUnit, CompletionConsumer));
389}
390
Daniel Dunbara9204832009-11-13 10:37:48 +0000391// Output Files
392
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000393void CompilerInstance::addOutputFile(const OutputFile &OutFile) {
394 assert(OutFile.OS && "Attempt to add empty stream to output list!");
395 OutputFiles.push_back(OutFile);
Daniel Dunbara9204832009-11-13 10:37:48 +0000396}
397
Kovarththanan Rajaratname51dd7b2010-03-06 12:07:48 +0000398void CompilerInstance::clearOutputFiles(bool EraseFiles) {
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000399 for (std::list<OutputFile>::iterator
Daniel Dunbara9204832009-11-13 10:37:48 +0000400 it = OutputFiles.begin(), ie = OutputFiles.end(); it != ie; ++it) {
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000401 delete it->OS;
402 if (!it->TempFilename.empty()) {
Anders Carlssonaf036a62011-03-06 22:25:35 +0000403 if (EraseFiles) {
404 bool existed;
405 llvm::sys::fs::remove(it->TempFilename, existed);
406 } else {
407 llvm::SmallString<128> NewOutFile(it->Filename);
408
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +0000409 // If '-working-directory' was passed, the output filename should be
410 // relative to that.
Anders Carlsson2e2468e2011-03-14 01:13:54 +0000411 FileMgr->FixupRelativePath(NewOutFile);
Anders Carlssonaf036a62011-03-06 22:25:35 +0000412 if (llvm::error_code ec = llvm::sys::fs::rename(it->TempFilename,
413 NewOutFile.str())) {
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000414 getDiagnostics().Report(diag::err_fe_unable_to_rename_temp)
Anders Carlssonaf036a62011-03-06 22:25:35 +0000415 << it->TempFilename << it->Filename << ec.message();
416
417 bool existed;
418 llvm::sys::fs::remove(it->TempFilename, existed);
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000419 }
420 }
421 } else if (!it->Filename.empty() && EraseFiles)
422 llvm::sys::Path(it->Filename).eraseFromDisk();
423
Daniel Dunbara9204832009-11-13 10:37:48 +0000424 }
425 OutputFiles.clear();
426}
427
Daniel Dunbarf482d592009-11-13 18:32:08 +0000428llvm::raw_fd_ostream *
429CompilerInstance::createDefaultOutputFile(bool Binary,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000430 StringRef InFile,
431 StringRef Extension) {
Daniel Dunbarf482d592009-11-13 18:32:08 +0000432 return createOutputFile(getFrontendOpts().OutputFile, Binary,
Daniel Dunbarff9cd962011-01-31 22:00:42 +0000433 /*RemoveFileOnSignal=*/true, InFile, Extension);
Daniel Dunbarf482d592009-11-13 18:32:08 +0000434}
435
436llvm::raw_fd_ostream *
Chris Lattner5f9e2722011-07-23 10:55:15 +0000437CompilerInstance::createOutputFile(StringRef OutputPath,
Daniel Dunbarff9cd962011-01-31 22:00:42 +0000438 bool Binary, bool RemoveFileOnSignal,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000439 StringRef InFile,
Argyrios Kyrtzidis7e909852011-07-28 00:45:10 +0000440 StringRef Extension,
441 bool UseTemporary) {
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000442 std::string Error, OutputPathName, TempPathName;
Daniel Dunbarf482d592009-11-13 18:32:08 +0000443 llvm::raw_fd_ostream *OS = createOutputFile(OutputPath, Error, Binary,
Daniel Dunbarff9cd962011-01-31 22:00:42 +0000444 RemoveFileOnSignal,
Daniel Dunbarf482d592009-11-13 18:32:08 +0000445 InFile, Extension,
Argyrios Kyrtzidis7e909852011-07-28 00:45:10 +0000446 UseTemporary,
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000447 &OutputPathName,
448 &TempPathName);
Daniel Dunbarf482d592009-11-13 18:32:08 +0000449 if (!OS) {
Daniel Dunbar36043592009-12-03 09:13:30 +0000450 getDiagnostics().Report(diag::err_fe_unable_to_open_output)
451 << OutputPath << Error;
452 return 0;
Daniel Dunbarf482d592009-11-13 18:32:08 +0000453 }
454
455 // Add the output file -- but don't try to remove "-", since this means we are
456 // using stdin.
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000457 addOutputFile(OutputFile((OutputPathName != "-") ? OutputPathName : "",
458 TempPathName, OS));
Daniel Dunbarf482d592009-11-13 18:32:08 +0000459
460 return OS;
461}
462
463llvm::raw_fd_ostream *
Chris Lattner5f9e2722011-07-23 10:55:15 +0000464CompilerInstance::createOutputFile(StringRef OutputPath,
Daniel Dunbarf482d592009-11-13 18:32:08 +0000465 std::string &Error,
466 bool Binary,
Daniel Dunbarff9cd962011-01-31 22:00:42 +0000467 bool RemoveFileOnSignal,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000468 StringRef InFile,
469 StringRef Extension,
Argyrios Kyrtzidis7e909852011-07-28 00:45:10 +0000470 bool UseTemporary,
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000471 std::string *ResultPathName,
472 std::string *TempPathName) {
473 std::string OutFile, TempFile;
Daniel Dunbarf482d592009-11-13 18:32:08 +0000474 if (!OutputPath.empty()) {
475 OutFile = OutputPath;
476 } else if (InFile == "-") {
477 OutFile = "-";
478 } else if (!Extension.empty()) {
479 llvm::sys::Path Path(InFile);
480 Path.eraseSuffix();
481 Path.appendSuffix(Extension);
482 OutFile = Path.str();
483 } else {
484 OutFile = "-";
485 }
Argyrios Kyrtzidis7e909852011-07-28 00:45:10 +0000486
487 llvm::OwningPtr<llvm::raw_fd_ostream> OS;
488 std::string OSFile;
489
490 if (UseTemporary && OutFile != "-") {
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000491 llvm::sys::Path OutPath(OutFile);
492 // Only create the temporary if we can actually write to OutPath, otherwise
493 // we want to fail early.
Michael J. Spencer32bef4e2011-01-10 02:34:13 +0000494 bool Exists;
495 if ((llvm::sys::fs::exists(OutPath.str(), Exists) || !Exists) ||
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000496 (OutPath.isRegularFile() && OutPath.canWrite())) {
497 // Create a temporary file.
Argyrios Kyrtzidis7e909852011-07-28 00:45:10 +0000498 llvm::SmallString<128> TempPath;
499 TempPath = OutFile;
500 TempPath += "-%%%%%%%%";
501 int fd;
502 if (llvm::sys::fs::unique_file(TempPath.str(), fd, TempPath,
503 /*makeAbsolute=*/false) == llvm::errc::success) {
504 OS.reset(new llvm::raw_fd_ostream(fd, /*shouldClose=*/true));
505 OSFile = TempFile = TempPath.str();
506 }
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000507 }
508 }
509
Argyrios Kyrtzidis7e909852011-07-28 00:45:10 +0000510 if (!OS) {
511 OSFile = OutFile;
512 OS.reset(
513 new llvm::raw_fd_ostream(OSFile.c_str(), Error,
514 (Binary ? llvm::raw_fd_ostream::F_Binary : 0)));
515 if (!Error.empty())
516 return 0;
517 }
Daniel Dunbarf482d592009-11-13 18:32:08 +0000518
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000519 // Make sure the out stream file gets removed if we crash.
Daniel Dunbarff9cd962011-01-31 22:00:42 +0000520 if (RemoveFileOnSignal)
521 llvm::sys::RemoveFileOnSignal(llvm::sys::Path(OSFile));
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000522
Daniel Dunbarf482d592009-11-13 18:32:08 +0000523 if (ResultPathName)
524 *ResultPathName = OutFile;
Argyrios Kyrtzidisdc245722010-09-17 17:38:48 +0000525 if (TempPathName)
526 *TempPathName = TempFile;
Daniel Dunbarf482d592009-11-13 18:32:08 +0000527
Daniel Dunbarfc971022009-11-20 22:32:38 +0000528 return OS.take();
Daniel Dunbarf482d592009-11-13 18:32:08 +0000529}
Daniel Dunbarccb6cb62009-11-14 07:53:04 +0000530
531// Initialization Utilities
532
Chris Lattner5f9e2722011-07-23 10:55:15 +0000533bool CompilerInstance::InitializeSourceManager(StringRef InputFile) {
Daniel Dunbarccb6cb62009-11-14 07:53:04 +0000534 return InitializeSourceManager(InputFile, getDiagnostics(), getFileManager(),
535 getSourceManager(), getFrontendOpts());
536}
537
Chris Lattner5f9e2722011-07-23 10:55:15 +0000538bool CompilerInstance::InitializeSourceManager(StringRef InputFile,
Daniel Dunbarccb6cb62009-11-14 07:53:04 +0000539 Diagnostic &Diags,
540 FileManager &FileMgr,
541 SourceManager &SourceMgr,
542 const FrontendOptions &Opts) {
Douglas Gregor414cb642010-11-30 05:23:00 +0000543 // Figure out where to get and map in the main file, unless it's already
544 // been created (e.g., by a precompiled preamble).
545 if (!SourceMgr.getMainFileID().isInvalid()) {
546 // Do nothing: the main file has already been set.
547 } else if (InputFile != "-") {
Chris Lattner39b49bc2010-11-23 08:35:12 +0000548 const FileEntry *File = FileMgr.getFile(InputFile);
Dan Gohman694137c2010-10-26 21:13:51 +0000549 if (!File) {
Daniel Dunbarccb6cb62009-11-14 07:53:04 +0000550 Diags.Report(diag::err_fe_error_reading) << InputFile;
551 return false;
552 }
Dan Gohman694137c2010-10-26 21:13:51 +0000553 SourceMgr.createMainFileID(File);
Daniel Dunbarccb6cb62009-11-14 07:53:04 +0000554 } else {
Michael J. Spencer4eeebc42010-12-16 03:28:14 +0000555 llvm::OwningPtr<llvm::MemoryBuffer> SB;
556 if (llvm::MemoryBuffer::getSTDIN(SB)) {
Michael J. Spencer3a321e22010-12-09 17:36:38 +0000557 // FIXME: Give ec.message() in this diag.
Daniel Dunbarccb6cb62009-11-14 07:53:04 +0000558 Diags.Report(diag::err_fe_error_reading_stdin);
559 return false;
560 }
Dan Gohman90d90812010-10-26 23:21:25 +0000561 const FileEntry *File = FileMgr.getVirtualFile(SB->getBufferIdentifier(),
Chris Lattner39b49bc2010-11-23 08:35:12 +0000562 SB->getBufferSize(), 0);
Dan Gohman90d90812010-10-26 23:21:25 +0000563 SourceMgr.createMainFileID(File);
Michael J. Spencer4eeebc42010-12-16 03:28:14 +0000564 SourceMgr.overrideFileContents(File, SB.take());
Daniel Dunbarccb6cb62009-11-14 07:53:04 +0000565 }
566
Dan Gohman694137c2010-10-26 21:13:51 +0000567 assert(!SourceMgr.getMainFileID().isInvalid() &&
568 "Couldn't establish MainFileID!");
Daniel Dunbarccb6cb62009-11-14 07:53:04 +0000569 return true;
570}
Daniel Dunbar0397af22010-01-13 00:48:06 +0000571
572// High-Level Operations
573
574bool CompilerInstance::ExecuteAction(FrontendAction &Act) {
575 assert(hasDiagnostics() && "Diagnostics engine is not initialized!");
576 assert(!getFrontendOpts().ShowHelp && "Client must handle '-help'!");
577 assert(!getFrontendOpts().ShowVersion && "Client must handle '-version'!");
578
579 // FIXME: Take this as an argument, once all the APIs we used have moved to
580 // taking it as an input instead of hard-coding llvm::errs.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000581 raw_ostream &OS = llvm::errs();
Daniel Dunbar0397af22010-01-13 00:48:06 +0000582
583 // Create the target instance.
584 setTarget(TargetInfo::CreateTargetInfo(getDiagnostics(), getTargetOpts()));
585 if (!hasTarget())
586 return false;
587
588 // Inform the target of the language options.
589 //
590 // FIXME: We shouldn't need to do this, the target should be immutable once
591 // created. This complexity should be lifted elsewhere.
592 getTarget().setForcedLangOptions(getLangOpts());
593
594 // Validate/process some options.
595 if (getHeaderSearchOpts().Verbose)
596 OS << "clang -cc1 version " CLANG_VERSION_STRING
597 << " based upon " << PACKAGE_STRING
598 << " hosted on " << llvm::sys::getHostTriple() << "\n";
599
600 if (getFrontendOpts().ShowTimers)
601 createFrontendTimer();
602
Douglas Gregor95dd5582010-03-30 17:33:59 +0000603 if (getFrontendOpts().ShowStats)
604 llvm::EnableStatistics();
605
Daniel Dunbar0397af22010-01-13 00:48:06 +0000606 for (unsigned i = 0, e = getFrontendOpts().Inputs.size(); i != e; ++i) {
607 const std::string &InFile = getFrontendOpts().Inputs[i].second;
608
Daniel Dunbar20560482010-06-07 23:23:50 +0000609 // Reset the ID tables if we are reusing the SourceManager.
610 if (hasSourceManager())
611 getSourceManager().clearIDTables();
Daniel Dunbar0397af22010-01-13 00:48:06 +0000612
Daniel Dunbard3598a62010-06-07 23:23:06 +0000613 if (Act.BeginSourceFile(*this, InFile, getFrontendOpts().Inputs[i].first)) {
Daniel Dunbar0397af22010-01-13 00:48:06 +0000614 Act.Execute();
615 Act.EndSourceFile();
616 }
617 }
618
Chris Lattner53eee7b2010-04-07 18:47:42 +0000619 if (getDiagnosticOpts().ShowCarets) {
Argyrios Kyrtzidisf2224d82010-11-18 20:06:46 +0000620 // We can have multiple diagnostics sharing one diagnostic client.
621 // Get the total number of warnings/errors from the client.
622 unsigned NumWarnings = getDiagnostics().getClient()->getNumWarnings();
623 unsigned NumErrors = getDiagnostics().getClient()->getNumErrors();
Chris Lattner53eee7b2010-04-07 18:47:42 +0000624
625 if (NumWarnings)
626 OS << NumWarnings << " warning" << (NumWarnings == 1 ? "" : "s");
627 if (NumWarnings && NumErrors)
628 OS << " and ";
629 if (NumErrors)
630 OS << NumErrors << " error" << (NumErrors == 1 ? "" : "s");
631 if (NumWarnings || NumErrors)
632 OS << " generated.\n";
633 }
Daniel Dunbar0397af22010-01-13 00:48:06 +0000634
Daniel Dunbar20560482010-06-07 23:23:50 +0000635 if (getFrontendOpts().ShowStats && hasFileManager()) {
Daniel Dunbar0397af22010-01-13 00:48:06 +0000636 getFileManager().PrintStats();
637 OS << "\n";
638 }
639
Argyrios Kyrtzidisab41b972010-11-18 21:13:57 +0000640 return !getDiagnostics().getClient()->getNumErrors();
Daniel Dunbar0397af22010-01-13 00:48:06 +0000641}
642
643