blob: b56a0d83a850e568dac607e43f942e7dc8f1cc91 [file] [log] [blame]
Argyrios Kyrtzidis4b562cf2009-06-20 08:27:14 +00001//===--- ASTUnit.cpp - ASTUnit utility ------------------------------------===//
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// ASTUnit Implementation.
11//
12//===----------------------------------------------------------------------===//
13
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000014#include "clang/Frontend/ASTUnit.h"
Douglas Gregor1d715ac2010-08-03 08:14:03 +000015#include "clang/Frontend/PCHWriter.h"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000016#include "clang/AST/ASTContext.h"
Daniel Dunbar521bf9c2009-12-01 09:51:01 +000017#include "clang/AST/ASTConsumer.h"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000018#include "clang/AST/DeclVisitor.h"
19#include "clang/AST/StmtVisitor.h"
Daniel Dunbar7b556682009-12-02 03:23:45 +000020#include "clang/Driver/Compilation.h"
21#include "clang/Driver/Driver.h"
22#include "clang/Driver/Job.h"
23#include "clang/Driver/Tool.h"
Daniel Dunbar521bf9c2009-12-01 09:51:01 +000024#include "clang/Frontend/CompilerInstance.h"
25#include "clang/Frontend/FrontendActions.h"
Daniel Dunbar7b556682009-12-02 03:23:45 +000026#include "clang/Frontend/FrontendDiagnostic.h"
Daniel Dunbar521bf9c2009-12-01 09:51:01 +000027#include "clang/Frontend/FrontendOptions.h"
Douglas Gregor1d715ac2010-08-03 08:14:03 +000028#include "clang/Frontend/PCHReader.h"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000029#include "clang/Lex/HeaderSearch.h"
30#include "clang/Lex/Preprocessor.h"
Daniel Dunbard58c03f2009-11-15 06:48:46 +000031#include "clang/Basic/TargetOptions.h"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000032#include "clang/Basic/TargetInfo.h"
33#include "clang/Basic/Diagnostic.h"
Douglas Gregor4db64a42010-01-23 00:14:00 +000034#include "llvm/Support/MemoryBuffer.h"
Daniel Dunbar7b556682009-12-02 03:23:45 +000035#include "llvm/System/Host.h"
Benjamin Kramer4a630d32009-10-18 11:34:14 +000036#include "llvm/System/Path.h"
Douglas Gregordf95a132010-08-09 20:45:32 +000037#include "llvm/Support/raw_ostream.h"
Douglas Gregor385103b2010-07-30 20:58:08 +000038#include "llvm/Support/Timer.h"
Douglas Gregor44c181a2010-07-23 00:33:23 +000039#include <cstdlib>
Zhongxing Xuad23ebe2010-07-23 02:15:08 +000040#include <cstdio>
Douglas Gregorcc5888d2010-07-31 00:40:00 +000041#include <sys/stat.h>
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000042using namespace clang;
43
Douglas Gregoreababfb2010-08-04 05:53:38 +000044/// \brief After failing to build a precompiled preamble (due to
45/// errors in the source that occurs in the preamble), the number of
46/// reparses during which we'll skip even trying to precompile the
47/// preamble.
48const unsigned DefaultPreambleRebuildInterval = 5;
49
Douglas Gregor3687e9d2010-04-05 21:10:19 +000050ASTUnit::ASTUnit(bool _MainFileIsAST)
Douglas Gregorabc563f2010-07-19 21:46:24 +000051 : CaptureDiagnostics(false), MainFileIsAST(_MainFileIsAST),
Douglas Gregordf95a132010-08-09 20:45:32 +000052 CompleteTranslationUnit(true), ConcurrencyCheckValue(CheckUnlocked),
53 PreambleRebuildCounter(0), SavedMainFileBuffer(0) {
Douglas Gregor385103b2010-07-30 20:58:08 +000054}
Douglas Gregor3687e9d2010-04-05 21:10:19 +000055
Daniel Dunbar521bf9c2009-12-01 09:51:01 +000056ASTUnit::~ASTUnit() {
Douglas Gregorbdf60622010-03-05 21:16:25 +000057 ConcurrencyCheckValue = CheckLocked;
Douglas Gregorabc563f2010-07-19 21:46:24 +000058 CleanTemporaryFiles();
Douglas Gregor175c4a92010-07-23 23:58:40 +000059 if (!PreambleFile.empty())
Douglas Gregor385103b2010-07-30 20:58:08 +000060 llvm::sys::Path(PreambleFile).eraseFromDisk();
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +000061
62 // Free the buffers associated with remapped files. We are required to
63 // perform this operation here because we explicitly request that the
64 // compiler instance *not* free these buffers for each invocation of the
65 // parser.
66 if (Invocation.get()) {
67 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
68 for (PreprocessorOptions::remapped_file_buffer_iterator
69 FB = PPOpts.remapped_file_buffer_begin(),
70 FBEnd = PPOpts.remapped_file_buffer_end();
71 FB != FBEnd;
72 ++FB)
73 delete FB->second;
74 }
Douglas Gregor28233422010-07-27 14:52:07 +000075
76 delete SavedMainFileBuffer;
Douglas Gregor385103b2010-07-30 20:58:08 +000077
78 for (unsigned I = 0, N = Timers.size(); I != N; ++I)
79 delete Timers[I];
Douglas Gregorabc563f2010-07-19 21:46:24 +000080}
81
82void ASTUnit::CleanTemporaryFiles() {
Douglas Gregor313e26c2010-02-18 23:35:40 +000083 for (unsigned I = 0, N = TemporaryFiles.size(); I != N; ++I)
84 TemporaryFiles[I].eraseFromDisk();
Douglas Gregorabc563f2010-07-19 21:46:24 +000085 TemporaryFiles.clear();
Steve Naroffe19944c2009-10-15 22:23:48 +000086}
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000087
88namespace {
89
90/// \brief Gathers information from PCHReader that will be used to initialize
91/// a Preprocessor.
Benjamin Kramerbd218282009-11-28 10:07:24 +000092class PCHInfoCollector : public PCHReaderListener {
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000093 LangOptions &LangOpt;
94 HeaderSearch &HSI;
95 std::string &TargetTriple;
96 std::string &Predefines;
97 unsigned &Counter;
Mike Stump1eb44332009-09-09 15:08:12 +000098
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000099 unsigned NumHeaderInfos;
Mike Stump1eb44332009-09-09 15:08:12 +0000100
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000101public:
102 PCHInfoCollector(LangOptions &LangOpt, HeaderSearch &HSI,
103 std::string &TargetTriple, std::string &Predefines,
104 unsigned &Counter)
105 : LangOpt(LangOpt), HSI(HSI), TargetTriple(TargetTriple),
106 Predefines(Predefines), Counter(Counter), NumHeaderInfos(0) {}
Mike Stump1eb44332009-09-09 15:08:12 +0000107
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000108 virtual bool ReadLanguageOptions(const LangOptions &LangOpts) {
109 LangOpt = LangOpts;
110 return false;
111 }
Mike Stump1eb44332009-09-09 15:08:12 +0000112
Daniel Dunbardc3c0d22009-11-11 00:52:11 +0000113 virtual bool ReadTargetTriple(llvm::StringRef Triple) {
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000114 TargetTriple = Triple;
115 return false;
116 }
Mike Stump1eb44332009-09-09 15:08:12 +0000117
Sebastian Redlcb481aa2010-07-14 23:29:55 +0000118 virtual bool ReadPredefinesBuffer(const PCHPredefinesBlocks &Buffers,
Daniel Dunbar7b5a1212009-11-11 05:29:04 +0000119 llvm::StringRef OriginalFileName,
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000120 std::string &SuggestedPredefines) {
Sebastian Redlcb481aa2010-07-14 23:29:55 +0000121 Predefines = Buffers[0].Data;
122 for (unsigned I = 1, N = Buffers.size(); I != N; ++I) {
123 Predefines += Buffers[I].Data;
124 }
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000125 return false;
126 }
Mike Stump1eb44332009-09-09 15:08:12 +0000127
Douglas Gregorec1afbf2010-03-16 19:09:18 +0000128 virtual void ReadHeaderFileInfo(const HeaderFileInfo &HFI, unsigned ID) {
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000129 HSI.setHeaderFileInfoForUID(HFI, NumHeaderInfos++);
130 }
Mike Stump1eb44332009-09-09 15:08:12 +0000131
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000132 virtual void ReadCounter(unsigned Value) {
133 Counter = Value;
134 }
135};
136
Douglas Gregora88084b2010-02-18 18:08:43 +0000137class StoredDiagnosticClient : public DiagnosticClient {
138 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiags;
139
140public:
141 explicit StoredDiagnosticClient(
142 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiags)
143 : StoredDiags(StoredDiags) { }
144
145 virtual void HandleDiagnostic(Diagnostic::Level Level,
146 const DiagnosticInfo &Info);
147};
148
149/// \brief RAII object that optionally captures diagnostics, if
150/// there is no diagnostic client to capture them already.
151class CaptureDroppedDiagnostics {
152 Diagnostic &Diags;
153 StoredDiagnosticClient Client;
154 DiagnosticClient *PreviousClient;
155
156public:
157 CaptureDroppedDiagnostics(bool RequestCapture, Diagnostic &Diags,
158 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiags)
159 : Diags(Diags), Client(StoredDiags), PreviousClient(Diags.getClient())
160 {
161 if (RequestCapture || Diags.getClient() == 0)
162 Diags.setClient(&Client);
163 }
164
165 ~CaptureDroppedDiagnostics() {
166 Diags.setClient(PreviousClient);
167 }
168};
169
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000170} // anonymous namespace
171
Douglas Gregora88084b2010-02-18 18:08:43 +0000172void StoredDiagnosticClient::HandleDiagnostic(Diagnostic::Level Level,
173 const DiagnosticInfo &Info) {
174 StoredDiags.push_back(StoredDiagnostic(Level, Info));
175}
176
Steve Naroff77accc12009-09-03 18:19:54 +0000177const std::string &ASTUnit::getOriginalSourceFileName() {
Daniel Dunbar68d40e22009-12-02 08:44:16 +0000178 return OriginalSourceFile;
Steve Naroff77accc12009-09-03 18:19:54 +0000179}
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000180
Steve Naroffe19944c2009-10-15 22:23:48 +0000181const std::string &ASTUnit::getPCHFileName() {
Daniel Dunbarc7822db2009-12-02 21:47:43 +0000182 assert(isMainFileAST() && "Not an ASTUnit from a PCH file!");
Benjamin Kramer7297c182010-01-30 16:23:25 +0000183 return static_cast<PCHReader *>(Ctx->getExternalSource())->getFileName();
Steve Naroffe19944c2009-10-15 22:23:48 +0000184}
185
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000186ASTUnit *ASTUnit::LoadFromPCHFile(const std::string &Filename,
Douglas Gregor28019772010-04-05 23:52:57 +0000187 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
Ted Kremenek5cf48762009-10-17 00:34:24 +0000188 bool OnlyLocalDecls,
Douglas Gregor4db64a42010-01-23 00:14:00 +0000189 RemappedFile *RemappedFiles,
Douglas Gregora88084b2010-02-18 18:08:43 +0000190 unsigned NumRemappedFiles,
191 bool CaptureDiagnostics) {
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000192 llvm::OwningPtr<ASTUnit> AST(new ASTUnit(true));
193
Douglas Gregor28019772010-04-05 23:52:57 +0000194 if (!Diags.getPtr()) {
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000195 // No diagnostics engine was provided, so create our own diagnostics object
196 // with the default options.
197 DiagnosticOptions DiagOpts;
Douglas Gregor28019772010-04-05 23:52:57 +0000198 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000199 }
Douglas Gregorabc563f2010-07-19 21:46:24 +0000200
201 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000202 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor28019772010-04-05 23:52:57 +0000203 AST->Diagnostics = Diags;
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000204 AST->FileMgr.reset(new FileManager);
205 AST->SourceMgr.reset(new SourceManager(AST->getDiagnostics()));
Steve Naroff36c44642009-10-19 14:34:22 +0000206 AST->HeaderInfo.reset(new HeaderSearch(AST->getFileManager()));
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000207
Douglas Gregora88084b2010-02-18 18:08:43 +0000208 // If requested, capture diagnostics in the ASTUnit.
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000209 CaptureDroppedDiagnostics Capture(CaptureDiagnostics, AST->getDiagnostics(),
Douglas Gregor405634b2010-04-05 18:10:21 +0000210 AST->StoredDiagnostics);
Douglas Gregora88084b2010-02-18 18:08:43 +0000211
Douglas Gregor4db64a42010-01-23 00:14:00 +0000212 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
213 // Create the file entry for the file that we're mapping from.
214 const FileEntry *FromFile
215 = AST->getFileManager().getVirtualFile(RemappedFiles[I].first,
216 RemappedFiles[I].second->getBufferSize(),
217 0);
218 if (!FromFile) {
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000219 AST->getDiagnostics().Report(diag::err_fe_remap_missing_from_file)
Douglas Gregor4db64a42010-01-23 00:14:00 +0000220 << RemappedFiles[I].first;
Douglas Gregorc8dfe5e2010-02-27 01:32:48 +0000221 delete RemappedFiles[I].second;
Douglas Gregor4db64a42010-01-23 00:14:00 +0000222 continue;
223 }
224
225 // Override the contents of the "from" file with the contents of
226 // the "to" file.
227 AST->getSourceManager().overrideFileContents(FromFile,
228 RemappedFiles[I].second);
229 }
230
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000231 // Gather Info for preprocessor construction later on.
Mike Stump1eb44332009-09-09 15:08:12 +0000232
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000233 LangOptions LangInfo;
234 HeaderSearch &HeaderInfo = *AST->HeaderInfo.get();
235 std::string TargetTriple;
236 std::string Predefines;
237 unsigned Counter;
238
Daniel Dunbarbce6f622009-09-03 05:59:50 +0000239 llvm::OwningPtr<PCHReader> Reader;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000240
Ted Kremenekfc062212009-10-19 21:44:57 +0000241 Reader.reset(new PCHReader(AST->getSourceManager(), AST->getFileManager(),
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000242 AST->getDiagnostics()));
Daniel Dunbarcc318932009-09-03 05:59:35 +0000243 Reader->setListener(new PCHInfoCollector(LangInfo, HeaderInfo, TargetTriple,
244 Predefines, Counter));
245
246 switch (Reader->ReadPCH(Filename)) {
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000247 case PCHReader::Success:
248 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000249
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000250 case PCHReader::Failure:
Argyrios Kyrtzidis106c9982009-06-25 18:22:30 +0000251 case PCHReader::IgnorePCH:
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000252 AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000253 return NULL;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000254 }
Mike Stump1eb44332009-09-09 15:08:12 +0000255
Daniel Dunbar68d40e22009-12-02 08:44:16 +0000256 AST->OriginalSourceFile = Reader->getOriginalSourceFile();
257
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000258 // PCH loaded successfully. Now create the preprocessor.
Mike Stump1eb44332009-09-09 15:08:12 +0000259
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000260 // Get information about the target being compiled for.
Daniel Dunbard58c03f2009-11-15 06:48:46 +0000261 //
262 // FIXME: This is broken, we should store the TargetOptions in the PCH.
263 TargetOptions TargetOpts;
264 TargetOpts.ABI = "";
Charles Davis98b7c5c2010-06-11 01:06:47 +0000265 TargetOpts.CXXABI = "itanium";
Daniel Dunbard58c03f2009-11-15 06:48:46 +0000266 TargetOpts.CPU = "";
267 TargetOpts.Features.clear();
268 TargetOpts.Triple = TargetTriple;
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000269 AST->Target.reset(TargetInfo::CreateTargetInfo(AST->getDiagnostics(),
270 TargetOpts));
271 AST->PP.reset(new Preprocessor(AST->getDiagnostics(), LangInfo,
272 *AST->Target.get(),
Daniel Dunbar31b87d82009-09-21 03:03:39 +0000273 AST->getSourceManager(), HeaderInfo));
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000274 Preprocessor &PP = *AST->PP.get();
275
Daniel Dunbard5b61262009-09-21 03:03:47 +0000276 PP.setPredefines(Reader->getSuggestedPredefines());
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000277 PP.setCounterValue(Counter);
Daniel Dunbarcc318932009-09-03 05:59:35 +0000278 Reader->setPreprocessor(PP);
Mike Stump1eb44332009-09-09 15:08:12 +0000279
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000280 // Create and initialize the ASTContext.
281
282 AST->Ctx.reset(new ASTContext(LangInfo,
Daniel Dunbar31b87d82009-09-21 03:03:39 +0000283 AST->getSourceManager(),
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000284 *AST->Target.get(),
285 PP.getIdentifierTable(),
286 PP.getSelectorTable(),
287 PP.getBuiltinInfo(),
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000288 /* size_reserve = */0));
289 ASTContext &Context = *AST->Ctx.get();
Mike Stump1eb44332009-09-09 15:08:12 +0000290
Daniel Dunbarcc318932009-09-03 05:59:35 +0000291 Reader->InitializeContext(Context);
Mike Stump1eb44332009-09-09 15:08:12 +0000292
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000293 // Attach the PCH reader to the AST context as an external AST
294 // source, so that declarations will be deserialized from the
295 // PCH file as needed.
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000296 PCHReader *ReaderPtr = Reader.get();
297 llvm::OwningPtr<ExternalASTSource> Source(Reader.take());
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000298 Context.setExternalSource(Source);
299
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000300 // Create an AST consumer, even though it isn't used.
301 AST->Consumer.reset(new ASTConsumer);
302
303 // Create a semantic analysis object and tell the PCH reader about it.
304 AST->TheSema.reset(new Sema(PP, Context, *AST->Consumer));
305 AST->TheSema->Initialize();
306 ReaderPtr->InitializeSema(*AST->TheSema);
307
Mike Stump1eb44332009-09-09 15:08:12 +0000308 return AST.take();
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000309}
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000310
311namespace {
312
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000313class TopLevelDeclTrackerConsumer : public ASTConsumer {
314 ASTUnit &Unit;
315
316public:
317 TopLevelDeclTrackerConsumer(ASTUnit &_Unit) : Unit(_Unit) {}
318
319 void HandleTopLevelDecl(DeclGroupRef D) {
Ted Kremenekda5a4282010-05-03 20:16:35 +0000320 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
321 Decl *D = *it;
322 // FIXME: Currently ObjC method declarations are incorrectly being
323 // reported as top-level declarations, even though their DeclContext
324 // is the containing ObjC @interface/@implementation. This is a
325 // fundamental problem in the parser right now.
326 if (isa<ObjCMethodDecl>(D))
327 continue;
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000328 Unit.addTopLevelDecl(D);
Ted Kremenekda5a4282010-05-03 20:16:35 +0000329 }
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000330 }
Sebastian Redl27372b42010-08-11 18:52:41 +0000331
332 // We're not interested in "interesting" decls.
333 void HandleInterestingDecl(DeclGroupRef) {}
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000334};
335
336class TopLevelDeclTrackerAction : public ASTFrontendAction {
337public:
338 ASTUnit &Unit;
339
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000340 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
341 llvm::StringRef InFile) {
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000342 return new TopLevelDeclTrackerConsumer(Unit);
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000343 }
344
345public:
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000346 TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {}
347
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000348 virtual bool hasCodeCompletionSupport() const { return false; }
Douglas Gregordf95a132010-08-09 20:45:32 +0000349 virtual bool usesCompleteTranslationUnit() {
350 return Unit.isCompleteTranslationUnit();
351 }
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000352};
353
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000354class PrecompilePreambleConsumer : public PCHGenerator {
355 ASTUnit &Unit;
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000356 std::vector<Decl *> TopLevelDecls;
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000357
358public:
359 PrecompilePreambleConsumer(ASTUnit &Unit,
360 const Preprocessor &PP, bool Chaining,
361 const char *isysroot, llvm::raw_ostream *Out)
362 : PCHGenerator(PP, Chaining, isysroot, Out), Unit(Unit) { }
363
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000364 virtual void HandleTopLevelDecl(DeclGroupRef D) {
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000365 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
366 Decl *D = *it;
367 // FIXME: Currently ObjC method declarations are incorrectly being
368 // reported as top-level declarations, even though their DeclContext
369 // is the containing ObjC @interface/@implementation. This is a
370 // fundamental problem in the parser right now.
371 if (isa<ObjCMethodDecl>(D))
372 continue;
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000373 TopLevelDecls.push_back(D);
374 }
375 }
376
377 virtual void HandleTranslationUnit(ASTContext &Ctx) {
378 PCHGenerator::HandleTranslationUnit(Ctx);
379 if (!Unit.getDiagnostics().hasErrorOccurred()) {
380 // Translate the top-level declarations we captured during
381 // parsing into declaration IDs in the precompiled
382 // preamble. This will allow us to deserialize those top-level
383 // declarations when requested.
384 for (unsigned I = 0, N = TopLevelDecls.size(); I != N; ++I)
385 Unit.addTopLevelDeclFromPreamble(
386 getWriter().getDeclID(TopLevelDecls[I]));
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000387 }
388 }
389};
390
391class PrecompilePreambleAction : public ASTFrontendAction {
392 ASTUnit &Unit;
393
394public:
395 explicit PrecompilePreambleAction(ASTUnit &Unit) : Unit(Unit) {}
396
397 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
398 llvm::StringRef InFile) {
399 std::string Sysroot;
400 llvm::raw_ostream *OS = 0;
401 bool Chaining;
402 if (GeneratePCHAction::ComputeASTConsumerArguments(CI, InFile, Sysroot,
403 OS, Chaining))
404 return 0;
405
406 const char *isysroot = CI.getFrontendOpts().RelocatablePCH ?
407 Sysroot.c_str() : 0;
408 return new PrecompilePreambleConsumer(Unit, CI.getPreprocessor(), Chaining,
409 isysroot, OS);
410 }
411
412 virtual bool hasCodeCompletionSupport() const { return false; }
413 virtual bool hasASTFileSupport() const { return false; }
Douglas Gregordf95a132010-08-09 20:45:32 +0000414 virtual bool usesCompleteTranslationUnit() { return false; }
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000415};
416
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000417}
418
Douglas Gregorabc563f2010-07-19 21:46:24 +0000419/// Parse the source file into a translation unit using the given compiler
420/// invocation, replacing the current translation unit.
421///
422/// \returns True if a failure occurred that causes the ASTUnit not to
423/// contain any translation-unit information, false otherwise.
Douglas Gregor754f3492010-07-24 00:38:13 +0000424bool ASTUnit::Parse(llvm::MemoryBuffer *OverrideMainBuffer) {
Douglas Gregor28233422010-07-27 14:52:07 +0000425 delete SavedMainFileBuffer;
426 SavedMainFileBuffer = 0;
427
Douglas Gregorabc563f2010-07-19 21:46:24 +0000428 if (!Invocation.get())
429 return true;
430
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000431 // Create the compiler instance to use for building the AST.
Daniel Dunbarcb6dda12009-12-02 08:43:56 +0000432 CompilerInstance Clang;
Douglas Gregorabc563f2010-07-19 21:46:24 +0000433 Clang.setInvocation(Invocation.take());
434 OriginalSourceFile = Clang.getFrontendOpts().Inputs[0].second;
435
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000436 // Set up diagnostics, capturing any diagnostics that would
437 // otherwise be dropped.
Douglas Gregorabc563f2010-07-19 21:46:24 +0000438 Clang.setDiagnostics(&getDiagnostics());
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000439 CaptureDroppedDiagnostics Capture(CaptureDiagnostics,
440 getDiagnostics(),
441 StoredDiagnostics);
Douglas Gregorabc563f2010-07-19 21:46:24 +0000442 Clang.setDiagnosticClient(getDiagnostics().getClient());
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000443
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000444 // Create the target instance.
445 Clang.setTarget(TargetInfo::CreateTargetInfo(Clang.getDiagnostics(),
446 Clang.getTargetOpts()));
Douglas Gregora88084b2010-02-18 18:08:43 +0000447 if (!Clang.hasTarget()) {
Douglas Gregora88084b2010-02-18 18:08:43 +0000448 Clang.takeDiagnosticClient();
Douglas Gregorabc563f2010-07-19 21:46:24 +0000449 return true;
Douglas Gregora88084b2010-02-18 18:08:43 +0000450 }
Douglas Gregorabc563f2010-07-19 21:46:24 +0000451
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000452 // Inform the target of the language options.
453 //
454 // FIXME: We shouldn't need to do this, the target should be immutable once
455 // created. This complexity should be lifted elsewhere.
456 Clang.getTarget().setForcedLangOptions(Clang.getLangOpts());
Douglas Gregorabc563f2010-07-19 21:46:24 +0000457
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000458 assert(Clang.getFrontendOpts().Inputs.size() == 1 &&
459 "Invocation must have exactly one source file!");
Daniel Dunbarc34ce3f2010-06-07 23:22:09 +0000460 assert(Clang.getFrontendOpts().Inputs[0].first != IK_AST &&
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000461 "FIXME: AST inputs not yet supported here!");
Daniel Dunbarfaddc3e2010-06-07 23:26:47 +0000462 assert(Clang.getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
463 "IR inputs not support here!");
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000464
Douglas Gregorabc563f2010-07-19 21:46:24 +0000465 // Configure the various subsystems.
466 // FIXME: Should we retain the previous file manager?
467 FileMgr.reset(new FileManager);
468 SourceMgr.reset(new SourceManager(getDiagnostics()));
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000469 TheSema.reset();
Douglas Gregorabc563f2010-07-19 21:46:24 +0000470 Ctx.reset();
471 PP.reset();
472
473 // Clear out old caches and data.
474 TopLevelDecls.clear();
Douglas Gregorabc563f2010-07-19 21:46:24 +0000475 CleanTemporaryFiles();
476 PreprocessedEntitiesByFile.clear();
Douglas Gregorc0659ec2010-08-02 20:51:39 +0000477
478 if (!OverrideMainBuffer)
479 StoredDiagnostics.clear();
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000480
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000481 // Create a file manager object to provide access to and cache the filesystem.
Douglas Gregorabc563f2010-07-19 21:46:24 +0000482 Clang.setFileManager(&getFileManager());
483
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000484 // Create the source manager.
Douglas Gregorabc563f2010-07-19 21:46:24 +0000485 Clang.setSourceManager(&getSourceManager());
486
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000487 // If the main file has been overridden due to the use of a preamble,
488 // make that override happen and introduce the preamble.
489 PreprocessorOptions &PreprocessorOpts = Clang.getPreprocessorOpts();
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000490 std::string PriorImplicitPCHInclude;
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000491 if (OverrideMainBuffer) {
492 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
493 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
494 PreprocessorOpts.PrecompiledPreambleBytes.second
495 = PreambleEndsAtStartOfLine;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000496 PriorImplicitPCHInclude = PreprocessorOpts.ImplicitPCHInclude;
Douglas Gregor385103b2010-07-30 20:58:08 +0000497 PreprocessorOpts.ImplicitPCHInclude = PreambleFile;
Douglas Gregorfae3b2f2010-07-27 00:27:13 +0000498 PreprocessorOpts.DisablePCHValidation = true;
Douglas Gregor28233422010-07-27 14:52:07 +0000499
500 // Keep track of the override buffer;
501 SavedMainFileBuffer = OverrideMainBuffer;
Douglas Gregorc0659ec2010-08-02 20:51:39 +0000502
503 // The stored diagnostic has the old source manager in it; update
504 // the locations to refer into the new source manager. Since we've
505 // been careful to make sure that the source manager's state
506 // before and after are identical, so that we can reuse the source
507 // location itself.
508 for (unsigned I = 0, N = StoredDiagnostics.size(); I != N; ++I) {
509 FullSourceLoc Loc(StoredDiagnostics[I].getLocation(),
510 getSourceManager());
511 StoredDiagnostics[I].setLocation(Loc);
512 }
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000513 }
514
Douglas Gregorabc563f2010-07-19 21:46:24 +0000515 llvm::OwningPtr<TopLevelDeclTrackerAction> Act;
516 Act.reset(new TopLevelDeclTrackerAction(*this));
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000517 if (!Act->BeginSourceFile(Clang, Clang.getFrontendOpts().Inputs[0].second,
Daniel Dunbard3598a62010-06-07 23:23:06 +0000518 Clang.getFrontendOpts().Inputs[0].first))
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000519 goto error;
Douglas Gregorabc563f2010-07-19 21:46:24 +0000520
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000521 Act->Execute();
Douglas Gregorabc563f2010-07-19 21:46:24 +0000522
Daniel Dunbar64a32ba2009-12-01 21:57:33 +0000523 // Steal the created target, context, and preprocessor, and take back the
524 // source and file managers.
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000525 TheSema.reset(Clang.takeSema());
526 Consumer.reset(Clang.takeASTConsumer());
Douglas Gregorabc563f2010-07-19 21:46:24 +0000527 Ctx.reset(Clang.takeASTContext());
528 PP.reset(Clang.takePreprocessor());
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000529 Clang.takeSourceManager();
530 Clang.takeFileManager();
Douglas Gregorabc563f2010-07-19 21:46:24 +0000531 Target.reset(Clang.takeTarget());
532
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000533 Act->EndSourceFile();
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000534
535 // Remove the overridden buffer we used for the preamble.
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000536 if (OverrideMainBuffer) {
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000537 PreprocessorOpts.eraseRemappedFile(
538 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000539 PreprocessorOpts.ImplicitPCHInclude = PriorImplicitPCHInclude;
540 }
541
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000542 Clang.takeDiagnosticClient();
Douglas Gregorabc563f2010-07-19 21:46:24 +0000543
544 Invocation.reset(Clang.takeInvocation());
545 return false;
546
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000547error:
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000548 // Remove the overridden buffer we used for the preamble.
Douglas Gregorfae3b2f2010-07-27 00:27:13 +0000549 if (OverrideMainBuffer) {
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000550 PreprocessorOpts.eraseRemappedFile(
551 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregorfae3b2f2010-07-27 00:27:13 +0000552 PreprocessorOpts.DisablePCHValidation = true;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000553 PreprocessorOpts.ImplicitPCHInclude = PriorImplicitPCHInclude;
Douglas Gregorfae3b2f2010-07-27 00:27:13 +0000554 }
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000555
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000556 Clang.takeSourceManager();
557 Clang.takeFileManager();
558 Clang.takeDiagnosticClient();
Douglas Gregorabc563f2010-07-19 21:46:24 +0000559 Invocation.reset(Clang.takeInvocation());
560 return true;
561}
562
Douglas Gregor44c181a2010-07-23 00:33:23 +0000563/// \brief Simple function to retrieve a path for a preamble precompiled header.
564static std::string GetPreamblePCHPath() {
565 // FIXME: This is lame; sys::Path should provide this function (in particular,
566 // it should know how to find the temporary files dir).
567 // FIXME: This is really lame. I copied this code from the Driver!
568 std::string Error;
569 const char *TmpDir = ::getenv("TMPDIR");
570 if (!TmpDir)
571 TmpDir = ::getenv("TEMP");
572 if (!TmpDir)
573 TmpDir = ::getenv("TMP");
574 if (!TmpDir)
575 TmpDir = "/tmp";
576 llvm::sys::Path P(TmpDir);
577 P.appendComponent("preamble");
Douglas Gregor6bf18302010-08-11 13:06:56 +0000578 P.appendSuffix("pch");
Douglas Gregor44c181a2010-07-23 00:33:23 +0000579 if (P.createTemporaryFileOnDisk())
580 return std::string();
581
Douglas Gregor6bf18302010-08-11 13:06:56 +0000582 fprintf(stderr, "Preamble file: %s\n", P.str().c_str());
Douglas Gregor44c181a2010-07-23 00:33:23 +0000583 return P.str();
584}
585
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000586/// \brief Compute the preamble for the main file, providing the source buffer
587/// that corresponds to the main file along with a pair (bytes, start-of-line)
588/// that describes the preamble.
589std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> >
Douglas Gregordf95a132010-08-09 20:45:32 +0000590ASTUnit::ComputePreamble(CompilerInvocation &Invocation,
591 unsigned MaxLines, bool &CreatedBuffer) {
Douglas Gregor175c4a92010-07-23 23:58:40 +0000592 FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
Douglas Gregor44c181a2010-07-23 00:33:23 +0000593 PreprocessorOptions &PreprocessorOpts
Douglas Gregor175c4a92010-07-23 23:58:40 +0000594 = Invocation.getPreprocessorOpts();
595 CreatedBuffer = false;
596
Douglas Gregor44c181a2010-07-23 00:33:23 +0000597 // Try to determine if the main file has been remapped, either from the
598 // command line (to another file) or directly through the compiler invocation
599 // (to a memory buffer).
Douglas Gregor175c4a92010-07-23 23:58:40 +0000600 llvm::MemoryBuffer *Buffer = 0;
Douglas Gregor44c181a2010-07-23 00:33:23 +0000601 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].second);
602 if (const llvm::sys::FileStatus *MainFileStatus = MainFilePath.getFileStatus()) {
603 // Check whether there is a file-file remapping of the main file
604 for (PreprocessorOptions::remapped_file_iterator
Douglas Gregor175c4a92010-07-23 23:58:40 +0000605 M = PreprocessorOpts.remapped_file_begin(),
606 E = PreprocessorOpts.remapped_file_end();
Douglas Gregor44c181a2010-07-23 00:33:23 +0000607 M != E;
608 ++M) {
609 llvm::sys::PathWithStatus MPath(M->first);
610 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
611 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
612 // We found a remapping. Try to load the resulting, remapped source.
Douglas Gregor175c4a92010-07-23 23:58:40 +0000613 if (CreatedBuffer) {
Douglas Gregor44c181a2010-07-23 00:33:23 +0000614 delete Buffer;
Douglas Gregor175c4a92010-07-23 23:58:40 +0000615 CreatedBuffer = false;
616 }
617
Douglas Gregor44c181a2010-07-23 00:33:23 +0000618 Buffer = llvm::MemoryBuffer::getFile(M->second);
619 if (!Buffer)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000620 return std::make_pair((llvm::MemoryBuffer*)0,
621 std::make_pair(0, true));
Douglas Gregor175c4a92010-07-23 23:58:40 +0000622 CreatedBuffer = true;
Douglas Gregor44c181a2010-07-23 00:33:23 +0000623
Douglas Gregor175c4a92010-07-23 23:58:40 +0000624 // Remove this remapping. We've captured the buffer already.
Douglas Gregor44c181a2010-07-23 00:33:23 +0000625 M = PreprocessorOpts.eraseRemappedFile(M);
626 E = PreprocessorOpts.remapped_file_end();
627 }
628 }
629 }
630
631 // Check whether there is a file-buffer remapping. It supercedes the
632 // file-file remapping.
633 for (PreprocessorOptions::remapped_file_buffer_iterator
634 M = PreprocessorOpts.remapped_file_buffer_begin(),
635 E = PreprocessorOpts.remapped_file_buffer_end();
636 M != E;
637 ++M) {
638 llvm::sys::PathWithStatus MPath(M->first);
639 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
640 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
641 // We found a remapping.
Douglas Gregor175c4a92010-07-23 23:58:40 +0000642 if (CreatedBuffer) {
Douglas Gregor44c181a2010-07-23 00:33:23 +0000643 delete Buffer;
Douglas Gregor175c4a92010-07-23 23:58:40 +0000644 CreatedBuffer = false;
645 }
Douglas Gregor44c181a2010-07-23 00:33:23 +0000646
Douglas Gregor175c4a92010-07-23 23:58:40 +0000647 Buffer = const_cast<llvm::MemoryBuffer *>(M->second);
648
649 // Remove this remapping. We've captured the buffer already.
Douglas Gregor44c181a2010-07-23 00:33:23 +0000650 M = PreprocessorOpts.eraseRemappedFile(M);
651 E = PreprocessorOpts.remapped_file_buffer_end();
652 }
653 }
Douglas Gregor175c4a92010-07-23 23:58:40 +0000654 }
Douglas Gregor44c181a2010-07-23 00:33:23 +0000655 }
656
657 // If the main source file was not remapped, load it now.
658 if (!Buffer) {
659 Buffer = llvm::MemoryBuffer::getFile(FrontendOpts.Inputs[0].second);
660 if (!Buffer)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000661 return std::make_pair((llvm::MemoryBuffer*)0, std::make_pair(0, true));
Douglas Gregor175c4a92010-07-23 23:58:40 +0000662
663 CreatedBuffer = true;
Douglas Gregor44c181a2010-07-23 00:33:23 +0000664 }
665
Douglas Gregordf95a132010-08-09 20:45:32 +0000666 return std::make_pair(Buffer, Lexer::ComputePreamble(Buffer, MaxLines));
Douglas Gregor175c4a92010-07-23 23:58:40 +0000667}
668
Douglas Gregor754f3492010-07-24 00:38:13 +0000669static llvm::MemoryBuffer *CreatePaddedMainFileBuffer(llvm::MemoryBuffer *Old,
670 bool DeleteOld,
671 unsigned NewSize,
672 llvm::StringRef NewName) {
673 llvm::MemoryBuffer *Result
674 = llvm::MemoryBuffer::getNewUninitMemBuffer(NewSize, NewName);
675 memcpy(const_cast<char*>(Result->getBufferStart()),
676 Old->getBufferStart(), Old->getBufferSize());
677 memset(const_cast<char*>(Result->getBufferStart()) + Old->getBufferSize(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000678 ' ', NewSize - Old->getBufferSize() - 1);
679 const_cast<char*>(Result->getBufferEnd())[-1] = '\n';
Douglas Gregor754f3492010-07-24 00:38:13 +0000680
681 if (DeleteOld)
682 delete Old;
683
684 return Result;
685}
686
Douglas Gregor175c4a92010-07-23 23:58:40 +0000687/// \brief Attempt to build or re-use a precompiled preamble when (re-)parsing
688/// the source file.
689///
690/// This routine will compute the preamble of the main source file. If a
691/// non-trivial preamble is found, it will precompile that preamble into a
692/// precompiled header so that the precompiled preamble can be used to reduce
693/// reparsing time. If a precompiled preamble has already been constructed,
694/// this routine will determine if it is still valid and, if so, avoid
695/// rebuilding the precompiled preamble.
696///
Douglas Gregordf95a132010-08-09 20:45:32 +0000697/// \param AllowRebuild When true (the default), this routine is
698/// allowed to rebuild the precompiled preamble if it is found to be
699/// out-of-date.
700///
701/// \param MaxLines When non-zero, the maximum number of lines that
702/// can occur within the preamble.
703///
Douglas Gregor754f3492010-07-24 00:38:13 +0000704/// \returns If the precompiled preamble can be used, returns a newly-allocated
705/// buffer that should be used in place of the main file when doing so.
706/// Otherwise, returns a NULL pointer.
Douglas Gregordf95a132010-08-09 20:45:32 +0000707llvm::MemoryBuffer *ASTUnit::getMainBufferWithPrecompiledPreamble(
708 bool AllowRebuild,
709 unsigned MaxLines) {
Douglas Gregor175c4a92010-07-23 23:58:40 +0000710 CompilerInvocation PreambleInvocation(*Invocation);
711 FrontendOptions &FrontendOpts = PreambleInvocation.getFrontendOpts();
712 PreprocessorOptions &PreprocessorOpts
713 = PreambleInvocation.getPreprocessorOpts();
714
715 bool CreatedPreambleBuffer = false;
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000716 std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> > NewPreamble
Douglas Gregordf95a132010-08-09 20:45:32 +0000717 = ComputePreamble(PreambleInvocation, MaxLines, CreatedPreambleBuffer);
Douglas Gregor175c4a92010-07-23 23:58:40 +0000718
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000719 if (!NewPreamble.second.first) {
Douglas Gregor175c4a92010-07-23 23:58:40 +0000720 // We couldn't find a preamble in the main source. Clear out the current
721 // preamble, if we have one. It's obviously no good any more.
722 Preamble.clear();
723 if (!PreambleFile.empty()) {
Douglas Gregor385103b2010-07-30 20:58:08 +0000724 llvm::sys::Path(PreambleFile).eraseFromDisk();
Douglas Gregor175c4a92010-07-23 23:58:40 +0000725 PreambleFile.clear();
726 }
727 if (CreatedPreambleBuffer)
728 delete NewPreamble.first;
Douglas Gregoreababfb2010-08-04 05:53:38 +0000729
730 // The next time we actually see a preamble, precompile it.
731 PreambleRebuildCounter = 1;
Douglas Gregor754f3492010-07-24 00:38:13 +0000732 return 0;
Douglas Gregor175c4a92010-07-23 23:58:40 +0000733 }
734
735 if (!Preamble.empty()) {
736 // We've previously computed a preamble. Check whether we have the same
737 // preamble now that we did before, and that there's enough space in
738 // the main-file buffer within the precompiled preamble to fit the
739 // new main file.
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000740 if (Preamble.size() == NewPreamble.second.first &&
741 PreambleEndsAtStartOfLine == NewPreamble.second.second &&
Douglas Gregor592508e2010-07-24 00:42:07 +0000742 NewPreamble.first->getBufferSize() < PreambleReservedSize-2 &&
Douglas Gregor175c4a92010-07-23 23:58:40 +0000743 memcmp(&Preamble[0], NewPreamble.first->getBufferStart(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000744 NewPreamble.second.first) == 0) {
Douglas Gregor175c4a92010-07-23 23:58:40 +0000745 // The preamble has not changed. We may be able to re-use the precompiled
746 // preamble.
Douglas Gregorc0659ec2010-08-02 20:51:39 +0000747
Douglas Gregorcc5888d2010-07-31 00:40:00 +0000748 // Check that none of the files used by the preamble have changed.
749 bool AnyFileChanged = false;
750
751 // First, make a record of those files that have been overridden via
752 // remapping or unsaved_files.
753 llvm::StringMap<std::pair<off_t, time_t> > OverriddenFiles;
754 for (PreprocessorOptions::remapped_file_iterator
755 R = PreprocessorOpts.remapped_file_begin(),
756 REnd = PreprocessorOpts.remapped_file_end();
757 !AnyFileChanged && R != REnd;
758 ++R) {
759 struct stat StatBuf;
760 if (stat(R->second.c_str(), &StatBuf)) {
761 // If we can't stat the file we're remapping to, assume that something
762 // horrible happened.
763 AnyFileChanged = true;
764 break;
765 }
Douglas Gregor754f3492010-07-24 00:38:13 +0000766
Douglas Gregorcc5888d2010-07-31 00:40:00 +0000767 OverriddenFiles[R->first] = std::make_pair(StatBuf.st_size,
768 StatBuf.st_mtime);
769 }
770 for (PreprocessorOptions::remapped_file_buffer_iterator
771 R = PreprocessorOpts.remapped_file_buffer_begin(),
772 REnd = PreprocessorOpts.remapped_file_buffer_end();
773 !AnyFileChanged && R != REnd;
774 ++R) {
775 // FIXME: Should we actually compare the contents of file->buffer
776 // remappings?
777 OverriddenFiles[R->first] = std::make_pair(R->second->getBufferSize(),
778 0);
779 }
780
781 // Check whether anything has changed.
782 for (llvm::StringMap<std::pair<off_t, time_t> >::iterator
783 F = FilesInPreamble.begin(), FEnd = FilesInPreamble.end();
784 !AnyFileChanged && F != FEnd;
785 ++F) {
786 llvm::StringMap<std::pair<off_t, time_t> >::iterator Overridden
787 = OverriddenFiles.find(F->first());
788 if (Overridden != OverriddenFiles.end()) {
789 // This file was remapped; check whether the newly-mapped file
790 // matches up with the previous mapping.
791 if (Overridden->second != F->second)
792 AnyFileChanged = true;
793 continue;
794 }
795
796 // The file was not remapped; check whether it has changed on disk.
797 struct stat StatBuf;
798 if (stat(F->first(), &StatBuf)) {
799 // If we can't stat the file, assume that something horrible happened.
800 AnyFileChanged = true;
801 } else if (StatBuf.st_size != F->second.first ||
802 StatBuf.st_mtime != F->second.second)
803 AnyFileChanged = true;
804 }
805
806 if (!AnyFileChanged) {
Douglas Gregorc0659ec2010-08-02 20:51:39 +0000807 // Okay! We can re-use the precompiled preamble.
808
809 // Set the state of the diagnostic object to mimic its state
810 // after parsing the preamble.
811 getDiagnostics().Reset();
812 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
813 if (StoredDiagnostics.size() > NumStoredDiagnosticsInPreamble)
814 StoredDiagnostics.erase(
815 StoredDiagnostics.begin() + NumStoredDiagnosticsInPreamble,
816 StoredDiagnostics.end());
817
818 // Create a version of the main file buffer that is padded to
819 // buffer size we reserved when creating the preamble.
Douglas Gregorcc5888d2010-07-31 00:40:00 +0000820 return CreatePaddedMainFileBuffer(NewPreamble.first,
821 CreatedPreambleBuffer,
822 PreambleReservedSize,
823 FrontendOpts.Inputs[0].second);
824 }
Douglas Gregor175c4a92010-07-23 23:58:40 +0000825 }
Douglas Gregordf95a132010-08-09 20:45:32 +0000826
827 // If we aren't allowed to rebuild the precompiled preamble, just
828 // return now.
829 if (!AllowRebuild)
830 return 0;
Douglas Gregor175c4a92010-07-23 23:58:40 +0000831
832 // We can't reuse the previously-computed preamble. Build a new one.
833 Preamble.clear();
Douglas Gregor385103b2010-07-30 20:58:08 +0000834 llvm::sys::Path(PreambleFile).eraseFromDisk();
Douglas Gregoreababfb2010-08-04 05:53:38 +0000835 PreambleRebuildCounter = 1;
Douglas Gregordf95a132010-08-09 20:45:32 +0000836 } else if (!AllowRebuild) {
837 // We aren't allowed to rebuild the precompiled preamble; just
838 // return now.
839 return 0;
840 }
Douglas Gregoreababfb2010-08-04 05:53:38 +0000841
842 // If the preamble rebuild counter > 1, it's because we previously
843 // failed to build a preamble and we're not yet ready to try
844 // again. Decrement the counter and return a failure.
845 if (PreambleRebuildCounter > 1) {
846 --PreambleRebuildCounter;
847 return 0;
848 }
849
Douglas Gregor175c4a92010-07-23 23:58:40 +0000850 // We did not previously compute a preamble, or it can't be reused anyway.
Douglas Gregor385103b2010-07-30 20:58:08 +0000851 llvm::Timer *PreambleTimer = 0;
852 if (TimerGroup.get()) {
853 PreambleTimer = new llvm::Timer("Precompiling preamble", *TimerGroup);
854 PreambleTimer->startTimer();
855 Timers.push_back(PreambleTimer);
856 }
Douglas Gregor44c181a2010-07-23 00:33:23 +0000857
858 // Create a new buffer that stores the preamble. The buffer also contains
859 // extra space for the original contents of the file (which will be present
860 // when we actually parse the file) along with more room in case the file
Douglas Gregor175c4a92010-07-23 23:58:40 +0000861 // grows.
862 PreambleReservedSize = NewPreamble.first->getBufferSize();
863 if (PreambleReservedSize < 4096)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000864 PreambleReservedSize = 8191;
Douglas Gregor44c181a2010-07-23 00:33:23 +0000865 else
Douglas Gregor175c4a92010-07-23 23:58:40 +0000866 PreambleReservedSize *= 2;
867
Douglas Gregorc0659ec2010-08-02 20:51:39 +0000868 // Save the preamble text for later; we'll need to compare against it for
869 // subsequent reparses.
870 Preamble.assign(NewPreamble.first->getBufferStart(),
871 NewPreamble.first->getBufferStart()
872 + NewPreamble.second.first);
873 PreambleEndsAtStartOfLine = NewPreamble.second.second;
874
Douglas Gregor44c181a2010-07-23 00:33:23 +0000875 llvm::MemoryBuffer *PreambleBuffer
Douglas Gregor175c4a92010-07-23 23:58:40 +0000876 = llvm::MemoryBuffer::getNewUninitMemBuffer(PreambleReservedSize,
Douglas Gregor44c181a2010-07-23 00:33:23 +0000877 FrontendOpts.Inputs[0].second);
878 memcpy(const_cast<char*>(PreambleBuffer->getBufferStart()),
Douglas Gregor175c4a92010-07-23 23:58:40 +0000879 NewPreamble.first->getBufferStart(), Preamble.size());
880 memset(const_cast<char*>(PreambleBuffer->getBufferStart()) + Preamble.size(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000881 ' ', PreambleReservedSize - Preamble.size() - 1);
882 const_cast<char*>(PreambleBuffer->getBufferEnd())[-1] = '\n';
Douglas Gregor44c181a2010-07-23 00:33:23 +0000883
884 // Remap the main source file to the preamble buffer.
Douglas Gregor175c4a92010-07-23 23:58:40 +0000885 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].second);
Douglas Gregor44c181a2010-07-23 00:33:23 +0000886 PreprocessorOpts.addRemappedFile(MainFilePath.str(), PreambleBuffer);
887
888 // Tell the compiler invocation to generate a temporary precompiled header.
889 FrontendOpts.ProgramAction = frontend::GeneratePCH;
Sebastian Redlf65339e2010-08-06 00:35:11 +0000890 // FIXME: Set ChainedPCH unconditionally, once it is ready.
891 if (::getenv("LIBCLANG_CHAINING"))
892 FrontendOpts.ChainedPCH = true;
Douglas Gregor44c181a2010-07-23 00:33:23 +0000893 // FIXME: Generate the precompiled header into memory?
Douglas Gregor385103b2010-07-30 20:58:08 +0000894 FrontendOpts.OutputFile = GetPreamblePCHPath();
Douglas Gregor44c181a2010-07-23 00:33:23 +0000895
896 // Create the compiler instance to use for building the precompiled preamble.
897 CompilerInstance Clang;
898 Clang.setInvocation(&PreambleInvocation);
899 OriginalSourceFile = Clang.getFrontendOpts().Inputs[0].second;
900
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000901 // Set up diagnostics, capturing all of the diagnostics produced.
Douglas Gregor44c181a2010-07-23 00:33:23 +0000902 Clang.setDiagnostics(&getDiagnostics());
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000903 CaptureDroppedDiagnostics Capture(CaptureDiagnostics,
904 getDiagnostics(),
905 StoredDiagnostics);
Douglas Gregor44c181a2010-07-23 00:33:23 +0000906 Clang.setDiagnosticClient(getDiagnostics().getClient());
907
908 // Create the target instance.
909 Clang.setTarget(TargetInfo::CreateTargetInfo(Clang.getDiagnostics(),
910 Clang.getTargetOpts()));
911 if (!Clang.hasTarget()) {
912 Clang.takeDiagnosticClient();
Douglas Gregor175c4a92010-07-23 23:58:40 +0000913 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
914 Preamble.clear();
915 if (CreatedPreambleBuffer)
916 delete NewPreamble.first;
Douglas Gregor385103b2010-07-30 20:58:08 +0000917 if (PreambleTimer)
918 PreambleTimer->stopTimer();
Douglas Gregoreababfb2010-08-04 05:53:38 +0000919 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor754f3492010-07-24 00:38:13 +0000920 return 0;
Douglas Gregor44c181a2010-07-23 00:33:23 +0000921 }
922
923 // Inform the target of the language options.
924 //
925 // FIXME: We shouldn't need to do this, the target should be immutable once
926 // created. This complexity should be lifted elsewhere.
927 Clang.getTarget().setForcedLangOptions(Clang.getLangOpts());
928
929 assert(Clang.getFrontendOpts().Inputs.size() == 1 &&
930 "Invocation must have exactly one source file!");
931 assert(Clang.getFrontendOpts().Inputs[0].first != IK_AST &&
932 "FIXME: AST inputs not yet supported here!");
933 assert(Clang.getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
934 "IR inputs not support here!");
935
936 // Clear out old caches and data.
937 StoredDiagnostics.clear();
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000938 TopLevelDecls.clear();
939 TopLevelDeclsInPreamble.clear();
Douglas Gregor44c181a2010-07-23 00:33:23 +0000940
941 // Create a file manager object to provide access to and cache the filesystem.
942 Clang.setFileManager(new FileManager);
943
944 // Create the source manager.
945 Clang.setSourceManager(new SourceManager(getDiagnostics()));
946
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000947 llvm::OwningPtr<PrecompilePreambleAction> Act;
948 Act.reset(new PrecompilePreambleAction(*this));
Douglas Gregor44c181a2010-07-23 00:33:23 +0000949 if (!Act->BeginSourceFile(Clang, Clang.getFrontendOpts().Inputs[0].second,
950 Clang.getFrontendOpts().Inputs[0].first)) {
951 Clang.takeDiagnosticClient();
952 Clang.takeInvocation();
Douglas Gregor175c4a92010-07-23 23:58:40 +0000953 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
954 Preamble.clear();
955 if (CreatedPreambleBuffer)
956 delete NewPreamble.first;
Douglas Gregor385103b2010-07-30 20:58:08 +0000957 if (PreambleTimer)
958 PreambleTimer->stopTimer();
Douglas Gregoreababfb2010-08-04 05:53:38 +0000959 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor385103b2010-07-30 20:58:08 +0000960
Douglas Gregor754f3492010-07-24 00:38:13 +0000961 return 0;
Douglas Gregor44c181a2010-07-23 00:33:23 +0000962 }
963
964 Act->Execute();
965 Act->EndSourceFile();
966 Clang.takeDiagnosticClient();
967 Clang.takeInvocation();
968
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000969 if (Diagnostics->hasErrorOccurred()) {
Douglas Gregor175c4a92010-07-23 23:58:40 +0000970 // There were errors parsing the preamble, so no precompiled header was
971 // generated. Forget that we even tried.
972 // FIXME: Should we leave a note for ourselves to try again?
973 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
974 Preamble.clear();
975 if (CreatedPreambleBuffer)
976 delete NewPreamble.first;
Douglas Gregor385103b2010-07-30 20:58:08 +0000977 if (PreambleTimer)
978 PreambleTimer->stopTimer();
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000979 TopLevelDeclsInPreamble.clear();
Douglas Gregoreababfb2010-08-04 05:53:38 +0000980 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor754f3492010-07-24 00:38:13 +0000981 return 0;
Douglas Gregor175c4a92010-07-23 23:58:40 +0000982 }
983
984 // Keep track of the preamble we precompiled.
985 PreambleFile = FrontendOpts.OutputFile;
Douglas Gregorc0659ec2010-08-02 20:51:39 +0000986 NumStoredDiagnosticsInPreamble = StoredDiagnostics.size();
987 NumWarningsInPreamble = getDiagnostics().getNumWarnings();
Douglas Gregorcc5888d2010-07-31 00:40:00 +0000988
989 // Keep track of all of the files that the source manager knows about,
990 // so we can verify whether they have changed or not.
991 FilesInPreamble.clear();
992 SourceManager &SourceMgr = Clang.getSourceManager();
993 const llvm::MemoryBuffer *MainFileBuffer
994 = SourceMgr.getBuffer(SourceMgr.getMainFileID());
995 for (SourceManager::fileinfo_iterator F = SourceMgr.fileinfo_begin(),
996 FEnd = SourceMgr.fileinfo_end();
997 F != FEnd;
998 ++F) {
999 const FileEntry *File = F->second->Entry;
1000 if (!File || F->second->getRawBuffer() == MainFileBuffer)
1001 continue;
1002
1003 FilesInPreamble[File->getName()]
1004 = std::make_pair(F->second->getSize(), File->getModificationTime());
1005 }
1006
Douglas Gregor385103b2010-07-30 20:58:08 +00001007 if (PreambleTimer)
1008 PreambleTimer->stopTimer();
1009
Douglas Gregoreababfb2010-08-04 05:53:38 +00001010 PreambleRebuildCounter = 1;
Douglas Gregor754f3492010-07-24 00:38:13 +00001011 return CreatePaddedMainFileBuffer(NewPreamble.first,
1012 CreatedPreambleBuffer,
1013 PreambleReservedSize,
1014 FrontendOpts.Inputs[0].second);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001015}
Douglas Gregorabc563f2010-07-19 21:46:24 +00001016
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001017void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
1018 std::vector<Decl *> Resolved;
1019 Resolved.reserve(TopLevelDeclsInPreamble.size());
1020 ExternalASTSource &Source = *getASTContext().getExternalSource();
1021 for (unsigned I = 0, N = TopLevelDeclsInPreamble.size(); I != N; ++I) {
1022 // Resolve the declaration ID to an actual declaration, possibly
1023 // deserializing the declaration in the process.
1024 Decl *D = Source.GetExternalDecl(TopLevelDeclsInPreamble[I]);
1025 if (D)
1026 Resolved.push_back(D);
1027 }
1028 TopLevelDeclsInPreamble.clear();
1029 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1030}
1031
1032unsigned ASTUnit::getMaxPCHLevel() const {
1033 if (!getOnlyLocalDecls())
1034 return Decl::MaxPCHLevel;
1035
1036 unsigned Result = 0;
1037 if (isMainFileAST() || SavedMainFileBuffer)
1038 ++Result;
1039 return Result;
1040}
1041
Douglas Gregorabc563f2010-07-19 21:46:24 +00001042ASTUnit *ASTUnit::LoadFromCompilerInvocation(CompilerInvocation *CI,
1043 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
1044 bool OnlyLocalDecls,
Douglas Gregor44c181a2010-07-23 00:33:23 +00001045 bool CaptureDiagnostics,
Douglas Gregordf95a132010-08-09 20:45:32 +00001046 bool PrecompilePreamble,
1047 bool CompleteTranslationUnit) {
Douglas Gregorabc563f2010-07-19 21:46:24 +00001048 if (!Diags.getPtr()) {
1049 // No diagnostics engine was provided, so create our own diagnostics object
1050 // with the default options.
1051 DiagnosticOptions DiagOpts;
1052 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
1053 }
1054
1055 // Create the AST unit.
1056 llvm::OwningPtr<ASTUnit> AST;
1057 AST.reset(new ASTUnit(false));
1058 AST->Diagnostics = Diags;
1059 AST->CaptureDiagnostics = CaptureDiagnostics;
1060 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregordf95a132010-08-09 20:45:32 +00001061 AST->CompleteTranslationUnit = CompleteTranslationUnit;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001062 AST->Invocation.reset(CI);
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001063 CI->getPreprocessorOpts().RetainRemappedFileBuffers = true;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001064
Douglas Gregor385103b2010-07-30 20:58:08 +00001065 if (getenv("LIBCLANG_TIMING"))
1066 AST->TimerGroup.reset(
1067 new llvm::TimerGroup(CI->getFrontendOpts().Inputs[0].second));
1068
1069
Douglas Gregor754f3492010-07-24 00:38:13 +00001070 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Douglas Gregorfd0b8702010-07-28 22:12:37 +00001071 // FIXME: When C++ PCH is ready, allow use of it for a precompiled preamble.
Douglas Gregoreababfb2010-08-04 05:53:38 +00001072 if (PrecompilePreamble && !CI->getLangOpts().CPlusPlus) {
1073 AST->PreambleRebuildCounter = 1;
Douglas Gregordf95a132010-08-09 20:45:32 +00001074 OverrideMainBuffer = AST->getMainBufferWithPrecompiledPreamble();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001075 }
Douglas Gregor44c181a2010-07-23 00:33:23 +00001076
Douglas Gregor385103b2010-07-30 20:58:08 +00001077 llvm::Timer *ParsingTimer = 0;
1078 if (AST->TimerGroup.get()) {
1079 ParsingTimer = new llvm::Timer("Initial parse", *AST->TimerGroup);
1080 ParsingTimer->startTimer();
1081 AST->Timers.push_back(ParsingTimer);
1082 }
Douglas Gregorabc563f2010-07-19 21:46:24 +00001083
Douglas Gregor385103b2010-07-30 20:58:08 +00001084 bool Failed = AST->Parse(OverrideMainBuffer);
1085 if (ParsingTimer)
1086 ParsingTimer->stopTimer();
1087
1088 return Failed? 0 : AST.take();
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001089}
Daniel Dunbar7b556682009-12-02 03:23:45 +00001090
1091ASTUnit *ASTUnit::LoadFromCommandLine(const char **ArgBegin,
1092 const char **ArgEnd,
Douglas Gregor28019772010-04-05 23:52:57 +00001093 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
Daniel Dunbar869824e2009-12-13 03:46:13 +00001094 llvm::StringRef ResourceFilesPath,
Daniel Dunbar7b556682009-12-02 03:23:45 +00001095 bool OnlyLocalDecls,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001096 RemappedFile *RemappedFiles,
Douglas Gregora88084b2010-02-18 18:08:43 +00001097 unsigned NumRemappedFiles,
Douglas Gregor44c181a2010-07-23 00:33:23 +00001098 bool CaptureDiagnostics,
Douglas Gregordf95a132010-08-09 20:45:32 +00001099 bool PrecompilePreamble,
1100 bool CompleteTranslationUnit) {
Douglas Gregor28019772010-04-05 23:52:57 +00001101 if (!Diags.getPtr()) {
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001102 // No diagnostics engine was provided, so create our own diagnostics object
1103 // with the default options.
1104 DiagnosticOptions DiagOpts;
Douglas Gregor28019772010-04-05 23:52:57 +00001105 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001106 }
1107
Daniel Dunbar7b556682009-12-02 03:23:45 +00001108 llvm::SmallVector<const char *, 16> Args;
1109 Args.push_back("<clang>"); // FIXME: Remove dummy argument.
1110 Args.insert(Args.end(), ArgBegin, ArgEnd);
1111
1112 // FIXME: Find a cleaner way to force the driver into restricted modes. We
1113 // also want to force it to use clang.
1114 Args.push_back("-fsyntax-only");
1115
Daniel Dunbar869824e2009-12-13 03:46:13 +00001116 // FIXME: We shouldn't have to pass in the path info.
Daniel Dunbar0bbad512010-07-19 00:44:04 +00001117 driver::Driver TheDriver("clang", llvm::sys::getHostTriple(),
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001118 "a.out", false, false, *Diags);
Daniel Dunbar3bd54cc2010-01-25 00:44:02 +00001119
1120 // Don't check that inputs exist, they have been remapped.
1121 TheDriver.setCheckInputsExist(false);
1122
Daniel Dunbar7b556682009-12-02 03:23:45 +00001123 llvm::OwningPtr<driver::Compilation> C(
1124 TheDriver.BuildCompilation(Args.size(), Args.data()));
1125
1126 // We expect to get back exactly one command job, if we didn't something
1127 // failed.
1128 const driver::JobList &Jobs = C->getJobs();
1129 if (Jobs.size() != 1 || !isa<driver::Command>(Jobs.begin())) {
1130 llvm::SmallString<256> Msg;
1131 llvm::raw_svector_ostream OS(Msg);
1132 C->PrintJob(OS, C->getJobs(), "; ", true);
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001133 Diags->Report(diag::err_fe_expected_compiler_job) << OS.str();
Daniel Dunbar7b556682009-12-02 03:23:45 +00001134 return 0;
1135 }
1136
1137 const driver::Command *Cmd = cast<driver::Command>(*Jobs.begin());
1138 if (llvm::StringRef(Cmd->getCreator().getName()) != "clang") {
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001139 Diags->Report(diag::err_fe_expected_clang_command);
Daniel Dunbar7b556682009-12-02 03:23:45 +00001140 return 0;
1141 }
1142
1143 const driver::ArgStringList &CCArgs = Cmd->getArguments();
Daniel Dunbar807b0612010-01-30 21:47:16 +00001144 llvm::OwningPtr<CompilerInvocation> CI(new CompilerInvocation);
Dan Gohmancb421fa2010-04-19 16:39:44 +00001145 CompilerInvocation::CreateFromArgs(*CI,
1146 const_cast<const char **>(CCArgs.data()),
1147 const_cast<const char **>(CCArgs.data()) +
Douglas Gregor44c181a2010-07-23 00:33:23 +00001148 CCArgs.size(),
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001149 *Diags);
Daniel Dunbar1e69fe32009-12-13 03:45:58 +00001150
Douglas Gregor4db64a42010-01-23 00:14:00 +00001151 // Override any files that need remapping
1152 for (unsigned I = 0; I != NumRemappedFiles; ++I)
Daniel Dunbar807b0612010-01-30 21:47:16 +00001153 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
Daniel Dunbarb26d4832010-02-16 01:55:04 +00001154 RemappedFiles[I].second);
Douglas Gregor4db64a42010-01-23 00:14:00 +00001155
Daniel Dunbar8b9adfe2009-12-15 00:06:45 +00001156 // Override the resources path.
Daniel Dunbar807b0612010-01-30 21:47:16 +00001157 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
Daniel Dunbar7b556682009-12-02 03:23:45 +00001158
Daniel Dunbarb26d4832010-02-16 01:55:04 +00001159 CI->getFrontendOpts().DisableFree = true;
Douglas Gregora88084b2010-02-18 18:08:43 +00001160 return LoadFromCompilerInvocation(CI.take(), Diags, OnlyLocalDecls,
Douglas Gregordf95a132010-08-09 20:45:32 +00001161 CaptureDiagnostics, PrecompilePreamble,
1162 CompleteTranslationUnit);
Daniel Dunbar7b556682009-12-02 03:23:45 +00001163}
Douglas Gregorabc563f2010-07-19 21:46:24 +00001164
1165bool ASTUnit::Reparse(RemappedFile *RemappedFiles, unsigned NumRemappedFiles) {
1166 if (!Invocation.get())
1167 return true;
1168
Douglas Gregor385103b2010-07-30 20:58:08 +00001169 llvm::Timer *ReparsingTimer = 0;
1170 if (TimerGroup.get()) {
1171 ReparsingTimer = new llvm::Timer("Reparse", *TimerGroup);
1172 ReparsingTimer->startTimer();
1173 Timers.push_back(ReparsingTimer);
1174 }
1175
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001176 // Remap files.
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001177 Invocation->getPreprocessorOpts().clearRemappedFiles();
1178 for (unsigned I = 0; I != NumRemappedFiles; ++I)
1179 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
1180 RemappedFiles[I].second);
1181
Douglas Gregoreababfb2010-08-04 05:53:38 +00001182 // If we have a preamble file lying around, or if we might try to
1183 // build a precompiled preamble, do so now.
Douglas Gregor754f3492010-07-24 00:38:13 +00001184 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Douglas Gregoreababfb2010-08-04 05:53:38 +00001185 if (!PreambleFile.empty() || PreambleRebuildCounter > 0)
Douglas Gregordf95a132010-08-09 20:45:32 +00001186 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001187
Douglas Gregorabc563f2010-07-19 21:46:24 +00001188 // Clear out the diagnostics state.
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001189 if (!OverrideMainBuffer)
1190 getDiagnostics().Reset();
Douglas Gregorabc563f2010-07-19 21:46:24 +00001191
Douglas Gregor175c4a92010-07-23 23:58:40 +00001192 // Parse the sources
Douglas Gregor754f3492010-07-24 00:38:13 +00001193 bool Result = Parse(OverrideMainBuffer);
Douglas Gregor385103b2010-07-30 20:58:08 +00001194 if (ReparsingTimer)
1195 ReparsingTimer->stopTimer();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001196 return Result;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001197}
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001198
1199void ASTUnit::CodeComplete(llvm::StringRef File, unsigned Line, unsigned Column,
1200 RemappedFile *RemappedFiles,
1201 unsigned NumRemappedFiles,
Douglas Gregorcee235c2010-08-05 09:09:23 +00001202 bool IncludeMacros,
1203 bool IncludeCodePatterns,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001204 CodeCompleteConsumer &Consumer,
1205 Diagnostic &Diag, LangOptions &LangOpts,
1206 SourceManager &SourceMgr, FileManager &FileMgr,
1207 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics) {
1208 if (!Invocation.get())
1209 return;
1210
Douglas Gregordf95a132010-08-09 20:45:32 +00001211 llvm::Timer *CompletionTimer = 0;
1212 if (TimerGroup.get()) {
1213 llvm::SmallString<128> TimerName;
1214 llvm::raw_svector_ostream TimerNameOut(TimerName);
1215 TimerNameOut << "Code completion @ " << File << ":" << Line << ":"
1216 << Column;
1217 CompletionTimer = new llvm::Timer(TimerNameOut.str(), *TimerGroup);
1218 CompletionTimer->startTimer();
1219 Timers.push_back(CompletionTimer);
1220 }
1221
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001222 CompilerInvocation CCInvocation(*Invocation);
1223 FrontendOptions &FrontendOpts = CCInvocation.getFrontendOpts();
1224 PreprocessorOptions &PreprocessorOpts = CCInvocation.getPreprocessorOpts();
Douglas Gregorcee235c2010-08-05 09:09:23 +00001225
1226 FrontendOpts.ShowMacrosInCodeCompletion = IncludeMacros;
1227 FrontendOpts.ShowCodePatternsInCodeCompletion = IncludeCodePatterns;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001228 FrontendOpts.CodeCompletionAt.FileName = File;
1229 FrontendOpts.CodeCompletionAt.Line = Line;
1230 FrontendOpts.CodeCompletionAt.Column = Column;
1231
Douglas Gregorcee235c2010-08-05 09:09:23 +00001232 // Turn on spell-checking when performing code completion. It leads
1233 // to better results.
1234 unsigned SpellChecking = CCInvocation.getLangOpts().SpellChecking;
1235 CCInvocation.getLangOpts().SpellChecking = 1;
1236
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001237 // Set the language options appropriately.
1238 LangOpts = CCInvocation.getLangOpts();
1239
1240 CompilerInstance Clang;
1241 Clang.setInvocation(&CCInvocation);
1242 OriginalSourceFile = Clang.getFrontendOpts().Inputs[0].second;
1243
1244 // Set up diagnostics, capturing any diagnostics produced.
1245 Clang.setDiagnostics(&Diag);
1246 CaptureDroppedDiagnostics Capture(true,
1247 Clang.getDiagnostics(),
1248 StoredDiagnostics);
1249 Clang.setDiagnosticClient(Diag.getClient());
1250
1251 // Create the target instance.
1252 Clang.setTarget(TargetInfo::CreateTargetInfo(Clang.getDiagnostics(),
1253 Clang.getTargetOpts()));
1254 if (!Clang.hasTarget()) {
1255 Clang.takeDiagnosticClient();
1256 Clang.takeInvocation();
1257 }
1258
1259 // Inform the target of the language options.
1260 //
1261 // FIXME: We shouldn't need to do this, the target should be immutable once
1262 // created. This complexity should be lifted elsewhere.
1263 Clang.getTarget().setForcedLangOptions(Clang.getLangOpts());
1264
1265 assert(Clang.getFrontendOpts().Inputs.size() == 1 &&
1266 "Invocation must have exactly one source file!");
1267 assert(Clang.getFrontendOpts().Inputs[0].first != IK_AST &&
1268 "FIXME: AST inputs not yet supported here!");
1269 assert(Clang.getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
1270 "IR inputs not support here!");
1271
1272
1273 // Use the source and file managers that we were given.
1274 Clang.setFileManager(&FileMgr);
1275 Clang.setSourceManager(&SourceMgr);
1276
1277 // Remap files.
1278 PreprocessorOpts.clearRemappedFiles();
Douglas Gregorb75d3df2010-08-04 17:07:00 +00001279 PreprocessorOpts.RetainRemappedFileBuffers = true;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001280 for (unsigned I = 0; I != NumRemappedFiles; ++I)
1281 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first,
1282 RemappedFiles[I].second);
1283
1284 // Use the code completion consumer we were given.
1285 Clang.setCodeCompletionConsumer(&Consumer);
1286
Douglas Gregordf95a132010-08-09 20:45:32 +00001287 // If we have a precompiled preamble, try to use it. We only allow
1288 // the use of the precompiled preamble if we're if the completion
1289 // point is within the main file, after the end of the precompiled
1290 // preamble.
1291 llvm::MemoryBuffer *OverrideMainBuffer = 0;
1292 if (!PreambleFile.empty()) {
1293 using llvm::sys::FileStatus;
1294 llvm::sys::PathWithStatus CompleteFilePath(File);
1295 llvm::sys::PathWithStatus MainPath(OriginalSourceFile);
1296 if (const FileStatus *CompleteFileStatus = CompleteFilePath.getFileStatus())
1297 if (const FileStatus *MainStatus = MainPath.getFileStatus())
1298 if (CompleteFileStatus->getUniqueID() == MainStatus->getUniqueID())
1299 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(false,
1300 Line);
1301 }
1302
1303 // If the main file has been overridden due to the use of a preamble,
1304 // make that override happen and introduce the preamble.
1305 if (OverrideMainBuffer) {
1306 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
1307 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
1308 PreprocessorOpts.PrecompiledPreambleBytes.second
1309 = PreambleEndsAtStartOfLine;
1310 PreprocessorOpts.ImplicitPCHInclude = PreambleFile;
1311 PreprocessorOpts.DisablePCHValidation = true;
1312
1313 // The stored diagnostics have the old source manager. Copy them
1314 // to our output set of stored diagnostics, updating the source
1315 // manager to the one we were given.
1316 for (unsigned I = 0, N = this->StoredDiagnostics.size(); I != N; ++I) {
1317 StoredDiagnostics.push_back(this->StoredDiagnostics[I]);
1318 FullSourceLoc Loc(StoredDiagnostics[I].getLocation(), SourceMgr);
1319 StoredDiagnostics[I].setLocation(Loc);
1320 }
1321 }
1322
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001323 llvm::OwningPtr<SyntaxOnlyAction> Act;
1324 Act.reset(new SyntaxOnlyAction);
1325 if (Act->BeginSourceFile(Clang, Clang.getFrontendOpts().Inputs[0].second,
1326 Clang.getFrontendOpts().Inputs[0].first)) {
1327 Act->Execute();
1328 Act->EndSourceFile();
1329 }
Douglas Gregordf95a132010-08-09 20:45:32 +00001330
1331 if (CompletionTimer)
1332 CompletionTimer->stopTimer();
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001333
1334 // Steal back our resources.
Douglas Gregordf95a132010-08-09 20:45:32 +00001335 delete OverrideMainBuffer;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001336 Clang.takeFileManager();
1337 Clang.takeSourceManager();
1338 Clang.takeInvocation();
1339 Clang.takeDiagnosticClient();
1340 Clang.takeCodeCompletionConsumer();
Douglas Gregorcee235c2010-08-05 09:09:23 +00001341 CCInvocation.getLangOpts().SpellChecking = SpellChecking;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001342}