blob: b287522806ed1ee8e7f0160124b4e3b576447702 [file] [log] [blame]
Argyrios Kyrtzidis4b562cf2009-06-20 08:27:14 +00001//===--- ASTUnit.cpp - ASTUnit utility ------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// ASTUnit Implementation.
11//
12//===----------------------------------------------------------------------===//
13
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000014#include "clang/Frontend/ASTUnit.h"
Douglas Gregor1d715ac2010-08-03 08:14:03 +000015#include "clang/Frontend/PCHWriter.h"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000016#include "clang/AST/ASTContext.h"
Daniel Dunbar521bf9c2009-12-01 09:51:01 +000017#include "clang/AST/ASTConsumer.h"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000018#include "clang/AST/DeclVisitor.h"
19#include "clang/AST/StmtVisitor.h"
Daniel Dunbar7b556682009-12-02 03:23:45 +000020#include "clang/Driver/Compilation.h"
21#include "clang/Driver/Driver.h"
22#include "clang/Driver/Job.h"
23#include "clang/Driver/Tool.h"
Daniel Dunbar521bf9c2009-12-01 09:51:01 +000024#include "clang/Frontend/CompilerInstance.h"
25#include "clang/Frontend/FrontendActions.h"
Daniel Dunbar7b556682009-12-02 03:23:45 +000026#include "clang/Frontend/FrontendDiagnostic.h"
Daniel Dunbar521bf9c2009-12-01 09:51:01 +000027#include "clang/Frontend/FrontendOptions.h"
Douglas Gregor1d715ac2010-08-03 08:14:03 +000028#include "clang/Frontend/PCHReader.h"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000029#include "clang/Lex/HeaderSearch.h"
30#include "clang/Lex/Preprocessor.h"
Daniel Dunbard58c03f2009-11-15 06:48:46 +000031#include "clang/Basic/TargetOptions.h"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000032#include "clang/Basic/TargetInfo.h"
33#include "clang/Basic/Diagnostic.h"
Douglas Gregor4db64a42010-01-23 00:14:00 +000034#include "llvm/Support/MemoryBuffer.h"
Daniel Dunbar7b556682009-12-02 03:23:45 +000035#include "llvm/System/Host.h"
Benjamin Kramer4a630d32009-10-18 11:34:14 +000036#include "llvm/System/Path.h"
Douglas Gregordf95a132010-08-09 20:45:32 +000037#include "llvm/Support/raw_ostream.h"
Douglas Gregor385103b2010-07-30 20:58:08 +000038#include "llvm/Support/Timer.h"
Douglas Gregor44c181a2010-07-23 00:33:23 +000039#include <cstdlib>
Zhongxing Xuad23ebe2010-07-23 02:15:08 +000040#include <cstdio>
Douglas Gregorcc5888d2010-07-31 00:40:00 +000041#include <sys/stat.h>
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000042using namespace clang;
43
Douglas Gregoreababfb2010-08-04 05:53:38 +000044/// \brief After failing to build a precompiled preamble (due to
45/// errors in the source that occurs in the preamble), the number of
46/// reparses during which we'll skip even trying to precompile the
47/// preamble.
48const unsigned DefaultPreambleRebuildInterval = 5;
49
Douglas Gregor3687e9d2010-04-05 21:10:19 +000050ASTUnit::ASTUnit(bool _MainFileIsAST)
Douglas Gregorabc563f2010-07-19 21:46:24 +000051 : CaptureDiagnostics(false), MainFileIsAST(_MainFileIsAST),
Douglas Gregordf95a132010-08-09 20:45:32 +000052 CompleteTranslationUnit(true), ConcurrencyCheckValue(CheckUnlocked),
53 PreambleRebuildCounter(0), SavedMainFileBuffer(0) {
Douglas Gregor385103b2010-07-30 20:58:08 +000054}
Douglas Gregor3687e9d2010-04-05 21:10:19 +000055
Daniel Dunbar521bf9c2009-12-01 09:51:01 +000056ASTUnit::~ASTUnit() {
Douglas Gregorbdf60622010-03-05 21:16:25 +000057 ConcurrencyCheckValue = CheckLocked;
Douglas Gregorabc563f2010-07-19 21:46:24 +000058 CleanTemporaryFiles();
Douglas Gregor175c4a92010-07-23 23:58:40 +000059 if (!PreambleFile.empty())
Douglas Gregor385103b2010-07-30 20:58:08 +000060 llvm::sys::Path(PreambleFile).eraseFromDisk();
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +000061
62 // Free the buffers associated with remapped files. We are required to
63 // perform this operation here because we explicitly request that the
64 // compiler instance *not* free these buffers for each invocation of the
65 // parser.
66 if (Invocation.get()) {
67 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
68 for (PreprocessorOptions::remapped_file_buffer_iterator
69 FB = PPOpts.remapped_file_buffer_begin(),
70 FBEnd = PPOpts.remapped_file_buffer_end();
71 FB != FBEnd;
72 ++FB)
73 delete FB->second;
74 }
Douglas Gregor28233422010-07-27 14:52:07 +000075
76 delete SavedMainFileBuffer;
Douglas Gregor385103b2010-07-30 20:58:08 +000077
78 for (unsigned I = 0, N = Timers.size(); I != N; ++I)
79 delete Timers[I];
Douglas Gregorabc563f2010-07-19 21:46:24 +000080}
81
82void ASTUnit::CleanTemporaryFiles() {
Douglas Gregor313e26c2010-02-18 23:35:40 +000083 for (unsigned I = 0, N = TemporaryFiles.size(); I != N; ++I)
84 TemporaryFiles[I].eraseFromDisk();
Douglas Gregorabc563f2010-07-19 21:46:24 +000085 TemporaryFiles.clear();
Steve Naroffe19944c2009-10-15 22:23:48 +000086}
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000087
88namespace {
89
90/// \brief Gathers information from PCHReader that will be used to initialize
91/// a Preprocessor.
Benjamin Kramerbd218282009-11-28 10:07:24 +000092class PCHInfoCollector : public PCHReaderListener {
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000093 LangOptions &LangOpt;
94 HeaderSearch &HSI;
95 std::string &TargetTriple;
96 std::string &Predefines;
97 unsigned &Counter;
Mike Stump1eb44332009-09-09 15:08:12 +000098
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000099 unsigned NumHeaderInfos;
Mike Stump1eb44332009-09-09 15:08:12 +0000100
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000101public:
102 PCHInfoCollector(LangOptions &LangOpt, HeaderSearch &HSI,
103 std::string &TargetTriple, std::string &Predefines,
104 unsigned &Counter)
105 : LangOpt(LangOpt), HSI(HSI), TargetTriple(TargetTriple),
106 Predefines(Predefines), Counter(Counter), NumHeaderInfos(0) {}
Mike Stump1eb44332009-09-09 15:08:12 +0000107
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000108 virtual bool ReadLanguageOptions(const LangOptions &LangOpts) {
109 LangOpt = LangOpts;
110 return false;
111 }
Mike Stump1eb44332009-09-09 15:08:12 +0000112
Daniel Dunbardc3c0d22009-11-11 00:52:11 +0000113 virtual bool ReadTargetTriple(llvm::StringRef Triple) {
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000114 TargetTriple = Triple;
115 return false;
116 }
Mike Stump1eb44332009-09-09 15:08:12 +0000117
Sebastian Redlcb481aa2010-07-14 23:29:55 +0000118 virtual bool ReadPredefinesBuffer(const PCHPredefinesBlocks &Buffers,
Daniel Dunbar7b5a1212009-11-11 05:29:04 +0000119 llvm::StringRef OriginalFileName,
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000120 std::string &SuggestedPredefines) {
Sebastian Redlcb481aa2010-07-14 23:29:55 +0000121 Predefines = Buffers[0].Data;
122 for (unsigned I = 1, N = Buffers.size(); I != N; ++I) {
123 Predefines += Buffers[I].Data;
124 }
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000125 return false;
126 }
Mike Stump1eb44332009-09-09 15:08:12 +0000127
Douglas Gregorec1afbf2010-03-16 19:09:18 +0000128 virtual void ReadHeaderFileInfo(const HeaderFileInfo &HFI, unsigned ID) {
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000129 HSI.setHeaderFileInfoForUID(HFI, NumHeaderInfos++);
130 }
Mike Stump1eb44332009-09-09 15:08:12 +0000131
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000132 virtual void ReadCounter(unsigned Value) {
133 Counter = Value;
134 }
135};
136
Douglas Gregora88084b2010-02-18 18:08:43 +0000137class StoredDiagnosticClient : public DiagnosticClient {
138 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiags;
139
140public:
141 explicit StoredDiagnosticClient(
142 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiags)
143 : StoredDiags(StoredDiags) { }
144
145 virtual void HandleDiagnostic(Diagnostic::Level Level,
146 const DiagnosticInfo &Info);
147};
148
149/// \brief RAII object that optionally captures diagnostics, if
150/// there is no diagnostic client to capture them already.
151class CaptureDroppedDiagnostics {
152 Diagnostic &Diags;
153 StoredDiagnosticClient Client;
154 DiagnosticClient *PreviousClient;
155
156public:
157 CaptureDroppedDiagnostics(bool RequestCapture, Diagnostic &Diags,
158 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiags)
159 : Diags(Diags), Client(StoredDiags), PreviousClient(Diags.getClient())
160 {
161 if (RequestCapture || Diags.getClient() == 0)
162 Diags.setClient(&Client);
163 }
164
165 ~CaptureDroppedDiagnostics() {
166 Diags.setClient(PreviousClient);
167 }
168};
169
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000170} // anonymous namespace
171
Douglas Gregora88084b2010-02-18 18:08:43 +0000172void StoredDiagnosticClient::HandleDiagnostic(Diagnostic::Level Level,
173 const DiagnosticInfo &Info) {
174 StoredDiags.push_back(StoredDiagnostic(Level, Info));
175}
176
Steve Naroff77accc12009-09-03 18:19:54 +0000177const std::string &ASTUnit::getOriginalSourceFileName() {
Daniel Dunbar68d40e22009-12-02 08:44:16 +0000178 return OriginalSourceFile;
Steve Naroff77accc12009-09-03 18:19:54 +0000179}
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000180
Steve Naroffe19944c2009-10-15 22:23:48 +0000181const std::string &ASTUnit::getPCHFileName() {
Daniel Dunbarc7822db2009-12-02 21:47:43 +0000182 assert(isMainFileAST() && "Not an ASTUnit from a PCH file!");
Benjamin Kramer7297c182010-01-30 16:23:25 +0000183 return static_cast<PCHReader *>(Ctx->getExternalSource())->getFileName();
Steve Naroffe19944c2009-10-15 22:23:48 +0000184}
185
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000186ASTUnit *ASTUnit::LoadFromPCHFile(const std::string &Filename,
Douglas Gregor28019772010-04-05 23:52:57 +0000187 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
Ted Kremenek5cf48762009-10-17 00:34:24 +0000188 bool OnlyLocalDecls,
Douglas Gregor4db64a42010-01-23 00:14:00 +0000189 RemappedFile *RemappedFiles,
Douglas Gregora88084b2010-02-18 18:08:43 +0000190 unsigned NumRemappedFiles,
191 bool CaptureDiagnostics) {
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000192 llvm::OwningPtr<ASTUnit> AST(new ASTUnit(true));
193
Douglas Gregor28019772010-04-05 23:52:57 +0000194 if (!Diags.getPtr()) {
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000195 // No diagnostics engine was provided, so create our own diagnostics object
196 // with the default options.
197 DiagnosticOptions DiagOpts;
Douglas Gregor28019772010-04-05 23:52:57 +0000198 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000199 }
Douglas Gregorabc563f2010-07-19 21:46:24 +0000200
201 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000202 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor28019772010-04-05 23:52:57 +0000203 AST->Diagnostics = Diags;
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000204 AST->FileMgr.reset(new FileManager);
205 AST->SourceMgr.reset(new SourceManager(AST->getDiagnostics()));
Steve Naroff36c44642009-10-19 14:34:22 +0000206 AST->HeaderInfo.reset(new HeaderSearch(AST->getFileManager()));
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000207
Douglas Gregora88084b2010-02-18 18:08:43 +0000208 // If requested, capture diagnostics in the ASTUnit.
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000209 CaptureDroppedDiagnostics Capture(CaptureDiagnostics, AST->getDiagnostics(),
Douglas Gregor405634b2010-04-05 18:10:21 +0000210 AST->StoredDiagnostics);
Douglas Gregora88084b2010-02-18 18:08:43 +0000211
Douglas Gregor4db64a42010-01-23 00:14:00 +0000212 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
213 // Create the file entry for the file that we're mapping from.
214 const FileEntry *FromFile
215 = AST->getFileManager().getVirtualFile(RemappedFiles[I].first,
216 RemappedFiles[I].second->getBufferSize(),
217 0);
218 if (!FromFile) {
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000219 AST->getDiagnostics().Report(diag::err_fe_remap_missing_from_file)
Douglas Gregor4db64a42010-01-23 00:14:00 +0000220 << RemappedFiles[I].first;
Douglas Gregorc8dfe5e2010-02-27 01:32:48 +0000221 delete RemappedFiles[I].second;
Douglas Gregor4db64a42010-01-23 00:14:00 +0000222 continue;
223 }
224
225 // Override the contents of the "from" file with the contents of
226 // the "to" file.
227 AST->getSourceManager().overrideFileContents(FromFile,
228 RemappedFiles[I].second);
229 }
230
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000231 // Gather Info for preprocessor construction later on.
Mike Stump1eb44332009-09-09 15:08:12 +0000232
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000233 LangOptions LangInfo;
234 HeaderSearch &HeaderInfo = *AST->HeaderInfo.get();
235 std::string TargetTriple;
236 std::string Predefines;
237 unsigned Counter;
238
Daniel Dunbarbce6f622009-09-03 05:59:50 +0000239 llvm::OwningPtr<PCHReader> Reader;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000240 llvm::OwningPtr<ExternalASTSource> Source;
241
Ted Kremenekfc062212009-10-19 21:44:57 +0000242 Reader.reset(new PCHReader(AST->getSourceManager(), AST->getFileManager(),
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000243 AST->getDiagnostics()));
Daniel Dunbarcc318932009-09-03 05:59:35 +0000244 Reader->setListener(new PCHInfoCollector(LangInfo, HeaderInfo, TargetTriple,
245 Predefines, Counter));
246
247 switch (Reader->ReadPCH(Filename)) {
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000248 case PCHReader::Success:
249 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000250
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000251 case PCHReader::Failure:
Argyrios Kyrtzidis106c9982009-06-25 18:22:30 +0000252 case PCHReader::IgnorePCH:
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000253 AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000254 return NULL;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000255 }
Mike Stump1eb44332009-09-09 15:08:12 +0000256
Daniel Dunbar68d40e22009-12-02 08:44:16 +0000257 AST->OriginalSourceFile = Reader->getOriginalSourceFile();
258
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000259 // PCH loaded successfully. Now create the preprocessor.
Mike Stump1eb44332009-09-09 15:08:12 +0000260
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000261 // Get information about the target being compiled for.
Daniel Dunbard58c03f2009-11-15 06:48:46 +0000262 //
263 // FIXME: This is broken, we should store the TargetOptions in the PCH.
264 TargetOptions TargetOpts;
265 TargetOpts.ABI = "";
Charles Davis98b7c5c2010-06-11 01:06:47 +0000266 TargetOpts.CXXABI = "itanium";
Daniel Dunbard58c03f2009-11-15 06:48:46 +0000267 TargetOpts.CPU = "";
268 TargetOpts.Features.clear();
269 TargetOpts.Triple = TargetTriple;
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000270 AST->Target.reset(TargetInfo::CreateTargetInfo(AST->getDiagnostics(),
271 TargetOpts));
272 AST->PP.reset(new Preprocessor(AST->getDiagnostics(), LangInfo,
273 *AST->Target.get(),
Daniel Dunbar31b87d82009-09-21 03:03:39 +0000274 AST->getSourceManager(), HeaderInfo));
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000275 Preprocessor &PP = *AST->PP.get();
276
Daniel Dunbard5b61262009-09-21 03:03:47 +0000277 PP.setPredefines(Reader->getSuggestedPredefines());
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000278 PP.setCounterValue(Counter);
Daniel Dunbarcc318932009-09-03 05:59:35 +0000279 Reader->setPreprocessor(PP);
Mike Stump1eb44332009-09-09 15:08:12 +0000280
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000281 // Create and initialize the ASTContext.
282
283 AST->Ctx.reset(new ASTContext(LangInfo,
Daniel Dunbar31b87d82009-09-21 03:03:39 +0000284 AST->getSourceManager(),
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000285 *AST->Target.get(),
286 PP.getIdentifierTable(),
287 PP.getSelectorTable(),
288 PP.getBuiltinInfo(),
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000289 /* size_reserve = */0));
290 ASTContext &Context = *AST->Ctx.get();
Mike Stump1eb44332009-09-09 15:08:12 +0000291
Daniel Dunbarcc318932009-09-03 05:59:35 +0000292 Reader->InitializeContext(Context);
Mike Stump1eb44332009-09-09 15:08:12 +0000293
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000294 // Attach the PCH reader to the AST context as an external AST
295 // source, so that declarations will be deserialized from the
296 // PCH file as needed.
Daniel Dunbarcc318932009-09-03 05:59:35 +0000297 Source.reset(Reader.take());
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000298 Context.setExternalSource(Source);
299
Mike Stump1eb44332009-09-09 15:08:12 +0000300 return AST.take();
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000301}
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000302
303namespace {
304
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000305class TopLevelDeclTrackerConsumer : public ASTConsumer {
306 ASTUnit &Unit;
307
308public:
309 TopLevelDeclTrackerConsumer(ASTUnit &_Unit) : Unit(_Unit) {}
310
311 void HandleTopLevelDecl(DeclGroupRef D) {
Ted Kremenekda5a4282010-05-03 20:16:35 +0000312 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
313 Decl *D = *it;
314 // FIXME: Currently ObjC method declarations are incorrectly being
315 // reported as top-level declarations, even though their DeclContext
316 // is the containing ObjC @interface/@implementation. This is a
317 // fundamental problem in the parser right now.
318 if (isa<ObjCMethodDecl>(D))
319 continue;
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000320 Unit.addTopLevelDecl(D);
Ted Kremenekda5a4282010-05-03 20:16:35 +0000321 }
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000322 }
323};
324
325class TopLevelDeclTrackerAction : public ASTFrontendAction {
326public:
327 ASTUnit &Unit;
328
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000329 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
330 llvm::StringRef InFile) {
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000331 return new TopLevelDeclTrackerConsumer(Unit);
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000332 }
333
334public:
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000335 TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {}
336
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000337 virtual bool hasCodeCompletionSupport() const { return false; }
Douglas Gregordf95a132010-08-09 20:45:32 +0000338 virtual bool usesCompleteTranslationUnit() {
339 return Unit.isCompleteTranslationUnit();
340 }
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000341};
342
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000343class PrecompilePreambleConsumer : public PCHGenerator {
344 ASTUnit &Unit;
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000345 std::vector<Decl *> TopLevelDecls;
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000346
347public:
348 PrecompilePreambleConsumer(ASTUnit &Unit,
349 const Preprocessor &PP, bool Chaining,
350 const char *isysroot, llvm::raw_ostream *Out)
351 : PCHGenerator(PP, Chaining, isysroot, Out), Unit(Unit) { }
352
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000353 virtual void HandleTopLevelDecl(DeclGroupRef D) {
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000354 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
355 Decl *D = *it;
356 // FIXME: Currently ObjC method declarations are incorrectly being
357 // reported as top-level declarations, even though their DeclContext
358 // is the containing ObjC @interface/@implementation. This is a
359 // fundamental problem in the parser right now.
360 if (isa<ObjCMethodDecl>(D))
361 continue;
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000362 TopLevelDecls.push_back(D);
363 }
364 }
365
366 virtual void HandleTranslationUnit(ASTContext &Ctx) {
367 PCHGenerator::HandleTranslationUnit(Ctx);
368 if (!Unit.getDiagnostics().hasErrorOccurred()) {
369 // Translate the top-level declarations we captured during
370 // parsing into declaration IDs in the precompiled
371 // preamble. This will allow us to deserialize those top-level
372 // declarations when requested.
373 for (unsigned I = 0, N = TopLevelDecls.size(); I != N; ++I)
374 Unit.addTopLevelDeclFromPreamble(
375 getWriter().getDeclID(TopLevelDecls[I]));
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000376 }
377 }
378};
379
380class PrecompilePreambleAction : public ASTFrontendAction {
381 ASTUnit &Unit;
382
383public:
384 explicit PrecompilePreambleAction(ASTUnit &Unit) : Unit(Unit) {}
385
386 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
387 llvm::StringRef InFile) {
388 std::string Sysroot;
389 llvm::raw_ostream *OS = 0;
390 bool Chaining;
391 if (GeneratePCHAction::ComputeASTConsumerArguments(CI, InFile, Sysroot,
392 OS, Chaining))
393 return 0;
394
395 const char *isysroot = CI.getFrontendOpts().RelocatablePCH ?
396 Sysroot.c_str() : 0;
397 return new PrecompilePreambleConsumer(Unit, CI.getPreprocessor(), Chaining,
398 isysroot, OS);
399 }
400
401 virtual bool hasCodeCompletionSupport() const { return false; }
402 virtual bool hasASTFileSupport() const { return false; }
Douglas Gregordf95a132010-08-09 20:45:32 +0000403 virtual bool usesCompleteTranslationUnit() { return false; }
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000404};
405
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000406}
407
Douglas Gregorabc563f2010-07-19 21:46:24 +0000408/// Parse the source file into a translation unit using the given compiler
409/// invocation, replacing the current translation unit.
410///
411/// \returns True if a failure occurred that causes the ASTUnit not to
412/// contain any translation-unit information, false otherwise.
Douglas Gregor754f3492010-07-24 00:38:13 +0000413bool ASTUnit::Parse(llvm::MemoryBuffer *OverrideMainBuffer) {
Douglas Gregor28233422010-07-27 14:52:07 +0000414 delete SavedMainFileBuffer;
415 SavedMainFileBuffer = 0;
416
Douglas Gregorabc563f2010-07-19 21:46:24 +0000417 if (!Invocation.get())
418 return true;
419
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000420 // Create the compiler instance to use for building the AST.
Daniel Dunbarcb6dda12009-12-02 08:43:56 +0000421 CompilerInstance Clang;
Douglas Gregorabc563f2010-07-19 21:46:24 +0000422 Clang.setInvocation(Invocation.take());
423 OriginalSourceFile = Clang.getFrontendOpts().Inputs[0].second;
424
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000425 // Set up diagnostics, capturing any diagnostics that would
426 // otherwise be dropped.
Douglas Gregorabc563f2010-07-19 21:46:24 +0000427 Clang.setDiagnostics(&getDiagnostics());
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000428 CaptureDroppedDiagnostics Capture(CaptureDiagnostics,
429 getDiagnostics(),
430 StoredDiagnostics);
Douglas Gregorabc563f2010-07-19 21:46:24 +0000431 Clang.setDiagnosticClient(getDiagnostics().getClient());
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000432
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000433 // Create the target instance.
434 Clang.setTarget(TargetInfo::CreateTargetInfo(Clang.getDiagnostics(),
435 Clang.getTargetOpts()));
Douglas Gregora88084b2010-02-18 18:08:43 +0000436 if (!Clang.hasTarget()) {
Douglas Gregora88084b2010-02-18 18:08:43 +0000437 Clang.takeDiagnosticClient();
Douglas Gregorabc563f2010-07-19 21:46:24 +0000438 return true;
Douglas Gregora88084b2010-02-18 18:08:43 +0000439 }
Douglas Gregorabc563f2010-07-19 21:46:24 +0000440
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000441 // Inform the target of the language options.
442 //
443 // FIXME: We shouldn't need to do this, the target should be immutable once
444 // created. This complexity should be lifted elsewhere.
445 Clang.getTarget().setForcedLangOptions(Clang.getLangOpts());
Douglas Gregorabc563f2010-07-19 21:46:24 +0000446
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000447 assert(Clang.getFrontendOpts().Inputs.size() == 1 &&
448 "Invocation must have exactly one source file!");
Daniel Dunbarc34ce3f2010-06-07 23:22:09 +0000449 assert(Clang.getFrontendOpts().Inputs[0].first != IK_AST &&
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000450 "FIXME: AST inputs not yet supported here!");
Daniel Dunbarfaddc3e2010-06-07 23:26:47 +0000451 assert(Clang.getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
452 "IR inputs not support here!");
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000453
Douglas Gregorabc563f2010-07-19 21:46:24 +0000454 // Configure the various subsystems.
455 // FIXME: Should we retain the previous file manager?
456 FileMgr.reset(new FileManager);
457 SourceMgr.reset(new SourceManager(getDiagnostics()));
458 Ctx.reset();
459 PP.reset();
460
461 // Clear out old caches and data.
462 TopLevelDecls.clear();
Douglas Gregorabc563f2010-07-19 21:46:24 +0000463 CleanTemporaryFiles();
464 PreprocessedEntitiesByFile.clear();
Douglas Gregorc0659ec2010-08-02 20:51:39 +0000465
466 if (!OverrideMainBuffer)
467 StoredDiagnostics.clear();
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000468
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000469 // Create a file manager object to provide access to and cache the filesystem.
Douglas Gregorabc563f2010-07-19 21:46:24 +0000470 Clang.setFileManager(&getFileManager());
471
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000472 // Create the source manager.
Douglas Gregorabc563f2010-07-19 21:46:24 +0000473 Clang.setSourceManager(&getSourceManager());
474
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000475 // If the main file has been overridden due to the use of a preamble,
476 // make that override happen and introduce the preamble.
477 PreprocessorOptions &PreprocessorOpts = Clang.getPreprocessorOpts();
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000478 std::string PriorImplicitPCHInclude;
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000479 if (OverrideMainBuffer) {
480 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
481 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
482 PreprocessorOpts.PrecompiledPreambleBytes.second
483 = PreambleEndsAtStartOfLine;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000484 PriorImplicitPCHInclude = PreprocessorOpts.ImplicitPCHInclude;
Douglas Gregor385103b2010-07-30 20:58:08 +0000485 PreprocessorOpts.ImplicitPCHInclude = PreambleFile;
Douglas Gregorfae3b2f2010-07-27 00:27:13 +0000486 PreprocessorOpts.DisablePCHValidation = true;
Douglas Gregor28233422010-07-27 14:52:07 +0000487
488 // Keep track of the override buffer;
489 SavedMainFileBuffer = OverrideMainBuffer;
Douglas Gregorc0659ec2010-08-02 20:51:39 +0000490
491 // The stored diagnostic has the old source manager in it; update
492 // the locations to refer into the new source manager. Since we've
493 // been careful to make sure that the source manager's state
494 // before and after are identical, so that we can reuse the source
495 // location itself.
496 for (unsigned I = 0, N = StoredDiagnostics.size(); I != N; ++I) {
497 FullSourceLoc Loc(StoredDiagnostics[I].getLocation(),
498 getSourceManager());
499 StoredDiagnostics[I].setLocation(Loc);
500 }
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000501 }
502
Douglas Gregorabc563f2010-07-19 21:46:24 +0000503 llvm::OwningPtr<TopLevelDeclTrackerAction> Act;
504 Act.reset(new TopLevelDeclTrackerAction(*this));
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000505 if (!Act->BeginSourceFile(Clang, Clang.getFrontendOpts().Inputs[0].second,
Daniel Dunbard3598a62010-06-07 23:23:06 +0000506 Clang.getFrontendOpts().Inputs[0].first))
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000507 goto error;
Douglas Gregorabc563f2010-07-19 21:46:24 +0000508
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000509 Act->Execute();
Douglas Gregorabc563f2010-07-19 21:46:24 +0000510
Daniel Dunbar64a32ba2009-12-01 21:57:33 +0000511 // Steal the created target, context, and preprocessor, and take back the
512 // source and file managers.
Douglas Gregorabc563f2010-07-19 21:46:24 +0000513 Ctx.reset(Clang.takeASTContext());
514 PP.reset(Clang.takePreprocessor());
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000515 Clang.takeSourceManager();
516 Clang.takeFileManager();
Douglas Gregorabc563f2010-07-19 21:46:24 +0000517 Target.reset(Clang.takeTarget());
518
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000519 Act->EndSourceFile();
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000520
521 // Remove the overridden buffer we used for the preamble.
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000522 if (OverrideMainBuffer) {
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000523 PreprocessorOpts.eraseRemappedFile(
524 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000525 PreprocessorOpts.ImplicitPCHInclude = PriorImplicitPCHInclude;
526 }
527
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000528 Clang.takeDiagnosticClient();
Douglas Gregorabc563f2010-07-19 21:46:24 +0000529
530 Invocation.reset(Clang.takeInvocation());
531 return false;
532
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000533error:
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000534 // Remove the overridden buffer we used for the preamble.
Douglas Gregorfae3b2f2010-07-27 00:27:13 +0000535 if (OverrideMainBuffer) {
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000536 PreprocessorOpts.eraseRemappedFile(
537 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregorfae3b2f2010-07-27 00:27:13 +0000538 PreprocessorOpts.DisablePCHValidation = true;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000539 PreprocessorOpts.ImplicitPCHInclude = PriorImplicitPCHInclude;
Douglas Gregorfae3b2f2010-07-27 00:27:13 +0000540 }
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000541
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000542 Clang.takeSourceManager();
543 Clang.takeFileManager();
544 Clang.takeDiagnosticClient();
Douglas Gregorabc563f2010-07-19 21:46:24 +0000545 Invocation.reset(Clang.takeInvocation());
546 return true;
547}
548
Douglas Gregor44c181a2010-07-23 00:33:23 +0000549/// \brief Simple function to retrieve a path for a preamble precompiled header.
550static std::string GetPreamblePCHPath() {
551 // FIXME: This is lame; sys::Path should provide this function (in particular,
552 // it should know how to find the temporary files dir).
553 // FIXME: This is really lame. I copied this code from the Driver!
554 std::string Error;
555 const char *TmpDir = ::getenv("TMPDIR");
556 if (!TmpDir)
557 TmpDir = ::getenv("TEMP");
558 if (!TmpDir)
559 TmpDir = ::getenv("TMP");
560 if (!TmpDir)
561 TmpDir = "/tmp";
562 llvm::sys::Path P(TmpDir);
563 P.appendComponent("preamble");
564 if (P.createTemporaryFileOnDisk())
565 return std::string();
566
567 P.appendSuffix("pch");
568 return P.str();
569}
570
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000571/// \brief Compute the preamble for the main file, providing the source buffer
572/// that corresponds to the main file along with a pair (bytes, start-of-line)
573/// that describes the preamble.
574std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> >
Douglas Gregordf95a132010-08-09 20:45:32 +0000575ASTUnit::ComputePreamble(CompilerInvocation &Invocation,
576 unsigned MaxLines, bool &CreatedBuffer) {
Douglas Gregor175c4a92010-07-23 23:58:40 +0000577 FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
Douglas Gregor44c181a2010-07-23 00:33:23 +0000578 PreprocessorOptions &PreprocessorOpts
Douglas Gregor175c4a92010-07-23 23:58:40 +0000579 = Invocation.getPreprocessorOpts();
580 CreatedBuffer = false;
581
Douglas Gregor44c181a2010-07-23 00:33:23 +0000582 // Try to determine if the main file has been remapped, either from the
583 // command line (to another file) or directly through the compiler invocation
584 // (to a memory buffer).
Douglas Gregor175c4a92010-07-23 23:58:40 +0000585 llvm::MemoryBuffer *Buffer = 0;
Douglas Gregor44c181a2010-07-23 00:33:23 +0000586 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].second);
587 if (const llvm::sys::FileStatus *MainFileStatus = MainFilePath.getFileStatus()) {
588 // Check whether there is a file-file remapping of the main file
589 for (PreprocessorOptions::remapped_file_iterator
Douglas Gregor175c4a92010-07-23 23:58:40 +0000590 M = PreprocessorOpts.remapped_file_begin(),
591 E = PreprocessorOpts.remapped_file_end();
Douglas Gregor44c181a2010-07-23 00:33:23 +0000592 M != E;
593 ++M) {
594 llvm::sys::PathWithStatus MPath(M->first);
595 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
596 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
597 // We found a remapping. Try to load the resulting, remapped source.
Douglas Gregor175c4a92010-07-23 23:58:40 +0000598 if (CreatedBuffer) {
Douglas Gregor44c181a2010-07-23 00:33:23 +0000599 delete Buffer;
Douglas Gregor175c4a92010-07-23 23:58:40 +0000600 CreatedBuffer = false;
601 }
602
Douglas Gregor44c181a2010-07-23 00:33:23 +0000603 Buffer = llvm::MemoryBuffer::getFile(M->second);
604 if (!Buffer)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000605 return std::make_pair((llvm::MemoryBuffer*)0,
606 std::make_pair(0, true));
Douglas Gregor175c4a92010-07-23 23:58:40 +0000607 CreatedBuffer = true;
Douglas Gregor44c181a2010-07-23 00:33:23 +0000608
Douglas Gregor175c4a92010-07-23 23:58:40 +0000609 // Remove this remapping. We've captured the buffer already.
Douglas Gregor44c181a2010-07-23 00:33:23 +0000610 M = PreprocessorOpts.eraseRemappedFile(M);
611 E = PreprocessorOpts.remapped_file_end();
612 }
613 }
614 }
615
616 // Check whether there is a file-buffer remapping. It supercedes the
617 // file-file remapping.
618 for (PreprocessorOptions::remapped_file_buffer_iterator
619 M = PreprocessorOpts.remapped_file_buffer_begin(),
620 E = PreprocessorOpts.remapped_file_buffer_end();
621 M != E;
622 ++M) {
623 llvm::sys::PathWithStatus MPath(M->first);
624 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
625 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
626 // We found a remapping.
Douglas Gregor175c4a92010-07-23 23:58:40 +0000627 if (CreatedBuffer) {
Douglas Gregor44c181a2010-07-23 00:33:23 +0000628 delete Buffer;
Douglas Gregor175c4a92010-07-23 23:58:40 +0000629 CreatedBuffer = false;
630 }
Douglas Gregor44c181a2010-07-23 00:33:23 +0000631
Douglas Gregor175c4a92010-07-23 23:58:40 +0000632 Buffer = const_cast<llvm::MemoryBuffer *>(M->second);
633
634 // Remove this remapping. We've captured the buffer already.
Douglas Gregor44c181a2010-07-23 00:33:23 +0000635 M = PreprocessorOpts.eraseRemappedFile(M);
636 E = PreprocessorOpts.remapped_file_buffer_end();
637 }
638 }
Douglas Gregor175c4a92010-07-23 23:58:40 +0000639 }
Douglas Gregor44c181a2010-07-23 00:33:23 +0000640 }
641
642 // If the main source file was not remapped, load it now.
643 if (!Buffer) {
644 Buffer = llvm::MemoryBuffer::getFile(FrontendOpts.Inputs[0].second);
645 if (!Buffer)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000646 return std::make_pair((llvm::MemoryBuffer*)0, std::make_pair(0, true));
Douglas Gregor175c4a92010-07-23 23:58:40 +0000647
648 CreatedBuffer = true;
Douglas Gregor44c181a2010-07-23 00:33:23 +0000649 }
650
Douglas Gregordf95a132010-08-09 20:45:32 +0000651 return std::make_pair(Buffer, Lexer::ComputePreamble(Buffer, MaxLines));
Douglas Gregor175c4a92010-07-23 23:58:40 +0000652}
653
Douglas Gregor754f3492010-07-24 00:38:13 +0000654static llvm::MemoryBuffer *CreatePaddedMainFileBuffer(llvm::MemoryBuffer *Old,
655 bool DeleteOld,
656 unsigned NewSize,
657 llvm::StringRef NewName) {
658 llvm::MemoryBuffer *Result
659 = llvm::MemoryBuffer::getNewUninitMemBuffer(NewSize, NewName);
660 memcpy(const_cast<char*>(Result->getBufferStart()),
661 Old->getBufferStart(), Old->getBufferSize());
662 memset(const_cast<char*>(Result->getBufferStart()) + Old->getBufferSize(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000663 ' ', NewSize - Old->getBufferSize() - 1);
664 const_cast<char*>(Result->getBufferEnd())[-1] = '\n';
Douglas Gregor754f3492010-07-24 00:38:13 +0000665
666 if (DeleteOld)
667 delete Old;
668
669 return Result;
670}
671
Douglas Gregor175c4a92010-07-23 23:58:40 +0000672/// \brief Attempt to build or re-use a precompiled preamble when (re-)parsing
673/// the source file.
674///
675/// This routine will compute the preamble of the main source file. If a
676/// non-trivial preamble is found, it will precompile that preamble into a
677/// precompiled header so that the precompiled preamble can be used to reduce
678/// reparsing time. If a precompiled preamble has already been constructed,
679/// this routine will determine if it is still valid and, if so, avoid
680/// rebuilding the precompiled preamble.
681///
Douglas Gregordf95a132010-08-09 20:45:32 +0000682/// \param AllowRebuild When true (the default), this routine is
683/// allowed to rebuild the precompiled preamble if it is found to be
684/// out-of-date.
685///
686/// \param MaxLines When non-zero, the maximum number of lines that
687/// can occur within the preamble.
688///
Douglas Gregor754f3492010-07-24 00:38:13 +0000689/// \returns If the precompiled preamble can be used, returns a newly-allocated
690/// buffer that should be used in place of the main file when doing so.
691/// Otherwise, returns a NULL pointer.
Douglas Gregordf95a132010-08-09 20:45:32 +0000692llvm::MemoryBuffer *ASTUnit::getMainBufferWithPrecompiledPreamble(
693 bool AllowRebuild,
694 unsigned MaxLines) {
Douglas Gregor175c4a92010-07-23 23:58:40 +0000695 CompilerInvocation PreambleInvocation(*Invocation);
696 FrontendOptions &FrontendOpts = PreambleInvocation.getFrontendOpts();
697 PreprocessorOptions &PreprocessorOpts
698 = PreambleInvocation.getPreprocessorOpts();
699
700 bool CreatedPreambleBuffer = false;
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000701 std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> > NewPreamble
Douglas Gregordf95a132010-08-09 20:45:32 +0000702 = ComputePreamble(PreambleInvocation, MaxLines, CreatedPreambleBuffer);
Douglas Gregor175c4a92010-07-23 23:58:40 +0000703
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000704 if (!NewPreamble.second.first) {
Douglas Gregor175c4a92010-07-23 23:58:40 +0000705 // We couldn't find a preamble in the main source. Clear out the current
706 // preamble, if we have one. It's obviously no good any more.
707 Preamble.clear();
708 if (!PreambleFile.empty()) {
Douglas Gregor385103b2010-07-30 20:58:08 +0000709 llvm::sys::Path(PreambleFile).eraseFromDisk();
Douglas Gregor175c4a92010-07-23 23:58:40 +0000710 PreambleFile.clear();
711 }
712 if (CreatedPreambleBuffer)
713 delete NewPreamble.first;
Douglas Gregoreababfb2010-08-04 05:53:38 +0000714
715 // The next time we actually see a preamble, precompile it.
716 PreambleRebuildCounter = 1;
Douglas Gregor754f3492010-07-24 00:38:13 +0000717 return 0;
Douglas Gregor175c4a92010-07-23 23:58:40 +0000718 }
719
720 if (!Preamble.empty()) {
721 // We've previously computed a preamble. Check whether we have the same
722 // preamble now that we did before, and that there's enough space in
723 // the main-file buffer within the precompiled preamble to fit the
724 // new main file.
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000725 if (Preamble.size() == NewPreamble.second.first &&
726 PreambleEndsAtStartOfLine == NewPreamble.second.second &&
Douglas Gregor592508e2010-07-24 00:42:07 +0000727 NewPreamble.first->getBufferSize() < PreambleReservedSize-2 &&
Douglas Gregor175c4a92010-07-23 23:58:40 +0000728 memcmp(&Preamble[0], NewPreamble.first->getBufferStart(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000729 NewPreamble.second.first) == 0) {
Douglas Gregor175c4a92010-07-23 23:58:40 +0000730 // The preamble has not changed. We may be able to re-use the precompiled
731 // preamble.
Douglas Gregorc0659ec2010-08-02 20:51:39 +0000732
Douglas Gregorcc5888d2010-07-31 00:40:00 +0000733 // Check that none of the files used by the preamble have changed.
734 bool AnyFileChanged = false;
735
736 // First, make a record of those files that have been overridden via
737 // remapping or unsaved_files.
738 llvm::StringMap<std::pair<off_t, time_t> > OverriddenFiles;
739 for (PreprocessorOptions::remapped_file_iterator
740 R = PreprocessorOpts.remapped_file_begin(),
741 REnd = PreprocessorOpts.remapped_file_end();
742 !AnyFileChanged && R != REnd;
743 ++R) {
744 struct stat StatBuf;
745 if (stat(R->second.c_str(), &StatBuf)) {
746 // If we can't stat the file we're remapping to, assume that something
747 // horrible happened.
748 AnyFileChanged = true;
749 break;
750 }
Douglas Gregor754f3492010-07-24 00:38:13 +0000751
Douglas Gregorcc5888d2010-07-31 00:40:00 +0000752 OverriddenFiles[R->first] = std::make_pair(StatBuf.st_size,
753 StatBuf.st_mtime);
754 }
755 for (PreprocessorOptions::remapped_file_buffer_iterator
756 R = PreprocessorOpts.remapped_file_buffer_begin(),
757 REnd = PreprocessorOpts.remapped_file_buffer_end();
758 !AnyFileChanged && R != REnd;
759 ++R) {
760 // FIXME: Should we actually compare the contents of file->buffer
761 // remappings?
762 OverriddenFiles[R->first] = std::make_pair(R->second->getBufferSize(),
763 0);
764 }
765
766 // Check whether anything has changed.
767 for (llvm::StringMap<std::pair<off_t, time_t> >::iterator
768 F = FilesInPreamble.begin(), FEnd = FilesInPreamble.end();
769 !AnyFileChanged && F != FEnd;
770 ++F) {
771 llvm::StringMap<std::pair<off_t, time_t> >::iterator Overridden
772 = OverriddenFiles.find(F->first());
773 if (Overridden != OverriddenFiles.end()) {
774 // This file was remapped; check whether the newly-mapped file
775 // matches up with the previous mapping.
776 if (Overridden->second != F->second)
777 AnyFileChanged = true;
778 continue;
779 }
780
781 // The file was not remapped; check whether it has changed on disk.
782 struct stat StatBuf;
783 if (stat(F->first(), &StatBuf)) {
784 // If we can't stat the file, assume that something horrible happened.
785 AnyFileChanged = true;
786 } else if (StatBuf.st_size != F->second.first ||
787 StatBuf.st_mtime != F->second.second)
788 AnyFileChanged = true;
789 }
790
791 if (!AnyFileChanged) {
Douglas Gregorc0659ec2010-08-02 20:51:39 +0000792 // Okay! We can re-use the precompiled preamble.
793
794 // Set the state of the diagnostic object to mimic its state
795 // after parsing the preamble.
796 getDiagnostics().Reset();
797 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
798 if (StoredDiagnostics.size() > NumStoredDiagnosticsInPreamble)
799 StoredDiagnostics.erase(
800 StoredDiagnostics.begin() + NumStoredDiagnosticsInPreamble,
801 StoredDiagnostics.end());
802
803 // Create a version of the main file buffer that is padded to
804 // buffer size we reserved when creating the preamble.
Douglas Gregorcc5888d2010-07-31 00:40:00 +0000805 return CreatePaddedMainFileBuffer(NewPreamble.first,
806 CreatedPreambleBuffer,
807 PreambleReservedSize,
808 FrontendOpts.Inputs[0].second);
809 }
Douglas Gregor175c4a92010-07-23 23:58:40 +0000810 }
Douglas Gregordf95a132010-08-09 20:45:32 +0000811
812 // If we aren't allowed to rebuild the precompiled preamble, just
813 // return now.
814 if (!AllowRebuild)
815 return 0;
Douglas Gregor175c4a92010-07-23 23:58:40 +0000816
817 // We can't reuse the previously-computed preamble. Build a new one.
818 Preamble.clear();
Douglas Gregor385103b2010-07-30 20:58:08 +0000819 llvm::sys::Path(PreambleFile).eraseFromDisk();
Douglas Gregoreababfb2010-08-04 05:53:38 +0000820 PreambleRebuildCounter = 1;
Douglas Gregordf95a132010-08-09 20:45:32 +0000821 } else if (!AllowRebuild) {
822 // We aren't allowed to rebuild the precompiled preamble; just
823 // return now.
824 return 0;
825 }
Douglas Gregoreababfb2010-08-04 05:53:38 +0000826
827 // If the preamble rebuild counter > 1, it's because we previously
828 // failed to build a preamble and we're not yet ready to try
829 // again. Decrement the counter and return a failure.
830 if (PreambleRebuildCounter > 1) {
831 --PreambleRebuildCounter;
832 return 0;
833 }
834
Douglas Gregor175c4a92010-07-23 23:58:40 +0000835 // We did not previously compute a preamble, or it can't be reused anyway.
Douglas Gregor385103b2010-07-30 20:58:08 +0000836 llvm::Timer *PreambleTimer = 0;
837 if (TimerGroup.get()) {
838 PreambleTimer = new llvm::Timer("Precompiling preamble", *TimerGroup);
839 PreambleTimer->startTimer();
840 Timers.push_back(PreambleTimer);
841 }
Douglas Gregor44c181a2010-07-23 00:33:23 +0000842
843 // Create a new buffer that stores the preamble. The buffer also contains
844 // extra space for the original contents of the file (which will be present
845 // when we actually parse the file) along with more room in case the file
Douglas Gregor175c4a92010-07-23 23:58:40 +0000846 // grows.
847 PreambleReservedSize = NewPreamble.first->getBufferSize();
848 if (PreambleReservedSize < 4096)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000849 PreambleReservedSize = 8191;
Douglas Gregor44c181a2010-07-23 00:33:23 +0000850 else
Douglas Gregor175c4a92010-07-23 23:58:40 +0000851 PreambleReservedSize *= 2;
852
Douglas Gregorc0659ec2010-08-02 20:51:39 +0000853 // Save the preamble text for later; we'll need to compare against it for
854 // subsequent reparses.
855 Preamble.assign(NewPreamble.first->getBufferStart(),
856 NewPreamble.first->getBufferStart()
857 + NewPreamble.second.first);
858 PreambleEndsAtStartOfLine = NewPreamble.second.second;
859
Douglas Gregor44c181a2010-07-23 00:33:23 +0000860 llvm::MemoryBuffer *PreambleBuffer
Douglas Gregor175c4a92010-07-23 23:58:40 +0000861 = llvm::MemoryBuffer::getNewUninitMemBuffer(PreambleReservedSize,
Douglas Gregor44c181a2010-07-23 00:33:23 +0000862 FrontendOpts.Inputs[0].second);
863 memcpy(const_cast<char*>(PreambleBuffer->getBufferStart()),
Douglas Gregor175c4a92010-07-23 23:58:40 +0000864 NewPreamble.first->getBufferStart(), Preamble.size());
865 memset(const_cast<char*>(PreambleBuffer->getBufferStart()) + Preamble.size(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000866 ' ', PreambleReservedSize - Preamble.size() - 1);
867 const_cast<char*>(PreambleBuffer->getBufferEnd())[-1] = '\n';
Douglas Gregor44c181a2010-07-23 00:33:23 +0000868
869 // Remap the main source file to the preamble buffer.
Douglas Gregor175c4a92010-07-23 23:58:40 +0000870 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].second);
Douglas Gregor44c181a2010-07-23 00:33:23 +0000871 PreprocessorOpts.addRemappedFile(MainFilePath.str(), PreambleBuffer);
872
873 // Tell the compiler invocation to generate a temporary precompiled header.
874 FrontendOpts.ProgramAction = frontend::GeneratePCH;
Sebastian Redlf65339e2010-08-06 00:35:11 +0000875 // FIXME: Set ChainedPCH unconditionally, once it is ready.
876 if (::getenv("LIBCLANG_CHAINING"))
877 FrontendOpts.ChainedPCH = true;
Douglas Gregor44c181a2010-07-23 00:33:23 +0000878 // FIXME: Generate the precompiled header into memory?
Douglas Gregor385103b2010-07-30 20:58:08 +0000879 FrontendOpts.OutputFile = GetPreamblePCHPath();
Douglas Gregor44c181a2010-07-23 00:33:23 +0000880
881 // Create the compiler instance to use for building the precompiled preamble.
882 CompilerInstance Clang;
883 Clang.setInvocation(&PreambleInvocation);
884 OriginalSourceFile = Clang.getFrontendOpts().Inputs[0].second;
885
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000886 // Set up diagnostics, capturing all of the diagnostics produced.
Douglas Gregor44c181a2010-07-23 00:33:23 +0000887 Clang.setDiagnostics(&getDiagnostics());
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000888 CaptureDroppedDiagnostics Capture(CaptureDiagnostics,
889 getDiagnostics(),
890 StoredDiagnostics);
Douglas Gregor44c181a2010-07-23 00:33:23 +0000891 Clang.setDiagnosticClient(getDiagnostics().getClient());
892
893 // Create the target instance.
894 Clang.setTarget(TargetInfo::CreateTargetInfo(Clang.getDiagnostics(),
895 Clang.getTargetOpts()));
896 if (!Clang.hasTarget()) {
897 Clang.takeDiagnosticClient();
Douglas Gregor175c4a92010-07-23 23:58:40 +0000898 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
899 Preamble.clear();
900 if (CreatedPreambleBuffer)
901 delete NewPreamble.first;
Douglas Gregor385103b2010-07-30 20:58:08 +0000902 if (PreambleTimer)
903 PreambleTimer->stopTimer();
Douglas Gregoreababfb2010-08-04 05:53:38 +0000904 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor754f3492010-07-24 00:38:13 +0000905 return 0;
Douglas Gregor44c181a2010-07-23 00:33:23 +0000906 }
907
908 // Inform the target of the language options.
909 //
910 // FIXME: We shouldn't need to do this, the target should be immutable once
911 // created. This complexity should be lifted elsewhere.
912 Clang.getTarget().setForcedLangOptions(Clang.getLangOpts());
913
914 assert(Clang.getFrontendOpts().Inputs.size() == 1 &&
915 "Invocation must have exactly one source file!");
916 assert(Clang.getFrontendOpts().Inputs[0].first != IK_AST &&
917 "FIXME: AST inputs not yet supported here!");
918 assert(Clang.getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
919 "IR inputs not support here!");
920
921 // Clear out old caches and data.
922 StoredDiagnostics.clear();
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000923 TopLevelDecls.clear();
924 TopLevelDeclsInPreamble.clear();
Douglas Gregor44c181a2010-07-23 00:33:23 +0000925
926 // Create a file manager object to provide access to and cache the filesystem.
927 Clang.setFileManager(new FileManager);
928
929 // Create the source manager.
930 Clang.setSourceManager(new SourceManager(getDiagnostics()));
931
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000932 llvm::OwningPtr<PrecompilePreambleAction> Act;
933 Act.reset(new PrecompilePreambleAction(*this));
Douglas Gregor44c181a2010-07-23 00:33:23 +0000934 if (!Act->BeginSourceFile(Clang, Clang.getFrontendOpts().Inputs[0].second,
935 Clang.getFrontendOpts().Inputs[0].first)) {
936 Clang.takeDiagnosticClient();
937 Clang.takeInvocation();
Douglas Gregor175c4a92010-07-23 23:58:40 +0000938 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
939 Preamble.clear();
940 if (CreatedPreambleBuffer)
941 delete NewPreamble.first;
Douglas Gregor385103b2010-07-30 20:58:08 +0000942 if (PreambleTimer)
943 PreambleTimer->stopTimer();
Douglas Gregoreababfb2010-08-04 05:53:38 +0000944 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor385103b2010-07-30 20:58:08 +0000945
Douglas Gregor754f3492010-07-24 00:38:13 +0000946 return 0;
Douglas Gregor44c181a2010-07-23 00:33:23 +0000947 }
948
949 Act->Execute();
950 Act->EndSourceFile();
951 Clang.takeDiagnosticClient();
952 Clang.takeInvocation();
953
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000954 if (Diagnostics->hasErrorOccurred()) {
Douglas Gregor175c4a92010-07-23 23:58:40 +0000955 // There were errors parsing the preamble, so no precompiled header was
956 // generated. Forget that we even tried.
957 // FIXME: Should we leave a note for ourselves to try again?
958 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
959 Preamble.clear();
960 if (CreatedPreambleBuffer)
961 delete NewPreamble.first;
Douglas Gregor385103b2010-07-30 20:58:08 +0000962 if (PreambleTimer)
963 PreambleTimer->stopTimer();
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000964 TopLevelDeclsInPreamble.clear();
Douglas Gregoreababfb2010-08-04 05:53:38 +0000965 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor754f3492010-07-24 00:38:13 +0000966 return 0;
Douglas Gregor175c4a92010-07-23 23:58:40 +0000967 }
968
969 // Keep track of the preamble we precompiled.
970 PreambleFile = FrontendOpts.OutputFile;
Douglas Gregorc0659ec2010-08-02 20:51:39 +0000971 NumStoredDiagnosticsInPreamble = StoredDiagnostics.size();
972 NumWarningsInPreamble = getDiagnostics().getNumWarnings();
Douglas Gregorcc5888d2010-07-31 00:40:00 +0000973
974 // Keep track of all of the files that the source manager knows about,
975 // so we can verify whether they have changed or not.
976 FilesInPreamble.clear();
977 SourceManager &SourceMgr = Clang.getSourceManager();
978 const llvm::MemoryBuffer *MainFileBuffer
979 = SourceMgr.getBuffer(SourceMgr.getMainFileID());
980 for (SourceManager::fileinfo_iterator F = SourceMgr.fileinfo_begin(),
981 FEnd = SourceMgr.fileinfo_end();
982 F != FEnd;
983 ++F) {
984 const FileEntry *File = F->second->Entry;
985 if (!File || F->second->getRawBuffer() == MainFileBuffer)
986 continue;
987
988 FilesInPreamble[File->getName()]
989 = std::make_pair(F->second->getSize(), File->getModificationTime());
990 }
991
Douglas Gregor385103b2010-07-30 20:58:08 +0000992 if (PreambleTimer)
993 PreambleTimer->stopTimer();
994
Douglas Gregoreababfb2010-08-04 05:53:38 +0000995 PreambleRebuildCounter = 1;
Douglas Gregor754f3492010-07-24 00:38:13 +0000996 return CreatePaddedMainFileBuffer(NewPreamble.first,
997 CreatedPreambleBuffer,
998 PreambleReservedSize,
999 FrontendOpts.Inputs[0].second);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001000}
Douglas Gregorabc563f2010-07-19 21:46:24 +00001001
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001002void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
1003 std::vector<Decl *> Resolved;
1004 Resolved.reserve(TopLevelDeclsInPreamble.size());
1005 ExternalASTSource &Source = *getASTContext().getExternalSource();
1006 for (unsigned I = 0, N = TopLevelDeclsInPreamble.size(); I != N; ++I) {
1007 // Resolve the declaration ID to an actual declaration, possibly
1008 // deserializing the declaration in the process.
1009 Decl *D = Source.GetExternalDecl(TopLevelDeclsInPreamble[I]);
1010 if (D)
1011 Resolved.push_back(D);
1012 }
1013 TopLevelDeclsInPreamble.clear();
1014 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1015}
1016
1017unsigned ASTUnit::getMaxPCHLevel() const {
1018 if (!getOnlyLocalDecls())
1019 return Decl::MaxPCHLevel;
1020
1021 unsigned Result = 0;
1022 if (isMainFileAST() || SavedMainFileBuffer)
1023 ++Result;
1024 return Result;
1025}
1026
Douglas Gregorabc563f2010-07-19 21:46:24 +00001027ASTUnit *ASTUnit::LoadFromCompilerInvocation(CompilerInvocation *CI,
1028 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
1029 bool OnlyLocalDecls,
Douglas Gregor44c181a2010-07-23 00:33:23 +00001030 bool CaptureDiagnostics,
Douglas Gregordf95a132010-08-09 20:45:32 +00001031 bool PrecompilePreamble,
1032 bool CompleteTranslationUnit) {
Douglas Gregorabc563f2010-07-19 21:46:24 +00001033 if (!Diags.getPtr()) {
1034 // No diagnostics engine was provided, so create our own diagnostics object
1035 // with the default options.
1036 DiagnosticOptions DiagOpts;
1037 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
1038 }
1039
1040 // Create the AST unit.
1041 llvm::OwningPtr<ASTUnit> AST;
1042 AST.reset(new ASTUnit(false));
1043 AST->Diagnostics = Diags;
1044 AST->CaptureDiagnostics = CaptureDiagnostics;
1045 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregordf95a132010-08-09 20:45:32 +00001046 AST->CompleteTranslationUnit = CompleteTranslationUnit;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001047 AST->Invocation.reset(CI);
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001048 CI->getPreprocessorOpts().RetainRemappedFileBuffers = true;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001049
Douglas Gregor385103b2010-07-30 20:58:08 +00001050 if (getenv("LIBCLANG_TIMING"))
1051 AST->TimerGroup.reset(
1052 new llvm::TimerGroup(CI->getFrontendOpts().Inputs[0].second));
1053
1054
Douglas Gregor754f3492010-07-24 00:38:13 +00001055 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Douglas Gregorfd0b8702010-07-28 22:12:37 +00001056 // FIXME: When C++ PCH is ready, allow use of it for a precompiled preamble.
Douglas Gregoreababfb2010-08-04 05:53:38 +00001057 if (PrecompilePreamble && !CI->getLangOpts().CPlusPlus) {
1058 AST->PreambleRebuildCounter = 1;
Douglas Gregordf95a132010-08-09 20:45:32 +00001059 OverrideMainBuffer = AST->getMainBufferWithPrecompiledPreamble();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001060 }
Douglas Gregor44c181a2010-07-23 00:33:23 +00001061
Douglas Gregor385103b2010-07-30 20:58:08 +00001062 llvm::Timer *ParsingTimer = 0;
1063 if (AST->TimerGroup.get()) {
1064 ParsingTimer = new llvm::Timer("Initial parse", *AST->TimerGroup);
1065 ParsingTimer->startTimer();
1066 AST->Timers.push_back(ParsingTimer);
1067 }
Douglas Gregorabc563f2010-07-19 21:46:24 +00001068
Douglas Gregor385103b2010-07-30 20:58:08 +00001069 bool Failed = AST->Parse(OverrideMainBuffer);
1070 if (ParsingTimer)
1071 ParsingTimer->stopTimer();
1072
1073 return Failed? 0 : AST.take();
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001074}
Daniel Dunbar7b556682009-12-02 03:23:45 +00001075
1076ASTUnit *ASTUnit::LoadFromCommandLine(const char **ArgBegin,
1077 const char **ArgEnd,
Douglas Gregor28019772010-04-05 23:52:57 +00001078 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
Daniel Dunbar869824e2009-12-13 03:46:13 +00001079 llvm::StringRef ResourceFilesPath,
Daniel Dunbar7b556682009-12-02 03:23:45 +00001080 bool OnlyLocalDecls,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001081 RemappedFile *RemappedFiles,
Douglas Gregora88084b2010-02-18 18:08:43 +00001082 unsigned NumRemappedFiles,
Douglas Gregor44c181a2010-07-23 00:33:23 +00001083 bool CaptureDiagnostics,
Douglas Gregordf95a132010-08-09 20:45:32 +00001084 bool PrecompilePreamble,
1085 bool CompleteTranslationUnit) {
Douglas Gregor28019772010-04-05 23:52:57 +00001086 if (!Diags.getPtr()) {
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001087 // No diagnostics engine was provided, so create our own diagnostics object
1088 // with the default options.
1089 DiagnosticOptions DiagOpts;
Douglas Gregor28019772010-04-05 23:52:57 +00001090 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001091 }
1092
Daniel Dunbar7b556682009-12-02 03:23:45 +00001093 llvm::SmallVector<const char *, 16> Args;
1094 Args.push_back("<clang>"); // FIXME: Remove dummy argument.
1095 Args.insert(Args.end(), ArgBegin, ArgEnd);
1096
1097 // FIXME: Find a cleaner way to force the driver into restricted modes. We
1098 // also want to force it to use clang.
1099 Args.push_back("-fsyntax-only");
1100
Daniel Dunbar869824e2009-12-13 03:46:13 +00001101 // FIXME: We shouldn't have to pass in the path info.
Daniel Dunbar0bbad512010-07-19 00:44:04 +00001102 driver::Driver TheDriver("clang", llvm::sys::getHostTriple(),
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001103 "a.out", false, false, *Diags);
Daniel Dunbar3bd54cc2010-01-25 00:44:02 +00001104
1105 // Don't check that inputs exist, they have been remapped.
1106 TheDriver.setCheckInputsExist(false);
1107
Daniel Dunbar7b556682009-12-02 03:23:45 +00001108 llvm::OwningPtr<driver::Compilation> C(
1109 TheDriver.BuildCompilation(Args.size(), Args.data()));
1110
1111 // We expect to get back exactly one command job, if we didn't something
1112 // failed.
1113 const driver::JobList &Jobs = C->getJobs();
1114 if (Jobs.size() != 1 || !isa<driver::Command>(Jobs.begin())) {
1115 llvm::SmallString<256> Msg;
1116 llvm::raw_svector_ostream OS(Msg);
1117 C->PrintJob(OS, C->getJobs(), "; ", true);
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001118 Diags->Report(diag::err_fe_expected_compiler_job) << OS.str();
Daniel Dunbar7b556682009-12-02 03:23:45 +00001119 return 0;
1120 }
1121
1122 const driver::Command *Cmd = cast<driver::Command>(*Jobs.begin());
1123 if (llvm::StringRef(Cmd->getCreator().getName()) != "clang") {
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001124 Diags->Report(diag::err_fe_expected_clang_command);
Daniel Dunbar7b556682009-12-02 03:23:45 +00001125 return 0;
1126 }
1127
1128 const driver::ArgStringList &CCArgs = Cmd->getArguments();
Daniel Dunbar807b0612010-01-30 21:47:16 +00001129 llvm::OwningPtr<CompilerInvocation> CI(new CompilerInvocation);
Dan Gohmancb421fa2010-04-19 16:39:44 +00001130 CompilerInvocation::CreateFromArgs(*CI,
1131 const_cast<const char **>(CCArgs.data()),
1132 const_cast<const char **>(CCArgs.data()) +
Douglas Gregor44c181a2010-07-23 00:33:23 +00001133 CCArgs.size(),
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001134 *Diags);
Daniel Dunbar1e69fe32009-12-13 03:45:58 +00001135
Douglas Gregor4db64a42010-01-23 00:14:00 +00001136 // Override any files that need remapping
1137 for (unsigned I = 0; I != NumRemappedFiles; ++I)
Daniel Dunbar807b0612010-01-30 21:47:16 +00001138 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
Daniel Dunbarb26d4832010-02-16 01:55:04 +00001139 RemappedFiles[I].second);
Douglas Gregor4db64a42010-01-23 00:14:00 +00001140
Daniel Dunbar8b9adfe2009-12-15 00:06:45 +00001141 // Override the resources path.
Daniel Dunbar807b0612010-01-30 21:47:16 +00001142 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
Daniel Dunbar7b556682009-12-02 03:23:45 +00001143
Daniel Dunbarb26d4832010-02-16 01:55:04 +00001144 CI->getFrontendOpts().DisableFree = true;
Douglas Gregora88084b2010-02-18 18:08:43 +00001145 return LoadFromCompilerInvocation(CI.take(), Diags, OnlyLocalDecls,
Douglas Gregordf95a132010-08-09 20:45:32 +00001146 CaptureDiagnostics, PrecompilePreamble,
1147 CompleteTranslationUnit);
Daniel Dunbar7b556682009-12-02 03:23:45 +00001148}
Douglas Gregorabc563f2010-07-19 21:46:24 +00001149
1150bool ASTUnit::Reparse(RemappedFile *RemappedFiles, unsigned NumRemappedFiles) {
1151 if (!Invocation.get())
1152 return true;
1153
Douglas Gregor385103b2010-07-30 20:58:08 +00001154 llvm::Timer *ReparsingTimer = 0;
1155 if (TimerGroup.get()) {
1156 ReparsingTimer = new llvm::Timer("Reparse", *TimerGroup);
1157 ReparsingTimer->startTimer();
1158 Timers.push_back(ReparsingTimer);
1159 }
1160
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001161 // Remap files.
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001162 Invocation->getPreprocessorOpts().clearRemappedFiles();
1163 for (unsigned I = 0; I != NumRemappedFiles; ++I)
1164 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
1165 RemappedFiles[I].second);
1166
Douglas Gregoreababfb2010-08-04 05:53:38 +00001167 // If we have a preamble file lying around, or if we might try to
1168 // build a precompiled preamble, do so now.
Douglas Gregor754f3492010-07-24 00:38:13 +00001169 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Douglas Gregoreababfb2010-08-04 05:53:38 +00001170 if (!PreambleFile.empty() || PreambleRebuildCounter > 0)
Douglas Gregordf95a132010-08-09 20:45:32 +00001171 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001172
Douglas Gregorabc563f2010-07-19 21:46:24 +00001173 // Clear out the diagnostics state.
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001174 if (!OverrideMainBuffer)
1175 getDiagnostics().Reset();
Douglas Gregorabc563f2010-07-19 21:46:24 +00001176
Douglas Gregor175c4a92010-07-23 23:58:40 +00001177 // Parse the sources
Douglas Gregor754f3492010-07-24 00:38:13 +00001178 bool Result = Parse(OverrideMainBuffer);
Douglas Gregor385103b2010-07-30 20:58:08 +00001179 if (ReparsingTimer)
1180 ReparsingTimer->stopTimer();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001181 return Result;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001182}
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001183
1184void ASTUnit::CodeComplete(llvm::StringRef File, unsigned Line, unsigned Column,
1185 RemappedFile *RemappedFiles,
1186 unsigned NumRemappedFiles,
Douglas Gregorcee235c2010-08-05 09:09:23 +00001187 bool IncludeMacros,
1188 bool IncludeCodePatterns,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001189 CodeCompleteConsumer &Consumer,
1190 Diagnostic &Diag, LangOptions &LangOpts,
1191 SourceManager &SourceMgr, FileManager &FileMgr,
1192 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics) {
1193 if (!Invocation.get())
1194 return;
1195
Douglas Gregordf95a132010-08-09 20:45:32 +00001196 llvm::Timer *CompletionTimer = 0;
1197 if (TimerGroup.get()) {
1198 llvm::SmallString<128> TimerName;
1199 llvm::raw_svector_ostream TimerNameOut(TimerName);
1200 TimerNameOut << "Code completion @ " << File << ":" << Line << ":"
1201 << Column;
1202 CompletionTimer = new llvm::Timer(TimerNameOut.str(), *TimerGroup);
1203 CompletionTimer->startTimer();
1204 Timers.push_back(CompletionTimer);
1205 }
1206
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001207 CompilerInvocation CCInvocation(*Invocation);
1208 FrontendOptions &FrontendOpts = CCInvocation.getFrontendOpts();
1209 PreprocessorOptions &PreprocessorOpts = CCInvocation.getPreprocessorOpts();
Douglas Gregorcee235c2010-08-05 09:09:23 +00001210
1211 FrontendOpts.ShowMacrosInCodeCompletion = IncludeMacros;
1212 FrontendOpts.ShowCodePatternsInCodeCompletion = IncludeCodePatterns;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001213 FrontendOpts.CodeCompletionAt.FileName = File;
1214 FrontendOpts.CodeCompletionAt.Line = Line;
1215 FrontendOpts.CodeCompletionAt.Column = Column;
1216
Douglas Gregorcee235c2010-08-05 09:09:23 +00001217 // Turn on spell-checking when performing code completion. It leads
1218 // to better results.
1219 unsigned SpellChecking = CCInvocation.getLangOpts().SpellChecking;
1220 CCInvocation.getLangOpts().SpellChecking = 1;
1221
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001222 // Set the language options appropriately.
1223 LangOpts = CCInvocation.getLangOpts();
1224
1225 CompilerInstance Clang;
1226 Clang.setInvocation(&CCInvocation);
1227 OriginalSourceFile = Clang.getFrontendOpts().Inputs[0].second;
1228
1229 // Set up diagnostics, capturing any diagnostics produced.
1230 Clang.setDiagnostics(&Diag);
1231 CaptureDroppedDiagnostics Capture(true,
1232 Clang.getDiagnostics(),
1233 StoredDiagnostics);
1234 Clang.setDiagnosticClient(Diag.getClient());
1235
1236 // Create the target instance.
1237 Clang.setTarget(TargetInfo::CreateTargetInfo(Clang.getDiagnostics(),
1238 Clang.getTargetOpts()));
1239 if (!Clang.hasTarget()) {
1240 Clang.takeDiagnosticClient();
1241 Clang.takeInvocation();
1242 }
1243
1244 // Inform the target of the language options.
1245 //
1246 // FIXME: We shouldn't need to do this, the target should be immutable once
1247 // created. This complexity should be lifted elsewhere.
1248 Clang.getTarget().setForcedLangOptions(Clang.getLangOpts());
1249
1250 assert(Clang.getFrontendOpts().Inputs.size() == 1 &&
1251 "Invocation must have exactly one source file!");
1252 assert(Clang.getFrontendOpts().Inputs[0].first != IK_AST &&
1253 "FIXME: AST inputs not yet supported here!");
1254 assert(Clang.getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
1255 "IR inputs not support here!");
1256
1257
1258 // Use the source and file managers that we were given.
1259 Clang.setFileManager(&FileMgr);
1260 Clang.setSourceManager(&SourceMgr);
1261
1262 // Remap files.
1263 PreprocessorOpts.clearRemappedFiles();
Douglas Gregorb75d3df2010-08-04 17:07:00 +00001264 PreprocessorOpts.RetainRemappedFileBuffers = true;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001265 for (unsigned I = 0; I != NumRemappedFiles; ++I)
1266 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first,
1267 RemappedFiles[I].second);
1268
1269 // Use the code completion consumer we were given.
1270 Clang.setCodeCompletionConsumer(&Consumer);
1271
Douglas Gregordf95a132010-08-09 20:45:32 +00001272 // If we have a precompiled preamble, try to use it. We only allow
1273 // the use of the precompiled preamble if we're if the completion
1274 // point is within the main file, after the end of the precompiled
1275 // preamble.
1276 llvm::MemoryBuffer *OverrideMainBuffer = 0;
1277 if (!PreambleFile.empty()) {
1278 using llvm::sys::FileStatus;
1279 llvm::sys::PathWithStatus CompleteFilePath(File);
1280 llvm::sys::PathWithStatus MainPath(OriginalSourceFile);
1281 if (const FileStatus *CompleteFileStatus = CompleteFilePath.getFileStatus())
1282 if (const FileStatus *MainStatus = MainPath.getFileStatus())
1283 if (CompleteFileStatus->getUniqueID() == MainStatus->getUniqueID())
1284 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(false,
1285 Line);
1286 }
1287
1288 // If the main file has been overridden due to the use of a preamble,
1289 // make that override happen and introduce the preamble.
1290 if (OverrideMainBuffer) {
1291 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
1292 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
1293 PreprocessorOpts.PrecompiledPreambleBytes.second
1294 = PreambleEndsAtStartOfLine;
1295 PreprocessorOpts.ImplicitPCHInclude = PreambleFile;
1296 PreprocessorOpts.DisablePCHValidation = true;
1297
1298 // The stored diagnostics have the old source manager. Copy them
1299 // to our output set of stored diagnostics, updating the source
1300 // manager to the one we were given.
1301 for (unsigned I = 0, N = this->StoredDiagnostics.size(); I != N; ++I) {
1302 StoredDiagnostics.push_back(this->StoredDiagnostics[I]);
1303 FullSourceLoc Loc(StoredDiagnostics[I].getLocation(), SourceMgr);
1304 StoredDiagnostics[I].setLocation(Loc);
1305 }
1306 }
1307
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001308 llvm::OwningPtr<SyntaxOnlyAction> Act;
1309 Act.reset(new SyntaxOnlyAction);
1310 if (Act->BeginSourceFile(Clang, Clang.getFrontendOpts().Inputs[0].second,
1311 Clang.getFrontendOpts().Inputs[0].first)) {
1312 Act->Execute();
1313 Act->EndSourceFile();
1314 }
Douglas Gregordf95a132010-08-09 20:45:32 +00001315
1316 if (CompletionTimer)
1317 CompletionTimer->stopTimer();
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001318
1319 // Steal back our resources.
Douglas Gregordf95a132010-08-09 20:45:32 +00001320 delete OverrideMainBuffer;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001321 Clang.takeFileManager();
1322 Clang.takeSourceManager();
1323 Clang.takeInvocation();
1324 Clang.takeDiagnosticClient();
1325 Clang.takeCodeCompletionConsumer();
Douglas Gregorcee235c2010-08-05 09:09:23 +00001326 CCInvocation.getLangOpts().SpellChecking = SpellChecking;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001327}