blob: bd60296ca80e6f3f63f17f036325a65fc898e7fb [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 Gregor385103b2010-07-30 20:58:08 +000037#include "llvm/Support/Timer.h"
Douglas Gregor44c181a2010-07-23 00:33:23 +000038#include <cstdlib>
Zhongxing Xuad23ebe2010-07-23 02:15:08 +000039#include <cstdio>
Douglas Gregorcc5888d2010-07-31 00:40:00 +000040#include <sys/stat.h>
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000041using namespace clang;
42
Douglas Gregor3687e9d2010-04-05 21:10:19 +000043ASTUnit::ASTUnit(bool _MainFileIsAST)
Douglas Gregorabc563f2010-07-19 21:46:24 +000044 : CaptureDiagnostics(false), MainFileIsAST(_MainFileIsAST),
Douglas Gregor385103b2010-07-30 20:58:08 +000045 ConcurrencyCheckValue(CheckUnlocked), SavedMainFileBuffer(0) {
46}
Douglas Gregor3687e9d2010-04-05 21:10:19 +000047
Daniel Dunbar521bf9c2009-12-01 09:51:01 +000048ASTUnit::~ASTUnit() {
Douglas Gregorbdf60622010-03-05 21:16:25 +000049 ConcurrencyCheckValue = CheckLocked;
Douglas Gregorabc563f2010-07-19 21:46:24 +000050 CleanTemporaryFiles();
Douglas Gregor175c4a92010-07-23 23:58:40 +000051 if (!PreambleFile.empty())
Douglas Gregor385103b2010-07-30 20:58:08 +000052 llvm::sys::Path(PreambleFile).eraseFromDisk();
Douglas Gregorf4f6c9d2010-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 Gregor28233422010-07-27 14:52:07 +000067
68 delete SavedMainFileBuffer;
Douglas Gregor385103b2010-07-30 20:58:08 +000069
70 for (unsigned I = 0, N = Timers.size(); I != N; ++I)
71 delete Timers[I];
Douglas Gregorabc563f2010-07-19 21:46:24 +000072}
73
74void ASTUnit::CleanTemporaryFiles() {
Douglas Gregor313e26c2010-02-18 23:35:40 +000075 for (unsigned I = 0, N = TemporaryFiles.size(); I != N; ++I)
76 TemporaryFiles[I].eraseFromDisk();
Douglas Gregorabc563f2010-07-19 21:46:24 +000077 TemporaryFiles.clear();
Steve Naroffe19944c2009-10-15 22:23:48 +000078}
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000079
80namespace {
81
82/// \brief Gathers information from PCHReader that will be used to initialize
83/// a Preprocessor.
Benjamin Kramerbd218282009-11-28 10:07:24 +000084class PCHInfoCollector : public PCHReaderListener {
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000085 LangOptions &LangOpt;
86 HeaderSearch &HSI;
87 std::string &TargetTriple;
88 std::string &Predefines;
89 unsigned &Counter;
Mike Stump1eb44332009-09-09 15:08:12 +000090
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000091 unsigned NumHeaderInfos;
Mike Stump1eb44332009-09-09 15:08:12 +000092
Argyrios Kyrtzidis0853a022009-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 Stump1eb44332009-09-09 15:08:12 +000099
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000100 virtual bool ReadLanguageOptions(const LangOptions &LangOpts) {
101 LangOpt = LangOpts;
102 return false;
103 }
Mike Stump1eb44332009-09-09 15:08:12 +0000104
Daniel Dunbardc3c0d22009-11-11 00:52:11 +0000105 virtual bool ReadTargetTriple(llvm::StringRef Triple) {
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000106 TargetTriple = Triple;
107 return false;
108 }
Mike Stump1eb44332009-09-09 15:08:12 +0000109
Sebastian Redlcb481aa2010-07-14 23:29:55 +0000110 virtual bool ReadPredefinesBuffer(const PCHPredefinesBlocks &Buffers,
Daniel Dunbar7b5a1212009-11-11 05:29:04 +0000111 llvm::StringRef OriginalFileName,
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000112 std::string &SuggestedPredefines) {
Sebastian Redlcb481aa2010-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 Kyrtzidis0853a022009-06-20 08:08:23 +0000117 return false;
118 }
Mike Stump1eb44332009-09-09 15:08:12 +0000119
Douglas Gregorec1afbf2010-03-16 19:09:18 +0000120 virtual void ReadHeaderFileInfo(const HeaderFileInfo &HFI, unsigned ID) {
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000121 HSI.setHeaderFileInfoForUID(HFI, NumHeaderInfos++);
122 }
Mike Stump1eb44332009-09-09 15:08:12 +0000123
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000124 virtual void ReadCounter(unsigned Value) {
125 Counter = Value;
126 }
127};
128
Douglas Gregora88084b2010-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 Kyrtzidis0853a022009-06-20 08:08:23 +0000162} // anonymous namespace
163
Douglas Gregora88084b2010-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 Naroff77accc12009-09-03 18:19:54 +0000169const std::string &ASTUnit::getOriginalSourceFileName() {
Daniel Dunbar68d40e22009-12-02 08:44:16 +0000170 return OriginalSourceFile;
Steve Naroff77accc12009-09-03 18:19:54 +0000171}
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000172
Steve Naroffe19944c2009-10-15 22:23:48 +0000173const std::string &ASTUnit::getPCHFileName() {
Daniel Dunbarc7822db2009-12-02 21:47:43 +0000174 assert(isMainFileAST() && "Not an ASTUnit from a PCH file!");
Benjamin Kramer7297c182010-01-30 16:23:25 +0000175 return static_cast<PCHReader *>(Ctx->getExternalSource())->getFileName();
Steve Naroffe19944c2009-10-15 22:23:48 +0000176}
177
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000178ASTUnit *ASTUnit::LoadFromPCHFile(const std::string &Filename,
Douglas Gregor28019772010-04-05 23:52:57 +0000179 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
Ted Kremenek5cf48762009-10-17 00:34:24 +0000180 bool OnlyLocalDecls,
Douglas Gregor4db64a42010-01-23 00:14:00 +0000181 RemappedFile *RemappedFiles,
Douglas Gregora88084b2010-02-18 18:08:43 +0000182 unsigned NumRemappedFiles,
183 bool CaptureDiagnostics) {
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000184 llvm::OwningPtr<ASTUnit> AST(new ASTUnit(true));
185
Douglas Gregor28019772010-04-05 23:52:57 +0000186 if (!Diags.getPtr()) {
Douglas Gregor3687e9d2010-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 Gregor28019772010-04-05 23:52:57 +0000190 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000191 }
Douglas Gregorabc563f2010-07-19 21:46:24 +0000192
193 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000194 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor28019772010-04-05 23:52:57 +0000195 AST->Diagnostics = Diags;
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000196 AST->FileMgr.reset(new FileManager);
197 AST->SourceMgr.reset(new SourceManager(AST->getDiagnostics()));
Steve Naroff36c44642009-10-19 14:34:22 +0000198 AST->HeaderInfo.reset(new HeaderSearch(AST->getFileManager()));
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000199
Douglas Gregora88084b2010-02-18 18:08:43 +0000200 // If requested, capture diagnostics in the ASTUnit.
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000201 CaptureDroppedDiagnostics Capture(CaptureDiagnostics, AST->getDiagnostics(),
Douglas Gregor405634b2010-04-05 18:10:21 +0000202 AST->StoredDiagnostics);
Douglas Gregora88084b2010-02-18 18:08:43 +0000203
Douglas Gregor4db64a42010-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 Gregor3687e9d2010-04-05 21:10:19 +0000211 AST->getDiagnostics().Report(diag::err_fe_remap_missing_from_file)
Douglas Gregor4db64a42010-01-23 00:14:00 +0000212 << RemappedFiles[I].first;
Douglas Gregorc8dfe5e2010-02-27 01:32:48 +0000213 delete RemappedFiles[I].second;
Douglas Gregor4db64a42010-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 Kyrtzidis0853a022009-06-20 08:08:23 +0000223 // Gather Info for preprocessor construction later on.
Mike Stump1eb44332009-09-09 15:08:12 +0000224
Argyrios Kyrtzidis0853a022009-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 Dunbarbce6f622009-09-03 05:59:50 +0000231 llvm::OwningPtr<PCHReader> Reader;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000232 llvm::OwningPtr<ExternalASTSource> Source;
233
Ted Kremenekfc062212009-10-19 21:44:57 +0000234 Reader.reset(new PCHReader(AST->getSourceManager(), AST->getFileManager(),
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000235 AST->getDiagnostics()));
Daniel Dunbarcc318932009-09-03 05:59:35 +0000236 Reader->setListener(new PCHInfoCollector(LangInfo, HeaderInfo, TargetTriple,
237 Predefines, Counter));
238
239 switch (Reader->ReadPCH(Filename)) {
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000240 case PCHReader::Success:
241 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000242
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000243 case PCHReader::Failure:
Argyrios Kyrtzidis106c9982009-06-25 18:22:30 +0000244 case PCHReader::IgnorePCH:
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000245 AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000246 return NULL;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000247 }
Mike Stump1eb44332009-09-09 15:08:12 +0000248
Daniel Dunbar68d40e22009-12-02 08:44:16 +0000249 AST->OriginalSourceFile = Reader->getOriginalSourceFile();
250
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000251 // PCH loaded successfully. Now create the preprocessor.
Mike Stump1eb44332009-09-09 15:08:12 +0000252
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000253 // Get information about the target being compiled for.
Daniel Dunbard58c03f2009-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 Davis98b7c5c2010-06-11 01:06:47 +0000258 TargetOpts.CXXABI = "itanium";
Daniel Dunbard58c03f2009-11-15 06:48:46 +0000259 TargetOpts.CPU = "";
260 TargetOpts.Features.clear();
261 TargetOpts.Triple = TargetTriple;
Douglas Gregor3687e9d2010-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 Dunbar31b87d82009-09-21 03:03:39 +0000266 AST->getSourceManager(), HeaderInfo));
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000267 Preprocessor &PP = *AST->PP.get();
268
Daniel Dunbard5b61262009-09-21 03:03:47 +0000269 PP.setPredefines(Reader->getSuggestedPredefines());
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000270 PP.setCounterValue(Counter);
Daniel Dunbarcc318932009-09-03 05:59:35 +0000271 Reader->setPreprocessor(PP);
Mike Stump1eb44332009-09-09 15:08:12 +0000272
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000273 // Create and initialize the ASTContext.
274
275 AST->Ctx.reset(new ASTContext(LangInfo,
Daniel Dunbar31b87d82009-09-21 03:03:39 +0000276 AST->getSourceManager(),
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000277 *AST->Target.get(),
278 PP.getIdentifierTable(),
279 PP.getSelectorTable(),
280 PP.getBuiltinInfo(),
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000281 /* size_reserve = */0));
282 ASTContext &Context = *AST->Ctx.get();
Mike Stump1eb44332009-09-09 15:08:12 +0000283
Daniel Dunbarcc318932009-09-03 05:59:35 +0000284 Reader->InitializeContext(Context);
Mike Stump1eb44332009-09-09 15:08:12 +0000285
Argyrios Kyrtzidis0853a022009-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 Dunbarcc318932009-09-03 05:59:35 +0000289 Source.reset(Reader.take());
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000290 Context.setExternalSource(Source);
291
Mike Stump1eb44332009-09-09 15:08:12 +0000292 return AST.take();
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000293}
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000294
295namespace {
296
Daniel Dunbarf772d1e2009-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 Kremenekda5a4282010-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;
312 Unit.getTopLevelDecls().push_back(D);
313 }
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000314 }
315};
316
317class TopLevelDeclTrackerAction : public ASTFrontendAction {
318public:
319 ASTUnit &Unit;
320
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000321 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
322 llvm::StringRef InFile) {
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000323 return new TopLevelDeclTrackerConsumer(Unit);
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000324 }
325
326public:
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000327 TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {}
328
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000329 virtual bool hasCodeCompletionSupport() const { return false; }
330};
331
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000332class PrecompilePreambleConsumer : public PCHGenerator {
333 ASTUnit &Unit;
334
335public:
336 PrecompilePreambleConsumer(ASTUnit &Unit,
337 const Preprocessor &PP, bool Chaining,
338 const char *isysroot, llvm::raw_ostream *Out)
339 : PCHGenerator(PP, Chaining, isysroot, Out), Unit(Unit) { }
340
341 void HandleTopLevelDecl(DeclGroupRef D) {
342 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
343 Decl *D = *it;
344 // FIXME: Currently ObjC method declarations are incorrectly being
345 // reported as top-level declarations, even though their DeclContext
346 // is the containing ObjC @interface/@implementation. This is a
347 // fundamental problem in the parser right now.
348 if (isa<ObjCMethodDecl>(D))
349 continue;
350 Unit.getTopLevelDecls().push_back(D);
351 }
352 }
353};
354
355class PrecompilePreambleAction : public ASTFrontendAction {
356 ASTUnit &Unit;
357
358public:
359 explicit PrecompilePreambleAction(ASTUnit &Unit) : Unit(Unit) {}
360
361 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
362 llvm::StringRef InFile) {
363 std::string Sysroot;
364 llvm::raw_ostream *OS = 0;
365 bool Chaining;
366 if (GeneratePCHAction::ComputeASTConsumerArguments(CI, InFile, Sysroot,
367 OS, Chaining))
368 return 0;
369
370 const char *isysroot = CI.getFrontendOpts().RelocatablePCH ?
371 Sysroot.c_str() : 0;
372 return new PrecompilePreambleConsumer(Unit, CI.getPreprocessor(), Chaining,
373 isysroot, OS);
374 }
375
376 virtual bool hasCodeCompletionSupport() const { return false; }
377 virtual bool hasASTFileSupport() const { return false; }
378};
379
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000380}
381
Douglas Gregorabc563f2010-07-19 21:46:24 +0000382/// Parse the source file into a translation unit using the given compiler
383/// invocation, replacing the current translation unit.
384///
385/// \returns True if a failure occurred that causes the ASTUnit not to
386/// contain any translation-unit information, false otherwise.
Douglas Gregor754f3492010-07-24 00:38:13 +0000387bool ASTUnit::Parse(llvm::MemoryBuffer *OverrideMainBuffer) {
Douglas Gregor28233422010-07-27 14:52:07 +0000388 delete SavedMainFileBuffer;
389 SavedMainFileBuffer = 0;
390
Douglas Gregorabc563f2010-07-19 21:46:24 +0000391 if (!Invocation.get())
392 return true;
393
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000394 // Create the compiler instance to use for building the AST.
Daniel Dunbarcb6dda12009-12-02 08:43:56 +0000395 CompilerInstance Clang;
Douglas Gregorabc563f2010-07-19 21:46:24 +0000396 Clang.setInvocation(Invocation.take());
397 OriginalSourceFile = Clang.getFrontendOpts().Inputs[0].second;
398
399 // Set up diagnostics.
400 Clang.setDiagnostics(&getDiagnostics());
401 Clang.setDiagnosticClient(getDiagnostics().getClient());
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000402
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000403 // Create the target instance.
404 Clang.setTarget(TargetInfo::CreateTargetInfo(Clang.getDiagnostics(),
405 Clang.getTargetOpts()));
Douglas Gregora88084b2010-02-18 18:08:43 +0000406 if (!Clang.hasTarget()) {
Douglas Gregora88084b2010-02-18 18:08:43 +0000407 Clang.takeDiagnosticClient();
Douglas Gregorabc563f2010-07-19 21:46:24 +0000408 return true;
Douglas Gregora88084b2010-02-18 18:08:43 +0000409 }
Douglas Gregorabc563f2010-07-19 21:46:24 +0000410
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000411 // Inform the target of the language options.
412 //
413 // FIXME: We shouldn't need to do this, the target should be immutable once
414 // created. This complexity should be lifted elsewhere.
415 Clang.getTarget().setForcedLangOptions(Clang.getLangOpts());
Douglas Gregorabc563f2010-07-19 21:46:24 +0000416
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000417 assert(Clang.getFrontendOpts().Inputs.size() == 1 &&
418 "Invocation must have exactly one source file!");
Daniel Dunbarc34ce3f2010-06-07 23:22:09 +0000419 assert(Clang.getFrontendOpts().Inputs[0].first != IK_AST &&
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000420 "FIXME: AST inputs not yet supported here!");
Daniel Dunbarfaddc3e2010-06-07 23:26:47 +0000421 assert(Clang.getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
422 "IR inputs not support here!");
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000423
Douglas Gregorabc563f2010-07-19 21:46:24 +0000424 // Configure the various subsystems.
425 // FIXME: Should we retain the previous file manager?
426 FileMgr.reset(new FileManager);
427 SourceMgr.reset(new SourceManager(getDiagnostics()));
428 Ctx.reset();
429 PP.reset();
430
431 // Clear out old caches and data.
432 TopLevelDecls.clear();
Douglas Gregorabc563f2010-07-19 21:46:24 +0000433 CleanTemporaryFiles();
434 PreprocessedEntitiesByFile.clear();
Douglas Gregorc0659ec2010-08-02 20:51:39 +0000435
436 if (!OverrideMainBuffer)
437 StoredDiagnostics.clear();
Douglas Gregorabc563f2010-07-19 21:46:24 +0000438
Douglas Gregora88084b2010-02-18 18:08:43 +0000439 // Capture any diagnostics that would otherwise be dropped.
440 CaptureDroppedDiagnostics Capture(CaptureDiagnostics,
441 Clang.getDiagnostics(),
Douglas Gregorabc563f2010-07-19 21:46:24 +0000442 StoredDiagnostics);
443
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000444 // Create a file manager object to provide access to and cache the filesystem.
Douglas Gregorabc563f2010-07-19 21:46:24 +0000445 Clang.setFileManager(&getFileManager());
446
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000447 // Create the source manager.
Douglas Gregorabc563f2010-07-19 21:46:24 +0000448 Clang.setSourceManager(&getSourceManager());
449
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000450 // If the main file has been overridden due to the use of a preamble,
451 // make that override happen and introduce the preamble.
452 PreprocessorOptions &PreprocessorOpts = Clang.getPreprocessorOpts();
453 if (OverrideMainBuffer) {
454 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
455 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
456 PreprocessorOpts.PrecompiledPreambleBytes.second
457 = PreambleEndsAtStartOfLine;
Douglas Gregor385103b2010-07-30 20:58:08 +0000458 PreprocessorOpts.ImplicitPCHInclude = PreambleFile;
Douglas Gregorfae3b2f2010-07-27 00:27:13 +0000459 PreprocessorOpts.DisablePCHValidation = true;
Douglas Gregor28233422010-07-27 14:52:07 +0000460
461 // Keep track of the override buffer;
462 SavedMainFileBuffer = OverrideMainBuffer;
Douglas Gregorc0659ec2010-08-02 20:51:39 +0000463
464 // The stored diagnostic has the old source manager in it; update
465 // the locations to refer into the new source manager. Since we've
466 // been careful to make sure that the source manager's state
467 // before and after are identical, so that we can reuse the source
468 // location itself.
469 for (unsigned I = 0, N = StoredDiagnostics.size(); I != N; ++I) {
470 FullSourceLoc Loc(StoredDiagnostics[I].getLocation(),
471 getSourceManager());
472 StoredDiagnostics[I].setLocation(Loc);
473 }
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000474 }
475
Douglas Gregorabc563f2010-07-19 21:46:24 +0000476 llvm::OwningPtr<TopLevelDeclTrackerAction> Act;
477 Act.reset(new TopLevelDeclTrackerAction(*this));
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000478 if (!Act->BeginSourceFile(Clang, Clang.getFrontendOpts().Inputs[0].second,
Daniel Dunbard3598a62010-06-07 23:23:06 +0000479 Clang.getFrontendOpts().Inputs[0].first))
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000480 goto error;
Douglas Gregorabc563f2010-07-19 21:46:24 +0000481
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000482 Act->Execute();
Douglas Gregorabc563f2010-07-19 21:46:24 +0000483
Daniel Dunbar64a32ba2009-12-01 21:57:33 +0000484 // Steal the created target, context, and preprocessor, and take back the
485 // source and file managers.
Douglas Gregorabc563f2010-07-19 21:46:24 +0000486 Ctx.reset(Clang.takeASTContext());
487 PP.reset(Clang.takePreprocessor());
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000488 Clang.takeSourceManager();
489 Clang.takeFileManager();
Douglas Gregorabc563f2010-07-19 21:46:24 +0000490 Target.reset(Clang.takeTarget());
491
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000492 Act->EndSourceFile();
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000493
494 // Remove the overridden buffer we used for the preamble.
Douglas Gregorc0659ec2010-08-02 20:51:39 +0000495 if (OverrideMainBuffer)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000496 PreprocessorOpts.eraseRemappedFile(
497 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregorabc563f2010-07-19 21:46:24 +0000498
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000499 Clang.takeDiagnosticClient();
Douglas Gregorabc563f2010-07-19 21:46:24 +0000500
501 Invocation.reset(Clang.takeInvocation());
502 return false;
503
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000504error:
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000505 // Remove the overridden buffer we used for the preamble.
Douglas Gregorfae3b2f2010-07-27 00:27:13 +0000506 if (OverrideMainBuffer) {
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000507 PreprocessorOpts.eraseRemappedFile(
508 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregorfae3b2f2010-07-27 00:27:13 +0000509 PreprocessorOpts.DisablePCHValidation = true;
510 }
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000511
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000512 Clang.takeSourceManager();
513 Clang.takeFileManager();
514 Clang.takeDiagnosticClient();
Douglas Gregorabc563f2010-07-19 21:46:24 +0000515 Invocation.reset(Clang.takeInvocation());
516 return true;
517}
518
Douglas Gregor44c181a2010-07-23 00:33:23 +0000519/// \brief Simple function to retrieve a path for a preamble precompiled header.
520static std::string GetPreamblePCHPath() {
521 // FIXME: This is lame; sys::Path should provide this function (in particular,
522 // it should know how to find the temporary files dir).
523 // FIXME: This is really lame. I copied this code from the Driver!
524 std::string Error;
525 const char *TmpDir = ::getenv("TMPDIR");
526 if (!TmpDir)
527 TmpDir = ::getenv("TEMP");
528 if (!TmpDir)
529 TmpDir = ::getenv("TMP");
530 if (!TmpDir)
531 TmpDir = "/tmp";
532 llvm::sys::Path P(TmpDir);
533 P.appendComponent("preamble");
534 if (P.createTemporaryFileOnDisk())
535 return std::string();
536
537 P.appendSuffix("pch");
538 return P.str();
539}
540
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000541/// \brief Compute the preamble for the main file, providing the source buffer
542/// that corresponds to the main file along with a pair (bytes, start-of-line)
543/// that describes the preamble.
544std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> >
Douglas Gregor175c4a92010-07-23 23:58:40 +0000545ASTUnit::ComputePreamble(CompilerInvocation &Invocation, bool &CreatedBuffer) {
546 FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
Douglas Gregor44c181a2010-07-23 00:33:23 +0000547 PreprocessorOptions &PreprocessorOpts
Douglas Gregor175c4a92010-07-23 23:58:40 +0000548 = Invocation.getPreprocessorOpts();
549 CreatedBuffer = false;
550
Douglas Gregor44c181a2010-07-23 00:33:23 +0000551 // Try to determine if the main file has been remapped, either from the
552 // command line (to another file) or directly through the compiler invocation
553 // (to a memory buffer).
Douglas Gregor175c4a92010-07-23 23:58:40 +0000554 llvm::MemoryBuffer *Buffer = 0;
Douglas Gregor44c181a2010-07-23 00:33:23 +0000555 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].second);
556 if (const llvm::sys::FileStatus *MainFileStatus = MainFilePath.getFileStatus()) {
557 // Check whether there is a file-file remapping of the main file
558 for (PreprocessorOptions::remapped_file_iterator
Douglas Gregor175c4a92010-07-23 23:58:40 +0000559 M = PreprocessorOpts.remapped_file_begin(),
560 E = PreprocessorOpts.remapped_file_end();
Douglas Gregor44c181a2010-07-23 00:33:23 +0000561 M != E;
562 ++M) {
563 llvm::sys::PathWithStatus MPath(M->first);
564 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
565 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
566 // We found a remapping. Try to load the resulting, remapped source.
Douglas Gregor175c4a92010-07-23 23:58:40 +0000567 if (CreatedBuffer) {
Douglas Gregor44c181a2010-07-23 00:33:23 +0000568 delete Buffer;
Douglas Gregor175c4a92010-07-23 23:58:40 +0000569 CreatedBuffer = false;
570 }
571
Douglas Gregor44c181a2010-07-23 00:33:23 +0000572 Buffer = llvm::MemoryBuffer::getFile(M->second);
573 if (!Buffer)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000574 return std::make_pair((llvm::MemoryBuffer*)0,
575 std::make_pair(0, true));
Douglas Gregor175c4a92010-07-23 23:58:40 +0000576 CreatedBuffer = true;
Douglas Gregor44c181a2010-07-23 00:33:23 +0000577
Douglas Gregor175c4a92010-07-23 23:58:40 +0000578 // Remove this remapping. We've captured the buffer already.
Douglas Gregor44c181a2010-07-23 00:33:23 +0000579 M = PreprocessorOpts.eraseRemappedFile(M);
580 E = PreprocessorOpts.remapped_file_end();
581 }
582 }
583 }
584
585 // Check whether there is a file-buffer remapping. It supercedes the
586 // file-file remapping.
587 for (PreprocessorOptions::remapped_file_buffer_iterator
588 M = PreprocessorOpts.remapped_file_buffer_begin(),
589 E = PreprocessorOpts.remapped_file_buffer_end();
590 M != E;
591 ++M) {
592 llvm::sys::PathWithStatus MPath(M->first);
593 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
594 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
595 // We found a remapping.
Douglas Gregor175c4a92010-07-23 23:58:40 +0000596 if (CreatedBuffer) {
Douglas Gregor44c181a2010-07-23 00:33:23 +0000597 delete Buffer;
Douglas Gregor175c4a92010-07-23 23:58:40 +0000598 CreatedBuffer = false;
599 }
Douglas Gregor44c181a2010-07-23 00:33:23 +0000600
Douglas Gregor175c4a92010-07-23 23:58:40 +0000601 Buffer = const_cast<llvm::MemoryBuffer *>(M->second);
602
603 // Remove this remapping. We've captured the buffer already.
Douglas Gregor44c181a2010-07-23 00:33:23 +0000604 M = PreprocessorOpts.eraseRemappedFile(M);
605 E = PreprocessorOpts.remapped_file_buffer_end();
606 }
607 }
Douglas Gregor175c4a92010-07-23 23:58:40 +0000608 }
Douglas Gregor44c181a2010-07-23 00:33:23 +0000609 }
610
611 // If the main source file was not remapped, load it now.
612 if (!Buffer) {
613 Buffer = llvm::MemoryBuffer::getFile(FrontendOpts.Inputs[0].second);
614 if (!Buffer)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000615 return std::make_pair((llvm::MemoryBuffer*)0, std::make_pair(0, true));
Douglas Gregor175c4a92010-07-23 23:58:40 +0000616
617 CreatedBuffer = true;
Douglas Gregor44c181a2010-07-23 00:33:23 +0000618 }
619
Douglas Gregor175c4a92010-07-23 23:58:40 +0000620 return std::make_pair(Buffer, Lexer::ComputePreamble(Buffer));
621}
622
Douglas Gregor754f3492010-07-24 00:38:13 +0000623static llvm::MemoryBuffer *CreatePaddedMainFileBuffer(llvm::MemoryBuffer *Old,
624 bool DeleteOld,
625 unsigned NewSize,
626 llvm::StringRef NewName) {
627 llvm::MemoryBuffer *Result
628 = llvm::MemoryBuffer::getNewUninitMemBuffer(NewSize, NewName);
629 memcpy(const_cast<char*>(Result->getBufferStart()),
630 Old->getBufferStart(), Old->getBufferSize());
631 memset(const_cast<char*>(Result->getBufferStart()) + Old->getBufferSize(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000632 ' ', NewSize - Old->getBufferSize() - 1);
633 const_cast<char*>(Result->getBufferEnd())[-1] = '\n';
Douglas Gregor754f3492010-07-24 00:38:13 +0000634
635 if (DeleteOld)
636 delete Old;
637
638 return Result;
639}
640
Douglas Gregor175c4a92010-07-23 23:58:40 +0000641/// \brief Attempt to build or re-use a precompiled preamble when (re-)parsing
642/// the source file.
643///
644/// This routine will compute the preamble of the main source file. If a
645/// non-trivial preamble is found, it will precompile that preamble into a
646/// precompiled header so that the precompiled preamble can be used to reduce
647/// reparsing time. If a precompiled preamble has already been constructed,
648/// this routine will determine if it is still valid and, if so, avoid
649/// rebuilding the precompiled preamble.
650///
Douglas Gregor754f3492010-07-24 00:38:13 +0000651/// \returns If the precompiled preamble can be used, returns a newly-allocated
652/// buffer that should be used in place of the main file when doing so.
653/// Otherwise, returns a NULL pointer.
654llvm::MemoryBuffer *ASTUnit::BuildPrecompiledPreamble() {
Douglas Gregor175c4a92010-07-23 23:58:40 +0000655 CompilerInvocation PreambleInvocation(*Invocation);
656 FrontendOptions &FrontendOpts = PreambleInvocation.getFrontendOpts();
657 PreprocessorOptions &PreprocessorOpts
658 = PreambleInvocation.getPreprocessorOpts();
659
660 bool CreatedPreambleBuffer = false;
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000661 std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> > NewPreamble
Douglas Gregor175c4a92010-07-23 23:58:40 +0000662 = ComputePreamble(PreambleInvocation, CreatedPreambleBuffer);
663
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000664 if (!NewPreamble.second.first) {
Douglas Gregor175c4a92010-07-23 23:58:40 +0000665 // We couldn't find a preamble in the main source. Clear out the current
666 // preamble, if we have one. It's obviously no good any more.
667 Preamble.clear();
668 if (!PreambleFile.empty()) {
Douglas Gregor385103b2010-07-30 20:58:08 +0000669 llvm::sys::Path(PreambleFile).eraseFromDisk();
Douglas Gregor175c4a92010-07-23 23:58:40 +0000670 PreambleFile.clear();
671 }
672 if (CreatedPreambleBuffer)
673 delete NewPreamble.first;
674
Douglas Gregor754f3492010-07-24 00:38:13 +0000675 return 0;
Douglas Gregor175c4a92010-07-23 23:58:40 +0000676 }
677
678 if (!Preamble.empty()) {
679 // We've previously computed a preamble. Check whether we have the same
680 // preamble now that we did before, and that there's enough space in
681 // the main-file buffer within the precompiled preamble to fit the
682 // new main file.
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000683 if (Preamble.size() == NewPreamble.second.first &&
684 PreambleEndsAtStartOfLine == NewPreamble.second.second &&
Douglas Gregor592508e2010-07-24 00:42:07 +0000685 NewPreamble.first->getBufferSize() < PreambleReservedSize-2 &&
Douglas Gregor175c4a92010-07-23 23:58:40 +0000686 memcmp(&Preamble[0], NewPreamble.first->getBufferStart(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000687 NewPreamble.second.first) == 0) {
Douglas Gregor175c4a92010-07-23 23:58:40 +0000688 // The preamble has not changed. We may be able to re-use the precompiled
689 // preamble.
Douglas Gregorc0659ec2010-08-02 20:51:39 +0000690
Douglas Gregorcc5888d2010-07-31 00:40:00 +0000691 // Check that none of the files used by the preamble have changed.
692 bool AnyFileChanged = false;
693
694 // First, make a record of those files that have been overridden via
695 // remapping or unsaved_files.
696 llvm::StringMap<std::pair<off_t, time_t> > OverriddenFiles;
697 for (PreprocessorOptions::remapped_file_iterator
698 R = PreprocessorOpts.remapped_file_begin(),
699 REnd = PreprocessorOpts.remapped_file_end();
700 !AnyFileChanged && R != REnd;
701 ++R) {
702 struct stat StatBuf;
703 if (stat(R->second.c_str(), &StatBuf)) {
704 // If we can't stat the file we're remapping to, assume that something
705 // horrible happened.
706 AnyFileChanged = true;
707 break;
708 }
Douglas Gregor754f3492010-07-24 00:38:13 +0000709
Douglas Gregorcc5888d2010-07-31 00:40:00 +0000710 OverriddenFiles[R->first] = std::make_pair(StatBuf.st_size,
711 StatBuf.st_mtime);
712 }
713 for (PreprocessorOptions::remapped_file_buffer_iterator
714 R = PreprocessorOpts.remapped_file_buffer_begin(),
715 REnd = PreprocessorOpts.remapped_file_buffer_end();
716 !AnyFileChanged && R != REnd;
717 ++R) {
718 // FIXME: Should we actually compare the contents of file->buffer
719 // remappings?
720 OverriddenFiles[R->first] = std::make_pair(R->second->getBufferSize(),
721 0);
722 }
723
724 // Check whether anything has changed.
725 for (llvm::StringMap<std::pair<off_t, time_t> >::iterator
726 F = FilesInPreamble.begin(), FEnd = FilesInPreamble.end();
727 !AnyFileChanged && F != FEnd;
728 ++F) {
729 llvm::StringMap<std::pair<off_t, time_t> >::iterator Overridden
730 = OverriddenFiles.find(F->first());
731 if (Overridden != OverriddenFiles.end()) {
732 // This file was remapped; check whether the newly-mapped file
733 // matches up with the previous mapping.
734 if (Overridden->second != F->second)
735 AnyFileChanged = true;
736 continue;
737 }
738
739 // The file was not remapped; check whether it has changed on disk.
740 struct stat StatBuf;
741 if (stat(F->first(), &StatBuf)) {
742 // If we can't stat the file, assume that something horrible happened.
743 AnyFileChanged = true;
744 } else if (StatBuf.st_size != F->second.first ||
745 StatBuf.st_mtime != F->second.second)
746 AnyFileChanged = true;
747 }
748
749 if (!AnyFileChanged) {
Douglas Gregorc0659ec2010-08-02 20:51:39 +0000750 // Okay! We can re-use the precompiled preamble.
751
752 // Set the state of the diagnostic object to mimic its state
753 // after parsing the preamble.
754 getDiagnostics().Reset();
755 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
756 if (StoredDiagnostics.size() > NumStoredDiagnosticsInPreamble)
757 StoredDiagnostics.erase(
758 StoredDiagnostics.begin() + NumStoredDiagnosticsInPreamble,
759 StoredDiagnostics.end());
760
761 // Create a version of the main file buffer that is padded to
762 // buffer size we reserved when creating the preamble.
Douglas Gregorcc5888d2010-07-31 00:40:00 +0000763 return CreatePaddedMainFileBuffer(NewPreamble.first,
764 CreatedPreambleBuffer,
765 PreambleReservedSize,
766 FrontendOpts.Inputs[0].second);
767 }
Douglas Gregor175c4a92010-07-23 23:58:40 +0000768 }
769
770 // We can't reuse the previously-computed preamble. Build a new one.
771 Preamble.clear();
Douglas Gregor385103b2010-07-30 20:58:08 +0000772 llvm::sys::Path(PreambleFile).eraseFromDisk();
Douglas Gregor175c4a92010-07-23 23:58:40 +0000773 }
774
775 // We did not previously compute a preamble, or it can't be reused anyway.
Douglas Gregor385103b2010-07-30 20:58:08 +0000776 llvm::Timer *PreambleTimer = 0;
777 if (TimerGroup.get()) {
778 PreambleTimer = new llvm::Timer("Precompiling preamble", *TimerGroup);
779 PreambleTimer->startTimer();
780 Timers.push_back(PreambleTimer);
781 }
Douglas Gregor44c181a2010-07-23 00:33:23 +0000782
783 // Create a new buffer that stores the preamble. The buffer also contains
784 // extra space for the original contents of the file (which will be present
785 // when we actually parse the file) along with more room in case the file
Douglas Gregor175c4a92010-07-23 23:58:40 +0000786 // grows.
787 PreambleReservedSize = NewPreamble.first->getBufferSize();
788 if (PreambleReservedSize < 4096)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000789 PreambleReservedSize = 8191;
Douglas Gregor44c181a2010-07-23 00:33:23 +0000790 else
Douglas Gregor175c4a92010-07-23 23:58:40 +0000791 PreambleReservedSize *= 2;
792
Douglas Gregorc0659ec2010-08-02 20:51:39 +0000793 // Save the preamble text for later; we'll need to compare against it for
794 // subsequent reparses.
795 Preamble.assign(NewPreamble.first->getBufferStart(),
796 NewPreamble.first->getBufferStart()
797 + NewPreamble.second.first);
798 PreambleEndsAtStartOfLine = NewPreamble.second.second;
799
Douglas Gregor44c181a2010-07-23 00:33:23 +0000800 llvm::MemoryBuffer *PreambleBuffer
Douglas Gregor175c4a92010-07-23 23:58:40 +0000801 = llvm::MemoryBuffer::getNewUninitMemBuffer(PreambleReservedSize,
Douglas Gregor44c181a2010-07-23 00:33:23 +0000802 FrontendOpts.Inputs[0].second);
803 memcpy(const_cast<char*>(PreambleBuffer->getBufferStart()),
Douglas Gregor175c4a92010-07-23 23:58:40 +0000804 NewPreamble.first->getBufferStart(), Preamble.size());
805 memset(const_cast<char*>(PreambleBuffer->getBufferStart()) + Preamble.size(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000806 ' ', PreambleReservedSize - Preamble.size() - 1);
807 const_cast<char*>(PreambleBuffer->getBufferEnd())[-1] = '\n';
Douglas Gregor44c181a2010-07-23 00:33:23 +0000808
809 // Remap the main source file to the preamble buffer.
Douglas Gregor175c4a92010-07-23 23:58:40 +0000810 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].second);
Douglas Gregor44c181a2010-07-23 00:33:23 +0000811 PreprocessorOpts.addRemappedFile(MainFilePath.str(), PreambleBuffer);
812
813 // Tell the compiler invocation to generate a temporary precompiled header.
814 FrontendOpts.ProgramAction = frontend::GeneratePCH;
815 // FIXME: Set ChainedPCH, once it is ready.
816 // FIXME: Generate the precompiled header into memory?
Douglas Gregor385103b2010-07-30 20:58:08 +0000817 FrontendOpts.OutputFile = GetPreamblePCHPath();
Douglas Gregor44c181a2010-07-23 00:33:23 +0000818
819 // Create the compiler instance to use for building the precompiled preamble.
820 CompilerInstance Clang;
821 Clang.setInvocation(&PreambleInvocation);
822 OriginalSourceFile = Clang.getFrontendOpts().Inputs[0].second;
823
824 // Set up diagnostics.
825 Clang.setDiagnostics(&getDiagnostics());
826 Clang.setDiagnosticClient(getDiagnostics().getClient());
827
828 // Create the target instance.
829 Clang.setTarget(TargetInfo::CreateTargetInfo(Clang.getDiagnostics(),
830 Clang.getTargetOpts()));
831 if (!Clang.hasTarget()) {
832 Clang.takeDiagnosticClient();
Douglas Gregor175c4a92010-07-23 23:58:40 +0000833 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
834 Preamble.clear();
835 if (CreatedPreambleBuffer)
836 delete NewPreamble.first;
Douglas Gregor385103b2010-07-30 20:58:08 +0000837 if (PreambleTimer)
838 PreambleTimer->stopTimer();
Douglas Gregor175c4a92010-07-23 23:58:40 +0000839
Douglas Gregor754f3492010-07-24 00:38:13 +0000840 return 0;
Douglas Gregor44c181a2010-07-23 00:33:23 +0000841 }
842
843 // Inform the target of the language options.
844 //
845 // FIXME: We shouldn't need to do this, the target should be immutable once
846 // created. This complexity should be lifted elsewhere.
847 Clang.getTarget().setForcedLangOptions(Clang.getLangOpts());
848
849 assert(Clang.getFrontendOpts().Inputs.size() == 1 &&
850 "Invocation must have exactly one source file!");
851 assert(Clang.getFrontendOpts().Inputs[0].first != IK_AST &&
852 "FIXME: AST inputs not yet supported here!");
853 assert(Clang.getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
854 "IR inputs not support here!");
855
856 // Clear out old caches and data.
857 StoredDiagnostics.clear();
858
859 // Capture any diagnostics that would otherwise be dropped.
860 CaptureDroppedDiagnostics Capture(CaptureDiagnostics,
Douglas Gregorc0659ec2010-08-02 20:51:39 +0000861 getDiagnostics(),
Douglas Gregor44c181a2010-07-23 00:33:23 +0000862 StoredDiagnostics);
863
864 // Create a file manager object to provide access to and cache the filesystem.
865 Clang.setFileManager(new FileManager);
866
867 // Create the source manager.
868 Clang.setSourceManager(new SourceManager(getDiagnostics()));
869
870 // FIXME: Eventually, we'll have to track top-level declarations here, too.
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000871 llvm::OwningPtr<PrecompilePreambleAction> Act;
872 Act.reset(new PrecompilePreambleAction(*this));
Douglas Gregor44c181a2010-07-23 00:33:23 +0000873 if (!Act->BeginSourceFile(Clang, Clang.getFrontendOpts().Inputs[0].second,
874 Clang.getFrontendOpts().Inputs[0].first)) {
875 Clang.takeDiagnosticClient();
876 Clang.takeInvocation();
Douglas Gregor175c4a92010-07-23 23:58:40 +0000877 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
878 Preamble.clear();
879 if (CreatedPreambleBuffer)
880 delete NewPreamble.first;
Douglas Gregor385103b2010-07-30 20:58:08 +0000881 if (PreambleTimer)
882 PreambleTimer->stopTimer();
883
Douglas Gregor754f3492010-07-24 00:38:13 +0000884 return 0;
Douglas Gregor44c181a2010-07-23 00:33:23 +0000885 }
886
887 Act->Execute();
888 Act->EndSourceFile();
889 Clang.takeDiagnosticClient();
890 Clang.takeInvocation();
891
Douglas Gregor175c4a92010-07-23 23:58:40 +0000892 if (Diagnostics->getNumErrors() > 0) {
893 // There were errors parsing the preamble, so no precompiled header was
894 // generated. Forget that we even tried.
895 // FIXME: Should we leave a note for ourselves to try again?
896 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
897 Preamble.clear();
898 if (CreatedPreambleBuffer)
899 delete NewPreamble.first;
Douglas Gregor385103b2010-07-30 20:58:08 +0000900 if (PreambleTimer)
901 PreambleTimer->stopTimer();
Douglas Gregor385103b2010-07-30 20:58:08 +0000902
Douglas Gregor754f3492010-07-24 00:38:13 +0000903 return 0;
Douglas Gregor175c4a92010-07-23 23:58:40 +0000904 }
905
906 // Keep track of the preamble we precompiled.
907 PreambleFile = FrontendOpts.OutputFile;
Douglas Gregorc0659ec2010-08-02 20:51:39 +0000908 NumStoredDiagnosticsInPreamble = StoredDiagnostics.size();
909 NumWarningsInPreamble = getDiagnostics().getNumWarnings();
Douglas Gregorcc5888d2010-07-31 00:40:00 +0000910
911 // Keep track of all of the files that the source manager knows about,
912 // so we can verify whether they have changed or not.
913 FilesInPreamble.clear();
914 SourceManager &SourceMgr = Clang.getSourceManager();
915 const llvm::MemoryBuffer *MainFileBuffer
916 = SourceMgr.getBuffer(SourceMgr.getMainFileID());
917 for (SourceManager::fileinfo_iterator F = SourceMgr.fileinfo_begin(),
918 FEnd = SourceMgr.fileinfo_end();
919 F != FEnd;
920 ++F) {
921 const FileEntry *File = F->second->Entry;
922 if (!File || F->second->getRawBuffer() == MainFileBuffer)
923 continue;
924
925 FilesInPreamble[File->getName()]
926 = std::make_pair(F->second->getSize(), File->getModificationTime());
927 }
928
Douglas Gregor385103b2010-07-30 20:58:08 +0000929 if (PreambleTimer)
930 PreambleTimer->stopTimer();
931
Douglas Gregor754f3492010-07-24 00:38:13 +0000932 return CreatePaddedMainFileBuffer(NewPreamble.first,
933 CreatedPreambleBuffer,
934 PreambleReservedSize,
935 FrontendOpts.Inputs[0].second);
Douglas Gregor44c181a2010-07-23 00:33:23 +0000936}
Douglas Gregorabc563f2010-07-19 21:46:24 +0000937
938ASTUnit *ASTUnit::LoadFromCompilerInvocation(CompilerInvocation *CI,
939 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
940 bool OnlyLocalDecls,
Douglas Gregor44c181a2010-07-23 00:33:23 +0000941 bool CaptureDiagnostics,
942 bool PrecompilePreamble) {
Douglas Gregorabc563f2010-07-19 21:46:24 +0000943 if (!Diags.getPtr()) {
944 // No diagnostics engine was provided, so create our own diagnostics object
945 // with the default options.
946 DiagnosticOptions DiagOpts;
947 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
948 }
949
950 // Create the AST unit.
951 llvm::OwningPtr<ASTUnit> AST;
952 AST.reset(new ASTUnit(false));
953 AST->Diagnostics = Diags;
954 AST->CaptureDiagnostics = CaptureDiagnostics;
955 AST->OnlyLocalDecls = OnlyLocalDecls;
956 AST->Invocation.reset(CI);
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000957 CI->getPreprocessorOpts().RetainRemappedFileBuffers = true;
Douglas Gregorabc563f2010-07-19 21:46:24 +0000958
Douglas Gregor385103b2010-07-30 20:58:08 +0000959 if (getenv("LIBCLANG_TIMING"))
960 AST->TimerGroup.reset(
961 new llvm::TimerGroup(CI->getFrontendOpts().Inputs[0].second));
962
963
Douglas Gregor754f3492010-07-24 00:38:13 +0000964 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Douglas Gregorfd0b8702010-07-28 22:12:37 +0000965 // FIXME: When C++ PCH is ready, allow use of it for a precompiled preamble.
966 if (PrecompilePreamble && !CI->getLangOpts().CPlusPlus)
Douglas Gregor754f3492010-07-24 00:38:13 +0000967 OverrideMainBuffer = AST->BuildPrecompiledPreamble();
Douglas Gregor44c181a2010-07-23 00:33:23 +0000968
Douglas Gregor385103b2010-07-30 20:58:08 +0000969 llvm::Timer *ParsingTimer = 0;
970 if (AST->TimerGroup.get()) {
971 ParsingTimer = new llvm::Timer("Initial parse", *AST->TimerGroup);
972 ParsingTimer->startTimer();
973 AST->Timers.push_back(ParsingTimer);
974 }
Douglas Gregorabc563f2010-07-19 21:46:24 +0000975
Douglas Gregor385103b2010-07-30 20:58:08 +0000976 bool Failed = AST->Parse(OverrideMainBuffer);
977 if (ParsingTimer)
978 ParsingTimer->stopTimer();
979
980 return Failed? 0 : AST.take();
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000981}
Daniel Dunbar7b556682009-12-02 03:23:45 +0000982
983ASTUnit *ASTUnit::LoadFromCommandLine(const char **ArgBegin,
984 const char **ArgEnd,
Douglas Gregor28019772010-04-05 23:52:57 +0000985 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
Daniel Dunbar869824e2009-12-13 03:46:13 +0000986 llvm::StringRef ResourceFilesPath,
Daniel Dunbar7b556682009-12-02 03:23:45 +0000987 bool OnlyLocalDecls,
Douglas Gregor4db64a42010-01-23 00:14:00 +0000988 RemappedFile *RemappedFiles,
Douglas Gregora88084b2010-02-18 18:08:43 +0000989 unsigned NumRemappedFiles,
Douglas Gregor44c181a2010-07-23 00:33:23 +0000990 bool CaptureDiagnostics,
991 bool PrecompilePreamble) {
Douglas Gregor28019772010-04-05 23:52:57 +0000992 if (!Diags.getPtr()) {
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000993 // No diagnostics engine was provided, so create our own diagnostics object
994 // with the default options.
995 DiagnosticOptions DiagOpts;
Douglas Gregor28019772010-04-05 23:52:57 +0000996 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000997 }
998
Daniel Dunbar7b556682009-12-02 03:23:45 +0000999 llvm::SmallVector<const char *, 16> Args;
1000 Args.push_back("<clang>"); // FIXME: Remove dummy argument.
1001 Args.insert(Args.end(), ArgBegin, ArgEnd);
1002
1003 // FIXME: Find a cleaner way to force the driver into restricted modes. We
1004 // also want to force it to use clang.
1005 Args.push_back("-fsyntax-only");
1006
Daniel Dunbar869824e2009-12-13 03:46:13 +00001007 // FIXME: We shouldn't have to pass in the path info.
Daniel Dunbar0bbad512010-07-19 00:44:04 +00001008 driver::Driver TheDriver("clang", llvm::sys::getHostTriple(),
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001009 "a.out", false, false, *Diags);
Daniel Dunbar3bd54cc2010-01-25 00:44:02 +00001010
1011 // Don't check that inputs exist, they have been remapped.
1012 TheDriver.setCheckInputsExist(false);
1013
Daniel Dunbar7b556682009-12-02 03:23:45 +00001014 llvm::OwningPtr<driver::Compilation> C(
1015 TheDriver.BuildCompilation(Args.size(), Args.data()));
1016
1017 // We expect to get back exactly one command job, if we didn't something
1018 // failed.
1019 const driver::JobList &Jobs = C->getJobs();
1020 if (Jobs.size() != 1 || !isa<driver::Command>(Jobs.begin())) {
1021 llvm::SmallString<256> Msg;
1022 llvm::raw_svector_ostream OS(Msg);
1023 C->PrintJob(OS, C->getJobs(), "; ", true);
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001024 Diags->Report(diag::err_fe_expected_compiler_job) << OS.str();
Daniel Dunbar7b556682009-12-02 03:23:45 +00001025 return 0;
1026 }
1027
1028 const driver::Command *Cmd = cast<driver::Command>(*Jobs.begin());
1029 if (llvm::StringRef(Cmd->getCreator().getName()) != "clang") {
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001030 Diags->Report(diag::err_fe_expected_clang_command);
Daniel Dunbar7b556682009-12-02 03:23:45 +00001031 return 0;
1032 }
1033
1034 const driver::ArgStringList &CCArgs = Cmd->getArguments();
Daniel Dunbar807b0612010-01-30 21:47:16 +00001035 llvm::OwningPtr<CompilerInvocation> CI(new CompilerInvocation);
Dan Gohmancb421fa2010-04-19 16:39:44 +00001036 CompilerInvocation::CreateFromArgs(*CI,
1037 const_cast<const char **>(CCArgs.data()),
1038 const_cast<const char **>(CCArgs.data()) +
Douglas Gregor44c181a2010-07-23 00:33:23 +00001039 CCArgs.size(),
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001040 *Diags);
Daniel Dunbar1e69fe32009-12-13 03:45:58 +00001041
Douglas Gregor4db64a42010-01-23 00:14:00 +00001042 // Override any files that need remapping
1043 for (unsigned I = 0; I != NumRemappedFiles; ++I)
Daniel Dunbar807b0612010-01-30 21:47:16 +00001044 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
Daniel Dunbarb26d4832010-02-16 01:55:04 +00001045 RemappedFiles[I].second);
Douglas Gregor4db64a42010-01-23 00:14:00 +00001046
Daniel Dunbar8b9adfe2009-12-15 00:06:45 +00001047 // Override the resources path.
Daniel Dunbar807b0612010-01-30 21:47:16 +00001048 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
Daniel Dunbar7b556682009-12-02 03:23:45 +00001049
Daniel Dunbarb26d4832010-02-16 01:55:04 +00001050 CI->getFrontendOpts().DisableFree = true;
Douglas Gregora88084b2010-02-18 18:08:43 +00001051 return LoadFromCompilerInvocation(CI.take(), Diags, OnlyLocalDecls,
Douglas Gregor44c181a2010-07-23 00:33:23 +00001052 CaptureDiagnostics, PrecompilePreamble);
Daniel Dunbar7b556682009-12-02 03:23:45 +00001053}
Douglas Gregorabc563f2010-07-19 21:46:24 +00001054
1055bool ASTUnit::Reparse(RemappedFile *RemappedFiles, unsigned NumRemappedFiles) {
1056 if (!Invocation.get())
1057 return true;
1058
Douglas Gregor385103b2010-07-30 20:58:08 +00001059 llvm::Timer *ReparsingTimer = 0;
1060 if (TimerGroup.get()) {
1061 ReparsingTimer = new llvm::Timer("Reparse", *TimerGroup);
1062 ReparsingTimer->startTimer();
1063 Timers.push_back(ReparsingTimer);
1064 }
1065
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001066 // Remap files.
1067 // FIXME: Do we want to remove old mappings for these files?
1068 Invocation->getPreprocessorOpts().clearRemappedFiles();
1069 for (unsigned I = 0; I != NumRemappedFiles; ++I)
1070 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
1071 RemappedFiles[I].second);
1072
Douglas Gregor175c4a92010-07-23 23:58:40 +00001073 // If we have a preamble file lying around, build or reuse the precompiled
1074 // preamble.
Douglas Gregor754f3492010-07-24 00:38:13 +00001075 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001076 if (!PreambleFile.empty())
Douglas Gregor754f3492010-07-24 00:38:13 +00001077 OverrideMainBuffer = BuildPrecompiledPreamble();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001078
Douglas Gregorabc563f2010-07-19 21:46:24 +00001079 // Clear out the diagnostics state.
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001080 if (!OverrideMainBuffer)
1081 getDiagnostics().Reset();
Douglas Gregorabc563f2010-07-19 21:46:24 +00001082
Douglas Gregor175c4a92010-07-23 23:58:40 +00001083 // Parse the sources
Douglas Gregor754f3492010-07-24 00:38:13 +00001084 bool Result = Parse(OverrideMainBuffer);
Douglas Gregor385103b2010-07-30 20:58:08 +00001085 if (ReparsingTimer)
1086 ReparsingTimer->stopTimer();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001087 return Result;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001088}