blob: 2a1244841e3b4d42a67a70c09e5e5726d9f6a531 [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"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000015#include "clang/AST/ASTContext.h"
Daniel Dunbar521bf9c2009-12-01 09:51:01 +000016#include "clang/AST/ASTConsumer.h"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000017#include "clang/AST/DeclVisitor.h"
Douglas Gregorf5586f62010-08-16 18:08:11 +000018#include "clang/AST/TypeOrdering.h"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000019#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"
Argyrios Kyrtzidis4e03c2b2011-03-07 22:45:01 +000023#include "clang/Driver/ArgList.h"
24#include "clang/Driver/Options.h"
Daniel Dunbar7b556682009-12-02 03:23:45 +000025#include "clang/Driver/Tool.h"
Daniel Dunbar521bf9c2009-12-01 09:51:01 +000026#include "clang/Frontend/CompilerInstance.h"
27#include "clang/Frontend/FrontendActions.h"
Daniel Dunbar7b556682009-12-02 03:23:45 +000028#include "clang/Frontend/FrontendDiagnostic.h"
Daniel Dunbar521bf9c2009-12-01 09:51:01 +000029#include "clang/Frontend/FrontendOptions.h"
Douglas Gregor32be4a52010-10-11 21:37:58 +000030#include "clang/Frontend/Utils.h"
Sebastian Redl6ab7cd82010-08-18 23:57:17 +000031#include "clang/Serialization/ASTReader.h"
Douglas Gregor89d99802010-11-30 06:16:57 +000032#include "clang/Serialization/ASTSerializationListener.h"
Sebastian Redl7faa2ec2010-08-18 23:56:37 +000033#include "clang/Serialization/ASTWriter.h"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000034#include "clang/Lex/HeaderSearch.h"
35#include "clang/Lex/Preprocessor.h"
Daniel Dunbard58c03f2009-11-15 06:48:46 +000036#include "clang/Basic/TargetOptions.h"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000037#include "clang/Basic/TargetInfo.h"
38#include "clang/Basic/Diagnostic.h"
Chris Lattner7f9fc3f2011-03-23 04:04:01 +000039#include "llvm/ADT/ArrayRef.h"
Douglas Gregor9b7db622011-02-16 18:16:54 +000040#include "llvm/ADT/StringExtras.h"
Douglas Gregor349d38c2010-08-16 23:08:34 +000041#include "llvm/ADT/StringSet.h"
Douglas Gregor1fd9e0d2010-12-07 00:05:48 +000042#include "llvm/Support/Atomic.h"
Douglas Gregor4db64a42010-01-23 00:14:00 +000043#include "llvm/Support/MemoryBuffer.h"
Michael J. Spencer03013fa2010-11-29 18:12:39 +000044#include "llvm/Support/Host.h"
45#include "llvm/Support/Path.h"
Douglas Gregordf95a132010-08-09 20:45:32 +000046#include "llvm/Support/raw_ostream.h"
Douglas Gregor385103b2010-07-30 20:58:08 +000047#include "llvm/Support/Timer.h"
Ted Kremenekb547eeb2011-03-18 02:06:56 +000048#include "llvm/Support/CrashRecoveryContext.h"
Douglas Gregor44c181a2010-07-23 00:33:23 +000049#include <cstdlib>
Zhongxing Xuad23ebe2010-07-23 02:15:08 +000050#include <cstdio>
Douglas Gregorcc5888d2010-07-31 00:40:00 +000051#include <sys/stat.h>
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000052using namespace clang;
53
Douglas Gregor213f18b2010-10-28 15:44:59 +000054using llvm::TimeRecord;
55
56namespace {
57 class SimpleTimer {
58 bool WantTiming;
59 TimeRecord Start;
60 std::string Output;
61
Benjamin Krameredfb7ec2010-11-09 20:00:56 +000062 public:
Douglas Gregor9dba61a2010-11-01 13:48:43 +000063 explicit SimpleTimer(bool WantTiming) : WantTiming(WantTiming) {
Douglas Gregor213f18b2010-10-28 15:44:59 +000064 if (WantTiming)
Benjamin Krameredfb7ec2010-11-09 20:00:56 +000065 Start = TimeRecord::getCurrentTime();
Douglas Gregor213f18b2010-10-28 15:44:59 +000066 }
67
Benjamin Krameredfb7ec2010-11-09 20:00:56 +000068 void setOutput(const llvm::Twine &Output) {
Douglas Gregor213f18b2010-10-28 15:44:59 +000069 if (WantTiming)
Benjamin Krameredfb7ec2010-11-09 20:00:56 +000070 this->Output = Output.str();
Douglas Gregor213f18b2010-10-28 15:44:59 +000071 }
72
Douglas Gregor213f18b2010-10-28 15:44:59 +000073 ~SimpleTimer() {
74 if (WantTiming) {
75 TimeRecord Elapsed = TimeRecord::getCurrentTime();
76 Elapsed -= Start;
77 llvm::errs() << Output << ':';
78 Elapsed.print(Elapsed, llvm::errs());
79 llvm::errs() << '\n';
80 }
81 }
82 };
83}
84
Douglas Gregoreababfb2010-08-04 05:53:38 +000085/// \brief After failing to build a precompiled preamble (due to
86/// errors in the source that occurs in the preamble), the number of
87/// reparses during which we'll skip even trying to precompile the
88/// preamble.
89const unsigned DefaultPreambleRebuildInterval = 5;
90
Douglas Gregore3c60a72010-11-17 00:13:31 +000091/// \brief Tracks the number of ASTUnit objects that are currently active.
92///
93/// Used for debugging purposes only.
Douglas Gregor1fd9e0d2010-12-07 00:05:48 +000094static llvm::sys::cas_flag ActiveASTUnitObjects;
Douglas Gregore3c60a72010-11-17 00:13:31 +000095
Douglas Gregor3687e9d2010-04-05 21:10:19 +000096ASTUnit::ASTUnit(bool _MainFileIsAST)
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +000097 : OnlyLocalDecls(false), CaptureDiagnostics(false),
98 MainFileIsAST(_MainFileIsAST),
Douglas Gregor213f18b2010-10-28 15:44:59 +000099 CompleteTranslationUnit(true), WantTiming(getenv("LIBCLANG_TIMING")),
Argyrios Kyrtzidis15727dd2011-03-05 01:03:48 +0000100 OwnsRemappedFileBuffers(true),
Douglas Gregor213f18b2010-10-28 15:44:59 +0000101 NumStoredDiagnosticsFromDriver(0),
Douglas Gregor4cd912a2010-10-12 00:50:20 +0000102 ConcurrencyCheckValue(CheckUnlocked),
Douglas Gregor671947b2010-08-19 01:33:06 +0000103 PreambleRebuildCounter(0), SavedMainFileBuffer(0), PreambleBuffer(0),
Douglas Gregor727d93e2010-08-17 00:40:40 +0000104 ShouldCacheCodeCompletionResults(false),
Douglas Gregor9b7db622011-02-16 18:16:54 +0000105 CompletionCacheTopLevelHashValue(0),
106 PreambleTopLevelHashValue(0),
107 CurrentTopLevelHashValue(0),
Douglas Gregor8b1540c2010-08-19 00:45:44 +0000108 UnsafeToFree(false) {
Douglas Gregore3c60a72010-11-17 00:13:31 +0000109 if (getenv("LIBCLANG_OBJTRACKING")) {
Douglas Gregor1fd9e0d2010-12-07 00:05:48 +0000110 llvm::sys::AtomicIncrement(&ActiveASTUnitObjects);
Douglas Gregore3c60a72010-11-17 00:13:31 +0000111 fprintf(stderr, "+++ %d translation units\n", ActiveASTUnitObjects);
112 }
Douglas Gregor385103b2010-07-30 20:58:08 +0000113}
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000114
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000115ASTUnit::~ASTUnit() {
Douglas Gregorbdf60622010-03-05 21:16:25 +0000116 ConcurrencyCheckValue = CheckLocked;
Douglas Gregorabc563f2010-07-19 21:46:24 +0000117 CleanTemporaryFiles();
Douglas Gregor175c4a92010-07-23 23:58:40 +0000118 if (!PreambleFile.empty())
Douglas Gregor385103b2010-07-30 20:58:08 +0000119 llvm::sys::Path(PreambleFile).eraseFromDisk();
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000120
121 // Free the buffers associated with remapped files. We are required to
122 // perform this operation here because we explicitly request that the
123 // compiler instance *not* free these buffers for each invocation of the
124 // parser.
Ted Kremenek4f327862011-03-21 18:40:17 +0000125 if (Invocation.getPtr() && OwnsRemappedFileBuffers) {
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000126 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
127 for (PreprocessorOptions::remapped_file_buffer_iterator
128 FB = PPOpts.remapped_file_buffer_begin(),
129 FBEnd = PPOpts.remapped_file_buffer_end();
130 FB != FBEnd;
131 ++FB)
132 delete FB->second;
133 }
Douglas Gregor28233422010-07-27 14:52:07 +0000134
135 delete SavedMainFileBuffer;
Douglas Gregor671947b2010-08-19 01:33:06 +0000136 delete PreambleBuffer;
137
Douglas Gregor213f18b2010-10-28 15:44:59 +0000138 ClearCachedCompletionResults();
Douglas Gregore3c60a72010-11-17 00:13:31 +0000139
140 if (getenv("LIBCLANG_OBJTRACKING")) {
Douglas Gregor1fd9e0d2010-12-07 00:05:48 +0000141 llvm::sys::AtomicDecrement(&ActiveASTUnitObjects);
Douglas Gregore3c60a72010-11-17 00:13:31 +0000142 fprintf(stderr, "--- %d translation units\n", ActiveASTUnitObjects);
143 }
Douglas Gregorabc563f2010-07-19 21:46:24 +0000144}
145
146void ASTUnit::CleanTemporaryFiles() {
Douglas Gregor313e26c2010-02-18 23:35:40 +0000147 for (unsigned I = 0, N = TemporaryFiles.size(); I != N; ++I)
148 TemporaryFiles[I].eraseFromDisk();
Douglas Gregorabc563f2010-07-19 21:46:24 +0000149 TemporaryFiles.clear();
Steve Naroffe19944c2009-10-15 22:23:48 +0000150}
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000151
Douglas Gregor8071e422010-08-15 06:18:01 +0000152/// \brief Determine the set of code-completion contexts in which this
153/// declaration should be shown.
154static unsigned getDeclShowContexts(NamedDecl *ND,
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000155 const LangOptions &LangOpts,
156 bool &IsNestedNameSpecifier) {
157 IsNestedNameSpecifier = false;
158
Douglas Gregor8071e422010-08-15 06:18:01 +0000159 if (isa<UsingShadowDecl>(ND))
160 ND = dyn_cast<NamedDecl>(ND->getUnderlyingDecl());
161 if (!ND)
162 return 0;
163
164 unsigned Contexts = 0;
165 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND) ||
166 isa<ClassTemplateDecl>(ND) || isa<TemplateTemplateParmDecl>(ND)) {
167 // Types can appear in these contexts.
168 if (LangOpts.CPlusPlus || !isa<TagDecl>(ND))
169 Contexts |= (1 << (CodeCompletionContext::CCC_TopLevel - 1))
170 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
171 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
172 | (1 << (CodeCompletionContext::CCC_Statement - 1))
Douglas Gregor02688102010-09-14 23:59:36 +0000173 | (1 << (CodeCompletionContext::CCC_Type - 1))
174 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1));
Douglas Gregor8071e422010-08-15 06:18:01 +0000175
176 // In C++, types can appear in expressions contexts (for functional casts).
177 if (LangOpts.CPlusPlus)
178 Contexts |= (1 << (CodeCompletionContext::CCC_Expression - 1));
179
180 // In Objective-C, message sends can send interfaces. In Objective-C++,
181 // all types are available due to functional casts.
182 if (LangOpts.CPlusPlus || isa<ObjCInterfaceDecl>(ND))
183 Contexts |= (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1));
184
185 // Deal with tag names.
186 if (isa<EnumDecl>(ND)) {
187 Contexts |= (1 << (CodeCompletionContext::CCC_EnumTag - 1));
188
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000189 // Part of the nested-name-specifier in C++0x.
Douglas Gregor8071e422010-08-15 06:18:01 +0000190 if (LangOpts.CPlusPlus0x)
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000191 IsNestedNameSpecifier = true;
Douglas Gregor8071e422010-08-15 06:18:01 +0000192 } else if (RecordDecl *Record = dyn_cast<RecordDecl>(ND)) {
193 if (Record->isUnion())
194 Contexts |= (1 << (CodeCompletionContext::CCC_UnionTag - 1));
195 else
196 Contexts |= (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1));
197
Douglas Gregor8071e422010-08-15 06:18:01 +0000198 if (LangOpts.CPlusPlus)
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000199 IsNestedNameSpecifier = true;
Douglas Gregor52779fb2010-09-23 23:01:17 +0000200 } else if (isa<ClassTemplateDecl>(ND))
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000201 IsNestedNameSpecifier = true;
Douglas Gregor8071e422010-08-15 06:18:01 +0000202 } else if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
203 // Values can appear in these contexts.
204 Contexts = (1 << (CodeCompletionContext::CCC_Statement - 1))
205 | (1 << (CodeCompletionContext::CCC_Expression - 1))
Douglas Gregor02688102010-09-14 23:59:36 +0000206 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1))
Douglas Gregor8071e422010-08-15 06:18:01 +0000207 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1));
208 } else if (isa<ObjCProtocolDecl>(ND)) {
209 Contexts = (1 << (CodeCompletionContext::CCC_ObjCProtocolName - 1));
210 } else if (isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) {
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000211 Contexts = (1 << (CodeCompletionContext::CCC_Namespace - 1));
Douglas Gregor8071e422010-08-15 06:18:01 +0000212
213 // Part of the nested-name-specifier.
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000214 IsNestedNameSpecifier = true;
Douglas Gregor8071e422010-08-15 06:18:01 +0000215 }
216
217 return Contexts;
218}
219
Douglas Gregor87c08a52010-08-13 22:48:40 +0000220void ASTUnit::CacheCodeCompletionResults() {
221 if (!TheSema)
222 return;
223
Douglas Gregor213f18b2010-10-28 15:44:59 +0000224 SimpleTimer Timer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +0000225 Timer.setOutput("Cache global code completions for " + getMainFileName());
Douglas Gregor87c08a52010-08-13 22:48:40 +0000226
227 // Clear out the previous results.
228 ClearCachedCompletionResults();
229
230 // Gather the set of global code completions.
John McCall0a2c5e22010-08-25 06:19:51 +0000231 typedef CodeCompletionResult Result;
Douglas Gregor87c08a52010-08-13 22:48:40 +0000232 llvm::SmallVector<Result, 8> Results;
Douglas Gregor48601b32011-02-16 19:08:06 +0000233 CachedCompletionAllocator = new GlobalCodeCompletionAllocator;
234 TheSema->GatherGlobalCodeCompletions(*CachedCompletionAllocator, Results);
Douglas Gregor87c08a52010-08-13 22:48:40 +0000235
236 // Translate global code completions into cached completions.
Douglas Gregorf5586f62010-08-16 18:08:11 +0000237 llvm::DenseMap<CanQualType, unsigned> CompletionTypes;
238
Douglas Gregor87c08a52010-08-13 22:48:40 +0000239 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
240 switch (Results[I].Kind) {
Douglas Gregor8071e422010-08-15 06:18:01 +0000241 case Result::RK_Declaration: {
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000242 bool IsNestedNameSpecifier = false;
Douglas Gregor8071e422010-08-15 06:18:01 +0000243 CachedCodeCompletionResult CachedResult;
Douglas Gregor218937c2011-02-01 19:23:04 +0000244 CachedResult.Completion = Results[I].CreateCodeCompletionString(*TheSema,
Douglas Gregor48601b32011-02-16 19:08:06 +0000245 *CachedCompletionAllocator);
Douglas Gregor8071e422010-08-15 06:18:01 +0000246 CachedResult.ShowInContexts = getDeclShowContexts(Results[I].Declaration,
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000247 Ctx->getLangOptions(),
248 IsNestedNameSpecifier);
Douglas Gregor8071e422010-08-15 06:18:01 +0000249 CachedResult.Priority = Results[I].Priority;
250 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregor58ddb602010-08-23 23:00:57 +0000251 CachedResult.Availability = Results[I].Availability;
Douglas Gregorc4421e92010-08-16 16:46:30 +0000252
Douglas Gregorf5586f62010-08-16 18:08:11 +0000253 // Keep track of the type of this completion in an ASTContext-agnostic
254 // way.
Douglas Gregorc4421e92010-08-16 16:46:30 +0000255 QualType UsageType = getDeclUsageType(*Ctx, Results[I].Declaration);
Douglas Gregorf5586f62010-08-16 18:08:11 +0000256 if (UsageType.isNull()) {
Douglas Gregorc4421e92010-08-16 16:46:30 +0000257 CachedResult.TypeClass = STC_Void;
Douglas Gregorf5586f62010-08-16 18:08:11 +0000258 CachedResult.Type = 0;
259 } else {
260 CanQualType CanUsageType
261 = Ctx->getCanonicalType(UsageType.getUnqualifiedType());
262 CachedResult.TypeClass = getSimplifiedTypeClass(CanUsageType);
263
264 // Determine whether we have already seen this type. If so, we save
265 // ourselves the work of formatting the type string by using the
266 // temporary, CanQualType-based hash table to find the associated value.
267 unsigned &TypeValue = CompletionTypes[CanUsageType];
268 if (TypeValue == 0) {
269 TypeValue = CompletionTypes.size();
270 CachedCompletionTypes[QualType(CanUsageType).getAsString()]
271 = TypeValue;
272 }
273
274 CachedResult.Type = TypeValue;
Douglas Gregorc4421e92010-08-16 16:46:30 +0000275 }
Douglas Gregorf5586f62010-08-16 18:08:11 +0000276
Douglas Gregor8071e422010-08-15 06:18:01 +0000277 CachedCompletionResults.push_back(CachedResult);
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000278
279 /// Handle nested-name-specifiers in C++.
280 if (TheSema->Context.getLangOptions().CPlusPlus &&
281 IsNestedNameSpecifier && !Results[I].StartsNestedNameSpecifier) {
282 // The contexts in which a nested-name-specifier can appear in C++.
283 unsigned NNSContexts
284 = (1 << (CodeCompletionContext::CCC_TopLevel - 1))
285 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
286 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
287 | (1 << (CodeCompletionContext::CCC_Statement - 1))
288 | (1 << (CodeCompletionContext::CCC_Expression - 1))
289 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
290 | (1 << (CodeCompletionContext::CCC_EnumTag - 1))
291 | (1 << (CodeCompletionContext::CCC_UnionTag - 1))
292 | (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1))
Douglas Gregor2ccccb32010-08-23 18:23:48 +0000293 | (1 << (CodeCompletionContext::CCC_Type - 1))
Douglas Gregor02688102010-09-14 23:59:36 +0000294 | (1 << (CodeCompletionContext::CCC_PotentiallyQualifiedName - 1))
295 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1));
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000296
297 if (isa<NamespaceDecl>(Results[I].Declaration) ||
298 isa<NamespaceAliasDecl>(Results[I].Declaration))
299 NNSContexts |= (1 << (CodeCompletionContext::CCC_Namespace - 1));
300
301 if (unsigned RemainingContexts
302 = NNSContexts & ~CachedResult.ShowInContexts) {
303 // If there any contexts where this completion can be a
304 // nested-name-specifier but isn't already an option, create a
305 // nested-name-specifier completion.
306 Results[I].StartsNestedNameSpecifier = true;
Douglas Gregor218937c2011-02-01 19:23:04 +0000307 CachedResult.Completion
308 = Results[I].CreateCodeCompletionString(*TheSema,
Douglas Gregor48601b32011-02-16 19:08:06 +0000309 *CachedCompletionAllocator);
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000310 CachedResult.ShowInContexts = RemainingContexts;
311 CachedResult.Priority = CCP_NestedNameSpecifier;
312 CachedResult.TypeClass = STC_Void;
313 CachedResult.Type = 0;
314 CachedCompletionResults.push_back(CachedResult);
315 }
316 }
Douglas Gregor87c08a52010-08-13 22:48:40 +0000317 break;
Douglas Gregor8071e422010-08-15 06:18:01 +0000318 }
319
Douglas Gregor87c08a52010-08-13 22:48:40 +0000320 case Result::RK_Keyword:
321 case Result::RK_Pattern:
322 // Ignore keywords and patterns; we don't care, since they are so
323 // easily regenerated.
324 break;
325
326 case Result::RK_Macro: {
327 CachedCodeCompletionResult CachedResult;
Douglas Gregor218937c2011-02-01 19:23:04 +0000328 CachedResult.Completion
329 = Results[I].CreateCodeCompletionString(*TheSema,
Douglas Gregor48601b32011-02-16 19:08:06 +0000330 *CachedCompletionAllocator);
Douglas Gregor87c08a52010-08-13 22:48:40 +0000331 CachedResult.ShowInContexts
332 = (1 << (CodeCompletionContext::CCC_TopLevel - 1))
333 | (1 << (CodeCompletionContext::CCC_ObjCInterface - 1))
334 | (1 << (CodeCompletionContext::CCC_ObjCImplementation - 1))
335 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
336 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
337 | (1 << (CodeCompletionContext::CCC_Statement - 1))
338 | (1 << (CodeCompletionContext::CCC_Expression - 1))
Douglas Gregor1fbb4472010-08-24 20:21:13 +0000339 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
Douglas Gregorf29c5232010-08-24 22:20:20 +0000340 | (1 << (CodeCompletionContext::CCC_MacroNameUse - 1))
Douglas Gregor02688102010-09-14 23:59:36 +0000341 | (1 << (CodeCompletionContext::CCC_PreprocessorExpression - 1))
Douglas Gregor5c722c702011-02-18 23:30:37 +0000342 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1))
343 | (1 << (CodeCompletionContext::CCC_OtherWithMacros - 1));
Douglas Gregor2ccccb32010-08-23 18:23:48 +0000344
Douglas Gregor87c08a52010-08-13 22:48:40 +0000345 CachedResult.Priority = Results[I].Priority;
346 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregor58ddb602010-08-23 23:00:57 +0000347 CachedResult.Availability = Results[I].Availability;
Douglas Gregor1827e102010-08-16 16:18:59 +0000348 CachedResult.TypeClass = STC_Void;
Douglas Gregorf5586f62010-08-16 18:08:11 +0000349 CachedResult.Type = 0;
Douglas Gregor87c08a52010-08-13 22:48:40 +0000350 CachedCompletionResults.push_back(CachedResult);
351 break;
352 }
353 }
Douglas Gregor87c08a52010-08-13 22:48:40 +0000354 }
Douglas Gregor9b7db622011-02-16 18:16:54 +0000355
356 // Save the current top-level hash value.
357 CompletionCacheTopLevelHashValue = CurrentTopLevelHashValue;
Douglas Gregor87c08a52010-08-13 22:48:40 +0000358}
359
360void ASTUnit::ClearCachedCompletionResults() {
Douglas Gregor87c08a52010-08-13 22:48:40 +0000361 CachedCompletionResults.clear();
Douglas Gregorf5586f62010-08-16 18:08:11 +0000362 CachedCompletionTypes.clear();
Douglas Gregor48601b32011-02-16 19:08:06 +0000363 CachedCompletionAllocator = 0;
Douglas Gregor87c08a52010-08-13 22:48:40 +0000364}
365
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000366namespace {
367
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000368/// \brief Gathers information from ASTReader that will be used to initialize
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000369/// a Preprocessor.
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000370class ASTInfoCollector : public ASTReaderListener {
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000371 LangOptions &LangOpt;
372 HeaderSearch &HSI;
373 std::string &TargetTriple;
374 std::string &Predefines;
375 unsigned &Counter;
Mike Stump1eb44332009-09-09 15:08:12 +0000376
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000377 unsigned NumHeaderInfos;
Mike Stump1eb44332009-09-09 15:08:12 +0000378
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000379public:
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000380 ASTInfoCollector(LangOptions &LangOpt, HeaderSearch &HSI,
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000381 std::string &TargetTriple, std::string &Predefines,
382 unsigned &Counter)
383 : LangOpt(LangOpt), HSI(HSI), TargetTriple(TargetTriple),
384 Predefines(Predefines), Counter(Counter), NumHeaderInfos(0) {}
Mike Stump1eb44332009-09-09 15:08:12 +0000385
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000386 virtual bool ReadLanguageOptions(const LangOptions &LangOpts) {
387 LangOpt = LangOpts;
388 return false;
389 }
Mike Stump1eb44332009-09-09 15:08:12 +0000390
Daniel Dunbardc3c0d22009-11-11 00:52:11 +0000391 virtual bool ReadTargetTriple(llvm::StringRef Triple) {
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000392 TargetTriple = Triple;
393 return false;
394 }
Mike Stump1eb44332009-09-09 15:08:12 +0000395
Sebastian Redlcb481aa2010-07-14 23:29:55 +0000396 virtual bool ReadPredefinesBuffer(const PCHPredefinesBlocks &Buffers,
Daniel Dunbar7b5a1212009-11-11 05:29:04 +0000397 llvm::StringRef OriginalFileName,
Nick Lewycky277a6e72011-02-23 21:16:44 +0000398 std::string &SuggestedPredefines,
399 FileManager &FileMgr) {
Sebastian Redlcb481aa2010-07-14 23:29:55 +0000400 Predefines = Buffers[0].Data;
401 for (unsigned I = 1, N = Buffers.size(); I != N; ++I) {
402 Predefines += Buffers[I].Data;
403 }
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000404 return false;
405 }
Mike Stump1eb44332009-09-09 15:08:12 +0000406
Douglas Gregorec1afbf2010-03-16 19:09:18 +0000407 virtual void ReadHeaderFileInfo(const HeaderFileInfo &HFI, unsigned ID) {
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000408 HSI.setHeaderFileInfoForUID(HFI, NumHeaderInfos++);
409 }
Mike Stump1eb44332009-09-09 15:08:12 +0000410
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000411 virtual void ReadCounter(unsigned Value) {
412 Counter = Value;
413 }
414};
415
Douglas Gregora88084b2010-02-18 18:08:43 +0000416class StoredDiagnosticClient : public DiagnosticClient {
417 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiags;
418
419public:
420 explicit StoredDiagnosticClient(
421 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiags)
422 : StoredDiags(StoredDiags) { }
423
424 virtual void HandleDiagnostic(Diagnostic::Level Level,
425 const DiagnosticInfo &Info);
426};
427
428/// \brief RAII object that optionally captures diagnostics, if
429/// there is no diagnostic client to capture them already.
430class CaptureDroppedDiagnostics {
431 Diagnostic &Diags;
432 StoredDiagnosticClient Client;
433 DiagnosticClient *PreviousClient;
434
435public:
436 CaptureDroppedDiagnostics(bool RequestCapture, Diagnostic &Diags,
Douglas Gregore47be3e2010-11-11 00:39:14 +0000437 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiags)
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000438 : Diags(Diags), Client(StoredDiags), PreviousClient(0)
Douglas Gregora88084b2010-02-18 18:08:43 +0000439 {
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000440 if (RequestCapture || Diags.getClient() == 0) {
441 PreviousClient = Diags.takeClient();
Douglas Gregora88084b2010-02-18 18:08:43 +0000442 Diags.setClient(&Client);
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000443 }
Douglas Gregora88084b2010-02-18 18:08:43 +0000444 }
445
446 ~CaptureDroppedDiagnostics() {
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000447 if (Diags.getClient() == &Client) {
448 Diags.takeClient();
449 Diags.setClient(PreviousClient);
450 }
Douglas Gregora88084b2010-02-18 18:08:43 +0000451 }
452};
453
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000454} // anonymous namespace
455
Douglas Gregora88084b2010-02-18 18:08:43 +0000456void StoredDiagnosticClient::HandleDiagnostic(Diagnostic::Level Level,
457 const DiagnosticInfo &Info) {
Argyrios Kyrtzidisf2224d82010-11-18 20:06:46 +0000458 // Default implementation (Warnings/errors count).
459 DiagnosticClient::HandleDiagnostic(Level, Info);
460
Douglas Gregora88084b2010-02-18 18:08:43 +0000461 StoredDiags.push_back(StoredDiagnostic(Level, Info));
462}
463
Steve Naroff77accc12009-09-03 18:19:54 +0000464const std::string &ASTUnit::getOriginalSourceFileName() {
Daniel Dunbar68d40e22009-12-02 08:44:16 +0000465 return OriginalSourceFile;
Steve Naroff77accc12009-09-03 18:19:54 +0000466}
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000467
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000468const std::string &ASTUnit::getASTFileName() {
469 assert(isMainFileAST() && "Not an ASTUnit from an AST file!");
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000470 return static_cast<ASTReader *>(Ctx->getExternalSource())->getFileName();
Steve Naroffe19944c2009-10-15 22:23:48 +0000471}
472
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +0000473llvm::MemoryBuffer *ASTUnit::getBufferForFile(llvm::StringRef Filename,
Chris Lattner75dfb652010-11-23 09:19:42 +0000474 std::string *ErrorStr) {
Chris Lattner39b49bc2010-11-23 08:35:12 +0000475 assert(FileMgr);
Chris Lattner75dfb652010-11-23 09:19:42 +0000476 return FileMgr->getBufferForFile(Filename, ErrorStr);
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +0000477}
478
Douglas Gregore47be3e2010-11-11 00:39:14 +0000479/// \brief Configure the diagnostics object for use with ASTUnit.
480void ASTUnit::ConfigureDiags(llvm::IntrusiveRefCntPtr<Diagnostic> &Diags,
Douglas Gregor0b53cf82011-01-19 01:02:47 +0000481 const char **ArgBegin, const char **ArgEnd,
Douglas Gregore47be3e2010-11-11 00:39:14 +0000482 ASTUnit &AST, bool CaptureDiagnostics) {
483 if (!Diags.getPtr()) {
484 // No diagnostics engine was provided, so create our own diagnostics object
485 // with the default options.
486 DiagnosticOptions DiagOpts;
487 DiagnosticClient *Client = 0;
488 if (CaptureDiagnostics)
489 Client = new StoredDiagnosticClient(AST.StoredDiagnostics);
Douglas Gregor0b53cf82011-01-19 01:02:47 +0000490 Diags = CompilerInstance::createDiagnostics(DiagOpts, ArgEnd- ArgBegin,
491 ArgBegin, Client);
Douglas Gregore47be3e2010-11-11 00:39:14 +0000492 } else if (CaptureDiagnostics) {
493 Diags->setClient(new StoredDiagnosticClient(AST.StoredDiagnostics));
494 }
495}
496
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000497ASTUnit *ASTUnit::LoadFromASTFile(const std::string &Filename,
Douglas Gregor28019772010-04-05 23:52:57 +0000498 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +0000499 const FileSystemOptions &FileSystemOpts,
Ted Kremenek5cf48762009-10-17 00:34:24 +0000500 bool OnlyLocalDecls,
Douglas Gregor4db64a42010-01-23 00:14:00 +0000501 RemappedFile *RemappedFiles,
Douglas Gregora88084b2010-02-18 18:08:43 +0000502 unsigned NumRemappedFiles,
503 bool CaptureDiagnostics) {
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000504 llvm::OwningPtr<ASTUnit> AST(new ASTUnit(true));
Ted Kremenekb547eeb2011-03-18 02:06:56 +0000505
506 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +0000507 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
508 ASTUnitCleanup(AST.get());
509 llvm::CrashRecoveryContextCleanupRegistrar<Diagnostic,
510 llvm::CrashRecoveryContextReleaseRefCleanup<Diagnostic> >
511 DiagCleanup(Diags.getPtr());
Ted Kremenekb547eeb2011-03-18 02:06:56 +0000512
Douglas Gregor0b53cf82011-01-19 01:02:47 +0000513 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
Douglas Gregorabc563f2010-07-19 21:46:24 +0000514
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000515 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregore47be3e2010-11-11 00:39:14 +0000516 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor28019772010-04-05 23:52:57 +0000517 AST->Diagnostics = Diags;
Ted Kremenek4f327862011-03-21 18:40:17 +0000518 AST->FileMgr = new FileManager(FileSystemOpts);
519 AST->SourceMgr = new SourceManager(AST->getDiagnostics(),
520 AST->getFileManager());
Chris Lattner39b49bc2010-11-23 08:35:12 +0000521 AST->HeaderInfo.reset(new HeaderSearch(AST->getFileManager()));
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000522
Douglas Gregor4db64a42010-01-23 00:14:00 +0000523 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000524 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
525 if (const llvm::MemoryBuffer *
526 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
527 // Create the file entry for the file that we're mapping from.
528 const FileEntry *FromFile
529 = AST->getFileManager().getVirtualFile(RemappedFiles[I].first,
530 memBuf->getBufferSize(),
531 0);
532 if (!FromFile) {
533 AST->getDiagnostics().Report(diag::err_fe_remap_missing_from_file)
534 << RemappedFiles[I].first;
535 delete memBuf;
536 continue;
537 }
538
539 // Override the contents of the "from" file with the contents of
540 // the "to" file.
541 AST->getSourceManager().overrideFileContents(FromFile, memBuf);
542
543 } else {
544 const char *fname = fileOrBuf.get<const char *>();
545 const FileEntry *ToFile = AST->FileMgr->getFile(fname);
546 if (!ToFile) {
547 AST->getDiagnostics().Report(diag::err_fe_remap_missing_to_file)
548 << RemappedFiles[I].first << fname;
549 continue;
550 }
551
552 // Create the file entry for the file that we're mapping from.
553 const FileEntry *FromFile
554 = AST->getFileManager().getVirtualFile(RemappedFiles[I].first,
555 ToFile->getSize(),
556 0);
557 if (!FromFile) {
558 AST->getDiagnostics().Report(diag::err_fe_remap_missing_from_file)
559 << RemappedFiles[I].first;
560 delete memBuf;
561 continue;
562 }
563
564 // Override the contents of the "from" file with the contents of
565 // the "to" file.
566 AST->getSourceManager().overrideFileContents(FromFile, ToFile);
Douglas Gregor4db64a42010-01-23 00:14:00 +0000567 }
Douglas Gregor4db64a42010-01-23 00:14:00 +0000568 }
569
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000570 // Gather Info for preprocessor construction later on.
Mike Stump1eb44332009-09-09 15:08:12 +0000571
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000572 LangOptions LangInfo;
573 HeaderSearch &HeaderInfo = *AST->HeaderInfo.get();
574 std::string TargetTriple;
575 std::string Predefines;
576 unsigned Counter;
577
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000578 llvm::OwningPtr<ASTReader> Reader;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000579
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000580 Reader.reset(new ASTReader(AST->getSourceManager(), AST->getFileManager(),
Chris Lattner39b49bc2010-11-23 08:35:12 +0000581 AST->getDiagnostics()));
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000582 Reader->setListener(new ASTInfoCollector(LangInfo, HeaderInfo, TargetTriple,
Daniel Dunbarcc318932009-09-03 05:59:35 +0000583 Predefines, Counter));
584
Sebastian Redl1d9f1fe2010-10-05 16:15:19 +0000585 switch (Reader->ReadAST(Filename, ASTReader::MainFile)) {
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000586 case ASTReader::Success:
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000587 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000588
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000589 case ASTReader::Failure:
590 case ASTReader::IgnorePCH:
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000591 AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000592 return NULL;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000593 }
Mike Stump1eb44332009-09-09 15:08:12 +0000594
Daniel Dunbar68d40e22009-12-02 08:44:16 +0000595 AST->OriginalSourceFile = Reader->getOriginalSourceFile();
596
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000597 // AST file loaded successfully. Now create the preprocessor.
Mike Stump1eb44332009-09-09 15:08:12 +0000598
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000599 // Get information about the target being compiled for.
Daniel Dunbard58c03f2009-11-15 06:48:46 +0000600 //
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000601 // FIXME: This is broken, we should store the TargetOptions in the AST file.
Daniel Dunbard58c03f2009-11-15 06:48:46 +0000602 TargetOptions TargetOpts;
603 TargetOpts.ABI = "";
John McCall875ab102010-08-22 06:43:33 +0000604 TargetOpts.CXXABI = "";
Daniel Dunbard58c03f2009-11-15 06:48:46 +0000605 TargetOpts.CPU = "";
606 TargetOpts.Features.clear();
607 TargetOpts.Triple = TargetTriple;
Ted Kremenek4f327862011-03-21 18:40:17 +0000608 AST->Target = TargetInfo::CreateTargetInfo(AST->getDiagnostics(),
609 TargetOpts);
610 AST->PP = new Preprocessor(AST->getDiagnostics(), LangInfo, *AST->Target,
611 AST->getSourceManager(), HeaderInfo);
612 Preprocessor &PP = *AST->PP;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000613
Daniel Dunbard5b61262009-09-21 03:03:47 +0000614 PP.setPredefines(Reader->getSuggestedPredefines());
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000615 PP.setCounterValue(Counter);
Daniel Dunbarcc318932009-09-03 05:59:35 +0000616 Reader->setPreprocessor(PP);
Mike Stump1eb44332009-09-09 15:08:12 +0000617
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000618 // Create and initialize the ASTContext.
619
Ted Kremenek4f327862011-03-21 18:40:17 +0000620 AST->Ctx = new ASTContext(LangInfo,
621 AST->getSourceManager(),
622 *AST->Target,
623 PP.getIdentifierTable(),
624 PP.getSelectorTable(),
625 PP.getBuiltinInfo(),
626 /* size_reserve = */0);
627 ASTContext &Context = *AST->Ctx;
Mike Stump1eb44332009-09-09 15:08:12 +0000628
Daniel Dunbarcc318932009-09-03 05:59:35 +0000629 Reader->InitializeContext(Context);
Mike Stump1eb44332009-09-09 15:08:12 +0000630
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000631 // Attach the AST reader to the AST context as an external AST
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000632 // source, so that declarations will be deserialized from the
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000633 // AST file as needed.
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000634 ASTReader *ReaderPtr = Reader.get();
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000635 llvm::OwningPtr<ExternalASTSource> Source(Reader.take());
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000636 Context.setExternalSource(Source);
637
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000638 // Create an AST consumer, even though it isn't used.
639 AST->Consumer.reset(new ASTConsumer);
640
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000641 // Create a semantic analysis object and tell the AST reader about it.
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000642 AST->TheSema.reset(new Sema(PP, Context, *AST->Consumer));
643 AST->TheSema->Initialize();
644 ReaderPtr->InitializeSema(*AST->TheSema);
645
Mike Stump1eb44332009-09-09 15:08:12 +0000646 return AST.take();
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000647}
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000648
649namespace {
650
Douglas Gregor9b7db622011-02-16 18:16:54 +0000651/// \brief Preprocessor callback class that updates a hash value with the names
652/// of all macros that have been defined by the translation unit.
653class MacroDefinitionTrackerPPCallbacks : public PPCallbacks {
654 unsigned &Hash;
655
656public:
657 explicit MacroDefinitionTrackerPPCallbacks(unsigned &Hash) : Hash(Hash) { }
658
659 virtual void MacroDefined(const Token &MacroNameTok, const MacroInfo *MI) {
660 Hash = llvm::HashString(MacroNameTok.getIdentifierInfo()->getName(), Hash);
661 }
662};
663
664/// \brief Add the given declaration to the hash of all top-level entities.
665void AddTopLevelDeclarationToHash(Decl *D, unsigned &Hash) {
666 if (!D)
667 return;
668
669 DeclContext *DC = D->getDeclContext();
670 if (!DC)
671 return;
672
673 if (!(DC->isTranslationUnit() || DC->getLookupParent()->isTranslationUnit()))
674 return;
675
676 if (NamedDecl *ND = dyn_cast<NamedDecl>(D)) {
677 if (ND->getIdentifier())
678 Hash = llvm::HashString(ND->getIdentifier()->getName(), Hash);
679 else if (DeclarationName Name = ND->getDeclName()) {
680 std::string NameStr = Name.getAsString();
681 Hash = llvm::HashString(NameStr, Hash);
682 }
683 return;
684 }
685
686 if (ObjCForwardProtocolDecl *Forward
687 = dyn_cast<ObjCForwardProtocolDecl>(D)) {
688 for (ObjCForwardProtocolDecl::protocol_iterator
689 P = Forward->protocol_begin(),
690 PEnd = Forward->protocol_end();
691 P != PEnd; ++P)
692 AddTopLevelDeclarationToHash(*P, Hash);
693 return;
694 }
695
696 if (ObjCClassDecl *Class = llvm::dyn_cast<ObjCClassDecl>(D)) {
697 for (ObjCClassDecl::iterator I = Class->begin(), IEnd = Class->end();
698 I != IEnd; ++I)
699 AddTopLevelDeclarationToHash(I->getInterface(), Hash);
700 return;
701 }
702}
703
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000704class TopLevelDeclTrackerConsumer : public ASTConsumer {
705 ASTUnit &Unit;
Douglas Gregor9b7db622011-02-16 18:16:54 +0000706 unsigned &Hash;
707
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000708public:
Douglas Gregor9b7db622011-02-16 18:16:54 +0000709 TopLevelDeclTrackerConsumer(ASTUnit &_Unit, unsigned &Hash)
710 : Unit(_Unit), Hash(Hash) {
711 Hash = 0;
712 }
713
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000714 void HandleTopLevelDecl(DeclGroupRef D) {
Ted Kremenekda5a4282010-05-03 20:16:35 +0000715 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
716 Decl *D = *it;
717 // FIXME: Currently ObjC method declarations are incorrectly being
718 // reported as top-level declarations, even though their DeclContext
719 // is the containing ObjC @interface/@implementation. This is a
720 // fundamental problem in the parser right now.
721 if (isa<ObjCMethodDecl>(D))
722 continue;
Douglas Gregor9b7db622011-02-16 18:16:54 +0000723
724 AddTopLevelDeclarationToHash(D, Hash);
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000725 Unit.addTopLevelDecl(D);
Ted Kremenekda5a4282010-05-03 20:16:35 +0000726 }
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000727 }
Sebastian Redl27372b42010-08-11 18:52:41 +0000728
729 // We're not interested in "interesting" decls.
730 void HandleInterestingDecl(DeclGroupRef) {}
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000731};
732
733class TopLevelDeclTrackerAction : public ASTFrontendAction {
734public:
735 ASTUnit &Unit;
736
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000737 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
738 llvm::StringRef InFile) {
Douglas Gregor9b7db622011-02-16 18:16:54 +0000739 CI.getPreprocessor().addPPCallbacks(
740 new MacroDefinitionTrackerPPCallbacks(Unit.getCurrentTopLevelHashValue()));
741 return new TopLevelDeclTrackerConsumer(Unit,
742 Unit.getCurrentTopLevelHashValue());
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000743 }
744
745public:
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000746 TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {}
747
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000748 virtual bool hasCodeCompletionSupport() const { return false; }
Douglas Gregordf95a132010-08-09 20:45:32 +0000749 virtual bool usesCompleteTranslationUnit() {
750 return Unit.isCompleteTranslationUnit();
751 }
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000752};
753
Douglas Gregor89d99802010-11-30 06:16:57 +0000754class PrecompilePreambleConsumer : public PCHGenerator,
755 public ASTSerializationListener {
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000756 ASTUnit &Unit;
Douglas Gregor9b7db622011-02-16 18:16:54 +0000757 unsigned &Hash;
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000758 std::vector<Decl *> TopLevelDecls;
Douglas Gregor89d99802010-11-30 06:16:57 +0000759
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000760public:
761 PrecompilePreambleConsumer(ASTUnit &Unit,
762 const Preprocessor &PP, bool Chaining,
763 const char *isysroot, llvm::raw_ostream *Out)
Douglas Gregor9b7db622011-02-16 18:16:54 +0000764 : PCHGenerator(PP, "", Chaining, isysroot, Out), Unit(Unit),
765 Hash(Unit.getCurrentTopLevelHashValue()) {
766 Hash = 0;
767 }
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000768
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000769 virtual void HandleTopLevelDecl(DeclGroupRef D) {
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000770 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
771 Decl *D = *it;
772 // FIXME: Currently ObjC method declarations are incorrectly being
773 // reported as top-level declarations, even though their DeclContext
774 // is the containing ObjC @interface/@implementation. This is a
775 // fundamental problem in the parser right now.
776 if (isa<ObjCMethodDecl>(D))
777 continue;
Douglas Gregor9b7db622011-02-16 18:16:54 +0000778 AddTopLevelDeclarationToHash(D, Hash);
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000779 TopLevelDecls.push_back(D);
780 }
781 }
782
783 virtual void HandleTranslationUnit(ASTContext &Ctx) {
784 PCHGenerator::HandleTranslationUnit(Ctx);
785 if (!Unit.getDiagnostics().hasErrorOccurred()) {
786 // Translate the top-level declarations we captured during
787 // parsing into declaration IDs in the precompiled
788 // preamble. This will allow us to deserialize those top-level
789 // declarations when requested.
790 for (unsigned I = 0, N = TopLevelDecls.size(); I != N; ++I)
791 Unit.addTopLevelDeclFromPreamble(
792 getWriter().getDeclID(TopLevelDecls[I]));
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000793 }
794 }
Douglas Gregor89d99802010-11-30 06:16:57 +0000795
796 virtual void SerializedPreprocessedEntity(PreprocessedEntity *Entity,
797 uint64_t Offset) {
798 Unit.addPreprocessedEntityFromPreamble(Offset);
799 }
800
801 virtual ASTSerializationListener *GetASTSerializationListener() {
802 return this;
803 }
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000804};
805
806class PrecompilePreambleAction : public ASTFrontendAction {
807 ASTUnit &Unit;
808
809public:
810 explicit PrecompilePreambleAction(ASTUnit &Unit) : Unit(Unit) {}
811
812 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
813 llvm::StringRef InFile) {
814 std::string Sysroot;
Argyrios Kyrtzidis8e3df4d2011-02-15 17:54:22 +0000815 std::string OutputFile;
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000816 llvm::raw_ostream *OS = 0;
817 bool Chaining;
Argyrios Kyrtzidis8e3df4d2011-02-15 17:54:22 +0000818 if (GeneratePCHAction::ComputeASTConsumerArguments(CI, InFile, Sysroot,
819 OutputFile,
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000820 OS, Chaining))
821 return 0;
822
823 const char *isysroot = CI.getFrontendOpts().RelocatablePCH ?
824 Sysroot.c_str() : 0;
Douglas Gregor9b7db622011-02-16 18:16:54 +0000825 CI.getPreprocessor().addPPCallbacks(
826 new MacroDefinitionTrackerPPCallbacks(Unit.getCurrentTopLevelHashValue()));
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000827 return new PrecompilePreambleConsumer(Unit, CI.getPreprocessor(), Chaining,
828 isysroot, OS);
829 }
830
831 virtual bool hasCodeCompletionSupport() const { return false; }
832 virtual bool hasASTFileSupport() const { return false; }
Douglas Gregordf95a132010-08-09 20:45:32 +0000833 virtual bool usesCompleteTranslationUnit() { return false; }
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000834};
835
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000836}
837
Douglas Gregorabc563f2010-07-19 21:46:24 +0000838/// Parse the source file into a translation unit using the given compiler
839/// invocation, replacing the current translation unit.
840///
841/// \returns True if a failure occurred that causes the ASTUnit not to
842/// contain any translation-unit information, false otherwise.
Douglas Gregor754f3492010-07-24 00:38:13 +0000843bool ASTUnit::Parse(llvm::MemoryBuffer *OverrideMainBuffer) {
Douglas Gregor28233422010-07-27 14:52:07 +0000844 delete SavedMainFileBuffer;
845 SavedMainFileBuffer = 0;
846
Ted Kremenek4f327862011-03-21 18:40:17 +0000847 if (!Invocation) {
Douglas Gregor671947b2010-08-19 01:33:06 +0000848 delete OverrideMainBuffer;
Douglas Gregorabc563f2010-07-19 21:46:24 +0000849 return true;
Douglas Gregor671947b2010-08-19 01:33:06 +0000850 }
Douglas Gregorabc563f2010-07-19 21:46:24 +0000851
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000852 // Create the compiler instance to use for building the AST.
Ted Kremenek03201fb2011-03-21 18:40:07 +0000853 llvm::OwningPtr<CompilerInstance> Clang(new CompilerInstance());
854
855 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +0000856 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
857 CICleanup(Clang.get());
Ted Kremenek03201fb2011-03-21 18:40:07 +0000858
Ted Kremenek4f327862011-03-21 18:40:17 +0000859 Clang->setInvocation(&*Invocation);
Ted Kremenek03201fb2011-03-21 18:40:07 +0000860 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].second;
Douglas Gregorabc563f2010-07-19 21:46:24 +0000861
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000862 // Set up diagnostics, capturing any diagnostics that would
863 // otherwise be dropped.
Ted Kremenek03201fb2011-03-21 18:40:07 +0000864 Clang->setDiagnostics(&getDiagnostics());
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000865
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000866 // Create the target instance.
Ted Kremenek03201fb2011-03-21 18:40:07 +0000867 Clang->getTargetOpts().Features = TargetFeatures;
868 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
Ted Kremenek4f327862011-03-21 18:40:17 +0000869 Clang->getTargetOpts()));
Ted Kremenek03201fb2011-03-21 18:40:07 +0000870 if (!Clang->hasTarget()) {
Douglas Gregor671947b2010-08-19 01:33:06 +0000871 delete OverrideMainBuffer;
Douglas Gregorabc563f2010-07-19 21:46:24 +0000872 return true;
Douglas Gregor671947b2010-08-19 01:33:06 +0000873 }
874
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000875 // Inform the target of the language options.
876 //
877 // FIXME: We shouldn't need to do this, the target should be immutable once
878 // created. This complexity should be lifted elsewhere.
Ted Kremenek03201fb2011-03-21 18:40:07 +0000879 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregorabc563f2010-07-19 21:46:24 +0000880
Ted Kremenek03201fb2011-03-21 18:40:07 +0000881 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000882 "Invocation must have exactly one source file!");
Ted Kremenek03201fb2011-03-21 18:40:07 +0000883 assert(Clang->getFrontendOpts().Inputs[0].first != IK_AST &&
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000884 "FIXME: AST inputs not yet supported here!");
Ted Kremenek03201fb2011-03-21 18:40:07 +0000885 assert(Clang->getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
Daniel Dunbarfaddc3e2010-06-07 23:26:47 +0000886 "IR inputs not support here!");
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000887
Douglas Gregorabc563f2010-07-19 21:46:24 +0000888 // Configure the various subsystems.
889 // FIXME: Should we retain the previous file manager?
Ted Kremenek03201fb2011-03-21 18:40:07 +0000890 FileSystemOpts = Clang->getFileSystemOpts();
Ted Kremenek4f327862011-03-21 18:40:17 +0000891 FileMgr = new FileManager(FileSystemOpts);
892 SourceMgr = new SourceManager(getDiagnostics(), *FileMgr);
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000893 TheSema.reset();
Ted Kremenek4f327862011-03-21 18:40:17 +0000894 Ctx = 0;
895 PP = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +0000896
897 // Clear out old caches and data.
898 TopLevelDecls.clear();
Douglas Gregor89d99802010-11-30 06:16:57 +0000899 PreprocessedEntities.clear();
Douglas Gregorabc563f2010-07-19 21:46:24 +0000900 CleanTemporaryFiles();
901 PreprocessedEntitiesByFile.clear();
Douglas Gregorc0659ec2010-08-02 20:51:39 +0000902
Douglas Gregorf128fed2010-08-20 00:02:33 +0000903 if (!OverrideMainBuffer) {
Douglas Gregor4cd912a2010-10-12 00:50:20 +0000904 StoredDiagnostics.erase(
905 StoredDiagnostics.begin() + NumStoredDiagnosticsFromDriver,
906 StoredDiagnostics.end());
Douglas Gregorf128fed2010-08-20 00:02:33 +0000907 TopLevelDeclsInPreamble.clear();
Douglas Gregor89d99802010-11-30 06:16:57 +0000908 PreprocessedEntitiesInPreamble.clear();
Douglas Gregorf128fed2010-08-20 00:02:33 +0000909 }
910
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000911 // Create a file manager object to provide access to and cache the filesystem.
Ted Kremenek03201fb2011-03-21 18:40:07 +0000912 Clang->setFileManager(&getFileManager());
Douglas Gregorabc563f2010-07-19 21:46:24 +0000913
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000914 // Create the source manager.
Ted Kremenek03201fb2011-03-21 18:40:07 +0000915 Clang->setSourceManager(&getSourceManager());
Douglas Gregorabc563f2010-07-19 21:46:24 +0000916
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000917 // If the main file has been overridden due to the use of a preamble,
918 // make that override happen and introduce the preamble.
Ted Kremenek03201fb2011-03-21 18:40:07 +0000919 PreprocessorOptions &PreprocessorOpts = Clang->getPreprocessorOpts();
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000920 std::string PriorImplicitPCHInclude;
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000921 if (OverrideMainBuffer) {
922 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
923 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
924 PreprocessorOpts.PrecompiledPreambleBytes.second
925 = PreambleEndsAtStartOfLine;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000926 PriorImplicitPCHInclude = PreprocessorOpts.ImplicitPCHInclude;
Douglas Gregor385103b2010-07-30 20:58:08 +0000927 PreprocessorOpts.ImplicitPCHInclude = PreambleFile;
Douglas Gregorfae3b2f2010-07-27 00:27:13 +0000928 PreprocessorOpts.DisablePCHValidation = true;
Douglas Gregor28233422010-07-27 14:52:07 +0000929
Douglas Gregorc0659ec2010-08-02 20:51:39 +0000930 // The stored diagnostic has the old source manager in it; update
931 // the locations to refer into the new source manager. Since we've
932 // been careful to make sure that the source manager's state
933 // before and after are identical, so that we can reuse the source
934 // location itself.
Douglas Gregor4cd912a2010-10-12 00:50:20 +0000935 for (unsigned I = NumStoredDiagnosticsFromDriver,
936 N = StoredDiagnostics.size();
937 I < N; ++I) {
Douglas Gregorc0659ec2010-08-02 20:51:39 +0000938 FullSourceLoc Loc(StoredDiagnostics[I].getLocation(),
939 getSourceManager());
940 StoredDiagnostics[I].setLocation(Loc);
941 }
Douglas Gregor4cd912a2010-10-12 00:50:20 +0000942
943 // Keep track of the override buffer;
944 SavedMainFileBuffer = OverrideMainBuffer;
Douglas Gregorf128fed2010-08-20 00:02:33 +0000945 } else {
946 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
947 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000948 }
949
Ted Kremenek25a11e12011-03-22 01:15:24 +0000950 llvm::OwningPtr<TopLevelDeclTrackerAction> Act(
951 new TopLevelDeclTrackerAction(*this));
952
953 // Recover resources if we crash before exiting this method.
954 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
955 ActCleanup(Act.get());
956
Ted Kremenek03201fb2011-03-21 18:40:07 +0000957 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0].second,
958 Clang->getFrontendOpts().Inputs[0].first))
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000959 goto error;
Douglas Gregorabc563f2010-07-19 21:46:24 +0000960
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000961 Act->Execute();
Douglas Gregorabc563f2010-07-19 21:46:24 +0000962
Ted Kremenek4f327862011-03-21 18:40:17 +0000963 // Steal the created target, context, and preprocessor.
Ted Kremenek03201fb2011-03-21 18:40:07 +0000964 TheSema.reset(Clang->takeSema());
965 Consumer.reset(Clang->takeASTConsumer());
Ted Kremenek4f327862011-03-21 18:40:17 +0000966 Ctx = &Clang->getASTContext();
967 PP = &Clang->getPreprocessor();
968 Clang->setSourceManager(0);
969 Clang->setFileManager(0);
970 Target = &Clang->getTarget();
Douglas Gregorabc563f2010-07-19 21:46:24 +0000971
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000972 Act->EndSourceFile();
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000973
974 // Remove the overridden buffer we used for the preamble.
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000975 if (OverrideMainBuffer) {
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000976 PreprocessorOpts.eraseRemappedFile(
977 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000978 PreprocessorOpts.ImplicitPCHInclude = PriorImplicitPCHInclude;
979 }
980
Douglas Gregorabc563f2010-07-19 21:46:24 +0000981 return false;
Ted Kremenek4f327862011-03-21 18:40:17 +0000982
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000983error:
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000984 // Remove the overridden buffer we used for the preamble.
Douglas Gregorfae3b2f2010-07-27 00:27:13 +0000985 if (OverrideMainBuffer) {
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000986 PreprocessorOpts.eraseRemappedFile(
987 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000988 PreprocessorOpts.ImplicitPCHInclude = PriorImplicitPCHInclude;
Douglas Gregor671947b2010-08-19 01:33:06 +0000989 delete OverrideMainBuffer;
Douglas Gregor37cf6632010-10-06 21:11:08 +0000990 SavedMainFileBuffer = 0;
Douglas Gregorfae3b2f2010-07-27 00:27:13 +0000991 }
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000992
Douglas Gregord54eb442010-10-12 16:25:54 +0000993 StoredDiagnostics.clear();
Douglas Gregorabc563f2010-07-19 21:46:24 +0000994 return true;
995}
996
Douglas Gregor44c181a2010-07-23 00:33:23 +0000997/// \brief Simple function to retrieve a path for a preamble precompiled header.
998static std::string GetPreamblePCHPath() {
999 // FIXME: This is lame; sys::Path should provide this function (in particular,
1000 // it should know how to find the temporary files dir).
1001 // FIXME: This is really lame. I copied this code from the Driver!
Douglas Gregor424668c2010-09-11 18:05:19 +00001002 // FIXME: This is a hack so that we can override the preamble file during
1003 // crash-recovery testing, which is the only case where the preamble files
1004 // are not necessarily cleaned up.
1005 const char *TmpFile = ::getenv("CINDEXTEST_PREAMBLE_FILE");
1006 if (TmpFile)
1007 return TmpFile;
1008
Douglas Gregor44c181a2010-07-23 00:33:23 +00001009 std::string Error;
1010 const char *TmpDir = ::getenv("TMPDIR");
1011 if (!TmpDir)
1012 TmpDir = ::getenv("TEMP");
1013 if (!TmpDir)
1014 TmpDir = ::getenv("TMP");
Douglas Gregorc6cb2b02010-09-11 17:51:16 +00001015#ifdef LLVM_ON_WIN32
1016 if (!TmpDir)
1017 TmpDir = ::getenv("USERPROFILE");
1018#endif
Douglas Gregor44c181a2010-07-23 00:33:23 +00001019 if (!TmpDir)
1020 TmpDir = "/tmp";
1021 llvm::sys::Path P(TmpDir);
Douglas Gregorc6cb2b02010-09-11 17:51:16 +00001022 P.createDirectoryOnDisk(true);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001023 P.appendComponent("preamble");
Douglas Gregor6bf18302010-08-11 13:06:56 +00001024 P.appendSuffix("pch");
Douglas Gregor44c181a2010-07-23 00:33:23 +00001025 if (P.createTemporaryFileOnDisk())
1026 return std::string();
1027
Douglas Gregor44c181a2010-07-23 00:33:23 +00001028 return P.str();
1029}
1030
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001031/// \brief Compute the preamble for the main file, providing the source buffer
1032/// that corresponds to the main file along with a pair (bytes, start-of-line)
1033/// that describes the preamble.
1034std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> >
Douglas Gregordf95a132010-08-09 20:45:32 +00001035ASTUnit::ComputePreamble(CompilerInvocation &Invocation,
1036 unsigned MaxLines, bool &CreatedBuffer) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001037 FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
Chris Lattner39b49bc2010-11-23 08:35:12 +00001038 PreprocessorOptions &PreprocessorOpts = Invocation.getPreprocessorOpts();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001039 CreatedBuffer = false;
1040
Douglas Gregor44c181a2010-07-23 00:33:23 +00001041 // Try to determine if the main file has been remapped, either from the
1042 // command line (to another file) or directly through the compiler invocation
1043 // (to a memory buffer).
Douglas Gregor175c4a92010-07-23 23:58:40 +00001044 llvm::MemoryBuffer *Buffer = 0;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001045 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].second);
1046 if (const llvm::sys::FileStatus *MainFileStatus = MainFilePath.getFileStatus()) {
1047 // Check whether there is a file-file remapping of the main file
1048 for (PreprocessorOptions::remapped_file_iterator
Douglas Gregor175c4a92010-07-23 23:58:40 +00001049 M = PreprocessorOpts.remapped_file_begin(),
1050 E = PreprocessorOpts.remapped_file_end();
Douglas Gregor44c181a2010-07-23 00:33:23 +00001051 M != E;
1052 ++M) {
1053 llvm::sys::PathWithStatus MPath(M->first);
1054 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
1055 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
1056 // We found a remapping. Try to load the resulting, remapped source.
Douglas Gregor175c4a92010-07-23 23:58:40 +00001057 if (CreatedBuffer) {
Douglas Gregor44c181a2010-07-23 00:33:23 +00001058 delete Buffer;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001059 CreatedBuffer = false;
1060 }
1061
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00001062 Buffer = getBufferForFile(M->second);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001063 if (!Buffer)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001064 return std::make_pair((llvm::MemoryBuffer*)0,
1065 std::make_pair(0, true));
Douglas Gregor175c4a92010-07-23 23:58:40 +00001066 CreatedBuffer = true;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001067 }
1068 }
1069 }
1070
1071 // Check whether there is a file-buffer remapping. It supercedes the
1072 // file-file remapping.
1073 for (PreprocessorOptions::remapped_file_buffer_iterator
1074 M = PreprocessorOpts.remapped_file_buffer_begin(),
1075 E = PreprocessorOpts.remapped_file_buffer_end();
1076 M != E;
1077 ++M) {
1078 llvm::sys::PathWithStatus MPath(M->first);
1079 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
1080 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
1081 // We found a remapping.
Douglas Gregor175c4a92010-07-23 23:58:40 +00001082 if (CreatedBuffer) {
Douglas Gregor44c181a2010-07-23 00:33:23 +00001083 delete Buffer;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001084 CreatedBuffer = false;
1085 }
Douglas Gregor44c181a2010-07-23 00:33:23 +00001086
Douglas Gregor175c4a92010-07-23 23:58:40 +00001087 Buffer = const_cast<llvm::MemoryBuffer *>(M->second);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001088 }
1089 }
Douglas Gregor175c4a92010-07-23 23:58:40 +00001090 }
Douglas Gregor44c181a2010-07-23 00:33:23 +00001091 }
1092
1093 // If the main source file was not remapped, load it now.
1094 if (!Buffer) {
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00001095 Buffer = getBufferForFile(FrontendOpts.Inputs[0].second);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001096 if (!Buffer)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001097 return std::make_pair((llvm::MemoryBuffer*)0, std::make_pair(0, true));
Douglas Gregor175c4a92010-07-23 23:58:40 +00001098
1099 CreatedBuffer = true;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001100 }
1101
Douglas Gregordf95a132010-08-09 20:45:32 +00001102 return std::make_pair(Buffer, Lexer::ComputePreamble(Buffer, MaxLines));
Douglas Gregor175c4a92010-07-23 23:58:40 +00001103}
1104
Douglas Gregor754f3492010-07-24 00:38:13 +00001105static llvm::MemoryBuffer *CreatePaddedMainFileBuffer(llvm::MemoryBuffer *Old,
Douglas Gregor754f3492010-07-24 00:38:13 +00001106 unsigned NewSize,
1107 llvm::StringRef NewName) {
1108 llvm::MemoryBuffer *Result
1109 = llvm::MemoryBuffer::getNewUninitMemBuffer(NewSize, NewName);
1110 memcpy(const_cast<char*>(Result->getBufferStart()),
1111 Old->getBufferStart(), Old->getBufferSize());
1112 memset(const_cast<char*>(Result->getBufferStart()) + Old->getBufferSize(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001113 ' ', NewSize - Old->getBufferSize() - 1);
1114 const_cast<char*>(Result->getBufferEnd())[-1] = '\n';
Douglas Gregor754f3492010-07-24 00:38:13 +00001115
Douglas Gregor754f3492010-07-24 00:38:13 +00001116 return Result;
1117}
1118
Douglas Gregor175c4a92010-07-23 23:58:40 +00001119/// \brief Attempt to build or re-use a precompiled preamble when (re-)parsing
1120/// the source file.
1121///
1122/// This routine will compute the preamble of the main source file. If a
1123/// non-trivial preamble is found, it will precompile that preamble into a
1124/// precompiled header so that the precompiled preamble can be used to reduce
1125/// reparsing time. If a precompiled preamble has already been constructed,
1126/// this routine will determine if it is still valid and, if so, avoid
1127/// rebuilding the precompiled preamble.
1128///
Douglas Gregordf95a132010-08-09 20:45:32 +00001129/// \param AllowRebuild When true (the default), this routine is
1130/// allowed to rebuild the precompiled preamble if it is found to be
1131/// out-of-date.
1132///
1133/// \param MaxLines When non-zero, the maximum number of lines that
1134/// can occur within the preamble.
1135///
Douglas Gregor754f3492010-07-24 00:38:13 +00001136/// \returns If the precompiled preamble can be used, returns a newly-allocated
1137/// buffer that should be used in place of the main file when doing so.
1138/// Otherwise, returns a NULL pointer.
Douglas Gregordf95a132010-08-09 20:45:32 +00001139llvm::MemoryBuffer *ASTUnit::getMainBufferWithPrecompiledPreamble(
Douglas Gregor2283d792010-08-20 00:59:43 +00001140 CompilerInvocation PreambleInvocation,
Douglas Gregordf95a132010-08-09 20:45:32 +00001141 bool AllowRebuild,
1142 unsigned MaxLines) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001143 FrontendOptions &FrontendOpts = PreambleInvocation.getFrontendOpts();
1144 PreprocessorOptions &PreprocessorOpts
1145 = PreambleInvocation.getPreprocessorOpts();
1146
1147 bool CreatedPreambleBuffer = false;
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001148 std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> > NewPreamble
Douglas Gregordf95a132010-08-09 20:45:32 +00001149 = ComputePreamble(PreambleInvocation, MaxLines, CreatedPreambleBuffer);
Douglas Gregor175c4a92010-07-23 23:58:40 +00001150
Douglas Gregor73fc9122010-11-16 20:45:51 +00001151 // If ComputePreamble() Take ownership of the
1152 llvm::OwningPtr<llvm::MemoryBuffer> OwnedPreambleBuffer;
1153 if (CreatedPreambleBuffer)
1154 OwnedPreambleBuffer.reset(NewPreamble.first);
1155
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001156 if (!NewPreamble.second.first) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001157 // We couldn't find a preamble in the main source. Clear out the current
1158 // preamble, if we have one. It's obviously no good any more.
1159 Preamble.clear();
1160 if (!PreambleFile.empty()) {
Douglas Gregor385103b2010-07-30 20:58:08 +00001161 llvm::sys::Path(PreambleFile).eraseFromDisk();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001162 PreambleFile.clear();
1163 }
Douglas Gregoreababfb2010-08-04 05:53:38 +00001164
1165 // The next time we actually see a preamble, precompile it.
1166 PreambleRebuildCounter = 1;
Douglas Gregor754f3492010-07-24 00:38:13 +00001167 return 0;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001168 }
1169
1170 if (!Preamble.empty()) {
1171 // We've previously computed a preamble. Check whether we have the same
1172 // preamble now that we did before, and that there's enough space in
1173 // the main-file buffer within the precompiled preamble to fit the
1174 // new main file.
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001175 if (Preamble.size() == NewPreamble.second.first &&
1176 PreambleEndsAtStartOfLine == NewPreamble.second.second &&
Douglas Gregor592508e2010-07-24 00:42:07 +00001177 NewPreamble.first->getBufferSize() < PreambleReservedSize-2 &&
Douglas Gregor175c4a92010-07-23 23:58:40 +00001178 memcmp(&Preamble[0], NewPreamble.first->getBufferStart(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001179 NewPreamble.second.first) == 0) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001180 // The preamble has not changed. We may be able to re-use the precompiled
1181 // preamble.
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001182
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001183 // Check that none of the files used by the preamble have changed.
1184 bool AnyFileChanged = false;
1185
1186 // First, make a record of those files that have been overridden via
1187 // remapping or unsaved_files.
1188 llvm::StringMap<std::pair<off_t, time_t> > OverriddenFiles;
1189 for (PreprocessorOptions::remapped_file_iterator
1190 R = PreprocessorOpts.remapped_file_begin(),
1191 REnd = PreprocessorOpts.remapped_file_end();
1192 !AnyFileChanged && R != REnd;
1193 ++R) {
1194 struct stat StatBuf;
Anders Carlsson340415c2011-03-18 19:23:38 +00001195 if (FileMgr->getNoncachedStatValue(R->second, StatBuf)) {
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001196 // If we can't stat the file we're remapping to, assume that something
1197 // horrible happened.
1198 AnyFileChanged = true;
1199 break;
1200 }
Douglas Gregor754f3492010-07-24 00:38:13 +00001201
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001202 OverriddenFiles[R->first] = std::make_pair(StatBuf.st_size,
1203 StatBuf.st_mtime);
1204 }
1205 for (PreprocessorOptions::remapped_file_buffer_iterator
1206 R = PreprocessorOpts.remapped_file_buffer_begin(),
1207 REnd = PreprocessorOpts.remapped_file_buffer_end();
1208 !AnyFileChanged && R != REnd;
1209 ++R) {
1210 // FIXME: Should we actually compare the contents of file->buffer
1211 // remappings?
1212 OverriddenFiles[R->first] = std::make_pair(R->second->getBufferSize(),
1213 0);
1214 }
1215
1216 // Check whether anything has changed.
1217 for (llvm::StringMap<std::pair<off_t, time_t> >::iterator
1218 F = FilesInPreamble.begin(), FEnd = FilesInPreamble.end();
1219 !AnyFileChanged && F != FEnd;
1220 ++F) {
1221 llvm::StringMap<std::pair<off_t, time_t> >::iterator Overridden
1222 = OverriddenFiles.find(F->first());
1223 if (Overridden != OverriddenFiles.end()) {
1224 // This file was remapped; check whether the newly-mapped file
1225 // matches up with the previous mapping.
1226 if (Overridden->second != F->second)
1227 AnyFileChanged = true;
1228 continue;
1229 }
1230
1231 // The file was not remapped; check whether it has changed on disk.
1232 struct stat StatBuf;
Anders Carlsson340415c2011-03-18 19:23:38 +00001233 if (FileMgr->getNoncachedStatValue(F->first(), StatBuf)) {
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001234 // If we can't stat the file, assume that something horrible happened.
1235 AnyFileChanged = true;
1236 } else if (StatBuf.st_size != F->second.first ||
1237 StatBuf.st_mtime != F->second.second)
1238 AnyFileChanged = true;
1239 }
1240
1241 if (!AnyFileChanged) {
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001242 // Okay! We can re-use the precompiled preamble.
1243
1244 // Set the state of the diagnostic object to mimic its state
1245 // after parsing the preamble.
Douglas Gregor32be4a52010-10-11 21:37:58 +00001246 // FIXME: This won't catch any #pragma push warning changes that
1247 // have occurred in the preamble.
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001248 getDiagnostics().Reset();
Douglas Gregor32be4a52010-10-11 21:37:58 +00001249 ProcessWarningOptions(getDiagnostics(),
1250 PreambleInvocation.getDiagnosticOpts());
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001251 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
1252 if (StoredDiagnostics.size() > NumStoredDiagnosticsInPreamble)
1253 StoredDiagnostics.erase(
1254 StoredDiagnostics.begin() + NumStoredDiagnosticsInPreamble,
1255 StoredDiagnostics.end());
1256
1257 // Create a version of the main file buffer that is padded to
1258 // buffer size we reserved when creating the preamble.
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001259 return CreatePaddedMainFileBuffer(NewPreamble.first,
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001260 PreambleReservedSize,
1261 FrontendOpts.Inputs[0].second);
1262 }
Douglas Gregor175c4a92010-07-23 23:58:40 +00001263 }
Douglas Gregordf95a132010-08-09 20:45:32 +00001264
1265 // If we aren't allowed to rebuild the precompiled preamble, just
1266 // return now.
1267 if (!AllowRebuild)
1268 return 0;
Douglas Gregoraa3e6ba2010-10-08 04:03:57 +00001269
Douglas Gregor175c4a92010-07-23 23:58:40 +00001270 // We can't reuse the previously-computed preamble. Build a new one.
1271 Preamble.clear();
Douglas Gregor385103b2010-07-30 20:58:08 +00001272 llvm::sys::Path(PreambleFile).eraseFromDisk();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001273 PreambleRebuildCounter = 1;
Douglas Gregordf95a132010-08-09 20:45:32 +00001274 } else if (!AllowRebuild) {
1275 // We aren't allowed to rebuild the precompiled preamble; just
1276 // return now.
1277 return 0;
1278 }
Douglas Gregoreababfb2010-08-04 05:53:38 +00001279
1280 // If the preamble rebuild counter > 1, it's because we previously
1281 // failed to build a preamble and we're not yet ready to try
1282 // again. Decrement the counter and return a failure.
1283 if (PreambleRebuildCounter > 1) {
1284 --PreambleRebuildCounter;
1285 return 0;
1286 }
1287
Douglas Gregor2cd4fd42010-09-11 17:56:52 +00001288 // Create a temporary file for the precompiled preamble. In rare
1289 // circumstances, this can fail.
1290 std::string PreamblePCHPath = GetPreamblePCHPath();
1291 if (PreamblePCHPath.empty()) {
1292 // Try again next time.
1293 PreambleRebuildCounter = 1;
1294 return 0;
1295 }
1296
Douglas Gregor175c4a92010-07-23 23:58:40 +00001297 // We did not previously compute a preamble, or it can't be reused anyway.
Douglas Gregor213f18b2010-10-28 15:44:59 +00001298 SimpleTimer PreambleTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00001299 PreambleTimer.setOutput("Precompiling preamble");
Douglas Gregor44c181a2010-07-23 00:33:23 +00001300
1301 // Create a new buffer that stores the preamble. The buffer also contains
1302 // extra space for the original contents of the file (which will be present
1303 // when we actually parse the file) along with more room in case the file
Douglas Gregor175c4a92010-07-23 23:58:40 +00001304 // grows.
1305 PreambleReservedSize = NewPreamble.first->getBufferSize();
1306 if (PreambleReservedSize < 4096)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001307 PreambleReservedSize = 8191;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001308 else
Douglas Gregor175c4a92010-07-23 23:58:40 +00001309 PreambleReservedSize *= 2;
1310
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001311 // Save the preamble text for later; we'll need to compare against it for
1312 // subsequent reparses.
1313 Preamble.assign(NewPreamble.first->getBufferStart(),
1314 NewPreamble.first->getBufferStart()
1315 + NewPreamble.second.first);
1316 PreambleEndsAtStartOfLine = NewPreamble.second.second;
1317
Douglas Gregor671947b2010-08-19 01:33:06 +00001318 delete PreambleBuffer;
1319 PreambleBuffer
Douglas Gregor175c4a92010-07-23 23:58:40 +00001320 = llvm::MemoryBuffer::getNewUninitMemBuffer(PreambleReservedSize,
Douglas Gregor44c181a2010-07-23 00:33:23 +00001321 FrontendOpts.Inputs[0].second);
1322 memcpy(const_cast<char*>(PreambleBuffer->getBufferStart()),
Douglas Gregor175c4a92010-07-23 23:58:40 +00001323 NewPreamble.first->getBufferStart(), Preamble.size());
1324 memset(const_cast<char*>(PreambleBuffer->getBufferStart()) + Preamble.size(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001325 ' ', PreambleReservedSize - Preamble.size() - 1);
1326 const_cast<char*>(PreambleBuffer->getBufferEnd())[-1] = '\n';
Douglas Gregor44c181a2010-07-23 00:33:23 +00001327
1328 // Remap the main source file to the preamble buffer.
Douglas Gregor175c4a92010-07-23 23:58:40 +00001329 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].second);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001330 PreprocessorOpts.addRemappedFile(MainFilePath.str(), PreambleBuffer);
1331
1332 // Tell the compiler invocation to generate a temporary precompiled header.
1333 FrontendOpts.ProgramAction = frontend::GeneratePCH;
Douglas Gregor85e51912010-10-01 01:05:22 +00001334 FrontendOpts.ChainedPCH = true;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001335 // FIXME: Generate the precompiled header into memory?
Douglas Gregor2cd4fd42010-09-11 17:56:52 +00001336 FrontendOpts.OutputFile = PreamblePCHPath;
Douglas Gregoraa3e6ba2010-10-08 04:03:57 +00001337 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
1338 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001339
1340 // Create the compiler instance to use for building the precompiled preamble.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001341 llvm::OwningPtr<CompilerInstance> Clang(new CompilerInstance());
1342
1343 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00001344 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1345 CICleanup(Clang.get());
Ted Kremenek03201fb2011-03-21 18:40:07 +00001346
1347 Clang->setInvocation(&PreambleInvocation);
1348 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].second;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001349
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001350 // Set up diagnostics, capturing all of the diagnostics produced.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001351 Clang->setDiagnostics(&getDiagnostics());
Douglas Gregor44c181a2010-07-23 00:33:23 +00001352
1353 // Create the target instance.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001354 Clang->getTargetOpts().Features = TargetFeatures;
1355 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
1356 Clang->getTargetOpts()));
1357 if (!Clang->hasTarget()) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001358 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1359 Preamble.clear();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001360 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor671947b2010-08-19 01:33:06 +00001361 PreprocessorOpts.eraseRemappedFile(
1362 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor754f3492010-07-24 00:38:13 +00001363 return 0;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001364 }
1365
1366 // Inform the target of the language options.
1367 //
1368 // FIXME: We shouldn't need to do this, the target should be immutable once
1369 // created. This complexity should be lifted elsewhere.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001370 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregor44c181a2010-07-23 00:33:23 +00001371
Ted Kremenek03201fb2011-03-21 18:40:07 +00001372 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Douglas Gregor44c181a2010-07-23 00:33:23 +00001373 "Invocation must have exactly one source file!");
Ted Kremenek03201fb2011-03-21 18:40:07 +00001374 assert(Clang->getFrontendOpts().Inputs[0].first != IK_AST &&
Douglas Gregor44c181a2010-07-23 00:33:23 +00001375 "FIXME: AST inputs not yet supported here!");
Ted Kremenek03201fb2011-03-21 18:40:07 +00001376 assert(Clang->getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
Douglas Gregor44c181a2010-07-23 00:33:23 +00001377 "IR inputs not support here!");
1378
1379 // Clear out old caches and data.
Douglas Gregoraa3e6ba2010-10-08 04:03:57 +00001380 getDiagnostics().Reset();
Ted Kremenek03201fb2011-03-21 18:40:07 +00001381 ProcessWarningOptions(getDiagnostics(), Clang->getDiagnosticOpts());
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001382 StoredDiagnostics.erase(
1383 StoredDiagnostics.begin() + NumStoredDiagnosticsFromDriver,
1384 StoredDiagnostics.end());
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001385 TopLevelDecls.clear();
1386 TopLevelDeclsInPreamble.clear();
Douglas Gregor89d99802010-11-30 06:16:57 +00001387 PreprocessedEntities.clear();
1388 PreprocessedEntitiesInPreamble.clear();
Douglas Gregor44c181a2010-07-23 00:33:23 +00001389
1390 // Create a file manager object to provide access to and cache the filesystem.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001391 Clang->setFileManager(new FileManager(Clang->getFileSystemOpts()));
Douglas Gregor44c181a2010-07-23 00:33:23 +00001392
1393 // Create the source manager.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001394 Clang->setSourceManager(new SourceManager(getDiagnostics(),
Ted Kremenek4f327862011-03-21 18:40:17 +00001395 Clang->getFileManager()));
Douglas Gregor44c181a2010-07-23 00:33:23 +00001396
Douglas Gregor1d715ac2010-08-03 08:14:03 +00001397 llvm::OwningPtr<PrecompilePreambleAction> Act;
1398 Act.reset(new PrecompilePreambleAction(*this));
Ted Kremenek03201fb2011-03-21 18:40:07 +00001399 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0].second,
1400 Clang->getFrontendOpts().Inputs[0].first)) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001401 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1402 Preamble.clear();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001403 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor671947b2010-08-19 01:33:06 +00001404 PreprocessorOpts.eraseRemappedFile(
1405 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor754f3492010-07-24 00:38:13 +00001406 return 0;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001407 }
1408
1409 Act->Execute();
1410 Act->EndSourceFile();
Ted Kremenek4f327862011-03-21 18:40:17 +00001411
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001412 if (Diagnostics->hasErrorOccurred()) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001413 // There were errors parsing the preamble, so no precompiled header was
1414 // generated. Forget that we even tried.
Douglas Gregor06e50442010-09-27 16:43:25 +00001415 // FIXME: Should we leave a note for ourselves to try again?
Douglas Gregor175c4a92010-07-23 23:58:40 +00001416 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1417 Preamble.clear();
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001418 TopLevelDeclsInPreamble.clear();
Douglas Gregor89d99802010-11-30 06:16:57 +00001419 PreprocessedEntities.clear();
1420 PreprocessedEntitiesInPreamble.clear();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001421 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor671947b2010-08-19 01:33:06 +00001422 PreprocessorOpts.eraseRemappedFile(
1423 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor754f3492010-07-24 00:38:13 +00001424 return 0;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001425 }
1426
1427 // Keep track of the preamble we precompiled.
1428 PreambleFile = FrontendOpts.OutputFile;
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001429 NumStoredDiagnosticsInPreamble = StoredDiagnostics.size();
1430 NumWarningsInPreamble = getDiagnostics().getNumWarnings();
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001431
1432 // Keep track of all of the files that the source manager knows about,
1433 // so we can verify whether they have changed or not.
1434 FilesInPreamble.clear();
Ted Kremenek03201fb2011-03-21 18:40:07 +00001435 SourceManager &SourceMgr = Clang->getSourceManager();
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001436 const llvm::MemoryBuffer *MainFileBuffer
1437 = SourceMgr.getBuffer(SourceMgr.getMainFileID());
1438 for (SourceManager::fileinfo_iterator F = SourceMgr.fileinfo_begin(),
1439 FEnd = SourceMgr.fileinfo_end();
1440 F != FEnd;
1441 ++F) {
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001442 const FileEntry *File = F->second->OrigEntry;
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001443 if (!File || F->second->getRawBuffer() == MainFileBuffer)
1444 continue;
1445
1446 FilesInPreamble[File->getName()]
1447 = std::make_pair(F->second->getSize(), File->getModificationTime());
1448 }
1449
Douglas Gregoreababfb2010-08-04 05:53:38 +00001450 PreambleRebuildCounter = 1;
Douglas Gregor671947b2010-08-19 01:33:06 +00001451 PreprocessorOpts.eraseRemappedFile(
1452 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor9b7db622011-02-16 18:16:54 +00001453
1454 // If the hash of top-level entities differs from the hash of the top-level
1455 // entities the last time we rebuilt the preamble, clear out the completion
1456 // cache.
1457 if (CurrentTopLevelHashValue != PreambleTopLevelHashValue) {
1458 CompletionCacheTopLevelHashValue = 0;
1459 PreambleTopLevelHashValue = CurrentTopLevelHashValue;
1460 }
1461
Douglas Gregor754f3492010-07-24 00:38:13 +00001462 return CreatePaddedMainFileBuffer(NewPreamble.first,
Douglas Gregor754f3492010-07-24 00:38:13 +00001463 PreambleReservedSize,
1464 FrontendOpts.Inputs[0].second);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001465}
Douglas Gregorabc563f2010-07-19 21:46:24 +00001466
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001467void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
1468 std::vector<Decl *> Resolved;
1469 Resolved.reserve(TopLevelDeclsInPreamble.size());
1470 ExternalASTSource &Source = *getASTContext().getExternalSource();
1471 for (unsigned I = 0, N = TopLevelDeclsInPreamble.size(); I != N; ++I) {
1472 // Resolve the declaration ID to an actual declaration, possibly
1473 // deserializing the declaration in the process.
1474 Decl *D = Source.GetExternalDecl(TopLevelDeclsInPreamble[I]);
1475 if (D)
1476 Resolved.push_back(D);
1477 }
1478 TopLevelDeclsInPreamble.clear();
1479 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1480}
1481
Douglas Gregor89d99802010-11-30 06:16:57 +00001482void ASTUnit::RealizePreprocessedEntitiesFromPreamble() {
1483 if (!PP)
1484 return;
1485
1486 PreprocessingRecord *PPRec = PP->getPreprocessingRecord();
1487 if (!PPRec)
1488 return;
1489
1490 ExternalPreprocessingRecordSource *External = PPRec->getExternalSource();
1491 if (!External)
1492 return;
1493
1494 for (unsigned I = 0, N = PreprocessedEntitiesInPreamble.size(); I != N; ++I) {
1495 if (PreprocessedEntity *PE
Douglas Gregor0a480292011-02-11 19:46:30 +00001496 = External->ReadPreprocessedEntityAtOffset(
1497 PreprocessedEntitiesInPreamble[I]))
Douglas Gregor89d99802010-11-30 06:16:57 +00001498 PreprocessedEntities.push_back(PE);
1499 }
1500
1501 if (PreprocessedEntities.empty())
1502 return;
1503
1504 PreprocessedEntities.insert(PreprocessedEntities.end(),
1505 PPRec->begin(true), PPRec->end(true));
1506}
1507
1508ASTUnit::pp_entity_iterator ASTUnit::pp_entity_begin() {
1509 if (!PreprocessedEntitiesInPreamble.empty() &&
1510 PreprocessedEntities.empty())
1511 RealizePreprocessedEntitiesFromPreamble();
1512
1513 if (PreprocessedEntities.empty())
1514 if (PreprocessingRecord *PPRec = PP->getPreprocessingRecord())
1515 return PPRec->begin(true);
1516
1517 return PreprocessedEntities.begin();
1518}
1519
1520ASTUnit::pp_entity_iterator ASTUnit::pp_entity_end() {
1521 if (!PreprocessedEntitiesInPreamble.empty() &&
1522 PreprocessedEntities.empty())
1523 RealizePreprocessedEntitiesFromPreamble();
1524
1525 if (PreprocessedEntities.empty())
1526 if (PreprocessingRecord *PPRec = PP->getPreprocessingRecord())
1527 return PPRec->end(true);
1528
1529 return PreprocessedEntities.end();
1530}
1531
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001532unsigned ASTUnit::getMaxPCHLevel() const {
1533 if (!getOnlyLocalDecls())
1534 return Decl::MaxPCHLevel;
1535
Sebastian Redl1d9f1fe2010-10-05 16:15:19 +00001536 return 0;
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001537}
1538
Douglas Gregor213f18b2010-10-28 15:44:59 +00001539llvm::StringRef ASTUnit::getMainFileName() const {
1540 return Invocation->getFrontendOpts().Inputs[0].second;
1541}
1542
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001543ASTUnit *ASTUnit::create(CompilerInvocation *CI,
1544 llvm::IntrusiveRefCntPtr<Diagnostic> Diags) {
1545 llvm::OwningPtr<ASTUnit> AST;
1546 AST.reset(new ASTUnit(false));
1547 ConfigureDiags(Diags, 0, 0, *AST, /*CaptureDiagnostics=*/false);
1548 AST->Diagnostics = Diags;
Ted Kremenek4f327862011-03-21 18:40:17 +00001549 AST->Invocation = CI;
Anders Carlsson0d8d7e62011-03-18 18:22:40 +00001550 AST->FileSystemOpts = CI->getFileSystemOpts();
Ted Kremenek4f327862011-03-21 18:40:17 +00001551 AST->FileMgr = new FileManager(AST->FileSystemOpts);
1552 AST->SourceMgr = new SourceManager(*Diags, *AST->FileMgr);
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001553
1554 return AST.take();
1555}
1556
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001557bool ASTUnit::LoadFromCompilerInvocation(bool PrecompilePreamble) {
1558 if (!Invocation)
1559 return true;
1560
1561 // We'll manage file buffers ourselves.
1562 Invocation->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1563 Invocation->getFrontendOpts().DisableFree = false;
Douglas Gregor0b53cf82011-01-19 01:02:47 +00001564 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001565
Douglas Gregor1aa27302011-01-27 18:02:58 +00001566 // Save the target features.
1567 TargetFeatures = Invocation->getTargetOpts().Features;
1568
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001569 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Douglas Gregor99ba2022010-10-27 17:24:53 +00001570 if (PrecompilePreamble) {
Douglas Gregor08bb4c62010-11-15 23:00:34 +00001571 PreambleRebuildCounter = 2;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001572 OverrideMainBuffer
1573 = getMainBufferWithPrecompiledPreamble(*Invocation);
1574 }
1575
Douglas Gregor213f18b2010-10-28 15:44:59 +00001576 SimpleTimer ParsingTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00001577 ParsingTimer.setOutput("Parsing " + getMainFileName());
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001578
Ted Kremenek25a11e12011-03-22 01:15:24 +00001579 // Recover resources if we crash before exiting this method.
1580 llvm::CrashRecoveryContextCleanupRegistrar<llvm::MemoryBuffer>
1581 MemBufferCleanup(OverrideMainBuffer);
1582
Douglas Gregor213f18b2010-10-28 15:44:59 +00001583 return Parse(OverrideMainBuffer);
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001584}
1585
Douglas Gregorabc563f2010-07-19 21:46:24 +00001586ASTUnit *ASTUnit::LoadFromCompilerInvocation(CompilerInvocation *CI,
1587 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
1588 bool OnlyLocalDecls,
Douglas Gregor44c181a2010-07-23 00:33:23 +00001589 bool CaptureDiagnostics,
Douglas Gregordf95a132010-08-09 20:45:32 +00001590 bool PrecompilePreamble,
Douglas Gregor87c08a52010-08-13 22:48:40 +00001591 bool CompleteTranslationUnit,
Douglas Gregore47be3e2010-11-11 00:39:14 +00001592 bool CacheCodeCompletionResults) {
Douglas Gregorabc563f2010-07-19 21:46:24 +00001593 // Create the AST unit.
1594 llvm::OwningPtr<ASTUnit> AST;
1595 AST.reset(new ASTUnit(false));
Douglas Gregor0b53cf82011-01-19 01:02:47 +00001596 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
Douglas Gregorabc563f2010-07-19 21:46:24 +00001597 AST->Diagnostics = Diags;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001598 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregore47be3e2010-11-11 00:39:14 +00001599 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregordf95a132010-08-09 20:45:32 +00001600 AST->CompleteTranslationUnit = CompleteTranslationUnit;
Douglas Gregor87c08a52010-08-13 22:48:40 +00001601 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Ted Kremenek4f327862011-03-21 18:40:17 +00001602 AST->Invocation = CI;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001603
Ted Kremenekb547eeb2011-03-18 02:06:56 +00001604 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00001605 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1606 ASTUnitCleanup(AST.get());
1607 llvm::CrashRecoveryContextCleanupRegistrar<Diagnostic,
1608 llvm::CrashRecoveryContextReleaseRefCleanup<Diagnostic> >
1609 DiagCleanup(Diags.getPtr());
Ted Kremenekb547eeb2011-03-18 02:06:56 +00001610
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001611 return AST->LoadFromCompilerInvocation(PrecompilePreamble)? 0 : AST.take();
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001612}
Daniel Dunbar7b556682009-12-02 03:23:45 +00001613
1614ASTUnit *ASTUnit::LoadFromCommandLine(const char **ArgBegin,
1615 const char **ArgEnd,
Douglas Gregor28019772010-04-05 23:52:57 +00001616 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
Daniel Dunbar869824e2009-12-13 03:46:13 +00001617 llvm::StringRef ResourceFilesPath,
Daniel Dunbar7b556682009-12-02 03:23:45 +00001618 bool OnlyLocalDecls,
Douglas Gregore47be3e2010-11-11 00:39:14 +00001619 bool CaptureDiagnostics,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001620 RemappedFile *RemappedFiles,
Douglas Gregora88084b2010-02-18 18:08:43 +00001621 unsigned NumRemappedFiles,
Argyrios Kyrtzidis299a4a92011-03-08 23:35:24 +00001622 bool RemappedFilesKeepOriginalName,
Douglas Gregordf95a132010-08-09 20:45:32 +00001623 bool PrecompilePreamble,
Douglas Gregor87c08a52010-08-13 22:48:40 +00001624 bool CompleteTranslationUnit,
Douglas Gregor99ba2022010-10-27 17:24:53 +00001625 bool CacheCodeCompletionResults,
1626 bool CXXPrecompilePreamble,
1627 bool CXXChainedPCH) {
Douglas Gregor28019772010-04-05 23:52:57 +00001628 if (!Diags.getPtr()) {
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001629 // No diagnostics engine was provided, so create our own diagnostics object
1630 // with the default options.
1631 DiagnosticOptions DiagOpts;
Douglas Gregor0b53cf82011-01-19 01:02:47 +00001632 Diags = CompilerInstance::createDiagnostics(DiagOpts, ArgEnd - ArgBegin,
1633 ArgBegin);
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001634 }
Daniel Dunbar7b556682009-12-02 03:23:45 +00001635
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001636 llvm::SmallVector<StoredDiagnostic, 4> StoredDiagnostics;
1637
Ted Kremenek4f327862011-03-21 18:40:17 +00001638 llvm::IntrusiveRefCntPtr<CompilerInvocation> CI;
Douglas Gregore47be3e2010-11-11 00:39:14 +00001639
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001640 {
Douglas Gregore47be3e2010-11-11 00:39:14 +00001641 CaptureDroppedDiagnostics Capture(CaptureDiagnostics, *Diags,
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001642 StoredDiagnostics);
Daniel Dunbar3bd54cc2010-01-25 00:44:02 +00001643
Argyrios Kyrtzidis832316e2011-04-04 23:11:45 +00001644 CI = clang::createInvocationFromCommandLine(
Argyrios Kyrtzidis054e4f52011-04-04 21:38:51 +00001645 llvm::ArrayRef<const char *>(ArgBegin, ArgEnd-ArgBegin),
1646 Diags);
1647 if (!CI)
Argyrios Kyrtzidis4e03c2b2011-03-07 22:45:01 +00001648 return 0;
Daniel Dunbar7b556682009-12-02 03:23:45 +00001649 }
Douglas Gregore47be3e2010-11-11 00:39:14 +00001650
Douglas Gregor4db64a42010-01-23 00:14:00 +00001651 // Override any files that need remapping
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001652 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
1653 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
1654 if (const llvm::MemoryBuffer *
1655 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
1656 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first, memBuf);
1657 } else {
1658 const char *fname = fileOrBuf.get<const char *>();
1659 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first, fname);
1660 }
1661 }
Argyrios Kyrtzidis299a4a92011-03-08 23:35:24 +00001662 CI->getPreprocessorOpts().RemappedFilesKeepOriginalName =
1663 RemappedFilesKeepOriginalName;
Douglas Gregor4db64a42010-01-23 00:14:00 +00001664
Daniel Dunbar8b9adfe2009-12-15 00:06:45 +00001665 // Override the resources path.
Daniel Dunbar807b0612010-01-30 21:47:16 +00001666 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
Daniel Dunbar7b556682009-12-02 03:23:45 +00001667
Douglas Gregor99ba2022010-10-27 17:24:53 +00001668 // Check whether we should precompile the preamble and/or use chained PCH.
1669 // FIXME: This is a temporary hack while we debug C++ chained PCH.
1670 if (CI->getLangOpts().CPlusPlus) {
1671 PrecompilePreamble = PrecompilePreamble && CXXPrecompilePreamble;
1672
1673 if (PrecompilePreamble && !CXXChainedPCH &&
1674 !CI->getPreprocessorOpts().ImplicitPCHInclude.empty())
1675 PrecompilePreamble = false;
1676 }
1677
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001678 // Create the AST unit.
1679 llvm::OwningPtr<ASTUnit> AST;
1680 AST.reset(new ASTUnit(false));
Douglas Gregor0b53cf82011-01-19 01:02:47 +00001681 ConfigureDiags(Diags, ArgBegin, ArgEnd, *AST, CaptureDiagnostics);
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001682 AST->Diagnostics = Diags;
Anders Carlsson0d8d7e62011-03-18 18:22:40 +00001683
1684 AST->FileSystemOpts = CI->getFileSystemOpts();
Ted Kremenek4f327862011-03-21 18:40:17 +00001685 AST->FileMgr = new FileManager(AST->FileSystemOpts);
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001686 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregore47be3e2010-11-11 00:39:14 +00001687 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001688 AST->CompleteTranslationUnit = CompleteTranslationUnit;
1689 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
1690 AST->NumStoredDiagnosticsFromDriver = StoredDiagnostics.size();
1691 AST->NumStoredDiagnosticsInPreamble = StoredDiagnostics.size();
1692 AST->StoredDiagnostics.swap(StoredDiagnostics);
Ted Kremenek4f327862011-03-21 18:40:17 +00001693 AST->Invocation = CI;
Ted Kremenekb547eeb2011-03-18 02:06:56 +00001694
1695 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00001696 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1697 ASTUnitCleanup(AST.get());
1698 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInvocation,
1699 llvm::CrashRecoveryContextReleaseRefCleanup<CompilerInvocation> >
1700 CICleanup(CI.getPtr());
1701 llvm::CrashRecoveryContextCleanupRegistrar<Diagnostic,
1702 llvm::CrashRecoveryContextReleaseRefCleanup<Diagnostic> >
1703 DiagCleanup(Diags.getPtr());
Ted Kremenekb547eeb2011-03-18 02:06:56 +00001704
Chris Lattner39b49bc2010-11-23 08:35:12 +00001705 return AST->LoadFromCompilerInvocation(PrecompilePreamble) ? 0 : AST.take();
Daniel Dunbar7b556682009-12-02 03:23:45 +00001706}
Douglas Gregorabc563f2010-07-19 21:46:24 +00001707
1708bool ASTUnit::Reparse(RemappedFile *RemappedFiles, unsigned NumRemappedFiles) {
Ted Kremenek4f327862011-03-21 18:40:17 +00001709 if (!Invocation)
Douglas Gregorabc563f2010-07-19 21:46:24 +00001710 return true;
1711
Douglas Gregor213f18b2010-10-28 15:44:59 +00001712 SimpleTimer ParsingTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00001713 ParsingTimer.setOutput("Reparsing " + getMainFileName());
Douglas Gregor213f18b2010-10-28 15:44:59 +00001714
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001715 // Remap files.
Douglas Gregorf128fed2010-08-20 00:02:33 +00001716 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
Douglas Gregor8ef6c8c2011-02-05 19:42:43 +00001717 PPOpts.DisableStatCache = true;
Douglas Gregorf128fed2010-08-20 00:02:33 +00001718 for (PreprocessorOptions::remapped_file_buffer_iterator
1719 R = PPOpts.remapped_file_buffer_begin(),
1720 REnd = PPOpts.remapped_file_buffer_end();
1721 R != REnd;
1722 ++R) {
1723 delete R->second;
1724 }
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001725 Invocation->getPreprocessorOpts().clearRemappedFiles();
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001726 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
1727 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
1728 if (const llvm::MemoryBuffer *
1729 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
1730 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
1731 memBuf);
1732 } else {
1733 const char *fname = fileOrBuf.get<const char *>();
1734 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
1735 fname);
1736 }
1737 }
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001738
Douglas Gregoreababfb2010-08-04 05:53:38 +00001739 // If we have a preamble file lying around, or if we might try to
1740 // build a precompiled preamble, do so now.
Douglas Gregor754f3492010-07-24 00:38:13 +00001741 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Douglas Gregoreababfb2010-08-04 05:53:38 +00001742 if (!PreambleFile.empty() || PreambleRebuildCounter > 0)
Douglas Gregor2283d792010-08-20 00:59:43 +00001743 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(*Invocation);
Douglas Gregor175c4a92010-07-23 23:58:40 +00001744
Douglas Gregorabc563f2010-07-19 21:46:24 +00001745 // Clear out the diagnostics state.
Douglas Gregor32be4a52010-10-11 21:37:58 +00001746 if (!OverrideMainBuffer) {
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001747 getDiagnostics().Reset();
Douglas Gregor32be4a52010-10-11 21:37:58 +00001748 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
1749 }
Douglas Gregorabc563f2010-07-19 21:46:24 +00001750
Douglas Gregor175c4a92010-07-23 23:58:40 +00001751 // Parse the sources
Douglas Gregor9b7db622011-02-16 18:16:54 +00001752 bool Result = Parse(OverrideMainBuffer);
1753
1754 // If we're caching global code-completion results, and the top-level
1755 // declarations have changed, clear out the code-completion cache.
1756 if (!Result && ShouldCacheCodeCompletionResults &&
1757 CurrentTopLevelHashValue != CompletionCacheTopLevelHashValue)
1758 CacheCodeCompletionResults();
1759
Douglas Gregor175c4a92010-07-23 23:58:40 +00001760 return Result;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001761}
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001762
Douglas Gregor87c08a52010-08-13 22:48:40 +00001763//----------------------------------------------------------------------------//
1764// Code completion
1765//----------------------------------------------------------------------------//
1766
1767namespace {
1768 /// \brief Code completion consumer that combines the cached code-completion
1769 /// results from an ASTUnit with the code-completion results provided to it,
1770 /// then passes the result on to
1771 class AugmentedCodeCompleteConsumer : public CodeCompleteConsumer {
1772 unsigned NormalContexts;
1773 ASTUnit &AST;
1774 CodeCompleteConsumer &Next;
1775
1776 public:
1777 AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next,
Douglas Gregor8071e422010-08-15 06:18:01 +00001778 bool IncludeMacros, bool IncludeCodePatterns,
1779 bool IncludeGlobals)
1780 : CodeCompleteConsumer(IncludeMacros, IncludeCodePatterns, IncludeGlobals,
Douglas Gregor87c08a52010-08-13 22:48:40 +00001781 Next.isOutputBinary()), AST(AST), Next(Next)
1782 {
1783 // Compute the set of contexts in which we will look when we don't have
1784 // any information about the specific context.
1785 NormalContexts
1786 = (1 << (CodeCompletionContext::CCC_TopLevel - 1))
1787 | (1 << (CodeCompletionContext::CCC_ObjCInterface - 1))
1788 | (1 << (CodeCompletionContext::CCC_ObjCImplementation - 1))
1789 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
1790 | (1 << (CodeCompletionContext::CCC_Statement - 1))
1791 | (1 << (CodeCompletionContext::CCC_Expression - 1))
1792 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
1793 | (1 << (CodeCompletionContext::CCC_MemberAccess - 1))
Douglas Gregor02688102010-09-14 23:59:36 +00001794 | (1 << (CodeCompletionContext::CCC_ObjCProtocolName - 1))
Douglas Gregor52779fb2010-09-23 23:01:17 +00001795 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1))
1796 | (1 << (CodeCompletionContext::CCC_Recovery - 1));
Douglas Gregor02688102010-09-14 23:59:36 +00001797
Douglas Gregor87c08a52010-08-13 22:48:40 +00001798 if (AST.getASTContext().getLangOptions().CPlusPlus)
1799 NormalContexts |= (1 << (CodeCompletionContext::CCC_EnumTag - 1))
1800 | (1 << (CodeCompletionContext::CCC_UnionTag - 1))
1801 | (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1));
1802 }
1803
1804 virtual void ProcessCodeCompleteResults(Sema &S,
1805 CodeCompletionContext Context,
John McCall0a2c5e22010-08-25 06:19:51 +00001806 CodeCompletionResult *Results,
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001807 unsigned NumResults);
Douglas Gregor87c08a52010-08-13 22:48:40 +00001808
1809 virtual void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
1810 OverloadCandidate *Candidates,
1811 unsigned NumCandidates) {
1812 Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates);
1813 }
Douglas Gregor218937c2011-02-01 19:23:04 +00001814
Douglas Gregordae68752011-02-01 22:57:45 +00001815 virtual CodeCompletionAllocator &getAllocator() {
Douglas Gregor218937c2011-02-01 19:23:04 +00001816 return Next.getAllocator();
1817 }
Douglas Gregor87c08a52010-08-13 22:48:40 +00001818 };
1819}
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001820
Douglas Gregor5f808c22010-08-16 21:18:39 +00001821/// \brief Helper function that computes which global names are hidden by the
1822/// local code-completion results.
Ted Kremenekc198f612010-11-07 06:11:36 +00001823static void CalculateHiddenNames(const CodeCompletionContext &Context,
1824 CodeCompletionResult *Results,
1825 unsigned NumResults,
1826 ASTContext &Ctx,
1827 llvm::StringSet<llvm::BumpPtrAllocator> &HiddenNames){
Douglas Gregor5f808c22010-08-16 21:18:39 +00001828 bool OnlyTagNames = false;
1829 switch (Context.getKind()) {
Douglas Gregor52779fb2010-09-23 23:01:17 +00001830 case CodeCompletionContext::CCC_Recovery:
Douglas Gregor5f808c22010-08-16 21:18:39 +00001831 case CodeCompletionContext::CCC_TopLevel:
1832 case CodeCompletionContext::CCC_ObjCInterface:
1833 case CodeCompletionContext::CCC_ObjCImplementation:
1834 case CodeCompletionContext::CCC_ObjCIvarList:
1835 case CodeCompletionContext::CCC_ClassStructUnion:
1836 case CodeCompletionContext::CCC_Statement:
1837 case CodeCompletionContext::CCC_Expression:
1838 case CodeCompletionContext::CCC_ObjCMessageReceiver:
1839 case CodeCompletionContext::CCC_MemberAccess:
1840 case CodeCompletionContext::CCC_Namespace:
1841 case CodeCompletionContext::CCC_Type:
Douglas Gregor2ccccb32010-08-23 18:23:48 +00001842 case CodeCompletionContext::CCC_Name:
1843 case CodeCompletionContext::CCC_PotentiallyQualifiedName:
Douglas Gregor02688102010-09-14 23:59:36 +00001844 case CodeCompletionContext::CCC_ParenthesizedExpression:
Douglas Gregor5f808c22010-08-16 21:18:39 +00001845 break;
1846
1847 case CodeCompletionContext::CCC_EnumTag:
1848 case CodeCompletionContext::CCC_UnionTag:
1849 case CodeCompletionContext::CCC_ClassOrStructTag:
1850 OnlyTagNames = true;
1851 break;
1852
1853 case CodeCompletionContext::CCC_ObjCProtocolName:
Douglas Gregor1fbb4472010-08-24 20:21:13 +00001854 case CodeCompletionContext::CCC_MacroName:
1855 case CodeCompletionContext::CCC_MacroNameUse:
Douglas Gregorf29c5232010-08-24 22:20:20 +00001856 case CodeCompletionContext::CCC_PreprocessorExpression:
Douglas Gregor721f3592010-08-25 18:41:16 +00001857 case CodeCompletionContext::CCC_PreprocessorDirective:
Douglas Gregor59a66942010-08-25 18:04:30 +00001858 case CodeCompletionContext::CCC_NaturalLanguage:
Douglas Gregor458433d2010-08-26 15:07:07 +00001859 case CodeCompletionContext::CCC_SelectorName:
Douglas Gregor1a480c42010-08-27 17:35:51 +00001860 case CodeCompletionContext::CCC_TypeQualifiers:
Douglas Gregor52779fb2010-09-23 23:01:17 +00001861 case CodeCompletionContext::CCC_Other:
Douglas Gregor5c722c702011-02-18 23:30:37 +00001862 case CodeCompletionContext::CCC_OtherWithMacros:
Douglas Gregor721f3592010-08-25 18:41:16 +00001863 // We're looking for nothing, or we're looking for names that cannot
1864 // be hidden.
Douglas Gregor5f808c22010-08-16 21:18:39 +00001865 return;
1866 }
1867
John McCall0a2c5e22010-08-25 06:19:51 +00001868 typedef CodeCompletionResult Result;
Douglas Gregor5f808c22010-08-16 21:18:39 +00001869 for (unsigned I = 0; I != NumResults; ++I) {
1870 if (Results[I].Kind != Result::RK_Declaration)
1871 continue;
1872
1873 unsigned IDNS
1874 = Results[I].Declaration->getUnderlyingDecl()->getIdentifierNamespace();
1875
1876 bool Hiding = false;
1877 if (OnlyTagNames)
1878 Hiding = (IDNS & Decl::IDNS_Tag);
1879 else {
1880 unsigned HiddenIDNS = (Decl::IDNS_Type | Decl::IDNS_Member |
Douglas Gregora5fb7c32010-08-16 23:05:20 +00001881 Decl::IDNS_Namespace | Decl::IDNS_Ordinary |
1882 Decl::IDNS_NonMemberOperator);
Douglas Gregor5f808c22010-08-16 21:18:39 +00001883 if (Ctx.getLangOptions().CPlusPlus)
1884 HiddenIDNS |= Decl::IDNS_Tag;
1885 Hiding = (IDNS & HiddenIDNS);
1886 }
1887
1888 if (!Hiding)
1889 continue;
1890
1891 DeclarationName Name = Results[I].Declaration->getDeclName();
1892 if (IdentifierInfo *Identifier = Name.getAsIdentifierInfo())
1893 HiddenNames.insert(Identifier->getName());
1894 else
1895 HiddenNames.insert(Name.getAsString());
1896 }
1897}
1898
1899
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001900void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &S,
1901 CodeCompletionContext Context,
John McCall0a2c5e22010-08-25 06:19:51 +00001902 CodeCompletionResult *Results,
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001903 unsigned NumResults) {
1904 // Merge the results we were given with the results we cached.
1905 bool AddedResult = false;
Douglas Gregor5f808c22010-08-16 21:18:39 +00001906 unsigned InContexts
Douglas Gregor52779fb2010-09-23 23:01:17 +00001907 = (Context.getKind() == CodeCompletionContext::CCC_Recovery? NormalContexts
Douglas Gregor5f808c22010-08-16 21:18:39 +00001908 : (1 << (Context.getKind() - 1)));
1909
1910 // Contains the set of names that are hidden by "local" completion results.
Ted Kremenekc198f612010-11-07 06:11:36 +00001911 llvm::StringSet<llvm::BumpPtrAllocator> HiddenNames;
John McCall0a2c5e22010-08-25 06:19:51 +00001912 typedef CodeCompletionResult Result;
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001913 llvm::SmallVector<Result, 8> AllResults;
1914 for (ASTUnit::cached_completion_iterator
Douglas Gregor5535d572010-08-16 21:23:13 +00001915 C = AST.cached_completion_begin(),
1916 CEnd = AST.cached_completion_end();
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001917 C != CEnd; ++C) {
1918 // If the context we are in matches any of the contexts we are
1919 // interested in, we'll add this result.
1920 if ((C->ShowInContexts & InContexts) == 0)
1921 continue;
1922
1923 // If we haven't added any results previously, do so now.
1924 if (!AddedResult) {
Douglas Gregor5f808c22010-08-16 21:18:39 +00001925 CalculateHiddenNames(Context, Results, NumResults, S.Context,
1926 HiddenNames);
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001927 AllResults.insert(AllResults.end(), Results, Results + NumResults);
1928 AddedResult = true;
1929 }
1930
Douglas Gregor5f808c22010-08-16 21:18:39 +00001931 // Determine whether this global completion result is hidden by a local
1932 // completion result. If so, skip it.
1933 if (C->Kind != CXCursor_MacroDefinition &&
1934 HiddenNames.count(C->Completion->getTypedText()))
1935 continue;
1936
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001937 // Adjust priority based on similar type classes.
1938 unsigned Priority = C->Priority;
Douglas Gregor4125c372010-08-25 18:03:13 +00001939 CXCursorKind CursorKind = C->Kind;
Douglas Gregor1fbb4472010-08-24 20:21:13 +00001940 CodeCompletionString *Completion = C->Completion;
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001941 if (!Context.getPreferredType().isNull()) {
1942 if (C->Kind == CXCursor_MacroDefinition) {
1943 Priority = getMacroUsagePriority(C->Completion->getTypedText(),
Douglas Gregorb05496d2010-09-20 21:11:48 +00001944 S.getLangOptions(),
Douglas Gregor1fbb4472010-08-24 20:21:13 +00001945 Context.getPreferredType()->isAnyPointerType());
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001946 } else if (C->Type) {
1947 CanQualType Expected
Douglas Gregor5535d572010-08-16 21:23:13 +00001948 = S.Context.getCanonicalType(
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001949 Context.getPreferredType().getUnqualifiedType());
1950 SimplifiedTypeClass ExpectedSTC = getSimplifiedTypeClass(Expected);
1951 if (ExpectedSTC == C->TypeClass) {
1952 // We know this type is similar; check for an exact match.
1953 llvm::StringMap<unsigned> &CachedCompletionTypes
Douglas Gregor5535d572010-08-16 21:23:13 +00001954 = AST.getCachedCompletionTypes();
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001955 llvm::StringMap<unsigned>::iterator Pos
Douglas Gregor5535d572010-08-16 21:23:13 +00001956 = CachedCompletionTypes.find(QualType(Expected).getAsString());
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001957 if (Pos != CachedCompletionTypes.end() && Pos->second == C->Type)
1958 Priority /= CCF_ExactTypeMatch;
1959 else
1960 Priority /= CCF_SimilarTypeMatch;
1961 }
1962 }
1963 }
1964
Douglas Gregor1fbb4472010-08-24 20:21:13 +00001965 // Adjust the completion string, if required.
1966 if (C->Kind == CXCursor_MacroDefinition &&
1967 Context.getKind() == CodeCompletionContext::CCC_MacroNameUse) {
1968 // Create a new code-completion string that just contains the
1969 // macro name, without its arguments.
Douglas Gregor218937c2011-02-01 19:23:04 +00001970 CodeCompletionBuilder Builder(getAllocator(), CCP_CodePattern,
1971 C->Availability);
1972 Builder.AddTypedTextChunk(C->Completion->getTypedText());
Douglas Gregor4125c372010-08-25 18:03:13 +00001973 CursorKind = CXCursor_NotImplemented;
1974 Priority = CCP_CodePattern;
Douglas Gregor218937c2011-02-01 19:23:04 +00001975 Completion = Builder.TakeString();
Douglas Gregor1fbb4472010-08-24 20:21:13 +00001976 }
1977
Douglas Gregor4125c372010-08-25 18:03:13 +00001978 AllResults.push_back(Result(Completion, Priority, CursorKind,
Douglas Gregor58ddb602010-08-23 23:00:57 +00001979 C->Availability));
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001980 }
1981
1982 // If we did not add any cached completion results, just forward the
1983 // results we were given to the next consumer.
1984 if (!AddedResult) {
1985 Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
1986 return;
1987 }
Douglas Gregor1e5e6682010-08-26 13:48:20 +00001988
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001989 Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
1990 AllResults.size());
1991}
1992
1993
1994
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001995void ASTUnit::CodeComplete(llvm::StringRef File, unsigned Line, unsigned Column,
1996 RemappedFile *RemappedFiles,
1997 unsigned NumRemappedFiles,
Douglas Gregorcee235c2010-08-05 09:09:23 +00001998 bool IncludeMacros,
1999 bool IncludeCodePatterns,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002000 CodeCompleteConsumer &Consumer,
2001 Diagnostic &Diag, LangOptions &LangOpts,
2002 SourceManager &SourceMgr, FileManager &FileMgr,
Douglas Gregor2283d792010-08-20 00:59:43 +00002003 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
2004 llvm::SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers) {
Ted Kremenek4f327862011-03-21 18:40:17 +00002005 if (!Invocation)
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002006 return;
2007
Douglas Gregor213f18b2010-10-28 15:44:59 +00002008 SimpleTimer CompletionTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00002009 CompletionTimer.setOutput("Code completion @ " + File + ":" +
2010 llvm::Twine(Line) + ":" + llvm::Twine(Column));
Douglas Gregordf95a132010-08-09 20:45:32 +00002011
Ted Kremenek4f327862011-03-21 18:40:17 +00002012 llvm::IntrusiveRefCntPtr<CompilerInvocation>
2013 CCInvocation(new CompilerInvocation(*Invocation));
2014
2015 FrontendOptions &FrontendOpts = CCInvocation->getFrontendOpts();
2016 PreprocessorOptions &PreprocessorOpts = CCInvocation->getPreprocessorOpts();
Douglas Gregorcee235c2010-08-05 09:09:23 +00002017
Douglas Gregor87c08a52010-08-13 22:48:40 +00002018 FrontendOpts.ShowMacrosInCodeCompletion
2019 = IncludeMacros && CachedCompletionResults.empty();
Douglas Gregorcee235c2010-08-05 09:09:23 +00002020 FrontendOpts.ShowCodePatternsInCodeCompletion = IncludeCodePatterns;
Douglas Gregor8071e422010-08-15 06:18:01 +00002021 FrontendOpts.ShowGlobalSymbolsInCodeCompletion
2022 = CachedCompletionResults.empty();
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002023 FrontendOpts.CodeCompletionAt.FileName = File;
2024 FrontendOpts.CodeCompletionAt.Line = Line;
2025 FrontendOpts.CodeCompletionAt.Column = Column;
2026
2027 // Set the language options appropriately.
Ted Kremenek4f327862011-03-21 18:40:17 +00002028 LangOpts = CCInvocation->getLangOpts();
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002029
Ted Kremenek03201fb2011-03-21 18:40:07 +00002030 llvm::OwningPtr<CompilerInstance> Clang(new CompilerInstance());
2031
2032 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00002033 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
2034 CICleanup(Clang.get());
Ted Kremenek03201fb2011-03-21 18:40:07 +00002035
Ted Kremenek4f327862011-03-21 18:40:17 +00002036 Clang->setInvocation(&*CCInvocation);
Ted Kremenek03201fb2011-03-21 18:40:07 +00002037 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].second;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002038
2039 // Set up diagnostics, capturing any diagnostics produced.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002040 Clang->setDiagnostics(&Diag);
Ted Kremenek4f327862011-03-21 18:40:17 +00002041 ProcessWarningOptions(Diag, CCInvocation->getDiagnosticOpts());
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002042 CaptureDroppedDiagnostics Capture(true,
Ted Kremenek03201fb2011-03-21 18:40:07 +00002043 Clang->getDiagnostics(),
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002044 StoredDiagnostics);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002045
2046 // Create the target instance.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002047 Clang->getTargetOpts().Features = TargetFeatures;
2048 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
2049 Clang->getTargetOpts()));
2050 if (!Clang->hasTarget()) {
Ted Kremenek4f327862011-03-21 18:40:17 +00002051 Clang->setInvocation(0);
Douglas Gregorbdbb0042010-08-18 22:29:43 +00002052 return;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002053 }
2054
2055 // Inform the target of the language options.
2056 //
2057 // FIXME: We shouldn't need to do this, the target should be immutable once
2058 // created. This complexity should be lifted elsewhere.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002059 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002060
Ted Kremenek03201fb2011-03-21 18:40:07 +00002061 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002062 "Invocation must have exactly one source file!");
Ted Kremenek03201fb2011-03-21 18:40:07 +00002063 assert(Clang->getFrontendOpts().Inputs[0].first != IK_AST &&
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002064 "FIXME: AST inputs not yet supported here!");
Ted Kremenek03201fb2011-03-21 18:40:07 +00002065 assert(Clang->getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002066 "IR inputs not support here!");
2067
2068
2069 // Use the source and file managers that we were given.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002070 Clang->setFileManager(&FileMgr);
2071 Clang->setSourceManager(&SourceMgr);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002072
2073 // Remap files.
2074 PreprocessorOpts.clearRemappedFiles();
Douglas Gregorb75d3df2010-08-04 17:07:00 +00002075 PreprocessorOpts.RetainRemappedFileBuffers = true;
Douglas Gregor2283d792010-08-20 00:59:43 +00002076 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00002077 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
2078 if (const llvm::MemoryBuffer *
2079 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
2080 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first, memBuf);
2081 OwnedBuffers.push_back(memBuf);
2082 } else {
2083 const char *fname = fileOrBuf.get<const char *>();
2084 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first, fname);
2085 }
Douglas Gregor2283d792010-08-20 00:59:43 +00002086 }
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002087
Douglas Gregor87c08a52010-08-13 22:48:40 +00002088 // Use the code completion consumer we were given, but adding any cached
2089 // code-completion results.
Douglas Gregor7f946ad2010-11-29 16:13:56 +00002090 AugmentedCodeCompleteConsumer *AugmentedConsumer
2091 = new AugmentedCodeCompleteConsumer(*this, Consumer,
2092 FrontendOpts.ShowMacrosInCodeCompletion,
2093 FrontendOpts.ShowCodePatternsInCodeCompletion,
2094 FrontendOpts.ShowGlobalSymbolsInCodeCompletion);
Ted Kremenek03201fb2011-03-21 18:40:07 +00002095 Clang->setCodeCompletionConsumer(AugmentedConsumer);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002096
Douglas Gregordf95a132010-08-09 20:45:32 +00002097 // If we have a precompiled preamble, try to use it. We only allow
2098 // the use of the precompiled preamble if we're if the completion
2099 // point is within the main file, after the end of the precompiled
2100 // preamble.
2101 llvm::MemoryBuffer *OverrideMainBuffer = 0;
2102 if (!PreambleFile.empty()) {
2103 using llvm::sys::FileStatus;
2104 llvm::sys::PathWithStatus CompleteFilePath(File);
2105 llvm::sys::PathWithStatus MainPath(OriginalSourceFile);
2106 if (const FileStatus *CompleteFileStatus = CompleteFilePath.getFileStatus())
2107 if (const FileStatus *MainStatus = MainPath.getFileStatus())
2108 if (CompleteFileStatus->getUniqueID() == MainStatus->getUniqueID())
Douglas Gregor2283d792010-08-20 00:59:43 +00002109 OverrideMainBuffer
Ted Kremenek4f327862011-03-21 18:40:17 +00002110 = getMainBufferWithPrecompiledPreamble(*CCInvocation, false,
Douglas Gregorc9c29a82010-08-25 18:04:15 +00002111 Line - 1);
Douglas Gregordf95a132010-08-09 20:45:32 +00002112 }
2113
2114 // If the main file has been overridden due to the use of a preamble,
2115 // make that override happen and introduce the preamble.
Douglas Gregor8ef6c8c2011-02-05 19:42:43 +00002116 PreprocessorOpts.DisableStatCache = true;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00002117 StoredDiagnostics.insert(StoredDiagnostics.end(),
2118 this->StoredDiagnostics.begin(),
2119 this->StoredDiagnostics.begin() + NumStoredDiagnosticsFromDriver);
Douglas Gregordf95a132010-08-09 20:45:32 +00002120 if (OverrideMainBuffer) {
2121 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
2122 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
2123 PreprocessorOpts.PrecompiledPreambleBytes.second
2124 = PreambleEndsAtStartOfLine;
2125 PreprocessorOpts.ImplicitPCHInclude = PreambleFile;
2126 PreprocessorOpts.DisablePCHValidation = true;
2127
2128 // The stored diagnostics have the old source manager. Copy them
2129 // to our output set of stored diagnostics, updating the source
2130 // manager to the one we were given.
Douglas Gregor4cd912a2010-10-12 00:50:20 +00002131 for (unsigned I = NumStoredDiagnosticsFromDriver,
2132 N = this->StoredDiagnostics.size();
2133 I < N; ++I) {
Douglas Gregordf95a132010-08-09 20:45:32 +00002134 StoredDiagnostics.push_back(this->StoredDiagnostics[I]);
2135 FullSourceLoc Loc(StoredDiagnostics[I].getLocation(), SourceMgr);
2136 StoredDiagnostics[I].setLocation(Loc);
2137 }
Douglas Gregor4cd912a2010-10-12 00:50:20 +00002138
Douglas Gregor2283d792010-08-20 00:59:43 +00002139 OwnedBuffers.push_back(OverrideMainBuffer);
Douglas Gregorf128fed2010-08-20 00:02:33 +00002140 } else {
2141 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
2142 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregordf95a132010-08-09 20:45:32 +00002143 }
2144
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002145 llvm::OwningPtr<SyntaxOnlyAction> Act;
2146 Act.reset(new SyntaxOnlyAction);
Ted Kremenek03201fb2011-03-21 18:40:07 +00002147 if (Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0].second,
2148 Clang->getFrontendOpts().Inputs[0].first)) {
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002149 Act->Execute();
2150 Act->EndSourceFile();
2151 }
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002152}
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002153
2154bool ASTUnit::Save(llvm::StringRef File) {
2155 if (getDiagnostics().hasErrorOccurred())
2156 return true;
2157
2158 // FIXME: Can we somehow regenerate the stat cache here, or do we need to
2159 // unconditionally create a stat cache when we parse the file?
2160 std::string ErrorInfo;
Benjamin Kramer1395c5d2010-08-15 16:54:31 +00002161 llvm::raw_fd_ostream Out(File.str().c_str(), ErrorInfo,
2162 llvm::raw_fd_ostream::F_Binary);
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002163 if (!ErrorInfo.empty() || Out.has_error())
2164 return true;
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00002165
2166 serialize(Out);
2167 Out.close();
2168 return Out.has_error();
2169}
2170
2171bool ASTUnit::serialize(llvm::raw_ostream &OS) {
2172 if (getDiagnostics().hasErrorOccurred())
2173 return true;
2174
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002175 std::vector<unsigned char> Buffer;
2176 llvm::BitstreamWriter Stream(Buffer);
Sebastian Redla4232eb2010-08-18 23:56:21 +00002177 ASTWriter Writer(Stream);
Argyrios Kyrtzidis8e3df4d2011-02-15 17:54:22 +00002178 Writer.WriteAST(getSema(), 0, std::string(), 0);
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002179
2180 // Write the generated bitstream to "Out".
Douglas Gregorbdbb0042010-08-18 22:29:43 +00002181 if (!Buffer.empty())
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00002182 OS.write((char *)&Buffer.front(), Buffer.size());
2183
2184 return false;
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002185}