blob: e369f430b7ac1e97f65f038a9d7e33ae81a5228c [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"
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +000048#include "llvm/Support/FileSystem.h"
Ted Kremenekb547eeb2011-03-18 02:06:56 +000049#include "llvm/Support/CrashRecoveryContext.h"
Douglas Gregor44c181a2010-07-23 00:33:23 +000050#include <cstdlib>
Zhongxing Xuad23ebe2010-07-23 02:15:08 +000051#include <cstdio>
Douglas Gregorcc5888d2010-07-31 00:40:00 +000052#include <sys/stat.h>
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000053using namespace clang;
54
Douglas Gregor213f18b2010-10-28 15:44:59 +000055using llvm::TimeRecord;
56
57namespace {
58 class SimpleTimer {
59 bool WantTiming;
60 TimeRecord Start;
61 std::string Output;
62
Benjamin Krameredfb7ec2010-11-09 20:00:56 +000063 public:
Douglas Gregor9dba61a2010-11-01 13:48:43 +000064 explicit SimpleTimer(bool WantTiming) : WantTiming(WantTiming) {
Douglas Gregor213f18b2010-10-28 15:44:59 +000065 if (WantTiming)
Benjamin Krameredfb7ec2010-11-09 20:00:56 +000066 Start = TimeRecord::getCurrentTime();
Douglas Gregor213f18b2010-10-28 15:44:59 +000067 }
68
Chris Lattner5f9e2722011-07-23 10:55:15 +000069 void setOutput(const Twine &Output) {
Douglas Gregor213f18b2010-10-28 15:44:59 +000070 if (WantTiming)
Benjamin Krameredfb7ec2010-11-09 20:00:56 +000071 this->Output = Output.str();
Douglas Gregor213f18b2010-10-28 15:44:59 +000072 }
73
Douglas Gregor213f18b2010-10-28 15:44:59 +000074 ~SimpleTimer() {
75 if (WantTiming) {
76 TimeRecord Elapsed = TimeRecord::getCurrentTime();
77 Elapsed -= Start;
78 llvm::errs() << Output << ':';
79 Elapsed.print(Elapsed, llvm::errs());
80 llvm::errs() << '\n';
81 }
82 }
83 };
84}
85
Douglas Gregoreababfb2010-08-04 05:53:38 +000086/// \brief After failing to build a precompiled preamble (due to
87/// errors in the source that occurs in the preamble), the number of
88/// reparses during which we'll skip even trying to precompile the
89/// preamble.
90const unsigned DefaultPreambleRebuildInterval = 5;
91
Douglas Gregore3c60a72010-11-17 00:13:31 +000092/// \brief Tracks the number of ASTUnit objects that are currently active.
93///
94/// Used for debugging purposes only.
Douglas Gregor1fd9e0d2010-12-07 00:05:48 +000095static llvm::sys::cas_flag ActiveASTUnitObjects;
Douglas Gregore3c60a72010-11-17 00:13:31 +000096
Douglas Gregor3687e9d2010-04-05 21:10:19 +000097ASTUnit::ASTUnit(bool _MainFileIsAST)
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +000098 : OnlyLocalDecls(false), CaptureDiagnostics(false),
99 MainFileIsAST(_MainFileIsAST),
Douglas Gregor213f18b2010-10-28 15:44:59 +0000100 CompleteTranslationUnit(true), WantTiming(getenv("LIBCLANG_TIMING")),
Argyrios Kyrtzidis15727dd2011-03-05 01:03:48 +0000101 OwnsRemappedFileBuffers(true),
Douglas Gregor213f18b2010-10-28 15:44:59 +0000102 NumStoredDiagnosticsFromDriver(0),
Douglas Gregor4cd912a2010-10-12 00:50:20 +0000103 ConcurrencyCheckValue(CheckUnlocked),
Douglas Gregor671947b2010-08-19 01:33:06 +0000104 PreambleRebuildCounter(0), SavedMainFileBuffer(0), PreambleBuffer(0),
Douglas Gregor727d93e2010-08-17 00:40:40 +0000105 ShouldCacheCodeCompletionResults(false),
Chandler Carruthba7537f2011-07-14 09:02:10 +0000106 NestedMacroExpansions(true),
Douglas Gregor9b7db622011-02-16 18:16:54 +0000107 CompletionCacheTopLevelHashValue(0),
108 PreambleTopLevelHashValue(0),
109 CurrentTopLevelHashValue(0),
Douglas Gregor8b1540c2010-08-19 00:45:44 +0000110 UnsafeToFree(false) {
Douglas Gregore3c60a72010-11-17 00:13:31 +0000111 if (getenv("LIBCLANG_OBJTRACKING")) {
Douglas Gregor1fd9e0d2010-12-07 00:05:48 +0000112 llvm::sys::AtomicIncrement(&ActiveASTUnitObjects);
Douglas Gregore3c60a72010-11-17 00:13:31 +0000113 fprintf(stderr, "+++ %d translation units\n", ActiveASTUnitObjects);
114 }
Douglas Gregor385103b2010-07-30 20:58:08 +0000115}
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000116
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000117ASTUnit::~ASTUnit() {
Douglas Gregorbdf60622010-03-05 21:16:25 +0000118 ConcurrencyCheckValue = CheckLocked;
Douglas Gregorabc563f2010-07-19 21:46:24 +0000119 CleanTemporaryFiles();
Douglas Gregor175c4a92010-07-23 23:58:40 +0000120 if (!PreambleFile.empty())
Douglas Gregor385103b2010-07-30 20:58:08 +0000121 llvm::sys::Path(PreambleFile).eraseFromDisk();
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000122
123 // Free the buffers associated with remapped files. We are required to
124 // perform this operation here because we explicitly request that the
125 // compiler instance *not* free these buffers for each invocation of the
126 // parser.
Ted Kremenek4f327862011-03-21 18:40:17 +0000127 if (Invocation.getPtr() && OwnsRemappedFileBuffers) {
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000128 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
129 for (PreprocessorOptions::remapped_file_buffer_iterator
130 FB = PPOpts.remapped_file_buffer_begin(),
131 FBEnd = PPOpts.remapped_file_buffer_end();
132 FB != FBEnd;
133 ++FB)
134 delete FB->second;
135 }
Douglas Gregor28233422010-07-27 14:52:07 +0000136
137 delete SavedMainFileBuffer;
Douglas Gregor671947b2010-08-19 01:33:06 +0000138 delete PreambleBuffer;
139
Douglas Gregor213f18b2010-10-28 15:44:59 +0000140 ClearCachedCompletionResults();
Douglas Gregore3c60a72010-11-17 00:13:31 +0000141
142 if (getenv("LIBCLANG_OBJTRACKING")) {
Douglas Gregor1fd9e0d2010-12-07 00:05:48 +0000143 llvm::sys::AtomicDecrement(&ActiveASTUnitObjects);
Douglas Gregore3c60a72010-11-17 00:13:31 +0000144 fprintf(stderr, "--- %d translation units\n", ActiveASTUnitObjects);
145 }
Douglas Gregorabc563f2010-07-19 21:46:24 +0000146}
147
148void ASTUnit::CleanTemporaryFiles() {
Douglas Gregor313e26c2010-02-18 23:35:40 +0000149 for (unsigned I = 0, N = TemporaryFiles.size(); I != N; ++I)
150 TemporaryFiles[I].eraseFromDisk();
Douglas Gregorabc563f2010-07-19 21:46:24 +0000151 TemporaryFiles.clear();
Steve Naroffe19944c2009-10-15 22:23:48 +0000152}
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000153
Douglas Gregor8071e422010-08-15 06:18:01 +0000154/// \brief Determine the set of code-completion contexts in which this
155/// declaration should be shown.
156static unsigned getDeclShowContexts(NamedDecl *ND,
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000157 const LangOptions &LangOpts,
158 bool &IsNestedNameSpecifier) {
159 IsNestedNameSpecifier = false;
160
Douglas Gregor8071e422010-08-15 06:18:01 +0000161 if (isa<UsingShadowDecl>(ND))
162 ND = dyn_cast<NamedDecl>(ND->getUnderlyingDecl());
163 if (!ND)
164 return 0;
165
166 unsigned Contexts = 0;
167 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND) ||
168 isa<ClassTemplateDecl>(ND) || isa<TemplateTemplateParmDecl>(ND)) {
169 // Types can appear in these contexts.
170 if (LangOpts.CPlusPlus || !isa<TagDecl>(ND))
171 Contexts |= (1 << (CodeCompletionContext::CCC_TopLevel - 1))
172 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
173 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
174 | (1 << (CodeCompletionContext::CCC_Statement - 1))
Douglas Gregor02688102010-09-14 23:59:36 +0000175 | (1 << (CodeCompletionContext::CCC_Type - 1))
176 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1));
Douglas Gregor8071e422010-08-15 06:18:01 +0000177
178 // In C++, types can appear in expressions contexts (for functional casts).
179 if (LangOpts.CPlusPlus)
180 Contexts |= (1 << (CodeCompletionContext::CCC_Expression - 1));
181
182 // In Objective-C, message sends can send interfaces. In Objective-C++,
183 // all types are available due to functional casts.
184 if (LangOpts.CPlusPlus || isa<ObjCInterfaceDecl>(ND))
185 Contexts |= (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1));
Douglas Gregor3da626b2011-07-07 16:03:39 +0000186
187 // In Objective-C, you can only be a subclass of another Objective-C class
188 if (isa<ObjCInterfaceDecl>(ND))
Douglas Gregor0f91c8c2011-07-30 06:55:39 +0000189 Contexts |= (1 << (CodeCompletionContext::CCC_ObjCInterfaceName - 1));
Douglas Gregor8071e422010-08-15 06:18:01 +0000190
191 // Deal with tag names.
192 if (isa<EnumDecl>(ND)) {
193 Contexts |= (1 << (CodeCompletionContext::CCC_EnumTag - 1));
194
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000195 // Part of the nested-name-specifier in C++0x.
Douglas Gregor8071e422010-08-15 06:18:01 +0000196 if (LangOpts.CPlusPlus0x)
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000197 IsNestedNameSpecifier = true;
Douglas Gregor8071e422010-08-15 06:18:01 +0000198 } else if (RecordDecl *Record = dyn_cast<RecordDecl>(ND)) {
199 if (Record->isUnion())
200 Contexts |= (1 << (CodeCompletionContext::CCC_UnionTag - 1));
201 else
202 Contexts |= (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1));
203
Douglas Gregor8071e422010-08-15 06:18:01 +0000204 if (LangOpts.CPlusPlus)
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000205 IsNestedNameSpecifier = true;
Douglas Gregor52779fb2010-09-23 23:01:17 +0000206 } else if (isa<ClassTemplateDecl>(ND))
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000207 IsNestedNameSpecifier = true;
Douglas Gregor8071e422010-08-15 06:18:01 +0000208 } else if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
209 // Values can appear in these contexts.
210 Contexts = (1 << (CodeCompletionContext::CCC_Statement - 1))
211 | (1 << (CodeCompletionContext::CCC_Expression - 1))
Douglas Gregor02688102010-09-14 23:59:36 +0000212 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1))
Douglas Gregor8071e422010-08-15 06:18:01 +0000213 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1));
214 } else if (isa<ObjCProtocolDecl>(ND)) {
215 Contexts = (1 << (CodeCompletionContext::CCC_ObjCProtocolName - 1));
Douglas Gregor3da626b2011-07-07 16:03:39 +0000216 } else if (isa<ObjCCategoryDecl>(ND)) {
217 Contexts = (1 << (CodeCompletionContext::CCC_ObjCCategoryName - 1));
Douglas Gregor8071e422010-08-15 06:18:01 +0000218 } else if (isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) {
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000219 Contexts = (1 << (CodeCompletionContext::CCC_Namespace - 1));
Douglas Gregor8071e422010-08-15 06:18:01 +0000220
221 // Part of the nested-name-specifier.
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000222 IsNestedNameSpecifier = true;
Douglas Gregor8071e422010-08-15 06:18:01 +0000223 }
224
225 return Contexts;
226}
227
Douglas Gregor87c08a52010-08-13 22:48:40 +0000228void ASTUnit::CacheCodeCompletionResults() {
229 if (!TheSema)
230 return;
231
Douglas Gregor213f18b2010-10-28 15:44:59 +0000232 SimpleTimer Timer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +0000233 Timer.setOutput("Cache global code completions for " + getMainFileName());
Douglas Gregor87c08a52010-08-13 22:48:40 +0000234
235 // Clear out the previous results.
236 ClearCachedCompletionResults();
237
238 // Gather the set of global code completions.
John McCall0a2c5e22010-08-25 06:19:51 +0000239 typedef CodeCompletionResult Result;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000240 SmallVector<Result, 8> Results;
Douglas Gregor48601b32011-02-16 19:08:06 +0000241 CachedCompletionAllocator = new GlobalCodeCompletionAllocator;
242 TheSema->GatherGlobalCodeCompletions(*CachedCompletionAllocator, Results);
Douglas Gregor87c08a52010-08-13 22:48:40 +0000243
244 // Translate global code completions into cached completions.
Douglas Gregorf5586f62010-08-16 18:08:11 +0000245 llvm::DenseMap<CanQualType, unsigned> CompletionTypes;
246
Douglas Gregor87c08a52010-08-13 22:48:40 +0000247 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
248 switch (Results[I].Kind) {
Douglas Gregor8071e422010-08-15 06:18:01 +0000249 case Result::RK_Declaration: {
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000250 bool IsNestedNameSpecifier = false;
Douglas Gregor8071e422010-08-15 06:18:01 +0000251 CachedCodeCompletionResult CachedResult;
Douglas Gregor218937c2011-02-01 19:23:04 +0000252 CachedResult.Completion = Results[I].CreateCodeCompletionString(*TheSema,
Douglas Gregor48601b32011-02-16 19:08:06 +0000253 *CachedCompletionAllocator);
Douglas Gregor8071e422010-08-15 06:18:01 +0000254 CachedResult.ShowInContexts = getDeclShowContexts(Results[I].Declaration,
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000255 Ctx->getLangOptions(),
256 IsNestedNameSpecifier);
Douglas Gregor8071e422010-08-15 06:18:01 +0000257 CachedResult.Priority = Results[I].Priority;
258 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregor58ddb602010-08-23 23:00:57 +0000259 CachedResult.Availability = Results[I].Availability;
Douglas Gregorc4421e92010-08-16 16:46:30 +0000260
Douglas Gregorf5586f62010-08-16 18:08:11 +0000261 // Keep track of the type of this completion in an ASTContext-agnostic
262 // way.
Douglas Gregorc4421e92010-08-16 16:46:30 +0000263 QualType UsageType = getDeclUsageType(*Ctx, Results[I].Declaration);
Douglas Gregorf5586f62010-08-16 18:08:11 +0000264 if (UsageType.isNull()) {
Douglas Gregorc4421e92010-08-16 16:46:30 +0000265 CachedResult.TypeClass = STC_Void;
Douglas Gregorf5586f62010-08-16 18:08:11 +0000266 CachedResult.Type = 0;
267 } else {
268 CanQualType CanUsageType
269 = Ctx->getCanonicalType(UsageType.getUnqualifiedType());
270 CachedResult.TypeClass = getSimplifiedTypeClass(CanUsageType);
271
272 // Determine whether we have already seen this type. If so, we save
273 // ourselves the work of formatting the type string by using the
274 // temporary, CanQualType-based hash table to find the associated value.
275 unsigned &TypeValue = CompletionTypes[CanUsageType];
276 if (TypeValue == 0) {
277 TypeValue = CompletionTypes.size();
278 CachedCompletionTypes[QualType(CanUsageType).getAsString()]
279 = TypeValue;
280 }
281
282 CachedResult.Type = TypeValue;
Douglas Gregorc4421e92010-08-16 16:46:30 +0000283 }
Douglas Gregorf5586f62010-08-16 18:08:11 +0000284
Douglas Gregor8071e422010-08-15 06:18:01 +0000285 CachedCompletionResults.push_back(CachedResult);
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000286
287 /// Handle nested-name-specifiers in C++.
288 if (TheSema->Context.getLangOptions().CPlusPlus &&
289 IsNestedNameSpecifier && !Results[I].StartsNestedNameSpecifier) {
290 // The contexts in which a nested-name-specifier can appear in C++.
291 unsigned NNSContexts
292 = (1 << (CodeCompletionContext::CCC_TopLevel - 1))
293 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
294 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
295 | (1 << (CodeCompletionContext::CCC_Statement - 1))
296 | (1 << (CodeCompletionContext::CCC_Expression - 1))
297 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
298 | (1 << (CodeCompletionContext::CCC_EnumTag - 1))
299 | (1 << (CodeCompletionContext::CCC_UnionTag - 1))
300 | (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1))
Douglas Gregor2ccccb32010-08-23 18:23:48 +0000301 | (1 << (CodeCompletionContext::CCC_Type - 1))
Douglas Gregor02688102010-09-14 23:59:36 +0000302 | (1 << (CodeCompletionContext::CCC_PotentiallyQualifiedName - 1))
303 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1));
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000304
305 if (isa<NamespaceDecl>(Results[I].Declaration) ||
306 isa<NamespaceAliasDecl>(Results[I].Declaration))
307 NNSContexts |= (1 << (CodeCompletionContext::CCC_Namespace - 1));
308
309 if (unsigned RemainingContexts
310 = NNSContexts & ~CachedResult.ShowInContexts) {
311 // If there any contexts where this completion can be a
312 // nested-name-specifier but isn't already an option, create a
313 // nested-name-specifier completion.
314 Results[I].StartsNestedNameSpecifier = true;
Douglas Gregor218937c2011-02-01 19:23:04 +0000315 CachedResult.Completion
316 = Results[I].CreateCodeCompletionString(*TheSema,
Douglas Gregor48601b32011-02-16 19:08:06 +0000317 *CachedCompletionAllocator);
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000318 CachedResult.ShowInContexts = RemainingContexts;
319 CachedResult.Priority = CCP_NestedNameSpecifier;
320 CachedResult.TypeClass = STC_Void;
321 CachedResult.Type = 0;
322 CachedCompletionResults.push_back(CachedResult);
323 }
324 }
Douglas Gregor87c08a52010-08-13 22:48:40 +0000325 break;
Douglas Gregor8071e422010-08-15 06:18:01 +0000326 }
327
Douglas Gregor87c08a52010-08-13 22:48:40 +0000328 case Result::RK_Keyword:
329 case Result::RK_Pattern:
330 // Ignore keywords and patterns; we don't care, since they are so
331 // easily regenerated.
332 break;
333
334 case Result::RK_Macro: {
335 CachedCodeCompletionResult CachedResult;
Douglas Gregor218937c2011-02-01 19:23:04 +0000336 CachedResult.Completion
337 = Results[I].CreateCodeCompletionString(*TheSema,
Douglas Gregor48601b32011-02-16 19:08:06 +0000338 *CachedCompletionAllocator);
Douglas Gregor87c08a52010-08-13 22:48:40 +0000339 CachedResult.ShowInContexts
340 = (1 << (CodeCompletionContext::CCC_TopLevel - 1))
341 | (1 << (CodeCompletionContext::CCC_ObjCInterface - 1))
342 | (1 << (CodeCompletionContext::CCC_ObjCImplementation - 1))
343 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
344 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
345 | (1 << (CodeCompletionContext::CCC_Statement - 1))
346 | (1 << (CodeCompletionContext::CCC_Expression - 1))
Douglas Gregor1fbb4472010-08-24 20:21:13 +0000347 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
Douglas Gregorf29c5232010-08-24 22:20:20 +0000348 | (1 << (CodeCompletionContext::CCC_MacroNameUse - 1))
Douglas Gregor02688102010-09-14 23:59:36 +0000349 | (1 << (CodeCompletionContext::CCC_PreprocessorExpression - 1))
Douglas Gregor5c722c702011-02-18 23:30:37 +0000350 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1))
351 | (1 << (CodeCompletionContext::CCC_OtherWithMacros - 1));
Douglas Gregor2ccccb32010-08-23 18:23:48 +0000352
Douglas Gregor87c08a52010-08-13 22:48:40 +0000353 CachedResult.Priority = Results[I].Priority;
354 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregor58ddb602010-08-23 23:00:57 +0000355 CachedResult.Availability = Results[I].Availability;
Douglas Gregor1827e102010-08-16 16:18:59 +0000356 CachedResult.TypeClass = STC_Void;
Douglas Gregorf5586f62010-08-16 18:08:11 +0000357 CachedResult.Type = 0;
Douglas Gregor87c08a52010-08-13 22:48:40 +0000358 CachedCompletionResults.push_back(CachedResult);
359 break;
360 }
361 }
Douglas Gregor87c08a52010-08-13 22:48:40 +0000362 }
Douglas Gregor9b7db622011-02-16 18:16:54 +0000363
364 // Save the current top-level hash value.
365 CompletionCacheTopLevelHashValue = CurrentTopLevelHashValue;
Douglas Gregor87c08a52010-08-13 22:48:40 +0000366}
367
368void ASTUnit::ClearCachedCompletionResults() {
Douglas Gregor87c08a52010-08-13 22:48:40 +0000369 CachedCompletionResults.clear();
Douglas Gregorf5586f62010-08-16 18:08:11 +0000370 CachedCompletionTypes.clear();
Douglas Gregor48601b32011-02-16 19:08:06 +0000371 CachedCompletionAllocator = 0;
Douglas Gregor87c08a52010-08-13 22:48:40 +0000372}
373
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000374namespace {
375
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000376/// \brief Gathers information from ASTReader that will be used to initialize
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000377/// a Preprocessor.
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000378class ASTInfoCollector : public ASTReaderListener {
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000379 LangOptions &LangOpt;
380 HeaderSearch &HSI;
381 std::string &TargetTriple;
382 std::string &Predefines;
383 unsigned &Counter;
Mike Stump1eb44332009-09-09 15:08:12 +0000384
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000385 unsigned NumHeaderInfos;
Mike Stump1eb44332009-09-09 15:08:12 +0000386
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000387public:
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000388 ASTInfoCollector(LangOptions &LangOpt, HeaderSearch &HSI,
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000389 std::string &TargetTriple, std::string &Predefines,
390 unsigned &Counter)
391 : LangOpt(LangOpt), HSI(HSI), TargetTriple(TargetTriple),
392 Predefines(Predefines), Counter(Counter), NumHeaderInfos(0) {}
Mike Stump1eb44332009-09-09 15:08:12 +0000393
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000394 virtual bool ReadLanguageOptions(const LangOptions &LangOpts) {
395 LangOpt = LangOpts;
396 return false;
397 }
Mike Stump1eb44332009-09-09 15:08:12 +0000398
Chris Lattner5f9e2722011-07-23 10:55:15 +0000399 virtual bool ReadTargetTriple(StringRef Triple) {
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000400 TargetTriple = Triple;
401 return false;
402 }
Mike Stump1eb44332009-09-09 15:08:12 +0000403
Sebastian Redlcb481aa2010-07-14 23:29:55 +0000404 virtual bool ReadPredefinesBuffer(const PCHPredefinesBlocks &Buffers,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000405 StringRef OriginalFileName,
Nick Lewycky277a6e72011-02-23 21:16:44 +0000406 std::string &SuggestedPredefines,
407 FileManager &FileMgr) {
Sebastian Redlcb481aa2010-07-14 23:29:55 +0000408 Predefines = Buffers[0].Data;
409 for (unsigned I = 1, N = Buffers.size(); I != N; ++I) {
410 Predefines += Buffers[I].Data;
411 }
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000412 return false;
413 }
Mike Stump1eb44332009-09-09 15:08:12 +0000414
Douglas Gregorec1afbf2010-03-16 19:09:18 +0000415 virtual void ReadHeaderFileInfo(const HeaderFileInfo &HFI, unsigned ID) {
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000416 HSI.setHeaderFileInfoForUID(HFI, NumHeaderInfos++);
417 }
Mike Stump1eb44332009-09-09 15:08:12 +0000418
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000419 virtual void ReadCounter(unsigned Value) {
420 Counter = Value;
421 }
422};
423
Douglas Gregora88084b2010-02-18 18:08:43 +0000424class StoredDiagnosticClient : public DiagnosticClient {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000425 SmallVectorImpl<StoredDiagnostic> &StoredDiags;
Douglas Gregora88084b2010-02-18 18:08:43 +0000426
427public:
428 explicit StoredDiagnosticClient(
Chris Lattner5f9e2722011-07-23 10:55:15 +0000429 SmallVectorImpl<StoredDiagnostic> &StoredDiags)
Douglas Gregora88084b2010-02-18 18:08:43 +0000430 : StoredDiags(StoredDiags) { }
431
432 virtual void HandleDiagnostic(Diagnostic::Level Level,
433 const DiagnosticInfo &Info);
434};
435
436/// \brief RAII object that optionally captures diagnostics, if
437/// there is no diagnostic client to capture them already.
438class CaptureDroppedDiagnostics {
439 Diagnostic &Diags;
440 StoredDiagnosticClient Client;
441 DiagnosticClient *PreviousClient;
442
443public:
444 CaptureDroppedDiagnostics(bool RequestCapture, Diagnostic &Diags,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000445 SmallVectorImpl<StoredDiagnostic> &StoredDiags)
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000446 : Diags(Diags), Client(StoredDiags), PreviousClient(0)
Douglas Gregora88084b2010-02-18 18:08:43 +0000447 {
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000448 if (RequestCapture || Diags.getClient() == 0) {
449 PreviousClient = Diags.takeClient();
Douglas Gregora88084b2010-02-18 18:08:43 +0000450 Diags.setClient(&Client);
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000451 }
Douglas Gregora88084b2010-02-18 18:08:43 +0000452 }
453
454 ~CaptureDroppedDiagnostics() {
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000455 if (Diags.getClient() == &Client) {
456 Diags.takeClient();
457 Diags.setClient(PreviousClient);
458 }
Douglas Gregora88084b2010-02-18 18:08:43 +0000459 }
460};
461
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000462} // anonymous namespace
463
Douglas Gregora88084b2010-02-18 18:08:43 +0000464void StoredDiagnosticClient::HandleDiagnostic(Diagnostic::Level Level,
465 const DiagnosticInfo &Info) {
Argyrios Kyrtzidisf2224d82010-11-18 20:06:46 +0000466 // Default implementation (Warnings/errors count).
467 DiagnosticClient::HandleDiagnostic(Level, Info);
468
Douglas Gregora88084b2010-02-18 18:08:43 +0000469 StoredDiags.push_back(StoredDiagnostic(Level, Info));
470}
471
Steve Naroff77accc12009-09-03 18:19:54 +0000472const std::string &ASTUnit::getOriginalSourceFileName() {
Daniel Dunbar68d40e22009-12-02 08:44:16 +0000473 return OriginalSourceFile;
Steve Naroff77accc12009-09-03 18:19:54 +0000474}
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000475
Chris Lattner5f9e2722011-07-23 10:55:15 +0000476llvm::MemoryBuffer *ASTUnit::getBufferForFile(StringRef Filename,
Chris Lattner75dfb652010-11-23 09:19:42 +0000477 std::string *ErrorStr) {
Chris Lattner39b49bc2010-11-23 08:35:12 +0000478 assert(FileMgr);
Chris Lattner75dfb652010-11-23 09:19:42 +0000479 return FileMgr->getBufferForFile(Filename, ErrorStr);
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +0000480}
481
Douglas Gregore47be3e2010-11-11 00:39:14 +0000482/// \brief Configure the diagnostics object for use with ASTUnit.
483void ASTUnit::ConfigureDiags(llvm::IntrusiveRefCntPtr<Diagnostic> &Diags,
Douglas Gregor0b53cf82011-01-19 01:02:47 +0000484 const char **ArgBegin, const char **ArgEnd,
Douglas Gregore47be3e2010-11-11 00:39:14 +0000485 ASTUnit &AST, bool CaptureDiagnostics) {
486 if (!Diags.getPtr()) {
487 // No diagnostics engine was provided, so create our own diagnostics object
488 // with the default options.
489 DiagnosticOptions DiagOpts;
490 DiagnosticClient *Client = 0;
491 if (CaptureDiagnostics)
492 Client = new StoredDiagnosticClient(AST.StoredDiagnostics);
Douglas Gregor0b53cf82011-01-19 01:02:47 +0000493 Diags = CompilerInstance::createDiagnostics(DiagOpts, ArgEnd- ArgBegin,
494 ArgBegin, Client);
Douglas Gregore47be3e2010-11-11 00:39:14 +0000495 } else if (CaptureDiagnostics) {
496 Diags->setClient(new StoredDiagnosticClient(AST.StoredDiagnostics));
497 }
498}
499
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000500ASTUnit *ASTUnit::LoadFromASTFile(const std::string &Filename,
Douglas Gregor28019772010-04-05 23:52:57 +0000501 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +0000502 const FileSystemOptions &FileSystemOpts,
Ted Kremenek5cf48762009-10-17 00:34:24 +0000503 bool OnlyLocalDecls,
Douglas Gregor4db64a42010-01-23 00:14:00 +0000504 RemappedFile *RemappedFiles,
Douglas Gregora88084b2010-02-18 18:08:43 +0000505 unsigned NumRemappedFiles,
506 bool CaptureDiagnostics) {
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000507 llvm::OwningPtr<ASTUnit> AST(new ASTUnit(true));
Ted Kremenekb547eeb2011-03-18 02:06:56 +0000508
509 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +0000510 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
511 ASTUnitCleanup(AST.get());
512 llvm::CrashRecoveryContextCleanupRegistrar<Diagnostic,
513 llvm::CrashRecoveryContextReleaseRefCleanup<Diagnostic> >
514 DiagCleanup(Diags.getPtr());
Ted Kremenekb547eeb2011-03-18 02:06:56 +0000515
Douglas Gregor0b53cf82011-01-19 01:02:47 +0000516 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
Douglas Gregorabc563f2010-07-19 21:46:24 +0000517
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000518 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregore47be3e2010-11-11 00:39:14 +0000519 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor28019772010-04-05 23:52:57 +0000520 AST->Diagnostics = Diags;
Ted Kremenek4f327862011-03-21 18:40:17 +0000521 AST->FileMgr = new FileManager(FileSystemOpts);
522 AST->SourceMgr = new SourceManager(AST->getDiagnostics(),
523 AST->getFileManager());
Chris Lattner39b49bc2010-11-23 08:35:12 +0000524 AST->HeaderInfo.reset(new HeaderSearch(AST->getFileManager()));
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000525
Douglas Gregor4db64a42010-01-23 00:14:00 +0000526 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000527 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
528 if (const llvm::MemoryBuffer *
529 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
530 // Create the file entry for the file that we're mapping from.
531 const FileEntry *FromFile
532 = AST->getFileManager().getVirtualFile(RemappedFiles[I].first,
533 memBuf->getBufferSize(),
534 0);
535 if (!FromFile) {
536 AST->getDiagnostics().Report(diag::err_fe_remap_missing_from_file)
537 << RemappedFiles[I].first;
538 delete memBuf;
539 continue;
540 }
541
542 // Override the contents of the "from" file with the contents of
543 // the "to" file.
544 AST->getSourceManager().overrideFileContents(FromFile, memBuf);
545
546 } else {
547 const char *fname = fileOrBuf.get<const char *>();
548 const FileEntry *ToFile = AST->FileMgr->getFile(fname);
549 if (!ToFile) {
550 AST->getDiagnostics().Report(diag::err_fe_remap_missing_to_file)
551 << RemappedFiles[I].first << fname;
552 continue;
553 }
554
555 // Create the file entry for the file that we're mapping from.
556 const FileEntry *FromFile
557 = AST->getFileManager().getVirtualFile(RemappedFiles[I].first,
558 ToFile->getSize(),
559 0);
560 if (!FromFile) {
561 AST->getDiagnostics().Report(diag::err_fe_remap_missing_from_file)
562 << RemappedFiles[I].first;
563 delete memBuf;
564 continue;
565 }
566
567 // Override the contents of the "from" file with the contents of
568 // the "to" file.
569 AST->getSourceManager().overrideFileContents(FromFile, ToFile);
Douglas Gregor4db64a42010-01-23 00:14:00 +0000570 }
Douglas Gregor4db64a42010-01-23 00:14:00 +0000571 }
572
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000573 // Gather Info for preprocessor construction later on.
Mike Stump1eb44332009-09-09 15:08:12 +0000574
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000575 LangOptions LangInfo;
576 HeaderSearch &HeaderInfo = *AST->HeaderInfo.get();
577 std::string TargetTriple;
578 std::string Predefines;
579 unsigned Counter;
580
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000581 llvm::OwningPtr<ASTReader> Reader;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000582
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000583 Reader.reset(new ASTReader(AST->getSourceManager(), AST->getFileManager(),
Chris Lattner39b49bc2010-11-23 08:35:12 +0000584 AST->getDiagnostics()));
Ted Kremenek8c647de2011-05-04 23:27:12 +0000585
586 // Recover resources if we crash before exiting this method.
587 llvm::CrashRecoveryContextCleanupRegistrar<ASTReader>
588 ReaderCleanup(Reader.get());
589
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000590 Reader->setListener(new ASTInfoCollector(LangInfo, HeaderInfo, TargetTriple,
Daniel Dunbarcc318932009-09-03 05:59:35 +0000591 Predefines, Counter));
592
Douglas Gregor72a9ae12011-07-22 16:00:58 +0000593 switch (Reader->ReadAST(Filename, serialization::MK_MainFile)) {
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000594 case ASTReader::Success:
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000595 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000596
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000597 case ASTReader::Failure:
598 case ASTReader::IgnorePCH:
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000599 AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000600 return NULL;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000601 }
Mike Stump1eb44332009-09-09 15:08:12 +0000602
Daniel Dunbar68d40e22009-12-02 08:44:16 +0000603 AST->OriginalSourceFile = Reader->getOriginalSourceFile();
604
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000605 // AST file loaded successfully. Now create the preprocessor.
Mike Stump1eb44332009-09-09 15:08:12 +0000606
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000607 // Get information about the target being compiled for.
Daniel Dunbard58c03f2009-11-15 06:48:46 +0000608 //
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000609 // FIXME: This is broken, we should store the TargetOptions in the AST file.
Daniel Dunbard58c03f2009-11-15 06:48:46 +0000610 TargetOptions TargetOpts;
611 TargetOpts.ABI = "";
John McCall875ab102010-08-22 06:43:33 +0000612 TargetOpts.CXXABI = "";
Daniel Dunbard58c03f2009-11-15 06:48:46 +0000613 TargetOpts.CPU = "";
614 TargetOpts.Features.clear();
615 TargetOpts.Triple = TargetTriple;
Ted Kremenek4f327862011-03-21 18:40:17 +0000616 AST->Target = TargetInfo::CreateTargetInfo(AST->getDiagnostics(),
617 TargetOpts);
618 AST->PP = new Preprocessor(AST->getDiagnostics(), LangInfo, *AST->Target,
619 AST->getSourceManager(), HeaderInfo);
620 Preprocessor &PP = *AST->PP;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000621
Daniel Dunbard5b61262009-09-21 03:03:47 +0000622 PP.setPredefines(Reader->getSuggestedPredefines());
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000623 PP.setCounterValue(Counter);
Daniel Dunbarcc318932009-09-03 05:59:35 +0000624 Reader->setPreprocessor(PP);
Mike Stump1eb44332009-09-09 15:08:12 +0000625
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000626 // Create and initialize the ASTContext.
627
Ted Kremenek4f327862011-03-21 18:40:17 +0000628 AST->Ctx = new ASTContext(LangInfo,
629 AST->getSourceManager(),
630 *AST->Target,
631 PP.getIdentifierTable(),
632 PP.getSelectorTable(),
633 PP.getBuiltinInfo(),
634 /* size_reserve = */0);
635 ASTContext &Context = *AST->Ctx;
Mike Stump1eb44332009-09-09 15:08:12 +0000636
Daniel Dunbarcc318932009-09-03 05:59:35 +0000637 Reader->InitializeContext(Context);
Mike Stump1eb44332009-09-09 15:08:12 +0000638
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000639 // Attach the AST reader to the AST context as an external AST
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000640 // source, so that declarations will be deserialized from the
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000641 // AST file as needed.
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000642 ASTReader *ReaderPtr = Reader.get();
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000643 llvm::OwningPtr<ExternalASTSource> Source(Reader.take());
Ted Kremenek8c647de2011-05-04 23:27:12 +0000644
645 // Unregister the cleanup for ASTReader. It will get cleaned up
646 // by the ASTUnit cleanup.
647 ReaderCleanup.unregister();
648
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000649 Context.setExternalSource(Source);
650
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000651 // Create an AST consumer, even though it isn't used.
652 AST->Consumer.reset(new ASTConsumer);
653
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000654 // Create a semantic analysis object and tell the AST reader about it.
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000655 AST->TheSema.reset(new Sema(PP, Context, *AST->Consumer));
656 AST->TheSema->Initialize();
657 ReaderPtr->InitializeSema(*AST->TheSema);
658
Mike Stump1eb44332009-09-09 15:08:12 +0000659 return AST.take();
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000660}
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000661
662namespace {
663
Douglas Gregor9b7db622011-02-16 18:16:54 +0000664/// \brief Preprocessor callback class that updates a hash value with the names
665/// of all macros that have been defined by the translation unit.
666class MacroDefinitionTrackerPPCallbacks : public PPCallbacks {
667 unsigned &Hash;
668
669public:
670 explicit MacroDefinitionTrackerPPCallbacks(unsigned &Hash) : Hash(Hash) { }
671
672 virtual void MacroDefined(const Token &MacroNameTok, const MacroInfo *MI) {
673 Hash = llvm::HashString(MacroNameTok.getIdentifierInfo()->getName(), Hash);
674 }
675};
676
677/// \brief Add the given declaration to the hash of all top-level entities.
678void AddTopLevelDeclarationToHash(Decl *D, unsigned &Hash) {
679 if (!D)
680 return;
681
682 DeclContext *DC = D->getDeclContext();
683 if (!DC)
684 return;
685
686 if (!(DC->isTranslationUnit() || DC->getLookupParent()->isTranslationUnit()))
687 return;
688
689 if (NamedDecl *ND = dyn_cast<NamedDecl>(D)) {
690 if (ND->getIdentifier())
691 Hash = llvm::HashString(ND->getIdentifier()->getName(), Hash);
692 else if (DeclarationName Name = ND->getDeclName()) {
693 std::string NameStr = Name.getAsString();
694 Hash = llvm::HashString(NameStr, Hash);
695 }
696 return;
697 }
698
699 if (ObjCForwardProtocolDecl *Forward
700 = dyn_cast<ObjCForwardProtocolDecl>(D)) {
701 for (ObjCForwardProtocolDecl::protocol_iterator
702 P = Forward->protocol_begin(),
703 PEnd = Forward->protocol_end();
704 P != PEnd; ++P)
705 AddTopLevelDeclarationToHash(*P, Hash);
706 return;
707 }
708
Chris Lattner5f9e2722011-07-23 10:55:15 +0000709 if (ObjCClassDecl *Class = dyn_cast<ObjCClassDecl>(D)) {
Douglas Gregor9b7db622011-02-16 18:16:54 +0000710 for (ObjCClassDecl::iterator I = Class->begin(), IEnd = Class->end();
711 I != IEnd; ++I)
712 AddTopLevelDeclarationToHash(I->getInterface(), Hash);
713 return;
714 }
715}
716
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000717class TopLevelDeclTrackerConsumer : public ASTConsumer {
718 ASTUnit &Unit;
Douglas Gregor9b7db622011-02-16 18:16:54 +0000719 unsigned &Hash;
720
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000721public:
Douglas Gregor9b7db622011-02-16 18:16:54 +0000722 TopLevelDeclTrackerConsumer(ASTUnit &_Unit, unsigned &Hash)
723 : Unit(_Unit), Hash(Hash) {
724 Hash = 0;
725 }
726
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000727 void HandleTopLevelDecl(DeclGroupRef D) {
Ted Kremenekda5a4282010-05-03 20:16:35 +0000728 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
729 Decl *D = *it;
730 // FIXME: Currently ObjC method declarations are incorrectly being
731 // reported as top-level declarations, even though their DeclContext
732 // is the containing ObjC @interface/@implementation. This is a
733 // fundamental problem in the parser right now.
734 if (isa<ObjCMethodDecl>(D))
735 continue;
Douglas Gregor9b7db622011-02-16 18:16:54 +0000736
737 AddTopLevelDeclarationToHash(D, Hash);
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000738 Unit.addTopLevelDecl(D);
Ted Kremenekda5a4282010-05-03 20:16:35 +0000739 }
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000740 }
Sebastian Redl27372b42010-08-11 18:52:41 +0000741
742 // We're not interested in "interesting" decls.
743 void HandleInterestingDecl(DeclGroupRef) {}
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000744};
745
746class TopLevelDeclTrackerAction : public ASTFrontendAction {
747public:
748 ASTUnit &Unit;
749
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000750 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000751 StringRef InFile) {
Douglas Gregor9b7db622011-02-16 18:16:54 +0000752 CI.getPreprocessor().addPPCallbacks(
753 new MacroDefinitionTrackerPPCallbacks(Unit.getCurrentTopLevelHashValue()));
754 return new TopLevelDeclTrackerConsumer(Unit,
755 Unit.getCurrentTopLevelHashValue());
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000756 }
757
758public:
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000759 TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {}
760
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000761 virtual bool hasCodeCompletionSupport() const { return false; }
Douglas Gregordf95a132010-08-09 20:45:32 +0000762 virtual bool usesCompleteTranslationUnit() {
763 return Unit.isCompleteTranslationUnit();
764 }
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000765};
766
Douglas Gregor89d99802010-11-30 06:16:57 +0000767class PrecompilePreambleConsumer : public PCHGenerator,
768 public ASTSerializationListener {
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000769 ASTUnit &Unit;
Douglas Gregor9b7db622011-02-16 18:16:54 +0000770 unsigned &Hash;
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000771 std::vector<Decl *> TopLevelDecls;
Douglas Gregor89d99802010-11-30 06:16:57 +0000772
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000773public:
774 PrecompilePreambleConsumer(ASTUnit &Unit,
775 const Preprocessor &PP, bool Chaining,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000776 StringRef isysroot, raw_ostream *Out)
Douglas Gregor9b7db622011-02-16 18:16:54 +0000777 : PCHGenerator(PP, "", Chaining, isysroot, Out), Unit(Unit),
778 Hash(Unit.getCurrentTopLevelHashValue()) {
779 Hash = 0;
780 }
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000781
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000782 virtual void HandleTopLevelDecl(DeclGroupRef D) {
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000783 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
784 Decl *D = *it;
785 // FIXME: Currently ObjC method declarations are incorrectly being
786 // reported as top-level declarations, even though their DeclContext
787 // is the containing ObjC @interface/@implementation. This is a
788 // fundamental problem in the parser right now.
789 if (isa<ObjCMethodDecl>(D))
790 continue;
Douglas Gregor9b7db622011-02-16 18:16:54 +0000791 AddTopLevelDeclarationToHash(D, Hash);
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000792 TopLevelDecls.push_back(D);
793 }
794 }
795
796 virtual void HandleTranslationUnit(ASTContext &Ctx) {
797 PCHGenerator::HandleTranslationUnit(Ctx);
798 if (!Unit.getDiagnostics().hasErrorOccurred()) {
799 // Translate the top-level declarations we captured during
800 // parsing into declaration IDs in the precompiled
801 // preamble. This will allow us to deserialize those top-level
802 // declarations when requested.
803 for (unsigned I = 0, N = TopLevelDecls.size(); I != N; ++I)
804 Unit.addTopLevelDeclFromPreamble(
805 getWriter().getDeclID(TopLevelDecls[I]));
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000806 }
807 }
Douglas Gregor89d99802010-11-30 06:16:57 +0000808
809 virtual void SerializedPreprocessedEntity(PreprocessedEntity *Entity,
810 uint64_t Offset) {
811 Unit.addPreprocessedEntityFromPreamble(Offset);
812 }
813
814 virtual ASTSerializationListener *GetASTSerializationListener() {
815 return this;
816 }
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000817};
818
819class PrecompilePreambleAction : public ASTFrontendAction {
820 ASTUnit &Unit;
821
822public:
823 explicit PrecompilePreambleAction(ASTUnit &Unit) : Unit(Unit) {}
824
825 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000826 StringRef InFile) {
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000827 std::string Sysroot;
Argyrios Kyrtzidis8e3df4d2011-02-15 17:54:22 +0000828 std::string OutputFile;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000829 raw_ostream *OS = 0;
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000830 bool Chaining;
Argyrios Kyrtzidis8e3df4d2011-02-15 17:54:22 +0000831 if (GeneratePCHAction::ComputeASTConsumerArguments(CI, InFile, Sysroot,
832 OutputFile,
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000833 OS, Chaining))
834 return 0;
835
Douglas Gregor832d6202011-07-22 16:35:34 +0000836 if (!CI.getFrontendOpts().RelocatablePCH)
837 Sysroot.clear();
838
Douglas Gregor9b7db622011-02-16 18:16:54 +0000839 CI.getPreprocessor().addPPCallbacks(
840 new MacroDefinitionTrackerPPCallbacks(Unit.getCurrentTopLevelHashValue()));
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000841 return new PrecompilePreambleConsumer(Unit, CI.getPreprocessor(), Chaining,
Douglas Gregor832d6202011-07-22 16:35:34 +0000842 Sysroot, OS);
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000843 }
844
845 virtual bool hasCodeCompletionSupport() const { return false; }
846 virtual bool hasASTFileSupport() const { return false; }
Douglas Gregordf95a132010-08-09 20:45:32 +0000847 virtual bool usesCompleteTranslationUnit() { return false; }
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000848};
849
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000850}
851
Douglas Gregorabc563f2010-07-19 21:46:24 +0000852/// Parse the source file into a translation unit using the given compiler
853/// invocation, replacing the current translation unit.
854///
855/// \returns True if a failure occurred that causes the ASTUnit not to
856/// contain any translation-unit information, false otherwise.
Douglas Gregor754f3492010-07-24 00:38:13 +0000857bool ASTUnit::Parse(llvm::MemoryBuffer *OverrideMainBuffer) {
Douglas Gregor28233422010-07-27 14:52:07 +0000858 delete SavedMainFileBuffer;
859 SavedMainFileBuffer = 0;
860
Ted Kremenek4f327862011-03-21 18:40:17 +0000861 if (!Invocation) {
Douglas Gregor671947b2010-08-19 01:33:06 +0000862 delete OverrideMainBuffer;
Douglas Gregorabc563f2010-07-19 21:46:24 +0000863 return true;
Douglas Gregor671947b2010-08-19 01:33:06 +0000864 }
Douglas Gregorabc563f2010-07-19 21:46:24 +0000865
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000866 // Create the compiler instance to use for building the AST.
Ted Kremenek03201fb2011-03-21 18:40:07 +0000867 llvm::OwningPtr<CompilerInstance> Clang(new CompilerInstance());
868
869 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +0000870 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
871 CICleanup(Clang.get());
Ted Kremenek03201fb2011-03-21 18:40:07 +0000872
Ted Kremenek4f327862011-03-21 18:40:17 +0000873 Clang->setInvocation(&*Invocation);
Ted Kremenek03201fb2011-03-21 18:40:07 +0000874 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].second;
Douglas Gregorabc563f2010-07-19 21:46:24 +0000875
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000876 // Set up diagnostics, capturing any diagnostics that would
877 // otherwise be dropped.
Ted Kremenek03201fb2011-03-21 18:40:07 +0000878 Clang->setDiagnostics(&getDiagnostics());
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000879
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000880 // Create the target instance.
Ted Kremenek03201fb2011-03-21 18:40:07 +0000881 Clang->getTargetOpts().Features = TargetFeatures;
882 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
Ted Kremenek4f327862011-03-21 18:40:17 +0000883 Clang->getTargetOpts()));
Ted Kremenek03201fb2011-03-21 18:40:07 +0000884 if (!Clang->hasTarget()) {
Douglas Gregor671947b2010-08-19 01:33:06 +0000885 delete OverrideMainBuffer;
Douglas Gregorabc563f2010-07-19 21:46:24 +0000886 return true;
Douglas Gregor671947b2010-08-19 01:33:06 +0000887 }
888
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000889 // Inform the target of the language options.
890 //
891 // FIXME: We shouldn't need to do this, the target should be immutable once
892 // created. This complexity should be lifted elsewhere.
Ted Kremenek03201fb2011-03-21 18:40:07 +0000893 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregorabc563f2010-07-19 21:46:24 +0000894
Ted Kremenek03201fb2011-03-21 18:40:07 +0000895 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000896 "Invocation must have exactly one source file!");
Ted Kremenek03201fb2011-03-21 18:40:07 +0000897 assert(Clang->getFrontendOpts().Inputs[0].first != IK_AST &&
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000898 "FIXME: AST inputs not yet supported here!");
Ted Kremenek03201fb2011-03-21 18:40:07 +0000899 assert(Clang->getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
Daniel Dunbarfaddc3e2010-06-07 23:26:47 +0000900 "IR inputs not support here!");
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000901
Douglas Gregorabc563f2010-07-19 21:46:24 +0000902 // Configure the various subsystems.
903 // FIXME: Should we retain the previous file manager?
Ted Kremenek03201fb2011-03-21 18:40:07 +0000904 FileSystemOpts = Clang->getFileSystemOpts();
Ted Kremenek4f327862011-03-21 18:40:17 +0000905 FileMgr = new FileManager(FileSystemOpts);
906 SourceMgr = new SourceManager(getDiagnostics(), *FileMgr);
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000907 TheSema.reset();
Ted Kremenek4f327862011-03-21 18:40:17 +0000908 Ctx = 0;
909 PP = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +0000910
911 // Clear out old caches and data.
912 TopLevelDecls.clear();
Douglas Gregor89d99802010-11-30 06:16:57 +0000913 PreprocessedEntities.clear();
Douglas Gregorabc563f2010-07-19 21:46:24 +0000914 CleanTemporaryFiles();
915 PreprocessedEntitiesByFile.clear();
Douglas Gregorc0659ec2010-08-02 20:51:39 +0000916
Douglas Gregorf128fed2010-08-20 00:02:33 +0000917 if (!OverrideMainBuffer) {
Douglas Gregor4cd912a2010-10-12 00:50:20 +0000918 StoredDiagnostics.erase(
919 StoredDiagnostics.begin() + NumStoredDiagnosticsFromDriver,
920 StoredDiagnostics.end());
Douglas Gregorf128fed2010-08-20 00:02:33 +0000921 TopLevelDeclsInPreamble.clear();
Douglas Gregor89d99802010-11-30 06:16:57 +0000922 PreprocessedEntitiesInPreamble.clear();
Douglas Gregorf128fed2010-08-20 00:02:33 +0000923 }
924
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000925 // Create a file manager object to provide access to and cache the filesystem.
Ted Kremenek03201fb2011-03-21 18:40:07 +0000926 Clang->setFileManager(&getFileManager());
Douglas Gregorabc563f2010-07-19 21:46:24 +0000927
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000928 // Create the source manager.
Ted Kremenek03201fb2011-03-21 18:40:07 +0000929 Clang->setSourceManager(&getSourceManager());
Douglas Gregorabc563f2010-07-19 21:46:24 +0000930
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000931 // If the main file has been overridden due to the use of a preamble,
932 // make that override happen and introduce the preamble.
Ted Kremenek03201fb2011-03-21 18:40:07 +0000933 PreprocessorOptions &PreprocessorOpts = Clang->getPreprocessorOpts();
Chandler Carruthba7537f2011-07-14 09:02:10 +0000934 PreprocessorOpts.DetailedRecordIncludesNestedMacroExpansions
935 = NestedMacroExpansions;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000936 std::string PriorImplicitPCHInclude;
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000937 if (OverrideMainBuffer) {
938 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
939 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
940 PreprocessorOpts.PrecompiledPreambleBytes.second
941 = PreambleEndsAtStartOfLine;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000942 PriorImplicitPCHInclude = PreprocessorOpts.ImplicitPCHInclude;
Douglas Gregor385103b2010-07-30 20:58:08 +0000943 PreprocessorOpts.ImplicitPCHInclude = PreambleFile;
Douglas Gregorfae3b2f2010-07-27 00:27:13 +0000944 PreprocessorOpts.DisablePCHValidation = true;
Douglas Gregor28233422010-07-27 14:52:07 +0000945
Douglas Gregorc0659ec2010-08-02 20:51:39 +0000946 // The stored diagnostic has the old source manager in it; update
947 // the locations to refer into the new source manager. Since we've
948 // been careful to make sure that the source manager's state
949 // before and after are identical, so that we can reuse the source
950 // location itself.
Douglas Gregor4cd912a2010-10-12 00:50:20 +0000951 for (unsigned I = NumStoredDiagnosticsFromDriver,
952 N = StoredDiagnostics.size();
953 I < N; ++I) {
Douglas Gregorc0659ec2010-08-02 20:51:39 +0000954 FullSourceLoc Loc(StoredDiagnostics[I].getLocation(),
955 getSourceManager());
956 StoredDiagnostics[I].setLocation(Loc);
957 }
Douglas Gregor4cd912a2010-10-12 00:50:20 +0000958
959 // Keep track of the override buffer;
960 SavedMainFileBuffer = OverrideMainBuffer;
Douglas Gregorf128fed2010-08-20 00:02:33 +0000961 } else {
962 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
963 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000964 }
965
Ted Kremenek25a11e12011-03-22 01:15:24 +0000966 llvm::OwningPtr<TopLevelDeclTrackerAction> Act(
967 new TopLevelDeclTrackerAction(*this));
968
969 // Recover resources if we crash before exiting this method.
970 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
971 ActCleanup(Act.get());
972
Ted Kremenek03201fb2011-03-21 18:40:07 +0000973 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0].second,
974 Clang->getFrontendOpts().Inputs[0].first))
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000975 goto error;
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000976
977 if (OverrideMainBuffer) {
Jonathan D. Turner9461fcc2011-07-22 17:25:03 +0000978 std::string ModName = PreambleFile;
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000979 TranslateStoredDiagnostics(Clang->getModuleManager(), ModName,
980 getSourceManager(), PreambleDiagnostics,
981 StoredDiagnostics);
982 }
983
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000984 Act->Execute();
Douglas Gregorabc563f2010-07-19 21:46:24 +0000985
Ted Kremenek4f327862011-03-21 18:40:17 +0000986 // Steal the created target, context, and preprocessor.
Ted Kremenek03201fb2011-03-21 18:40:07 +0000987 TheSema.reset(Clang->takeSema());
988 Consumer.reset(Clang->takeASTConsumer());
Ted Kremenek4f327862011-03-21 18:40:17 +0000989 Ctx = &Clang->getASTContext();
990 PP = &Clang->getPreprocessor();
991 Clang->setSourceManager(0);
992 Clang->setFileManager(0);
993 Target = &Clang->getTarget();
Douglas Gregorabc563f2010-07-19 21:46:24 +0000994
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000995 Act->EndSourceFile();
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000996
997 // Remove the overridden buffer we used for the preamble.
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000998 if (OverrideMainBuffer) {
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000999 PreprocessorOpts.eraseRemappedFile(
1000 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001001 PreprocessorOpts.ImplicitPCHInclude = PriorImplicitPCHInclude;
1002 }
1003
Douglas Gregorabc563f2010-07-19 21:46:24 +00001004 return false;
Ted Kremenek4f327862011-03-21 18:40:17 +00001005
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001006error:
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001007 // Remove the overridden buffer we used for the preamble.
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001008 if (OverrideMainBuffer) {
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001009 PreprocessorOpts.eraseRemappedFile(
1010 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001011 PreprocessorOpts.ImplicitPCHInclude = PriorImplicitPCHInclude;
Douglas Gregor671947b2010-08-19 01:33:06 +00001012 delete OverrideMainBuffer;
Douglas Gregor37cf6632010-10-06 21:11:08 +00001013 SavedMainFileBuffer = 0;
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001014 }
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001015
Douglas Gregord54eb442010-10-12 16:25:54 +00001016 StoredDiagnostics.clear();
Douglas Gregorabc563f2010-07-19 21:46:24 +00001017 return true;
1018}
1019
Douglas Gregor44c181a2010-07-23 00:33:23 +00001020/// \brief Simple function to retrieve a path for a preamble precompiled header.
1021static std::string GetPreamblePCHPath() {
1022 // FIXME: This is lame; sys::Path should provide this function (in particular,
1023 // it should know how to find the temporary files dir).
1024 // FIXME: This is really lame. I copied this code from the Driver!
Douglas Gregor424668c2010-09-11 18:05:19 +00001025 // FIXME: This is a hack so that we can override the preamble file during
1026 // crash-recovery testing, which is the only case where the preamble files
1027 // are not necessarily cleaned up.
1028 const char *TmpFile = ::getenv("CINDEXTEST_PREAMBLE_FILE");
1029 if (TmpFile)
1030 return TmpFile;
1031
Douglas Gregor44c181a2010-07-23 00:33:23 +00001032 std::string Error;
1033 const char *TmpDir = ::getenv("TMPDIR");
1034 if (!TmpDir)
1035 TmpDir = ::getenv("TEMP");
1036 if (!TmpDir)
1037 TmpDir = ::getenv("TMP");
Douglas Gregorc6cb2b02010-09-11 17:51:16 +00001038#ifdef LLVM_ON_WIN32
1039 if (!TmpDir)
1040 TmpDir = ::getenv("USERPROFILE");
1041#endif
Douglas Gregor44c181a2010-07-23 00:33:23 +00001042 if (!TmpDir)
1043 TmpDir = "/tmp";
1044 llvm::sys::Path P(TmpDir);
Douglas Gregorc6cb2b02010-09-11 17:51:16 +00001045 P.createDirectoryOnDisk(true);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001046 P.appendComponent("preamble");
Douglas Gregor6bf18302010-08-11 13:06:56 +00001047 P.appendSuffix("pch");
Argyrios Kyrtzidisbc9d5a32011-07-21 18:44:46 +00001048 if (P.makeUnique(/*reuse_current=*/false, /*ErrMsg*/0))
Douglas Gregor44c181a2010-07-23 00:33:23 +00001049 return std::string();
1050
Douglas Gregor44c181a2010-07-23 00:33:23 +00001051 return P.str();
1052}
1053
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001054/// \brief Compute the preamble for the main file, providing the source buffer
1055/// that corresponds to the main file along with a pair (bytes, start-of-line)
1056/// that describes the preamble.
1057std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> >
Douglas Gregordf95a132010-08-09 20:45:32 +00001058ASTUnit::ComputePreamble(CompilerInvocation &Invocation,
1059 unsigned MaxLines, bool &CreatedBuffer) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001060 FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
Chris Lattner39b49bc2010-11-23 08:35:12 +00001061 PreprocessorOptions &PreprocessorOpts = Invocation.getPreprocessorOpts();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001062 CreatedBuffer = false;
1063
Douglas Gregor44c181a2010-07-23 00:33:23 +00001064 // Try to determine if the main file has been remapped, either from the
1065 // command line (to another file) or directly through the compiler invocation
1066 // (to a memory buffer).
Douglas Gregor175c4a92010-07-23 23:58:40 +00001067 llvm::MemoryBuffer *Buffer = 0;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001068 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].second);
1069 if (const llvm::sys::FileStatus *MainFileStatus = MainFilePath.getFileStatus()) {
1070 // Check whether there is a file-file remapping of the main file
1071 for (PreprocessorOptions::remapped_file_iterator
Douglas Gregor175c4a92010-07-23 23:58:40 +00001072 M = PreprocessorOpts.remapped_file_begin(),
1073 E = PreprocessorOpts.remapped_file_end();
Douglas Gregor44c181a2010-07-23 00:33:23 +00001074 M != E;
1075 ++M) {
1076 llvm::sys::PathWithStatus MPath(M->first);
1077 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
1078 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
1079 // We found a remapping. Try to load the resulting, remapped source.
Douglas Gregor175c4a92010-07-23 23:58:40 +00001080 if (CreatedBuffer) {
Douglas Gregor44c181a2010-07-23 00:33:23 +00001081 delete Buffer;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001082 CreatedBuffer = false;
1083 }
1084
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00001085 Buffer = getBufferForFile(M->second);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001086 if (!Buffer)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001087 return std::make_pair((llvm::MemoryBuffer*)0,
1088 std::make_pair(0, true));
Douglas Gregor175c4a92010-07-23 23:58:40 +00001089 CreatedBuffer = true;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001090 }
1091 }
1092 }
1093
1094 // Check whether there is a file-buffer remapping. It supercedes the
1095 // file-file remapping.
1096 for (PreprocessorOptions::remapped_file_buffer_iterator
1097 M = PreprocessorOpts.remapped_file_buffer_begin(),
1098 E = PreprocessorOpts.remapped_file_buffer_end();
1099 M != E;
1100 ++M) {
1101 llvm::sys::PathWithStatus MPath(M->first);
1102 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
1103 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
1104 // We found a remapping.
Douglas Gregor175c4a92010-07-23 23:58:40 +00001105 if (CreatedBuffer) {
Douglas Gregor44c181a2010-07-23 00:33:23 +00001106 delete Buffer;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001107 CreatedBuffer = false;
1108 }
Douglas Gregor44c181a2010-07-23 00:33:23 +00001109
Douglas Gregor175c4a92010-07-23 23:58:40 +00001110 Buffer = const_cast<llvm::MemoryBuffer *>(M->second);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001111 }
1112 }
Douglas Gregor175c4a92010-07-23 23:58:40 +00001113 }
Douglas Gregor44c181a2010-07-23 00:33:23 +00001114 }
1115
1116 // If the main source file was not remapped, load it now.
1117 if (!Buffer) {
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00001118 Buffer = getBufferForFile(FrontendOpts.Inputs[0].second);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001119 if (!Buffer)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001120 return std::make_pair((llvm::MemoryBuffer*)0, std::make_pair(0, true));
Douglas Gregor175c4a92010-07-23 23:58:40 +00001121
1122 CreatedBuffer = true;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001123 }
1124
Douglas Gregordf95a132010-08-09 20:45:32 +00001125 return std::make_pair(Buffer, Lexer::ComputePreamble(Buffer, MaxLines));
Douglas Gregor175c4a92010-07-23 23:58:40 +00001126}
1127
Douglas Gregor754f3492010-07-24 00:38:13 +00001128static llvm::MemoryBuffer *CreatePaddedMainFileBuffer(llvm::MemoryBuffer *Old,
Douglas Gregor754f3492010-07-24 00:38:13 +00001129 unsigned NewSize,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001130 StringRef NewName) {
Douglas Gregor754f3492010-07-24 00:38:13 +00001131 llvm::MemoryBuffer *Result
1132 = llvm::MemoryBuffer::getNewUninitMemBuffer(NewSize, NewName);
1133 memcpy(const_cast<char*>(Result->getBufferStart()),
1134 Old->getBufferStart(), Old->getBufferSize());
1135 memset(const_cast<char*>(Result->getBufferStart()) + Old->getBufferSize(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001136 ' ', NewSize - Old->getBufferSize() - 1);
1137 const_cast<char*>(Result->getBufferEnd())[-1] = '\n';
Douglas Gregor754f3492010-07-24 00:38:13 +00001138
Douglas Gregor754f3492010-07-24 00:38:13 +00001139 return Result;
1140}
1141
Douglas Gregor175c4a92010-07-23 23:58:40 +00001142/// \brief Attempt to build or re-use a precompiled preamble when (re-)parsing
1143/// the source file.
1144///
1145/// This routine will compute the preamble of the main source file. If a
1146/// non-trivial preamble is found, it will precompile that preamble into a
1147/// precompiled header so that the precompiled preamble can be used to reduce
1148/// reparsing time. If a precompiled preamble has already been constructed,
1149/// this routine will determine if it is still valid and, if so, avoid
1150/// rebuilding the precompiled preamble.
1151///
Douglas Gregordf95a132010-08-09 20:45:32 +00001152/// \param AllowRebuild When true (the default), this routine is
1153/// allowed to rebuild the precompiled preamble if it is found to be
1154/// out-of-date.
1155///
1156/// \param MaxLines When non-zero, the maximum number of lines that
1157/// can occur within the preamble.
1158///
Douglas Gregor754f3492010-07-24 00:38:13 +00001159/// \returns If the precompiled preamble can be used, returns a newly-allocated
1160/// buffer that should be used in place of the main file when doing so.
1161/// Otherwise, returns a NULL pointer.
Douglas Gregordf95a132010-08-09 20:45:32 +00001162llvm::MemoryBuffer *ASTUnit::getMainBufferWithPrecompiledPreamble(
Douglas Gregor01b6e312011-07-01 18:22:13 +00001163 const CompilerInvocation &PreambleInvocationIn,
Douglas Gregordf95a132010-08-09 20:45:32 +00001164 bool AllowRebuild,
1165 unsigned MaxLines) {
Douglas Gregor01b6e312011-07-01 18:22:13 +00001166
1167 llvm::IntrusiveRefCntPtr<CompilerInvocation>
1168 PreambleInvocation(new CompilerInvocation(PreambleInvocationIn));
1169 FrontendOptions &FrontendOpts = PreambleInvocation->getFrontendOpts();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001170 PreprocessorOptions &PreprocessorOpts
Douglas Gregor01b6e312011-07-01 18:22:13 +00001171 = PreambleInvocation->getPreprocessorOpts();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001172
1173 bool CreatedPreambleBuffer = false;
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001174 std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> > NewPreamble
Douglas Gregor01b6e312011-07-01 18:22:13 +00001175 = ComputePreamble(*PreambleInvocation, MaxLines, CreatedPreambleBuffer);
Douglas Gregor175c4a92010-07-23 23:58:40 +00001176
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001177 // If ComputePreamble() Take ownership of the preamble buffer.
Douglas Gregor73fc9122010-11-16 20:45:51 +00001178 llvm::OwningPtr<llvm::MemoryBuffer> OwnedPreambleBuffer;
1179 if (CreatedPreambleBuffer)
1180 OwnedPreambleBuffer.reset(NewPreamble.first);
1181
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001182 if (!NewPreamble.second.first) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001183 // We couldn't find a preamble in the main source. Clear out the current
1184 // preamble, if we have one. It's obviously no good any more.
1185 Preamble.clear();
1186 if (!PreambleFile.empty()) {
Douglas Gregor385103b2010-07-30 20:58:08 +00001187 llvm::sys::Path(PreambleFile).eraseFromDisk();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001188 PreambleFile.clear();
1189 }
Douglas Gregoreababfb2010-08-04 05:53:38 +00001190
1191 // The next time we actually see a preamble, precompile it.
1192 PreambleRebuildCounter = 1;
Douglas Gregor754f3492010-07-24 00:38:13 +00001193 return 0;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001194 }
1195
1196 if (!Preamble.empty()) {
1197 // We've previously computed a preamble. Check whether we have the same
1198 // preamble now that we did before, and that there's enough space in
1199 // the main-file buffer within the precompiled preamble to fit the
1200 // new main file.
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001201 if (Preamble.size() == NewPreamble.second.first &&
1202 PreambleEndsAtStartOfLine == NewPreamble.second.second &&
Douglas Gregor592508e2010-07-24 00:42:07 +00001203 NewPreamble.first->getBufferSize() < PreambleReservedSize-2 &&
Douglas Gregor175c4a92010-07-23 23:58:40 +00001204 memcmp(&Preamble[0], NewPreamble.first->getBufferStart(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001205 NewPreamble.second.first) == 0) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001206 // The preamble has not changed. We may be able to re-use the precompiled
1207 // preamble.
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001208
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001209 // Check that none of the files used by the preamble have changed.
1210 bool AnyFileChanged = false;
1211
1212 // First, make a record of those files that have been overridden via
1213 // remapping or unsaved_files.
1214 llvm::StringMap<std::pair<off_t, time_t> > OverriddenFiles;
1215 for (PreprocessorOptions::remapped_file_iterator
1216 R = PreprocessorOpts.remapped_file_begin(),
1217 REnd = PreprocessorOpts.remapped_file_end();
1218 !AnyFileChanged && R != REnd;
1219 ++R) {
1220 struct stat StatBuf;
Anders Carlsson340415c2011-03-18 19:23:38 +00001221 if (FileMgr->getNoncachedStatValue(R->second, StatBuf)) {
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001222 // If we can't stat the file we're remapping to, assume that something
1223 // horrible happened.
1224 AnyFileChanged = true;
1225 break;
1226 }
Douglas Gregor754f3492010-07-24 00:38:13 +00001227
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001228 OverriddenFiles[R->first] = std::make_pair(StatBuf.st_size,
1229 StatBuf.st_mtime);
1230 }
1231 for (PreprocessorOptions::remapped_file_buffer_iterator
1232 R = PreprocessorOpts.remapped_file_buffer_begin(),
1233 REnd = PreprocessorOpts.remapped_file_buffer_end();
1234 !AnyFileChanged && R != REnd;
1235 ++R) {
1236 // FIXME: Should we actually compare the contents of file->buffer
1237 // remappings?
1238 OverriddenFiles[R->first] = std::make_pair(R->second->getBufferSize(),
1239 0);
1240 }
1241
1242 // Check whether anything has changed.
1243 for (llvm::StringMap<std::pair<off_t, time_t> >::iterator
1244 F = FilesInPreamble.begin(), FEnd = FilesInPreamble.end();
1245 !AnyFileChanged && F != FEnd;
1246 ++F) {
1247 llvm::StringMap<std::pair<off_t, time_t> >::iterator Overridden
1248 = OverriddenFiles.find(F->first());
1249 if (Overridden != OverriddenFiles.end()) {
1250 // This file was remapped; check whether the newly-mapped file
1251 // matches up with the previous mapping.
1252 if (Overridden->second != F->second)
1253 AnyFileChanged = true;
1254 continue;
1255 }
1256
1257 // The file was not remapped; check whether it has changed on disk.
1258 struct stat StatBuf;
Anders Carlsson340415c2011-03-18 19:23:38 +00001259 if (FileMgr->getNoncachedStatValue(F->first(), StatBuf)) {
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001260 // If we can't stat the file, assume that something horrible happened.
1261 AnyFileChanged = true;
1262 } else if (StatBuf.st_size != F->second.first ||
1263 StatBuf.st_mtime != F->second.second)
1264 AnyFileChanged = true;
1265 }
1266
1267 if (!AnyFileChanged) {
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001268 // Okay! We can re-use the precompiled preamble.
1269
1270 // Set the state of the diagnostic object to mimic its state
1271 // after parsing the preamble.
Douglas Gregor32be4a52010-10-11 21:37:58 +00001272 // FIXME: This won't catch any #pragma push warning changes that
1273 // have occurred in the preamble.
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001274 getDiagnostics().Reset();
Douglas Gregor32be4a52010-10-11 21:37:58 +00001275 ProcessWarningOptions(getDiagnostics(),
Douglas Gregor01b6e312011-07-01 18:22:13 +00001276 PreambleInvocation->getDiagnosticOpts());
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001277 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001278
1279 // Create a version of the main file buffer that is padded to
1280 // buffer size we reserved when creating the preamble.
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001281 return CreatePaddedMainFileBuffer(NewPreamble.first,
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001282 PreambleReservedSize,
1283 FrontendOpts.Inputs[0].second);
1284 }
Douglas Gregor175c4a92010-07-23 23:58:40 +00001285 }
Douglas Gregordf95a132010-08-09 20:45:32 +00001286
1287 // If we aren't allowed to rebuild the precompiled preamble, just
1288 // return now.
1289 if (!AllowRebuild)
1290 return 0;
Douglas Gregoraa3e6ba2010-10-08 04:03:57 +00001291
Douglas Gregor175c4a92010-07-23 23:58:40 +00001292 // We can't reuse the previously-computed preamble. Build a new one.
1293 Preamble.clear();
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001294 PreambleDiagnostics.clear();
Douglas Gregor385103b2010-07-30 20:58:08 +00001295 llvm::sys::Path(PreambleFile).eraseFromDisk();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001296 PreambleRebuildCounter = 1;
Douglas Gregordf95a132010-08-09 20:45:32 +00001297 } else if (!AllowRebuild) {
1298 // We aren't allowed to rebuild the precompiled preamble; just
1299 // return now.
1300 return 0;
1301 }
Douglas Gregoreababfb2010-08-04 05:53:38 +00001302
1303 // If the preamble rebuild counter > 1, it's because we previously
1304 // failed to build a preamble and we're not yet ready to try
1305 // again. Decrement the counter and return a failure.
1306 if (PreambleRebuildCounter > 1) {
1307 --PreambleRebuildCounter;
1308 return 0;
1309 }
1310
Douglas Gregor2cd4fd42010-09-11 17:56:52 +00001311 // Create a temporary file for the precompiled preamble. In rare
1312 // circumstances, this can fail.
1313 std::string PreamblePCHPath = GetPreamblePCHPath();
1314 if (PreamblePCHPath.empty()) {
1315 // Try again next time.
1316 PreambleRebuildCounter = 1;
1317 return 0;
1318 }
1319
Douglas Gregor175c4a92010-07-23 23:58:40 +00001320 // We did not previously compute a preamble, or it can't be reused anyway.
Douglas Gregor213f18b2010-10-28 15:44:59 +00001321 SimpleTimer PreambleTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00001322 PreambleTimer.setOutput("Precompiling preamble");
Douglas Gregor44c181a2010-07-23 00:33:23 +00001323
1324 // Create a new buffer that stores the preamble. The buffer also contains
1325 // extra space for the original contents of the file (which will be present
1326 // when we actually parse the file) along with more room in case the file
Douglas Gregor175c4a92010-07-23 23:58:40 +00001327 // grows.
1328 PreambleReservedSize = NewPreamble.first->getBufferSize();
1329 if (PreambleReservedSize < 4096)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001330 PreambleReservedSize = 8191;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001331 else
Douglas Gregor175c4a92010-07-23 23:58:40 +00001332 PreambleReservedSize *= 2;
1333
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001334 // Save the preamble text for later; we'll need to compare against it for
1335 // subsequent reparses.
1336 Preamble.assign(NewPreamble.first->getBufferStart(),
1337 NewPreamble.first->getBufferStart()
1338 + NewPreamble.second.first);
1339 PreambleEndsAtStartOfLine = NewPreamble.second.second;
1340
Douglas Gregor671947b2010-08-19 01:33:06 +00001341 delete PreambleBuffer;
1342 PreambleBuffer
Douglas Gregor175c4a92010-07-23 23:58:40 +00001343 = llvm::MemoryBuffer::getNewUninitMemBuffer(PreambleReservedSize,
Douglas Gregor44c181a2010-07-23 00:33:23 +00001344 FrontendOpts.Inputs[0].second);
1345 memcpy(const_cast<char*>(PreambleBuffer->getBufferStart()),
Douglas Gregor175c4a92010-07-23 23:58:40 +00001346 NewPreamble.first->getBufferStart(), Preamble.size());
1347 memset(const_cast<char*>(PreambleBuffer->getBufferStart()) + Preamble.size(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001348 ' ', PreambleReservedSize - Preamble.size() - 1);
1349 const_cast<char*>(PreambleBuffer->getBufferEnd())[-1] = '\n';
Douglas Gregor44c181a2010-07-23 00:33:23 +00001350
1351 // Remap the main source file to the preamble buffer.
Douglas Gregor175c4a92010-07-23 23:58:40 +00001352 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].second);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001353 PreprocessorOpts.addRemappedFile(MainFilePath.str(), PreambleBuffer);
1354
1355 // Tell the compiler invocation to generate a temporary precompiled header.
1356 FrontendOpts.ProgramAction = frontend::GeneratePCH;
Douglas Gregor85e51912010-10-01 01:05:22 +00001357 FrontendOpts.ChainedPCH = true;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001358 // FIXME: Generate the precompiled header into memory?
Douglas Gregor2cd4fd42010-09-11 17:56:52 +00001359 FrontendOpts.OutputFile = PreamblePCHPath;
Douglas Gregoraa3e6ba2010-10-08 04:03:57 +00001360 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
1361 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001362
1363 // Create the compiler instance to use for building the precompiled preamble.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001364 llvm::OwningPtr<CompilerInstance> Clang(new CompilerInstance());
1365
1366 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00001367 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1368 CICleanup(Clang.get());
Ted Kremenek03201fb2011-03-21 18:40:07 +00001369
Douglas Gregor01b6e312011-07-01 18:22:13 +00001370 Clang->setInvocation(&*PreambleInvocation);
Ted Kremenek03201fb2011-03-21 18:40:07 +00001371 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].second;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001372
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001373 // Set up diagnostics, capturing all of the diagnostics produced.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001374 Clang->setDiagnostics(&getDiagnostics());
Douglas Gregor44c181a2010-07-23 00:33:23 +00001375
1376 // Create the target instance.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001377 Clang->getTargetOpts().Features = TargetFeatures;
1378 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
1379 Clang->getTargetOpts()));
1380 if (!Clang->hasTarget()) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001381 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1382 Preamble.clear();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001383 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor671947b2010-08-19 01:33:06 +00001384 PreprocessorOpts.eraseRemappedFile(
1385 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor754f3492010-07-24 00:38:13 +00001386 return 0;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001387 }
1388
1389 // Inform the target of the language options.
1390 //
1391 // FIXME: We shouldn't need to do this, the target should be immutable once
1392 // created. This complexity should be lifted elsewhere.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001393 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregor44c181a2010-07-23 00:33:23 +00001394
Ted Kremenek03201fb2011-03-21 18:40:07 +00001395 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Douglas Gregor44c181a2010-07-23 00:33:23 +00001396 "Invocation must have exactly one source file!");
Ted Kremenek03201fb2011-03-21 18:40:07 +00001397 assert(Clang->getFrontendOpts().Inputs[0].first != IK_AST &&
Douglas Gregor44c181a2010-07-23 00:33:23 +00001398 "FIXME: AST inputs not yet supported here!");
Ted Kremenek03201fb2011-03-21 18:40:07 +00001399 assert(Clang->getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
Douglas Gregor44c181a2010-07-23 00:33:23 +00001400 "IR inputs not support here!");
1401
1402 // Clear out old caches and data.
Douglas Gregoraa3e6ba2010-10-08 04:03:57 +00001403 getDiagnostics().Reset();
Ted Kremenek03201fb2011-03-21 18:40:07 +00001404 ProcessWarningOptions(getDiagnostics(), Clang->getDiagnosticOpts());
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001405 StoredDiagnostics.erase(
1406 StoredDiagnostics.begin() + NumStoredDiagnosticsFromDriver,
1407 StoredDiagnostics.end());
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001408 TopLevelDecls.clear();
1409 TopLevelDeclsInPreamble.clear();
Douglas Gregor89d99802010-11-30 06:16:57 +00001410 PreprocessedEntities.clear();
1411 PreprocessedEntitiesInPreamble.clear();
Douglas Gregor44c181a2010-07-23 00:33:23 +00001412
1413 // Create a file manager object to provide access to and cache the filesystem.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001414 Clang->setFileManager(new FileManager(Clang->getFileSystemOpts()));
Douglas Gregor44c181a2010-07-23 00:33:23 +00001415
1416 // Create the source manager.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001417 Clang->setSourceManager(new SourceManager(getDiagnostics(),
Ted Kremenek4f327862011-03-21 18:40:17 +00001418 Clang->getFileManager()));
Douglas Gregor44c181a2010-07-23 00:33:23 +00001419
Douglas Gregor1d715ac2010-08-03 08:14:03 +00001420 llvm::OwningPtr<PrecompilePreambleAction> Act;
1421 Act.reset(new PrecompilePreambleAction(*this));
Ted Kremenek03201fb2011-03-21 18:40:07 +00001422 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0].second,
1423 Clang->getFrontendOpts().Inputs[0].first)) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001424 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1425 Preamble.clear();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001426 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor671947b2010-08-19 01:33:06 +00001427 PreprocessorOpts.eraseRemappedFile(
1428 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor754f3492010-07-24 00:38:13 +00001429 return 0;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001430 }
1431
1432 Act->Execute();
1433 Act->EndSourceFile();
Ted Kremenek4f327862011-03-21 18:40:17 +00001434
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001435 if (Diagnostics->hasErrorOccurred()) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001436 // There were errors parsing the preamble, so no precompiled header was
1437 // generated. Forget that we even tried.
Douglas Gregor06e50442010-09-27 16:43:25 +00001438 // FIXME: Should we leave a note for ourselves to try again?
Douglas Gregor175c4a92010-07-23 23:58:40 +00001439 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1440 Preamble.clear();
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001441 TopLevelDeclsInPreamble.clear();
Douglas Gregor89d99802010-11-30 06:16:57 +00001442 PreprocessedEntities.clear();
1443 PreprocessedEntitiesInPreamble.clear();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001444 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor671947b2010-08-19 01:33:06 +00001445 PreprocessorOpts.eraseRemappedFile(
1446 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor754f3492010-07-24 00:38:13 +00001447 return 0;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001448 }
1449
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001450 // Transfer any diagnostics generated when parsing the preamble into the set
1451 // of preamble diagnostics.
1452 PreambleDiagnostics.clear();
1453 PreambleDiagnostics.insert(PreambleDiagnostics.end(),
1454 StoredDiagnostics.begin() + NumStoredDiagnosticsFromDriver,
1455 StoredDiagnostics.end());
1456 StoredDiagnostics.erase(
1457 StoredDiagnostics.begin() + NumStoredDiagnosticsFromDriver,
1458 StoredDiagnostics.end());
1459
Douglas Gregor175c4a92010-07-23 23:58:40 +00001460 // Keep track of the preamble we precompiled.
1461 PreambleFile = FrontendOpts.OutputFile;
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001462 NumWarningsInPreamble = getDiagnostics().getNumWarnings();
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001463
1464 // Keep track of all of the files that the source manager knows about,
1465 // so we can verify whether they have changed or not.
1466 FilesInPreamble.clear();
Ted Kremenek03201fb2011-03-21 18:40:07 +00001467 SourceManager &SourceMgr = Clang->getSourceManager();
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001468 const llvm::MemoryBuffer *MainFileBuffer
1469 = SourceMgr.getBuffer(SourceMgr.getMainFileID());
1470 for (SourceManager::fileinfo_iterator F = SourceMgr.fileinfo_begin(),
1471 FEnd = SourceMgr.fileinfo_end();
1472 F != FEnd;
1473 ++F) {
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001474 const FileEntry *File = F->second->OrigEntry;
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001475 if (!File || F->second->getRawBuffer() == MainFileBuffer)
1476 continue;
1477
1478 FilesInPreamble[File->getName()]
1479 = std::make_pair(F->second->getSize(), File->getModificationTime());
1480 }
1481
Douglas Gregoreababfb2010-08-04 05:53:38 +00001482 PreambleRebuildCounter = 1;
Douglas Gregor671947b2010-08-19 01:33:06 +00001483 PreprocessorOpts.eraseRemappedFile(
1484 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor9b7db622011-02-16 18:16:54 +00001485
1486 // If the hash of top-level entities differs from the hash of the top-level
1487 // entities the last time we rebuilt the preamble, clear out the completion
1488 // cache.
1489 if (CurrentTopLevelHashValue != PreambleTopLevelHashValue) {
1490 CompletionCacheTopLevelHashValue = 0;
1491 PreambleTopLevelHashValue = CurrentTopLevelHashValue;
1492 }
1493
Douglas Gregor754f3492010-07-24 00:38:13 +00001494 return CreatePaddedMainFileBuffer(NewPreamble.first,
Douglas Gregor754f3492010-07-24 00:38:13 +00001495 PreambleReservedSize,
1496 FrontendOpts.Inputs[0].second);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001497}
Douglas Gregorabc563f2010-07-19 21:46:24 +00001498
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001499void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
1500 std::vector<Decl *> Resolved;
1501 Resolved.reserve(TopLevelDeclsInPreamble.size());
1502 ExternalASTSource &Source = *getASTContext().getExternalSource();
1503 for (unsigned I = 0, N = TopLevelDeclsInPreamble.size(); I != N; ++I) {
1504 // Resolve the declaration ID to an actual declaration, possibly
1505 // deserializing the declaration in the process.
1506 Decl *D = Source.GetExternalDecl(TopLevelDeclsInPreamble[I]);
1507 if (D)
1508 Resolved.push_back(D);
1509 }
1510 TopLevelDeclsInPreamble.clear();
1511 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1512}
1513
Douglas Gregor89d99802010-11-30 06:16:57 +00001514void ASTUnit::RealizePreprocessedEntitiesFromPreamble() {
1515 if (!PP)
1516 return;
1517
1518 PreprocessingRecord *PPRec = PP->getPreprocessingRecord();
1519 if (!PPRec)
1520 return;
1521
1522 ExternalPreprocessingRecordSource *External = PPRec->getExternalSource();
1523 if (!External)
1524 return;
1525
1526 for (unsigned I = 0, N = PreprocessedEntitiesInPreamble.size(); I != N; ++I) {
1527 if (PreprocessedEntity *PE
Douglas Gregor0a480292011-02-11 19:46:30 +00001528 = External->ReadPreprocessedEntityAtOffset(
1529 PreprocessedEntitiesInPreamble[I]))
Douglas Gregor89d99802010-11-30 06:16:57 +00001530 PreprocessedEntities.push_back(PE);
1531 }
1532
1533 if (PreprocessedEntities.empty())
1534 return;
1535
1536 PreprocessedEntities.insert(PreprocessedEntities.end(),
1537 PPRec->begin(true), PPRec->end(true));
1538}
1539
1540ASTUnit::pp_entity_iterator ASTUnit::pp_entity_begin() {
1541 if (!PreprocessedEntitiesInPreamble.empty() &&
1542 PreprocessedEntities.empty())
1543 RealizePreprocessedEntitiesFromPreamble();
1544
Douglas Gregor89d99802010-11-30 06:16:57 +00001545 return PreprocessedEntities.begin();
1546}
1547
1548ASTUnit::pp_entity_iterator ASTUnit::pp_entity_end() {
1549 if (!PreprocessedEntitiesInPreamble.empty() &&
1550 PreprocessedEntities.empty())
1551 RealizePreprocessedEntitiesFromPreamble();
Douglas Gregor4c30bb12011-07-21 00:47:40 +00001552
Douglas Gregor89d99802010-11-30 06:16:57 +00001553 return PreprocessedEntities.end();
1554}
1555
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001556unsigned ASTUnit::getMaxPCHLevel() const {
1557 if (!getOnlyLocalDecls())
1558 return Decl::MaxPCHLevel;
1559
Sebastian Redl1d9f1fe2010-10-05 16:15:19 +00001560 return 0;
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001561}
1562
Chris Lattner5f9e2722011-07-23 10:55:15 +00001563StringRef ASTUnit::getMainFileName() const {
Douglas Gregor213f18b2010-10-28 15:44:59 +00001564 return Invocation->getFrontendOpts().Inputs[0].second;
1565}
1566
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001567ASTUnit *ASTUnit::create(CompilerInvocation *CI,
1568 llvm::IntrusiveRefCntPtr<Diagnostic> Diags) {
1569 llvm::OwningPtr<ASTUnit> AST;
1570 AST.reset(new ASTUnit(false));
1571 ConfigureDiags(Diags, 0, 0, *AST, /*CaptureDiagnostics=*/false);
1572 AST->Diagnostics = Diags;
Ted Kremenek4f327862011-03-21 18:40:17 +00001573 AST->Invocation = CI;
Anders Carlsson0d8d7e62011-03-18 18:22:40 +00001574 AST->FileSystemOpts = CI->getFileSystemOpts();
Ted Kremenek4f327862011-03-21 18:40:17 +00001575 AST->FileMgr = new FileManager(AST->FileSystemOpts);
1576 AST->SourceMgr = new SourceManager(*Diags, *AST->FileMgr);
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001577
1578 return AST.take();
1579}
1580
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001581ASTUnit *ASTUnit::LoadFromCompilerInvocationAction(CompilerInvocation *CI,
1582 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
1583 ASTFrontendAction *Action) {
1584 assert(CI && "A CompilerInvocation is required");
1585
1586 // Create the AST unit.
1587 llvm::OwningPtr<ASTUnit> AST;
1588 AST.reset(new ASTUnit(false));
1589 ConfigureDiags(Diags, 0, 0, *AST, /*CaptureDiagnostics*/false);
1590 AST->Diagnostics = Diags;
1591 AST->OnlyLocalDecls = false;
1592 AST->CaptureDiagnostics = false;
1593 AST->CompleteTranslationUnit = Action ? Action->usesCompleteTranslationUnit()
1594 : true;
1595 AST->ShouldCacheCodeCompletionResults = false;
1596 AST->Invocation = CI;
1597
1598 // Recover resources if we crash before exiting this method.
1599 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1600 ASTUnitCleanup(AST.get());
1601 llvm::CrashRecoveryContextCleanupRegistrar<Diagnostic,
1602 llvm::CrashRecoveryContextReleaseRefCleanup<Diagnostic> >
1603 DiagCleanup(Diags.getPtr());
1604
1605 // We'll manage file buffers ourselves.
1606 CI->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1607 CI->getFrontendOpts().DisableFree = false;
1608 ProcessWarningOptions(AST->getDiagnostics(), CI->getDiagnosticOpts());
1609
1610 // Save the target features.
1611 AST->TargetFeatures = CI->getTargetOpts().Features;
1612
1613 // Create the compiler instance to use for building the AST.
1614 llvm::OwningPtr<CompilerInstance> Clang(new CompilerInstance());
1615
1616 // Recover resources if we crash before exiting this method.
1617 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1618 CICleanup(Clang.get());
1619
1620 Clang->setInvocation(CI);
1621 AST->OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].second;
1622
1623 // Set up diagnostics, capturing any diagnostics that would
1624 // otherwise be dropped.
1625 Clang->setDiagnostics(&AST->getDiagnostics());
1626
1627 // Create the target instance.
1628 Clang->getTargetOpts().Features = AST->TargetFeatures;
1629 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
1630 Clang->getTargetOpts()));
1631 if (!Clang->hasTarget())
1632 return 0;
1633
1634 // Inform the target of the language options.
1635 //
1636 // FIXME: We shouldn't need to do this, the target should be immutable once
1637 // created. This complexity should be lifted elsewhere.
1638 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
1639
1640 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1641 "Invocation must have exactly one source file!");
1642 assert(Clang->getFrontendOpts().Inputs[0].first != IK_AST &&
1643 "FIXME: AST inputs not yet supported here!");
1644 assert(Clang->getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
1645 "IR inputs not supported here!");
1646
1647 // Configure the various subsystems.
1648 AST->FileSystemOpts = Clang->getFileSystemOpts();
1649 AST->FileMgr = new FileManager(AST->FileSystemOpts);
1650 AST->SourceMgr = new SourceManager(AST->getDiagnostics(), *AST->FileMgr);
1651 AST->TheSema.reset();
1652 AST->Ctx = 0;
1653 AST->PP = 0;
1654
1655 // Create a file manager object to provide access to and cache the filesystem.
1656 Clang->setFileManager(&AST->getFileManager());
1657
1658 // Create the source manager.
1659 Clang->setSourceManager(&AST->getSourceManager());
1660
1661 ASTFrontendAction *Act = Action;
1662
1663 llvm::OwningPtr<TopLevelDeclTrackerAction> TrackerAct;
1664 if (!Act) {
1665 TrackerAct.reset(new TopLevelDeclTrackerAction(*AST));
1666 Act = TrackerAct.get();
1667 }
1668
1669 // Recover resources if we crash before exiting this method.
1670 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1671 ActCleanup(TrackerAct.get());
1672
1673 if (!Act->BeginSourceFile(*Clang.get(),
1674 Clang->getFrontendOpts().Inputs[0].second,
1675 Clang->getFrontendOpts().Inputs[0].first))
1676 return 0;
1677
1678 Act->Execute();
1679
1680 // Steal the created target, context, and preprocessor.
1681 AST->TheSema.reset(Clang->takeSema());
1682 AST->Consumer.reset(Clang->takeASTConsumer());
1683 AST->Ctx = &Clang->getASTContext();
1684 AST->PP = &Clang->getPreprocessor();
1685 Clang->setSourceManager(0);
1686 Clang->setFileManager(0);
1687 AST->Target = &Clang->getTarget();
1688
1689 Act->EndSourceFile();
1690
1691 return AST.take();
1692}
1693
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001694bool ASTUnit::LoadFromCompilerInvocation(bool PrecompilePreamble) {
1695 if (!Invocation)
1696 return true;
1697
1698 // We'll manage file buffers ourselves.
1699 Invocation->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1700 Invocation->getFrontendOpts().DisableFree = false;
Douglas Gregor0b53cf82011-01-19 01:02:47 +00001701 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001702
Douglas Gregor1aa27302011-01-27 18:02:58 +00001703 // Save the target features.
1704 TargetFeatures = Invocation->getTargetOpts().Features;
1705
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001706 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Douglas Gregor99ba2022010-10-27 17:24:53 +00001707 if (PrecompilePreamble) {
Douglas Gregor08bb4c62010-11-15 23:00:34 +00001708 PreambleRebuildCounter = 2;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001709 OverrideMainBuffer
1710 = getMainBufferWithPrecompiledPreamble(*Invocation);
1711 }
1712
Douglas Gregor213f18b2010-10-28 15:44:59 +00001713 SimpleTimer ParsingTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00001714 ParsingTimer.setOutput("Parsing " + getMainFileName());
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001715
Ted Kremenek25a11e12011-03-22 01:15:24 +00001716 // Recover resources if we crash before exiting this method.
1717 llvm::CrashRecoveryContextCleanupRegistrar<llvm::MemoryBuffer>
1718 MemBufferCleanup(OverrideMainBuffer);
1719
Douglas Gregor213f18b2010-10-28 15:44:59 +00001720 return Parse(OverrideMainBuffer);
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001721}
1722
Douglas Gregorabc563f2010-07-19 21:46:24 +00001723ASTUnit *ASTUnit::LoadFromCompilerInvocation(CompilerInvocation *CI,
1724 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
1725 bool OnlyLocalDecls,
Douglas Gregor44c181a2010-07-23 00:33:23 +00001726 bool CaptureDiagnostics,
Douglas Gregordf95a132010-08-09 20:45:32 +00001727 bool PrecompilePreamble,
Douglas Gregor87c08a52010-08-13 22:48:40 +00001728 bool CompleteTranslationUnit,
Douglas Gregordca8ee82011-05-06 16:33:08 +00001729 bool CacheCodeCompletionResults,
Chandler Carruthba7537f2011-07-14 09:02:10 +00001730 bool NestedMacroExpansions) {
Douglas Gregorabc563f2010-07-19 21:46:24 +00001731 // Create the AST unit.
1732 llvm::OwningPtr<ASTUnit> AST;
1733 AST.reset(new ASTUnit(false));
Douglas Gregor0b53cf82011-01-19 01:02:47 +00001734 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
Douglas Gregorabc563f2010-07-19 21:46:24 +00001735 AST->Diagnostics = Diags;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001736 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregore47be3e2010-11-11 00:39:14 +00001737 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregordf95a132010-08-09 20:45:32 +00001738 AST->CompleteTranslationUnit = CompleteTranslationUnit;
Douglas Gregor87c08a52010-08-13 22:48:40 +00001739 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Ted Kremenek4f327862011-03-21 18:40:17 +00001740 AST->Invocation = CI;
Chandler Carruthba7537f2011-07-14 09:02:10 +00001741 AST->NestedMacroExpansions = NestedMacroExpansions;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001742
Ted Kremenekb547eeb2011-03-18 02:06:56 +00001743 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00001744 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1745 ASTUnitCleanup(AST.get());
1746 llvm::CrashRecoveryContextCleanupRegistrar<Diagnostic,
1747 llvm::CrashRecoveryContextReleaseRefCleanup<Diagnostic> >
1748 DiagCleanup(Diags.getPtr());
Ted Kremenekb547eeb2011-03-18 02:06:56 +00001749
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001750 return AST->LoadFromCompilerInvocation(PrecompilePreamble)? 0 : AST.take();
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001751}
Daniel Dunbar7b556682009-12-02 03:23:45 +00001752
1753ASTUnit *ASTUnit::LoadFromCommandLine(const char **ArgBegin,
1754 const char **ArgEnd,
Douglas Gregor28019772010-04-05 23:52:57 +00001755 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001756 StringRef ResourceFilesPath,
Daniel Dunbar7b556682009-12-02 03:23:45 +00001757 bool OnlyLocalDecls,
Douglas Gregore47be3e2010-11-11 00:39:14 +00001758 bool CaptureDiagnostics,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001759 RemappedFile *RemappedFiles,
Douglas Gregora88084b2010-02-18 18:08:43 +00001760 unsigned NumRemappedFiles,
Argyrios Kyrtzidis299a4a92011-03-08 23:35:24 +00001761 bool RemappedFilesKeepOriginalName,
Douglas Gregordf95a132010-08-09 20:45:32 +00001762 bool PrecompilePreamble,
Douglas Gregor87c08a52010-08-13 22:48:40 +00001763 bool CompleteTranslationUnit,
Douglas Gregor99ba2022010-10-27 17:24:53 +00001764 bool CacheCodeCompletionResults,
1765 bool CXXPrecompilePreamble,
Douglas Gregordca8ee82011-05-06 16:33:08 +00001766 bool CXXChainedPCH,
Chandler Carruthba7537f2011-07-14 09:02:10 +00001767 bool NestedMacroExpansions) {
Douglas Gregor28019772010-04-05 23:52:57 +00001768 if (!Diags.getPtr()) {
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001769 // No diagnostics engine was provided, so create our own diagnostics object
1770 // with the default options.
1771 DiagnosticOptions DiagOpts;
Douglas Gregor0b53cf82011-01-19 01:02:47 +00001772 Diags = CompilerInstance::createDiagnostics(DiagOpts, ArgEnd - ArgBegin,
1773 ArgBegin);
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001774 }
Daniel Dunbar7b556682009-12-02 03:23:45 +00001775
Chris Lattner5f9e2722011-07-23 10:55:15 +00001776 SmallVector<StoredDiagnostic, 4> StoredDiagnostics;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001777
Ted Kremenek4f327862011-03-21 18:40:17 +00001778 llvm::IntrusiveRefCntPtr<CompilerInvocation> CI;
Douglas Gregore47be3e2010-11-11 00:39:14 +00001779
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001780 {
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001781
Douglas Gregore47be3e2010-11-11 00:39:14 +00001782 CaptureDroppedDiagnostics Capture(CaptureDiagnostics, *Diags,
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001783 StoredDiagnostics);
Daniel Dunbar3bd54cc2010-01-25 00:44:02 +00001784
Argyrios Kyrtzidis832316e2011-04-04 23:11:45 +00001785 CI = clang::createInvocationFromCommandLine(
Frits van Bommele9c02652011-07-18 12:00:32 +00001786 llvm::makeArrayRef(ArgBegin, ArgEnd),
1787 Diags);
Argyrios Kyrtzidis054e4f52011-04-04 21:38:51 +00001788 if (!CI)
Argyrios Kyrtzidis4e03c2b2011-03-07 22:45:01 +00001789 return 0;
Daniel Dunbar7b556682009-12-02 03:23:45 +00001790 }
Douglas Gregore47be3e2010-11-11 00:39:14 +00001791
Douglas Gregor4db64a42010-01-23 00:14:00 +00001792 // Override any files that need remapping
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001793 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
1794 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
1795 if (const llvm::MemoryBuffer *
1796 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
1797 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first, memBuf);
1798 } else {
1799 const char *fname = fileOrBuf.get<const char *>();
1800 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first, fname);
1801 }
1802 }
Argyrios Kyrtzidis299a4a92011-03-08 23:35:24 +00001803 CI->getPreprocessorOpts().RemappedFilesKeepOriginalName =
1804 RemappedFilesKeepOriginalName;
Douglas Gregor4db64a42010-01-23 00:14:00 +00001805
Daniel Dunbar8b9adfe2009-12-15 00:06:45 +00001806 // Override the resources path.
Daniel Dunbar807b0612010-01-30 21:47:16 +00001807 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
Daniel Dunbar7b556682009-12-02 03:23:45 +00001808
Douglas Gregor99ba2022010-10-27 17:24:53 +00001809 // Check whether we should precompile the preamble and/or use chained PCH.
1810 // FIXME: This is a temporary hack while we debug C++ chained PCH.
1811 if (CI->getLangOpts().CPlusPlus) {
1812 PrecompilePreamble = PrecompilePreamble && CXXPrecompilePreamble;
1813
1814 if (PrecompilePreamble && !CXXChainedPCH &&
1815 !CI->getPreprocessorOpts().ImplicitPCHInclude.empty())
1816 PrecompilePreamble = false;
1817 }
1818
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001819 // Create the AST unit.
1820 llvm::OwningPtr<ASTUnit> AST;
1821 AST.reset(new ASTUnit(false));
Douglas Gregor0b53cf82011-01-19 01:02:47 +00001822 ConfigureDiags(Diags, ArgBegin, ArgEnd, *AST, CaptureDiagnostics);
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001823 AST->Diagnostics = Diags;
Anders Carlsson0d8d7e62011-03-18 18:22:40 +00001824
1825 AST->FileSystemOpts = CI->getFileSystemOpts();
Ted Kremenek4f327862011-03-21 18:40:17 +00001826 AST->FileMgr = new FileManager(AST->FileSystemOpts);
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001827 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregore47be3e2010-11-11 00:39:14 +00001828 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001829 AST->CompleteTranslationUnit = CompleteTranslationUnit;
1830 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
1831 AST->NumStoredDiagnosticsFromDriver = StoredDiagnostics.size();
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001832 AST->StoredDiagnostics.swap(StoredDiagnostics);
Ted Kremenek4f327862011-03-21 18:40:17 +00001833 AST->Invocation = CI;
Chandler Carruthba7537f2011-07-14 09:02:10 +00001834 AST->NestedMacroExpansions = NestedMacroExpansions;
Ted Kremenekb547eeb2011-03-18 02:06:56 +00001835
1836 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00001837 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1838 ASTUnitCleanup(AST.get());
1839 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInvocation,
1840 llvm::CrashRecoveryContextReleaseRefCleanup<CompilerInvocation> >
1841 CICleanup(CI.getPtr());
1842 llvm::CrashRecoveryContextCleanupRegistrar<Diagnostic,
1843 llvm::CrashRecoveryContextReleaseRefCleanup<Diagnostic> >
1844 DiagCleanup(Diags.getPtr());
Ted Kremenekb547eeb2011-03-18 02:06:56 +00001845
Chris Lattner39b49bc2010-11-23 08:35:12 +00001846 return AST->LoadFromCompilerInvocation(PrecompilePreamble) ? 0 : AST.take();
Daniel Dunbar7b556682009-12-02 03:23:45 +00001847}
Douglas Gregorabc563f2010-07-19 21:46:24 +00001848
1849bool ASTUnit::Reparse(RemappedFile *RemappedFiles, unsigned NumRemappedFiles) {
Ted Kremenek4f327862011-03-21 18:40:17 +00001850 if (!Invocation)
Douglas Gregorabc563f2010-07-19 21:46:24 +00001851 return true;
1852
Douglas Gregor213f18b2010-10-28 15:44:59 +00001853 SimpleTimer ParsingTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00001854 ParsingTimer.setOutput("Reparsing " + getMainFileName());
Douglas Gregor213f18b2010-10-28 15:44:59 +00001855
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001856 // Remap files.
Douglas Gregorf128fed2010-08-20 00:02:33 +00001857 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
Douglas Gregor8ef6c8c2011-02-05 19:42:43 +00001858 PPOpts.DisableStatCache = true;
Douglas Gregorf128fed2010-08-20 00:02:33 +00001859 for (PreprocessorOptions::remapped_file_buffer_iterator
1860 R = PPOpts.remapped_file_buffer_begin(),
1861 REnd = PPOpts.remapped_file_buffer_end();
1862 R != REnd;
1863 ++R) {
1864 delete R->second;
1865 }
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001866 Invocation->getPreprocessorOpts().clearRemappedFiles();
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001867 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
1868 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
1869 if (const llvm::MemoryBuffer *
1870 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
1871 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
1872 memBuf);
1873 } else {
1874 const char *fname = fileOrBuf.get<const char *>();
1875 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
1876 fname);
1877 }
1878 }
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001879
Douglas Gregoreababfb2010-08-04 05:53:38 +00001880 // If we have a preamble file lying around, or if we might try to
1881 // build a precompiled preamble, do so now.
Douglas Gregor754f3492010-07-24 00:38:13 +00001882 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Douglas Gregoreababfb2010-08-04 05:53:38 +00001883 if (!PreambleFile.empty() || PreambleRebuildCounter > 0)
Douglas Gregor2283d792010-08-20 00:59:43 +00001884 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(*Invocation);
Douglas Gregor175c4a92010-07-23 23:58:40 +00001885
Douglas Gregorabc563f2010-07-19 21:46:24 +00001886 // Clear out the diagnostics state.
Douglas Gregor32be4a52010-10-11 21:37:58 +00001887 if (!OverrideMainBuffer) {
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001888 getDiagnostics().Reset();
Douglas Gregor32be4a52010-10-11 21:37:58 +00001889 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
1890 }
Douglas Gregorabc563f2010-07-19 21:46:24 +00001891
Douglas Gregor175c4a92010-07-23 23:58:40 +00001892 // Parse the sources
Douglas Gregor9b7db622011-02-16 18:16:54 +00001893 bool Result = Parse(OverrideMainBuffer);
1894
1895 // If we're caching global code-completion results, and the top-level
1896 // declarations have changed, clear out the code-completion cache.
1897 if (!Result && ShouldCacheCodeCompletionResults &&
1898 CurrentTopLevelHashValue != CompletionCacheTopLevelHashValue)
1899 CacheCodeCompletionResults();
1900
Douglas Gregor8fa0a802011-08-04 20:04:59 +00001901 // We now need to clear out the completion allocator for
1902 // clang_getCursorCompletionString; it'll be recreated if necessary.
1903 CursorCompletionAllocator = 0;
1904
Douglas Gregor175c4a92010-07-23 23:58:40 +00001905 return Result;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001906}
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001907
Douglas Gregor87c08a52010-08-13 22:48:40 +00001908//----------------------------------------------------------------------------//
1909// Code completion
1910//----------------------------------------------------------------------------//
1911
1912namespace {
1913 /// \brief Code completion consumer that combines the cached code-completion
1914 /// results from an ASTUnit with the code-completion results provided to it,
1915 /// then passes the result on to
1916 class AugmentedCodeCompleteConsumer : public CodeCompleteConsumer {
Douglas Gregor3da626b2011-07-07 16:03:39 +00001917 unsigned long long NormalContexts;
Douglas Gregor87c08a52010-08-13 22:48:40 +00001918 ASTUnit &AST;
1919 CodeCompleteConsumer &Next;
1920
1921 public:
1922 AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next,
Douglas Gregor8071e422010-08-15 06:18:01 +00001923 bool IncludeMacros, bool IncludeCodePatterns,
1924 bool IncludeGlobals)
1925 : CodeCompleteConsumer(IncludeMacros, IncludeCodePatterns, IncludeGlobals,
Douglas Gregor87c08a52010-08-13 22:48:40 +00001926 Next.isOutputBinary()), AST(AST), Next(Next)
1927 {
1928 // Compute the set of contexts in which we will look when we don't have
1929 // any information about the specific context.
1930 NormalContexts
Douglas Gregor3da626b2011-07-07 16:03:39 +00001931 = (1LL << (CodeCompletionContext::CCC_TopLevel - 1))
1932 | (1LL << (CodeCompletionContext::CCC_ObjCInterface - 1))
1933 | (1LL << (CodeCompletionContext::CCC_ObjCImplementation - 1))
1934 | (1LL << (CodeCompletionContext::CCC_ObjCIvarList - 1))
1935 | (1LL << (CodeCompletionContext::CCC_Statement - 1))
1936 | (1LL << (CodeCompletionContext::CCC_Expression - 1))
1937 | (1LL << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
1938 | (1LL << (CodeCompletionContext::CCC_DotMemberAccess - 1))
1939 | (1LL << (CodeCompletionContext::CCC_ArrowMemberAccess - 1))
1940 | (1LL << (CodeCompletionContext::CCC_ObjCPropertyAccess - 1))
1941 | (1LL << (CodeCompletionContext::CCC_ObjCProtocolName - 1))
1942 | (1LL << (CodeCompletionContext::CCC_ParenthesizedExpression - 1))
1943 | (1LL << (CodeCompletionContext::CCC_Recovery - 1));
Douglas Gregor02688102010-09-14 23:59:36 +00001944
Douglas Gregor87c08a52010-08-13 22:48:40 +00001945 if (AST.getASTContext().getLangOptions().CPlusPlus)
Douglas Gregor3da626b2011-07-07 16:03:39 +00001946 NormalContexts |= (1LL << (CodeCompletionContext::CCC_EnumTag - 1))
1947 | (1LL << (CodeCompletionContext::CCC_UnionTag - 1))
1948 | (1LL << (CodeCompletionContext::CCC_ClassOrStructTag - 1));
Douglas Gregor87c08a52010-08-13 22:48:40 +00001949 }
1950
1951 virtual void ProcessCodeCompleteResults(Sema &S,
1952 CodeCompletionContext Context,
John McCall0a2c5e22010-08-25 06:19:51 +00001953 CodeCompletionResult *Results,
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001954 unsigned NumResults);
Douglas Gregor87c08a52010-08-13 22:48:40 +00001955
1956 virtual void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
1957 OverloadCandidate *Candidates,
1958 unsigned NumCandidates) {
1959 Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates);
1960 }
Douglas Gregor218937c2011-02-01 19:23:04 +00001961
Douglas Gregordae68752011-02-01 22:57:45 +00001962 virtual CodeCompletionAllocator &getAllocator() {
Douglas Gregor218937c2011-02-01 19:23:04 +00001963 return Next.getAllocator();
1964 }
Douglas Gregor87c08a52010-08-13 22:48:40 +00001965 };
1966}
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001967
Douglas Gregor5f808c22010-08-16 21:18:39 +00001968/// \brief Helper function that computes which global names are hidden by the
1969/// local code-completion results.
Ted Kremenekc198f612010-11-07 06:11:36 +00001970static void CalculateHiddenNames(const CodeCompletionContext &Context,
1971 CodeCompletionResult *Results,
1972 unsigned NumResults,
1973 ASTContext &Ctx,
1974 llvm::StringSet<llvm::BumpPtrAllocator> &HiddenNames){
Douglas Gregor5f808c22010-08-16 21:18:39 +00001975 bool OnlyTagNames = false;
1976 switch (Context.getKind()) {
Douglas Gregor52779fb2010-09-23 23:01:17 +00001977 case CodeCompletionContext::CCC_Recovery:
Douglas Gregor5f808c22010-08-16 21:18:39 +00001978 case CodeCompletionContext::CCC_TopLevel:
1979 case CodeCompletionContext::CCC_ObjCInterface:
1980 case CodeCompletionContext::CCC_ObjCImplementation:
1981 case CodeCompletionContext::CCC_ObjCIvarList:
1982 case CodeCompletionContext::CCC_ClassStructUnion:
1983 case CodeCompletionContext::CCC_Statement:
1984 case CodeCompletionContext::CCC_Expression:
1985 case CodeCompletionContext::CCC_ObjCMessageReceiver:
Douglas Gregor3da626b2011-07-07 16:03:39 +00001986 case CodeCompletionContext::CCC_DotMemberAccess:
1987 case CodeCompletionContext::CCC_ArrowMemberAccess:
1988 case CodeCompletionContext::CCC_ObjCPropertyAccess:
Douglas Gregor5f808c22010-08-16 21:18:39 +00001989 case CodeCompletionContext::CCC_Namespace:
1990 case CodeCompletionContext::CCC_Type:
Douglas Gregor2ccccb32010-08-23 18:23:48 +00001991 case CodeCompletionContext::CCC_Name:
1992 case CodeCompletionContext::CCC_PotentiallyQualifiedName:
Douglas Gregor02688102010-09-14 23:59:36 +00001993 case CodeCompletionContext::CCC_ParenthesizedExpression:
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00001994 case CodeCompletionContext::CCC_ObjCInterfaceName:
Douglas Gregor5f808c22010-08-16 21:18:39 +00001995 break;
1996
1997 case CodeCompletionContext::CCC_EnumTag:
1998 case CodeCompletionContext::CCC_UnionTag:
1999 case CodeCompletionContext::CCC_ClassOrStructTag:
2000 OnlyTagNames = true;
2001 break;
2002
2003 case CodeCompletionContext::CCC_ObjCProtocolName:
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002004 case CodeCompletionContext::CCC_MacroName:
2005 case CodeCompletionContext::CCC_MacroNameUse:
Douglas Gregorf29c5232010-08-24 22:20:20 +00002006 case CodeCompletionContext::CCC_PreprocessorExpression:
Douglas Gregor721f3592010-08-25 18:41:16 +00002007 case CodeCompletionContext::CCC_PreprocessorDirective:
Douglas Gregor59a66942010-08-25 18:04:30 +00002008 case CodeCompletionContext::CCC_NaturalLanguage:
Douglas Gregor458433d2010-08-26 15:07:07 +00002009 case CodeCompletionContext::CCC_SelectorName:
Douglas Gregor1a480c42010-08-27 17:35:51 +00002010 case CodeCompletionContext::CCC_TypeQualifiers:
Douglas Gregor52779fb2010-09-23 23:01:17 +00002011 case CodeCompletionContext::CCC_Other:
Douglas Gregor5c722c702011-02-18 23:30:37 +00002012 case CodeCompletionContext::CCC_OtherWithMacros:
Douglas Gregor3da626b2011-07-07 16:03:39 +00002013 case CodeCompletionContext::CCC_ObjCInstanceMessage:
2014 case CodeCompletionContext::CCC_ObjCClassMessage:
2015 case CodeCompletionContext::CCC_ObjCCategoryName:
Douglas Gregor721f3592010-08-25 18:41:16 +00002016 // We're looking for nothing, or we're looking for names that cannot
2017 // be hidden.
Douglas Gregor5f808c22010-08-16 21:18:39 +00002018 return;
2019 }
2020
John McCall0a2c5e22010-08-25 06:19:51 +00002021 typedef CodeCompletionResult Result;
Douglas Gregor5f808c22010-08-16 21:18:39 +00002022 for (unsigned I = 0; I != NumResults; ++I) {
2023 if (Results[I].Kind != Result::RK_Declaration)
2024 continue;
2025
2026 unsigned IDNS
2027 = Results[I].Declaration->getUnderlyingDecl()->getIdentifierNamespace();
2028
2029 bool Hiding = false;
2030 if (OnlyTagNames)
2031 Hiding = (IDNS & Decl::IDNS_Tag);
2032 else {
2033 unsigned HiddenIDNS = (Decl::IDNS_Type | Decl::IDNS_Member |
Douglas Gregora5fb7c32010-08-16 23:05:20 +00002034 Decl::IDNS_Namespace | Decl::IDNS_Ordinary |
2035 Decl::IDNS_NonMemberOperator);
Douglas Gregor5f808c22010-08-16 21:18:39 +00002036 if (Ctx.getLangOptions().CPlusPlus)
2037 HiddenIDNS |= Decl::IDNS_Tag;
2038 Hiding = (IDNS & HiddenIDNS);
2039 }
2040
2041 if (!Hiding)
2042 continue;
2043
2044 DeclarationName Name = Results[I].Declaration->getDeclName();
2045 if (IdentifierInfo *Identifier = Name.getAsIdentifierInfo())
2046 HiddenNames.insert(Identifier->getName());
2047 else
2048 HiddenNames.insert(Name.getAsString());
2049 }
2050}
2051
2052
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002053void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &S,
2054 CodeCompletionContext Context,
John McCall0a2c5e22010-08-25 06:19:51 +00002055 CodeCompletionResult *Results,
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002056 unsigned NumResults) {
2057 // Merge the results we were given with the results we cached.
2058 bool AddedResult = false;
Douglas Gregor5f808c22010-08-16 21:18:39 +00002059 unsigned InContexts
Douglas Gregor52779fb2010-09-23 23:01:17 +00002060 = (Context.getKind() == CodeCompletionContext::CCC_Recovery? NormalContexts
NAKAMURA Takumi01a429a2011-08-17 01:46:16 +00002061 : (1ULL << (Context.getKind() - 1)));
Douglas Gregor5f808c22010-08-16 21:18:39 +00002062 // Contains the set of names that are hidden by "local" completion results.
Ted Kremenekc198f612010-11-07 06:11:36 +00002063 llvm::StringSet<llvm::BumpPtrAllocator> HiddenNames;
John McCall0a2c5e22010-08-25 06:19:51 +00002064 typedef CodeCompletionResult Result;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002065 SmallVector<Result, 8> AllResults;
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002066 for (ASTUnit::cached_completion_iterator
Douglas Gregor5535d572010-08-16 21:23:13 +00002067 C = AST.cached_completion_begin(),
2068 CEnd = AST.cached_completion_end();
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002069 C != CEnd; ++C) {
2070 // If the context we are in matches any of the contexts we are
2071 // interested in, we'll add this result.
2072 if ((C->ShowInContexts & InContexts) == 0)
2073 continue;
2074
2075 // If we haven't added any results previously, do so now.
2076 if (!AddedResult) {
Douglas Gregor5f808c22010-08-16 21:18:39 +00002077 CalculateHiddenNames(Context, Results, NumResults, S.Context,
2078 HiddenNames);
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002079 AllResults.insert(AllResults.end(), Results, Results + NumResults);
2080 AddedResult = true;
2081 }
2082
Douglas Gregor5f808c22010-08-16 21:18:39 +00002083 // Determine whether this global completion result is hidden by a local
2084 // completion result. If so, skip it.
2085 if (C->Kind != CXCursor_MacroDefinition &&
2086 HiddenNames.count(C->Completion->getTypedText()))
2087 continue;
2088
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002089 // Adjust priority based on similar type classes.
2090 unsigned Priority = C->Priority;
Douglas Gregor4125c372010-08-25 18:03:13 +00002091 CXCursorKind CursorKind = C->Kind;
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002092 CodeCompletionString *Completion = C->Completion;
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002093 if (!Context.getPreferredType().isNull()) {
2094 if (C->Kind == CXCursor_MacroDefinition) {
2095 Priority = getMacroUsagePriority(C->Completion->getTypedText(),
Douglas Gregorb05496d2010-09-20 21:11:48 +00002096 S.getLangOptions(),
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002097 Context.getPreferredType()->isAnyPointerType());
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002098 } else if (C->Type) {
2099 CanQualType Expected
Douglas Gregor5535d572010-08-16 21:23:13 +00002100 = S.Context.getCanonicalType(
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002101 Context.getPreferredType().getUnqualifiedType());
2102 SimplifiedTypeClass ExpectedSTC = getSimplifiedTypeClass(Expected);
2103 if (ExpectedSTC == C->TypeClass) {
2104 // We know this type is similar; check for an exact match.
2105 llvm::StringMap<unsigned> &CachedCompletionTypes
Douglas Gregor5535d572010-08-16 21:23:13 +00002106 = AST.getCachedCompletionTypes();
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002107 llvm::StringMap<unsigned>::iterator Pos
Douglas Gregor5535d572010-08-16 21:23:13 +00002108 = CachedCompletionTypes.find(QualType(Expected).getAsString());
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002109 if (Pos != CachedCompletionTypes.end() && Pos->second == C->Type)
2110 Priority /= CCF_ExactTypeMatch;
2111 else
2112 Priority /= CCF_SimilarTypeMatch;
2113 }
2114 }
2115 }
2116
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002117 // Adjust the completion string, if required.
2118 if (C->Kind == CXCursor_MacroDefinition &&
2119 Context.getKind() == CodeCompletionContext::CCC_MacroNameUse) {
2120 // Create a new code-completion string that just contains the
2121 // macro name, without its arguments.
Douglas Gregor218937c2011-02-01 19:23:04 +00002122 CodeCompletionBuilder Builder(getAllocator(), CCP_CodePattern,
2123 C->Availability);
2124 Builder.AddTypedTextChunk(C->Completion->getTypedText());
Douglas Gregor4125c372010-08-25 18:03:13 +00002125 CursorKind = CXCursor_NotImplemented;
2126 Priority = CCP_CodePattern;
Douglas Gregor218937c2011-02-01 19:23:04 +00002127 Completion = Builder.TakeString();
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002128 }
2129
Douglas Gregor4125c372010-08-25 18:03:13 +00002130 AllResults.push_back(Result(Completion, Priority, CursorKind,
Douglas Gregor58ddb602010-08-23 23:00:57 +00002131 C->Availability));
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002132 }
2133
2134 // If we did not add any cached completion results, just forward the
2135 // results we were given to the next consumer.
2136 if (!AddedResult) {
2137 Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
2138 return;
2139 }
Douglas Gregor1e5e6682010-08-26 13:48:20 +00002140
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002141 Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
2142 AllResults.size());
2143}
2144
2145
2146
Chris Lattner5f9e2722011-07-23 10:55:15 +00002147void ASTUnit::CodeComplete(StringRef File, unsigned Line, unsigned Column,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002148 RemappedFile *RemappedFiles,
2149 unsigned NumRemappedFiles,
Douglas Gregorcee235c2010-08-05 09:09:23 +00002150 bool IncludeMacros,
2151 bool IncludeCodePatterns,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002152 CodeCompleteConsumer &Consumer,
2153 Diagnostic &Diag, LangOptions &LangOpts,
2154 SourceManager &SourceMgr, FileManager &FileMgr,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002155 SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
2156 SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers) {
Ted Kremenek4f327862011-03-21 18:40:17 +00002157 if (!Invocation)
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002158 return;
2159
Douglas Gregor213f18b2010-10-28 15:44:59 +00002160 SimpleTimer CompletionTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00002161 CompletionTimer.setOutput("Code completion @ " + File + ":" +
Chris Lattner5f9e2722011-07-23 10:55:15 +00002162 Twine(Line) + ":" + Twine(Column));
Douglas Gregordf95a132010-08-09 20:45:32 +00002163
Ted Kremenek4f327862011-03-21 18:40:17 +00002164 llvm::IntrusiveRefCntPtr<CompilerInvocation>
2165 CCInvocation(new CompilerInvocation(*Invocation));
2166
2167 FrontendOptions &FrontendOpts = CCInvocation->getFrontendOpts();
2168 PreprocessorOptions &PreprocessorOpts = CCInvocation->getPreprocessorOpts();
Douglas Gregorcee235c2010-08-05 09:09:23 +00002169
Douglas Gregor87c08a52010-08-13 22:48:40 +00002170 FrontendOpts.ShowMacrosInCodeCompletion
2171 = IncludeMacros && CachedCompletionResults.empty();
Douglas Gregorcee235c2010-08-05 09:09:23 +00002172 FrontendOpts.ShowCodePatternsInCodeCompletion = IncludeCodePatterns;
Douglas Gregor8071e422010-08-15 06:18:01 +00002173 FrontendOpts.ShowGlobalSymbolsInCodeCompletion
2174 = CachedCompletionResults.empty();
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002175 FrontendOpts.CodeCompletionAt.FileName = File;
2176 FrontendOpts.CodeCompletionAt.Line = Line;
2177 FrontendOpts.CodeCompletionAt.Column = Column;
2178
2179 // Set the language options appropriately.
Ted Kremenek4f327862011-03-21 18:40:17 +00002180 LangOpts = CCInvocation->getLangOpts();
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002181
Ted Kremenek03201fb2011-03-21 18:40:07 +00002182 llvm::OwningPtr<CompilerInstance> Clang(new CompilerInstance());
2183
2184 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00002185 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
2186 CICleanup(Clang.get());
Ted Kremenek03201fb2011-03-21 18:40:07 +00002187
Ted Kremenek4f327862011-03-21 18:40:17 +00002188 Clang->setInvocation(&*CCInvocation);
Ted Kremenek03201fb2011-03-21 18:40:07 +00002189 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].second;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002190
2191 // Set up diagnostics, capturing any diagnostics produced.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002192 Clang->setDiagnostics(&Diag);
Ted Kremenek4f327862011-03-21 18:40:17 +00002193 ProcessWarningOptions(Diag, CCInvocation->getDiagnosticOpts());
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002194 CaptureDroppedDiagnostics Capture(true,
Ted Kremenek03201fb2011-03-21 18:40:07 +00002195 Clang->getDiagnostics(),
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002196 StoredDiagnostics);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002197
2198 // Create the target instance.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002199 Clang->getTargetOpts().Features = TargetFeatures;
2200 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
2201 Clang->getTargetOpts()));
2202 if (!Clang->hasTarget()) {
Ted Kremenek4f327862011-03-21 18:40:17 +00002203 Clang->setInvocation(0);
Douglas Gregorbdbb0042010-08-18 22:29:43 +00002204 return;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002205 }
2206
2207 // Inform the target of the language options.
2208 //
2209 // FIXME: We shouldn't need to do this, the target should be immutable once
2210 // created. This complexity should be lifted elsewhere.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002211 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002212
Ted Kremenek03201fb2011-03-21 18:40:07 +00002213 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002214 "Invocation must have exactly one source file!");
Ted Kremenek03201fb2011-03-21 18:40:07 +00002215 assert(Clang->getFrontendOpts().Inputs[0].first != IK_AST &&
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002216 "FIXME: AST inputs not yet supported here!");
Ted Kremenek03201fb2011-03-21 18:40:07 +00002217 assert(Clang->getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002218 "IR inputs not support here!");
2219
2220
2221 // Use the source and file managers that we were given.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002222 Clang->setFileManager(&FileMgr);
2223 Clang->setSourceManager(&SourceMgr);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002224
2225 // Remap files.
2226 PreprocessorOpts.clearRemappedFiles();
Douglas Gregorb75d3df2010-08-04 17:07:00 +00002227 PreprocessorOpts.RetainRemappedFileBuffers = true;
Douglas Gregor2283d792010-08-20 00:59:43 +00002228 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00002229 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
2230 if (const llvm::MemoryBuffer *
2231 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
2232 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first, memBuf);
2233 OwnedBuffers.push_back(memBuf);
2234 } else {
2235 const char *fname = fileOrBuf.get<const char *>();
2236 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first, fname);
2237 }
Douglas Gregor2283d792010-08-20 00:59:43 +00002238 }
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002239
Douglas Gregor87c08a52010-08-13 22:48:40 +00002240 // Use the code completion consumer we were given, but adding any cached
2241 // code-completion results.
Douglas Gregor7f946ad2010-11-29 16:13:56 +00002242 AugmentedCodeCompleteConsumer *AugmentedConsumer
2243 = new AugmentedCodeCompleteConsumer(*this, Consumer,
2244 FrontendOpts.ShowMacrosInCodeCompletion,
2245 FrontendOpts.ShowCodePatternsInCodeCompletion,
2246 FrontendOpts.ShowGlobalSymbolsInCodeCompletion);
Ted Kremenek03201fb2011-03-21 18:40:07 +00002247 Clang->setCodeCompletionConsumer(AugmentedConsumer);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002248
Douglas Gregordf95a132010-08-09 20:45:32 +00002249 // If we have a precompiled preamble, try to use it. We only allow
2250 // the use of the precompiled preamble if we're if the completion
2251 // point is within the main file, after the end of the precompiled
2252 // preamble.
2253 llvm::MemoryBuffer *OverrideMainBuffer = 0;
2254 if (!PreambleFile.empty()) {
2255 using llvm::sys::FileStatus;
2256 llvm::sys::PathWithStatus CompleteFilePath(File);
2257 llvm::sys::PathWithStatus MainPath(OriginalSourceFile);
2258 if (const FileStatus *CompleteFileStatus = CompleteFilePath.getFileStatus())
2259 if (const FileStatus *MainStatus = MainPath.getFileStatus())
2260 if (CompleteFileStatus->getUniqueID() == MainStatus->getUniqueID())
Douglas Gregor2283d792010-08-20 00:59:43 +00002261 OverrideMainBuffer
Ted Kremenek4f327862011-03-21 18:40:17 +00002262 = getMainBufferWithPrecompiledPreamble(*CCInvocation, false,
Douglas Gregorc9c29a82010-08-25 18:04:15 +00002263 Line - 1);
Douglas Gregordf95a132010-08-09 20:45:32 +00002264 }
2265
2266 // If the main file has been overridden due to the use of a preamble,
2267 // make that override happen and introduce the preamble.
Douglas Gregor8ef6c8c2011-02-05 19:42:43 +00002268 PreprocessorOpts.DisableStatCache = true;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00002269 StoredDiagnostics.insert(StoredDiagnostics.end(),
2270 this->StoredDiagnostics.begin(),
2271 this->StoredDiagnostics.begin() + NumStoredDiagnosticsFromDriver);
Douglas Gregordf95a132010-08-09 20:45:32 +00002272 if (OverrideMainBuffer) {
2273 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
2274 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
2275 PreprocessorOpts.PrecompiledPreambleBytes.second
2276 = PreambleEndsAtStartOfLine;
2277 PreprocessorOpts.ImplicitPCHInclude = PreambleFile;
2278 PreprocessorOpts.DisablePCHValidation = true;
2279
Douglas Gregor2283d792010-08-20 00:59:43 +00002280 OwnedBuffers.push_back(OverrideMainBuffer);
Douglas Gregorf128fed2010-08-20 00:02:33 +00002281 } else {
2282 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
2283 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregordf95a132010-08-09 20:45:32 +00002284 }
2285
Douglas Gregordca8ee82011-05-06 16:33:08 +00002286 // Disable the preprocessing record
2287 PreprocessorOpts.DetailedRecord = false;
2288
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002289 llvm::OwningPtr<SyntaxOnlyAction> Act;
2290 Act.reset(new SyntaxOnlyAction);
Ted Kremenek03201fb2011-03-21 18:40:07 +00002291 if (Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0].second,
2292 Clang->getFrontendOpts().Inputs[0].first)) {
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002293 if (OverrideMainBuffer) {
Jonathan D. Turner9461fcc2011-07-22 17:25:03 +00002294 std::string ModName = PreambleFile;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002295 TranslateStoredDiagnostics(Clang->getModuleManager(), ModName,
2296 getSourceManager(), PreambleDiagnostics,
2297 StoredDiagnostics);
2298 }
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002299 Act->Execute();
2300 Act->EndSourceFile();
2301 }
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002302}
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002303
Chris Lattner5f9e2722011-07-23 10:55:15 +00002304CXSaveError ASTUnit::Save(StringRef File) {
Douglas Gregor85bea972011-07-06 17:40:26 +00002305 if (getDiagnostics().hasUnrecoverableErrorOccurred())
Douglas Gregor39c411f2011-07-06 16:43:36 +00002306 return CXSaveError_TranslationErrors;
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002307
2308 // Write to a temporary file and later rename it to the actual file, to avoid
2309 // possible race conditions.
Argyrios Kyrtzidis7e909852011-07-28 00:45:10 +00002310 llvm::SmallString<128> TempPath;
2311 TempPath = File;
2312 TempPath += "-%%%%%%%%";
2313 int fd;
2314 if (llvm::sys::fs::unique_file(TempPath.str(), fd, TempPath,
2315 /*makeAbsolute=*/false))
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002316 return CXSaveError_Unknown;
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002317
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002318 // FIXME: Can we somehow regenerate the stat cache here, or do we need to
2319 // unconditionally create a stat cache when we parse the file?
Argyrios Kyrtzidis7e909852011-07-28 00:45:10 +00002320 llvm::raw_fd_ostream Out(fd, /*shouldClose=*/true);
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00002321
2322 serialize(Out);
2323 Out.close();
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002324 if (Out.has_error())
2325 return CXSaveError_Unknown;
2326
2327 if (llvm::error_code ec = llvm::sys::fs::rename(TempPath.str(), File)) {
2328 bool exists;
2329 llvm::sys::fs::remove(TempPath.str(), exists);
2330 return CXSaveError_Unknown;
2331 }
2332
2333 return CXSaveError_None;
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00002334}
2335
Chris Lattner5f9e2722011-07-23 10:55:15 +00002336bool ASTUnit::serialize(raw_ostream &OS) {
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00002337 if (getDiagnostics().hasErrorOccurred())
2338 return true;
2339
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002340 std::vector<unsigned char> Buffer;
2341 llvm::BitstreamWriter Stream(Buffer);
Sebastian Redla4232eb2010-08-18 23:56:21 +00002342 ASTWriter Writer(Stream);
Douglas Gregor832d6202011-07-22 16:35:34 +00002343 Writer.WriteAST(getSema(), 0, std::string(), "");
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002344
2345 // Write the generated bitstream to "Out".
Douglas Gregorbdbb0042010-08-18 22:29:43 +00002346 if (!Buffer.empty())
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00002347 OS.write((char *)&Buffer.front(), Buffer.size());
2348
2349 return false;
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002350}
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002351
2352typedef ContinuousRangeMap<unsigned, int, 2> SLocRemap;
2353
2354static void TranslateSLoc(SourceLocation &L, SLocRemap &Remap) {
2355 unsigned Raw = L.getRawEncoding();
2356 const unsigned MacroBit = 1U << 31;
2357 L = SourceLocation::getFromRawEncoding((Raw & MacroBit) |
2358 ((Raw & ~MacroBit) + Remap.find(Raw & ~MacroBit)->second));
2359}
2360
2361void ASTUnit::TranslateStoredDiagnostics(
2362 ASTReader *MMan,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002363 StringRef ModName,
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002364 SourceManager &SrcMgr,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002365 const SmallVectorImpl<StoredDiagnostic> &Diags,
2366 SmallVectorImpl<StoredDiagnostic> &Out) {
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002367 // The stored diagnostic has the old source manager in it; update
2368 // the locations to refer into the new source manager. We also need to remap
2369 // all the locations to the new view. This includes the diag location, any
2370 // associated source ranges, and the source ranges of associated fix-its.
2371 // FIXME: There should be a cleaner way to do this.
2372
Chris Lattner5f9e2722011-07-23 10:55:15 +00002373 SmallVector<StoredDiagnostic, 4> Result;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002374 Result.reserve(Diags.size());
2375 assert(MMan && "Don't have a module manager");
Jonathan D. Turner48d2c3f2011-07-26 18:21:30 +00002376 serialization::Module *Mod = MMan->ModuleMgr.lookup(ModName);
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002377 assert(Mod && "Don't have preamble module");
2378 SLocRemap &Remap = Mod->SLocRemap;
2379 for (unsigned I = 0, N = Diags.size(); I != N; ++I) {
2380 // Rebuild the StoredDiagnostic.
2381 const StoredDiagnostic &SD = Diags[I];
2382 SourceLocation L = SD.getLocation();
2383 TranslateSLoc(L, Remap);
2384 FullSourceLoc Loc(L, SrcMgr);
2385
Chris Lattner5f9e2722011-07-23 10:55:15 +00002386 SmallVector<CharSourceRange, 4> Ranges;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002387 Ranges.reserve(SD.range_size());
2388 for (StoredDiagnostic::range_iterator I = SD.range_begin(),
2389 E = SD.range_end();
2390 I != E; ++I) {
2391 SourceLocation BL = I->getBegin();
2392 TranslateSLoc(BL, Remap);
2393 SourceLocation EL = I->getEnd();
2394 TranslateSLoc(EL, Remap);
2395 Ranges.push_back(CharSourceRange(SourceRange(BL, EL), I->isTokenRange()));
2396 }
2397
Chris Lattner5f9e2722011-07-23 10:55:15 +00002398 SmallVector<FixItHint, 2> FixIts;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002399 FixIts.reserve(SD.fixit_size());
2400 for (StoredDiagnostic::fixit_iterator I = SD.fixit_begin(),
2401 E = SD.fixit_end();
2402 I != E; ++I) {
2403 FixIts.push_back(FixItHint());
2404 FixItHint &FH = FixIts.back();
2405 FH.CodeToInsert = I->CodeToInsert;
2406 SourceLocation BL = I->RemoveRange.getBegin();
2407 TranslateSLoc(BL, Remap);
2408 SourceLocation EL = I->RemoveRange.getEnd();
2409 TranslateSLoc(EL, Remap);
2410 FH.RemoveRange = CharSourceRange(SourceRange(BL, EL),
2411 I->RemoveRange.isTokenRange());
2412 }
2413
2414 Result.push_back(StoredDiagnostic(SD.getLevel(), SD.getID(),
2415 SD.getMessage(), Loc, Ranges, FixIts));
2416 }
2417 Result.swap(Out);
2418}