blob: a573fb41ab649a678fb61c895c705a925db240cf [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),
Douglas Gregor87c08a52010-08-13 22:48:40 +000053 PreambleRebuildCounter(0), SavedMainFileBuffer(0),
54 ShouldCacheCodeCompletionResults(false) {
Douglas Gregor385103b2010-07-30 20:58:08 +000055}
Douglas Gregor3687e9d2010-04-05 21:10:19 +000056
Daniel Dunbar521bf9c2009-12-01 09:51:01 +000057ASTUnit::~ASTUnit() {
Douglas Gregorbdf60622010-03-05 21:16:25 +000058 ConcurrencyCheckValue = CheckLocked;
Douglas Gregorabc563f2010-07-19 21:46:24 +000059 CleanTemporaryFiles();
Douglas Gregor175c4a92010-07-23 23:58:40 +000060 if (!PreambleFile.empty())
Douglas Gregor385103b2010-07-30 20:58:08 +000061 llvm::sys::Path(PreambleFile).eraseFromDisk();
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +000062
63 // Free the buffers associated with remapped files. We are required to
64 // perform this operation here because we explicitly request that the
65 // compiler instance *not* free these buffers for each invocation of the
66 // parser.
67 if (Invocation.get()) {
68 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
69 for (PreprocessorOptions::remapped_file_buffer_iterator
70 FB = PPOpts.remapped_file_buffer_begin(),
71 FBEnd = PPOpts.remapped_file_buffer_end();
72 FB != FBEnd;
73 ++FB)
74 delete FB->second;
75 }
Douglas Gregor28233422010-07-27 14:52:07 +000076
77 delete SavedMainFileBuffer;
Douglas Gregor385103b2010-07-30 20:58:08 +000078
Douglas Gregor87c08a52010-08-13 22:48:40 +000079 ClearCachedCompletionResults();
80
Douglas Gregor385103b2010-07-30 20:58:08 +000081 for (unsigned I = 0, N = Timers.size(); I != N; ++I)
82 delete Timers[I];
Douglas Gregorabc563f2010-07-19 21:46:24 +000083}
84
85void ASTUnit::CleanTemporaryFiles() {
Douglas Gregor313e26c2010-02-18 23:35:40 +000086 for (unsigned I = 0, N = TemporaryFiles.size(); I != N; ++I)
87 TemporaryFiles[I].eraseFromDisk();
Douglas Gregorabc563f2010-07-19 21:46:24 +000088 TemporaryFiles.clear();
Steve Naroffe19944c2009-10-15 22:23:48 +000089}
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000090
Douglas Gregor8071e422010-08-15 06:18:01 +000091/// \brief Determine the set of code-completion contexts in which this
92/// declaration should be shown.
93static unsigned getDeclShowContexts(NamedDecl *ND,
94 const LangOptions &LangOpts) {
95 if (isa<UsingShadowDecl>(ND))
96 ND = dyn_cast<NamedDecl>(ND->getUnderlyingDecl());
97 if (!ND)
98 return 0;
99
100 unsigned Contexts = 0;
101 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND) ||
102 isa<ClassTemplateDecl>(ND) || isa<TemplateTemplateParmDecl>(ND)) {
103 // Types can appear in these contexts.
104 if (LangOpts.CPlusPlus || !isa<TagDecl>(ND))
105 Contexts |= (1 << (CodeCompletionContext::CCC_TopLevel - 1))
106 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
107 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
108 | (1 << (CodeCompletionContext::CCC_Statement - 1))
109 | (1 << (CodeCompletionContext::CCC_Type - 1));
110
111 // In C++, types can appear in expressions contexts (for functional casts).
112 if (LangOpts.CPlusPlus)
113 Contexts |= (1 << (CodeCompletionContext::CCC_Expression - 1));
114
115 // In Objective-C, message sends can send interfaces. In Objective-C++,
116 // all types are available due to functional casts.
117 if (LangOpts.CPlusPlus || isa<ObjCInterfaceDecl>(ND))
118 Contexts |= (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1));
119
120 // Deal with tag names.
121 if (isa<EnumDecl>(ND)) {
122 Contexts |= (1 << (CodeCompletionContext::CCC_EnumTag - 1));
123
124 // Part of the nested-name-specifier.
125 if (LangOpts.CPlusPlus0x)
126 Contexts |= (1 << (CodeCompletionContext::CCC_MemberAccess - 1));
127 } else if (RecordDecl *Record = dyn_cast<RecordDecl>(ND)) {
128 if (Record->isUnion())
129 Contexts |= (1 << (CodeCompletionContext::CCC_UnionTag - 1));
130 else
131 Contexts |= (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1));
132
133 // Part of the nested-name-specifier.
134 if (LangOpts.CPlusPlus)
135 Contexts |= (1 << (CodeCompletionContext::CCC_MemberAccess - 1));
136 }
137 } else if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
138 // Values can appear in these contexts.
139 Contexts = (1 << (CodeCompletionContext::CCC_Statement - 1))
140 | (1 << (CodeCompletionContext::CCC_Expression - 1))
141 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1));
142 } else if (isa<ObjCProtocolDecl>(ND)) {
143 Contexts = (1 << (CodeCompletionContext::CCC_ObjCProtocolName - 1));
144 } else if (isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) {
145 Contexts = (1 << (CodeCompletionContext::CCC_TopLevel - 1))
146 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
147 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
148 | (1 << (CodeCompletionContext::CCC_Statement - 1))
149 | (1 << (CodeCompletionContext::CCC_Expression - 1))
150 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
151 | (1 << (CodeCompletionContext::CCC_Namespace - 1));
152
153 // Part of the nested-name-specifier.
154 Contexts |= (1 << (CodeCompletionContext::CCC_MemberAccess - 1))
155 | (1 << (CodeCompletionContext::CCC_EnumTag - 1))
156 | (1 << (CodeCompletionContext::CCC_UnionTag - 1))
157 | (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1))
158 | (1 << (CodeCompletionContext::CCC_Type - 1));
159 }
160
161 return Contexts;
162}
163
Douglas Gregor87c08a52010-08-13 22:48:40 +0000164void ASTUnit::CacheCodeCompletionResults() {
165 if (!TheSema)
166 return;
167
168 llvm::Timer *CachingTimer = 0;
169 if (TimerGroup.get()) {
170 CachingTimer = new llvm::Timer("Cache global code completions",
171 *TimerGroup);
172 CachingTimer->startTimer();
173 Timers.push_back(CachingTimer);
174 }
175
176 // Clear out the previous results.
177 ClearCachedCompletionResults();
178
179 // Gather the set of global code completions.
180 typedef CodeCompleteConsumer::Result Result;
181 llvm::SmallVector<Result, 8> Results;
182 TheSema->GatherGlobalCodeCompletions(Results);
183
184 // Translate global code completions into cached completions.
185 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
186 switch (Results[I].Kind) {
Douglas Gregor8071e422010-08-15 06:18:01 +0000187 case Result::RK_Declaration: {
188 CachedCodeCompletionResult CachedResult;
189 CachedResult.Completion = Results[I].CreateCodeCompletionString(*TheSema);
190 CachedResult.ShowInContexts = getDeclShowContexts(Results[I].Declaration,
191 Ctx->getLangOptions());
192 CachedResult.Priority = Results[I].Priority;
193 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregor1827e102010-08-16 16:18:59 +0000194 CachedResult.TypeClass
195 = getSimplifiedTypeClass(
196 Ctx->getCanonicalType(getDeclUsageType(*Ctx,
197 Results[I].Declaration)));
Douglas Gregor8071e422010-08-15 06:18:01 +0000198 CachedCompletionResults.push_back(CachedResult);
Douglas Gregor87c08a52010-08-13 22:48:40 +0000199 break;
Douglas Gregor8071e422010-08-15 06:18:01 +0000200 }
201
Douglas Gregor87c08a52010-08-13 22:48:40 +0000202 case Result::RK_Keyword:
203 case Result::RK_Pattern:
204 // Ignore keywords and patterns; we don't care, since they are so
205 // easily regenerated.
206 break;
207
208 case Result::RK_Macro: {
209 CachedCodeCompletionResult CachedResult;
210 CachedResult.Completion = Results[I].CreateCodeCompletionString(*TheSema);
211 CachedResult.ShowInContexts
212 = (1 << (CodeCompletionContext::CCC_TopLevel - 1))
213 | (1 << (CodeCompletionContext::CCC_ObjCInterface - 1))
214 | (1 << (CodeCompletionContext::CCC_ObjCImplementation - 1))
215 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
216 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
217 | (1 << (CodeCompletionContext::CCC_Statement - 1))
218 | (1 << (CodeCompletionContext::CCC_Expression - 1))
219 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1));
220 CachedResult.Priority = Results[I].Priority;
221 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregor1827e102010-08-16 16:18:59 +0000222 CachedResult.TypeClass = STC_Void;
Douglas Gregor87c08a52010-08-13 22:48:40 +0000223 CachedCompletionResults.push_back(CachedResult);
224 break;
225 }
226 }
227 Results[I].Destroy();
228 }
229
230 if (CachingTimer)
231 CachingTimer->stopTimer();
232}
233
234void ASTUnit::ClearCachedCompletionResults() {
235 for (unsigned I = 0, N = CachedCompletionResults.size(); I != N; ++I)
236 delete CachedCompletionResults[I].Completion;
237 CachedCompletionResults.clear();
238}
239
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000240namespace {
241
242/// \brief Gathers information from PCHReader that will be used to initialize
243/// a Preprocessor.
Benjamin Kramerbd218282009-11-28 10:07:24 +0000244class PCHInfoCollector : public PCHReaderListener {
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000245 LangOptions &LangOpt;
246 HeaderSearch &HSI;
247 std::string &TargetTriple;
248 std::string &Predefines;
249 unsigned &Counter;
Mike Stump1eb44332009-09-09 15:08:12 +0000250
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000251 unsigned NumHeaderInfos;
Mike Stump1eb44332009-09-09 15:08:12 +0000252
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000253public:
254 PCHInfoCollector(LangOptions &LangOpt, HeaderSearch &HSI,
255 std::string &TargetTriple, std::string &Predefines,
256 unsigned &Counter)
257 : LangOpt(LangOpt), HSI(HSI), TargetTriple(TargetTriple),
258 Predefines(Predefines), Counter(Counter), NumHeaderInfos(0) {}
Mike Stump1eb44332009-09-09 15:08:12 +0000259
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000260 virtual bool ReadLanguageOptions(const LangOptions &LangOpts) {
261 LangOpt = LangOpts;
262 return false;
263 }
Mike Stump1eb44332009-09-09 15:08:12 +0000264
Daniel Dunbardc3c0d22009-11-11 00:52:11 +0000265 virtual bool ReadTargetTriple(llvm::StringRef Triple) {
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000266 TargetTriple = Triple;
267 return false;
268 }
Mike Stump1eb44332009-09-09 15:08:12 +0000269
Sebastian Redlcb481aa2010-07-14 23:29:55 +0000270 virtual bool ReadPredefinesBuffer(const PCHPredefinesBlocks &Buffers,
Daniel Dunbar7b5a1212009-11-11 05:29:04 +0000271 llvm::StringRef OriginalFileName,
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000272 std::string &SuggestedPredefines) {
Sebastian Redlcb481aa2010-07-14 23:29:55 +0000273 Predefines = Buffers[0].Data;
274 for (unsigned I = 1, N = Buffers.size(); I != N; ++I) {
275 Predefines += Buffers[I].Data;
276 }
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000277 return false;
278 }
Mike Stump1eb44332009-09-09 15:08:12 +0000279
Douglas Gregorec1afbf2010-03-16 19:09:18 +0000280 virtual void ReadHeaderFileInfo(const HeaderFileInfo &HFI, unsigned ID) {
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000281 HSI.setHeaderFileInfoForUID(HFI, NumHeaderInfos++);
282 }
Mike Stump1eb44332009-09-09 15:08:12 +0000283
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000284 virtual void ReadCounter(unsigned Value) {
285 Counter = Value;
286 }
287};
288
Douglas Gregora88084b2010-02-18 18:08:43 +0000289class StoredDiagnosticClient : public DiagnosticClient {
290 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiags;
291
292public:
293 explicit StoredDiagnosticClient(
294 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiags)
295 : StoredDiags(StoredDiags) { }
296
297 virtual void HandleDiagnostic(Diagnostic::Level Level,
298 const DiagnosticInfo &Info);
299};
300
301/// \brief RAII object that optionally captures diagnostics, if
302/// there is no diagnostic client to capture them already.
303class CaptureDroppedDiagnostics {
304 Diagnostic &Diags;
305 StoredDiagnosticClient Client;
306 DiagnosticClient *PreviousClient;
307
308public:
309 CaptureDroppedDiagnostics(bool RequestCapture, Diagnostic &Diags,
310 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiags)
311 : Diags(Diags), Client(StoredDiags), PreviousClient(Diags.getClient())
312 {
313 if (RequestCapture || Diags.getClient() == 0)
314 Diags.setClient(&Client);
315 }
316
317 ~CaptureDroppedDiagnostics() {
318 Diags.setClient(PreviousClient);
319 }
320};
321
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000322} // anonymous namespace
323
Douglas Gregora88084b2010-02-18 18:08:43 +0000324void StoredDiagnosticClient::HandleDiagnostic(Diagnostic::Level Level,
325 const DiagnosticInfo &Info) {
326 StoredDiags.push_back(StoredDiagnostic(Level, Info));
327}
328
Steve Naroff77accc12009-09-03 18:19:54 +0000329const std::string &ASTUnit::getOriginalSourceFileName() {
Daniel Dunbar68d40e22009-12-02 08:44:16 +0000330 return OriginalSourceFile;
Steve Naroff77accc12009-09-03 18:19:54 +0000331}
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000332
Steve Naroffe19944c2009-10-15 22:23:48 +0000333const std::string &ASTUnit::getPCHFileName() {
Daniel Dunbarc7822db2009-12-02 21:47:43 +0000334 assert(isMainFileAST() && "Not an ASTUnit from a PCH file!");
Benjamin Kramer7297c182010-01-30 16:23:25 +0000335 return static_cast<PCHReader *>(Ctx->getExternalSource())->getFileName();
Steve Naroffe19944c2009-10-15 22:23:48 +0000336}
337
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000338ASTUnit *ASTUnit::LoadFromPCHFile(const std::string &Filename,
Douglas Gregor28019772010-04-05 23:52:57 +0000339 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
Ted Kremenek5cf48762009-10-17 00:34:24 +0000340 bool OnlyLocalDecls,
Douglas Gregor4db64a42010-01-23 00:14:00 +0000341 RemappedFile *RemappedFiles,
Douglas Gregora88084b2010-02-18 18:08:43 +0000342 unsigned NumRemappedFiles,
343 bool CaptureDiagnostics) {
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000344 llvm::OwningPtr<ASTUnit> AST(new ASTUnit(true));
345
Douglas Gregor28019772010-04-05 23:52:57 +0000346 if (!Diags.getPtr()) {
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000347 // No diagnostics engine was provided, so create our own diagnostics object
348 // with the default options.
349 DiagnosticOptions DiagOpts;
Douglas Gregor28019772010-04-05 23:52:57 +0000350 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000351 }
Douglas Gregorabc563f2010-07-19 21:46:24 +0000352
353 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000354 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor28019772010-04-05 23:52:57 +0000355 AST->Diagnostics = Diags;
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000356 AST->FileMgr.reset(new FileManager);
357 AST->SourceMgr.reset(new SourceManager(AST->getDiagnostics()));
Steve Naroff36c44642009-10-19 14:34:22 +0000358 AST->HeaderInfo.reset(new HeaderSearch(AST->getFileManager()));
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000359
Douglas Gregora88084b2010-02-18 18:08:43 +0000360 // If requested, capture diagnostics in the ASTUnit.
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000361 CaptureDroppedDiagnostics Capture(CaptureDiagnostics, AST->getDiagnostics(),
Douglas Gregor405634b2010-04-05 18:10:21 +0000362 AST->StoredDiagnostics);
Douglas Gregora88084b2010-02-18 18:08:43 +0000363
Douglas Gregor4db64a42010-01-23 00:14:00 +0000364 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
365 // Create the file entry for the file that we're mapping from.
366 const FileEntry *FromFile
367 = AST->getFileManager().getVirtualFile(RemappedFiles[I].first,
368 RemappedFiles[I].second->getBufferSize(),
369 0);
370 if (!FromFile) {
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000371 AST->getDiagnostics().Report(diag::err_fe_remap_missing_from_file)
Douglas Gregor4db64a42010-01-23 00:14:00 +0000372 << RemappedFiles[I].first;
Douglas Gregorc8dfe5e2010-02-27 01:32:48 +0000373 delete RemappedFiles[I].second;
Douglas Gregor4db64a42010-01-23 00:14:00 +0000374 continue;
375 }
376
377 // Override the contents of the "from" file with the contents of
378 // the "to" file.
379 AST->getSourceManager().overrideFileContents(FromFile,
380 RemappedFiles[I].second);
381 }
382
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000383 // Gather Info for preprocessor construction later on.
Mike Stump1eb44332009-09-09 15:08:12 +0000384
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000385 LangOptions LangInfo;
386 HeaderSearch &HeaderInfo = *AST->HeaderInfo.get();
387 std::string TargetTriple;
388 std::string Predefines;
389 unsigned Counter;
390
Daniel Dunbarbce6f622009-09-03 05:59:50 +0000391 llvm::OwningPtr<PCHReader> Reader;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000392
Ted Kremenekfc062212009-10-19 21:44:57 +0000393 Reader.reset(new PCHReader(AST->getSourceManager(), AST->getFileManager(),
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000394 AST->getDiagnostics()));
Daniel Dunbarcc318932009-09-03 05:59:35 +0000395 Reader->setListener(new PCHInfoCollector(LangInfo, HeaderInfo, TargetTriple,
396 Predefines, Counter));
397
398 switch (Reader->ReadPCH(Filename)) {
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000399 case PCHReader::Success:
400 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000401
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000402 case PCHReader::Failure:
Argyrios Kyrtzidis106c9982009-06-25 18:22:30 +0000403 case PCHReader::IgnorePCH:
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000404 AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000405 return NULL;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000406 }
Mike Stump1eb44332009-09-09 15:08:12 +0000407
Daniel Dunbar68d40e22009-12-02 08:44:16 +0000408 AST->OriginalSourceFile = Reader->getOriginalSourceFile();
409
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000410 // PCH loaded successfully. Now create the preprocessor.
Mike Stump1eb44332009-09-09 15:08:12 +0000411
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000412 // Get information about the target being compiled for.
Daniel Dunbard58c03f2009-11-15 06:48:46 +0000413 //
414 // FIXME: This is broken, we should store the TargetOptions in the PCH.
415 TargetOptions TargetOpts;
416 TargetOpts.ABI = "";
Charles Davis98b7c5c2010-06-11 01:06:47 +0000417 TargetOpts.CXXABI = "itanium";
Daniel Dunbard58c03f2009-11-15 06:48:46 +0000418 TargetOpts.CPU = "";
419 TargetOpts.Features.clear();
420 TargetOpts.Triple = TargetTriple;
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000421 AST->Target.reset(TargetInfo::CreateTargetInfo(AST->getDiagnostics(),
422 TargetOpts));
423 AST->PP.reset(new Preprocessor(AST->getDiagnostics(), LangInfo,
424 *AST->Target.get(),
Daniel Dunbar31b87d82009-09-21 03:03:39 +0000425 AST->getSourceManager(), HeaderInfo));
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000426 Preprocessor &PP = *AST->PP.get();
427
Daniel Dunbard5b61262009-09-21 03:03:47 +0000428 PP.setPredefines(Reader->getSuggestedPredefines());
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000429 PP.setCounterValue(Counter);
Daniel Dunbarcc318932009-09-03 05:59:35 +0000430 Reader->setPreprocessor(PP);
Mike Stump1eb44332009-09-09 15:08:12 +0000431
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000432 // Create and initialize the ASTContext.
433
434 AST->Ctx.reset(new ASTContext(LangInfo,
Daniel Dunbar31b87d82009-09-21 03:03:39 +0000435 AST->getSourceManager(),
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000436 *AST->Target.get(),
437 PP.getIdentifierTable(),
438 PP.getSelectorTable(),
439 PP.getBuiltinInfo(),
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000440 /* size_reserve = */0));
441 ASTContext &Context = *AST->Ctx.get();
Mike Stump1eb44332009-09-09 15:08:12 +0000442
Daniel Dunbarcc318932009-09-03 05:59:35 +0000443 Reader->InitializeContext(Context);
Mike Stump1eb44332009-09-09 15:08:12 +0000444
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000445 // Attach the PCH reader to the AST context as an external AST
446 // source, so that declarations will be deserialized from the
447 // PCH file as needed.
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000448 PCHReader *ReaderPtr = Reader.get();
449 llvm::OwningPtr<ExternalASTSource> Source(Reader.take());
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000450 Context.setExternalSource(Source);
451
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000452 // Create an AST consumer, even though it isn't used.
453 AST->Consumer.reset(new ASTConsumer);
454
455 // Create a semantic analysis object and tell the PCH reader about it.
456 AST->TheSema.reset(new Sema(PP, Context, *AST->Consumer));
457 AST->TheSema->Initialize();
458 ReaderPtr->InitializeSema(*AST->TheSema);
459
Mike Stump1eb44332009-09-09 15:08:12 +0000460 return AST.take();
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000461}
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000462
463namespace {
464
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000465class TopLevelDeclTrackerConsumer : public ASTConsumer {
466 ASTUnit &Unit;
467
468public:
469 TopLevelDeclTrackerConsumer(ASTUnit &_Unit) : Unit(_Unit) {}
470
471 void HandleTopLevelDecl(DeclGroupRef D) {
Ted Kremenekda5a4282010-05-03 20:16:35 +0000472 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
473 Decl *D = *it;
474 // FIXME: Currently ObjC method declarations are incorrectly being
475 // reported as top-level declarations, even though their DeclContext
476 // is the containing ObjC @interface/@implementation. This is a
477 // fundamental problem in the parser right now.
478 if (isa<ObjCMethodDecl>(D))
479 continue;
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000480 Unit.addTopLevelDecl(D);
Ted Kremenekda5a4282010-05-03 20:16:35 +0000481 }
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000482 }
Sebastian Redl27372b42010-08-11 18:52:41 +0000483
484 // We're not interested in "interesting" decls.
485 void HandleInterestingDecl(DeclGroupRef) {}
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000486};
487
488class TopLevelDeclTrackerAction : public ASTFrontendAction {
489public:
490 ASTUnit &Unit;
491
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000492 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
493 llvm::StringRef InFile) {
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000494 return new TopLevelDeclTrackerConsumer(Unit);
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000495 }
496
497public:
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000498 TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {}
499
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000500 virtual bool hasCodeCompletionSupport() const { return false; }
Douglas Gregordf95a132010-08-09 20:45:32 +0000501 virtual bool usesCompleteTranslationUnit() {
502 return Unit.isCompleteTranslationUnit();
503 }
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000504};
505
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000506class PrecompilePreambleConsumer : public PCHGenerator {
507 ASTUnit &Unit;
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000508 std::vector<Decl *> TopLevelDecls;
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000509
510public:
511 PrecompilePreambleConsumer(ASTUnit &Unit,
512 const Preprocessor &PP, bool Chaining,
513 const char *isysroot, llvm::raw_ostream *Out)
514 : PCHGenerator(PP, Chaining, isysroot, Out), Unit(Unit) { }
515
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000516 virtual void HandleTopLevelDecl(DeclGroupRef D) {
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000517 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
518 Decl *D = *it;
519 // FIXME: Currently ObjC method declarations are incorrectly being
520 // reported as top-level declarations, even though their DeclContext
521 // is the containing ObjC @interface/@implementation. This is a
522 // fundamental problem in the parser right now.
523 if (isa<ObjCMethodDecl>(D))
524 continue;
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000525 TopLevelDecls.push_back(D);
526 }
527 }
528
529 virtual void HandleTranslationUnit(ASTContext &Ctx) {
530 PCHGenerator::HandleTranslationUnit(Ctx);
531 if (!Unit.getDiagnostics().hasErrorOccurred()) {
532 // Translate the top-level declarations we captured during
533 // parsing into declaration IDs in the precompiled
534 // preamble. This will allow us to deserialize those top-level
535 // declarations when requested.
536 for (unsigned I = 0, N = TopLevelDecls.size(); I != N; ++I)
537 Unit.addTopLevelDeclFromPreamble(
538 getWriter().getDeclID(TopLevelDecls[I]));
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000539 }
540 }
541};
542
543class PrecompilePreambleAction : public ASTFrontendAction {
544 ASTUnit &Unit;
545
546public:
547 explicit PrecompilePreambleAction(ASTUnit &Unit) : Unit(Unit) {}
548
549 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
550 llvm::StringRef InFile) {
551 std::string Sysroot;
552 llvm::raw_ostream *OS = 0;
553 bool Chaining;
554 if (GeneratePCHAction::ComputeASTConsumerArguments(CI, InFile, Sysroot,
555 OS, Chaining))
556 return 0;
557
558 const char *isysroot = CI.getFrontendOpts().RelocatablePCH ?
559 Sysroot.c_str() : 0;
560 return new PrecompilePreambleConsumer(Unit, CI.getPreprocessor(), Chaining,
561 isysroot, OS);
562 }
563
564 virtual bool hasCodeCompletionSupport() const { return false; }
565 virtual bool hasASTFileSupport() const { return false; }
Douglas Gregordf95a132010-08-09 20:45:32 +0000566 virtual bool usesCompleteTranslationUnit() { return false; }
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000567};
568
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000569}
570
Douglas Gregorabc563f2010-07-19 21:46:24 +0000571/// Parse the source file into a translation unit using the given compiler
572/// invocation, replacing the current translation unit.
573///
574/// \returns True if a failure occurred that causes the ASTUnit not to
575/// contain any translation-unit information, false otherwise.
Douglas Gregor754f3492010-07-24 00:38:13 +0000576bool ASTUnit::Parse(llvm::MemoryBuffer *OverrideMainBuffer) {
Douglas Gregor28233422010-07-27 14:52:07 +0000577 delete SavedMainFileBuffer;
578 SavedMainFileBuffer = 0;
579
Douglas Gregorabc563f2010-07-19 21:46:24 +0000580 if (!Invocation.get())
581 return true;
582
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000583 // Create the compiler instance to use for building the AST.
Daniel Dunbarcb6dda12009-12-02 08:43:56 +0000584 CompilerInstance Clang;
Douglas Gregorabc563f2010-07-19 21:46:24 +0000585 Clang.setInvocation(Invocation.take());
586 OriginalSourceFile = Clang.getFrontendOpts().Inputs[0].second;
587
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000588 // Set up diagnostics, capturing any diagnostics that would
589 // otherwise be dropped.
Douglas Gregorabc563f2010-07-19 21:46:24 +0000590 Clang.setDiagnostics(&getDiagnostics());
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000591 CaptureDroppedDiagnostics Capture(CaptureDiagnostics,
592 getDiagnostics(),
593 StoredDiagnostics);
Douglas Gregorabc563f2010-07-19 21:46:24 +0000594 Clang.setDiagnosticClient(getDiagnostics().getClient());
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000595
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000596 // Create the target instance.
597 Clang.setTarget(TargetInfo::CreateTargetInfo(Clang.getDiagnostics(),
598 Clang.getTargetOpts()));
Douglas Gregora88084b2010-02-18 18:08:43 +0000599 if (!Clang.hasTarget()) {
Douglas Gregora88084b2010-02-18 18:08:43 +0000600 Clang.takeDiagnosticClient();
Douglas Gregorabc563f2010-07-19 21:46:24 +0000601 return true;
Douglas Gregora88084b2010-02-18 18:08:43 +0000602 }
Douglas Gregorabc563f2010-07-19 21:46:24 +0000603
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000604 // Inform the target of the language options.
605 //
606 // FIXME: We shouldn't need to do this, the target should be immutable once
607 // created. This complexity should be lifted elsewhere.
608 Clang.getTarget().setForcedLangOptions(Clang.getLangOpts());
Douglas Gregorabc563f2010-07-19 21:46:24 +0000609
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000610 assert(Clang.getFrontendOpts().Inputs.size() == 1 &&
611 "Invocation must have exactly one source file!");
Daniel Dunbarc34ce3f2010-06-07 23:22:09 +0000612 assert(Clang.getFrontendOpts().Inputs[0].first != IK_AST &&
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000613 "FIXME: AST inputs not yet supported here!");
Daniel Dunbarfaddc3e2010-06-07 23:26:47 +0000614 assert(Clang.getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
615 "IR inputs not support here!");
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000616
Douglas Gregorabc563f2010-07-19 21:46:24 +0000617 // Configure the various subsystems.
618 // FIXME: Should we retain the previous file manager?
619 FileMgr.reset(new FileManager);
620 SourceMgr.reset(new SourceManager(getDiagnostics()));
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000621 TheSema.reset();
Douglas Gregorabc563f2010-07-19 21:46:24 +0000622 Ctx.reset();
623 PP.reset();
624
625 // Clear out old caches and data.
626 TopLevelDecls.clear();
Douglas Gregorabc563f2010-07-19 21:46:24 +0000627 CleanTemporaryFiles();
628 PreprocessedEntitiesByFile.clear();
Douglas Gregorc0659ec2010-08-02 20:51:39 +0000629
630 if (!OverrideMainBuffer)
631 StoredDiagnostics.clear();
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000632
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000633 // Create a file manager object to provide access to and cache the filesystem.
Douglas Gregorabc563f2010-07-19 21:46:24 +0000634 Clang.setFileManager(&getFileManager());
635
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000636 // Create the source manager.
Douglas Gregorabc563f2010-07-19 21:46:24 +0000637 Clang.setSourceManager(&getSourceManager());
638
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000639 // If the main file has been overridden due to the use of a preamble,
640 // make that override happen and introduce the preamble.
641 PreprocessorOptions &PreprocessorOpts = Clang.getPreprocessorOpts();
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000642 std::string PriorImplicitPCHInclude;
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000643 if (OverrideMainBuffer) {
644 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
645 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
646 PreprocessorOpts.PrecompiledPreambleBytes.second
647 = PreambleEndsAtStartOfLine;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000648 PriorImplicitPCHInclude = PreprocessorOpts.ImplicitPCHInclude;
Douglas Gregor385103b2010-07-30 20:58:08 +0000649 PreprocessorOpts.ImplicitPCHInclude = PreambleFile;
Douglas Gregorfae3b2f2010-07-27 00:27:13 +0000650 PreprocessorOpts.DisablePCHValidation = true;
Douglas Gregor28233422010-07-27 14:52:07 +0000651
652 // Keep track of the override buffer;
653 SavedMainFileBuffer = OverrideMainBuffer;
Douglas Gregorc0659ec2010-08-02 20:51:39 +0000654
655 // The stored diagnostic has the old source manager in it; update
656 // the locations to refer into the new source manager. Since we've
657 // been careful to make sure that the source manager's state
658 // before and after are identical, so that we can reuse the source
659 // location itself.
660 for (unsigned I = 0, N = StoredDiagnostics.size(); I != N; ++I) {
661 FullSourceLoc Loc(StoredDiagnostics[I].getLocation(),
662 getSourceManager());
663 StoredDiagnostics[I].setLocation(Loc);
664 }
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000665 }
666
Douglas Gregorabc563f2010-07-19 21:46:24 +0000667 llvm::OwningPtr<TopLevelDeclTrackerAction> Act;
668 Act.reset(new TopLevelDeclTrackerAction(*this));
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000669 if (!Act->BeginSourceFile(Clang, Clang.getFrontendOpts().Inputs[0].second,
Daniel Dunbard3598a62010-06-07 23:23:06 +0000670 Clang.getFrontendOpts().Inputs[0].first))
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000671 goto error;
Douglas Gregorabc563f2010-07-19 21:46:24 +0000672
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000673 Act->Execute();
Douglas Gregorabc563f2010-07-19 21:46:24 +0000674
Daniel Dunbar64a32ba2009-12-01 21:57:33 +0000675 // Steal the created target, context, and preprocessor, and take back the
676 // source and file managers.
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000677 TheSema.reset(Clang.takeSema());
678 Consumer.reset(Clang.takeASTConsumer());
Douglas Gregorabc563f2010-07-19 21:46:24 +0000679 Ctx.reset(Clang.takeASTContext());
680 PP.reset(Clang.takePreprocessor());
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000681 Clang.takeSourceManager();
682 Clang.takeFileManager();
Douglas Gregorabc563f2010-07-19 21:46:24 +0000683 Target.reset(Clang.takeTarget());
684
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000685 Act->EndSourceFile();
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000686
687 // Remove the overridden buffer we used for the preamble.
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000688 if (OverrideMainBuffer) {
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000689 PreprocessorOpts.eraseRemappedFile(
690 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000691 PreprocessorOpts.ImplicitPCHInclude = PriorImplicitPCHInclude;
692 }
693
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000694 Clang.takeDiagnosticClient();
Douglas Gregorabc563f2010-07-19 21:46:24 +0000695
696 Invocation.reset(Clang.takeInvocation());
Douglas Gregor87c08a52010-08-13 22:48:40 +0000697
698 // If we were asked to cache code-completion results and don't have any
699 // results yet, do so now.
700 if (ShouldCacheCodeCompletionResults && CachedCompletionResults.empty())
701 CacheCodeCompletionResults();
702
Douglas Gregorabc563f2010-07-19 21:46:24 +0000703 return false;
704
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000705error:
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000706 // Remove the overridden buffer we used for the preamble.
Douglas Gregorfae3b2f2010-07-27 00:27:13 +0000707 if (OverrideMainBuffer) {
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000708 PreprocessorOpts.eraseRemappedFile(
709 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregorfae3b2f2010-07-27 00:27:13 +0000710 PreprocessorOpts.DisablePCHValidation = true;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000711 PreprocessorOpts.ImplicitPCHInclude = PriorImplicitPCHInclude;
Douglas Gregorfae3b2f2010-07-27 00:27:13 +0000712 }
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000713
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000714 Clang.takeSourceManager();
715 Clang.takeFileManager();
716 Clang.takeDiagnosticClient();
Douglas Gregorabc563f2010-07-19 21:46:24 +0000717 Invocation.reset(Clang.takeInvocation());
718 return true;
719}
720
Douglas Gregor44c181a2010-07-23 00:33:23 +0000721/// \brief Simple function to retrieve a path for a preamble precompiled header.
722static std::string GetPreamblePCHPath() {
723 // FIXME: This is lame; sys::Path should provide this function (in particular,
724 // it should know how to find the temporary files dir).
725 // FIXME: This is really lame. I copied this code from the Driver!
726 std::string Error;
727 const char *TmpDir = ::getenv("TMPDIR");
728 if (!TmpDir)
729 TmpDir = ::getenv("TEMP");
730 if (!TmpDir)
731 TmpDir = ::getenv("TMP");
732 if (!TmpDir)
733 TmpDir = "/tmp";
734 llvm::sys::Path P(TmpDir);
735 P.appendComponent("preamble");
Douglas Gregor6bf18302010-08-11 13:06:56 +0000736 P.appendSuffix("pch");
Douglas Gregor44c181a2010-07-23 00:33:23 +0000737 if (P.createTemporaryFileOnDisk())
738 return std::string();
739
Douglas Gregor44c181a2010-07-23 00:33:23 +0000740 return P.str();
741}
742
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000743/// \brief Compute the preamble for the main file, providing the source buffer
744/// that corresponds to the main file along with a pair (bytes, start-of-line)
745/// that describes the preamble.
746std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> >
Douglas Gregordf95a132010-08-09 20:45:32 +0000747ASTUnit::ComputePreamble(CompilerInvocation &Invocation,
748 unsigned MaxLines, bool &CreatedBuffer) {
Douglas Gregor175c4a92010-07-23 23:58:40 +0000749 FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
Douglas Gregor44c181a2010-07-23 00:33:23 +0000750 PreprocessorOptions &PreprocessorOpts
Douglas Gregor175c4a92010-07-23 23:58:40 +0000751 = Invocation.getPreprocessorOpts();
752 CreatedBuffer = false;
753
Douglas Gregor44c181a2010-07-23 00:33:23 +0000754 // Try to determine if the main file has been remapped, either from the
755 // command line (to another file) or directly through the compiler invocation
756 // (to a memory buffer).
Douglas Gregor175c4a92010-07-23 23:58:40 +0000757 llvm::MemoryBuffer *Buffer = 0;
Douglas Gregor44c181a2010-07-23 00:33:23 +0000758 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].second);
759 if (const llvm::sys::FileStatus *MainFileStatus = MainFilePath.getFileStatus()) {
760 // Check whether there is a file-file remapping of the main file
761 for (PreprocessorOptions::remapped_file_iterator
Douglas Gregor175c4a92010-07-23 23:58:40 +0000762 M = PreprocessorOpts.remapped_file_begin(),
763 E = PreprocessorOpts.remapped_file_end();
Douglas Gregor44c181a2010-07-23 00:33:23 +0000764 M != E;
765 ++M) {
766 llvm::sys::PathWithStatus MPath(M->first);
767 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
768 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
769 // We found a remapping. Try to load the resulting, remapped source.
Douglas Gregor175c4a92010-07-23 23:58:40 +0000770 if (CreatedBuffer) {
Douglas Gregor44c181a2010-07-23 00:33:23 +0000771 delete Buffer;
Douglas Gregor175c4a92010-07-23 23:58:40 +0000772 CreatedBuffer = false;
773 }
774
Douglas Gregor44c181a2010-07-23 00:33:23 +0000775 Buffer = llvm::MemoryBuffer::getFile(M->second);
776 if (!Buffer)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000777 return std::make_pair((llvm::MemoryBuffer*)0,
778 std::make_pair(0, true));
Douglas Gregor175c4a92010-07-23 23:58:40 +0000779 CreatedBuffer = true;
Douglas Gregor44c181a2010-07-23 00:33:23 +0000780
Douglas Gregor175c4a92010-07-23 23:58:40 +0000781 // Remove this remapping. We've captured the buffer already.
Douglas Gregor44c181a2010-07-23 00:33:23 +0000782 M = PreprocessorOpts.eraseRemappedFile(M);
783 E = PreprocessorOpts.remapped_file_end();
784 }
785 }
786 }
787
788 // Check whether there is a file-buffer remapping. It supercedes the
789 // file-file remapping.
790 for (PreprocessorOptions::remapped_file_buffer_iterator
791 M = PreprocessorOpts.remapped_file_buffer_begin(),
792 E = PreprocessorOpts.remapped_file_buffer_end();
793 M != E;
794 ++M) {
795 llvm::sys::PathWithStatus MPath(M->first);
796 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
797 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
798 // We found a remapping.
Douglas Gregor175c4a92010-07-23 23:58:40 +0000799 if (CreatedBuffer) {
Douglas Gregor44c181a2010-07-23 00:33:23 +0000800 delete Buffer;
Douglas Gregor175c4a92010-07-23 23:58:40 +0000801 CreatedBuffer = false;
802 }
Douglas Gregor44c181a2010-07-23 00:33:23 +0000803
Douglas Gregor175c4a92010-07-23 23:58:40 +0000804 Buffer = const_cast<llvm::MemoryBuffer *>(M->second);
805
806 // Remove this remapping. We've captured the buffer already.
Douglas Gregor44c181a2010-07-23 00:33:23 +0000807 M = PreprocessorOpts.eraseRemappedFile(M);
808 E = PreprocessorOpts.remapped_file_buffer_end();
809 }
810 }
Douglas Gregor175c4a92010-07-23 23:58:40 +0000811 }
Douglas Gregor44c181a2010-07-23 00:33:23 +0000812 }
813
814 // If the main source file was not remapped, load it now.
815 if (!Buffer) {
816 Buffer = llvm::MemoryBuffer::getFile(FrontendOpts.Inputs[0].second);
817 if (!Buffer)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000818 return std::make_pair((llvm::MemoryBuffer*)0, std::make_pair(0, true));
Douglas Gregor175c4a92010-07-23 23:58:40 +0000819
820 CreatedBuffer = true;
Douglas Gregor44c181a2010-07-23 00:33:23 +0000821 }
822
Douglas Gregordf95a132010-08-09 20:45:32 +0000823 return std::make_pair(Buffer, Lexer::ComputePreamble(Buffer, MaxLines));
Douglas Gregor175c4a92010-07-23 23:58:40 +0000824}
825
Douglas Gregor754f3492010-07-24 00:38:13 +0000826static llvm::MemoryBuffer *CreatePaddedMainFileBuffer(llvm::MemoryBuffer *Old,
827 bool DeleteOld,
828 unsigned NewSize,
829 llvm::StringRef NewName) {
830 llvm::MemoryBuffer *Result
831 = llvm::MemoryBuffer::getNewUninitMemBuffer(NewSize, NewName);
832 memcpy(const_cast<char*>(Result->getBufferStart()),
833 Old->getBufferStart(), Old->getBufferSize());
834 memset(const_cast<char*>(Result->getBufferStart()) + Old->getBufferSize(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000835 ' ', NewSize - Old->getBufferSize() - 1);
836 const_cast<char*>(Result->getBufferEnd())[-1] = '\n';
Douglas Gregor754f3492010-07-24 00:38:13 +0000837
838 if (DeleteOld)
839 delete Old;
840
841 return Result;
842}
843
Douglas Gregor175c4a92010-07-23 23:58:40 +0000844/// \brief Attempt to build or re-use a precompiled preamble when (re-)parsing
845/// the source file.
846///
847/// This routine will compute the preamble of the main source file. If a
848/// non-trivial preamble is found, it will precompile that preamble into a
849/// precompiled header so that the precompiled preamble can be used to reduce
850/// reparsing time. If a precompiled preamble has already been constructed,
851/// this routine will determine if it is still valid and, if so, avoid
852/// rebuilding the precompiled preamble.
853///
Douglas Gregordf95a132010-08-09 20:45:32 +0000854/// \param AllowRebuild When true (the default), this routine is
855/// allowed to rebuild the precompiled preamble if it is found to be
856/// out-of-date.
857///
858/// \param MaxLines When non-zero, the maximum number of lines that
859/// can occur within the preamble.
860///
Douglas Gregor754f3492010-07-24 00:38:13 +0000861/// \returns If the precompiled preamble can be used, returns a newly-allocated
862/// buffer that should be used in place of the main file when doing so.
863/// Otherwise, returns a NULL pointer.
Douglas Gregordf95a132010-08-09 20:45:32 +0000864llvm::MemoryBuffer *ASTUnit::getMainBufferWithPrecompiledPreamble(
865 bool AllowRebuild,
866 unsigned MaxLines) {
Douglas Gregor175c4a92010-07-23 23:58:40 +0000867 CompilerInvocation PreambleInvocation(*Invocation);
868 FrontendOptions &FrontendOpts = PreambleInvocation.getFrontendOpts();
869 PreprocessorOptions &PreprocessorOpts
870 = PreambleInvocation.getPreprocessorOpts();
871
872 bool CreatedPreambleBuffer = false;
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000873 std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> > NewPreamble
Douglas Gregordf95a132010-08-09 20:45:32 +0000874 = ComputePreamble(PreambleInvocation, MaxLines, CreatedPreambleBuffer);
Douglas Gregor175c4a92010-07-23 23:58:40 +0000875
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000876 if (!NewPreamble.second.first) {
Douglas Gregor175c4a92010-07-23 23:58:40 +0000877 // We couldn't find a preamble in the main source. Clear out the current
878 // preamble, if we have one. It's obviously no good any more.
879 Preamble.clear();
880 if (!PreambleFile.empty()) {
Douglas Gregor385103b2010-07-30 20:58:08 +0000881 llvm::sys::Path(PreambleFile).eraseFromDisk();
Douglas Gregor175c4a92010-07-23 23:58:40 +0000882 PreambleFile.clear();
883 }
884 if (CreatedPreambleBuffer)
885 delete NewPreamble.first;
Douglas Gregoreababfb2010-08-04 05:53:38 +0000886
887 // The next time we actually see a preamble, precompile it.
888 PreambleRebuildCounter = 1;
Douglas Gregor754f3492010-07-24 00:38:13 +0000889 return 0;
Douglas Gregor175c4a92010-07-23 23:58:40 +0000890 }
891
892 if (!Preamble.empty()) {
893 // We've previously computed a preamble. Check whether we have the same
894 // preamble now that we did before, and that there's enough space in
895 // the main-file buffer within the precompiled preamble to fit the
896 // new main file.
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000897 if (Preamble.size() == NewPreamble.second.first &&
898 PreambleEndsAtStartOfLine == NewPreamble.second.second &&
Douglas Gregor592508e2010-07-24 00:42:07 +0000899 NewPreamble.first->getBufferSize() < PreambleReservedSize-2 &&
Douglas Gregor175c4a92010-07-23 23:58:40 +0000900 memcmp(&Preamble[0], NewPreamble.first->getBufferStart(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000901 NewPreamble.second.first) == 0) {
Douglas Gregor175c4a92010-07-23 23:58:40 +0000902 // The preamble has not changed. We may be able to re-use the precompiled
903 // preamble.
Douglas Gregorc0659ec2010-08-02 20:51:39 +0000904
Douglas Gregorcc5888d2010-07-31 00:40:00 +0000905 // Check that none of the files used by the preamble have changed.
906 bool AnyFileChanged = false;
907
908 // First, make a record of those files that have been overridden via
909 // remapping or unsaved_files.
910 llvm::StringMap<std::pair<off_t, time_t> > OverriddenFiles;
911 for (PreprocessorOptions::remapped_file_iterator
912 R = PreprocessorOpts.remapped_file_begin(),
913 REnd = PreprocessorOpts.remapped_file_end();
914 !AnyFileChanged && R != REnd;
915 ++R) {
916 struct stat StatBuf;
917 if (stat(R->second.c_str(), &StatBuf)) {
918 // If we can't stat the file we're remapping to, assume that something
919 // horrible happened.
920 AnyFileChanged = true;
921 break;
922 }
Douglas Gregor754f3492010-07-24 00:38:13 +0000923
Douglas Gregorcc5888d2010-07-31 00:40:00 +0000924 OverriddenFiles[R->first] = std::make_pair(StatBuf.st_size,
925 StatBuf.st_mtime);
926 }
927 for (PreprocessorOptions::remapped_file_buffer_iterator
928 R = PreprocessorOpts.remapped_file_buffer_begin(),
929 REnd = PreprocessorOpts.remapped_file_buffer_end();
930 !AnyFileChanged && R != REnd;
931 ++R) {
932 // FIXME: Should we actually compare the contents of file->buffer
933 // remappings?
934 OverriddenFiles[R->first] = std::make_pair(R->second->getBufferSize(),
935 0);
936 }
937
938 // Check whether anything has changed.
939 for (llvm::StringMap<std::pair<off_t, time_t> >::iterator
940 F = FilesInPreamble.begin(), FEnd = FilesInPreamble.end();
941 !AnyFileChanged && F != FEnd;
942 ++F) {
943 llvm::StringMap<std::pair<off_t, time_t> >::iterator Overridden
944 = OverriddenFiles.find(F->first());
945 if (Overridden != OverriddenFiles.end()) {
946 // This file was remapped; check whether the newly-mapped file
947 // matches up with the previous mapping.
948 if (Overridden->second != F->second)
949 AnyFileChanged = true;
950 continue;
951 }
952
953 // The file was not remapped; check whether it has changed on disk.
954 struct stat StatBuf;
955 if (stat(F->first(), &StatBuf)) {
956 // If we can't stat the file, assume that something horrible happened.
957 AnyFileChanged = true;
958 } else if (StatBuf.st_size != F->second.first ||
959 StatBuf.st_mtime != F->second.second)
960 AnyFileChanged = true;
961 }
962
963 if (!AnyFileChanged) {
Douglas Gregorc0659ec2010-08-02 20:51:39 +0000964 // Okay! We can re-use the precompiled preamble.
965
966 // Set the state of the diagnostic object to mimic its state
967 // after parsing the preamble.
968 getDiagnostics().Reset();
969 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
970 if (StoredDiagnostics.size() > NumStoredDiagnosticsInPreamble)
971 StoredDiagnostics.erase(
972 StoredDiagnostics.begin() + NumStoredDiagnosticsInPreamble,
973 StoredDiagnostics.end());
974
975 // Create a version of the main file buffer that is padded to
976 // buffer size we reserved when creating the preamble.
Douglas Gregorcc5888d2010-07-31 00:40:00 +0000977 return CreatePaddedMainFileBuffer(NewPreamble.first,
978 CreatedPreambleBuffer,
979 PreambleReservedSize,
980 FrontendOpts.Inputs[0].second);
981 }
Douglas Gregor175c4a92010-07-23 23:58:40 +0000982 }
Douglas Gregordf95a132010-08-09 20:45:32 +0000983
984 // If we aren't allowed to rebuild the precompiled preamble, just
985 // return now.
986 if (!AllowRebuild)
987 return 0;
Douglas Gregor175c4a92010-07-23 23:58:40 +0000988
989 // We can't reuse the previously-computed preamble. Build a new one.
990 Preamble.clear();
Douglas Gregor385103b2010-07-30 20:58:08 +0000991 llvm::sys::Path(PreambleFile).eraseFromDisk();
Douglas Gregoreababfb2010-08-04 05:53:38 +0000992 PreambleRebuildCounter = 1;
Douglas Gregordf95a132010-08-09 20:45:32 +0000993 } else if (!AllowRebuild) {
994 // We aren't allowed to rebuild the precompiled preamble; just
995 // return now.
996 return 0;
997 }
Douglas Gregoreababfb2010-08-04 05:53:38 +0000998
999 // If the preamble rebuild counter > 1, it's because we previously
1000 // failed to build a preamble and we're not yet ready to try
1001 // again. Decrement the counter and return a failure.
1002 if (PreambleRebuildCounter > 1) {
1003 --PreambleRebuildCounter;
1004 return 0;
1005 }
1006
Douglas Gregor175c4a92010-07-23 23:58:40 +00001007 // We did not previously compute a preamble, or it can't be reused anyway.
Douglas Gregor385103b2010-07-30 20:58:08 +00001008 llvm::Timer *PreambleTimer = 0;
1009 if (TimerGroup.get()) {
1010 PreambleTimer = new llvm::Timer("Precompiling preamble", *TimerGroup);
1011 PreambleTimer->startTimer();
1012 Timers.push_back(PreambleTimer);
1013 }
Douglas Gregor44c181a2010-07-23 00:33:23 +00001014
1015 // Create a new buffer that stores the preamble. The buffer also contains
1016 // extra space for the original contents of the file (which will be present
1017 // when we actually parse the file) along with more room in case the file
Douglas Gregor175c4a92010-07-23 23:58:40 +00001018 // grows.
1019 PreambleReservedSize = NewPreamble.first->getBufferSize();
1020 if (PreambleReservedSize < 4096)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001021 PreambleReservedSize = 8191;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001022 else
Douglas Gregor175c4a92010-07-23 23:58:40 +00001023 PreambleReservedSize *= 2;
1024
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001025 // Save the preamble text for later; we'll need to compare against it for
1026 // subsequent reparses.
1027 Preamble.assign(NewPreamble.first->getBufferStart(),
1028 NewPreamble.first->getBufferStart()
1029 + NewPreamble.second.first);
1030 PreambleEndsAtStartOfLine = NewPreamble.second.second;
1031
Douglas Gregor44c181a2010-07-23 00:33:23 +00001032 llvm::MemoryBuffer *PreambleBuffer
Douglas Gregor175c4a92010-07-23 23:58:40 +00001033 = llvm::MemoryBuffer::getNewUninitMemBuffer(PreambleReservedSize,
Douglas Gregor44c181a2010-07-23 00:33:23 +00001034 FrontendOpts.Inputs[0].second);
1035 memcpy(const_cast<char*>(PreambleBuffer->getBufferStart()),
Douglas Gregor175c4a92010-07-23 23:58:40 +00001036 NewPreamble.first->getBufferStart(), Preamble.size());
1037 memset(const_cast<char*>(PreambleBuffer->getBufferStart()) + Preamble.size(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001038 ' ', PreambleReservedSize - Preamble.size() - 1);
1039 const_cast<char*>(PreambleBuffer->getBufferEnd())[-1] = '\n';
Douglas Gregor44c181a2010-07-23 00:33:23 +00001040
1041 // Remap the main source file to the preamble buffer.
Douglas Gregor175c4a92010-07-23 23:58:40 +00001042 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].second);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001043 PreprocessorOpts.addRemappedFile(MainFilePath.str(), PreambleBuffer);
1044
1045 // Tell the compiler invocation to generate a temporary precompiled header.
1046 FrontendOpts.ProgramAction = frontend::GeneratePCH;
Sebastian Redlf65339e2010-08-06 00:35:11 +00001047 // FIXME: Set ChainedPCH unconditionally, once it is ready.
1048 if (::getenv("LIBCLANG_CHAINING"))
1049 FrontendOpts.ChainedPCH = true;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001050 // FIXME: Generate the precompiled header into memory?
Douglas Gregor385103b2010-07-30 20:58:08 +00001051 FrontendOpts.OutputFile = GetPreamblePCHPath();
Douglas Gregor44c181a2010-07-23 00:33:23 +00001052
1053 // Create the compiler instance to use for building the precompiled preamble.
1054 CompilerInstance Clang;
1055 Clang.setInvocation(&PreambleInvocation);
1056 OriginalSourceFile = Clang.getFrontendOpts().Inputs[0].second;
1057
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001058 // Set up diagnostics, capturing all of the diagnostics produced.
Douglas Gregor44c181a2010-07-23 00:33:23 +00001059 Clang.setDiagnostics(&getDiagnostics());
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001060 CaptureDroppedDiagnostics Capture(CaptureDiagnostics,
1061 getDiagnostics(),
1062 StoredDiagnostics);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001063 Clang.setDiagnosticClient(getDiagnostics().getClient());
1064
1065 // Create the target instance.
1066 Clang.setTarget(TargetInfo::CreateTargetInfo(Clang.getDiagnostics(),
1067 Clang.getTargetOpts()));
1068 if (!Clang.hasTarget()) {
1069 Clang.takeDiagnosticClient();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001070 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1071 Preamble.clear();
1072 if (CreatedPreambleBuffer)
1073 delete NewPreamble.first;
Douglas Gregor385103b2010-07-30 20:58:08 +00001074 if (PreambleTimer)
1075 PreambleTimer->stopTimer();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001076 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor754f3492010-07-24 00:38:13 +00001077 return 0;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001078 }
1079
1080 // Inform the target of the language options.
1081 //
1082 // FIXME: We shouldn't need to do this, the target should be immutable once
1083 // created. This complexity should be lifted elsewhere.
1084 Clang.getTarget().setForcedLangOptions(Clang.getLangOpts());
1085
1086 assert(Clang.getFrontendOpts().Inputs.size() == 1 &&
1087 "Invocation must have exactly one source file!");
1088 assert(Clang.getFrontendOpts().Inputs[0].first != IK_AST &&
1089 "FIXME: AST inputs not yet supported here!");
1090 assert(Clang.getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
1091 "IR inputs not support here!");
1092
1093 // Clear out old caches and data.
1094 StoredDiagnostics.clear();
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001095 TopLevelDecls.clear();
1096 TopLevelDeclsInPreamble.clear();
Douglas Gregor44c181a2010-07-23 00:33:23 +00001097
1098 // Create a file manager object to provide access to and cache the filesystem.
1099 Clang.setFileManager(new FileManager);
1100
1101 // Create the source manager.
1102 Clang.setSourceManager(new SourceManager(getDiagnostics()));
1103
Douglas Gregor1d715ac2010-08-03 08:14:03 +00001104 llvm::OwningPtr<PrecompilePreambleAction> Act;
1105 Act.reset(new PrecompilePreambleAction(*this));
Douglas Gregor44c181a2010-07-23 00:33:23 +00001106 if (!Act->BeginSourceFile(Clang, Clang.getFrontendOpts().Inputs[0].second,
1107 Clang.getFrontendOpts().Inputs[0].first)) {
1108 Clang.takeDiagnosticClient();
1109 Clang.takeInvocation();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001110 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1111 Preamble.clear();
1112 if (CreatedPreambleBuffer)
1113 delete NewPreamble.first;
Douglas Gregor385103b2010-07-30 20:58:08 +00001114 if (PreambleTimer)
1115 PreambleTimer->stopTimer();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001116 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor385103b2010-07-30 20:58:08 +00001117
Douglas Gregor754f3492010-07-24 00:38:13 +00001118 return 0;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001119 }
1120
1121 Act->Execute();
1122 Act->EndSourceFile();
1123 Clang.takeDiagnosticClient();
1124 Clang.takeInvocation();
1125
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001126 if (Diagnostics->hasErrorOccurred()) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001127 // There were errors parsing the preamble, so no precompiled header was
1128 // generated. Forget that we even tried.
1129 // FIXME: Should we leave a note for ourselves to try again?
1130 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1131 Preamble.clear();
1132 if (CreatedPreambleBuffer)
1133 delete NewPreamble.first;
Douglas Gregor385103b2010-07-30 20:58:08 +00001134 if (PreambleTimer)
1135 PreambleTimer->stopTimer();
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001136 TopLevelDeclsInPreamble.clear();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001137 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor754f3492010-07-24 00:38:13 +00001138 return 0;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001139 }
1140
1141 // Keep track of the preamble we precompiled.
1142 PreambleFile = FrontendOpts.OutputFile;
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001143 NumStoredDiagnosticsInPreamble = StoredDiagnostics.size();
1144 NumWarningsInPreamble = getDiagnostics().getNumWarnings();
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001145
1146 // Keep track of all of the files that the source manager knows about,
1147 // so we can verify whether they have changed or not.
1148 FilesInPreamble.clear();
1149 SourceManager &SourceMgr = Clang.getSourceManager();
1150 const llvm::MemoryBuffer *MainFileBuffer
1151 = SourceMgr.getBuffer(SourceMgr.getMainFileID());
1152 for (SourceManager::fileinfo_iterator F = SourceMgr.fileinfo_begin(),
1153 FEnd = SourceMgr.fileinfo_end();
1154 F != FEnd;
1155 ++F) {
1156 const FileEntry *File = F->second->Entry;
1157 if (!File || F->second->getRawBuffer() == MainFileBuffer)
1158 continue;
1159
1160 FilesInPreamble[File->getName()]
1161 = std::make_pair(F->second->getSize(), File->getModificationTime());
1162 }
1163
Douglas Gregor385103b2010-07-30 20:58:08 +00001164 if (PreambleTimer)
1165 PreambleTimer->stopTimer();
1166
Douglas Gregoreababfb2010-08-04 05:53:38 +00001167 PreambleRebuildCounter = 1;
Douglas Gregor754f3492010-07-24 00:38:13 +00001168 return CreatePaddedMainFileBuffer(NewPreamble.first,
1169 CreatedPreambleBuffer,
1170 PreambleReservedSize,
1171 FrontendOpts.Inputs[0].second);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001172}
Douglas Gregorabc563f2010-07-19 21:46:24 +00001173
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001174void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
1175 std::vector<Decl *> Resolved;
1176 Resolved.reserve(TopLevelDeclsInPreamble.size());
1177 ExternalASTSource &Source = *getASTContext().getExternalSource();
1178 for (unsigned I = 0, N = TopLevelDeclsInPreamble.size(); I != N; ++I) {
1179 // Resolve the declaration ID to an actual declaration, possibly
1180 // deserializing the declaration in the process.
1181 Decl *D = Source.GetExternalDecl(TopLevelDeclsInPreamble[I]);
1182 if (D)
1183 Resolved.push_back(D);
1184 }
1185 TopLevelDeclsInPreamble.clear();
1186 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1187}
1188
1189unsigned ASTUnit::getMaxPCHLevel() const {
1190 if (!getOnlyLocalDecls())
1191 return Decl::MaxPCHLevel;
1192
1193 unsigned Result = 0;
1194 if (isMainFileAST() || SavedMainFileBuffer)
1195 ++Result;
1196 return Result;
1197}
1198
Douglas Gregorabc563f2010-07-19 21:46:24 +00001199ASTUnit *ASTUnit::LoadFromCompilerInvocation(CompilerInvocation *CI,
1200 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
1201 bool OnlyLocalDecls,
Douglas Gregor44c181a2010-07-23 00:33:23 +00001202 bool CaptureDiagnostics,
Douglas Gregordf95a132010-08-09 20:45:32 +00001203 bool PrecompilePreamble,
Douglas Gregor87c08a52010-08-13 22:48:40 +00001204 bool CompleteTranslationUnit,
1205 bool CacheCodeCompletionResults) {
Douglas Gregorabc563f2010-07-19 21:46:24 +00001206 if (!Diags.getPtr()) {
1207 // No diagnostics engine was provided, so create our own diagnostics object
1208 // with the default options.
1209 DiagnosticOptions DiagOpts;
1210 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
1211 }
1212
1213 // Create the AST unit.
1214 llvm::OwningPtr<ASTUnit> AST;
1215 AST.reset(new ASTUnit(false));
1216 AST->Diagnostics = Diags;
1217 AST->CaptureDiagnostics = CaptureDiagnostics;
1218 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregordf95a132010-08-09 20:45:32 +00001219 AST->CompleteTranslationUnit = CompleteTranslationUnit;
Douglas Gregor87c08a52010-08-13 22:48:40 +00001220 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001221 AST->Invocation.reset(CI);
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001222 CI->getPreprocessorOpts().RetainRemappedFileBuffers = true;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001223
Douglas Gregor385103b2010-07-30 20:58:08 +00001224 if (getenv("LIBCLANG_TIMING"))
1225 AST->TimerGroup.reset(
1226 new llvm::TimerGroup(CI->getFrontendOpts().Inputs[0].second));
1227
1228
Douglas Gregor754f3492010-07-24 00:38:13 +00001229 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Douglas Gregorfd0b8702010-07-28 22:12:37 +00001230 // FIXME: When C++ PCH is ready, allow use of it for a precompiled preamble.
Douglas Gregoreababfb2010-08-04 05:53:38 +00001231 if (PrecompilePreamble && !CI->getLangOpts().CPlusPlus) {
1232 AST->PreambleRebuildCounter = 1;
Douglas Gregordf95a132010-08-09 20:45:32 +00001233 OverrideMainBuffer = AST->getMainBufferWithPrecompiledPreamble();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001234 }
Douglas Gregor44c181a2010-07-23 00:33:23 +00001235
Douglas Gregor385103b2010-07-30 20:58:08 +00001236 llvm::Timer *ParsingTimer = 0;
1237 if (AST->TimerGroup.get()) {
1238 ParsingTimer = new llvm::Timer("Initial parse", *AST->TimerGroup);
1239 ParsingTimer->startTimer();
1240 AST->Timers.push_back(ParsingTimer);
1241 }
Douglas Gregorabc563f2010-07-19 21:46:24 +00001242
Douglas Gregor385103b2010-07-30 20:58:08 +00001243 bool Failed = AST->Parse(OverrideMainBuffer);
1244 if (ParsingTimer)
1245 ParsingTimer->stopTimer();
1246
1247 return Failed? 0 : AST.take();
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001248}
Daniel Dunbar7b556682009-12-02 03:23:45 +00001249
1250ASTUnit *ASTUnit::LoadFromCommandLine(const char **ArgBegin,
1251 const char **ArgEnd,
Douglas Gregor28019772010-04-05 23:52:57 +00001252 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
Daniel Dunbar869824e2009-12-13 03:46:13 +00001253 llvm::StringRef ResourceFilesPath,
Daniel Dunbar7b556682009-12-02 03:23:45 +00001254 bool OnlyLocalDecls,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001255 RemappedFile *RemappedFiles,
Douglas Gregora88084b2010-02-18 18:08:43 +00001256 unsigned NumRemappedFiles,
Douglas Gregor44c181a2010-07-23 00:33:23 +00001257 bool CaptureDiagnostics,
Douglas Gregordf95a132010-08-09 20:45:32 +00001258 bool PrecompilePreamble,
Douglas Gregor87c08a52010-08-13 22:48:40 +00001259 bool CompleteTranslationUnit,
1260 bool CacheCodeCompletionResults) {
Douglas Gregor28019772010-04-05 23:52:57 +00001261 if (!Diags.getPtr()) {
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001262 // No diagnostics engine was provided, so create our own diagnostics object
1263 // with the default options.
1264 DiagnosticOptions DiagOpts;
Douglas Gregor28019772010-04-05 23:52:57 +00001265 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001266 }
1267
Daniel Dunbar7b556682009-12-02 03:23:45 +00001268 llvm::SmallVector<const char *, 16> Args;
1269 Args.push_back("<clang>"); // FIXME: Remove dummy argument.
1270 Args.insert(Args.end(), ArgBegin, ArgEnd);
1271
1272 // FIXME: Find a cleaner way to force the driver into restricted modes. We
1273 // also want to force it to use clang.
1274 Args.push_back("-fsyntax-only");
1275
Daniel Dunbar869824e2009-12-13 03:46:13 +00001276 // FIXME: We shouldn't have to pass in the path info.
Daniel Dunbar0bbad512010-07-19 00:44:04 +00001277 driver::Driver TheDriver("clang", llvm::sys::getHostTriple(),
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001278 "a.out", false, false, *Diags);
Daniel Dunbar3bd54cc2010-01-25 00:44:02 +00001279
1280 // Don't check that inputs exist, they have been remapped.
1281 TheDriver.setCheckInputsExist(false);
1282
Daniel Dunbar7b556682009-12-02 03:23:45 +00001283 llvm::OwningPtr<driver::Compilation> C(
1284 TheDriver.BuildCompilation(Args.size(), Args.data()));
1285
1286 // We expect to get back exactly one command job, if we didn't something
1287 // failed.
1288 const driver::JobList &Jobs = C->getJobs();
1289 if (Jobs.size() != 1 || !isa<driver::Command>(Jobs.begin())) {
1290 llvm::SmallString<256> Msg;
1291 llvm::raw_svector_ostream OS(Msg);
1292 C->PrintJob(OS, C->getJobs(), "; ", true);
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001293 Diags->Report(diag::err_fe_expected_compiler_job) << OS.str();
Daniel Dunbar7b556682009-12-02 03:23:45 +00001294 return 0;
1295 }
1296
1297 const driver::Command *Cmd = cast<driver::Command>(*Jobs.begin());
1298 if (llvm::StringRef(Cmd->getCreator().getName()) != "clang") {
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001299 Diags->Report(diag::err_fe_expected_clang_command);
Daniel Dunbar7b556682009-12-02 03:23:45 +00001300 return 0;
1301 }
1302
1303 const driver::ArgStringList &CCArgs = Cmd->getArguments();
Daniel Dunbar807b0612010-01-30 21:47:16 +00001304 llvm::OwningPtr<CompilerInvocation> CI(new CompilerInvocation);
Dan Gohmancb421fa2010-04-19 16:39:44 +00001305 CompilerInvocation::CreateFromArgs(*CI,
1306 const_cast<const char **>(CCArgs.data()),
1307 const_cast<const char **>(CCArgs.data()) +
Douglas Gregor44c181a2010-07-23 00:33:23 +00001308 CCArgs.size(),
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001309 *Diags);
Daniel Dunbar1e69fe32009-12-13 03:45:58 +00001310
Douglas Gregor4db64a42010-01-23 00:14:00 +00001311 // Override any files that need remapping
1312 for (unsigned I = 0; I != NumRemappedFiles; ++I)
Daniel Dunbar807b0612010-01-30 21:47:16 +00001313 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
Daniel Dunbarb26d4832010-02-16 01:55:04 +00001314 RemappedFiles[I].second);
Douglas Gregor4db64a42010-01-23 00:14:00 +00001315
Daniel Dunbar8b9adfe2009-12-15 00:06:45 +00001316 // Override the resources path.
Daniel Dunbar807b0612010-01-30 21:47:16 +00001317 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
Daniel Dunbar7b556682009-12-02 03:23:45 +00001318
Daniel Dunbarb26d4832010-02-16 01:55:04 +00001319 CI->getFrontendOpts().DisableFree = true;
Douglas Gregora88084b2010-02-18 18:08:43 +00001320 return LoadFromCompilerInvocation(CI.take(), Diags, OnlyLocalDecls,
Douglas Gregordf95a132010-08-09 20:45:32 +00001321 CaptureDiagnostics, PrecompilePreamble,
Douglas Gregor87c08a52010-08-13 22:48:40 +00001322 CompleteTranslationUnit,
1323 CacheCodeCompletionResults);
Daniel Dunbar7b556682009-12-02 03:23:45 +00001324}
Douglas Gregorabc563f2010-07-19 21:46:24 +00001325
1326bool ASTUnit::Reparse(RemappedFile *RemappedFiles, unsigned NumRemappedFiles) {
1327 if (!Invocation.get())
1328 return true;
1329
Douglas Gregor385103b2010-07-30 20:58:08 +00001330 llvm::Timer *ReparsingTimer = 0;
1331 if (TimerGroup.get()) {
1332 ReparsingTimer = new llvm::Timer("Reparse", *TimerGroup);
1333 ReparsingTimer->startTimer();
1334 Timers.push_back(ReparsingTimer);
1335 }
1336
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001337 // Remap files.
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001338 Invocation->getPreprocessorOpts().clearRemappedFiles();
1339 for (unsigned I = 0; I != NumRemappedFiles; ++I)
1340 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
1341 RemappedFiles[I].second);
1342
Douglas Gregoreababfb2010-08-04 05:53:38 +00001343 // If we have a preamble file lying around, or if we might try to
1344 // build a precompiled preamble, do so now.
Douglas Gregor754f3492010-07-24 00:38:13 +00001345 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Douglas Gregoreababfb2010-08-04 05:53:38 +00001346 if (!PreambleFile.empty() || PreambleRebuildCounter > 0)
Douglas Gregordf95a132010-08-09 20:45:32 +00001347 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001348
Douglas Gregorabc563f2010-07-19 21:46:24 +00001349 // Clear out the diagnostics state.
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001350 if (!OverrideMainBuffer)
1351 getDiagnostics().Reset();
Douglas Gregorabc563f2010-07-19 21:46:24 +00001352
Douglas Gregor175c4a92010-07-23 23:58:40 +00001353 // Parse the sources
Douglas Gregor754f3492010-07-24 00:38:13 +00001354 bool Result = Parse(OverrideMainBuffer);
Douglas Gregor385103b2010-07-30 20:58:08 +00001355 if (ReparsingTimer)
1356 ReparsingTimer->stopTimer();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001357 return Result;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001358}
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001359
Douglas Gregor87c08a52010-08-13 22:48:40 +00001360//----------------------------------------------------------------------------//
1361// Code completion
1362//----------------------------------------------------------------------------//
1363
1364namespace {
1365 /// \brief Code completion consumer that combines the cached code-completion
1366 /// results from an ASTUnit with the code-completion results provided to it,
1367 /// then passes the result on to
1368 class AugmentedCodeCompleteConsumer : public CodeCompleteConsumer {
1369 unsigned NormalContexts;
1370 ASTUnit &AST;
1371 CodeCompleteConsumer &Next;
1372
1373 public:
1374 AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next,
Douglas Gregor8071e422010-08-15 06:18:01 +00001375 bool IncludeMacros, bool IncludeCodePatterns,
1376 bool IncludeGlobals)
1377 : CodeCompleteConsumer(IncludeMacros, IncludeCodePatterns, IncludeGlobals,
Douglas Gregor87c08a52010-08-13 22:48:40 +00001378 Next.isOutputBinary()), AST(AST), Next(Next)
1379 {
1380 // Compute the set of contexts in which we will look when we don't have
1381 // any information about the specific context.
1382 NormalContexts
1383 = (1 << (CodeCompletionContext::CCC_TopLevel - 1))
1384 | (1 << (CodeCompletionContext::CCC_ObjCInterface - 1))
1385 | (1 << (CodeCompletionContext::CCC_ObjCImplementation - 1))
1386 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
1387 | (1 << (CodeCompletionContext::CCC_Statement - 1))
1388 | (1 << (CodeCompletionContext::CCC_Expression - 1))
1389 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
1390 | (1 << (CodeCompletionContext::CCC_MemberAccess - 1))
1391 | (1 << (CodeCompletionContext::CCC_ObjCProtocolName - 1));
1392
1393 if (AST.getASTContext().getLangOptions().CPlusPlus)
1394 NormalContexts |= (1 << (CodeCompletionContext::CCC_EnumTag - 1))
1395 | (1 << (CodeCompletionContext::CCC_UnionTag - 1))
1396 | (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1));
1397 }
1398
1399 virtual void ProcessCodeCompleteResults(Sema &S,
1400 CodeCompletionContext Context,
1401 Result *Results,
1402 unsigned NumResults) {
1403 // Merge the results we were given with the results we cached.
1404 bool AddedResult = false;
1405 unsigned InContexts =
1406 (Context.getKind() == CodeCompletionContext::CCC_Other? NormalContexts
1407 : (1 << (Context.getKind() - 1)));
1408 typedef CodeCompleteConsumer::Result Result;
1409 llvm::SmallVector<Result, 8> AllResults;
1410 for (ASTUnit::cached_completion_iterator
1411 C = AST.cached_completion_begin(),
1412 CEnd = AST.cached_completion_end();
1413 C != CEnd; ++C) {
1414 // If the context we are in matches any of the contexts we are
1415 // interested in, we'll add this result.
1416 if ((C->ShowInContexts & InContexts) == 0)
1417 continue;
1418
1419 // If we haven't added any results previously, do so now.
1420 if (!AddedResult) {
1421 AllResults.insert(AllResults.end(), Results, Results + NumResults);
1422 AddedResult = true;
1423 }
1424
Douglas Gregor1827e102010-08-16 16:18:59 +00001425 // Adjust priority based on similar type classes.
1426 unsigned Priority = C->Priority;
1427 if (!Context.getPreferredType().isNull()) {
1428 if (C->Kind == CXCursor_MacroDefinition) {
1429 Priority = getMacroUsagePriority(C->Completion->getTypedText(),
1430 Context.getPreferredType()->isAnyPointerType());
1431 } else {
1432 CanQualType Expected
1433 = S.Context.getCanonicalType(Context.getPreferredType());
1434 SimplifiedTypeClass ExpectedSTC = getSimplifiedTypeClass(Expected);
1435 if (ExpectedSTC == C->TypeClass) {
1436 // FIXME: How can we check for an exact match?
1437 Priority /= CCF_SimilarTypeMatch;
1438 }
1439 }
1440 }
1441
1442 AllResults.push_back(Result(C->Completion, Priority, C->Kind));
Douglas Gregor87c08a52010-08-13 22:48:40 +00001443 }
1444
1445 // If we did not add any cached completion results, just forward the
1446 // results we were given to the next consumer.
1447 if (!AddedResult) {
1448 Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
1449 return;
1450 }
1451
1452 Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
1453 AllResults.size());
1454 }
1455
1456 virtual void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
1457 OverloadCandidate *Candidates,
1458 unsigned NumCandidates) {
1459 Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates);
1460 }
1461 };
1462}
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001463void ASTUnit::CodeComplete(llvm::StringRef File, unsigned Line, unsigned Column,
1464 RemappedFile *RemappedFiles,
1465 unsigned NumRemappedFiles,
Douglas Gregorcee235c2010-08-05 09:09:23 +00001466 bool IncludeMacros,
1467 bool IncludeCodePatterns,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001468 CodeCompleteConsumer &Consumer,
1469 Diagnostic &Diag, LangOptions &LangOpts,
1470 SourceManager &SourceMgr, FileManager &FileMgr,
1471 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics) {
1472 if (!Invocation.get())
1473 return;
1474
Douglas Gregordf95a132010-08-09 20:45:32 +00001475 llvm::Timer *CompletionTimer = 0;
1476 if (TimerGroup.get()) {
1477 llvm::SmallString<128> TimerName;
1478 llvm::raw_svector_ostream TimerNameOut(TimerName);
1479 TimerNameOut << "Code completion @ " << File << ":" << Line << ":"
1480 << Column;
1481 CompletionTimer = new llvm::Timer(TimerNameOut.str(), *TimerGroup);
1482 CompletionTimer->startTimer();
1483 Timers.push_back(CompletionTimer);
1484 }
1485
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001486 CompilerInvocation CCInvocation(*Invocation);
1487 FrontendOptions &FrontendOpts = CCInvocation.getFrontendOpts();
1488 PreprocessorOptions &PreprocessorOpts = CCInvocation.getPreprocessorOpts();
Douglas Gregorcee235c2010-08-05 09:09:23 +00001489
Douglas Gregor87c08a52010-08-13 22:48:40 +00001490 FrontendOpts.ShowMacrosInCodeCompletion
1491 = IncludeMacros && CachedCompletionResults.empty();
Douglas Gregorcee235c2010-08-05 09:09:23 +00001492 FrontendOpts.ShowCodePatternsInCodeCompletion = IncludeCodePatterns;
Douglas Gregor8071e422010-08-15 06:18:01 +00001493 FrontendOpts.ShowGlobalSymbolsInCodeCompletion
1494 = CachedCompletionResults.empty();
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001495 FrontendOpts.CodeCompletionAt.FileName = File;
1496 FrontendOpts.CodeCompletionAt.Line = Line;
1497 FrontendOpts.CodeCompletionAt.Column = Column;
1498
Douglas Gregorcee235c2010-08-05 09:09:23 +00001499 // Turn on spell-checking when performing code completion. It leads
1500 // to better results.
1501 unsigned SpellChecking = CCInvocation.getLangOpts().SpellChecking;
1502 CCInvocation.getLangOpts().SpellChecking = 1;
1503
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001504 // Set the language options appropriately.
1505 LangOpts = CCInvocation.getLangOpts();
1506
1507 CompilerInstance Clang;
1508 Clang.setInvocation(&CCInvocation);
1509 OriginalSourceFile = Clang.getFrontendOpts().Inputs[0].second;
1510
1511 // Set up diagnostics, capturing any diagnostics produced.
1512 Clang.setDiagnostics(&Diag);
1513 CaptureDroppedDiagnostics Capture(true,
1514 Clang.getDiagnostics(),
1515 StoredDiagnostics);
1516 Clang.setDiagnosticClient(Diag.getClient());
1517
1518 // Create the target instance.
1519 Clang.setTarget(TargetInfo::CreateTargetInfo(Clang.getDiagnostics(),
1520 Clang.getTargetOpts()));
1521 if (!Clang.hasTarget()) {
1522 Clang.takeDiagnosticClient();
1523 Clang.takeInvocation();
1524 }
1525
1526 // Inform the target of the language options.
1527 //
1528 // FIXME: We shouldn't need to do this, the target should be immutable once
1529 // created. This complexity should be lifted elsewhere.
1530 Clang.getTarget().setForcedLangOptions(Clang.getLangOpts());
1531
1532 assert(Clang.getFrontendOpts().Inputs.size() == 1 &&
1533 "Invocation must have exactly one source file!");
1534 assert(Clang.getFrontendOpts().Inputs[0].first != IK_AST &&
1535 "FIXME: AST inputs not yet supported here!");
1536 assert(Clang.getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
1537 "IR inputs not support here!");
1538
1539
1540 // Use the source and file managers that we were given.
1541 Clang.setFileManager(&FileMgr);
1542 Clang.setSourceManager(&SourceMgr);
1543
1544 // Remap files.
1545 PreprocessorOpts.clearRemappedFiles();
Douglas Gregorb75d3df2010-08-04 17:07:00 +00001546 PreprocessorOpts.RetainRemappedFileBuffers = true;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001547 for (unsigned I = 0; I != NumRemappedFiles; ++I)
1548 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first,
1549 RemappedFiles[I].second);
1550
Douglas Gregor87c08a52010-08-13 22:48:40 +00001551 // Use the code completion consumer we were given, but adding any cached
1552 // code-completion results.
1553 AugmentedCodeCompleteConsumer
1554 AugmentedConsumer(*this, Consumer, FrontendOpts.ShowMacrosInCodeCompletion,
Douglas Gregor8071e422010-08-15 06:18:01 +00001555 FrontendOpts.ShowCodePatternsInCodeCompletion,
1556 FrontendOpts.ShowGlobalSymbolsInCodeCompletion);
Douglas Gregor87c08a52010-08-13 22:48:40 +00001557 Clang.setCodeCompletionConsumer(&AugmentedConsumer);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001558
Douglas Gregordf95a132010-08-09 20:45:32 +00001559 // If we have a precompiled preamble, try to use it. We only allow
1560 // the use of the precompiled preamble if we're if the completion
1561 // point is within the main file, after the end of the precompiled
1562 // preamble.
1563 llvm::MemoryBuffer *OverrideMainBuffer = 0;
1564 if (!PreambleFile.empty()) {
1565 using llvm::sys::FileStatus;
1566 llvm::sys::PathWithStatus CompleteFilePath(File);
1567 llvm::sys::PathWithStatus MainPath(OriginalSourceFile);
1568 if (const FileStatus *CompleteFileStatus = CompleteFilePath.getFileStatus())
1569 if (const FileStatus *MainStatus = MainPath.getFileStatus())
1570 if (CompleteFileStatus->getUniqueID() == MainStatus->getUniqueID())
1571 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(false,
1572 Line);
1573 }
1574
1575 // If the main file has been overridden due to the use of a preamble,
1576 // make that override happen and introduce the preamble.
1577 if (OverrideMainBuffer) {
1578 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
1579 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
1580 PreprocessorOpts.PrecompiledPreambleBytes.second
1581 = PreambleEndsAtStartOfLine;
1582 PreprocessorOpts.ImplicitPCHInclude = PreambleFile;
1583 PreprocessorOpts.DisablePCHValidation = true;
1584
1585 // The stored diagnostics have the old source manager. Copy them
1586 // to our output set of stored diagnostics, updating the source
1587 // manager to the one we were given.
1588 for (unsigned I = 0, N = this->StoredDiagnostics.size(); I != N; ++I) {
1589 StoredDiagnostics.push_back(this->StoredDiagnostics[I]);
1590 FullSourceLoc Loc(StoredDiagnostics[I].getLocation(), SourceMgr);
1591 StoredDiagnostics[I].setLocation(Loc);
1592 }
1593 }
1594
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001595 llvm::OwningPtr<SyntaxOnlyAction> Act;
1596 Act.reset(new SyntaxOnlyAction);
1597 if (Act->BeginSourceFile(Clang, Clang.getFrontendOpts().Inputs[0].second,
1598 Clang.getFrontendOpts().Inputs[0].first)) {
1599 Act->Execute();
1600 Act->EndSourceFile();
1601 }
Douglas Gregordf95a132010-08-09 20:45:32 +00001602
1603 if (CompletionTimer)
1604 CompletionTimer->stopTimer();
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001605
1606 // Steal back our resources.
Douglas Gregordf95a132010-08-09 20:45:32 +00001607 delete OverrideMainBuffer;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001608 Clang.takeFileManager();
1609 Clang.takeSourceManager();
1610 Clang.takeInvocation();
1611 Clang.takeDiagnosticClient();
1612 Clang.takeCodeCompletionConsumer();
Douglas Gregorcee235c2010-08-05 09:09:23 +00001613 CCInvocation.getLangOpts().SpellChecking = SpellChecking;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001614}
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00001615
1616bool ASTUnit::Save(llvm::StringRef File) {
1617 if (getDiagnostics().hasErrorOccurred())
1618 return true;
1619
1620 // FIXME: Can we somehow regenerate the stat cache here, or do we need to
1621 // unconditionally create a stat cache when we parse the file?
1622 std::string ErrorInfo;
Benjamin Kramer1395c5d2010-08-15 16:54:31 +00001623 llvm::raw_fd_ostream Out(File.str().c_str(), ErrorInfo,
1624 llvm::raw_fd_ostream::F_Binary);
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00001625 if (!ErrorInfo.empty() || Out.has_error())
1626 return true;
1627
1628 std::vector<unsigned char> Buffer;
1629 llvm::BitstreamWriter Stream(Buffer);
1630 PCHWriter Writer(Stream);
1631 Writer.WritePCH(getSema(), 0, 0);
1632
1633 // Write the generated bitstream to "Out".
1634 Out.write((char *)&Buffer.front(), Buffer.size());
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00001635 Out.close();
1636 return Out.has_error();
1637}