blob: c37610afc391646e279b782c092e64850c5423df [file] [log] [blame]
Argyrios Kyrtzidis3a08ec12009-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 Kyrtzidisce379752009-06-20 08:08:23 +000014#include "clang/Frontend/ASTUnit.h"
Douglas Gregor48c8cd32010-08-03 08:14:03 +000015#include "clang/Frontend/PCHWriter.h"
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000016#include "clang/AST/ASTContext.h"
Daniel Dunbar764c0822009-12-01 09:51:01 +000017#include "clang/AST/ASTConsumer.h"
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000018#include "clang/AST/DeclVisitor.h"
19#include "clang/AST/StmtVisitor.h"
Daniel Dunbar55a17b62009-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 Dunbar764c0822009-12-01 09:51:01 +000024#include "clang/Frontend/CompilerInstance.h"
25#include "clang/Frontend/FrontendActions.h"
Daniel Dunbar55a17b62009-12-02 03:23:45 +000026#include "clang/Frontend/FrontendDiagnostic.h"
Daniel Dunbar764c0822009-12-01 09:51:01 +000027#include "clang/Frontend/FrontendOptions.h"
Douglas Gregor48c8cd32010-08-03 08:14:03 +000028#include "clang/Frontend/PCHReader.h"
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000029#include "clang/Lex/HeaderSearch.h"
30#include "clang/Lex/Preprocessor.h"
Daniel Dunbarb9bbd542009-11-15 06:48:46 +000031#include "clang/Basic/TargetOptions.h"
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000032#include "clang/Basic/TargetInfo.h"
33#include "clang/Basic/Diagnostic.h"
Douglas Gregoraa98ed92010-01-23 00:14:00 +000034#include "llvm/Support/MemoryBuffer.h"
Daniel Dunbar55a17b62009-12-02 03:23:45 +000035#include "llvm/System/Host.h"
Benjamin Kramer6c839f82009-10-18 11:34:14 +000036#include "llvm/System/Path.h"
Douglas Gregor15ba0b32010-07-30 20:58:08 +000037#include "llvm/Support/Timer.h"
Douglas Gregorbe2d8c62010-07-23 00:33:23 +000038#include <cstdlib>
Zhongxing Xu318e4032010-07-23 02:15:08 +000039#include <cstdio>
Douglas Gregor0e119552010-07-31 00:40:00 +000040#include <sys/stat.h>
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000041using namespace clang;
42
Douglas Gregord03e8232010-04-05 21:10:19 +000043ASTUnit::ASTUnit(bool _MainFileIsAST)
Douglas Gregoraa21cc42010-07-19 21:46:24 +000044 : CaptureDiagnostics(false), MainFileIsAST(_MainFileIsAST),
Douglas Gregor15ba0b32010-07-30 20:58:08 +000045 ConcurrencyCheckValue(CheckUnlocked), SavedMainFileBuffer(0) {
46}
Douglas Gregord03e8232010-04-05 21:10:19 +000047
Daniel Dunbar764c0822009-12-01 09:51:01 +000048ASTUnit::~ASTUnit() {
Douglas Gregor0c7c2f82010-03-05 21:16:25 +000049 ConcurrencyCheckValue = CheckLocked;
Douglas Gregoraa21cc42010-07-19 21:46:24 +000050 CleanTemporaryFiles();
Douglas Gregor4dde7492010-07-23 23:58:40 +000051 if (!PreambleFile.empty())
Douglas Gregor15ba0b32010-07-30 20:58:08 +000052 llvm::sys::Path(PreambleFile).eraseFromDisk();
Douglas Gregor3f4bea02010-07-26 21:36:20 +000053
54 // Free the buffers associated with remapped files. We are required to
55 // perform this operation here because we explicitly request that the
56 // compiler instance *not* free these buffers for each invocation of the
57 // parser.
58 if (Invocation.get()) {
59 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
60 for (PreprocessorOptions::remapped_file_buffer_iterator
61 FB = PPOpts.remapped_file_buffer_begin(),
62 FBEnd = PPOpts.remapped_file_buffer_end();
63 FB != FBEnd;
64 ++FB)
65 delete FB->second;
66 }
Douglas Gregor96c04262010-07-27 14:52:07 +000067
68 delete SavedMainFileBuffer;
Douglas Gregor15ba0b32010-07-30 20:58:08 +000069
70 for (unsigned I = 0, N = Timers.size(); I != N; ++I)
71 delete Timers[I];
Douglas Gregoraa21cc42010-07-19 21:46:24 +000072}
73
74void ASTUnit::CleanTemporaryFiles() {
Douglas Gregor6cb5ba42010-02-18 23:35:40 +000075 for (unsigned I = 0, N = TemporaryFiles.size(); I != N; ++I)
76 TemporaryFiles[I].eraseFromDisk();
Douglas Gregoraa21cc42010-07-19 21:46:24 +000077 TemporaryFiles.clear();
Steve Naroff44cd60e2009-10-15 22:23:48 +000078}
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000079
80namespace {
81
82/// \brief Gathers information from PCHReader that will be used to initialize
83/// a Preprocessor.
Benjamin Kramer16634c22009-11-28 10:07:24 +000084class PCHInfoCollector : public PCHReaderListener {
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000085 LangOptions &LangOpt;
86 HeaderSearch &HSI;
87 std::string &TargetTriple;
88 std::string &Predefines;
89 unsigned &Counter;
Mike Stump11289f42009-09-09 15:08:12 +000090
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000091 unsigned NumHeaderInfos;
Mike Stump11289f42009-09-09 15:08:12 +000092
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000093public:
94 PCHInfoCollector(LangOptions &LangOpt, HeaderSearch &HSI,
95 std::string &TargetTriple, std::string &Predefines,
96 unsigned &Counter)
97 : LangOpt(LangOpt), HSI(HSI), TargetTriple(TargetTriple),
98 Predefines(Predefines), Counter(Counter), NumHeaderInfos(0) {}
Mike Stump11289f42009-09-09 15:08:12 +000099
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000100 virtual bool ReadLanguageOptions(const LangOptions &LangOpts) {
101 LangOpt = LangOpts;
102 return false;
103 }
Mike Stump11289f42009-09-09 15:08:12 +0000104
Daniel Dunbar20a682d2009-11-11 00:52:11 +0000105 virtual bool ReadTargetTriple(llvm::StringRef Triple) {
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000106 TargetTriple = Triple;
107 return false;
108 }
Mike Stump11289f42009-09-09 15:08:12 +0000109
Sebastian Redl8b41f302010-07-14 23:29:55 +0000110 virtual bool ReadPredefinesBuffer(const PCHPredefinesBlocks &Buffers,
Daniel Dunbar000c4ff2009-11-11 05:29:04 +0000111 llvm::StringRef OriginalFileName,
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000112 std::string &SuggestedPredefines) {
Sebastian Redl8b41f302010-07-14 23:29:55 +0000113 Predefines = Buffers[0].Data;
114 for (unsigned I = 1, N = Buffers.size(); I != N; ++I) {
115 Predefines += Buffers[I].Data;
116 }
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000117 return false;
118 }
Mike Stump11289f42009-09-09 15:08:12 +0000119
Douglas Gregora2f49452010-03-16 19:09:18 +0000120 virtual void ReadHeaderFileInfo(const HeaderFileInfo &HFI, unsigned ID) {
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000121 HSI.setHeaderFileInfoForUID(HFI, NumHeaderInfos++);
122 }
Mike Stump11289f42009-09-09 15:08:12 +0000123
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000124 virtual void ReadCounter(unsigned Value) {
125 Counter = Value;
126 }
127};
128
Douglas Gregor33cdd812010-02-18 18:08:43 +0000129class StoredDiagnosticClient : public DiagnosticClient {
130 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiags;
131
132public:
133 explicit StoredDiagnosticClient(
134 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiags)
135 : StoredDiags(StoredDiags) { }
136
137 virtual void HandleDiagnostic(Diagnostic::Level Level,
138 const DiagnosticInfo &Info);
139};
140
141/// \brief RAII object that optionally captures diagnostics, if
142/// there is no diagnostic client to capture them already.
143class CaptureDroppedDiagnostics {
144 Diagnostic &Diags;
145 StoredDiagnosticClient Client;
146 DiagnosticClient *PreviousClient;
147
148public:
149 CaptureDroppedDiagnostics(bool RequestCapture, Diagnostic &Diags,
150 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiags)
151 : Diags(Diags), Client(StoredDiags), PreviousClient(Diags.getClient())
152 {
153 if (RequestCapture || Diags.getClient() == 0)
154 Diags.setClient(&Client);
155 }
156
157 ~CaptureDroppedDiagnostics() {
158 Diags.setClient(PreviousClient);
159 }
160};
161
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000162} // anonymous namespace
163
Douglas Gregor33cdd812010-02-18 18:08:43 +0000164void StoredDiagnosticClient::HandleDiagnostic(Diagnostic::Level Level,
165 const DiagnosticInfo &Info) {
166 StoredDiags.push_back(StoredDiagnostic(Level, Info));
167}
168
Steve Naroffc0683b92009-09-03 18:19:54 +0000169const std::string &ASTUnit::getOriginalSourceFileName() {
Daniel Dunbara8a50932009-12-02 08:44:16 +0000170 return OriginalSourceFile;
Steve Naroffc0683b92009-09-03 18:19:54 +0000171}
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000172
Steve Naroff44cd60e2009-10-15 22:23:48 +0000173const std::string &ASTUnit::getPCHFileName() {
Daniel Dunbara18f9582009-12-02 21:47:43 +0000174 assert(isMainFileAST() && "Not an ASTUnit from a PCH file!");
Benjamin Kramer2ecf8eb2010-01-30 16:23:25 +0000175 return static_cast<PCHReader *>(Ctx->getExternalSource())->getFileName();
Steve Naroff44cd60e2009-10-15 22:23:48 +0000176}
177
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000178ASTUnit *ASTUnit::LoadFromPCHFile(const std::string &Filename,
Douglas Gregor7f95d262010-04-05 23:52:57 +0000179 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
Ted Kremenek8bcb1c62009-10-17 00:34:24 +0000180 bool OnlyLocalDecls,
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000181 RemappedFile *RemappedFiles,
Douglas Gregor33cdd812010-02-18 18:08:43 +0000182 unsigned NumRemappedFiles,
183 bool CaptureDiagnostics) {
Douglas Gregord03e8232010-04-05 21:10:19 +0000184 llvm::OwningPtr<ASTUnit> AST(new ASTUnit(true));
185
Douglas Gregor7f95d262010-04-05 23:52:57 +0000186 if (!Diags.getPtr()) {
Douglas Gregord03e8232010-04-05 21:10:19 +0000187 // No diagnostics engine was provided, so create our own diagnostics object
188 // with the default options.
189 DiagnosticOptions DiagOpts;
Douglas Gregor7f95d262010-04-05 23:52:57 +0000190 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Douglas Gregord03e8232010-04-05 21:10:19 +0000191 }
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000192
193 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor16bef852009-10-16 20:01:17 +0000194 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor7f95d262010-04-05 23:52:57 +0000195 AST->Diagnostics = Diags;
Douglas Gregord03e8232010-04-05 21:10:19 +0000196 AST->FileMgr.reset(new FileManager);
197 AST->SourceMgr.reset(new SourceManager(AST->getDiagnostics()));
Steve Naroff505fb842009-10-19 14:34:22 +0000198 AST->HeaderInfo.reset(new HeaderSearch(AST->getFileManager()));
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000199
Douglas Gregor33cdd812010-02-18 18:08:43 +0000200 // If requested, capture diagnostics in the ASTUnit.
Douglas Gregord03e8232010-04-05 21:10:19 +0000201 CaptureDroppedDiagnostics Capture(CaptureDiagnostics, AST->getDiagnostics(),
Douglas Gregora2433152010-04-05 18:10:21 +0000202 AST->StoredDiagnostics);
Douglas Gregor33cdd812010-02-18 18:08:43 +0000203
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000204 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
205 // Create the file entry for the file that we're mapping from.
206 const FileEntry *FromFile
207 = AST->getFileManager().getVirtualFile(RemappedFiles[I].first,
208 RemappedFiles[I].second->getBufferSize(),
209 0);
210 if (!FromFile) {
Douglas Gregord03e8232010-04-05 21:10:19 +0000211 AST->getDiagnostics().Report(diag::err_fe_remap_missing_from_file)
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000212 << RemappedFiles[I].first;
Douglas Gregor89a56c52010-02-27 01:32:48 +0000213 delete RemappedFiles[I].second;
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000214 continue;
215 }
216
217 // Override the contents of the "from" file with the contents of
218 // the "to" file.
219 AST->getSourceManager().overrideFileContents(FromFile,
220 RemappedFiles[I].second);
221 }
222
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000223 // Gather Info for preprocessor construction later on.
Mike Stump11289f42009-09-09 15:08:12 +0000224
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000225 LangOptions LangInfo;
226 HeaderSearch &HeaderInfo = *AST->HeaderInfo.get();
227 std::string TargetTriple;
228 std::string Predefines;
229 unsigned Counter;
230
Daniel Dunbar3a0637b2009-09-03 05:59:50 +0000231 llvm::OwningPtr<PCHReader> Reader;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000232 llvm::OwningPtr<ExternalASTSource> Source;
233
Ted Kremenek428c6372009-10-19 21:44:57 +0000234 Reader.reset(new PCHReader(AST->getSourceManager(), AST->getFileManager(),
Douglas Gregord03e8232010-04-05 21:10:19 +0000235 AST->getDiagnostics()));
Daniel Dunbar2d9c7402009-09-03 05:59:35 +0000236 Reader->setListener(new PCHInfoCollector(LangInfo, HeaderInfo, TargetTriple,
237 Predefines, Counter));
238
239 switch (Reader->ReadPCH(Filename)) {
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000240 case PCHReader::Success:
241 break;
Mike Stump11289f42009-09-09 15:08:12 +0000242
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000243 case PCHReader::Failure:
Argyrios Kyrtzidis55c34112009-06-25 18:22:30 +0000244 case PCHReader::IgnorePCH:
Douglas Gregord03e8232010-04-05 21:10:19 +0000245 AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000246 return NULL;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000247 }
Mike Stump11289f42009-09-09 15:08:12 +0000248
Daniel Dunbara8a50932009-12-02 08:44:16 +0000249 AST->OriginalSourceFile = Reader->getOriginalSourceFile();
250
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000251 // PCH loaded successfully. Now create the preprocessor.
Mike Stump11289f42009-09-09 15:08:12 +0000252
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000253 // Get information about the target being compiled for.
Daniel Dunbarb9bbd542009-11-15 06:48:46 +0000254 //
255 // FIXME: This is broken, we should store the TargetOptions in the PCH.
256 TargetOptions TargetOpts;
257 TargetOpts.ABI = "";
Charles Davis95a546e2010-06-11 01:06:47 +0000258 TargetOpts.CXXABI = "itanium";
Daniel Dunbarb9bbd542009-11-15 06:48:46 +0000259 TargetOpts.CPU = "";
260 TargetOpts.Features.clear();
261 TargetOpts.Triple = TargetTriple;
Douglas Gregord03e8232010-04-05 21:10:19 +0000262 AST->Target.reset(TargetInfo::CreateTargetInfo(AST->getDiagnostics(),
263 TargetOpts));
264 AST->PP.reset(new Preprocessor(AST->getDiagnostics(), LangInfo,
265 *AST->Target.get(),
Daniel Dunbar7cd285f2009-09-21 03:03:39 +0000266 AST->getSourceManager(), HeaderInfo));
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000267 Preprocessor &PP = *AST->PP.get();
268
Daniel Dunbarb7bbfdd2009-09-21 03:03:47 +0000269 PP.setPredefines(Reader->getSuggestedPredefines());
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000270 PP.setCounterValue(Counter);
Daniel Dunbar2d9c7402009-09-03 05:59:35 +0000271 Reader->setPreprocessor(PP);
Mike Stump11289f42009-09-09 15:08:12 +0000272
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000273 // Create and initialize the ASTContext.
274
275 AST->Ctx.reset(new ASTContext(LangInfo,
Daniel Dunbar7cd285f2009-09-21 03:03:39 +0000276 AST->getSourceManager(),
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000277 *AST->Target.get(),
278 PP.getIdentifierTable(),
279 PP.getSelectorTable(),
280 PP.getBuiltinInfo(),
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000281 /* size_reserve = */0));
282 ASTContext &Context = *AST->Ctx.get();
Mike Stump11289f42009-09-09 15:08:12 +0000283
Daniel Dunbar2d9c7402009-09-03 05:59:35 +0000284 Reader->InitializeContext(Context);
Mike Stump11289f42009-09-09 15:08:12 +0000285
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000286 // Attach the PCH reader to the AST context as an external AST
287 // source, so that declarations will be deserialized from the
288 // PCH file as needed.
Daniel Dunbar2d9c7402009-09-03 05:59:35 +0000289 Source.reset(Reader.take());
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000290 Context.setExternalSource(Source);
291
Mike Stump11289f42009-09-09 15:08:12 +0000292 return AST.take();
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000293}
Daniel Dunbar764c0822009-12-01 09:51:01 +0000294
295namespace {
296
Daniel Dunbar644dca02009-12-04 08:17:33 +0000297class TopLevelDeclTrackerConsumer : public ASTConsumer {
298 ASTUnit &Unit;
299
300public:
301 TopLevelDeclTrackerConsumer(ASTUnit &_Unit) : Unit(_Unit) {}
302
303 void HandleTopLevelDecl(DeclGroupRef D) {
Ted Kremenekacc59c32010-05-03 20:16:35 +0000304 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
305 Decl *D = *it;
306 // FIXME: Currently ObjC method declarations are incorrectly being
307 // reported as top-level declarations, even though their DeclContext
308 // is the containing ObjC @interface/@implementation. This is a
309 // fundamental problem in the parser right now.
310 if (isa<ObjCMethodDecl>(D))
311 continue;
Douglas Gregore9db88f2010-08-03 19:06:41 +0000312 Unit.addTopLevelDecl(D);
Ted Kremenekacc59c32010-05-03 20:16:35 +0000313 }
Daniel Dunbar644dca02009-12-04 08:17:33 +0000314 }
315};
316
317class TopLevelDeclTrackerAction : public ASTFrontendAction {
318public:
319 ASTUnit &Unit;
320
Daniel Dunbar764c0822009-12-01 09:51:01 +0000321 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
322 llvm::StringRef InFile) {
Daniel Dunbar644dca02009-12-04 08:17:33 +0000323 return new TopLevelDeclTrackerConsumer(Unit);
Daniel Dunbar764c0822009-12-01 09:51:01 +0000324 }
325
326public:
Daniel Dunbar644dca02009-12-04 08:17:33 +0000327 TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {}
328
Daniel Dunbar764c0822009-12-01 09:51:01 +0000329 virtual bool hasCodeCompletionSupport() const { return false; }
330};
331
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000332class PrecompilePreambleConsumer : public PCHGenerator {
333 ASTUnit &Unit;
Douglas Gregore9db88f2010-08-03 19:06:41 +0000334 std::vector<Decl *> TopLevelDecls;
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000335
336public:
337 PrecompilePreambleConsumer(ASTUnit &Unit,
338 const Preprocessor &PP, bool Chaining,
339 const char *isysroot, llvm::raw_ostream *Out)
340 : PCHGenerator(PP, Chaining, isysroot, Out), Unit(Unit) { }
341
Douglas Gregore9db88f2010-08-03 19:06:41 +0000342 virtual void HandleTopLevelDecl(DeclGroupRef D) {
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000343 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
344 Decl *D = *it;
345 // FIXME: Currently ObjC method declarations are incorrectly being
346 // reported as top-level declarations, even though their DeclContext
347 // is the containing ObjC @interface/@implementation. This is a
348 // fundamental problem in the parser right now.
349 if (isa<ObjCMethodDecl>(D))
350 continue;
Douglas Gregore9db88f2010-08-03 19:06:41 +0000351 TopLevelDecls.push_back(D);
352 }
353 }
354
355 virtual void HandleTranslationUnit(ASTContext &Ctx) {
356 PCHGenerator::HandleTranslationUnit(Ctx);
357 if (!Unit.getDiagnostics().hasErrorOccurred()) {
358 // Translate the top-level declarations we captured during
359 // parsing into declaration IDs in the precompiled
360 // preamble. This will allow us to deserialize those top-level
361 // declarations when requested.
362 for (unsigned I = 0, N = TopLevelDecls.size(); I != N; ++I)
363 Unit.addTopLevelDeclFromPreamble(
364 getWriter().getDeclID(TopLevelDecls[I]));
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000365 }
366 }
367};
368
369class PrecompilePreambleAction : public ASTFrontendAction {
370 ASTUnit &Unit;
371
372public:
373 explicit PrecompilePreambleAction(ASTUnit &Unit) : Unit(Unit) {}
374
375 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
376 llvm::StringRef InFile) {
377 std::string Sysroot;
378 llvm::raw_ostream *OS = 0;
379 bool Chaining;
380 if (GeneratePCHAction::ComputeASTConsumerArguments(CI, InFile, Sysroot,
381 OS, Chaining))
382 return 0;
383
384 const char *isysroot = CI.getFrontendOpts().RelocatablePCH ?
385 Sysroot.c_str() : 0;
386 return new PrecompilePreambleConsumer(Unit, CI.getPreprocessor(), Chaining,
387 isysroot, OS);
388 }
389
390 virtual bool hasCodeCompletionSupport() const { return false; }
391 virtual bool hasASTFileSupport() const { return false; }
392};
393
Daniel Dunbar764c0822009-12-01 09:51:01 +0000394}
395
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000396/// Parse the source file into a translation unit using the given compiler
397/// invocation, replacing the current translation unit.
398///
399/// \returns True if a failure occurred that causes the ASTUnit not to
400/// contain any translation-unit information, false otherwise.
Douglas Gregor6481ef12010-07-24 00:38:13 +0000401bool ASTUnit::Parse(llvm::MemoryBuffer *OverrideMainBuffer) {
Douglas Gregor96c04262010-07-27 14:52:07 +0000402 delete SavedMainFileBuffer;
403 SavedMainFileBuffer = 0;
404
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000405 if (!Invocation.get())
406 return true;
407
Daniel Dunbar764c0822009-12-01 09:51:01 +0000408 // Create the compiler instance to use for building the AST.
Daniel Dunbar7afbb8c2009-12-02 08:43:56 +0000409 CompilerInstance Clang;
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000410 Clang.setInvocation(Invocation.take());
411 OriginalSourceFile = Clang.getFrontendOpts().Inputs[0].second;
412
413 // Set up diagnostics.
414 Clang.setDiagnostics(&getDiagnostics());
415 Clang.setDiagnosticClient(getDiagnostics().getClient());
Douglas Gregord03e8232010-04-05 21:10:19 +0000416
Daniel Dunbar764c0822009-12-01 09:51:01 +0000417 // Create the target instance.
418 Clang.setTarget(TargetInfo::CreateTargetInfo(Clang.getDiagnostics(),
419 Clang.getTargetOpts()));
Douglas Gregor33cdd812010-02-18 18:08:43 +0000420 if (!Clang.hasTarget()) {
Douglas Gregor33cdd812010-02-18 18:08:43 +0000421 Clang.takeDiagnosticClient();
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000422 return true;
Douglas Gregor33cdd812010-02-18 18:08:43 +0000423 }
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000424
Daniel Dunbar764c0822009-12-01 09:51:01 +0000425 // Inform the target of the language options.
426 //
427 // FIXME: We shouldn't need to do this, the target should be immutable once
428 // created. This complexity should be lifted elsewhere.
429 Clang.getTarget().setForcedLangOptions(Clang.getLangOpts());
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000430
Daniel Dunbar764c0822009-12-01 09:51:01 +0000431 assert(Clang.getFrontendOpts().Inputs.size() == 1 &&
432 "Invocation must have exactly one source file!");
Daniel Dunbar9b491e72010-06-07 23:22:09 +0000433 assert(Clang.getFrontendOpts().Inputs[0].first != IK_AST &&
Daniel Dunbar764c0822009-12-01 09:51:01 +0000434 "FIXME: AST inputs not yet supported here!");
Daniel Dunbar9507f9c2010-06-07 23:26:47 +0000435 assert(Clang.getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
436 "IR inputs not support here!");
Daniel Dunbar764c0822009-12-01 09:51:01 +0000437
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000438 // Configure the various subsystems.
439 // FIXME: Should we retain the previous file manager?
440 FileMgr.reset(new FileManager);
441 SourceMgr.reset(new SourceManager(getDiagnostics()));
442 Ctx.reset();
443 PP.reset();
444
445 // Clear out old caches and data.
446 TopLevelDecls.clear();
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000447 CleanTemporaryFiles();
448 PreprocessedEntitiesByFile.clear();
Douglas Gregord9a30af2010-08-02 20:51:39 +0000449
450 if (!OverrideMainBuffer)
451 StoredDiagnostics.clear();
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000452
Douglas Gregor33cdd812010-02-18 18:08:43 +0000453 // Capture any diagnostics that would otherwise be dropped.
454 CaptureDroppedDiagnostics Capture(CaptureDiagnostics,
455 Clang.getDiagnostics(),
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000456 StoredDiagnostics);
457
Daniel Dunbar764c0822009-12-01 09:51:01 +0000458 // Create a file manager object to provide access to and cache the filesystem.
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000459 Clang.setFileManager(&getFileManager());
460
Daniel Dunbar764c0822009-12-01 09:51:01 +0000461 // Create the source manager.
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000462 Clang.setSourceManager(&getSourceManager());
463
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000464 // If the main file has been overridden due to the use of a preamble,
465 // make that override happen and introduce the preamble.
466 PreprocessorOptions &PreprocessorOpts = Clang.getPreprocessorOpts();
467 if (OverrideMainBuffer) {
468 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
469 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
470 PreprocessorOpts.PrecompiledPreambleBytes.second
471 = PreambleEndsAtStartOfLine;
Douglas Gregor15ba0b32010-07-30 20:58:08 +0000472 PreprocessorOpts.ImplicitPCHInclude = PreambleFile;
Douglas Gregorce3a8292010-07-27 00:27:13 +0000473 PreprocessorOpts.DisablePCHValidation = true;
Douglas Gregor96c04262010-07-27 14:52:07 +0000474
475 // Keep track of the override buffer;
476 SavedMainFileBuffer = OverrideMainBuffer;
Douglas Gregord9a30af2010-08-02 20:51:39 +0000477
478 // The stored diagnostic has the old source manager in it; update
479 // the locations to refer into the new source manager. Since we've
480 // been careful to make sure that the source manager's state
481 // before and after are identical, so that we can reuse the source
482 // location itself.
483 for (unsigned I = 0, N = StoredDiagnostics.size(); I != N; ++I) {
484 FullSourceLoc Loc(StoredDiagnostics[I].getLocation(),
485 getSourceManager());
486 StoredDiagnostics[I].setLocation(Loc);
487 }
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000488 }
489
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000490 llvm::OwningPtr<TopLevelDeclTrackerAction> Act;
491 Act.reset(new TopLevelDeclTrackerAction(*this));
Daniel Dunbar644dca02009-12-04 08:17:33 +0000492 if (!Act->BeginSourceFile(Clang, Clang.getFrontendOpts().Inputs[0].second,
Daniel Dunbar86546382010-06-07 23:23:06 +0000493 Clang.getFrontendOpts().Inputs[0].first))
Daniel Dunbar764c0822009-12-01 09:51:01 +0000494 goto error;
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000495
Daniel Dunbar644dca02009-12-04 08:17:33 +0000496 Act->Execute();
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000497
Daniel Dunbard2f8be32009-12-01 21:57:33 +0000498 // Steal the created target, context, and preprocessor, and take back the
499 // source and file managers.
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000500 Ctx.reset(Clang.takeASTContext());
501 PP.reset(Clang.takePreprocessor());
Daniel Dunbar764c0822009-12-01 09:51:01 +0000502 Clang.takeSourceManager();
503 Clang.takeFileManager();
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000504 Target.reset(Clang.takeTarget());
505
Daniel Dunbar644dca02009-12-04 08:17:33 +0000506 Act->EndSourceFile();
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000507
508 // Remove the overridden buffer we used for the preamble.
Douglas Gregord9a30af2010-08-02 20:51:39 +0000509 if (OverrideMainBuffer)
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000510 PreprocessorOpts.eraseRemappedFile(
511 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000512
Daniel Dunbar764c0822009-12-01 09:51:01 +0000513 Clang.takeDiagnosticClient();
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000514
515 Invocation.reset(Clang.takeInvocation());
516 return false;
517
Daniel Dunbar764c0822009-12-01 09:51:01 +0000518error:
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000519 // Remove the overridden buffer we used for the preamble.
Douglas Gregorce3a8292010-07-27 00:27:13 +0000520 if (OverrideMainBuffer) {
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000521 PreprocessorOpts.eraseRemappedFile(
522 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregorce3a8292010-07-27 00:27:13 +0000523 PreprocessorOpts.DisablePCHValidation = true;
524 }
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000525
Daniel Dunbar764c0822009-12-01 09:51:01 +0000526 Clang.takeSourceManager();
527 Clang.takeFileManager();
528 Clang.takeDiagnosticClient();
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000529 Invocation.reset(Clang.takeInvocation());
530 return true;
531}
532
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000533/// \brief Simple function to retrieve a path for a preamble precompiled header.
534static std::string GetPreamblePCHPath() {
535 // FIXME: This is lame; sys::Path should provide this function (in particular,
536 // it should know how to find the temporary files dir).
537 // FIXME: This is really lame. I copied this code from the Driver!
538 std::string Error;
539 const char *TmpDir = ::getenv("TMPDIR");
540 if (!TmpDir)
541 TmpDir = ::getenv("TEMP");
542 if (!TmpDir)
543 TmpDir = ::getenv("TMP");
544 if (!TmpDir)
545 TmpDir = "/tmp";
546 llvm::sys::Path P(TmpDir);
547 P.appendComponent("preamble");
548 if (P.createTemporaryFileOnDisk())
549 return std::string();
550
551 P.appendSuffix("pch");
552 return P.str();
553}
554
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000555/// \brief Compute the preamble for the main file, providing the source buffer
556/// that corresponds to the main file along with a pair (bytes, start-of-line)
557/// that describes the preamble.
558std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> >
Douglas Gregor4dde7492010-07-23 23:58:40 +0000559ASTUnit::ComputePreamble(CompilerInvocation &Invocation, bool &CreatedBuffer) {
560 FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000561 PreprocessorOptions &PreprocessorOpts
Douglas Gregor4dde7492010-07-23 23:58:40 +0000562 = Invocation.getPreprocessorOpts();
563 CreatedBuffer = false;
564
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000565 // Try to determine if the main file has been remapped, either from the
566 // command line (to another file) or directly through the compiler invocation
567 // (to a memory buffer).
Douglas Gregor4dde7492010-07-23 23:58:40 +0000568 llvm::MemoryBuffer *Buffer = 0;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000569 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].second);
570 if (const llvm::sys::FileStatus *MainFileStatus = MainFilePath.getFileStatus()) {
571 // Check whether there is a file-file remapping of the main file
572 for (PreprocessorOptions::remapped_file_iterator
Douglas Gregor4dde7492010-07-23 23:58:40 +0000573 M = PreprocessorOpts.remapped_file_begin(),
574 E = PreprocessorOpts.remapped_file_end();
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000575 M != E;
576 ++M) {
577 llvm::sys::PathWithStatus MPath(M->first);
578 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
579 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
580 // We found a remapping. Try to load the resulting, remapped source.
Douglas Gregor4dde7492010-07-23 23:58:40 +0000581 if (CreatedBuffer) {
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000582 delete Buffer;
Douglas Gregor4dde7492010-07-23 23:58:40 +0000583 CreatedBuffer = false;
584 }
585
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000586 Buffer = llvm::MemoryBuffer::getFile(M->second);
587 if (!Buffer)
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000588 return std::make_pair((llvm::MemoryBuffer*)0,
589 std::make_pair(0, true));
Douglas Gregor4dde7492010-07-23 23:58:40 +0000590 CreatedBuffer = true;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000591
Douglas Gregor4dde7492010-07-23 23:58:40 +0000592 // Remove this remapping. We've captured the buffer already.
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000593 M = PreprocessorOpts.eraseRemappedFile(M);
594 E = PreprocessorOpts.remapped_file_end();
595 }
596 }
597 }
598
599 // Check whether there is a file-buffer remapping. It supercedes the
600 // file-file remapping.
601 for (PreprocessorOptions::remapped_file_buffer_iterator
602 M = PreprocessorOpts.remapped_file_buffer_begin(),
603 E = PreprocessorOpts.remapped_file_buffer_end();
604 M != E;
605 ++M) {
606 llvm::sys::PathWithStatus MPath(M->first);
607 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
608 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
609 // We found a remapping.
Douglas Gregor4dde7492010-07-23 23:58:40 +0000610 if (CreatedBuffer) {
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000611 delete Buffer;
Douglas Gregor4dde7492010-07-23 23:58:40 +0000612 CreatedBuffer = false;
613 }
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000614
Douglas Gregor4dde7492010-07-23 23:58:40 +0000615 Buffer = const_cast<llvm::MemoryBuffer *>(M->second);
616
617 // Remove this remapping. We've captured the buffer already.
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000618 M = PreprocessorOpts.eraseRemappedFile(M);
619 E = PreprocessorOpts.remapped_file_buffer_end();
620 }
621 }
Douglas Gregor4dde7492010-07-23 23:58:40 +0000622 }
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000623 }
624
625 // If the main source file was not remapped, load it now.
626 if (!Buffer) {
627 Buffer = llvm::MemoryBuffer::getFile(FrontendOpts.Inputs[0].second);
628 if (!Buffer)
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000629 return std::make_pair((llvm::MemoryBuffer*)0, std::make_pair(0, true));
Douglas Gregor4dde7492010-07-23 23:58:40 +0000630
631 CreatedBuffer = true;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000632 }
633
Douglas Gregor4dde7492010-07-23 23:58:40 +0000634 return std::make_pair(Buffer, Lexer::ComputePreamble(Buffer));
635}
636
Douglas Gregor6481ef12010-07-24 00:38:13 +0000637static llvm::MemoryBuffer *CreatePaddedMainFileBuffer(llvm::MemoryBuffer *Old,
638 bool DeleteOld,
639 unsigned NewSize,
640 llvm::StringRef NewName) {
641 llvm::MemoryBuffer *Result
642 = llvm::MemoryBuffer::getNewUninitMemBuffer(NewSize, NewName);
643 memcpy(const_cast<char*>(Result->getBufferStart()),
644 Old->getBufferStart(), Old->getBufferSize());
645 memset(const_cast<char*>(Result->getBufferStart()) + Old->getBufferSize(),
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000646 ' ', NewSize - Old->getBufferSize() - 1);
647 const_cast<char*>(Result->getBufferEnd())[-1] = '\n';
Douglas Gregor6481ef12010-07-24 00:38:13 +0000648
649 if (DeleteOld)
650 delete Old;
651
652 return Result;
653}
654
Douglas Gregor4dde7492010-07-23 23:58:40 +0000655/// \brief Attempt to build or re-use a precompiled preamble when (re-)parsing
656/// the source file.
657///
658/// This routine will compute the preamble of the main source file. If a
659/// non-trivial preamble is found, it will precompile that preamble into a
660/// precompiled header so that the precompiled preamble can be used to reduce
661/// reparsing time. If a precompiled preamble has already been constructed,
662/// this routine will determine if it is still valid and, if so, avoid
663/// rebuilding the precompiled preamble.
664///
Douglas Gregor6481ef12010-07-24 00:38:13 +0000665/// \returns If the precompiled preamble can be used, returns a newly-allocated
666/// buffer that should be used in place of the main file when doing so.
667/// Otherwise, returns a NULL pointer.
668llvm::MemoryBuffer *ASTUnit::BuildPrecompiledPreamble() {
Douglas Gregor4dde7492010-07-23 23:58:40 +0000669 CompilerInvocation PreambleInvocation(*Invocation);
670 FrontendOptions &FrontendOpts = PreambleInvocation.getFrontendOpts();
671 PreprocessorOptions &PreprocessorOpts
672 = PreambleInvocation.getPreprocessorOpts();
673
674 bool CreatedPreambleBuffer = false;
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000675 std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> > NewPreamble
Douglas Gregor4dde7492010-07-23 23:58:40 +0000676 = ComputePreamble(PreambleInvocation, CreatedPreambleBuffer);
677
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000678 if (!NewPreamble.second.first) {
Douglas Gregor4dde7492010-07-23 23:58:40 +0000679 // We couldn't find a preamble in the main source. Clear out the current
680 // preamble, if we have one. It's obviously no good any more.
681 Preamble.clear();
682 if (!PreambleFile.empty()) {
Douglas Gregor15ba0b32010-07-30 20:58:08 +0000683 llvm::sys::Path(PreambleFile).eraseFromDisk();
Douglas Gregor4dde7492010-07-23 23:58:40 +0000684 PreambleFile.clear();
685 }
686 if (CreatedPreambleBuffer)
687 delete NewPreamble.first;
688
Douglas Gregor6481ef12010-07-24 00:38:13 +0000689 return 0;
Douglas Gregor4dde7492010-07-23 23:58:40 +0000690 }
691
692 if (!Preamble.empty()) {
693 // We've previously computed a preamble. Check whether we have the same
694 // preamble now that we did before, and that there's enough space in
695 // the main-file buffer within the precompiled preamble to fit the
696 // new main file.
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000697 if (Preamble.size() == NewPreamble.second.first &&
698 PreambleEndsAtStartOfLine == NewPreamble.second.second &&
Douglas Gregorf5275a82010-07-24 00:42:07 +0000699 NewPreamble.first->getBufferSize() < PreambleReservedSize-2 &&
Douglas Gregor4dde7492010-07-23 23:58:40 +0000700 memcmp(&Preamble[0], NewPreamble.first->getBufferStart(),
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000701 NewPreamble.second.first) == 0) {
Douglas Gregor4dde7492010-07-23 23:58:40 +0000702 // The preamble has not changed. We may be able to re-use the precompiled
703 // preamble.
Douglas Gregord9a30af2010-08-02 20:51:39 +0000704
Douglas Gregor0e119552010-07-31 00:40:00 +0000705 // Check that none of the files used by the preamble have changed.
706 bool AnyFileChanged = false;
707
708 // First, make a record of those files that have been overridden via
709 // remapping or unsaved_files.
710 llvm::StringMap<std::pair<off_t, time_t> > OverriddenFiles;
711 for (PreprocessorOptions::remapped_file_iterator
712 R = PreprocessorOpts.remapped_file_begin(),
713 REnd = PreprocessorOpts.remapped_file_end();
714 !AnyFileChanged && R != REnd;
715 ++R) {
716 struct stat StatBuf;
717 if (stat(R->second.c_str(), &StatBuf)) {
718 // If we can't stat the file we're remapping to, assume that something
719 // horrible happened.
720 AnyFileChanged = true;
721 break;
722 }
Douglas Gregor6481ef12010-07-24 00:38:13 +0000723
Douglas Gregor0e119552010-07-31 00:40:00 +0000724 OverriddenFiles[R->first] = std::make_pair(StatBuf.st_size,
725 StatBuf.st_mtime);
726 }
727 for (PreprocessorOptions::remapped_file_buffer_iterator
728 R = PreprocessorOpts.remapped_file_buffer_begin(),
729 REnd = PreprocessorOpts.remapped_file_buffer_end();
730 !AnyFileChanged && R != REnd;
731 ++R) {
732 // FIXME: Should we actually compare the contents of file->buffer
733 // remappings?
734 OverriddenFiles[R->first] = std::make_pair(R->second->getBufferSize(),
735 0);
736 }
737
738 // Check whether anything has changed.
739 for (llvm::StringMap<std::pair<off_t, time_t> >::iterator
740 F = FilesInPreamble.begin(), FEnd = FilesInPreamble.end();
741 !AnyFileChanged && F != FEnd;
742 ++F) {
743 llvm::StringMap<std::pair<off_t, time_t> >::iterator Overridden
744 = OverriddenFiles.find(F->first());
745 if (Overridden != OverriddenFiles.end()) {
746 // This file was remapped; check whether the newly-mapped file
747 // matches up with the previous mapping.
748 if (Overridden->second != F->second)
749 AnyFileChanged = true;
750 continue;
751 }
752
753 // The file was not remapped; check whether it has changed on disk.
754 struct stat StatBuf;
755 if (stat(F->first(), &StatBuf)) {
756 // If we can't stat the file, assume that something horrible happened.
757 AnyFileChanged = true;
758 } else if (StatBuf.st_size != F->second.first ||
759 StatBuf.st_mtime != F->second.second)
760 AnyFileChanged = true;
761 }
762
763 if (!AnyFileChanged) {
Douglas Gregord9a30af2010-08-02 20:51:39 +0000764 // Okay! We can re-use the precompiled preamble.
765
766 // Set the state of the diagnostic object to mimic its state
767 // after parsing the preamble.
768 getDiagnostics().Reset();
769 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
770 if (StoredDiagnostics.size() > NumStoredDiagnosticsInPreamble)
771 StoredDiagnostics.erase(
772 StoredDiagnostics.begin() + NumStoredDiagnosticsInPreamble,
773 StoredDiagnostics.end());
774
775 // Create a version of the main file buffer that is padded to
776 // buffer size we reserved when creating the preamble.
Douglas Gregor0e119552010-07-31 00:40:00 +0000777 return CreatePaddedMainFileBuffer(NewPreamble.first,
778 CreatedPreambleBuffer,
779 PreambleReservedSize,
780 FrontendOpts.Inputs[0].second);
781 }
Douglas Gregor4dde7492010-07-23 23:58:40 +0000782 }
783
784 // We can't reuse the previously-computed preamble. Build a new one.
785 Preamble.clear();
Douglas Gregor15ba0b32010-07-30 20:58:08 +0000786 llvm::sys::Path(PreambleFile).eraseFromDisk();
Douglas Gregor4dde7492010-07-23 23:58:40 +0000787 }
788
789 // We did not previously compute a preamble, or it can't be reused anyway.
Douglas Gregor15ba0b32010-07-30 20:58:08 +0000790 llvm::Timer *PreambleTimer = 0;
791 if (TimerGroup.get()) {
792 PreambleTimer = new llvm::Timer("Precompiling preamble", *TimerGroup);
793 PreambleTimer->startTimer();
794 Timers.push_back(PreambleTimer);
795 }
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000796
797 // Create a new buffer that stores the preamble. The buffer also contains
798 // extra space for the original contents of the file (which will be present
799 // when we actually parse the file) along with more room in case the file
Douglas Gregor4dde7492010-07-23 23:58:40 +0000800 // grows.
801 PreambleReservedSize = NewPreamble.first->getBufferSize();
802 if (PreambleReservedSize < 4096)
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000803 PreambleReservedSize = 8191;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000804 else
Douglas Gregor4dde7492010-07-23 23:58:40 +0000805 PreambleReservedSize *= 2;
806
Douglas Gregord9a30af2010-08-02 20:51:39 +0000807 // Save the preamble text for later; we'll need to compare against it for
808 // subsequent reparses.
809 Preamble.assign(NewPreamble.first->getBufferStart(),
810 NewPreamble.first->getBufferStart()
811 + NewPreamble.second.first);
812 PreambleEndsAtStartOfLine = NewPreamble.second.second;
813
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000814 llvm::MemoryBuffer *PreambleBuffer
Douglas Gregor4dde7492010-07-23 23:58:40 +0000815 = llvm::MemoryBuffer::getNewUninitMemBuffer(PreambleReservedSize,
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000816 FrontendOpts.Inputs[0].second);
817 memcpy(const_cast<char*>(PreambleBuffer->getBufferStart()),
Douglas Gregor4dde7492010-07-23 23:58:40 +0000818 NewPreamble.first->getBufferStart(), Preamble.size());
819 memset(const_cast<char*>(PreambleBuffer->getBufferStart()) + Preamble.size(),
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000820 ' ', PreambleReservedSize - Preamble.size() - 1);
821 const_cast<char*>(PreambleBuffer->getBufferEnd())[-1] = '\n';
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000822
823 // Remap the main source file to the preamble buffer.
Douglas Gregor4dde7492010-07-23 23:58:40 +0000824 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].second);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000825 PreprocessorOpts.addRemappedFile(MainFilePath.str(), PreambleBuffer);
826
827 // Tell the compiler invocation to generate a temporary precompiled header.
828 FrontendOpts.ProgramAction = frontend::GeneratePCH;
829 // FIXME: Set ChainedPCH, once it is ready.
830 // FIXME: Generate the precompiled header into memory?
Douglas Gregor15ba0b32010-07-30 20:58:08 +0000831 FrontendOpts.OutputFile = GetPreamblePCHPath();
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000832
833 // Create the compiler instance to use for building the precompiled preamble.
834 CompilerInstance Clang;
835 Clang.setInvocation(&PreambleInvocation);
836 OriginalSourceFile = Clang.getFrontendOpts().Inputs[0].second;
837
838 // Set up diagnostics.
839 Clang.setDiagnostics(&getDiagnostics());
840 Clang.setDiagnosticClient(getDiagnostics().getClient());
841
842 // Create the target instance.
843 Clang.setTarget(TargetInfo::CreateTargetInfo(Clang.getDiagnostics(),
844 Clang.getTargetOpts()));
845 if (!Clang.hasTarget()) {
846 Clang.takeDiagnosticClient();
Douglas Gregor4dde7492010-07-23 23:58:40 +0000847 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
848 Preamble.clear();
849 if (CreatedPreambleBuffer)
850 delete NewPreamble.first;
Douglas Gregor15ba0b32010-07-30 20:58:08 +0000851 if (PreambleTimer)
852 PreambleTimer->stopTimer();
Douglas Gregor4dde7492010-07-23 23:58:40 +0000853
Douglas Gregor6481ef12010-07-24 00:38:13 +0000854 return 0;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000855 }
856
857 // Inform the target of the language options.
858 //
859 // FIXME: We shouldn't need to do this, the target should be immutable once
860 // created. This complexity should be lifted elsewhere.
861 Clang.getTarget().setForcedLangOptions(Clang.getLangOpts());
862
863 assert(Clang.getFrontendOpts().Inputs.size() == 1 &&
864 "Invocation must have exactly one source file!");
865 assert(Clang.getFrontendOpts().Inputs[0].first != IK_AST &&
866 "FIXME: AST inputs not yet supported here!");
867 assert(Clang.getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
868 "IR inputs not support here!");
869
870 // Clear out old caches and data.
871 StoredDiagnostics.clear();
Douglas Gregore9db88f2010-08-03 19:06:41 +0000872 TopLevelDecls.clear();
873 TopLevelDeclsInPreamble.clear();
874
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000875 // Capture any diagnostics that would otherwise be dropped.
876 CaptureDroppedDiagnostics Capture(CaptureDiagnostics,
Douglas Gregord9a30af2010-08-02 20:51:39 +0000877 getDiagnostics(),
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000878 StoredDiagnostics);
879
880 // Create a file manager object to provide access to and cache the filesystem.
881 Clang.setFileManager(new FileManager);
882
883 // Create the source manager.
884 Clang.setSourceManager(new SourceManager(getDiagnostics()));
885
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000886 llvm::OwningPtr<PrecompilePreambleAction> Act;
887 Act.reset(new PrecompilePreambleAction(*this));
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000888 if (!Act->BeginSourceFile(Clang, Clang.getFrontendOpts().Inputs[0].second,
889 Clang.getFrontendOpts().Inputs[0].first)) {
890 Clang.takeDiagnosticClient();
891 Clang.takeInvocation();
Douglas Gregor4dde7492010-07-23 23:58:40 +0000892 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
893 Preamble.clear();
894 if (CreatedPreambleBuffer)
895 delete NewPreamble.first;
Douglas Gregor15ba0b32010-07-30 20:58:08 +0000896 if (PreambleTimer)
897 PreambleTimer->stopTimer();
898
Douglas Gregor6481ef12010-07-24 00:38:13 +0000899 return 0;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000900 }
901
902 Act->Execute();
903 Act->EndSourceFile();
904 Clang.takeDiagnosticClient();
905 Clang.takeInvocation();
906
Douglas Gregore9db88f2010-08-03 19:06:41 +0000907 if (Diagnostics->hasErrorOccurred()) {
Douglas Gregor4dde7492010-07-23 23:58:40 +0000908 // There were errors parsing the preamble, so no precompiled header was
909 // generated. Forget that we even tried.
910 // FIXME: Should we leave a note for ourselves to try again?
911 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
912 Preamble.clear();
913 if (CreatedPreambleBuffer)
914 delete NewPreamble.first;
Douglas Gregor15ba0b32010-07-30 20:58:08 +0000915 if (PreambleTimer)
916 PreambleTimer->stopTimer();
Douglas Gregore9db88f2010-08-03 19:06:41 +0000917 TopLevelDeclsInPreamble.clear();
Douglas Gregor6481ef12010-07-24 00:38:13 +0000918 return 0;
Douglas Gregor4dde7492010-07-23 23:58:40 +0000919 }
920
921 // Keep track of the preamble we precompiled.
922 PreambleFile = FrontendOpts.OutputFile;
Douglas Gregord9a30af2010-08-02 20:51:39 +0000923 NumStoredDiagnosticsInPreamble = StoredDiagnostics.size();
924 NumWarningsInPreamble = getDiagnostics().getNumWarnings();
Douglas Gregor0e119552010-07-31 00:40:00 +0000925
926 // Keep track of all of the files that the source manager knows about,
927 // so we can verify whether they have changed or not.
928 FilesInPreamble.clear();
929 SourceManager &SourceMgr = Clang.getSourceManager();
930 const llvm::MemoryBuffer *MainFileBuffer
931 = SourceMgr.getBuffer(SourceMgr.getMainFileID());
932 for (SourceManager::fileinfo_iterator F = SourceMgr.fileinfo_begin(),
933 FEnd = SourceMgr.fileinfo_end();
934 F != FEnd;
935 ++F) {
936 const FileEntry *File = F->second->Entry;
937 if (!File || F->second->getRawBuffer() == MainFileBuffer)
938 continue;
939
940 FilesInPreamble[File->getName()]
941 = std::make_pair(F->second->getSize(), File->getModificationTime());
942 }
943
Douglas Gregor15ba0b32010-07-30 20:58:08 +0000944 if (PreambleTimer)
945 PreambleTimer->stopTimer();
946
Douglas Gregor6481ef12010-07-24 00:38:13 +0000947 return CreatePaddedMainFileBuffer(NewPreamble.first,
948 CreatedPreambleBuffer,
949 PreambleReservedSize,
950 FrontendOpts.Inputs[0].second);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000951}
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000952
Douglas Gregore9db88f2010-08-03 19:06:41 +0000953void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
954 std::vector<Decl *> Resolved;
955 Resolved.reserve(TopLevelDeclsInPreamble.size());
956 ExternalASTSource &Source = *getASTContext().getExternalSource();
957 for (unsigned I = 0, N = TopLevelDeclsInPreamble.size(); I != N; ++I) {
958 // Resolve the declaration ID to an actual declaration, possibly
959 // deserializing the declaration in the process.
960 Decl *D = Source.GetExternalDecl(TopLevelDeclsInPreamble[I]);
961 if (D)
962 Resolved.push_back(D);
963 }
964 TopLevelDeclsInPreamble.clear();
965 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
966}
967
968unsigned ASTUnit::getMaxPCHLevel() const {
969 if (!getOnlyLocalDecls())
970 return Decl::MaxPCHLevel;
971
972 unsigned Result = 0;
973 if (isMainFileAST() || SavedMainFileBuffer)
974 ++Result;
975 return Result;
976}
977
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000978ASTUnit *ASTUnit::LoadFromCompilerInvocation(CompilerInvocation *CI,
979 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
980 bool OnlyLocalDecls,
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000981 bool CaptureDiagnostics,
982 bool PrecompilePreamble) {
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000983 if (!Diags.getPtr()) {
984 // No diagnostics engine was provided, so create our own diagnostics object
985 // with the default options.
986 DiagnosticOptions DiagOpts;
987 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
988 }
989
990 // Create the AST unit.
991 llvm::OwningPtr<ASTUnit> AST;
992 AST.reset(new ASTUnit(false));
993 AST->Diagnostics = Diags;
994 AST->CaptureDiagnostics = CaptureDiagnostics;
995 AST->OnlyLocalDecls = OnlyLocalDecls;
996 AST->Invocation.reset(CI);
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000997 CI->getPreprocessorOpts().RetainRemappedFileBuffers = true;
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000998
Douglas Gregor15ba0b32010-07-30 20:58:08 +0000999 if (getenv("LIBCLANG_TIMING"))
1000 AST->TimerGroup.reset(
1001 new llvm::TimerGroup(CI->getFrontendOpts().Inputs[0].second));
1002
1003
Douglas Gregor6481ef12010-07-24 00:38:13 +00001004 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Douglas Gregora5fd5222010-07-28 22:12:37 +00001005 // FIXME: When C++ PCH is ready, allow use of it for a precompiled preamble.
1006 if (PrecompilePreamble && !CI->getLangOpts().CPlusPlus)
Douglas Gregor6481ef12010-07-24 00:38:13 +00001007 OverrideMainBuffer = AST->BuildPrecompiledPreamble();
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001008
Douglas Gregor15ba0b32010-07-30 20:58:08 +00001009 llvm::Timer *ParsingTimer = 0;
1010 if (AST->TimerGroup.get()) {
1011 ParsingTimer = new llvm::Timer("Initial parse", *AST->TimerGroup);
1012 ParsingTimer->startTimer();
1013 AST->Timers.push_back(ParsingTimer);
1014 }
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001015
Douglas Gregor15ba0b32010-07-30 20:58:08 +00001016 bool Failed = AST->Parse(OverrideMainBuffer);
1017 if (ParsingTimer)
1018 ParsingTimer->stopTimer();
1019
1020 return Failed? 0 : AST.take();
Daniel Dunbar764c0822009-12-01 09:51:01 +00001021}
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001022
1023ASTUnit *ASTUnit::LoadFromCommandLine(const char **ArgBegin,
1024 const char **ArgEnd,
Douglas Gregor7f95d262010-04-05 23:52:57 +00001025 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
Daniel Dunbar8d4a2022009-12-13 03:46:13 +00001026 llvm::StringRef ResourceFilesPath,
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001027 bool OnlyLocalDecls,
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001028 RemappedFile *RemappedFiles,
Douglas Gregor33cdd812010-02-18 18:08:43 +00001029 unsigned NumRemappedFiles,
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001030 bool CaptureDiagnostics,
1031 bool PrecompilePreamble) {
Douglas Gregor7f95d262010-04-05 23:52:57 +00001032 if (!Diags.getPtr()) {
Douglas Gregord03e8232010-04-05 21:10:19 +00001033 // No diagnostics engine was provided, so create our own diagnostics object
1034 // with the default options.
1035 DiagnosticOptions DiagOpts;
Douglas Gregor7f95d262010-04-05 23:52:57 +00001036 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Douglas Gregord03e8232010-04-05 21:10:19 +00001037 }
1038
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001039 llvm::SmallVector<const char *, 16> Args;
1040 Args.push_back("<clang>"); // FIXME: Remove dummy argument.
1041 Args.insert(Args.end(), ArgBegin, ArgEnd);
1042
1043 // FIXME: Find a cleaner way to force the driver into restricted modes. We
1044 // also want to force it to use clang.
1045 Args.push_back("-fsyntax-only");
1046
Daniel Dunbar8d4a2022009-12-13 03:46:13 +00001047 // FIXME: We shouldn't have to pass in the path info.
Daniel Dunbare38764c2010-07-19 00:44:04 +00001048 driver::Driver TheDriver("clang", llvm::sys::getHostTriple(),
Douglas Gregord03e8232010-04-05 21:10:19 +00001049 "a.out", false, false, *Diags);
Daniel Dunbarfcf2d422010-01-25 00:44:02 +00001050
1051 // Don't check that inputs exist, they have been remapped.
1052 TheDriver.setCheckInputsExist(false);
1053
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001054 llvm::OwningPtr<driver::Compilation> C(
1055 TheDriver.BuildCompilation(Args.size(), Args.data()));
1056
1057 // We expect to get back exactly one command job, if we didn't something
1058 // failed.
1059 const driver::JobList &Jobs = C->getJobs();
1060 if (Jobs.size() != 1 || !isa<driver::Command>(Jobs.begin())) {
1061 llvm::SmallString<256> Msg;
1062 llvm::raw_svector_ostream OS(Msg);
1063 C->PrintJob(OS, C->getJobs(), "; ", true);
Douglas Gregord03e8232010-04-05 21:10:19 +00001064 Diags->Report(diag::err_fe_expected_compiler_job) << OS.str();
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001065 return 0;
1066 }
1067
1068 const driver::Command *Cmd = cast<driver::Command>(*Jobs.begin());
1069 if (llvm::StringRef(Cmd->getCreator().getName()) != "clang") {
Douglas Gregord03e8232010-04-05 21:10:19 +00001070 Diags->Report(diag::err_fe_expected_clang_command);
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001071 return 0;
1072 }
1073
1074 const driver::ArgStringList &CCArgs = Cmd->getArguments();
Daniel Dunbar6b03ece2010-01-30 21:47:16 +00001075 llvm::OwningPtr<CompilerInvocation> CI(new CompilerInvocation);
Dan Gohman145f3f12010-04-19 16:39:44 +00001076 CompilerInvocation::CreateFromArgs(*CI,
1077 const_cast<const char **>(CCArgs.data()),
1078 const_cast<const char **>(CCArgs.data()) +
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001079 CCArgs.size(),
Douglas Gregord03e8232010-04-05 21:10:19 +00001080 *Diags);
Daniel Dunbard6136772009-12-13 03:45:58 +00001081
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001082 // Override any files that need remapping
1083 for (unsigned I = 0; I != NumRemappedFiles; ++I)
Daniel Dunbar6b03ece2010-01-30 21:47:16 +00001084 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
Daniel Dunbar19511922010-02-16 01:55:04 +00001085 RemappedFiles[I].second);
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001086
Daniel Dunbara5a166d2009-12-15 00:06:45 +00001087 // Override the resources path.
Daniel Dunbar6b03ece2010-01-30 21:47:16 +00001088 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001089
Daniel Dunbar19511922010-02-16 01:55:04 +00001090 CI->getFrontendOpts().DisableFree = true;
Douglas Gregor33cdd812010-02-18 18:08:43 +00001091 return LoadFromCompilerInvocation(CI.take(), Diags, OnlyLocalDecls,
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001092 CaptureDiagnostics, PrecompilePreamble);
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001093}
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001094
1095bool ASTUnit::Reparse(RemappedFile *RemappedFiles, unsigned NumRemappedFiles) {
1096 if (!Invocation.get())
1097 return true;
1098
Douglas Gregor15ba0b32010-07-30 20:58:08 +00001099 llvm::Timer *ReparsingTimer = 0;
1100 if (TimerGroup.get()) {
1101 ReparsingTimer = new llvm::Timer("Reparse", *TimerGroup);
1102 ReparsingTimer->startTimer();
1103 Timers.push_back(ReparsingTimer);
1104 }
1105
Douglas Gregor0e119552010-07-31 00:40:00 +00001106 // Remap files.
1107 // FIXME: Do we want to remove old mappings for these files?
1108 Invocation->getPreprocessorOpts().clearRemappedFiles();
1109 for (unsigned I = 0; I != NumRemappedFiles; ++I)
1110 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
1111 RemappedFiles[I].second);
1112
Douglas Gregor4dde7492010-07-23 23:58:40 +00001113 // If we have a preamble file lying around, build or reuse the precompiled
1114 // preamble.
Douglas Gregor6481ef12010-07-24 00:38:13 +00001115 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Douglas Gregor4dde7492010-07-23 23:58:40 +00001116 if (!PreambleFile.empty())
Douglas Gregor6481ef12010-07-24 00:38:13 +00001117 OverrideMainBuffer = BuildPrecompiledPreamble();
Douglas Gregor4dde7492010-07-23 23:58:40 +00001118
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001119 // Clear out the diagnostics state.
Douglas Gregord9a30af2010-08-02 20:51:39 +00001120 if (!OverrideMainBuffer)
1121 getDiagnostics().Reset();
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001122
Douglas Gregor4dde7492010-07-23 23:58:40 +00001123 // Parse the sources
Douglas Gregor6481ef12010-07-24 00:38:13 +00001124 bool Result = Parse(OverrideMainBuffer);
Douglas Gregor15ba0b32010-07-30 20:58:08 +00001125 if (ReparsingTimer)
1126 ReparsingTimer->stopTimer();
Douglas Gregor4dde7492010-07-23 23:58:40 +00001127 return Result;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001128}