blob: 2d58beead8b57f53d4d7b892ec8064ac625e6c02 [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"
Daniel Dunbar12ce6942009-11-14 02:47:17 +000011#include "clang/AST/ASTConsumer.h"
Daniel Dunbar5eb81002009-11-13 08:20:47 +000012#include "clang/AST/ASTContext.h"
Daniel Dunbar2a79e162009-11-13 03:51:44 +000013#include "clang/Basic/Diagnostic.h"
Daniel Dunbar16b74492009-11-13 04:12:06 +000014#include "clang/Basic/FileManager.h"
15#include "clang/Basic/SourceManager.h"
Daniel Dunbar2a79e162009-11-13 03:51:44 +000016#include "clang/Basic/TargetInfo.h"
Daniel Dunbar22dacfa2009-11-13 05:52:11 +000017#include "clang/Lex/HeaderSearch.h"
18#include "clang/Lex/Preprocessor.h"
19#include "clang/Lex/PTHManager.h"
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +000020#include "clang/Frontend/ChainedDiagnosticClient.h"
Daniel Dunbar0f800392009-11-13 08:21:10 +000021#include "clang/Frontend/PCHReader.h"
Daniel Dunbarc2f484f2009-11-13 09:36:05 +000022#include "clang/Frontend/FrontendDiagnostic.h"
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +000023#include "clang/Frontend/TextDiagnosticPrinter.h"
Daniel Dunbarf79dced2009-11-14 03:24:39 +000024#include "clang/Frontend/VerifyDiagnosticsClient.h"
Daniel Dunbar22dacfa2009-11-13 05:52:11 +000025#include "clang/Frontend/Utils.h"
Daniel Dunbarc2f484f2009-11-13 09:36:05 +000026#include "clang/Sema/CodeCompleteConsumer.h"
Daniel Dunbar2a79e162009-11-13 03:51:44 +000027#include "llvm/LLVMContext.h"
Daniel Dunbarccb6cb62009-11-14 07:53:04 +000028#include "llvm/Support/MemoryBuffer.h"
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +000029#include "llvm/Support/raw_ostream.h"
Kovarththanan Rajaratnamf79bafa2009-11-29 09:57:35 +000030#include "llvm/Support/Timer.h"
Daniel Dunbara9204832009-11-13 10:37:48 +000031#include "llvm/System/Path.h"
Douglas Gregor2b4074f2009-12-01 05:55:20 +000032#include "llvm/System/Program.h"
Daniel Dunbar2a79e162009-11-13 03:51:44 +000033using namespace clang;
34
35CompilerInstance::CompilerInstance(llvm::LLVMContext *_LLVMContext,
36 bool _OwnsLLVMContext)
37 : LLVMContext(_LLVMContext),
38 OwnsLLVMContext(_OwnsLLVMContext) {
Daniel Dunbarc2f484f2009-11-13 09:36:05 +000039 }
Daniel Dunbar2a79e162009-11-13 03:51:44 +000040
41CompilerInstance::~CompilerInstance() {
42 if (OwnsLLVMContext)
43 delete LLVMContext;
44}
Daniel Dunbar16b74492009-11-13 04:12:06 +000045
Daniel Dunbar8a9f5692009-11-14 01:20:40 +000046void CompilerInstance::setDiagnostics(Diagnostic *Value) {
47 Diagnostics.reset(Value);
48}
49
50void CompilerInstance::setDiagnosticClient(DiagnosticClient *Value) {
51 DiagClient.reset(Value);
52}
53
54void CompilerInstance::setTarget(TargetInfo *Value) {
55 Target.reset(Value);
56}
57
58void CompilerInstance::setFileManager(FileManager *Value) {
59 FileMgr.reset(Value);
60}
61
62void CompilerInstance::setSourceManager(SourceManager *Value) {
63 SourceMgr.reset(Value);
64}
65
66void CompilerInstance::setPreprocessor(Preprocessor *Value) {
67 PP.reset(Value);
68}
69
70void CompilerInstance::setASTContext(ASTContext *Value) {
71 Context.reset(Value);
72}
73
Daniel Dunbar12ce6942009-11-14 02:47:17 +000074void CompilerInstance::setASTConsumer(ASTConsumer *Value) {
75 Consumer.reset(Value);
76}
77
Daniel Dunbar8a9f5692009-11-14 01:20:40 +000078void CompilerInstance::setCodeCompletionConsumer(CodeCompleteConsumer *Value) {
79 CompletionConsumer.reset(Value);
80}
81
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +000082// Diagnostics
83
84static void SetUpBuildDumpLog(const DiagnosticOptions &DiagOpts,
85 unsigned argc, char **argv,
86 llvm::OwningPtr<DiagnosticClient> &DiagClient) {
87 std::string ErrorInfo;
88 llvm::raw_ostream *OS =
89 new llvm::raw_fd_ostream(DiagOpts.DumpBuildInformation.c_str(), ErrorInfo);
90 if (!ErrorInfo.empty()) {
91 // FIXME: Do not fail like this.
92 llvm::errs() << "error opening -dump-build-information file '"
93 << DiagOpts.DumpBuildInformation << "', option ignored!\n";
94 delete OS;
95 return;
96 }
97
98 (*OS) << "clang-cc command line arguments: ";
99 for (unsigned i = 0; i != argc; ++i)
100 (*OS) << argv[i] << ' ';
101 (*OS) << '\n';
102
103 // Chain in a diagnostic client which will log the diagnostics.
104 DiagnosticClient *Logger =
105 new TextDiagnosticPrinter(*OS, DiagOpts, /*OwnsOutputStream=*/true);
106 DiagClient.reset(new ChainedDiagnosticClient(DiagClient.take(), Logger));
107}
108
109void CompilerInstance::createDiagnostics(int Argc, char **Argv) {
110 Diagnostics.reset(createDiagnostics(getDiagnosticOpts(), Argc, Argv));
111
112 if (Diagnostics)
113 DiagClient.reset(Diagnostics->getClient());
114}
115
116Diagnostic *CompilerInstance::createDiagnostics(const DiagnosticOptions &Opts,
117 int Argc, char **Argv) {
Daniel Dunbar221c7212009-11-14 07:53:24 +0000118 llvm::OwningPtr<Diagnostic> Diags(new Diagnostic());
119
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000120 // Create the diagnostic client for reporting errors or for
121 // implementing -verify.
Daniel Dunbarf79dced2009-11-14 03:24:39 +0000122 llvm::OwningPtr<DiagnosticClient> DiagClient(
123 new TextDiagnosticPrinter(llvm::errs(), Opts));
124
125 // Chain in -verify checker, if requested.
126 if (Opts.VerifyDiagnostics)
Daniel Dunbar221c7212009-11-14 07:53:24 +0000127 DiagClient.reset(new VerifyDiagnosticsClient(*Diags, DiagClient.take()));
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000128
129 if (!Opts.DumpBuildInformation.empty())
130 SetUpBuildDumpLog(Opts, Argc, Argv, DiagClient);
131
132 // Configure our handling of diagnostics.
Daniel Dunbar221c7212009-11-14 07:53:24 +0000133 Diags->setClient(DiagClient.take());
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000134 if (ProcessWarningOptions(*Diags, Opts))
135 return 0;
136
Daniel Dunbar221c7212009-11-14 07:53:24 +0000137 return Diags.take();
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000138}
139
140// File Manager
141
Daniel Dunbar16b74492009-11-13 04:12:06 +0000142void CompilerInstance::createFileManager() {
143 FileMgr.reset(new FileManager());
144}
145
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000146// Source Manager
147
Daniel Dunbar16b74492009-11-13 04:12:06 +0000148void CompilerInstance::createSourceManager() {
149 SourceMgr.reset(new SourceManager());
150}
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000151
Daniel Dunbar0fbb3d92009-11-13 05:52:34 +0000152// Preprocessor
153
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000154void CompilerInstance::createPreprocessor() {
155 PP.reset(createPreprocessor(getDiagnostics(), getLangOpts(),
156 getPreprocessorOpts(), getHeaderSearchOpts(),
157 getDependencyOutputOpts(), getTarget(),
158 getSourceManager(), getFileManager()));
159}
160
161Preprocessor *
162CompilerInstance::createPreprocessor(Diagnostic &Diags,
163 const LangOptions &LangInfo,
164 const PreprocessorOptions &PPOpts,
165 const HeaderSearchOptions &HSOpts,
166 const DependencyOutputOptions &DepOpts,
167 const TargetInfo &Target,
168 SourceManager &SourceMgr,
169 FileManager &FileMgr) {
170 // Create a PTH manager if we are using some form of a token cache.
171 PTHManager *PTHMgr = 0;
Daniel Dunbar049d3a02009-11-17 05:52:41 +0000172 if (!PPOpts.TokenCache.empty())
173 PTHMgr = PTHManager::Create(PPOpts.TokenCache, Diags);
Daniel Dunbar22dacfa2009-11-13 05:52:11 +0000174
175 // FIXME: Don't fail like this.
176 if (Diags.hasErrorOccurred())
177 exit(1);
178
179 // Create the Preprocessor.
180 HeaderSearch *HeaderInfo = new HeaderSearch(FileMgr);
181 Preprocessor *PP = new Preprocessor(Diags, LangInfo, Target,
182 SourceMgr, *HeaderInfo, PTHMgr,
183 /*OwnsHeaderSearch=*/true);
184
185 // Note that this is different then passing PTHMgr to Preprocessor's ctor.
186 // That argument is used as the IdentifierInfoLookup argument to
187 // IdentifierTable's ctor.
188 if (PTHMgr) {
189 PTHMgr->setPreprocessor(PP);
190 PP->setPTHManager(PTHMgr);
191 }
192
193 InitializePreprocessor(*PP, PPOpts, HSOpts);
194
195 // Handle generating dependencies, if requested.
196 if (!DepOpts.OutputFile.empty())
197 AttachDependencyFileGen(*PP, DepOpts);
198
199 return PP;
200}
Daniel Dunbar5eb81002009-11-13 08:20:47 +0000201
202// ASTContext
203
204void CompilerInstance::createASTContext() {
205 Preprocessor &PP = getPreprocessor();
206 Context.reset(new ASTContext(getLangOpts(), PP.getSourceManager(),
207 getTarget(), PP.getIdentifierTable(),
208 PP.getSelectorTable(), PP.getBuiltinInfo(),
209 /*FreeMemory=*/ !getFrontendOpts().DisableFree,
210 /*size_reserve=*/ 0));
211}
Daniel Dunbar0f800392009-11-13 08:21:10 +0000212
213// ExternalASTSource
214
215void CompilerInstance::createPCHExternalASTSource(llvm::StringRef Path) {
216 llvm::OwningPtr<ExternalASTSource> Source;
217 Source.reset(createPCHExternalASTSource(Path, getHeaderSearchOpts().Sysroot,
218 getPreprocessor(), getASTContext()));
219 getASTContext().setExternalSource(Source);
220}
221
222ExternalASTSource *
223CompilerInstance::createPCHExternalASTSource(llvm::StringRef Path,
224 const std::string &Sysroot,
225 Preprocessor &PP,
226 ASTContext &Context) {
227 llvm::OwningPtr<PCHReader> Reader;
228 Reader.reset(new PCHReader(PP, &Context,
229 Sysroot.empty() ? 0 : Sysroot.c_str()));
230
231 switch (Reader->ReadPCH(Path)) {
232 case PCHReader::Success:
233 // Set the predefines buffer as suggested by the PCH reader. Typically, the
234 // predefines buffer will be empty.
235 PP.setPredefines(Reader->getSuggestedPredefines());
236 return Reader.take();
237
238 case PCHReader::Failure:
239 // Unrecoverable failure: don't even try to process the input file.
240 break;
241
242 case PCHReader::IgnorePCH:
243 // No suitable PCH file could be found. Return an error.
244 break;
245 }
246
247 return 0;
248}
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000249
250// Code Completion
251
252void CompilerInstance::createCodeCompletionConsumer() {
253 const ParsedSourceLocation &Loc = getFrontendOpts().CodeCompletionAt;
254 CompletionConsumer.reset(
255 createCodeCompletionConsumer(getPreprocessor(),
256 Loc.FileName, Loc.Line, Loc.Column,
257 getFrontendOpts().DebugCodeCompletionPrinter,
258 getFrontendOpts().ShowMacrosInCodeCompletion,
259 llvm::outs()));
Douglas Gregor2b4074f2009-12-01 05:55:20 +0000260
261 if (CompletionConsumer->isOutputBinary() &&
262 llvm::sys::Program::ChangeStdoutToBinary()) {
263 getPreprocessor().getDiagnostics().Report(diag::err_fe_stdout_binary);
264 CompletionConsumer.reset();
265 }
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000266}
267
Kovarththanan Rajaratnamf79bafa2009-11-29 09:57:35 +0000268void CompilerInstance::createFrontendTimer() {
269 FrontendTimer.reset(new llvm::Timer("Clang front-end timer"));
270}
271
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000272CodeCompleteConsumer *
273CompilerInstance::createCodeCompletionConsumer(Preprocessor &PP,
274 const std::string &Filename,
275 unsigned Line,
276 unsigned Column,
277 bool UseDebugPrinter,
278 bool ShowMacros,
279 llvm::raw_ostream &OS) {
280 // Tell the source manager to chop off the given file at a specific
281 // line and column.
282 const FileEntry *Entry = PP.getFileManager().getFile(Filename);
283 if (!Entry) {
284 PP.getDiagnostics().Report(diag::err_fe_invalid_code_complete_file)
285 << Filename;
286 return 0;
287 }
288
289 // Truncate the named file at the given line/column.
Douglas Gregor29684422009-12-02 06:49:09 +0000290 PP.SetCodeCompletionPoint(Entry, Line, Column);
Daniel Dunbarc2f484f2009-11-13 09:36:05 +0000291
292 // Set up the creation routine for code-completion.
293 if (UseDebugPrinter)
294 return new PrintingCodeCompleteConsumer(ShowMacros, OS);
295 else
296 return new CIndexCodeCompleteConsumer(ShowMacros, OS);
297}
Daniel Dunbara9204832009-11-13 10:37:48 +0000298
299// Output Files
300
301void CompilerInstance::addOutputFile(llvm::StringRef Path,
302 llvm::raw_ostream *OS) {
303 assert(OS && "Attempt to add empty stream to output list!");
304 OutputFiles.push_back(std::make_pair(Path, OS));
305}
306
307void CompilerInstance::ClearOutputFiles(bool EraseFiles) {
308 for (std::list< std::pair<std::string, llvm::raw_ostream*> >::iterator
309 it = OutputFiles.begin(), ie = OutputFiles.end(); it != ie; ++it) {
310 delete it->second;
311 if (EraseFiles && !it->first.empty())
312 llvm::sys::Path(it->first).eraseFromDisk();
313 }
314 OutputFiles.clear();
315}
316
Daniel Dunbarf482d592009-11-13 18:32:08 +0000317llvm::raw_fd_ostream *
318CompilerInstance::createDefaultOutputFile(bool Binary,
319 llvm::StringRef InFile,
320 llvm::StringRef Extension) {
321 return createOutputFile(getFrontendOpts().OutputFile, Binary,
322 InFile, Extension);
323}
324
325llvm::raw_fd_ostream *
326CompilerInstance::createOutputFile(llvm::StringRef OutputPath,
327 bool Binary,
328 llvm::StringRef InFile,
329 llvm::StringRef Extension) {
330 std::string Error, OutputPathName;
331 llvm::raw_fd_ostream *OS = createOutputFile(OutputPath, Error, Binary,
332 InFile, Extension,
333 &OutputPathName);
334 if (!OS) {
335 // FIXME: Don't fail this way.
Daniel Dunbarfc971022009-11-20 22:32:38 +0000336 llvm::errs() << "error: " << Error << "\n";
Daniel Dunbarf482d592009-11-13 18:32:08 +0000337 ::exit(1);
338 }
339
340 // Add the output file -- but don't try to remove "-", since this means we are
341 // using stdin.
342 addOutputFile((OutputPathName != "-") ? OutputPathName : "", OS);
343
344 return OS;
345}
346
347llvm::raw_fd_ostream *
348CompilerInstance::createOutputFile(llvm::StringRef OutputPath,
349 std::string &Error,
350 bool Binary,
351 llvm::StringRef InFile,
352 llvm::StringRef Extension,
353 std::string *ResultPathName) {
354 std::string OutFile;
355 if (!OutputPath.empty()) {
356 OutFile = OutputPath;
357 } else if (InFile == "-") {
358 OutFile = "-";
359 } else if (!Extension.empty()) {
360 llvm::sys::Path Path(InFile);
361 Path.eraseSuffix();
362 Path.appendSuffix(Extension);
363 OutFile = Path.str();
364 } else {
365 OutFile = "-";
366 }
367
Daniel Dunbarfc971022009-11-20 22:32:38 +0000368 llvm::OwningPtr<llvm::raw_fd_ostream> OS(
Daniel Dunbarf482d592009-11-13 18:32:08 +0000369 new llvm::raw_fd_ostream(OutFile.c_str(), Error,
Daniel Dunbarfc971022009-11-20 22:32:38 +0000370 (Binary ? llvm::raw_fd_ostream::F_Binary : 0)));
371 if (!Error.empty())
Daniel Dunbarf482d592009-11-13 18:32:08 +0000372 return 0;
373
374 if (ResultPathName)
375 *ResultPathName = OutFile;
376
Daniel Dunbarfc971022009-11-20 22:32:38 +0000377 return OS.take();
Daniel Dunbarf482d592009-11-13 18:32:08 +0000378}
Daniel Dunbarccb6cb62009-11-14 07:53:04 +0000379
380// Initialization Utilities
381
382bool CompilerInstance::InitializeSourceManager(llvm::StringRef InputFile) {
383 return InitializeSourceManager(InputFile, getDiagnostics(), getFileManager(),
384 getSourceManager(), getFrontendOpts());
385}
386
387bool CompilerInstance::InitializeSourceManager(llvm::StringRef InputFile,
388 Diagnostic &Diags,
389 FileManager &FileMgr,
390 SourceManager &SourceMgr,
391 const FrontendOptions &Opts) {
392 // Figure out where to get and map in the main file.
393 if (Opts.EmptyInputOnly) {
394 const char *EmptyStr = "";
395 llvm::MemoryBuffer *SB =
396 llvm::MemoryBuffer::getMemBuffer(EmptyStr, EmptyStr, "<empty input>");
397 SourceMgr.createMainFileIDForMemBuffer(SB);
398 } else if (InputFile != "-") {
399 const FileEntry *File = FileMgr.getFile(InputFile);
400 if (File) SourceMgr.createMainFileID(File, SourceLocation());
401 if (SourceMgr.getMainFileID().isInvalid()) {
402 Diags.Report(diag::err_fe_error_reading) << InputFile;
403 return false;
404 }
405 } else {
406 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
407 SourceMgr.createMainFileIDForMemBuffer(SB);
408 if (SourceMgr.getMainFileID().isInvalid()) {
409 Diags.Report(diag::err_fe_error_reading_stdin);
410 return false;
411 }
412 }
413
414 return true;
415}