blob: a0cfee13030784a8228c72f29e0225211f5bfe22 [file] [log] [blame]
Argyrios Kyrtzidis3a08ec12009-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 Kyrtzidisce379752009-06-20 08:08:23 +000014#include "clang/Frontend/ASTUnit.h"
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000015#include "clang/AST/ASTContext.h"
Daniel Dunbar764c0822009-12-01 09:51:01 +000016#include "clang/AST/ASTConsumer.h"
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000017#include "clang/AST/DeclVisitor.h"
Douglas Gregorb61c07a2010-08-16 18:08:11 +000018#include "clang/AST/TypeOrdering.h"
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000019#include "clang/AST/StmtVisitor.h"
Daniel Dunbar55a17b62009-12-02 03:23:45 +000020#include "clang/Driver/Compilation.h"
21#include "clang/Driver/Driver.h"
22#include "clang/Driver/Job.h"
Argyrios Kyrtzidisbc1f48f2011-03-07 22:45:01 +000023#include "clang/Driver/ArgList.h"
24#include "clang/Driver/Options.h"
Daniel Dunbar55a17b62009-12-02 03:23:45 +000025#include "clang/Driver/Tool.h"
Daniel Dunbar764c0822009-12-01 09:51:01 +000026#include "clang/Frontend/CompilerInstance.h"
27#include "clang/Frontend/FrontendActions.h"
Daniel Dunbar55a17b62009-12-02 03:23:45 +000028#include "clang/Frontend/FrontendDiagnostic.h"
Daniel Dunbar764c0822009-12-01 09:51:01 +000029#include "clang/Frontend/FrontendOptions.h"
Douglas Gregor36e3b5c2010-10-11 21:37:58 +000030#include "clang/Frontend/Utils.h"
Sebastian Redlf5b13462010-08-18 23:57:17 +000031#include "clang/Serialization/ASTReader.h"
Sebastian Redl1914c6f2010-08-18 23:56:37 +000032#include "clang/Serialization/ASTWriter.h"
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000033#include "clang/Lex/HeaderSearch.h"
34#include "clang/Lex/Preprocessor.h"
Daniel Dunbarb9bbd542009-11-15 06:48:46 +000035#include "clang/Basic/TargetOptions.h"
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000036#include "clang/Basic/TargetInfo.h"
37#include "clang/Basic/Diagnostic.h"
Chris Lattnerce6c42f2011-03-23 04:04:01 +000038#include "llvm/ADT/ArrayRef.h"
Douglas Gregordf7a79a2011-02-16 18:16:54 +000039#include "llvm/ADT/StringExtras.h"
Douglas Gregor40a5a7d2010-08-16 23:08:34 +000040#include "llvm/ADT/StringSet.h"
Douglas Gregor9aeaa4d2010-12-07 00:05:48 +000041#include "llvm/Support/Atomic.h"
Douglas Gregoraa98ed92010-01-23 00:14:00 +000042#include "llvm/Support/MemoryBuffer.h"
Michael J. Spencer8aaf4992010-11-29 18:12:39 +000043#include "llvm/Support/Host.h"
44#include "llvm/Support/Path.h"
Douglas Gregor028d3e42010-08-09 20:45:32 +000045#include "llvm/Support/raw_ostream.h"
Douglas Gregor15ba0b32010-07-30 20:58:08 +000046#include "llvm/Support/Timer.h"
Argyrios Kyrtzidis55e75572011-07-21 18:44:49 +000047#include "llvm/Support/FileSystem.h"
Argyrios Kyrtzidisebf01362011-10-10 21:57:12 +000048#include "llvm/Support/Mutex.h"
Ted Kremenekbd307a52011-10-27 19:44:25 +000049#include "llvm/Support/MutexGuard.h"
Ted Kremenek4422bfe2011-03-18 02:06:56 +000050#include "llvm/Support/CrashRecoveryContext.h"
Douglas Gregorbe2d8c62010-07-23 00:33:23 +000051#include <cstdlib>
Zhongxing Xu318e4032010-07-23 02:15:08 +000052#include <cstdio>
Douglas Gregor0e119552010-07-31 00:40:00 +000053#include <sys/stat.h>
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000054using namespace clang;
55
Douglas Gregor16896c42010-10-28 15:44:59 +000056using llvm::TimeRecord;
57
58namespace {
59 class SimpleTimer {
60 bool WantTiming;
61 TimeRecord Start;
62 std::string Output;
63
Benjamin Kramerf2e5a912010-11-09 20:00:56 +000064 public:
Douglas Gregor1cbdd952010-11-01 13:48:43 +000065 explicit SimpleTimer(bool WantTiming) : WantTiming(WantTiming) {
Douglas Gregor16896c42010-10-28 15:44:59 +000066 if (WantTiming)
Benjamin Kramerf2e5a912010-11-09 20:00:56 +000067 Start = TimeRecord::getCurrentTime();
Douglas Gregor16896c42010-10-28 15:44:59 +000068 }
69
Chris Lattner0e62c1c2011-07-23 10:55:15 +000070 void setOutput(const Twine &Output) {
Douglas Gregor16896c42010-10-28 15:44:59 +000071 if (WantTiming)
Benjamin Kramerf2e5a912010-11-09 20:00:56 +000072 this->Output = Output.str();
Douglas Gregor16896c42010-10-28 15:44:59 +000073 }
74
Douglas Gregor16896c42010-10-28 15:44:59 +000075 ~SimpleTimer() {
76 if (WantTiming) {
77 TimeRecord Elapsed = TimeRecord::getCurrentTime();
78 Elapsed -= Start;
79 llvm::errs() << Output << ':';
80 Elapsed.print(Elapsed, llvm::errs());
81 llvm::errs() << '\n';
82 }
83 }
84 };
Ted Kremenek06b4f912011-10-27 17:55:18 +000085
86 struct OnDiskData {
87 /// \brief The file in which the precompiled preamble is stored.
88 std::string PreambleFile;
89
90 /// \brief Temporary files that should be removed when the ASTUnit is
91 /// destroyed.
92 SmallVector<llvm::sys::Path, 4> TemporaryFiles;
93
94 /// \brief Erase temporary files.
95 void CleanTemporaryFiles();
96
97 /// \brief Erase the preamble file.
98 void CleanPreambleFile();
99
100 /// \brief Erase temporary files and the preamble file.
101 void Cleanup();
102 };
103}
104
Ted Kremenekbd307a52011-10-27 19:44:25 +0000105static llvm::sys::SmartMutex<false> &getOnDiskMutex() {
106 static llvm::sys::SmartMutex<false> M(/* recursive = */ true);
107 return M;
108}
109
Ted Kremenek06b4f912011-10-27 17:55:18 +0000110static void cleanupOnDiskMapAtExit(void);
111
112typedef llvm::DenseMap<const ASTUnit *, OnDiskData *> OnDiskDataMap;
113static OnDiskDataMap &getOnDiskDataMap() {
114 static OnDiskDataMap M;
115 static bool hasRegisteredAtExit = false;
116 if (!hasRegisteredAtExit) {
117 hasRegisteredAtExit = true;
118 atexit(cleanupOnDiskMapAtExit);
119 }
120 return M;
121}
122
123static void cleanupOnDiskMapAtExit(void) {
Ted Kremenekbd307a52011-10-27 19:44:25 +0000124 // No mutex required here since we are leaving the program.
Ted Kremenek06b4f912011-10-27 17:55:18 +0000125 OnDiskDataMap &M = getOnDiskDataMap();
126 for (OnDiskDataMap::iterator I = M.begin(), E = M.end(); I != E; ++I) {
127 // We don't worry about freeing the memory associated with OnDiskDataMap.
128 // All we care about is erasing stale files.
129 I->second->Cleanup();
130 }
131}
132
133static OnDiskData &getOnDiskData(const ASTUnit *AU) {
Ted Kremenekbd307a52011-10-27 19:44:25 +0000134 // We require the mutex since we are modifying the structure of the
135 // DenseMap.
136 llvm::MutexGuard Guard(getOnDiskMutex());
Ted Kremenek06b4f912011-10-27 17:55:18 +0000137 OnDiskDataMap &M = getOnDiskDataMap();
138 OnDiskData *&D = M[AU];
139 if (!D)
140 D = new OnDiskData();
141 return *D;
142}
143
144static void erasePreambleFile(const ASTUnit *AU) {
145 getOnDiskData(AU).CleanPreambleFile();
146}
147
148static void removeOnDiskEntry(const ASTUnit *AU) {
Ted Kremenekbd307a52011-10-27 19:44:25 +0000149 // We require the mutex since we are modifying the structure of the
150 // DenseMap.
151 llvm::MutexGuard Guard(getOnDiskMutex());
Ted Kremenek06b4f912011-10-27 17:55:18 +0000152 OnDiskDataMap &M = getOnDiskDataMap();
153 OnDiskDataMap::iterator I = M.find(AU);
154 if (I != M.end()) {
155 I->second->Cleanup();
156 delete I->second;
157 M.erase(AU);
158 }
159}
160
161static void setPreambleFile(const ASTUnit *AU, llvm::StringRef preambleFile) {
162 getOnDiskData(AU).PreambleFile = preambleFile;
163}
164
165static const std::string &getPreambleFile(const ASTUnit *AU) {
166 return getOnDiskData(AU).PreambleFile;
167}
168
169void OnDiskData::CleanTemporaryFiles() {
170 for (unsigned I = 0, N = TemporaryFiles.size(); I != N; ++I)
171 TemporaryFiles[I].eraseFromDisk();
172 TemporaryFiles.clear();
173}
174
175void OnDiskData::CleanPreambleFile() {
176 if (!PreambleFile.empty()) {
177 llvm::sys::Path(PreambleFile).eraseFromDisk();
178 PreambleFile.clear();
179 }
180}
181
182void OnDiskData::Cleanup() {
183 CleanTemporaryFiles();
184 CleanPreambleFile();
185}
186
187void ASTUnit::CleanTemporaryFiles() {
188 getOnDiskData(this).CleanTemporaryFiles();
189}
190
191void ASTUnit::addTemporaryFile(const llvm::sys::Path &TempFile) {
192 getOnDiskData(this).TemporaryFiles.push_back(TempFile);
Douglas Gregor16896c42010-10-28 15:44:59 +0000193}
194
Douglas Gregorbb420ab2010-08-04 05:53:38 +0000195/// \brief After failing to build a precompiled preamble (due to
196/// errors in the source that occurs in the preamble), the number of
197/// reparses during which we'll skip even trying to precompile the
198/// preamble.
199const unsigned DefaultPreambleRebuildInterval = 5;
200
Douglas Gregor68dbaea2010-11-17 00:13:31 +0000201/// \brief Tracks the number of ASTUnit objects that are currently active.
202///
203/// Used for debugging purposes only.
Douglas Gregor9aeaa4d2010-12-07 00:05:48 +0000204static llvm::sys::cas_flag ActiveASTUnitObjects;
Douglas Gregor68dbaea2010-11-17 00:13:31 +0000205
Douglas Gregord03e8232010-04-05 21:10:19 +0000206ASTUnit::ASTUnit(bool _MainFileIsAST)
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +0000207 : OnlyLocalDecls(false), CaptureDiagnostics(false),
208 MainFileIsAST(_MainFileIsAST),
Douglas Gregor69f74f82011-08-25 22:30:56 +0000209 TUKind(TU_Complete), WantTiming(getenv("LIBCLANG_TIMING")),
Argyrios Kyrtzidis4954bc12011-03-05 01:03:48 +0000210 OwnsRemappedFileBuffers(true),
Douglas Gregor16896c42010-10-28 15:44:59 +0000211 NumStoredDiagnosticsFromDriver(0),
Douglas Gregora0734c52010-08-19 01:33:06 +0000212 PreambleRebuildCounter(0), SavedMainFileBuffer(0), PreambleBuffer(0),
Douglas Gregor2c8bd472010-08-17 00:40:40 +0000213 ShouldCacheCodeCompletionResults(false),
Chandler Carruthde81fc82011-07-14 09:02:10 +0000214 NestedMacroExpansions(true),
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000215 CompletionCacheTopLevelHashValue(0),
216 PreambleTopLevelHashValue(0),
217 CurrentTopLevelHashValue(0),
Douglas Gregor4740c452010-08-19 00:45:44 +0000218 UnsafeToFree(false) {
Douglas Gregor68dbaea2010-11-17 00:13:31 +0000219 if (getenv("LIBCLANG_OBJTRACKING")) {
Douglas Gregor9aeaa4d2010-12-07 00:05:48 +0000220 llvm::sys::AtomicIncrement(&ActiveASTUnitObjects);
Douglas Gregor68dbaea2010-11-17 00:13:31 +0000221 fprintf(stderr, "+++ %d translation units\n", ActiveASTUnitObjects);
222 }
Douglas Gregor15ba0b32010-07-30 20:58:08 +0000223}
Douglas Gregord03e8232010-04-05 21:10:19 +0000224
Daniel Dunbar764c0822009-12-01 09:51:01 +0000225ASTUnit::~ASTUnit() {
Ted Kremenek06b4f912011-10-27 17:55:18 +0000226 // Clean up the temporary files and the preamble file.
227 removeOnDiskEntry(this);
228
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000229 // Free the buffers associated with remapped files. We are required to
230 // perform this operation here because we explicitly request that the
231 // compiler instance *not* free these buffers for each invocation of the
232 // parser.
Ted Kremenek5e14d392011-03-21 18:40:17 +0000233 if (Invocation.getPtr() && OwnsRemappedFileBuffers) {
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000234 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
235 for (PreprocessorOptions::remapped_file_buffer_iterator
236 FB = PPOpts.remapped_file_buffer_begin(),
237 FBEnd = PPOpts.remapped_file_buffer_end();
238 FB != FBEnd;
239 ++FB)
240 delete FB->second;
241 }
Douglas Gregor96c04262010-07-27 14:52:07 +0000242
243 delete SavedMainFileBuffer;
Douglas Gregora0734c52010-08-19 01:33:06 +0000244 delete PreambleBuffer;
245
Douglas Gregor16896c42010-10-28 15:44:59 +0000246 ClearCachedCompletionResults();
Douglas Gregor68dbaea2010-11-17 00:13:31 +0000247
248 if (getenv("LIBCLANG_OBJTRACKING")) {
Douglas Gregor9aeaa4d2010-12-07 00:05:48 +0000249 llvm::sys::AtomicDecrement(&ActiveASTUnitObjects);
Douglas Gregor68dbaea2010-11-17 00:13:31 +0000250 fprintf(stderr, "--- %d translation units\n", ActiveASTUnitObjects);
251 }
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000252}
253
Douglas Gregor39982192010-08-15 06:18:01 +0000254/// \brief Determine the set of code-completion contexts in which this
255/// declaration should be shown.
256static unsigned getDeclShowContexts(NamedDecl *ND,
Douglas Gregor59cab552010-08-16 23:05:20 +0000257 const LangOptions &LangOpts,
258 bool &IsNestedNameSpecifier) {
259 IsNestedNameSpecifier = false;
260
Douglas Gregor39982192010-08-15 06:18:01 +0000261 if (isa<UsingShadowDecl>(ND))
262 ND = dyn_cast<NamedDecl>(ND->getUnderlyingDecl());
263 if (!ND)
264 return 0;
265
266 unsigned Contexts = 0;
267 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND) ||
268 isa<ClassTemplateDecl>(ND) || isa<TemplateTemplateParmDecl>(ND)) {
269 // Types can appear in these contexts.
270 if (LangOpts.CPlusPlus || !isa<TagDecl>(ND))
271 Contexts |= (1 << (CodeCompletionContext::CCC_TopLevel - 1))
272 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
273 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
274 | (1 << (CodeCompletionContext::CCC_Statement - 1))
Douglas Gregor5e35d592010-09-14 23:59:36 +0000275 | (1 << (CodeCompletionContext::CCC_Type - 1))
276 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1));
Douglas Gregor39982192010-08-15 06:18:01 +0000277
278 // In C++, types can appear in expressions contexts (for functional casts).
279 if (LangOpts.CPlusPlus)
280 Contexts |= (1 << (CodeCompletionContext::CCC_Expression - 1));
281
282 // In Objective-C, message sends can send interfaces. In Objective-C++,
283 // all types are available due to functional casts.
284 if (LangOpts.CPlusPlus || isa<ObjCInterfaceDecl>(ND))
285 Contexts |= (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1));
Douglas Gregor21325842011-07-07 16:03:39 +0000286
287 // In Objective-C, you can only be a subclass of another Objective-C class
288 if (isa<ObjCInterfaceDecl>(ND))
Douglas Gregor2c595ad2011-07-30 06:55:39 +0000289 Contexts |= (1 << (CodeCompletionContext::CCC_ObjCInterfaceName - 1));
Douglas Gregor39982192010-08-15 06:18:01 +0000290
291 // Deal with tag names.
292 if (isa<EnumDecl>(ND)) {
293 Contexts |= (1 << (CodeCompletionContext::CCC_EnumTag - 1));
294
Douglas Gregor59cab552010-08-16 23:05:20 +0000295 // Part of the nested-name-specifier in C++0x.
Douglas Gregor39982192010-08-15 06:18:01 +0000296 if (LangOpts.CPlusPlus0x)
Douglas Gregor59cab552010-08-16 23:05:20 +0000297 IsNestedNameSpecifier = true;
Douglas Gregor39982192010-08-15 06:18:01 +0000298 } else if (RecordDecl *Record = dyn_cast<RecordDecl>(ND)) {
299 if (Record->isUnion())
300 Contexts |= (1 << (CodeCompletionContext::CCC_UnionTag - 1));
301 else
302 Contexts |= (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1));
303
Douglas Gregor39982192010-08-15 06:18:01 +0000304 if (LangOpts.CPlusPlus)
Douglas Gregor59cab552010-08-16 23:05:20 +0000305 IsNestedNameSpecifier = true;
Douglas Gregor0ac41382010-09-23 23:01:17 +0000306 } else if (isa<ClassTemplateDecl>(ND))
Douglas Gregor59cab552010-08-16 23:05:20 +0000307 IsNestedNameSpecifier = true;
Douglas Gregor39982192010-08-15 06:18:01 +0000308 } else if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
309 // Values can appear in these contexts.
310 Contexts = (1 << (CodeCompletionContext::CCC_Statement - 1))
311 | (1 << (CodeCompletionContext::CCC_Expression - 1))
Douglas Gregor5e35d592010-09-14 23:59:36 +0000312 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1))
Douglas Gregor39982192010-08-15 06:18:01 +0000313 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1));
314 } else if (isa<ObjCProtocolDecl>(ND)) {
315 Contexts = (1 << (CodeCompletionContext::CCC_ObjCProtocolName - 1));
Douglas Gregor21325842011-07-07 16:03:39 +0000316 } else if (isa<ObjCCategoryDecl>(ND)) {
317 Contexts = (1 << (CodeCompletionContext::CCC_ObjCCategoryName - 1));
Douglas Gregor39982192010-08-15 06:18:01 +0000318 } else if (isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) {
Douglas Gregor59cab552010-08-16 23:05:20 +0000319 Contexts = (1 << (CodeCompletionContext::CCC_Namespace - 1));
Douglas Gregor39982192010-08-15 06:18:01 +0000320
321 // Part of the nested-name-specifier.
Douglas Gregor59cab552010-08-16 23:05:20 +0000322 IsNestedNameSpecifier = true;
Douglas Gregor39982192010-08-15 06:18:01 +0000323 }
324
325 return Contexts;
326}
327
Douglas Gregorb14904c2010-08-13 22:48:40 +0000328void ASTUnit::CacheCodeCompletionResults() {
329 if (!TheSema)
330 return;
331
Douglas Gregor16896c42010-10-28 15:44:59 +0000332 SimpleTimer Timer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +0000333 Timer.setOutput("Cache global code completions for " + getMainFileName());
Douglas Gregorb14904c2010-08-13 22:48:40 +0000334
335 // Clear out the previous results.
336 ClearCachedCompletionResults();
337
338 // Gather the set of global code completions.
John McCall276321a2010-08-25 06:19:51 +0000339 typedef CodeCompletionResult Result;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000340 SmallVector<Result, 8> Results;
Douglas Gregor162b7122011-02-16 19:08:06 +0000341 CachedCompletionAllocator = new GlobalCodeCompletionAllocator;
342 TheSema->GatherGlobalCodeCompletions(*CachedCompletionAllocator, Results);
Douglas Gregorb14904c2010-08-13 22:48:40 +0000343
344 // Translate global code completions into cached completions.
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000345 llvm::DenseMap<CanQualType, unsigned> CompletionTypes;
346
Douglas Gregorb14904c2010-08-13 22:48:40 +0000347 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
348 switch (Results[I].Kind) {
Douglas Gregor39982192010-08-15 06:18:01 +0000349 case Result::RK_Declaration: {
Douglas Gregor59cab552010-08-16 23:05:20 +0000350 bool IsNestedNameSpecifier = false;
Douglas Gregor39982192010-08-15 06:18:01 +0000351 CachedCodeCompletionResult CachedResult;
Douglas Gregorb278aaf2011-02-01 19:23:04 +0000352 CachedResult.Completion = Results[I].CreateCodeCompletionString(*TheSema,
Douglas Gregor162b7122011-02-16 19:08:06 +0000353 *CachedCompletionAllocator);
Douglas Gregor39982192010-08-15 06:18:01 +0000354 CachedResult.ShowInContexts = getDeclShowContexts(Results[I].Declaration,
Douglas Gregor59cab552010-08-16 23:05:20 +0000355 Ctx->getLangOptions(),
356 IsNestedNameSpecifier);
Douglas Gregor39982192010-08-15 06:18:01 +0000357 CachedResult.Priority = Results[I].Priority;
358 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregorf757a122010-08-23 23:00:57 +0000359 CachedResult.Availability = Results[I].Availability;
Douglas Gregor24747402010-08-16 16:46:30 +0000360
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000361 // Keep track of the type of this completion in an ASTContext-agnostic
362 // way.
Douglas Gregor24747402010-08-16 16:46:30 +0000363 QualType UsageType = getDeclUsageType(*Ctx, Results[I].Declaration);
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000364 if (UsageType.isNull()) {
Douglas Gregor24747402010-08-16 16:46:30 +0000365 CachedResult.TypeClass = STC_Void;
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000366 CachedResult.Type = 0;
367 } else {
368 CanQualType CanUsageType
369 = Ctx->getCanonicalType(UsageType.getUnqualifiedType());
370 CachedResult.TypeClass = getSimplifiedTypeClass(CanUsageType);
371
372 // Determine whether we have already seen this type. If so, we save
373 // ourselves the work of formatting the type string by using the
374 // temporary, CanQualType-based hash table to find the associated value.
375 unsigned &TypeValue = CompletionTypes[CanUsageType];
376 if (TypeValue == 0) {
377 TypeValue = CompletionTypes.size();
378 CachedCompletionTypes[QualType(CanUsageType).getAsString()]
379 = TypeValue;
380 }
381
382 CachedResult.Type = TypeValue;
Douglas Gregor24747402010-08-16 16:46:30 +0000383 }
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000384
Douglas Gregor39982192010-08-15 06:18:01 +0000385 CachedCompletionResults.push_back(CachedResult);
Douglas Gregor59cab552010-08-16 23:05:20 +0000386
387 /// Handle nested-name-specifiers in C++.
388 if (TheSema->Context.getLangOptions().CPlusPlus &&
389 IsNestedNameSpecifier && !Results[I].StartsNestedNameSpecifier) {
390 // The contexts in which a nested-name-specifier can appear in C++.
391 unsigned NNSContexts
392 = (1 << (CodeCompletionContext::CCC_TopLevel - 1))
393 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
394 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
395 | (1 << (CodeCompletionContext::CCC_Statement - 1))
396 | (1 << (CodeCompletionContext::CCC_Expression - 1))
397 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
398 | (1 << (CodeCompletionContext::CCC_EnumTag - 1))
399 | (1 << (CodeCompletionContext::CCC_UnionTag - 1))
400 | (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1))
Douglas Gregorc49f5b22010-08-23 18:23:48 +0000401 | (1 << (CodeCompletionContext::CCC_Type - 1))
Douglas Gregor5e35d592010-09-14 23:59:36 +0000402 | (1 << (CodeCompletionContext::CCC_PotentiallyQualifiedName - 1))
403 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1));
Douglas Gregor59cab552010-08-16 23:05:20 +0000404
405 if (isa<NamespaceDecl>(Results[I].Declaration) ||
406 isa<NamespaceAliasDecl>(Results[I].Declaration))
407 NNSContexts |= (1 << (CodeCompletionContext::CCC_Namespace - 1));
408
409 if (unsigned RemainingContexts
410 = NNSContexts & ~CachedResult.ShowInContexts) {
411 // If there any contexts where this completion can be a
412 // nested-name-specifier but isn't already an option, create a
413 // nested-name-specifier completion.
414 Results[I].StartsNestedNameSpecifier = true;
Douglas Gregorb278aaf2011-02-01 19:23:04 +0000415 CachedResult.Completion
416 = Results[I].CreateCodeCompletionString(*TheSema,
Douglas Gregor162b7122011-02-16 19:08:06 +0000417 *CachedCompletionAllocator);
Douglas Gregor59cab552010-08-16 23:05:20 +0000418 CachedResult.ShowInContexts = RemainingContexts;
419 CachedResult.Priority = CCP_NestedNameSpecifier;
420 CachedResult.TypeClass = STC_Void;
421 CachedResult.Type = 0;
422 CachedCompletionResults.push_back(CachedResult);
423 }
424 }
Douglas Gregorb14904c2010-08-13 22:48:40 +0000425 break;
Douglas Gregor39982192010-08-15 06:18:01 +0000426 }
427
Douglas Gregorb14904c2010-08-13 22:48:40 +0000428 case Result::RK_Keyword:
429 case Result::RK_Pattern:
430 // Ignore keywords and patterns; we don't care, since they are so
431 // easily regenerated.
432 break;
433
434 case Result::RK_Macro: {
435 CachedCodeCompletionResult CachedResult;
Douglas Gregorb278aaf2011-02-01 19:23:04 +0000436 CachedResult.Completion
437 = Results[I].CreateCodeCompletionString(*TheSema,
Douglas Gregor162b7122011-02-16 19:08:06 +0000438 *CachedCompletionAllocator);
Douglas Gregorb14904c2010-08-13 22:48:40 +0000439 CachedResult.ShowInContexts
440 = (1 << (CodeCompletionContext::CCC_TopLevel - 1))
441 | (1 << (CodeCompletionContext::CCC_ObjCInterface - 1))
442 | (1 << (CodeCompletionContext::CCC_ObjCImplementation - 1))
443 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
444 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
445 | (1 << (CodeCompletionContext::CCC_Statement - 1))
446 | (1 << (CodeCompletionContext::CCC_Expression - 1))
Douglas Gregor12785102010-08-24 20:21:13 +0000447 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
Douglas Gregorec00a262010-08-24 22:20:20 +0000448 | (1 << (CodeCompletionContext::CCC_MacroNameUse - 1))
Douglas Gregor5e35d592010-09-14 23:59:36 +0000449 | (1 << (CodeCompletionContext::CCC_PreprocessorExpression - 1))
Douglas Gregor3a69eaf2011-02-18 23:30:37 +0000450 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1))
451 | (1 << (CodeCompletionContext::CCC_OtherWithMacros - 1));
Douglas Gregorc49f5b22010-08-23 18:23:48 +0000452
Douglas Gregorb14904c2010-08-13 22:48:40 +0000453 CachedResult.Priority = Results[I].Priority;
454 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregorf757a122010-08-23 23:00:57 +0000455 CachedResult.Availability = Results[I].Availability;
Douglas Gregor6e240332010-08-16 16:18:59 +0000456 CachedResult.TypeClass = STC_Void;
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000457 CachedResult.Type = 0;
Douglas Gregorb14904c2010-08-13 22:48:40 +0000458 CachedCompletionResults.push_back(CachedResult);
459 break;
460 }
461 }
Douglas Gregorb14904c2010-08-13 22:48:40 +0000462 }
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000463
464 // Save the current top-level hash value.
465 CompletionCacheTopLevelHashValue = CurrentTopLevelHashValue;
Douglas Gregorb14904c2010-08-13 22:48:40 +0000466}
467
468void ASTUnit::ClearCachedCompletionResults() {
Douglas Gregorb14904c2010-08-13 22:48:40 +0000469 CachedCompletionResults.clear();
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000470 CachedCompletionTypes.clear();
Douglas Gregor162b7122011-02-16 19:08:06 +0000471 CachedCompletionAllocator = 0;
Douglas Gregorb14904c2010-08-13 22:48:40 +0000472}
473
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000474namespace {
475
Sebastian Redl2c499f62010-08-18 23:56:43 +0000476/// \brief Gathers information from ASTReader that will be used to initialize
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000477/// a Preprocessor.
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000478class ASTInfoCollector : public ASTReaderListener {
Douglas Gregor83297df2011-09-01 23:39:15 +0000479 Preprocessor &PP;
Douglas Gregore8bbc122011-09-02 00:18:52 +0000480 ASTContext &Context;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000481 LangOptions &LangOpt;
482 HeaderSearch &HSI;
Douglas Gregor83297df2011-09-01 23:39:15 +0000483 llvm::IntrusiveRefCntPtr<TargetInfo> &Target;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000484 std::string &Predefines;
485 unsigned &Counter;
Mike Stump11289f42009-09-09 15:08:12 +0000486
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000487 unsigned NumHeaderInfos;
Mike Stump11289f42009-09-09 15:08:12 +0000488
Douglas Gregore8bbc122011-09-02 00:18:52 +0000489 bool InitializedLanguage;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000490public:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000491 ASTInfoCollector(Preprocessor &PP, ASTContext &Context, LangOptions &LangOpt,
492 HeaderSearch &HSI,
Douglas Gregor83297df2011-09-01 23:39:15 +0000493 llvm::IntrusiveRefCntPtr<TargetInfo> &Target,
494 std::string &Predefines,
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000495 unsigned &Counter)
Douglas Gregore8bbc122011-09-02 00:18:52 +0000496 : PP(PP), Context(Context), LangOpt(LangOpt), HSI(HSI), Target(Target),
Douglas Gregor83297df2011-09-01 23:39:15 +0000497 Predefines(Predefines), Counter(Counter), NumHeaderInfos(0),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000498 InitializedLanguage(false) {}
Mike Stump11289f42009-09-09 15:08:12 +0000499
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000500 virtual bool ReadLanguageOptions(const LangOptions &LangOpts) {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000501 if (InitializedLanguage)
Douglas Gregor83297df2011-09-01 23:39:15 +0000502 return false;
503
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000504 LangOpt = LangOpts;
Douglas Gregor83297df2011-09-01 23:39:15 +0000505
506 // Initialize the preprocessor.
507 PP.Initialize(*Target);
Douglas Gregore8bbc122011-09-02 00:18:52 +0000508
509 // Initialize the ASTContext
510 Context.InitBuiltinTypes(*Target);
511
512 InitializedLanguage = true;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000513 return false;
514 }
Mike Stump11289f42009-09-09 15:08:12 +0000515
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000516 virtual bool ReadTargetTriple(StringRef Triple) {
Douglas Gregor83297df2011-09-01 23:39:15 +0000517 // If we've already initialized the target, don't do it again.
518 if (Target)
519 return false;
520
521 // FIXME: This is broken, we should store the TargetOptions in the AST file.
522 TargetOptions TargetOpts;
523 TargetOpts.ABI = "";
524 TargetOpts.CXXABI = "";
525 TargetOpts.CPU = "";
526 TargetOpts.Features.clear();
527 TargetOpts.Triple = Triple;
528 Target = TargetInfo::CreateTargetInfo(PP.getDiagnostics(), TargetOpts);
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000529 return false;
530 }
Mike Stump11289f42009-09-09 15:08:12 +0000531
Sebastian Redl8b41f302010-07-14 23:29:55 +0000532 virtual bool ReadPredefinesBuffer(const PCHPredefinesBlocks &Buffers,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000533 StringRef OriginalFileName,
Nick Lewycky36079892011-02-23 21:16:44 +0000534 std::string &SuggestedPredefines,
535 FileManager &FileMgr) {
Sebastian Redl8b41f302010-07-14 23:29:55 +0000536 Predefines = Buffers[0].Data;
537 for (unsigned I = 1, N = Buffers.size(); I != N; ++I) {
538 Predefines += Buffers[I].Data;
539 }
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000540 return false;
541 }
Mike Stump11289f42009-09-09 15:08:12 +0000542
Douglas Gregora2f49452010-03-16 19:09:18 +0000543 virtual void ReadHeaderFileInfo(const HeaderFileInfo &HFI, unsigned ID) {
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000544 HSI.setHeaderFileInfoForUID(HFI, NumHeaderInfos++);
545 }
Mike Stump11289f42009-09-09 15:08:12 +0000546
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000547 virtual void ReadCounter(unsigned Value) {
548 Counter = Value;
549 }
550};
551
David Blaikief18d91a2011-09-26 00:01:39 +0000552class StoredDiagnosticConsumer : public DiagnosticConsumer {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000553 SmallVectorImpl<StoredDiagnostic> &StoredDiags;
Douglas Gregor33cdd812010-02-18 18:08:43 +0000554
555public:
David Blaikief18d91a2011-09-26 00:01:39 +0000556 explicit StoredDiagnosticConsumer(
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000557 SmallVectorImpl<StoredDiagnostic> &StoredDiags)
Douglas Gregor33cdd812010-02-18 18:08:43 +0000558 : StoredDiags(StoredDiags) { }
559
David Blaikie9c902b52011-09-25 23:23:43 +0000560 virtual void HandleDiagnostic(DiagnosticsEngine::Level Level,
David Blaikieb5784322011-09-26 01:18:08 +0000561 const Diagnostic &Info);
Douglas Gregord0e9e3a2011-09-29 00:38:00 +0000562
563 DiagnosticConsumer *clone(DiagnosticsEngine &Diags) const {
564 // Just drop any diagnostics that come from cloned consumers; they'll
565 // have different source managers anyway.
566 return new IgnoringDiagConsumer();
567 }
Douglas Gregor33cdd812010-02-18 18:08:43 +0000568};
569
570/// \brief RAII object that optionally captures diagnostics, if
571/// there is no diagnostic client to capture them already.
572class CaptureDroppedDiagnostics {
David Blaikie9c902b52011-09-25 23:23:43 +0000573 DiagnosticsEngine &Diags;
David Blaikief18d91a2011-09-26 00:01:39 +0000574 StoredDiagnosticConsumer Client;
David Blaikiee2eefae2011-09-25 23:39:51 +0000575 DiagnosticConsumer *PreviousClient;
Douglas Gregor33cdd812010-02-18 18:08:43 +0000576
577public:
David Blaikie9c902b52011-09-25 23:23:43 +0000578 CaptureDroppedDiagnostics(bool RequestCapture, DiagnosticsEngine &Diags,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000579 SmallVectorImpl<StoredDiagnostic> &StoredDiags)
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000580 : Diags(Diags), Client(StoredDiags), PreviousClient(0)
Douglas Gregor33cdd812010-02-18 18:08:43 +0000581 {
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000582 if (RequestCapture || Diags.getClient() == 0) {
583 PreviousClient = Diags.takeClient();
Douglas Gregor33cdd812010-02-18 18:08:43 +0000584 Diags.setClient(&Client);
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000585 }
Douglas Gregor33cdd812010-02-18 18:08:43 +0000586 }
587
588 ~CaptureDroppedDiagnostics() {
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000589 if (Diags.getClient() == &Client) {
590 Diags.takeClient();
591 Diags.setClient(PreviousClient);
592 }
Douglas Gregor33cdd812010-02-18 18:08:43 +0000593 }
594};
595
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000596} // anonymous namespace
597
David Blaikief18d91a2011-09-26 00:01:39 +0000598void StoredDiagnosticConsumer::HandleDiagnostic(DiagnosticsEngine::Level Level,
David Blaikieb5784322011-09-26 01:18:08 +0000599 const Diagnostic &Info) {
Argyrios Kyrtzidisc79346a2010-11-18 20:06:46 +0000600 // Default implementation (Warnings/errors count).
David Blaikiee2eefae2011-09-25 23:39:51 +0000601 DiagnosticConsumer::HandleDiagnostic(Level, Info);
Argyrios Kyrtzidisc79346a2010-11-18 20:06:46 +0000602
Douglas Gregor33cdd812010-02-18 18:08:43 +0000603 StoredDiags.push_back(StoredDiagnostic(Level, Info));
604}
605
Steve Naroffc0683b92009-09-03 18:19:54 +0000606const std::string &ASTUnit::getOriginalSourceFileName() {
Daniel Dunbara8a50932009-12-02 08:44:16 +0000607 return OriginalSourceFile;
Steve Naroffc0683b92009-09-03 18:19:54 +0000608}
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000609
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000610llvm::MemoryBuffer *ASTUnit::getBufferForFile(StringRef Filename,
Chris Lattner26b5c192010-11-23 09:19:42 +0000611 std::string *ErrorStr) {
Chris Lattner5159f612010-11-23 08:35:12 +0000612 assert(FileMgr);
Chris Lattner26b5c192010-11-23 09:19:42 +0000613 return FileMgr->getBufferForFile(Filename, ErrorStr);
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000614}
615
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000616/// \brief Configure the diagnostics object for use with ASTUnit.
David Blaikie9c902b52011-09-25 23:23:43 +0000617void ASTUnit::ConfigureDiags(llvm::IntrusiveRefCntPtr<DiagnosticsEngine> &Diags,
Douglas Gregor345c1bc2011-01-19 01:02:47 +0000618 const char **ArgBegin, const char **ArgEnd,
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000619 ASTUnit &AST, bool CaptureDiagnostics) {
620 if (!Diags.getPtr()) {
621 // No diagnostics engine was provided, so create our own diagnostics object
622 // with the default options.
623 DiagnosticOptions DiagOpts;
David Blaikiee2eefae2011-09-25 23:39:51 +0000624 DiagnosticConsumer *Client = 0;
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000625 if (CaptureDiagnostics)
David Blaikief18d91a2011-09-26 00:01:39 +0000626 Client = new StoredDiagnosticConsumer(AST.StoredDiagnostics);
Douglas Gregor345c1bc2011-01-19 01:02:47 +0000627 Diags = CompilerInstance::createDiagnostics(DiagOpts, ArgEnd- ArgBegin,
628 ArgBegin, Client);
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000629 } else if (CaptureDiagnostics) {
David Blaikief18d91a2011-09-26 00:01:39 +0000630 Diags->setClient(new StoredDiagnosticConsumer(AST.StoredDiagnostics));
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000631 }
632}
633
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000634ASTUnit *ASTUnit::LoadFromASTFile(const std::string &Filename,
David Blaikie9c902b52011-09-25 23:23:43 +0000635 llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000636 const FileSystemOptions &FileSystemOpts,
Ted Kremenek8bcb1c62009-10-17 00:34:24 +0000637 bool OnlyLocalDecls,
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000638 RemappedFile *RemappedFiles,
Douglas Gregor33cdd812010-02-18 18:08:43 +0000639 unsigned NumRemappedFiles,
640 bool CaptureDiagnostics) {
Douglas Gregord03e8232010-04-05 21:10:19 +0000641 llvm::OwningPtr<ASTUnit> AST(new ASTUnit(true));
Ted Kremenek4422bfe2011-03-18 02:06:56 +0000642
643 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +0000644 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
645 ASTUnitCleanup(AST.get());
David Blaikie9c902b52011-09-25 23:23:43 +0000646 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
647 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Ted Kremenek022a4902011-03-22 01:15:24 +0000648 DiagCleanup(Diags.getPtr());
Ted Kremenek4422bfe2011-03-18 02:06:56 +0000649
Douglas Gregor345c1bc2011-01-19 01:02:47 +0000650 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000651
Douglas Gregor16bef852009-10-16 20:01:17 +0000652 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000653 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor7f95d262010-04-05 23:52:57 +0000654 AST->Diagnostics = Diags;
Ted Kremenek5e14d392011-03-21 18:40:17 +0000655 AST->FileMgr = new FileManager(FileSystemOpts);
656 AST->SourceMgr = new SourceManager(AST->getDiagnostics(),
657 AST->getFileManager());
Chris Lattner5159f612010-11-23 08:35:12 +0000658 AST->HeaderInfo.reset(new HeaderSearch(AST->getFileManager()));
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000659
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000660 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +0000661 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
662 if (const llvm::MemoryBuffer *
663 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
664 // Create the file entry for the file that we're mapping from.
665 const FileEntry *FromFile
666 = AST->getFileManager().getVirtualFile(RemappedFiles[I].first,
667 memBuf->getBufferSize(),
668 0);
669 if (!FromFile) {
670 AST->getDiagnostics().Report(diag::err_fe_remap_missing_from_file)
671 << RemappedFiles[I].first;
672 delete memBuf;
673 continue;
674 }
675
676 // Override the contents of the "from" file with the contents of
677 // the "to" file.
678 AST->getSourceManager().overrideFileContents(FromFile, memBuf);
679
680 } else {
681 const char *fname = fileOrBuf.get<const char *>();
682 const FileEntry *ToFile = AST->FileMgr->getFile(fname);
683 if (!ToFile) {
684 AST->getDiagnostics().Report(diag::err_fe_remap_missing_to_file)
685 << RemappedFiles[I].first << fname;
686 continue;
687 }
688
689 // Create the file entry for the file that we're mapping from.
690 const FileEntry *FromFile
691 = AST->getFileManager().getVirtualFile(RemappedFiles[I].first,
692 ToFile->getSize(),
693 0);
694 if (!FromFile) {
695 AST->getDiagnostics().Report(diag::err_fe_remap_missing_from_file)
696 << RemappedFiles[I].first;
697 delete memBuf;
698 continue;
699 }
700
701 // Override the contents of the "from" file with the contents of
702 // the "to" file.
703 AST->getSourceManager().overrideFileContents(FromFile, ToFile);
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000704 }
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000705 }
706
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000707 // Gather Info for preprocessor construction later on.
Mike Stump11289f42009-09-09 15:08:12 +0000708
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000709 HeaderSearch &HeaderInfo = *AST->HeaderInfo.get();
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000710 std::string Predefines;
711 unsigned Counter;
712
Sebastian Redl2c499f62010-08-18 23:56:43 +0000713 llvm::OwningPtr<ASTReader> Reader;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000714
Douglas Gregor83297df2011-09-01 23:39:15 +0000715 AST->PP = new Preprocessor(AST->getDiagnostics(), AST->ASTFileLangOpts,
716 /*Target=*/0, AST->getSourceManager(), HeaderInfo,
717 *AST,
718 /*IILookup=*/0,
719 /*OwnsHeaderSearch=*/false,
720 /*DelayInitialization=*/true);
Douglas Gregore8bbc122011-09-02 00:18:52 +0000721 Preprocessor &PP = *AST->PP;
722
723 AST->Ctx = new ASTContext(AST->ASTFileLangOpts,
724 AST->getSourceManager(),
725 /*Target=*/0,
726 PP.getIdentifierTable(),
727 PP.getSelectorTable(),
728 PP.getBuiltinInfo(),
729 /* size_reserve = */0,
730 /*DelayInitialization=*/true);
731 ASTContext &Context = *AST->Ctx;
Douglas Gregor83297df2011-09-01 23:39:15 +0000732
Douglas Gregor8835e032011-09-02 00:26:20 +0000733 Reader.reset(new ASTReader(PP, Context));
Ted Kremenek2159b8d2011-05-04 23:27:12 +0000734
735 // Recover resources if we crash before exiting this method.
736 llvm::CrashRecoveryContextCleanupRegistrar<ASTReader>
737 ReaderCleanup(Reader.get());
738
Douglas Gregore8bbc122011-09-02 00:18:52 +0000739 Reader->setListener(new ASTInfoCollector(*AST->PP, Context,
Douglas Gregor83297df2011-09-01 23:39:15 +0000740 AST->ASTFileLangOpts, HeaderInfo,
741 AST->Target, Predefines, Counter));
Daniel Dunbar2d9c7402009-09-03 05:59:35 +0000742
Douglas Gregora6895d82011-07-22 16:00:58 +0000743 switch (Reader->ReadAST(Filename, serialization::MK_MainFile)) {
Sebastian Redl2c499f62010-08-18 23:56:43 +0000744 case ASTReader::Success:
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000745 break;
Mike Stump11289f42009-09-09 15:08:12 +0000746
Sebastian Redl2c499f62010-08-18 23:56:43 +0000747 case ASTReader::Failure:
748 case ASTReader::IgnorePCH:
Douglas Gregord03e8232010-04-05 21:10:19 +0000749 AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000750 return NULL;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000751 }
Mike Stump11289f42009-09-09 15:08:12 +0000752
Daniel Dunbara8a50932009-12-02 08:44:16 +0000753 AST->OriginalSourceFile = Reader->getOriginalSourceFile();
754
Daniel Dunbarb7bbfdd2009-09-21 03:03:47 +0000755 PP.setPredefines(Reader->getSuggestedPredefines());
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000756 PP.setCounterValue(Counter);
Mike Stump11289f42009-09-09 15:08:12 +0000757
Sebastian Redl2c499f62010-08-18 23:56:43 +0000758 // Attach the AST reader to the AST context as an external AST
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000759 // source, so that declarations will be deserialized from the
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000760 // AST file as needed.
Sebastian Redl2c499f62010-08-18 23:56:43 +0000761 ASTReader *ReaderPtr = Reader.get();
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000762 llvm::OwningPtr<ExternalASTSource> Source(Reader.take());
Ted Kremenek2159b8d2011-05-04 23:27:12 +0000763
764 // Unregister the cleanup for ASTReader. It will get cleaned up
765 // by the ASTUnit cleanup.
766 ReaderCleanup.unregister();
767
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000768 Context.setExternalSource(Source);
769
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000770 // Create an AST consumer, even though it isn't used.
771 AST->Consumer.reset(new ASTConsumer);
772
Sebastian Redl2c499f62010-08-18 23:56:43 +0000773 // Create a semantic analysis object and tell the AST reader about it.
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000774 AST->TheSema.reset(new Sema(PP, Context, *AST->Consumer));
775 AST->TheSema->Initialize();
776 ReaderPtr->InitializeSema(*AST->TheSema);
777
Mike Stump11289f42009-09-09 15:08:12 +0000778 return AST.take();
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000779}
Daniel Dunbar764c0822009-12-01 09:51:01 +0000780
781namespace {
782
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000783/// \brief Preprocessor callback class that updates a hash value with the names
784/// of all macros that have been defined by the translation unit.
785class MacroDefinitionTrackerPPCallbacks : public PPCallbacks {
786 unsigned &Hash;
787
788public:
789 explicit MacroDefinitionTrackerPPCallbacks(unsigned &Hash) : Hash(Hash) { }
790
791 virtual void MacroDefined(const Token &MacroNameTok, const MacroInfo *MI) {
792 Hash = llvm::HashString(MacroNameTok.getIdentifierInfo()->getName(), Hash);
793 }
794};
795
796/// \brief Add the given declaration to the hash of all top-level entities.
797void AddTopLevelDeclarationToHash(Decl *D, unsigned &Hash) {
798 if (!D)
799 return;
800
801 DeclContext *DC = D->getDeclContext();
802 if (!DC)
803 return;
804
805 if (!(DC->isTranslationUnit() || DC->getLookupParent()->isTranslationUnit()))
806 return;
807
808 if (NamedDecl *ND = dyn_cast<NamedDecl>(D)) {
809 if (ND->getIdentifier())
810 Hash = llvm::HashString(ND->getIdentifier()->getName(), Hash);
811 else if (DeclarationName Name = ND->getDeclName()) {
812 std::string NameStr = Name.getAsString();
813 Hash = llvm::HashString(NameStr, Hash);
814 }
815 return;
816 }
817
818 if (ObjCForwardProtocolDecl *Forward
819 = dyn_cast<ObjCForwardProtocolDecl>(D)) {
820 for (ObjCForwardProtocolDecl::protocol_iterator
821 P = Forward->protocol_begin(),
822 PEnd = Forward->protocol_end();
823 P != PEnd; ++P)
824 AddTopLevelDeclarationToHash(*P, Hash);
825 return;
826 }
827
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000828 if (ObjCClassDecl *Class = dyn_cast<ObjCClassDecl>(D)) {
Fariborz Jahanian3a039e32011-08-27 20:50:59 +0000829 AddTopLevelDeclarationToHash(Class->getForwardInterfaceDecl(), Hash);
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000830 return;
831 }
832}
833
Daniel Dunbar644dca02009-12-04 08:17:33 +0000834class TopLevelDeclTrackerConsumer : public ASTConsumer {
835 ASTUnit &Unit;
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000836 unsigned &Hash;
837
Daniel Dunbar644dca02009-12-04 08:17:33 +0000838public:
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000839 TopLevelDeclTrackerConsumer(ASTUnit &_Unit, unsigned &Hash)
840 : Unit(_Unit), Hash(Hash) {
841 Hash = 0;
842 }
843
Daniel Dunbar644dca02009-12-04 08:17:33 +0000844 void HandleTopLevelDecl(DeclGroupRef D) {
Ted Kremenekacc59c32010-05-03 20:16:35 +0000845 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
846 Decl *D = *it;
847 // FIXME: Currently ObjC method declarations are incorrectly being
848 // reported as top-level declarations, even though their DeclContext
849 // is the containing ObjC @interface/@implementation. This is a
850 // fundamental problem in the parser right now.
851 if (isa<ObjCMethodDecl>(D))
852 continue;
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000853
854 AddTopLevelDeclarationToHash(D, Hash);
Douglas Gregore9db88f2010-08-03 19:06:41 +0000855 Unit.addTopLevelDecl(D);
Ted Kremenekacc59c32010-05-03 20:16:35 +0000856 }
Daniel Dunbar644dca02009-12-04 08:17:33 +0000857 }
Sebastian Redleaa4ade2010-08-11 18:52:41 +0000858
859 // We're not interested in "interesting" decls.
860 void HandleInterestingDecl(DeclGroupRef) {}
Daniel Dunbar644dca02009-12-04 08:17:33 +0000861};
862
863class TopLevelDeclTrackerAction : public ASTFrontendAction {
864public:
865 ASTUnit &Unit;
866
Daniel Dunbar764c0822009-12-01 09:51:01 +0000867 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000868 StringRef InFile) {
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000869 CI.getPreprocessor().addPPCallbacks(
870 new MacroDefinitionTrackerPPCallbacks(Unit.getCurrentTopLevelHashValue()));
871 return new TopLevelDeclTrackerConsumer(Unit,
872 Unit.getCurrentTopLevelHashValue());
Daniel Dunbar764c0822009-12-01 09:51:01 +0000873 }
874
875public:
Daniel Dunbar644dca02009-12-04 08:17:33 +0000876 TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {}
877
Daniel Dunbar764c0822009-12-01 09:51:01 +0000878 virtual bool hasCodeCompletionSupport() const { return false; }
Douglas Gregor69f74f82011-08-25 22:30:56 +0000879 virtual TranslationUnitKind getTranslationUnitKind() {
880 return Unit.getTranslationUnitKind();
Douglas Gregor028d3e42010-08-09 20:45:32 +0000881 }
Daniel Dunbar764c0822009-12-01 09:51:01 +0000882};
883
Argyrios Kyrtzidis57332712011-09-19 20:40:48 +0000884class PrecompilePreambleConsumer : public PCHGenerator {
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000885 ASTUnit &Unit;
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000886 unsigned &Hash;
Douglas Gregore9db88f2010-08-03 19:06:41 +0000887 std::vector<Decl *> TopLevelDecls;
Douglas Gregorf88e35b2010-11-30 06:16:57 +0000888
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000889public:
Douglas Gregor36db4f92011-08-25 22:35:51 +0000890 PrecompilePreambleConsumer(ASTUnit &Unit, const Preprocessor &PP,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000891 StringRef isysroot, raw_ostream *Out)
Douglas Gregor4a69c2e2011-09-01 17:04:32 +0000892 : PCHGenerator(PP, "", /*IsModule=*/false, isysroot, Out), Unit(Unit),
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000893 Hash(Unit.getCurrentTopLevelHashValue()) {
894 Hash = 0;
895 }
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000896
Douglas Gregore9db88f2010-08-03 19:06:41 +0000897 virtual void HandleTopLevelDecl(DeclGroupRef D) {
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000898 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
899 Decl *D = *it;
900 // FIXME: Currently ObjC method declarations are incorrectly being
901 // reported as top-level declarations, even though their DeclContext
902 // is the containing ObjC @interface/@implementation. This is a
903 // fundamental problem in the parser right now.
904 if (isa<ObjCMethodDecl>(D))
905 continue;
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000906 AddTopLevelDeclarationToHash(D, Hash);
Douglas Gregore9db88f2010-08-03 19:06:41 +0000907 TopLevelDecls.push_back(D);
908 }
909 }
910
911 virtual void HandleTranslationUnit(ASTContext &Ctx) {
912 PCHGenerator::HandleTranslationUnit(Ctx);
913 if (!Unit.getDiagnostics().hasErrorOccurred()) {
914 // Translate the top-level declarations we captured during
915 // parsing into declaration IDs in the precompiled
916 // preamble. This will allow us to deserialize those top-level
917 // declarations when requested.
918 for (unsigned I = 0, N = TopLevelDecls.size(); I != N; ++I)
919 Unit.addTopLevelDeclFromPreamble(
920 getWriter().getDeclID(TopLevelDecls[I]));
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000921 }
922 }
923};
924
925class PrecompilePreambleAction : public ASTFrontendAction {
926 ASTUnit &Unit;
927
928public:
929 explicit PrecompilePreambleAction(ASTUnit &Unit) : Unit(Unit) {}
930
931 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000932 StringRef InFile) {
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000933 std::string Sysroot;
Argyrios Kyrtzidis10b23682011-02-15 17:54:22 +0000934 std::string OutputFile;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000935 raw_ostream *OS = 0;
Argyrios Kyrtzidis10b23682011-02-15 17:54:22 +0000936 if (GeneratePCHAction::ComputeASTConsumerArguments(CI, InFile, Sysroot,
937 OutputFile,
Douglas Gregor36db4f92011-08-25 22:35:51 +0000938 OS))
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000939 return 0;
940
Douglas Gregorc567ba22011-07-22 16:35:34 +0000941 if (!CI.getFrontendOpts().RelocatablePCH)
942 Sysroot.clear();
943
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000944 CI.getPreprocessor().addPPCallbacks(
945 new MacroDefinitionTrackerPPCallbacks(Unit.getCurrentTopLevelHashValue()));
Douglas Gregor36db4f92011-08-25 22:35:51 +0000946 return new PrecompilePreambleConsumer(Unit, CI.getPreprocessor(), Sysroot,
947 OS);
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000948 }
949
950 virtual bool hasCodeCompletionSupport() const { return false; }
951 virtual bool hasASTFileSupport() const { return false; }
Douglas Gregor69f74f82011-08-25 22:30:56 +0000952 virtual TranslationUnitKind getTranslationUnitKind() { return TU_Prefix; }
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000953};
954
Daniel Dunbar764c0822009-12-01 09:51:01 +0000955}
956
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000957/// Parse the source file into a translation unit using the given compiler
958/// invocation, replacing the current translation unit.
959///
960/// \returns True if a failure occurred that causes the ASTUnit not to
961/// contain any translation-unit information, false otherwise.
Douglas Gregor6481ef12010-07-24 00:38:13 +0000962bool ASTUnit::Parse(llvm::MemoryBuffer *OverrideMainBuffer) {
Douglas Gregor96c04262010-07-27 14:52:07 +0000963 delete SavedMainFileBuffer;
964 SavedMainFileBuffer = 0;
965
Ted Kremenek5e14d392011-03-21 18:40:17 +0000966 if (!Invocation) {
Douglas Gregora0734c52010-08-19 01:33:06 +0000967 delete OverrideMainBuffer;
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000968 return true;
Douglas Gregora0734c52010-08-19 01:33:06 +0000969 }
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000970
Daniel Dunbar764c0822009-12-01 09:51:01 +0000971 // Create the compiler instance to use for building the AST.
Ted Kremenek84de4a12011-03-21 18:40:07 +0000972 llvm::OwningPtr<CompilerInstance> Clang(new CompilerInstance());
973
974 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +0000975 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
976 CICleanup(Clang.get());
Ted Kremenek84de4a12011-03-21 18:40:07 +0000977
Argyrios Kyrtzidis14c32e82011-09-12 18:09:38 +0000978 llvm::IntrusiveRefCntPtr<CompilerInvocation>
979 CCInvocation(new CompilerInvocation(*Invocation));
980
981 Clang->setInvocation(CCInvocation.getPtr());
Ted Kremenek84de4a12011-03-21 18:40:07 +0000982 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].second;
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000983
Douglas Gregor8e984da2010-08-04 16:47:14 +0000984 // Set up diagnostics, capturing any diagnostics that would
985 // otherwise be dropped.
Ted Kremenek84de4a12011-03-21 18:40:07 +0000986 Clang->setDiagnostics(&getDiagnostics());
Douglas Gregord03e8232010-04-05 21:10:19 +0000987
Daniel Dunbar764c0822009-12-01 09:51:01 +0000988 // Create the target instance.
Ted Kremenek84de4a12011-03-21 18:40:07 +0000989 Clang->getTargetOpts().Features = TargetFeatures;
990 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
Ted Kremenek5e14d392011-03-21 18:40:17 +0000991 Clang->getTargetOpts()));
Ted Kremenek84de4a12011-03-21 18:40:07 +0000992 if (!Clang->hasTarget()) {
Douglas Gregora0734c52010-08-19 01:33:06 +0000993 delete OverrideMainBuffer;
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000994 return true;
Douglas Gregora0734c52010-08-19 01:33:06 +0000995 }
996
Daniel Dunbar764c0822009-12-01 09:51:01 +0000997 // Inform the target of the language options.
998 //
999 // FIXME: We shouldn't need to do this, the target should be immutable once
1000 // created. This complexity should be lifted elsewhere.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001001 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001002
Ted Kremenek84de4a12011-03-21 18:40:07 +00001003 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Daniel Dunbar764c0822009-12-01 09:51:01 +00001004 "Invocation must have exactly one source file!");
Ted Kremenek84de4a12011-03-21 18:40:07 +00001005 assert(Clang->getFrontendOpts().Inputs[0].first != IK_AST &&
Daniel Dunbar764c0822009-12-01 09:51:01 +00001006 "FIXME: AST inputs not yet supported here!");
Ted Kremenek84de4a12011-03-21 18:40:07 +00001007 assert(Clang->getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
Daniel Dunbar9507f9c2010-06-07 23:26:47 +00001008 "IR inputs not support here!");
Daniel Dunbar764c0822009-12-01 09:51:01 +00001009
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001010 // Configure the various subsystems.
1011 // FIXME: Should we retain the previous file manager?
Ted Kremenek84de4a12011-03-21 18:40:07 +00001012 FileSystemOpts = Clang->getFileSystemOpts();
Ted Kremenek5e14d392011-03-21 18:40:17 +00001013 FileMgr = new FileManager(FileSystemOpts);
1014 SourceMgr = new SourceManager(getDiagnostics(), *FileMgr);
Douglas Gregor6fd55e02010-08-13 03:15:25 +00001015 TheSema.reset();
Ted Kremenek5e14d392011-03-21 18:40:17 +00001016 Ctx = 0;
1017 PP = 0;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001018
1019 // Clear out old caches and data.
1020 TopLevelDecls.clear();
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001021 CleanTemporaryFiles();
Douglas Gregord9a30af2010-08-02 20:51:39 +00001022
Douglas Gregor7b02b582010-08-20 00:02:33 +00001023 if (!OverrideMainBuffer) {
Argyrios Kyrtzidis067cbfa2011-10-24 17:25:20 +00001024 StoredDiagnostics.erase(stored_diag_afterDriver_begin(), stored_diag_end());
Douglas Gregor7b02b582010-08-20 00:02:33 +00001025 TopLevelDeclsInPreamble.clear();
1026 }
1027
Daniel Dunbar764c0822009-12-01 09:51:01 +00001028 // Create a file manager object to provide access to and cache the filesystem.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001029 Clang->setFileManager(&getFileManager());
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001030
Daniel Dunbar764c0822009-12-01 09:51:01 +00001031 // Create the source manager.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001032 Clang->setSourceManager(&getSourceManager());
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001033
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001034 // If the main file has been overridden due to the use of a preamble,
1035 // make that override happen and introduce the preamble.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001036 PreprocessorOptions &PreprocessorOpts = Clang->getPreprocessorOpts();
Chandler Carruthde81fc82011-07-14 09:02:10 +00001037 PreprocessorOpts.DetailedRecordIncludesNestedMacroExpansions
1038 = NestedMacroExpansions;
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001039 if (OverrideMainBuffer) {
1040 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
1041 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
1042 PreprocessorOpts.PrecompiledPreambleBytes.second
1043 = PreambleEndsAtStartOfLine;
Ted Kremenek06b4f912011-10-27 17:55:18 +00001044 PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
Douglas Gregorce3a8292010-07-27 00:27:13 +00001045 PreprocessorOpts.DisablePCHValidation = true;
Douglas Gregor96c04262010-07-27 14:52:07 +00001046
Douglas Gregord9a30af2010-08-02 20:51:39 +00001047 // The stored diagnostic has the old source manager in it; update
1048 // the locations to refer into the new source manager. Since we've
1049 // been careful to make sure that the source manager's state
1050 // before and after are identical, so that we can reuse the source
1051 // location itself.
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001052 for (unsigned I = NumStoredDiagnosticsFromDriver,
1053 N = StoredDiagnostics.size();
1054 I < N; ++I) {
Douglas Gregord9a30af2010-08-02 20:51:39 +00001055 FullSourceLoc Loc(StoredDiagnostics[I].getLocation(),
1056 getSourceManager());
1057 StoredDiagnostics[I].setLocation(Loc);
1058 }
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001059
1060 // Keep track of the override buffer;
1061 SavedMainFileBuffer = OverrideMainBuffer;
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001062 }
1063
Ted Kremenek022a4902011-03-22 01:15:24 +00001064 llvm::OwningPtr<TopLevelDeclTrackerAction> Act(
1065 new TopLevelDeclTrackerAction(*this));
1066
1067 // Recover resources if we crash before exiting this method.
1068 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1069 ActCleanup(Act.get());
1070
Ted Kremenek84de4a12011-03-21 18:40:07 +00001071 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0].second,
1072 Clang->getFrontendOpts().Inputs[0].first))
Daniel Dunbar764c0822009-12-01 09:51:01 +00001073 goto error;
Douglas Gregor925296b2011-07-19 16:10:42 +00001074
1075 if (OverrideMainBuffer) {
Ted Kremenek06b4f912011-10-27 17:55:18 +00001076 std::string ModName = getPreambleFile(this);
Douglas Gregor925296b2011-07-19 16:10:42 +00001077 TranslateStoredDiagnostics(Clang->getModuleManager(), ModName,
1078 getSourceManager(), PreambleDiagnostics,
1079 StoredDiagnostics);
1080 }
1081
Daniel Dunbar644dca02009-12-04 08:17:33 +00001082 Act->Execute();
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001083
Ted Kremenek5e14d392011-03-21 18:40:17 +00001084 // Steal the created target, context, and preprocessor.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001085 TheSema.reset(Clang->takeSema());
1086 Consumer.reset(Clang->takeASTConsumer());
Ted Kremenek5e14d392011-03-21 18:40:17 +00001087 Ctx = &Clang->getASTContext();
1088 PP = &Clang->getPreprocessor();
1089 Clang->setSourceManager(0);
1090 Clang->setFileManager(0);
1091 Target = &Clang->getTarget();
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001092
Daniel Dunbar644dca02009-12-04 08:17:33 +00001093 Act->EndSourceFile();
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001094
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001095 return false;
Ted Kremenek5e14d392011-03-21 18:40:17 +00001096
Daniel Dunbar764c0822009-12-01 09:51:01 +00001097error:
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001098 // Remove the overridden buffer we used for the preamble.
Douglas Gregorce3a8292010-07-27 00:27:13 +00001099 if (OverrideMainBuffer) {
Douglas Gregora0734c52010-08-19 01:33:06 +00001100 delete OverrideMainBuffer;
Douglas Gregora3d3ba12010-10-06 21:11:08 +00001101 SavedMainFileBuffer = 0;
Douglas Gregorce3a8292010-07-27 00:27:13 +00001102 }
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001103
Douglas Gregorefc46952010-10-12 16:25:54 +00001104 StoredDiagnostics.clear();
Argyrios Kyrtzidis067cbfa2011-10-24 17:25:20 +00001105 NumStoredDiagnosticsFromDriver = 0;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001106 return true;
1107}
1108
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001109/// \brief Simple function to retrieve a path for a preamble precompiled header.
1110static std::string GetPreamblePCHPath() {
1111 // FIXME: This is lame; sys::Path should provide this function (in particular,
1112 // it should know how to find the temporary files dir).
1113 // FIXME: This is really lame. I copied this code from the Driver!
Douglas Gregor250ab1d2010-09-11 18:05:19 +00001114 // FIXME: This is a hack so that we can override the preamble file during
1115 // crash-recovery testing, which is the only case where the preamble files
1116 // are not necessarily cleaned up.
1117 const char *TmpFile = ::getenv("CINDEXTEST_PREAMBLE_FILE");
1118 if (TmpFile)
1119 return TmpFile;
1120
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001121 std::string Error;
1122 const char *TmpDir = ::getenv("TMPDIR");
1123 if (!TmpDir)
1124 TmpDir = ::getenv("TEMP");
1125 if (!TmpDir)
1126 TmpDir = ::getenv("TMP");
Douglas Gregorce3449f2010-09-11 17:51:16 +00001127#ifdef LLVM_ON_WIN32
1128 if (!TmpDir)
1129 TmpDir = ::getenv("USERPROFILE");
1130#endif
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001131 if (!TmpDir)
1132 TmpDir = "/tmp";
1133 llvm::sys::Path P(TmpDir);
Douglas Gregorce3449f2010-09-11 17:51:16 +00001134 P.createDirectoryOnDisk(true);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001135 P.appendComponent("preamble");
Douglas Gregor20975b22010-08-11 13:06:56 +00001136 P.appendSuffix("pch");
Argyrios Kyrtzidisff9a5502011-07-21 18:44:46 +00001137 if (P.makeUnique(/*reuse_current=*/false, /*ErrMsg*/0))
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001138 return std::string();
1139
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001140 return P.str();
1141}
1142
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001143/// \brief Compute the preamble for the main file, providing the source buffer
1144/// that corresponds to the main file along with a pair (bytes, start-of-line)
1145/// that describes the preamble.
1146std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> >
Douglas Gregor028d3e42010-08-09 20:45:32 +00001147ASTUnit::ComputePreamble(CompilerInvocation &Invocation,
1148 unsigned MaxLines, bool &CreatedBuffer) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001149 FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
Chris Lattner5159f612010-11-23 08:35:12 +00001150 PreprocessorOptions &PreprocessorOpts = Invocation.getPreprocessorOpts();
Douglas Gregor4dde7492010-07-23 23:58:40 +00001151 CreatedBuffer = false;
1152
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001153 // Try to determine if the main file has been remapped, either from the
1154 // command line (to another file) or directly through the compiler invocation
1155 // (to a memory buffer).
Douglas Gregor4dde7492010-07-23 23:58:40 +00001156 llvm::MemoryBuffer *Buffer = 0;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001157 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].second);
1158 if (const llvm::sys::FileStatus *MainFileStatus = MainFilePath.getFileStatus()) {
1159 // Check whether there is a file-file remapping of the main file
1160 for (PreprocessorOptions::remapped_file_iterator
Douglas Gregor4dde7492010-07-23 23:58:40 +00001161 M = PreprocessorOpts.remapped_file_begin(),
1162 E = PreprocessorOpts.remapped_file_end();
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001163 M != E;
1164 ++M) {
1165 llvm::sys::PathWithStatus MPath(M->first);
1166 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
1167 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
1168 // We found a remapping. Try to load the resulting, remapped source.
Douglas Gregor4dde7492010-07-23 23:58:40 +00001169 if (CreatedBuffer) {
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001170 delete Buffer;
Douglas Gregor4dde7492010-07-23 23:58:40 +00001171 CreatedBuffer = false;
1172 }
1173
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +00001174 Buffer = getBufferForFile(M->second);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001175 if (!Buffer)
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001176 return std::make_pair((llvm::MemoryBuffer*)0,
1177 std::make_pair(0, true));
Douglas Gregor4dde7492010-07-23 23:58:40 +00001178 CreatedBuffer = true;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001179 }
1180 }
1181 }
1182
1183 // Check whether there is a file-buffer remapping. It supercedes the
1184 // file-file remapping.
1185 for (PreprocessorOptions::remapped_file_buffer_iterator
1186 M = PreprocessorOpts.remapped_file_buffer_begin(),
1187 E = PreprocessorOpts.remapped_file_buffer_end();
1188 M != E;
1189 ++M) {
1190 llvm::sys::PathWithStatus MPath(M->first);
1191 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
1192 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
1193 // We found a remapping.
Douglas Gregor4dde7492010-07-23 23:58:40 +00001194 if (CreatedBuffer) {
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001195 delete Buffer;
Douglas Gregor4dde7492010-07-23 23:58:40 +00001196 CreatedBuffer = false;
1197 }
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001198
Douglas Gregor4dde7492010-07-23 23:58:40 +00001199 Buffer = const_cast<llvm::MemoryBuffer *>(M->second);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001200 }
1201 }
Douglas Gregor4dde7492010-07-23 23:58:40 +00001202 }
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001203 }
1204
1205 // If the main source file was not remapped, load it now.
1206 if (!Buffer) {
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +00001207 Buffer = getBufferForFile(FrontendOpts.Inputs[0].second);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001208 if (!Buffer)
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001209 return std::make_pair((llvm::MemoryBuffer*)0, std::make_pair(0, true));
Douglas Gregor4dde7492010-07-23 23:58:40 +00001210
1211 CreatedBuffer = true;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001212 }
1213
Argyrios Kyrtzidis7aecbc72011-08-25 20:39:19 +00001214 return std::make_pair(Buffer, Lexer::ComputePreamble(Buffer,
1215 Invocation.getLangOpts(),
1216 MaxLines));
Douglas Gregor4dde7492010-07-23 23:58:40 +00001217}
1218
Douglas Gregor6481ef12010-07-24 00:38:13 +00001219static llvm::MemoryBuffer *CreatePaddedMainFileBuffer(llvm::MemoryBuffer *Old,
Douglas Gregor6481ef12010-07-24 00:38:13 +00001220 unsigned NewSize,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001221 StringRef NewName) {
Douglas Gregor6481ef12010-07-24 00:38:13 +00001222 llvm::MemoryBuffer *Result
1223 = llvm::MemoryBuffer::getNewUninitMemBuffer(NewSize, NewName);
1224 memcpy(const_cast<char*>(Result->getBufferStart()),
1225 Old->getBufferStart(), Old->getBufferSize());
1226 memset(const_cast<char*>(Result->getBufferStart()) + Old->getBufferSize(),
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001227 ' ', NewSize - Old->getBufferSize() - 1);
1228 const_cast<char*>(Result->getBufferEnd())[-1] = '\n';
Douglas Gregor6481ef12010-07-24 00:38:13 +00001229
Douglas Gregor6481ef12010-07-24 00:38:13 +00001230 return Result;
1231}
1232
Douglas Gregor4dde7492010-07-23 23:58:40 +00001233/// \brief Attempt to build or re-use a precompiled preamble when (re-)parsing
1234/// the source file.
1235///
1236/// This routine will compute the preamble of the main source file. If a
1237/// non-trivial preamble is found, it will precompile that preamble into a
1238/// precompiled header so that the precompiled preamble can be used to reduce
1239/// reparsing time. If a precompiled preamble has already been constructed,
1240/// this routine will determine if it is still valid and, if so, avoid
1241/// rebuilding the precompiled preamble.
1242///
Douglas Gregor028d3e42010-08-09 20:45:32 +00001243/// \param AllowRebuild When true (the default), this routine is
1244/// allowed to rebuild the precompiled preamble if it is found to be
1245/// out-of-date.
1246///
1247/// \param MaxLines When non-zero, the maximum number of lines that
1248/// can occur within the preamble.
1249///
Douglas Gregor6481ef12010-07-24 00:38:13 +00001250/// \returns If the precompiled preamble can be used, returns a newly-allocated
1251/// buffer that should be used in place of the main file when doing so.
1252/// Otherwise, returns a NULL pointer.
Douglas Gregor028d3e42010-08-09 20:45:32 +00001253llvm::MemoryBuffer *ASTUnit::getMainBufferWithPrecompiledPreamble(
Douglas Gregor3cc15812011-07-01 18:22:13 +00001254 const CompilerInvocation &PreambleInvocationIn,
Douglas Gregor028d3e42010-08-09 20:45:32 +00001255 bool AllowRebuild,
1256 unsigned MaxLines) {
Douglas Gregor3cc15812011-07-01 18:22:13 +00001257
1258 llvm::IntrusiveRefCntPtr<CompilerInvocation>
1259 PreambleInvocation(new CompilerInvocation(PreambleInvocationIn));
1260 FrontendOptions &FrontendOpts = PreambleInvocation->getFrontendOpts();
Douglas Gregor4dde7492010-07-23 23:58:40 +00001261 PreprocessorOptions &PreprocessorOpts
Douglas Gregor3cc15812011-07-01 18:22:13 +00001262 = PreambleInvocation->getPreprocessorOpts();
Douglas Gregor4dde7492010-07-23 23:58:40 +00001263
1264 bool CreatedPreambleBuffer = false;
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001265 std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> > NewPreamble
Douglas Gregor3cc15812011-07-01 18:22:13 +00001266 = ComputePreamble(*PreambleInvocation, MaxLines, CreatedPreambleBuffer);
Douglas Gregor4dde7492010-07-23 23:58:40 +00001267
Douglas Gregor925296b2011-07-19 16:10:42 +00001268 // If ComputePreamble() Take ownership of the preamble buffer.
Douglas Gregor3edb1672010-11-16 20:45:51 +00001269 llvm::OwningPtr<llvm::MemoryBuffer> OwnedPreambleBuffer;
1270 if (CreatedPreambleBuffer)
1271 OwnedPreambleBuffer.reset(NewPreamble.first);
1272
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001273 if (!NewPreamble.second.first) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001274 // We couldn't find a preamble in the main source. Clear out the current
1275 // preamble, if we have one. It's obviously no good any more.
1276 Preamble.clear();
Ted Kremenek06b4f912011-10-27 17:55:18 +00001277 erasePreambleFile(this);
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001278
1279 // The next time we actually see a preamble, precompile it.
1280 PreambleRebuildCounter = 1;
Douglas Gregor6481ef12010-07-24 00:38:13 +00001281 return 0;
Douglas Gregor4dde7492010-07-23 23:58:40 +00001282 }
1283
1284 if (!Preamble.empty()) {
1285 // We've previously computed a preamble. Check whether we have the same
1286 // preamble now that we did before, and that there's enough space in
1287 // the main-file buffer within the precompiled preamble to fit the
1288 // new main file.
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001289 if (Preamble.size() == NewPreamble.second.first &&
1290 PreambleEndsAtStartOfLine == NewPreamble.second.second &&
Douglas Gregorf5275a82010-07-24 00:42:07 +00001291 NewPreamble.first->getBufferSize() < PreambleReservedSize-2 &&
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00001292 memcmp(Preamble.getBufferStart(), NewPreamble.first->getBufferStart(),
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001293 NewPreamble.second.first) == 0) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001294 // The preamble has not changed. We may be able to re-use the precompiled
1295 // preamble.
Douglas Gregord9a30af2010-08-02 20:51:39 +00001296
Douglas Gregor0e119552010-07-31 00:40:00 +00001297 // Check that none of the files used by the preamble have changed.
1298 bool AnyFileChanged = false;
1299
1300 // First, make a record of those files that have been overridden via
1301 // remapping or unsaved_files.
1302 llvm::StringMap<std::pair<off_t, time_t> > OverriddenFiles;
1303 for (PreprocessorOptions::remapped_file_iterator
1304 R = PreprocessorOpts.remapped_file_begin(),
1305 REnd = PreprocessorOpts.remapped_file_end();
1306 !AnyFileChanged && R != REnd;
1307 ++R) {
1308 struct stat StatBuf;
Anders Carlsson9583f792011-03-18 19:23:38 +00001309 if (FileMgr->getNoncachedStatValue(R->second, StatBuf)) {
Douglas Gregor0e119552010-07-31 00:40:00 +00001310 // If we can't stat the file we're remapping to, assume that something
1311 // horrible happened.
1312 AnyFileChanged = true;
1313 break;
1314 }
Douglas Gregor6481ef12010-07-24 00:38:13 +00001315
Douglas Gregor0e119552010-07-31 00:40:00 +00001316 OverriddenFiles[R->first] = std::make_pair(StatBuf.st_size,
1317 StatBuf.st_mtime);
1318 }
1319 for (PreprocessorOptions::remapped_file_buffer_iterator
1320 R = PreprocessorOpts.remapped_file_buffer_begin(),
1321 REnd = PreprocessorOpts.remapped_file_buffer_end();
1322 !AnyFileChanged && R != REnd;
1323 ++R) {
1324 // FIXME: Should we actually compare the contents of file->buffer
1325 // remappings?
1326 OverriddenFiles[R->first] = std::make_pair(R->second->getBufferSize(),
1327 0);
1328 }
1329
1330 // Check whether anything has changed.
1331 for (llvm::StringMap<std::pair<off_t, time_t> >::iterator
1332 F = FilesInPreamble.begin(), FEnd = FilesInPreamble.end();
1333 !AnyFileChanged && F != FEnd;
1334 ++F) {
1335 llvm::StringMap<std::pair<off_t, time_t> >::iterator Overridden
1336 = OverriddenFiles.find(F->first());
1337 if (Overridden != OverriddenFiles.end()) {
1338 // This file was remapped; check whether the newly-mapped file
1339 // matches up with the previous mapping.
1340 if (Overridden->second != F->second)
1341 AnyFileChanged = true;
1342 continue;
1343 }
1344
1345 // The file was not remapped; check whether it has changed on disk.
1346 struct stat StatBuf;
Anders Carlsson9583f792011-03-18 19:23:38 +00001347 if (FileMgr->getNoncachedStatValue(F->first(), StatBuf)) {
Douglas Gregor0e119552010-07-31 00:40:00 +00001348 // If we can't stat the file, assume that something horrible happened.
1349 AnyFileChanged = true;
1350 } else if (StatBuf.st_size != F->second.first ||
1351 StatBuf.st_mtime != F->second.second)
1352 AnyFileChanged = true;
1353 }
1354
1355 if (!AnyFileChanged) {
Douglas Gregord9a30af2010-08-02 20:51:39 +00001356 // Okay! We can re-use the precompiled preamble.
1357
1358 // Set the state of the diagnostic object to mimic its state
1359 // after parsing the preamble.
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00001360 // FIXME: This won't catch any #pragma push warning changes that
1361 // have occurred in the preamble.
Douglas Gregord9a30af2010-08-02 20:51:39 +00001362 getDiagnostics().Reset();
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00001363 ProcessWarningOptions(getDiagnostics(),
Douglas Gregor3cc15812011-07-01 18:22:13 +00001364 PreambleInvocation->getDiagnosticOpts());
Douglas Gregord9a30af2010-08-02 20:51:39 +00001365 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
Douglas Gregord9a30af2010-08-02 20:51:39 +00001366
1367 // Create a version of the main file buffer that is padded to
1368 // buffer size we reserved when creating the preamble.
Douglas Gregor0e119552010-07-31 00:40:00 +00001369 return CreatePaddedMainFileBuffer(NewPreamble.first,
Douglas Gregor0e119552010-07-31 00:40:00 +00001370 PreambleReservedSize,
1371 FrontendOpts.Inputs[0].second);
1372 }
Douglas Gregor4dde7492010-07-23 23:58:40 +00001373 }
Douglas Gregor028d3e42010-08-09 20:45:32 +00001374
1375 // If we aren't allowed to rebuild the precompiled preamble, just
1376 // return now.
1377 if (!AllowRebuild)
1378 return 0;
Douglas Gregorbb6a8812010-10-08 04:03:57 +00001379
Douglas Gregor4dde7492010-07-23 23:58:40 +00001380 // We can't reuse the previously-computed preamble. Build a new one.
1381 Preamble.clear();
Douglas Gregor925296b2011-07-19 16:10:42 +00001382 PreambleDiagnostics.clear();
Ted Kremenek06b4f912011-10-27 17:55:18 +00001383 erasePreambleFile(this);
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001384 PreambleRebuildCounter = 1;
Douglas Gregor028d3e42010-08-09 20:45:32 +00001385 } else if (!AllowRebuild) {
1386 // We aren't allowed to rebuild the precompiled preamble; just
1387 // return now.
1388 return 0;
1389 }
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001390
1391 // If the preamble rebuild counter > 1, it's because we previously
1392 // failed to build a preamble and we're not yet ready to try
1393 // again. Decrement the counter and return a failure.
1394 if (PreambleRebuildCounter > 1) {
1395 --PreambleRebuildCounter;
1396 return 0;
1397 }
1398
Douglas Gregore10f0e52010-09-11 17:56:52 +00001399 // Create a temporary file for the precompiled preamble. In rare
1400 // circumstances, this can fail.
1401 std::string PreamblePCHPath = GetPreamblePCHPath();
1402 if (PreamblePCHPath.empty()) {
1403 // Try again next time.
1404 PreambleRebuildCounter = 1;
1405 return 0;
1406 }
1407
Douglas Gregor4dde7492010-07-23 23:58:40 +00001408 // We did not previously compute a preamble, or it can't be reused anyway.
Douglas Gregor16896c42010-10-28 15:44:59 +00001409 SimpleTimer PreambleTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00001410 PreambleTimer.setOutput("Precompiling preamble");
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001411
1412 // Create a new buffer that stores the preamble. The buffer also contains
1413 // extra space for the original contents of the file (which will be present
1414 // when we actually parse the file) along with more room in case the file
Douglas Gregor4dde7492010-07-23 23:58:40 +00001415 // grows.
1416 PreambleReservedSize = NewPreamble.first->getBufferSize();
1417 if (PreambleReservedSize < 4096)
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001418 PreambleReservedSize = 8191;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001419 else
Douglas Gregor4dde7492010-07-23 23:58:40 +00001420 PreambleReservedSize *= 2;
1421
Douglas Gregord9a30af2010-08-02 20:51:39 +00001422 // Save the preamble text for later; we'll need to compare against it for
1423 // subsequent reparses.
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00001424 StringRef MainFilename = PreambleInvocation->getFrontendOpts().Inputs[0].second;
1425 Preamble.assign(FileMgr->getFile(MainFilename),
1426 NewPreamble.first->getBufferStart(),
Douglas Gregord9a30af2010-08-02 20:51:39 +00001427 NewPreamble.first->getBufferStart()
1428 + NewPreamble.second.first);
1429 PreambleEndsAtStartOfLine = NewPreamble.second.second;
1430
Douglas Gregora0734c52010-08-19 01:33:06 +00001431 delete PreambleBuffer;
1432 PreambleBuffer
Douglas Gregor4dde7492010-07-23 23:58:40 +00001433 = llvm::MemoryBuffer::getNewUninitMemBuffer(PreambleReservedSize,
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001434 FrontendOpts.Inputs[0].second);
1435 memcpy(const_cast<char*>(PreambleBuffer->getBufferStart()),
Douglas Gregor4dde7492010-07-23 23:58:40 +00001436 NewPreamble.first->getBufferStart(), Preamble.size());
1437 memset(const_cast<char*>(PreambleBuffer->getBufferStart()) + Preamble.size(),
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001438 ' ', PreambleReservedSize - Preamble.size() - 1);
1439 const_cast<char*>(PreambleBuffer->getBufferEnd())[-1] = '\n';
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001440
1441 // Remap the main source file to the preamble buffer.
Douglas Gregor4dde7492010-07-23 23:58:40 +00001442 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].second);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001443 PreprocessorOpts.addRemappedFile(MainFilePath.str(), PreambleBuffer);
1444
1445 // Tell the compiler invocation to generate a temporary precompiled header.
1446 FrontendOpts.ProgramAction = frontend::GeneratePCH;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001447 // FIXME: Generate the precompiled header into memory?
Douglas Gregore10f0e52010-09-11 17:56:52 +00001448 FrontendOpts.OutputFile = PreamblePCHPath;
Douglas Gregorbb6a8812010-10-08 04:03:57 +00001449 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
1450 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001451
1452 // Create the compiler instance to use for building the precompiled preamble.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001453 llvm::OwningPtr<CompilerInstance> Clang(new CompilerInstance());
1454
1455 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00001456 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1457 CICleanup(Clang.get());
Ted Kremenek84de4a12011-03-21 18:40:07 +00001458
Douglas Gregor3cc15812011-07-01 18:22:13 +00001459 Clang->setInvocation(&*PreambleInvocation);
Ted Kremenek84de4a12011-03-21 18:40:07 +00001460 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].second;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001461
Douglas Gregor8e984da2010-08-04 16:47:14 +00001462 // Set up diagnostics, capturing all of the diagnostics produced.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001463 Clang->setDiagnostics(&getDiagnostics());
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001464
1465 // Create the target instance.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001466 Clang->getTargetOpts().Features = TargetFeatures;
1467 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
1468 Clang->getTargetOpts()));
1469 if (!Clang->hasTarget()) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001470 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1471 Preamble.clear();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001472 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregora0734c52010-08-19 01:33:06 +00001473 PreprocessorOpts.eraseRemappedFile(
1474 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor6481ef12010-07-24 00:38:13 +00001475 return 0;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001476 }
1477
1478 // Inform the target of the language options.
1479 //
1480 // FIXME: We shouldn't need to do this, the target should be immutable once
1481 // created. This complexity should be lifted elsewhere.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001482 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001483
Ted Kremenek84de4a12011-03-21 18:40:07 +00001484 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001485 "Invocation must have exactly one source file!");
Ted Kremenek84de4a12011-03-21 18:40:07 +00001486 assert(Clang->getFrontendOpts().Inputs[0].first != IK_AST &&
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001487 "FIXME: AST inputs not yet supported here!");
Ted Kremenek84de4a12011-03-21 18:40:07 +00001488 assert(Clang->getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001489 "IR inputs not support here!");
1490
1491 // Clear out old caches and data.
Douglas Gregorbb6a8812010-10-08 04:03:57 +00001492 getDiagnostics().Reset();
Ted Kremenek84de4a12011-03-21 18:40:07 +00001493 ProcessWarningOptions(getDiagnostics(), Clang->getDiagnosticOpts());
Argyrios Kyrtzidis067cbfa2011-10-24 17:25:20 +00001494 StoredDiagnostics.erase(stored_diag_afterDriver_begin(), stored_diag_end());
Douglas Gregore9db88f2010-08-03 19:06:41 +00001495 TopLevelDecls.clear();
1496 TopLevelDeclsInPreamble.clear();
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001497
1498 // Create a file manager object to provide access to and cache the filesystem.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001499 Clang->setFileManager(new FileManager(Clang->getFileSystemOpts()));
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001500
1501 // Create the source manager.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001502 Clang->setSourceManager(new SourceManager(getDiagnostics(),
Ted Kremenek5e14d392011-03-21 18:40:17 +00001503 Clang->getFileManager()));
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001504
Douglas Gregor48c8cd32010-08-03 08:14:03 +00001505 llvm::OwningPtr<PrecompilePreambleAction> Act;
1506 Act.reset(new PrecompilePreambleAction(*this));
Ted Kremenek84de4a12011-03-21 18:40:07 +00001507 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0].second,
1508 Clang->getFrontendOpts().Inputs[0].first)) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001509 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1510 Preamble.clear();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001511 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregora0734c52010-08-19 01:33:06 +00001512 PreprocessorOpts.eraseRemappedFile(
1513 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor6481ef12010-07-24 00:38:13 +00001514 return 0;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001515 }
1516
1517 Act->Execute();
1518 Act->EndSourceFile();
Ted Kremenek5e14d392011-03-21 18:40:17 +00001519
Douglas Gregore9db88f2010-08-03 19:06:41 +00001520 if (Diagnostics->hasErrorOccurred()) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001521 // There were errors parsing the preamble, so no precompiled header was
1522 // generated. Forget that we even tried.
Douglas Gregora6f74e22010-09-27 16:43:25 +00001523 // FIXME: Should we leave a note for ourselves to try again?
Douglas Gregor4dde7492010-07-23 23:58:40 +00001524 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1525 Preamble.clear();
Douglas Gregore9db88f2010-08-03 19:06:41 +00001526 TopLevelDeclsInPreamble.clear();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001527 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregora0734c52010-08-19 01:33:06 +00001528 PreprocessorOpts.eraseRemappedFile(
1529 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor6481ef12010-07-24 00:38:13 +00001530 return 0;
Douglas Gregor4dde7492010-07-23 23:58:40 +00001531 }
1532
Douglas Gregor925296b2011-07-19 16:10:42 +00001533 // Transfer any diagnostics generated when parsing the preamble into the set
1534 // of preamble diagnostics.
1535 PreambleDiagnostics.clear();
1536 PreambleDiagnostics.insert(PreambleDiagnostics.end(),
Argyrios Kyrtzidis067cbfa2011-10-24 17:25:20 +00001537 stored_diag_afterDriver_begin(), stored_diag_end());
1538 StoredDiagnostics.erase(stored_diag_afterDriver_begin(), stored_diag_end());
Douglas Gregor925296b2011-07-19 16:10:42 +00001539
Douglas Gregor4dde7492010-07-23 23:58:40 +00001540 // Keep track of the preamble we precompiled.
Ted Kremenek06b4f912011-10-27 17:55:18 +00001541 setPreambleFile(this, FrontendOpts.OutputFile);
Douglas Gregord9a30af2010-08-02 20:51:39 +00001542 NumWarningsInPreamble = getDiagnostics().getNumWarnings();
Douglas Gregor0e119552010-07-31 00:40:00 +00001543
1544 // Keep track of all of the files that the source manager knows about,
1545 // so we can verify whether they have changed or not.
1546 FilesInPreamble.clear();
Ted Kremenek84de4a12011-03-21 18:40:07 +00001547 SourceManager &SourceMgr = Clang->getSourceManager();
Douglas Gregor0e119552010-07-31 00:40:00 +00001548 const llvm::MemoryBuffer *MainFileBuffer
1549 = SourceMgr.getBuffer(SourceMgr.getMainFileID());
1550 for (SourceManager::fileinfo_iterator F = SourceMgr.fileinfo_begin(),
1551 FEnd = SourceMgr.fileinfo_end();
1552 F != FEnd;
1553 ++F) {
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00001554 const FileEntry *File = F->second->OrigEntry;
Douglas Gregor0e119552010-07-31 00:40:00 +00001555 if (!File || F->second->getRawBuffer() == MainFileBuffer)
1556 continue;
1557
1558 FilesInPreamble[File->getName()]
1559 = std::make_pair(F->second->getSize(), File->getModificationTime());
1560 }
1561
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001562 PreambleRebuildCounter = 1;
Douglas Gregora0734c52010-08-19 01:33:06 +00001563 PreprocessorOpts.eraseRemappedFile(
1564 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregordf7a79a2011-02-16 18:16:54 +00001565
1566 // If the hash of top-level entities differs from the hash of the top-level
1567 // entities the last time we rebuilt the preamble, clear out the completion
1568 // cache.
1569 if (CurrentTopLevelHashValue != PreambleTopLevelHashValue) {
1570 CompletionCacheTopLevelHashValue = 0;
1571 PreambleTopLevelHashValue = CurrentTopLevelHashValue;
1572 }
1573
Douglas Gregor6481ef12010-07-24 00:38:13 +00001574 return CreatePaddedMainFileBuffer(NewPreamble.first,
Douglas Gregor6481ef12010-07-24 00:38:13 +00001575 PreambleReservedSize,
1576 FrontendOpts.Inputs[0].second);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001577}
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001578
Douglas Gregore9db88f2010-08-03 19:06:41 +00001579void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
1580 std::vector<Decl *> Resolved;
1581 Resolved.reserve(TopLevelDeclsInPreamble.size());
1582 ExternalASTSource &Source = *getASTContext().getExternalSource();
1583 for (unsigned I = 0, N = TopLevelDeclsInPreamble.size(); I != N; ++I) {
1584 // Resolve the declaration ID to an actual declaration, possibly
1585 // deserializing the declaration in the process.
1586 Decl *D = Source.GetExternalDecl(TopLevelDeclsInPreamble[I]);
1587 if (D)
1588 Resolved.push_back(D);
1589 }
1590 TopLevelDeclsInPreamble.clear();
1591 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1592}
1593
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001594StringRef ASTUnit::getMainFileName() const {
Douglas Gregor16896c42010-10-28 15:44:59 +00001595 return Invocation->getFrontendOpts().Inputs[0].second;
1596}
1597
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00001598ASTUnit *ASTUnit::create(CompilerInvocation *CI,
David Blaikie9c902b52011-09-25 23:23:43 +00001599 llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Diags) {
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00001600 llvm::OwningPtr<ASTUnit> AST;
1601 AST.reset(new ASTUnit(false));
1602 ConfigureDiags(Diags, 0, 0, *AST, /*CaptureDiagnostics=*/false);
1603 AST->Diagnostics = Diags;
Ted Kremenek5e14d392011-03-21 18:40:17 +00001604 AST->Invocation = CI;
Anders Carlssonc30dcec2011-03-18 18:22:40 +00001605 AST->FileSystemOpts = CI->getFileSystemOpts();
Ted Kremenek5e14d392011-03-21 18:40:17 +00001606 AST->FileMgr = new FileManager(AST->FileSystemOpts);
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001607 AST->SourceMgr = new SourceManager(AST->getDiagnostics(), *AST->FileMgr);
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00001608
1609 return AST.take();
1610}
1611
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001612ASTUnit *ASTUnit::LoadFromCompilerInvocationAction(CompilerInvocation *CI,
David Blaikie9c902b52011-09-25 23:23:43 +00001613 llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001614 ASTFrontendAction *Action,
1615 ASTUnit *Unit) {
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001616 assert(CI && "A CompilerInvocation is required");
1617
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001618 llvm::OwningPtr<ASTUnit> OwnAST;
1619 ASTUnit *AST = Unit;
1620 if (!AST) {
1621 // Create the AST unit.
1622 OwnAST.reset(create(CI, Diags));
1623 AST = OwnAST.get();
1624 }
1625
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001626 AST->OnlyLocalDecls = false;
1627 AST->CaptureDiagnostics = false;
Douglas Gregor69f74f82011-08-25 22:30:56 +00001628 AST->TUKind = Action ? Action->getTranslationUnitKind() : TU_Complete;
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001629 AST->ShouldCacheCodeCompletionResults = false;
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001630
1631 // Recover resources if we crash before exiting this method.
1632 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001633 ASTUnitCleanup(OwnAST.get());
David Blaikie9c902b52011-09-25 23:23:43 +00001634 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1635 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001636 DiagCleanup(Diags.getPtr());
1637
1638 // We'll manage file buffers ourselves.
1639 CI->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1640 CI->getFrontendOpts().DisableFree = false;
1641 ProcessWarningOptions(AST->getDiagnostics(), CI->getDiagnosticOpts());
1642
1643 // Save the target features.
1644 AST->TargetFeatures = CI->getTargetOpts().Features;
1645
1646 // Create the compiler instance to use for building the AST.
1647 llvm::OwningPtr<CompilerInstance> Clang(new CompilerInstance());
1648
1649 // Recover resources if we crash before exiting this method.
1650 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1651 CICleanup(Clang.get());
1652
1653 Clang->setInvocation(CI);
1654 AST->OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].second;
1655
1656 // Set up diagnostics, capturing any diagnostics that would
1657 // otherwise be dropped.
1658 Clang->setDiagnostics(&AST->getDiagnostics());
1659
1660 // Create the target instance.
1661 Clang->getTargetOpts().Features = AST->TargetFeatures;
1662 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
1663 Clang->getTargetOpts()));
1664 if (!Clang->hasTarget())
1665 return 0;
1666
1667 // Inform the target of the language options.
1668 //
1669 // FIXME: We shouldn't need to do this, the target should be immutable once
1670 // created. This complexity should be lifted elsewhere.
1671 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
1672
1673 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1674 "Invocation must have exactly one source file!");
1675 assert(Clang->getFrontendOpts().Inputs[0].first != IK_AST &&
1676 "FIXME: AST inputs not yet supported here!");
1677 assert(Clang->getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
1678 "IR inputs not supported here!");
1679
1680 // Configure the various subsystems.
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001681 AST->TheSema.reset();
1682 AST->Ctx = 0;
1683 AST->PP = 0;
1684
1685 // Create a file manager object to provide access to and cache the filesystem.
1686 Clang->setFileManager(&AST->getFileManager());
1687
1688 // Create the source manager.
1689 Clang->setSourceManager(&AST->getSourceManager());
1690
1691 ASTFrontendAction *Act = Action;
1692
1693 llvm::OwningPtr<TopLevelDeclTrackerAction> TrackerAct;
1694 if (!Act) {
1695 TrackerAct.reset(new TopLevelDeclTrackerAction(*AST));
1696 Act = TrackerAct.get();
1697 }
1698
1699 // Recover resources if we crash before exiting this method.
1700 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1701 ActCleanup(TrackerAct.get());
1702
1703 if (!Act->BeginSourceFile(*Clang.get(),
1704 Clang->getFrontendOpts().Inputs[0].second,
1705 Clang->getFrontendOpts().Inputs[0].first))
1706 return 0;
1707
1708 Act->Execute();
1709
1710 // Steal the created target, context, and preprocessor.
1711 AST->TheSema.reset(Clang->takeSema());
1712 AST->Consumer.reset(Clang->takeASTConsumer());
1713 AST->Ctx = &Clang->getASTContext();
1714 AST->PP = &Clang->getPreprocessor();
1715 Clang->setSourceManager(0);
1716 Clang->setFileManager(0);
1717 AST->Target = &Clang->getTarget();
1718
1719 Act->EndSourceFile();
1720
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001721 if (OwnAST)
1722 return OwnAST.take();
1723 else
1724 return AST;
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001725}
1726
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001727bool ASTUnit::LoadFromCompilerInvocation(bool PrecompilePreamble) {
1728 if (!Invocation)
1729 return true;
1730
1731 // We'll manage file buffers ourselves.
1732 Invocation->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1733 Invocation->getFrontendOpts().DisableFree = false;
Douglas Gregor345c1bc2011-01-19 01:02:47 +00001734 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001735
Douglas Gregorffd6dc42011-01-27 18:02:58 +00001736 // Save the target features.
1737 TargetFeatures = Invocation->getTargetOpts().Features;
1738
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001739 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Douglas Gregorf5a18542010-10-27 17:24:53 +00001740 if (PrecompilePreamble) {
Douglas Gregorc6592922010-11-15 23:00:34 +00001741 PreambleRebuildCounter = 2;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001742 OverrideMainBuffer
1743 = getMainBufferWithPrecompiledPreamble(*Invocation);
1744 }
1745
Douglas Gregor16896c42010-10-28 15:44:59 +00001746 SimpleTimer ParsingTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00001747 ParsingTimer.setOutput("Parsing " + getMainFileName());
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001748
Ted Kremenek022a4902011-03-22 01:15:24 +00001749 // Recover resources if we crash before exiting this method.
1750 llvm::CrashRecoveryContextCleanupRegistrar<llvm::MemoryBuffer>
1751 MemBufferCleanup(OverrideMainBuffer);
1752
Douglas Gregor16896c42010-10-28 15:44:59 +00001753 return Parse(OverrideMainBuffer);
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001754}
1755
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001756ASTUnit *ASTUnit::LoadFromCompilerInvocation(CompilerInvocation *CI,
David Blaikie9c902b52011-09-25 23:23:43 +00001757 llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001758 bool OnlyLocalDecls,
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001759 bool CaptureDiagnostics,
Douglas Gregor028d3e42010-08-09 20:45:32 +00001760 bool PrecompilePreamble,
Douglas Gregor69f74f82011-08-25 22:30:56 +00001761 TranslationUnitKind TUKind,
Douglas Gregor998caea2011-05-06 16:33:08 +00001762 bool CacheCodeCompletionResults,
Chandler Carruthde81fc82011-07-14 09:02:10 +00001763 bool NestedMacroExpansions) {
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001764 // Create the AST unit.
1765 llvm::OwningPtr<ASTUnit> AST;
1766 AST.reset(new ASTUnit(false));
Douglas Gregor345c1bc2011-01-19 01:02:47 +00001767 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001768 AST->Diagnostics = Diags;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001769 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001770 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor69f74f82011-08-25 22:30:56 +00001771 AST->TUKind = TUKind;
Douglas Gregorb14904c2010-08-13 22:48:40 +00001772 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Ted Kremenek5e14d392011-03-21 18:40:17 +00001773 AST->Invocation = CI;
Chandler Carruthde81fc82011-07-14 09:02:10 +00001774 AST->NestedMacroExpansions = NestedMacroExpansions;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001775
Ted Kremenek4422bfe2011-03-18 02:06:56 +00001776 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00001777 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1778 ASTUnitCleanup(AST.get());
David Blaikie9c902b52011-09-25 23:23:43 +00001779 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1780 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Ted Kremenek022a4902011-03-22 01:15:24 +00001781 DiagCleanup(Diags.getPtr());
Ted Kremenek4422bfe2011-03-18 02:06:56 +00001782
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001783 return AST->LoadFromCompilerInvocation(PrecompilePreamble)? 0 : AST.take();
Daniel Dunbar764c0822009-12-01 09:51:01 +00001784}
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001785
1786ASTUnit *ASTUnit::LoadFromCommandLine(const char **ArgBegin,
1787 const char **ArgEnd,
David Blaikie9c902b52011-09-25 23:23:43 +00001788 llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001789 StringRef ResourceFilesPath,
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001790 bool OnlyLocalDecls,
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001791 bool CaptureDiagnostics,
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001792 RemappedFile *RemappedFiles,
Douglas Gregor33cdd812010-02-18 18:08:43 +00001793 unsigned NumRemappedFiles,
Argyrios Kyrtzidis97d3a382011-03-08 23:35:24 +00001794 bool RemappedFilesKeepOriginalName,
Douglas Gregor028d3e42010-08-09 20:45:32 +00001795 bool PrecompilePreamble,
Douglas Gregor69f74f82011-08-25 22:30:56 +00001796 TranslationUnitKind TUKind,
Douglas Gregorf5a18542010-10-27 17:24:53 +00001797 bool CacheCodeCompletionResults,
Chandler Carruthde81fc82011-07-14 09:02:10 +00001798 bool NestedMacroExpansions) {
Douglas Gregor7f95d262010-04-05 23:52:57 +00001799 if (!Diags.getPtr()) {
Douglas Gregord03e8232010-04-05 21:10:19 +00001800 // No diagnostics engine was provided, so create our own diagnostics object
1801 // with the default options.
1802 DiagnosticOptions DiagOpts;
Douglas Gregor345c1bc2011-01-19 01:02:47 +00001803 Diags = CompilerInstance::createDiagnostics(DiagOpts, ArgEnd - ArgBegin,
1804 ArgBegin);
Douglas Gregord03e8232010-04-05 21:10:19 +00001805 }
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001806
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001807 SmallVector<StoredDiagnostic, 4> StoredDiagnostics;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001808
Ted Kremenek5e14d392011-03-21 18:40:17 +00001809 llvm::IntrusiveRefCntPtr<CompilerInvocation> CI;
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001810
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001811 {
Douglas Gregor925296b2011-07-19 16:10:42 +00001812
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001813 CaptureDroppedDiagnostics Capture(CaptureDiagnostics, *Diags,
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001814 StoredDiagnostics);
Daniel Dunbarfcf2d422010-01-25 00:44:02 +00001815
Argyrios Kyrtzidis5cf423e2011-04-04 23:11:45 +00001816 CI = clang::createInvocationFromCommandLine(
Frits van Bommel717d7ed2011-07-18 12:00:32 +00001817 llvm::makeArrayRef(ArgBegin, ArgEnd),
1818 Diags);
Argyrios Kyrtzidisf606b822011-04-04 21:38:51 +00001819 if (!CI)
Argyrios Kyrtzidisbc1f48f2011-03-07 22:45:01 +00001820 return 0;
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001821 }
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001822
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001823 // Override any files that need remapping
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00001824 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
1825 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
1826 if (const llvm::MemoryBuffer *
1827 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
1828 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first, memBuf);
1829 } else {
1830 const char *fname = fileOrBuf.get<const char *>();
1831 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first, fname);
1832 }
1833 }
Argyrios Kyrtzidis97d3a382011-03-08 23:35:24 +00001834 CI->getPreprocessorOpts().RemappedFilesKeepOriginalName =
1835 RemappedFilesKeepOriginalName;
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001836
Daniel Dunbara5a166d2009-12-15 00:06:45 +00001837 // Override the resources path.
Daniel Dunbar6b03ece2010-01-30 21:47:16 +00001838 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001839
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001840 // Create the AST unit.
1841 llvm::OwningPtr<ASTUnit> AST;
1842 AST.reset(new ASTUnit(false));
Douglas Gregor345c1bc2011-01-19 01:02:47 +00001843 ConfigureDiags(Diags, ArgBegin, ArgEnd, *AST, CaptureDiagnostics);
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001844 AST->Diagnostics = Diags;
Anders Carlssonc30dcec2011-03-18 18:22:40 +00001845
1846 AST->FileSystemOpts = CI->getFileSystemOpts();
Ted Kremenek5e14d392011-03-21 18:40:17 +00001847 AST->FileMgr = new FileManager(AST->FileSystemOpts);
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001848 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001849 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor69f74f82011-08-25 22:30:56 +00001850 AST->TUKind = TUKind;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001851 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
1852 AST->NumStoredDiagnosticsFromDriver = StoredDiagnostics.size();
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001853 AST->StoredDiagnostics.swap(StoredDiagnostics);
Ted Kremenek5e14d392011-03-21 18:40:17 +00001854 AST->Invocation = CI;
Chandler Carruthde81fc82011-07-14 09:02:10 +00001855 AST->NestedMacroExpansions = NestedMacroExpansions;
Ted Kremenek4422bfe2011-03-18 02:06:56 +00001856
1857 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00001858 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1859 ASTUnitCleanup(AST.get());
1860 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInvocation,
1861 llvm::CrashRecoveryContextReleaseRefCleanup<CompilerInvocation> >
1862 CICleanup(CI.getPtr());
David Blaikie9c902b52011-09-25 23:23:43 +00001863 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1864 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Ted Kremenek022a4902011-03-22 01:15:24 +00001865 DiagCleanup(Diags.getPtr());
Ted Kremenek4422bfe2011-03-18 02:06:56 +00001866
Chris Lattner5159f612010-11-23 08:35:12 +00001867 return AST->LoadFromCompilerInvocation(PrecompilePreamble) ? 0 : AST.take();
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001868}
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001869
1870bool ASTUnit::Reparse(RemappedFile *RemappedFiles, unsigned NumRemappedFiles) {
Ted Kremenek5e14d392011-03-21 18:40:17 +00001871 if (!Invocation)
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001872 return true;
1873
Douglas Gregor16896c42010-10-28 15:44:59 +00001874 SimpleTimer ParsingTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00001875 ParsingTimer.setOutput("Reparsing " + getMainFileName());
Douglas Gregor16896c42010-10-28 15:44:59 +00001876
Douglas Gregor0e119552010-07-31 00:40:00 +00001877 // Remap files.
Douglas Gregor7b02b582010-08-20 00:02:33 +00001878 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
Douglas Gregor606c4ac2011-02-05 19:42:43 +00001879 PPOpts.DisableStatCache = true;
Douglas Gregor7b02b582010-08-20 00:02:33 +00001880 for (PreprocessorOptions::remapped_file_buffer_iterator
1881 R = PPOpts.remapped_file_buffer_begin(),
1882 REnd = PPOpts.remapped_file_buffer_end();
1883 R != REnd;
1884 ++R) {
1885 delete R->second;
1886 }
Douglas Gregor0e119552010-07-31 00:40:00 +00001887 Invocation->getPreprocessorOpts().clearRemappedFiles();
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00001888 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
1889 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
1890 if (const llvm::MemoryBuffer *
1891 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
1892 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
1893 memBuf);
1894 } else {
1895 const char *fname = fileOrBuf.get<const char *>();
1896 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
1897 fname);
1898 }
1899 }
Douglas Gregor0e119552010-07-31 00:40:00 +00001900
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001901 // If we have a preamble file lying around, or if we might try to
1902 // build a precompiled preamble, do so now.
Douglas Gregor6481ef12010-07-24 00:38:13 +00001903 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Ted Kremenek06b4f912011-10-27 17:55:18 +00001904 if (!getPreambleFile(this).empty() || PreambleRebuildCounter > 0)
Douglas Gregorb97b6662010-08-20 00:59:43 +00001905 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(*Invocation);
Douglas Gregor4dde7492010-07-23 23:58:40 +00001906
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001907 // Clear out the diagnostics state.
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00001908 if (!OverrideMainBuffer) {
Douglas Gregord9a30af2010-08-02 20:51:39 +00001909 getDiagnostics().Reset();
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00001910 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
1911 }
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001912
Douglas Gregor4dde7492010-07-23 23:58:40 +00001913 // Parse the sources
Douglas Gregordf7a79a2011-02-16 18:16:54 +00001914 bool Result = Parse(OverrideMainBuffer);
1915
1916 // If we're caching global code-completion results, and the top-level
1917 // declarations have changed, clear out the code-completion cache.
1918 if (!Result && ShouldCacheCodeCompletionResults &&
1919 CurrentTopLevelHashValue != CompletionCacheTopLevelHashValue)
1920 CacheCodeCompletionResults();
1921
Douglas Gregor3f35bb22011-08-04 20:04:59 +00001922 // We now need to clear out the completion allocator for
1923 // clang_getCursorCompletionString; it'll be recreated if necessary.
1924 CursorCompletionAllocator = 0;
1925
Douglas Gregor4dde7492010-07-23 23:58:40 +00001926 return Result;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001927}
Douglas Gregor8e984da2010-08-04 16:47:14 +00001928
Douglas Gregorb14904c2010-08-13 22:48:40 +00001929//----------------------------------------------------------------------------//
1930// Code completion
1931//----------------------------------------------------------------------------//
1932
1933namespace {
1934 /// \brief Code completion consumer that combines the cached code-completion
1935 /// results from an ASTUnit with the code-completion results provided to it,
1936 /// then passes the result on to
1937 class AugmentedCodeCompleteConsumer : public CodeCompleteConsumer {
Douglas Gregor21325842011-07-07 16:03:39 +00001938 unsigned long long NormalContexts;
Douglas Gregorb14904c2010-08-13 22:48:40 +00001939 ASTUnit &AST;
1940 CodeCompleteConsumer &Next;
1941
1942 public:
1943 AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next,
Douglas Gregor39982192010-08-15 06:18:01 +00001944 bool IncludeMacros, bool IncludeCodePatterns,
1945 bool IncludeGlobals)
1946 : CodeCompleteConsumer(IncludeMacros, IncludeCodePatterns, IncludeGlobals,
Douglas Gregorb14904c2010-08-13 22:48:40 +00001947 Next.isOutputBinary()), AST(AST), Next(Next)
1948 {
1949 // Compute the set of contexts in which we will look when we don't have
1950 // any information about the specific context.
1951 NormalContexts
Douglas Gregor21325842011-07-07 16:03:39 +00001952 = (1LL << (CodeCompletionContext::CCC_TopLevel - 1))
1953 | (1LL << (CodeCompletionContext::CCC_ObjCInterface - 1))
1954 | (1LL << (CodeCompletionContext::CCC_ObjCImplementation - 1))
1955 | (1LL << (CodeCompletionContext::CCC_ObjCIvarList - 1))
1956 | (1LL << (CodeCompletionContext::CCC_Statement - 1))
1957 | (1LL << (CodeCompletionContext::CCC_Expression - 1))
1958 | (1LL << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
1959 | (1LL << (CodeCompletionContext::CCC_DotMemberAccess - 1))
1960 | (1LL << (CodeCompletionContext::CCC_ArrowMemberAccess - 1))
1961 | (1LL << (CodeCompletionContext::CCC_ObjCPropertyAccess - 1))
1962 | (1LL << (CodeCompletionContext::CCC_ObjCProtocolName - 1))
1963 | (1LL << (CodeCompletionContext::CCC_ParenthesizedExpression - 1))
1964 | (1LL << (CodeCompletionContext::CCC_Recovery - 1));
Douglas Gregor5e35d592010-09-14 23:59:36 +00001965
Douglas Gregorb14904c2010-08-13 22:48:40 +00001966 if (AST.getASTContext().getLangOptions().CPlusPlus)
Douglas Gregor21325842011-07-07 16:03:39 +00001967 NormalContexts |= (1LL << (CodeCompletionContext::CCC_EnumTag - 1))
1968 | (1LL << (CodeCompletionContext::CCC_UnionTag - 1))
1969 | (1LL << (CodeCompletionContext::CCC_ClassOrStructTag - 1));
Douglas Gregorb14904c2010-08-13 22:48:40 +00001970 }
1971
1972 virtual void ProcessCodeCompleteResults(Sema &S,
1973 CodeCompletionContext Context,
John McCall276321a2010-08-25 06:19:51 +00001974 CodeCompletionResult *Results,
Douglas Gregord46cf182010-08-16 20:01:48 +00001975 unsigned NumResults);
Douglas Gregorb14904c2010-08-13 22:48:40 +00001976
1977 virtual void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
1978 OverloadCandidate *Candidates,
1979 unsigned NumCandidates) {
1980 Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates);
1981 }
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001982
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00001983 virtual CodeCompletionAllocator &getAllocator() {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001984 return Next.getAllocator();
1985 }
Douglas Gregorb14904c2010-08-13 22:48:40 +00001986 };
1987}
Douglas Gregord46cf182010-08-16 20:01:48 +00001988
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001989/// \brief Helper function that computes which global names are hidden by the
1990/// local code-completion results.
Ted Kremenek6a153372010-11-07 06:11:36 +00001991static void CalculateHiddenNames(const CodeCompletionContext &Context,
1992 CodeCompletionResult *Results,
1993 unsigned NumResults,
1994 ASTContext &Ctx,
1995 llvm::StringSet<llvm::BumpPtrAllocator> &HiddenNames){
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001996 bool OnlyTagNames = false;
1997 switch (Context.getKind()) {
Douglas Gregor0ac41382010-09-23 23:01:17 +00001998 case CodeCompletionContext::CCC_Recovery:
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001999 case CodeCompletionContext::CCC_TopLevel:
2000 case CodeCompletionContext::CCC_ObjCInterface:
2001 case CodeCompletionContext::CCC_ObjCImplementation:
2002 case CodeCompletionContext::CCC_ObjCIvarList:
2003 case CodeCompletionContext::CCC_ClassStructUnion:
2004 case CodeCompletionContext::CCC_Statement:
2005 case CodeCompletionContext::CCC_Expression:
2006 case CodeCompletionContext::CCC_ObjCMessageReceiver:
Douglas Gregor21325842011-07-07 16:03:39 +00002007 case CodeCompletionContext::CCC_DotMemberAccess:
2008 case CodeCompletionContext::CCC_ArrowMemberAccess:
2009 case CodeCompletionContext::CCC_ObjCPropertyAccess:
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002010 case CodeCompletionContext::CCC_Namespace:
2011 case CodeCompletionContext::CCC_Type:
Douglas Gregorc49f5b22010-08-23 18:23:48 +00002012 case CodeCompletionContext::CCC_Name:
2013 case CodeCompletionContext::CCC_PotentiallyQualifiedName:
Douglas Gregor5e35d592010-09-14 23:59:36 +00002014 case CodeCompletionContext::CCC_ParenthesizedExpression:
Douglas Gregor2c595ad2011-07-30 06:55:39 +00002015 case CodeCompletionContext::CCC_ObjCInterfaceName:
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002016 break;
2017
2018 case CodeCompletionContext::CCC_EnumTag:
2019 case CodeCompletionContext::CCC_UnionTag:
2020 case CodeCompletionContext::CCC_ClassOrStructTag:
2021 OnlyTagNames = true;
2022 break;
2023
2024 case CodeCompletionContext::CCC_ObjCProtocolName:
Douglas Gregor12785102010-08-24 20:21:13 +00002025 case CodeCompletionContext::CCC_MacroName:
2026 case CodeCompletionContext::CCC_MacroNameUse:
Douglas Gregorec00a262010-08-24 22:20:20 +00002027 case CodeCompletionContext::CCC_PreprocessorExpression:
Douglas Gregor0de55ce2010-08-25 18:41:16 +00002028 case CodeCompletionContext::CCC_PreprocessorDirective:
Douglas Gregorea147052010-08-25 18:04:30 +00002029 case CodeCompletionContext::CCC_NaturalLanguage:
Douglas Gregor67c692c2010-08-26 15:07:07 +00002030 case CodeCompletionContext::CCC_SelectorName:
Douglas Gregor28c78432010-08-27 17:35:51 +00002031 case CodeCompletionContext::CCC_TypeQualifiers:
Douglas Gregor0ac41382010-09-23 23:01:17 +00002032 case CodeCompletionContext::CCC_Other:
Douglas Gregor3a69eaf2011-02-18 23:30:37 +00002033 case CodeCompletionContext::CCC_OtherWithMacros:
Douglas Gregor21325842011-07-07 16:03:39 +00002034 case CodeCompletionContext::CCC_ObjCInstanceMessage:
2035 case CodeCompletionContext::CCC_ObjCClassMessage:
2036 case CodeCompletionContext::CCC_ObjCCategoryName:
Douglas Gregor0de55ce2010-08-25 18:41:16 +00002037 // We're looking for nothing, or we're looking for names that cannot
2038 // be hidden.
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002039 return;
2040 }
2041
John McCall276321a2010-08-25 06:19:51 +00002042 typedef CodeCompletionResult Result;
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002043 for (unsigned I = 0; I != NumResults; ++I) {
2044 if (Results[I].Kind != Result::RK_Declaration)
2045 continue;
2046
2047 unsigned IDNS
2048 = Results[I].Declaration->getUnderlyingDecl()->getIdentifierNamespace();
2049
2050 bool Hiding = false;
2051 if (OnlyTagNames)
2052 Hiding = (IDNS & Decl::IDNS_Tag);
2053 else {
2054 unsigned HiddenIDNS = (Decl::IDNS_Type | Decl::IDNS_Member |
Douglas Gregor59cab552010-08-16 23:05:20 +00002055 Decl::IDNS_Namespace | Decl::IDNS_Ordinary |
2056 Decl::IDNS_NonMemberOperator);
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002057 if (Ctx.getLangOptions().CPlusPlus)
2058 HiddenIDNS |= Decl::IDNS_Tag;
2059 Hiding = (IDNS & HiddenIDNS);
2060 }
2061
2062 if (!Hiding)
2063 continue;
2064
2065 DeclarationName Name = Results[I].Declaration->getDeclName();
2066 if (IdentifierInfo *Identifier = Name.getAsIdentifierInfo())
2067 HiddenNames.insert(Identifier->getName());
2068 else
2069 HiddenNames.insert(Name.getAsString());
2070 }
2071}
2072
2073
Douglas Gregord46cf182010-08-16 20:01:48 +00002074void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &S,
2075 CodeCompletionContext Context,
John McCall276321a2010-08-25 06:19:51 +00002076 CodeCompletionResult *Results,
Douglas Gregord46cf182010-08-16 20:01:48 +00002077 unsigned NumResults) {
2078 // Merge the results we were given with the results we cached.
2079 bool AddedResult = false;
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002080 unsigned InContexts
Douglas Gregor0ac41382010-09-23 23:01:17 +00002081 = (Context.getKind() == CodeCompletionContext::CCC_Recovery? NormalContexts
NAKAMURA Takumi203f87c2011-08-17 01:46:16 +00002082 : (1ULL << (Context.getKind() - 1)));
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002083 // Contains the set of names that are hidden by "local" completion results.
Ted Kremenek6a153372010-11-07 06:11:36 +00002084 llvm::StringSet<llvm::BumpPtrAllocator> HiddenNames;
John McCall276321a2010-08-25 06:19:51 +00002085 typedef CodeCompletionResult Result;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002086 SmallVector<Result, 8> AllResults;
Douglas Gregord46cf182010-08-16 20:01:48 +00002087 for (ASTUnit::cached_completion_iterator
Douglas Gregordf239672010-08-16 21:23:13 +00002088 C = AST.cached_completion_begin(),
2089 CEnd = AST.cached_completion_end();
Douglas Gregord46cf182010-08-16 20:01:48 +00002090 C != CEnd; ++C) {
2091 // If the context we are in matches any of the contexts we are
2092 // interested in, we'll add this result.
2093 if ((C->ShowInContexts & InContexts) == 0)
2094 continue;
2095
2096 // If we haven't added any results previously, do so now.
2097 if (!AddedResult) {
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002098 CalculateHiddenNames(Context, Results, NumResults, S.Context,
2099 HiddenNames);
Douglas Gregord46cf182010-08-16 20:01:48 +00002100 AllResults.insert(AllResults.end(), Results, Results + NumResults);
2101 AddedResult = true;
2102 }
2103
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002104 // Determine whether this global completion result is hidden by a local
2105 // completion result. If so, skip it.
2106 if (C->Kind != CXCursor_MacroDefinition &&
2107 HiddenNames.count(C->Completion->getTypedText()))
2108 continue;
2109
Douglas Gregord46cf182010-08-16 20:01:48 +00002110 // Adjust priority based on similar type classes.
2111 unsigned Priority = C->Priority;
Douglas Gregor8850aa32010-08-25 18:03:13 +00002112 CXCursorKind CursorKind = C->Kind;
Douglas Gregor12785102010-08-24 20:21:13 +00002113 CodeCompletionString *Completion = C->Completion;
Douglas Gregord46cf182010-08-16 20:01:48 +00002114 if (!Context.getPreferredType().isNull()) {
2115 if (C->Kind == CXCursor_MacroDefinition) {
2116 Priority = getMacroUsagePriority(C->Completion->getTypedText(),
Douglas Gregor9dcf58a2010-09-20 21:11:48 +00002117 S.getLangOptions(),
Douglas Gregor12785102010-08-24 20:21:13 +00002118 Context.getPreferredType()->isAnyPointerType());
Douglas Gregord46cf182010-08-16 20:01:48 +00002119 } else if (C->Type) {
2120 CanQualType Expected
Douglas Gregordf239672010-08-16 21:23:13 +00002121 = S.Context.getCanonicalType(
Douglas Gregord46cf182010-08-16 20:01:48 +00002122 Context.getPreferredType().getUnqualifiedType());
2123 SimplifiedTypeClass ExpectedSTC = getSimplifiedTypeClass(Expected);
2124 if (ExpectedSTC == C->TypeClass) {
2125 // We know this type is similar; check for an exact match.
2126 llvm::StringMap<unsigned> &CachedCompletionTypes
Douglas Gregordf239672010-08-16 21:23:13 +00002127 = AST.getCachedCompletionTypes();
Douglas Gregord46cf182010-08-16 20:01:48 +00002128 llvm::StringMap<unsigned>::iterator Pos
Douglas Gregordf239672010-08-16 21:23:13 +00002129 = CachedCompletionTypes.find(QualType(Expected).getAsString());
Douglas Gregord46cf182010-08-16 20:01:48 +00002130 if (Pos != CachedCompletionTypes.end() && Pos->second == C->Type)
2131 Priority /= CCF_ExactTypeMatch;
2132 else
2133 Priority /= CCF_SimilarTypeMatch;
2134 }
2135 }
2136 }
2137
Douglas Gregor12785102010-08-24 20:21:13 +00002138 // Adjust the completion string, if required.
2139 if (C->Kind == CXCursor_MacroDefinition &&
2140 Context.getKind() == CodeCompletionContext::CCC_MacroNameUse) {
2141 // Create a new code-completion string that just contains the
2142 // macro name, without its arguments.
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002143 CodeCompletionBuilder Builder(getAllocator(), CCP_CodePattern,
2144 C->Availability);
2145 Builder.AddTypedTextChunk(C->Completion->getTypedText());
Douglas Gregor8850aa32010-08-25 18:03:13 +00002146 CursorKind = CXCursor_NotImplemented;
2147 Priority = CCP_CodePattern;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002148 Completion = Builder.TakeString();
Douglas Gregor12785102010-08-24 20:21:13 +00002149 }
2150
Douglas Gregor8850aa32010-08-25 18:03:13 +00002151 AllResults.push_back(Result(Completion, Priority, CursorKind,
Douglas Gregorf757a122010-08-23 23:00:57 +00002152 C->Availability));
Douglas Gregord46cf182010-08-16 20:01:48 +00002153 }
2154
2155 // If we did not add any cached completion results, just forward the
2156 // results we were given to the next consumer.
2157 if (!AddedResult) {
2158 Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
2159 return;
2160 }
Douglas Gregor49f67ce2010-08-26 13:48:20 +00002161
Douglas Gregord46cf182010-08-16 20:01:48 +00002162 Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
2163 AllResults.size());
2164}
2165
2166
2167
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002168void ASTUnit::CodeComplete(StringRef File, unsigned Line, unsigned Column,
Douglas Gregor8e984da2010-08-04 16:47:14 +00002169 RemappedFile *RemappedFiles,
2170 unsigned NumRemappedFiles,
Douglas Gregorb68bc592010-08-05 09:09:23 +00002171 bool IncludeMacros,
2172 bool IncludeCodePatterns,
Douglas Gregor8e984da2010-08-04 16:47:14 +00002173 CodeCompleteConsumer &Consumer,
David Blaikie9c902b52011-09-25 23:23:43 +00002174 DiagnosticsEngine &Diag, LangOptions &LangOpts,
Douglas Gregor8e984da2010-08-04 16:47:14 +00002175 SourceManager &SourceMgr, FileManager &FileMgr,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002176 SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
2177 SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers) {
Ted Kremenek5e14d392011-03-21 18:40:17 +00002178 if (!Invocation)
Douglas Gregor8e984da2010-08-04 16:47:14 +00002179 return;
2180
Douglas Gregor16896c42010-10-28 15:44:59 +00002181 SimpleTimer CompletionTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00002182 CompletionTimer.setOutput("Code completion @ " + File + ":" +
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002183 Twine(Line) + ":" + Twine(Column));
Douglas Gregor028d3e42010-08-09 20:45:32 +00002184
Ted Kremenek5e14d392011-03-21 18:40:17 +00002185 llvm::IntrusiveRefCntPtr<CompilerInvocation>
2186 CCInvocation(new CompilerInvocation(*Invocation));
2187
2188 FrontendOptions &FrontendOpts = CCInvocation->getFrontendOpts();
2189 PreprocessorOptions &PreprocessorOpts = CCInvocation->getPreprocessorOpts();
Douglas Gregorb68bc592010-08-05 09:09:23 +00002190
Douglas Gregorb14904c2010-08-13 22:48:40 +00002191 FrontendOpts.ShowMacrosInCodeCompletion
2192 = IncludeMacros && CachedCompletionResults.empty();
Douglas Gregorb68bc592010-08-05 09:09:23 +00002193 FrontendOpts.ShowCodePatternsInCodeCompletion = IncludeCodePatterns;
Douglas Gregor39982192010-08-15 06:18:01 +00002194 FrontendOpts.ShowGlobalSymbolsInCodeCompletion
2195 = CachedCompletionResults.empty();
Douglas Gregor8e984da2010-08-04 16:47:14 +00002196 FrontendOpts.CodeCompletionAt.FileName = File;
2197 FrontendOpts.CodeCompletionAt.Line = Line;
2198 FrontendOpts.CodeCompletionAt.Column = Column;
2199
2200 // Set the language options appropriately.
Ted Kremenek5e14d392011-03-21 18:40:17 +00002201 LangOpts = CCInvocation->getLangOpts();
Douglas Gregor8e984da2010-08-04 16:47:14 +00002202
Ted Kremenek84de4a12011-03-21 18:40:07 +00002203 llvm::OwningPtr<CompilerInstance> Clang(new CompilerInstance());
2204
2205 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00002206 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
2207 CICleanup(Clang.get());
Ted Kremenek84de4a12011-03-21 18:40:07 +00002208
Ted Kremenek5e14d392011-03-21 18:40:17 +00002209 Clang->setInvocation(&*CCInvocation);
Ted Kremenek84de4a12011-03-21 18:40:07 +00002210 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].second;
Douglas Gregor8e984da2010-08-04 16:47:14 +00002211
2212 // Set up diagnostics, capturing any diagnostics produced.
Ted Kremenek84de4a12011-03-21 18:40:07 +00002213 Clang->setDiagnostics(&Diag);
Ted Kremenek5e14d392011-03-21 18:40:17 +00002214 ProcessWarningOptions(Diag, CCInvocation->getDiagnosticOpts());
Douglas Gregor8e984da2010-08-04 16:47:14 +00002215 CaptureDroppedDiagnostics Capture(true,
Ted Kremenek84de4a12011-03-21 18:40:07 +00002216 Clang->getDiagnostics(),
Douglas Gregor8e984da2010-08-04 16:47:14 +00002217 StoredDiagnostics);
Douglas Gregor8e984da2010-08-04 16:47:14 +00002218
2219 // Create the target instance.
Ted Kremenek84de4a12011-03-21 18:40:07 +00002220 Clang->getTargetOpts().Features = TargetFeatures;
2221 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
2222 Clang->getTargetOpts()));
2223 if (!Clang->hasTarget()) {
Ted Kremenek5e14d392011-03-21 18:40:17 +00002224 Clang->setInvocation(0);
Douglas Gregor2dd19f12010-08-18 22:29:43 +00002225 return;
Douglas Gregor8e984da2010-08-04 16:47:14 +00002226 }
2227
2228 // Inform the target of the language options.
2229 //
2230 // FIXME: We shouldn't need to do this, the target should be immutable once
2231 // created. This complexity should be lifted elsewhere.
Ted Kremenek84de4a12011-03-21 18:40:07 +00002232 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregor8e984da2010-08-04 16:47:14 +00002233
Ted Kremenek84de4a12011-03-21 18:40:07 +00002234 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Douglas Gregor8e984da2010-08-04 16:47:14 +00002235 "Invocation must have exactly one source file!");
Ted Kremenek84de4a12011-03-21 18:40:07 +00002236 assert(Clang->getFrontendOpts().Inputs[0].first != IK_AST &&
Douglas Gregor8e984da2010-08-04 16:47:14 +00002237 "FIXME: AST inputs not yet supported here!");
Ted Kremenek84de4a12011-03-21 18:40:07 +00002238 assert(Clang->getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
Douglas Gregor8e984da2010-08-04 16:47:14 +00002239 "IR inputs not support here!");
2240
2241
2242 // Use the source and file managers that we were given.
Ted Kremenek84de4a12011-03-21 18:40:07 +00002243 Clang->setFileManager(&FileMgr);
2244 Clang->setSourceManager(&SourceMgr);
Douglas Gregor8e984da2010-08-04 16:47:14 +00002245
2246 // Remap files.
2247 PreprocessorOpts.clearRemappedFiles();
Douglas Gregord8a5dba2010-08-04 17:07:00 +00002248 PreprocessorOpts.RetainRemappedFileBuffers = true;
Douglas Gregorb97b6662010-08-20 00:59:43 +00002249 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00002250 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
2251 if (const llvm::MemoryBuffer *
2252 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
2253 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first, memBuf);
2254 OwnedBuffers.push_back(memBuf);
2255 } else {
2256 const char *fname = fileOrBuf.get<const char *>();
2257 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first, fname);
2258 }
Douglas Gregorb97b6662010-08-20 00:59:43 +00002259 }
Douglas Gregor8e984da2010-08-04 16:47:14 +00002260
Douglas Gregorb14904c2010-08-13 22:48:40 +00002261 // Use the code completion consumer we were given, but adding any cached
2262 // code-completion results.
Douglas Gregore9186e62010-11-29 16:13:56 +00002263 AugmentedCodeCompleteConsumer *AugmentedConsumer
2264 = new AugmentedCodeCompleteConsumer(*this, Consumer,
2265 FrontendOpts.ShowMacrosInCodeCompletion,
2266 FrontendOpts.ShowCodePatternsInCodeCompletion,
2267 FrontendOpts.ShowGlobalSymbolsInCodeCompletion);
Ted Kremenek84de4a12011-03-21 18:40:07 +00002268 Clang->setCodeCompletionConsumer(AugmentedConsumer);
Douglas Gregor8e984da2010-08-04 16:47:14 +00002269
Douglas Gregor028d3e42010-08-09 20:45:32 +00002270 // If we have a precompiled preamble, try to use it. We only allow
2271 // the use of the precompiled preamble if we're if the completion
2272 // point is within the main file, after the end of the precompiled
2273 // preamble.
2274 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Ted Kremenek06b4f912011-10-27 17:55:18 +00002275 if (!getPreambleFile(this).empty()) {
Douglas Gregor028d3e42010-08-09 20:45:32 +00002276 using llvm::sys::FileStatus;
2277 llvm::sys::PathWithStatus CompleteFilePath(File);
2278 llvm::sys::PathWithStatus MainPath(OriginalSourceFile);
2279 if (const FileStatus *CompleteFileStatus = CompleteFilePath.getFileStatus())
2280 if (const FileStatus *MainStatus = MainPath.getFileStatus())
Argyrios Kyrtzidisa3deaee2011-09-04 03:32:04 +00002281 if (CompleteFileStatus->getUniqueID() == MainStatus->getUniqueID() &&
2282 Line > 1)
Douglas Gregorb97b6662010-08-20 00:59:43 +00002283 OverrideMainBuffer
Ted Kremenek5e14d392011-03-21 18:40:17 +00002284 = getMainBufferWithPrecompiledPreamble(*CCInvocation, false,
Douglas Gregor8e817b62010-08-25 18:04:15 +00002285 Line - 1);
Douglas Gregor028d3e42010-08-09 20:45:32 +00002286 }
2287
2288 // If the main file has been overridden due to the use of a preamble,
2289 // make that override happen and introduce the preamble.
Douglas Gregor606c4ac2011-02-05 19:42:43 +00002290 PreprocessorOpts.DisableStatCache = true;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00002291 StoredDiagnostics.insert(StoredDiagnostics.end(),
Argyrios Kyrtzidis067cbfa2011-10-24 17:25:20 +00002292 stored_diag_begin(),
2293 stored_diag_afterDriver_begin());
Douglas Gregor028d3e42010-08-09 20:45:32 +00002294 if (OverrideMainBuffer) {
2295 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
2296 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
2297 PreprocessorOpts.PrecompiledPreambleBytes.second
2298 = PreambleEndsAtStartOfLine;
Ted Kremenek06b4f912011-10-27 17:55:18 +00002299 PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
Douglas Gregor028d3e42010-08-09 20:45:32 +00002300 PreprocessorOpts.DisablePCHValidation = true;
2301
Douglas Gregorb97b6662010-08-20 00:59:43 +00002302 OwnedBuffers.push_back(OverrideMainBuffer);
Douglas Gregor7b02b582010-08-20 00:02:33 +00002303 } else {
2304 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
2305 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregor028d3e42010-08-09 20:45:32 +00002306 }
2307
Douglas Gregor998caea2011-05-06 16:33:08 +00002308 // Disable the preprocessing record
2309 PreprocessorOpts.DetailedRecord = false;
2310
Douglas Gregor8e984da2010-08-04 16:47:14 +00002311 llvm::OwningPtr<SyntaxOnlyAction> Act;
2312 Act.reset(new SyntaxOnlyAction);
Ted Kremenek84de4a12011-03-21 18:40:07 +00002313 if (Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0].second,
2314 Clang->getFrontendOpts().Inputs[0].first)) {
Douglas Gregor925296b2011-07-19 16:10:42 +00002315 if (OverrideMainBuffer) {
Ted Kremenek06b4f912011-10-27 17:55:18 +00002316 std::string ModName = getPreambleFile(this);
Douglas Gregor925296b2011-07-19 16:10:42 +00002317 TranslateStoredDiagnostics(Clang->getModuleManager(), ModName,
2318 getSourceManager(), PreambleDiagnostics,
2319 StoredDiagnostics);
2320 }
Douglas Gregor8e984da2010-08-04 16:47:14 +00002321 Act->Execute();
2322 Act->EndSourceFile();
2323 }
Douglas Gregor8e984da2010-08-04 16:47:14 +00002324}
Douglas Gregore9386682010-08-13 05:36:37 +00002325
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002326CXSaveError ASTUnit::Save(StringRef File) {
Douglas Gregor8a60bbe2011-07-06 17:40:26 +00002327 if (getDiagnostics().hasUnrecoverableErrorOccurred())
Douglas Gregor30c80fa2011-07-06 16:43:36 +00002328 return CXSaveError_TranslationErrors;
Argyrios Kyrtzidis55e75572011-07-21 18:44:49 +00002329
2330 // Write to a temporary file and later rename it to the actual file, to avoid
2331 // possible race conditions.
Argyrios Kyrtzidis08a2bfd2011-07-28 00:45:10 +00002332 llvm::SmallString<128> TempPath;
2333 TempPath = File;
2334 TempPath += "-%%%%%%%%";
2335 int fd;
2336 if (llvm::sys::fs::unique_file(TempPath.str(), fd, TempPath,
2337 /*makeAbsolute=*/false))
Argyrios Kyrtzidis55e75572011-07-21 18:44:49 +00002338 return CXSaveError_Unknown;
Argyrios Kyrtzidis55e75572011-07-21 18:44:49 +00002339
Douglas Gregore9386682010-08-13 05:36:37 +00002340 // FIXME: Can we somehow regenerate the stat cache here, or do we need to
2341 // unconditionally create a stat cache when we parse the file?
Argyrios Kyrtzidis08a2bfd2011-07-28 00:45:10 +00002342 llvm::raw_fd_ostream Out(fd, /*shouldClose=*/true);
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00002343
2344 serialize(Out);
2345 Out.close();
Argyrios Kyrtzidis55e75572011-07-21 18:44:49 +00002346 if (Out.has_error())
2347 return CXSaveError_Unknown;
2348
2349 if (llvm::error_code ec = llvm::sys::fs::rename(TempPath.str(), File)) {
2350 bool exists;
2351 llvm::sys::fs::remove(TempPath.str(), exists);
2352 return CXSaveError_Unknown;
2353 }
2354
2355 return CXSaveError_None;
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00002356}
2357
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002358bool ASTUnit::serialize(raw_ostream &OS) {
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00002359 if (getDiagnostics().hasErrorOccurred())
2360 return true;
2361
Douglas Gregore9386682010-08-13 05:36:37 +00002362 std::vector<unsigned char> Buffer;
2363 llvm::BitstreamWriter Stream(Buffer);
Sebastian Redl55c0ad52010-08-18 23:56:21 +00002364 ASTWriter Writer(Stream);
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00002365 // FIXME: Handle modules
2366 Writer.WriteAST(getSema(), 0, std::string(), /*IsModule=*/false, "");
Douglas Gregore9386682010-08-13 05:36:37 +00002367
2368 // Write the generated bitstream to "Out".
Douglas Gregor2dd19f12010-08-18 22:29:43 +00002369 if (!Buffer.empty())
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00002370 OS.write((char *)&Buffer.front(), Buffer.size());
2371
2372 return false;
Douglas Gregore9386682010-08-13 05:36:37 +00002373}
Douglas Gregor925296b2011-07-19 16:10:42 +00002374
2375typedef ContinuousRangeMap<unsigned, int, 2> SLocRemap;
2376
2377static void TranslateSLoc(SourceLocation &L, SLocRemap &Remap) {
2378 unsigned Raw = L.getRawEncoding();
2379 const unsigned MacroBit = 1U << 31;
2380 L = SourceLocation::getFromRawEncoding((Raw & MacroBit) |
2381 ((Raw & ~MacroBit) + Remap.find(Raw & ~MacroBit)->second));
2382}
2383
2384void ASTUnit::TranslateStoredDiagnostics(
2385 ASTReader *MMan,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002386 StringRef ModName,
Douglas Gregor925296b2011-07-19 16:10:42 +00002387 SourceManager &SrcMgr,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002388 const SmallVectorImpl<StoredDiagnostic> &Diags,
2389 SmallVectorImpl<StoredDiagnostic> &Out) {
Douglas Gregor925296b2011-07-19 16:10:42 +00002390 // The stored diagnostic has the old source manager in it; update
2391 // the locations to refer into the new source manager. We also need to remap
2392 // all the locations to the new view. This includes the diag location, any
2393 // associated source ranges, and the source ranges of associated fix-its.
2394 // FIXME: There should be a cleaner way to do this.
2395
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002396 SmallVector<StoredDiagnostic, 4> Result;
Douglas Gregor925296b2011-07-19 16:10:42 +00002397 Result.reserve(Diags.size());
2398 assert(MMan && "Don't have a module manager");
Jonathan D. Turnerb2b08232011-07-26 18:21:30 +00002399 serialization::Module *Mod = MMan->ModuleMgr.lookup(ModName);
Douglas Gregor925296b2011-07-19 16:10:42 +00002400 assert(Mod && "Don't have preamble module");
2401 SLocRemap &Remap = Mod->SLocRemap;
2402 for (unsigned I = 0, N = Diags.size(); I != N; ++I) {
2403 // Rebuild the StoredDiagnostic.
2404 const StoredDiagnostic &SD = Diags[I];
2405 SourceLocation L = SD.getLocation();
2406 TranslateSLoc(L, Remap);
2407 FullSourceLoc Loc(L, SrcMgr);
2408
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002409 SmallVector<CharSourceRange, 4> Ranges;
Douglas Gregor925296b2011-07-19 16:10:42 +00002410 Ranges.reserve(SD.range_size());
2411 for (StoredDiagnostic::range_iterator I = SD.range_begin(),
2412 E = SD.range_end();
2413 I != E; ++I) {
2414 SourceLocation BL = I->getBegin();
2415 TranslateSLoc(BL, Remap);
2416 SourceLocation EL = I->getEnd();
2417 TranslateSLoc(EL, Remap);
2418 Ranges.push_back(CharSourceRange(SourceRange(BL, EL), I->isTokenRange()));
2419 }
2420
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002421 SmallVector<FixItHint, 2> FixIts;
Douglas Gregor925296b2011-07-19 16:10:42 +00002422 FixIts.reserve(SD.fixit_size());
2423 for (StoredDiagnostic::fixit_iterator I = SD.fixit_begin(),
2424 E = SD.fixit_end();
2425 I != E; ++I) {
2426 FixIts.push_back(FixItHint());
2427 FixItHint &FH = FixIts.back();
2428 FH.CodeToInsert = I->CodeToInsert;
2429 SourceLocation BL = I->RemoveRange.getBegin();
2430 TranslateSLoc(BL, Remap);
2431 SourceLocation EL = I->RemoveRange.getEnd();
2432 TranslateSLoc(EL, Remap);
2433 FH.RemoveRange = CharSourceRange(SourceRange(BL, EL),
2434 I->RemoveRange.isTokenRange());
2435 }
2436
2437 Result.push_back(StoredDiagnostic(SD.getLevel(), SD.getID(),
2438 SD.getMessage(), Loc, Ranges, FixIts));
2439 }
2440 Result.swap(Out);
2441}
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002442
2443SourceLocation ASTUnit::getLocation(const FileEntry *File,
2444 unsigned Line, unsigned Col) const {
2445 const SourceManager &SM = getSourceManager();
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00002446 SourceLocation Loc = SM.translateFileLineCol(File, Line, Col);
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002447 return SM.getMacroArgExpandedLocation(Loc);
2448}
2449
2450SourceLocation ASTUnit::getLocation(const FileEntry *File,
2451 unsigned Offset) const {
2452 const SourceManager &SM = getSourceManager();
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00002453 SourceLocation FileLoc = SM.translateFileLineCol(File, 1, 1);
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002454 return SM.getMacroArgExpandedLocation(FileLoc.getLocWithOffset(Offset));
2455}
2456
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00002457/// \brief If \arg Loc is a loaded location from the preamble, returns
2458/// the corresponding local location of the main file, otherwise it returns
2459/// \arg Loc.
2460SourceLocation ASTUnit::mapLocationFromPreamble(SourceLocation Loc) {
2461 FileID PreambleID;
2462 if (SourceMgr)
2463 PreambleID = SourceMgr->getPreambleFileID();
2464
2465 if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2466 return Loc;
2467
2468 unsigned Offs;
2469 if (SourceMgr->isInFileID(Loc, PreambleID, &Offs) && Offs < Preamble.size()) {
2470 SourceLocation FileLoc
2471 = SourceMgr->getLocForStartOfFile(SourceMgr->getMainFileID());
2472 return FileLoc.getLocWithOffset(Offs);
2473 }
2474
2475 return Loc;
2476}
2477
2478/// \brief If \arg Loc is a local location of the main file but inside the
2479/// preamble chunk, returns the corresponding loaded location from the
2480/// preamble, otherwise it returns \arg Loc.
2481SourceLocation ASTUnit::mapLocationToPreamble(SourceLocation Loc) {
2482 FileID PreambleID;
2483 if (SourceMgr)
2484 PreambleID = SourceMgr->getPreambleFileID();
2485
2486 if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2487 return Loc;
2488
2489 unsigned Offs;
2490 if (SourceMgr->isInFileID(Loc, SourceMgr->getMainFileID(), &Offs) &&
2491 Offs < Preamble.size()) {
2492 SourceLocation FileLoc = SourceMgr->getLocForStartOfFile(PreambleID);
2493 return FileLoc.getLocWithOffset(Offs);
2494 }
2495
2496 return Loc;
2497}
2498
Argyrios Kyrtzidis429ec022011-10-25 00:29:50 +00002499bool ASTUnit::isInPreambleFileID(SourceLocation Loc) {
2500 FileID FID;
2501 if (SourceMgr)
2502 FID = SourceMgr->getPreambleFileID();
2503
2504 if (Loc.isInvalid() || FID.isInvalid())
2505 return false;
2506
2507 return SourceMgr->isInFileID(Loc, FID);
2508}
2509
2510bool ASTUnit::isInMainFileID(SourceLocation Loc) {
2511 FileID FID;
2512 if (SourceMgr)
2513 FID = SourceMgr->getMainFileID();
2514
2515 if (Loc.isInvalid() || FID.isInvalid())
2516 return false;
2517
2518 return SourceMgr->isInFileID(Loc, FID);
2519}
2520
2521SourceLocation ASTUnit::getEndOfPreambleFileID() {
2522 FileID FID;
2523 if (SourceMgr)
2524 FID = SourceMgr->getPreambleFileID();
2525
2526 if (FID.isInvalid())
2527 return SourceLocation();
2528
2529 return SourceMgr->getLocForEndOfFile(FID);
2530}
2531
2532SourceLocation ASTUnit::getStartOfMainFileID() {
2533 FileID FID;
2534 if (SourceMgr)
2535 FID = SourceMgr->getMainFileID();
2536
2537 if (FID.isInvalid())
2538 return SourceLocation();
2539
2540 return SourceMgr->getLocForStartOfFile(FID);
2541}
2542
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002543void ASTUnit::PreambleData::countLines() const {
2544 NumLines = 0;
2545 if (empty())
2546 return;
2547
2548 for (std::vector<char>::const_iterator
2549 I = Buffer.begin(), E = Buffer.end(); I != E; ++I) {
2550 if (*I == '\n')
2551 ++NumLines;
2552 }
2553 if (Buffer.back() != '\n')
2554 ++NumLines;
2555}
Argyrios Kyrtzidisebf01362011-10-10 21:57:12 +00002556
2557#ifndef NDEBUG
2558ASTUnit::ConcurrencyState::ConcurrencyState() {
2559 Mutex = new llvm::sys::MutexImpl(/*recursive=*/true);
2560}
2561
2562ASTUnit::ConcurrencyState::~ConcurrencyState() {
2563 delete static_cast<llvm::sys::MutexImpl *>(Mutex);
2564}
2565
2566void ASTUnit::ConcurrencyState::start() {
2567 bool acquired = static_cast<llvm::sys::MutexImpl *>(Mutex)->tryacquire();
2568 assert(acquired && "Concurrent access to ASTUnit!");
2569}
2570
2571void ASTUnit::ConcurrencyState::finish() {
2572 static_cast<llvm::sys::MutexImpl *>(Mutex)->release();
2573}
2574
2575#else // NDEBUG
2576
2577ASTUnit::ConcurrencyState::ConcurrencyState() {}
2578ASTUnit::ConcurrencyState::~ConcurrencyState() {}
2579void ASTUnit::ConcurrencyState::start() {}
2580void ASTUnit::ConcurrencyState::finish() {}
2581
2582#endif