blob: a340d7db33eada0fb858ea3366f88b03b939d659 [file] [log] [blame]
Argyrios Kyrtzidis4b562cf2009-06-20 08:27:14 +00001//===--- ASTUnit.cpp - ASTUnit utility ------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// ASTUnit Implementation.
11//
12//===----------------------------------------------------------------------===//
13
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000014#include "clang/Frontend/ASTUnit.h"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000015#include "clang/AST/ASTContext.h"
Daniel Dunbar521bf9c2009-12-01 09:51:01 +000016#include "clang/AST/ASTConsumer.h"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000017#include "clang/AST/DeclVisitor.h"
Douglas Gregorf5586f62010-08-16 18:08:11 +000018#include "clang/AST/TypeOrdering.h"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000019#include "clang/AST/StmtVisitor.h"
Daniel Dunbar521bf9c2009-12-01 09:51:01 +000020#include "clang/Frontend/CompilerInstance.h"
21#include "clang/Frontend/FrontendActions.h"
Daniel Dunbar7b556682009-12-02 03:23:45 +000022#include "clang/Frontend/FrontendDiagnostic.h"
Daniel Dunbar521bf9c2009-12-01 09:51:01 +000023#include "clang/Frontend/FrontendOptions.h"
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +000024#include "clang/Frontend/MultiplexConsumer.h"
Douglas Gregor32be4a52010-10-11 21:37:58 +000025#include "clang/Frontend/Utils.h"
Sebastian Redl6ab7cd82010-08-18 23:57:17 +000026#include "clang/Serialization/ASTReader.h"
Sebastian Redl7faa2ec2010-08-18 23:56:37 +000027#include "clang/Serialization/ASTWriter.h"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000028#include "clang/Lex/HeaderSearch.h"
29#include "clang/Lex/Preprocessor.h"
Daniel Dunbard58c03f2009-11-15 06:48:46 +000030#include "clang/Basic/TargetOptions.h"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000031#include "clang/Basic/TargetInfo.h"
32#include "clang/Basic/Diagnostic.h"
Chris Lattner7f9fc3f2011-03-23 04:04:01 +000033#include "llvm/ADT/ArrayRef.h"
Douglas Gregor9b7db622011-02-16 18:16:54 +000034#include "llvm/ADT/StringExtras.h"
Douglas Gregor349d38c2010-08-16 23:08:34 +000035#include "llvm/ADT/StringSet.h"
Douglas Gregor1fd9e0d2010-12-07 00:05:48 +000036#include "llvm/Support/Atomic.h"
Douglas Gregor4db64a42010-01-23 00:14:00 +000037#include "llvm/Support/MemoryBuffer.h"
Michael J. Spencer03013fa2010-11-29 18:12:39 +000038#include "llvm/Support/Host.h"
39#include "llvm/Support/Path.h"
Douglas Gregordf95a132010-08-09 20:45:32 +000040#include "llvm/Support/raw_ostream.h"
Douglas Gregor385103b2010-07-30 20:58:08 +000041#include "llvm/Support/Timer.h"
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +000042#include "llvm/Support/FileSystem.h"
Argyrios Kyrtzidisa696ece2011-10-10 21:57:12 +000043#include "llvm/Support/Mutex.h"
Ted Kremeneke055f8a2011-10-27 19:44:25 +000044#include "llvm/Support/MutexGuard.h"
Ted Kremenekb547eeb2011-03-18 02:06:56 +000045#include "llvm/Support/CrashRecoveryContext.h"
Douglas Gregor44c181a2010-07-23 00:33:23 +000046#include <cstdlib>
Zhongxing Xuad23ebe2010-07-23 02:15:08 +000047#include <cstdio>
Douglas Gregorcc5888d2010-07-31 00:40:00 +000048#include <sys/stat.h>
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000049using namespace clang;
50
Douglas Gregor213f18b2010-10-28 15:44:59 +000051using llvm::TimeRecord;
52
53namespace {
54 class SimpleTimer {
55 bool WantTiming;
56 TimeRecord Start;
57 std::string Output;
58
Benjamin Krameredfb7ec2010-11-09 20:00:56 +000059 public:
Douglas Gregor9dba61a2010-11-01 13:48:43 +000060 explicit SimpleTimer(bool WantTiming) : WantTiming(WantTiming) {
Douglas Gregor213f18b2010-10-28 15:44:59 +000061 if (WantTiming)
Benjamin Krameredfb7ec2010-11-09 20:00:56 +000062 Start = TimeRecord::getCurrentTime();
Douglas Gregor213f18b2010-10-28 15:44:59 +000063 }
64
Chris Lattner5f9e2722011-07-23 10:55:15 +000065 void setOutput(const Twine &Output) {
Douglas Gregor213f18b2010-10-28 15:44:59 +000066 if (WantTiming)
Benjamin Krameredfb7ec2010-11-09 20:00:56 +000067 this->Output = Output.str();
Douglas Gregor213f18b2010-10-28 15:44:59 +000068 }
69
Douglas Gregor213f18b2010-10-28 15:44:59 +000070 ~SimpleTimer() {
71 if (WantTiming) {
72 TimeRecord Elapsed = TimeRecord::getCurrentTime();
73 Elapsed -= Start;
74 llvm::errs() << Output << ':';
75 Elapsed.print(Elapsed, llvm::errs());
76 llvm::errs() << '\n';
77 }
78 }
79 };
Ted Kremenek1872b312011-10-27 17:55:18 +000080
81 struct OnDiskData {
82 /// \brief The file in which the precompiled preamble is stored.
83 std::string PreambleFile;
84
85 /// \brief Temporary files that should be removed when the ASTUnit is
86 /// destroyed.
87 SmallVector<llvm::sys::Path, 4> TemporaryFiles;
88
89 /// \brief Erase temporary files.
90 void CleanTemporaryFiles();
91
92 /// \brief Erase the preamble file.
93 void CleanPreambleFile();
94
95 /// \brief Erase temporary files and the preamble file.
96 void Cleanup();
97 };
98}
99
Ted Kremeneke055f8a2011-10-27 19:44:25 +0000100static llvm::sys::SmartMutex<false> &getOnDiskMutex() {
101 static llvm::sys::SmartMutex<false> M(/* recursive = */ true);
102 return M;
103}
104
Ted Kremenek1872b312011-10-27 17:55:18 +0000105static void cleanupOnDiskMapAtExit(void);
106
107typedef llvm::DenseMap<const ASTUnit *, OnDiskData *> OnDiskDataMap;
108static OnDiskDataMap &getOnDiskDataMap() {
109 static OnDiskDataMap M;
110 static bool hasRegisteredAtExit = false;
111 if (!hasRegisteredAtExit) {
112 hasRegisteredAtExit = true;
113 atexit(cleanupOnDiskMapAtExit);
114 }
115 return M;
116}
117
118static void cleanupOnDiskMapAtExit(void) {
Argyrios Kyrtzidis81788132012-07-03 16:30:52 +0000119 // Use the mutex because there can be an alive thread destroying an ASTUnit.
120 llvm::MutexGuard Guard(getOnDiskMutex());
Ted Kremenek1872b312011-10-27 17:55:18 +0000121 OnDiskDataMap &M = getOnDiskDataMap();
122 for (OnDiskDataMap::iterator I = M.begin(), E = M.end(); I != E; ++I) {
123 // We don't worry about freeing the memory associated with OnDiskDataMap.
124 // All we care about is erasing stale files.
125 I->second->Cleanup();
126 }
127}
128
129static OnDiskData &getOnDiskData(const ASTUnit *AU) {
Ted Kremeneke055f8a2011-10-27 19:44:25 +0000130 // We require the mutex since we are modifying the structure of the
131 // DenseMap.
132 llvm::MutexGuard Guard(getOnDiskMutex());
Ted Kremenek1872b312011-10-27 17:55:18 +0000133 OnDiskDataMap &M = getOnDiskDataMap();
134 OnDiskData *&D = M[AU];
135 if (!D)
136 D = new OnDiskData();
137 return *D;
138}
139
140static void erasePreambleFile(const ASTUnit *AU) {
141 getOnDiskData(AU).CleanPreambleFile();
142}
143
144static void removeOnDiskEntry(const ASTUnit *AU) {
Ted Kremeneke055f8a2011-10-27 19:44:25 +0000145 // We require the mutex since we are modifying the structure of the
146 // DenseMap.
147 llvm::MutexGuard Guard(getOnDiskMutex());
Ted Kremenek1872b312011-10-27 17:55:18 +0000148 OnDiskDataMap &M = getOnDiskDataMap();
149 OnDiskDataMap::iterator I = M.find(AU);
150 if (I != M.end()) {
151 I->second->Cleanup();
152 delete I->second;
153 M.erase(AU);
154 }
155}
156
157static void setPreambleFile(const ASTUnit *AU, llvm::StringRef preambleFile) {
158 getOnDiskData(AU).PreambleFile = preambleFile;
159}
160
161static const std::string &getPreambleFile(const ASTUnit *AU) {
162 return getOnDiskData(AU).PreambleFile;
163}
164
165void OnDiskData::CleanTemporaryFiles() {
166 for (unsigned I = 0, N = TemporaryFiles.size(); I != N; ++I)
167 TemporaryFiles[I].eraseFromDisk();
168 TemporaryFiles.clear();
169}
170
171void OnDiskData::CleanPreambleFile() {
172 if (!PreambleFile.empty()) {
173 llvm::sys::Path(PreambleFile).eraseFromDisk();
174 PreambleFile.clear();
175 }
176}
177
178void OnDiskData::Cleanup() {
179 CleanTemporaryFiles();
180 CleanPreambleFile();
181}
182
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000183struct ASTUnit::ASTWriterData {
184 SmallString<128> Buffer;
185 llvm::BitstreamWriter Stream;
186 ASTWriter Writer;
187
188 ASTWriterData() : Stream(Buffer), Writer(Stream) { }
189};
190
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000191void ASTUnit::clearFileLevelDecls() {
192 for (FileDeclsTy::iterator
193 I = FileDecls.begin(), E = FileDecls.end(); I != E; ++I)
194 delete I->second;
195 FileDecls.clear();
196}
197
Ted Kremenek1872b312011-10-27 17:55:18 +0000198void ASTUnit::CleanTemporaryFiles() {
199 getOnDiskData(this).CleanTemporaryFiles();
200}
201
202void ASTUnit::addTemporaryFile(const llvm::sys::Path &TempFile) {
203 getOnDiskData(this).TemporaryFiles.push_back(TempFile);
Douglas Gregor213f18b2010-10-28 15:44:59 +0000204}
205
Douglas Gregoreababfb2010-08-04 05:53:38 +0000206/// \brief After failing to build a precompiled preamble (due to
207/// errors in the source that occurs in the preamble), the number of
208/// reparses during which we'll skip even trying to precompile the
209/// preamble.
210const unsigned DefaultPreambleRebuildInterval = 5;
211
Douglas Gregore3c60a72010-11-17 00:13:31 +0000212/// \brief Tracks the number of ASTUnit objects that are currently active.
213///
214/// Used for debugging purposes only.
Douglas Gregor1fd9e0d2010-12-07 00:05:48 +0000215static llvm::sys::cas_flag ActiveASTUnitObjects;
Douglas Gregore3c60a72010-11-17 00:13:31 +0000216
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000217ASTUnit::ASTUnit(bool _MainFileIsAST)
Argyrios Kyrtzidis62ba9f62011-11-01 17:14:15 +0000218 : Reader(0), OnlyLocalDecls(false), CaptureDiagnostics(false),
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +0000219 MainFileIsAST(_MainFileIsAST),
Douglas Gregor467dc882011-08-25 22:30:56 +0000220 TUKind(TU_Complete), WantTiming(getenv("LIBCLANG_TIMING")),
Argyrios Kyrtzidis15727dd2011-03-05 01:03:48 +0000221 OwnsRemappedFileBuffers(true),
Douglas Gregor213f18b2010-10-28 15:44:59 +0000222 NumStoredDiagnosticsFromDriver(0),
Douglas Gregor671947b2010-08-19 01:33:06 +0000223 PreambleRebuildCounter(0), SavedMainFileBuffer(0), PreambleBuffer(0),
Argyrios Kyrtzidis98704012011-11-29 18:18:33 +0000224 NumWarningsInPreamble(0),
Douglas Gregor727d93e2010-08-17 00:40:40 +0000225 ShouldCacheCodeCompletionResults(false),
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +0000226 IncludeBriefCommentsInCodeCompletion(false), UserFilesAreVolatile(false),
Douglas Gregor9b7db622011-02-16 18:16:54 +0000227 CompletionCacheTopLevelHashValue(0),
228 PreambleTopLevelHashValue(0),
229 CurrentTopLevelHashValue(0),
Douglas Gregor8b1540c2010-08-19 00:45:44 +0000230 UnsafeToFree(false) {
Douglas Gregore3c60a72010-11-17 00:13:31 +0000231 if (getenv("LIBCLANG_OBJTRACKING")) {
Douglas Gregor1fd9e0d2010-12-07 00:05:48 +0000232 llvm::sys::AtomicIncrement(&ActiveASTUnitObjects);
Douglas Gregore3c60a72010-11-17 00:13:31 +0000233 fprintf(stderr, "+++ %d translation units\n", ActiveASTUnitObjects);
234 }
Douglas Gregor385103b2010-07-30 20:58:08 +0000235}
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000236
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000237ASTUnit::~ASTUnit() {
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000238 clearFileLevelDecls();
239
Ted Kremenek1872b312011-10-27 17:55:18 +0000240 // Clean up the temporary files and the preamble file.
241 removeOnDiskEntry(this);
242
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000243 // Free the buffers associated with remapped files. We are required to
244 // perform this operation here because we explicitly request that the
245 // compiler instance *not* free these buffers for each invocation of the
246 // parser.
Ted Kremenek4f327862011-03-21 18:40:17 +0000247 if (Invocation.getPtr() && OwnsRemappedFileBuffers) {
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000248 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
249 for (PreprocessorOptions::remapped_file_buffer_iterator
250 FB = PPOpts.remapped_file_buffer_begin(),
251 FBEnd = PPOpts.remapped_file_buffer_end();
252 FB != FBEnd;
253 ++FB)
254 delete FB->second;
255 }
Douglas Gregor28233422010-07-27 14:52:07 +0000256
257 delete SavedMainFileBuffer;
Douglas Gregor671947b2010-08-19 01:33:06 +0000258 delete PreambleBuffer;
259
Douglas Gregor213f18b2010-10-28 15:44:59 +0000260 ClearCachedCompletionResults();
Douglas Gregore3c60a72010-11-17 00:13:31 +0000261
262 if (getenv("LIBCLANG_OBJTRACKING")) {
Douglas Gregor1fd9e0d2010-12-07 00:05:48 +0000263 llvm::sys::AtomicDecrement(&ActiveASTUnitObjects);
Douglas Gregore3c60a72010-11-17 00:13:31 +0000264 fprintf(stderr, "--- %d translation units\n", ActiveASTUnitObjects);
265 }
Douglas Gregorabc563f2010-07-19 21:46:24 +0000266}
267
Argyrios Kyrtzidis7fe90f32012-01-17 18:48:07 +0000268void ASTUnit::setPreprocessor(Preprocessor *pp) { PP = pp; }
269
Douglas Gregor8071e422010-08-15 06:18:01 +0000270/// \brief Determine the set of code-completion contexts in which this
271/// declaration should be shown.
272static unsigned getDeclShowContexts(NamedDecl *ND,
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000273 const LangOptions &LangOpts,
274 bool &IsNestedNameSpecifier) {
275 IsNestedNameSpecifier = false;
276
Douglas Gregor8071e422010-08-15 06:18:01 +0000277 if (isa<UsingShadowDecl>(ND))
278 ND = dyn_cast<NamedDecl>(ND->getUnderlyingDecl());
279 if (!ND)
280 return 0;
281
Richard Smith026b3582012-08-14 03:13:00 +0000282 uint64_t Contexts = 0;
Douglas Gregor8071e422010-08-15 06:18:01 +0000283 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND) ||
284 isa<ClassTemplateDecl>(ND) || isa<TemplateTemplateParmDecl>(ND)) {
285 // Types can appear in these contexts.
286 if (LangOpts.CPlusPlus || !isa<TagDecl>(ND))
Richard Smith026b3582012-08-14 03:13:00 +0000287 Contexts |= (1LL << CodeCompletionContext::CCC_TopLevel)
288 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
289 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
290 | (1LL << CodeCompletionContext::CCC_Statement)
291 | (1LL << CodeCompletionContext::CCC_Type)
292 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression);
Douglas Gregor8071e422010-08-15 06:18:01 +0000293
294 // In C++, types can appear in expressions contexts (for functional casts).
295 if (LangOpts.CPlusPlus)
Richard Smith026b3582012-08-14 03:13:00 +0000296 Contexts |= (1LL << CodeCompletionContext::CCC_Expression);
Douglas Gregor8071e422010-08-15 06:18:01 +0000297
298 // In Objective-C, message sends can send interfaces. In Objective-C++,
299 // all types are available due to functional casts.
300 if (LangOpts.CPlusPlus || isa<ObjCInterfaceDecl>(ND))
Richard Smith026b3582012-08-14 03:13:00 +0000301 Contexts |= (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver);
Douglas Gregor3da626b2011-07-07 16:03:39 +0000302
303 // In Objective-C, you can only be a subclass of another Objective-C class
304 if (isa<ObjCInterfaceDecl>(ND))
Richard Smith026b3582012-08-14 03:13:00 +0000305 Contexts |= (1LL << CodeCompletionContext::CCC_ObjCInterfaceName);
Douglas Gregor8071e422010-08-15 06:18:01 +0000306
307 // Deal with tag names.
308 if (isa<EnumDecl>(ND)) {
Richard Smith026b3582012-08-14 03:13:00 +0000309 Contexts |= (1LL << CodeCompletionContext::CCC_EnumTag);
Douglas Gregor8071e422010-08-15 06:18:01 +0000310
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000311 // Part of the nested-name-specifier in C++0x.
Douglas Gregor8071e422010-08-15 06:18:01 +0000312 if (LangOpts.CPlusPlus0x)
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000313 IsNestedNameSpecifier = true;
Douglas Gregor8071e422010-08-15 06:18:01 +0000314 } else if (RecordDecl *Record = dyn_cast<RecordDecl>(ND)) {
315 if (Record->isUnion())
Richard Smith026b3582012-08-14 03:13:00 +0000316 Contexts |= (1LL << CodeCompletionContext::CCC_UnionTag);
Douglas Gregor8071e422010-08-15 06:18:01 +0000317 else
Richard Smith026b3582012-08-14 03:13:00 +0000318 Contexts |= (1LL << CodeCompletionContext::CCC_ClassOrStructTag);
Douglas Gregor8071e422010-08-15 06:18:01 +0000319
Douglas Gregor8071e422010-08-15 06:18:01 +0000320 if (LangOpts.CPlusPlus)
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000321 IsNestedNameSpecifier = true;
Douglas Gregor52779fb2010-09-23 23:01:17 +0000322 } else if (isa<ClassTemplateDecl>(ND))
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000323 IsNestedNameSpecifier = true;
Douglas Gregor8071e422010-08-15 06:18:01 +0000324 } else if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
325 // Values can appear in these contexts.
Richard Smith026b3582012-08-14 03:13:00 +0000326 Contexts = (1LL << CodeCompletionContext::CCC_Statement)
327 | (1LL << CodeCompletionContext::CCC_Expression)
328 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
329 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver);
Douglas Gregor8071e422010-08-15 06:18:01 +0000330 } else if (isa<ObjCProtocolDecl>(ND)) {
Richard Smith026b3582012-08-14 03:13:00 +0000331 Contexts = (1LL << CodeCompletionContext::CCC_ObjCProtocolName);
Douglas Gregor3da626b2011-07-07 16:03:39 +0000332 } else if (isa<ObjCCategoryDecl>(ND)) {
Richard Smith026b3582012-08-14 03:13:00 +0000333 Contexts = (1LL << CodeCompletionContext::CCC_ObjCCategoryName);
Douglas Gregor8071e422010-08-15 06:18:01 +0000334 } else if (isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) {
Richard Smith026b3582012-08-14 03:13:00 +0000335 Contexts = (1LL << CodeCompletionContext::CCC_Namespace);
Douglas Gregor8071e422010-08-15 06:18:01 +0000336
337 // Part of the nested-name-specifier.
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000338 IsNestedNameSpecifier = true;
Douglas Gregor8071e422010-08-15 06:18:01 +0000339 }
340
341 return Contexts;
342}
343
Douglas Gregor87c08a52010-08-13 22:48:40 +0000344void ASTUnit::CacheCodeCompletionResults() {
345 if (!TheSema)
346 return;
347
Douglas Gregor213f18b2010-10-28 15:44:59 +0000348 SimpleTimer Timer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +0000349 Timer.setOutput("Cache global code completions for " + getMainFileName());
Douglas Gregor87c08a52010-08-13 22:48:40 +0000350
351 // Clear out the previous results.
352 ClearCachedCompletionResults();
353
354 // Gather the set of global code completions.
John McCall0a2c5e22010-08-25 06:19:51 +0000355 typedef CodeCompletionResult Result;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000356 SmallVector<Result, 8> Results;
Douglas Gregor48601b32011-02-16 19:08:06 +0000357 CachedCompletionAllocator = new GlobalCodeCompletionAllocator;
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +0000358 TheSema->GatherGlobalCodeCompletions(*CachedCompletionAllocator,
359 getCodeCompletionTUInfo(), Results);
Douglas Gregor87c08a52010-08-13 22:48:40 +0000360
361 // Translate global code completions into cached completions.
Douglas Gregorf5586f62010-08-16 18:08:11 +0000362 llvm::DenseMap<CanQualType, unsigned> CompletionTypes;
363
Douglas Gregor87c08a52010-08-13 22:48:40 +0000364 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
365 switch (Results[I].Kind) {
Douglas Gregor8071e422010-08-15 06:18:01 +0000366 case Result::RK_Declaration: {
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000367 bool IsNestedNameSpecifier = false;
Douglas Gregor8071e422010-08-15 06:18:01 +0000368 CachedCodeCompletionResult CachedResult;
Douglas Gregor218937c2011-02-01 19:23:04 +0000369 CachedResult.Completion = Results[I].CreateCodeCompletionString(*TheSema,
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +0000370 *CachedCompletionAllocator,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +0000371 getCodeCompletionTUInfo(),
372 IncludeBriefCommentsInCodeCompletion);
Douglas Gregor8071e422010-08-15 06:18:01 +0000373 CachedResult.ShowInContexts = getDeclShowContexts(Results[I].Declaration,
David Blaikie4e4d0842012-03-11 07:00:24 +0000374 Ctx->getLangOpts(),
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000375 IsNestedNameSpecifier);
Douglas Gregor8071e422010-08-15 06:18:01 +0000376 CachedResult.Priority = Results[I].Priority;
377 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregor58ddb602010-08-23 23:00:57 +0000378 CachedResult.Availability = Results[I].Availability;
Douglas Gregorc4421e92010-08-16 16:46:30 +0000379
Douglas Gregorf5586f62010-08-16 18:08:11 +0000380 // Keep track of the type of this completion in an ASTContext-agnostic
381 // way.
Douglas Gregorc4421e92010-08-16 16:46:30 +0000382 QualType UsageType = getDeclUsageType(*Ctx, Results[I].Declaration);
Douglas Gregorf5586f62010-08-16 18:08:11 +0000383 if (UsageType.isNull()) {
Douglas Gregorc4421e92010-08-16 16:46:30 +0000384 CachedResult.TypeClass = STC_Void;
Douglas Gregorf5586f62010-08-16 18:08:11 +0000385 CachedResult.Type = 0;
386 } else {
387 CanQualType CanUsageType
388 = Ctx->getCanonicalType(UsageType.getUnqualifiedType());
389 CachedResult.TypeClass = getSimplifiedTypeClass(CanUsageType);
390
391 // Determine whether we have already seen this type. If so, we save
392 // ourselves the work of formatting the type string by using the
393 // temporary, CanQualType-based hash table to find the associated value.
394 unsigned &TypeValue = CompletionTypes[CanUsageType];
395 if (TypeValue == 0) {
396 TypeValue = CompletionTypes.size();
397 CachedCompletionTypes[QualType(CanUsageType).getAsString()]
398 = TypeValue;
399 }
400
401 CachedResult.Type = TypeValue;
Douglas Gregorc4421e92010-08-16 16:46:30 +0000402 }
Douglas Gregorf5586f62010-08-16 18:08:11 +0000403
Douglas Gregor8071e422010-08-15 06:18:01 +0000404 CachedCompletionResults.push_back(CachedResult);
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000405
406 /// Handle nested-name-specifiers in C++.
David Blaikie4e4d0842012-03-11 07:00:24 +0000407 if (TheSema->Context.getLangOpts().CPlusPlus &&
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000408 IsNestedNameSpecifier && !Results[I].StartsNestedNameSpecifier) {
409 // The contexts in which a nested-name-specifier can appear in C++.
Richard Smith026b3582012-08-14 03:13:00 +0000410 uint64_t NNSContexts
411 = (1LL << CodeCompletionContext::CCC_TopLevel)
412 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
413 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
414 | (1LL << CodeCompletionContext::CCC_Statement)
415 | (1LL << CodeCompletionContext::CCC_Expression)
416 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
417 | (1LL << CodeCompletionContext::CCC_EnumTag)
418 | (1LL << CodeCompletionContext::CCC_UnionTag)
419 | (1LL << CodeCompletionContext::CCC_ClassOrStructTag)
420 | (1LL << CodeCompletionContext::CCC_Type)
421 | (1LL << CodeCompletionContext::CCC_PotentiallyQualifiedName)
422 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression);
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000423
424 if (isa<NamespaceDecl>(Results[I].Declaration) ||
425 isa<NamespaceAliasDecl>(Results[I].Declaration))
Richard Smith026b3582012-08-14 03:13:00 +0000426 NNSContexts |= (1LL << CodeCompletionContext::CCC_Namespace);
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000427
428 if (unsigned RemainingContexts
429 = NNSContexts & ~CachedResult.ShowInContexts) {
430 // If there any contexts where this completion can be a
431 // nested-name-specifier but isn't already an option, create a
432 // nested-name-specifier completion.
433 Results[I].StartsNestedNameSpecifier = true;
Douglas Gregor218937c2011-02-01 19:23:04 +0000434 CachedResult.Completion
435 = Results[I].CreateCodeCompletionString(*TheSema,
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +0000436 *CachedCompletionAllocator,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +0000437 getCodeCompletionTUInfo(),
438 IncludeBriefCommentsInCodeCompletion);
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000439 CachedResult.ShowInContexts = RemainingContexts;
440 CachedResult.Priority = CCP_NestedNameSpecifier;
441 CachedResult.TypeClass = STC_Void;
442 CachedResult.Type = 0;
443 CachedCompletionResults.push_back(CachedResult);
444 }
445 }
Douglas Gregor87c08a52010-08-13 22:48:40 +0000446 break;
Douglas Gregor8071e422010-08-15 06:18:01 +0000447 }
448
Douglas Gregor87c08a52010-08-13 22:48:40 +0000449 case Result::RK_Keyword:
450 case Result::RK_Pattern:
451 // Ignore keywords and patterns; we don't care, since they are so
452 // easily regenerated.
453 break;
454
455 case Result::RK_Macro: {
456 CachedCodeCompletionResult CachedResult;
Douglas Gregor218937c2011-02-01 19:23:04 +0000457 CachedResult.Completion
458 = Results[I].CreateCodeCompletionString(*TheSema,
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +0000459 *CachedCompletionAllocator,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +0000460 getCodeCompletionTUInfo(),
461 IncludeBriefCommentsInCodeCompletion);
Douglas Gregor87c08a52010-08-13 22:48:40 +0000462 CachedResult.ShowInContexts
Richard Smith026b3582012-08-14 03:13:00 +0000463 = (1LL << CodeCompletionContext::CCC_TopLevel)
464 | (1LL << CodeCompletionContext::CCC_ObjCInterface)
465 | (1LL << CodeCompletionContext::CCC_ObjCImplementation)
466 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
467 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
468 | (1LL << CodeCompletionContext::CCC_Statement)
469 | (1LL << CodeCompletionContext::CCC_Expression)
470 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
471 | (1LL << CodeCompletionContext::CCC_MacroNameUse)
472 | (1LL << CodeCompletionContext::CCC_PreprocessorExpression)
473 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
474 | (1LL << CodeCompletionContext::CCC_OtherWithMacros);
Douglas Gregor2ccccb32010-08-23 18:23:48 +0000475
Douglas Gregor87c08a52010-08-13 22:48:40 +0000476 CachedResult.Priority = Results[I].Priority;
477 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregor58ddb602010-08-23 23:00:57 +0000478 CachedResult.Availability = Results[I].Availability;
Douglas Gregor1827e102010-08-16 16:18:59 +0000479 CachedResult.TypeClass = STC_Void;
Douglas Gregorf5586f62010-08-16 18:08:11 +0000480 CachedResult.Type = 0;
Douglas Gregor87c08a52010-08-13 22:48:40 +0000481 CachedCompletionResults.push_back(CachedResult);
482 break;
483 }
484 }
Douglas Gregor87c08a52010-08-13 22:48:40 +0000485 }
Douglas Gregor9b7db622011-02-16 18:16:54 +0000486
487 // Save the current top-level hash value.
488 CompletionCacheTopLevelHashValue = CurrentTopLevelHashValue;
Douglas Gregor87c08a52010-08-13 22:48:40 +0000489}
490
491void ASTUnit::ClearCachedCompletionResults() {
Douglas Gregor87c08a52010-08-13 22:48:40 +0000492 CachedCompletionResults.clear();
Douglas Gregorf5586f62010-08-16 18:08:11 +0000493 CachedCompletionTypes.clear();
Douglas Gregor48601b32011-02-16 19:08:06 +0000494 CachedCompletionAllocator = 0;
Douglas Gregor87c08a52010-08-13 22:48:40 +0000495}
496
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000497namespace {
498
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000499/// \brief Gathers information from ASTReader that will be used to initialize
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000500/// a Preprocessor.
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000501class ASTInfoCollector : public ASTReaderListener {
Douglas Gregor998b3d32011-09-01 23:39:15 +0000502 Preprocessor &PP;
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000503 ASTContext &Context;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000504 LangOptions &LangOpt;
505 HeaderSearch &HSI;
Douglas Gregor57016dd2012-10-16 23:40:58 +0000506 IntrusiveRefCntPtr<TargetOptions> &TargetOpts;
Dylan Noblesmithc93dc782012-02-20 14:00:23 +0000507 IntrusiveRefCntPtr<TargetInfo> &Target;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000508 std::string &Predefines;
509 unsigned &Counter;
Mike Stump1eb44332009-09-09 15:08:12 +0000510
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000511 unsigned NumHeaderInfos;
Mike Stump1eb44332009-09-09 15:08:12 +0000512
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000513 bool InitializedLanguage;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000514public:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000515 ASTInfoCollector(Preprocessor &PP, ASTContext &Context, LangOptions &LangOpt,
Douglas Gregor57016dd2012-10-16 23:40:58 +0000516 HeaderSearch &HSI,
517 IntrusiveRefCntPtr<TargetOptions> &TargetOpts,
Dylan Noblesmithc93dc782012-02-20 14:00:23 +0000518 IntrusiveRefCntPtr<TargetInfo> &Target,
Douglas Gregor998b3d32011-09-01 23:39:15 +0000519 std::string &Predefines,
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000520 unsigned &Counter)
Douglas Gregor9a022bb2012-10-15 16:45:32 +0000521 : PP(PP), Context(Context), LangOpt(LangOpt), HSI(HSI),
522 TargetOpts(TargetOpts), Target(Target),
Douglas Gregor998b3d32011-09-01 23:39:15 +0000523 Predefines(Predefines), Counter(Counter), NumHeaderInfos(0),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000524 InitializedLanguage(false) {}
Mike Stump1eb44332009-09-09 15:08:12 +0000525
Argyrios Kyrtzidis62288ed2012-10-10 02:12:47 +0000526 virtual bool ReadLanguageOptions(const serialization::ModuleFile &M,
Douglas Gregor38295be2012-10-22 23:51:00 +0000527 const LangOptions &LangOpts,
528 bool Complain) {
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000529 if (InitializedLanguage)
Douglas Gregor998b3d32011-09-01 23:39:15 +0000530 return false;
531
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000532 assert(M.Kind == serialization::MK_MainFile);
Argyrios Kyrtzidis7f186332012-09-14 20:24:53 +0000533
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000534 LangOpt = LangOpts;
535 InitializedLanguage = true;
536
537 updated();
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000538 return false;
539 }
Mike Stump1eb44332009-09-09 15:08:12 +0000540
Douglas Gregor57016dd2012-10-16 23:40:58 +0000541 virtual bool ReadTargetOptions(const serialization::ModuleFile &M,
Douglas Gregor38295be2012-10-22 23:51:00 +0000542 const TargetOptions &TargetOpts,
543 bool Complain) {
Douglas Gregor998b3d32011-09-01 23:39:15 +0000544 // If we've already initialized the target, don't do it again.
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000545 if (Target)
Douglas Gregor998b3d32011-09-01 23:39:15 +0000546 return false;
547
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000548 assert(M.Kind == serialization::MK_MainFile);
549
Douglas Gregor57016dd2012-10-16 23:40:58 +0000550
551 this->TargetOpts = new TargetOptions(TargetOpts);
552 Target = TargetInfo::CreateTargetInfo(PP.getDiagnostics(),
553 *this->TargetOpts);
Argyrios Kyrtzidis7f186332012-09-14 20:24:53 +0000554
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000555 updated();
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000556 return false;
557 }
Mike Stump1eb44332009-09-09 15:08:12 +0000558
Sebastian Redlcb481aa2010-07-14 23:29:55 +0000559 virtual bool ReadPredefinesBuffer(const PCHPredefinesBlocks &Buffers,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000560 StringRef OriginalFileName,
Nick Lewycky277a6e72011-02-23 21:16:44 +0000561 std::string &SuggestedPredefines,
Douglas Gregor38295be2012-10-22 23:51:00 +0000562 FileManager &FileMgr,
563 bool Complain) {
Sebastian Redlcb481aa2010-07-14 23:29:55 +0000564 Predefines = Buffers[0].Data;
565 for (unsigned I = 1, N = Buffers.size(); I != N; ++I) {
566 Predefines += Buffers[I].Data;
567 }
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000568 return false;
569 }
Mike Stump1eb44332009-09-09 15:08:12 +0000570
Douglas Gregorec1afbf2010-03-16 19:09:18 +0000571 virtual void ReadHeaderFileInfo(const HeaderFileInfo &HFI, unsigned ID) {
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000572 HSI.setHeaderFileInfoForUID(HFI, NumHeaderInfos++);
573 }
Mike Stump1eb44332009-09-09 15:08:12 +0000574
Argyrios Kyrtzidis62288ed2012-10-10 02:12:47 +0000575 virtual void ReadCounter(const serialization::ModuleFile &M, unsigned Value) {
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000576 Counter = Value;
577 }
Argyrios Kyrtzidis7f186332012-09-14 20:24:53 +0000578
579private:
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000580 void updated() {
581 if (!Target || !InitializedLanguage)
582 return;
583
584 // Inform the target of the language options.
585 //
586 // FIXME: We shouldn't need to do this, the target should be immutable once
587 // created. This complexity should be lifted elsewhere.
588 Target->setForcedLangOptions(LangOpt);
589
590 // Initialize the preprocessor.
591 PP.Initialize(*Target);
592
593 // Initialize the ASTContext
594 Context.InitBuiltinTypes(*Target);
Argyrios Kyrtzidis7f186332012-09-14 20:24:53 +0000595 }
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000596};
597
David Blaikie26e7a902011-09-26 00:01:39 +0000598class StoredDiagnosticConsumer : public DiagnosticConsumer {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000599 SmallVectorImpl<StoredDiagnostic> &StoredDiags;
Douglas Gregora88084b2010-02-18 18:08:43 +0000600
601public:
David Blaikie26e7a902011-09-26 00:01:39 +0000602 explicit StoredDiagnosticConsumer(
Chris Lattner5f9e2722011-07-23 10:55:15 +0000603 SmallVectorImpl<StoredDiagnostic> &StoredDiags)
Douglas Gregora88084b2010-02-18 18:08:43 +0000604 : StoredDiags(StoredDiags) { }
605
David Blaikied6471f72011-09-25 23:23:43 +0000606 virtual void HandleDiagnostic(DiagnosticsEngine::Level Level,
David Blaikie40847cf2011-09-26 01:18:08 +0000607 const Diagnostic &Info);
Douglas Gregoraee526e2011-09-29 00:38:00 +0000608
609 DiagnosticConsumer *clone(DiagnosticsEngine &Diags) const {
610 // Just drop any diagnostics that come from cloned consumers; they'll
611 // have different source managers anyway.
Douglas Gregor85ae12d2012-01-29 19:57:03 +0000612 // FIXME: We'd like to be able to capture these somehow, even if it's just
613 // file/line/column, because they could occur when parsing module maps or
614 // building modules on-demand.
Douglas Gregoraee526e2011-09-29 00:38:00 +0000615 return new IgnoringDiagConsumer();
616 }
Douglas Gregora88084b2010-02-18 18:08:43 +0000617};
618
619/// \brief RAII object that optionally captures diagnostics, if
620/// there is no diagnostic client to capture them already.
621class CaptureDroppedDiagnostics {
David Blaikied6471f72011-09-25 23:23:43 +0000622 DiagnosticsEngine &Diags;
David Blaikie26e7a902011-09-26 00:01:39 +0000623 StoredDiagnosticConsumer Client;
David Blaikie78ad0b92011-09-25 23:39:51 +0000624 DiagnosticConsumer *PreviousClient;
Douglas Gregora88084b2010-02-18 18:08:43 +0000625
626public:
David Blaikied6471f72011-09-25 23:23:43 +0000627 CaptureDroppedDiagnostics(bool RequestCapture, DiagnosticsEngine &Diags,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000628 SmallVectorImpl<StoredDiagnostic> &StoredDiags)
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000629 : Diags(Diags), Client(StoredDiags), PreviousClient(0)
Douglas Gregora88084b2010-02-18 18:08:43 +0000630 {
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000631 if (RequestCapture || Diags.getClient() == 0) {
632 PreviousClient = Diags.takeClient();
Douglas Gregora88084b2010-02-18 18:08:43 +0000633 Diags.setClient(&Client);
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000634 }
Douglas Gregora88084b2010-02-18 18:08:43 +0000635 }
636
637 ~CaptureDroppedDiagnostics() {
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000638 if (Diags.getClient() == &Client) {
639 Diags.takeClient();
640 Diags.setClient(PreviousClient);
641 }
Douglas Gregora88084b2010-02-18 18:08:43 +0000642 }
643};
644
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000645} // anonymous namespace
646
David Blaikie26e7a902011-09-26 00:01:39 +0000647void StoredDiagnosticConsumer::HandleDiagnostic(DiagnosticsEngine::Level Level,
David Blaikie40847cf2011-09-26 01:18:08 +0000648 const Diagnostic &Info) {
Argyrios Kyrtzidisf2224d82010-11-18 20:06:46 +0000649 // Default implementation (Warnings/errors count).
David Blaikie78ad0b92011-09-25 23:39:51 +0000650 DiagnosticConsumer::HandleDiagnostic(Level, Info);
Argyrios Kyrtzidisf2224d82010-11-18 20:06:46 +0000651
Douglas Gregora88084b2010-02-18 18:08:43 +0000652 StoredDiags.push_back(StoredDiagnostic(Level, Info));
653}
654
Steve Naroff77accc12009-09-03 18:19:54 +0000655const std::string &ASTUnit::getOriginalSourceFileName() {
Daniel Dunbar68d40e22009-12-02 08:44:16 +0000656 return OriginalSourceFile;
Steve Naroff77accc12009-09-03 18:19:54 +0000657}
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000658
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000659ASTDeserializationListener *ASTUnit::getDeserializationListener() {
660 if (WriterData)
661 return &WriterData->Writer;
662 return 0;
663}
664
Chris Lattner5f9e2722011-07-23 10:55:15 +0000665llvm::MemoryBuffer *ASTUnit::getBufferForFile(StringRef Filename,
Chris Lattner75dfb652010-11-23 09:19:42 +0000666 std::string *ErrorStr) {
Chris Lattner39b49bc2010-11-23 08:35:12 +0000667 assert(FileMgr);
Chris Lattner75dfb652010-11-23 09:19:42 +0000668 return FileMgr->getBufferForFile(Filename, ErrorStr);
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +0000669}
670
Douglas Gregore47be3e2010-11-11 00:39:14 +0000671/// \brief Configure the diagnostics object for use with ASTUnit.
Dylan Noblesmithc93dc782012-02-20 14:00:23 +0000672void ASTUnit::ConfigureDiags(IntrusiveRefCntPtr<DiagnosticsEngine> &Diags,
Douglas Gregor0b53cf82011-01-19 01:02:47 +0000673 const char **ArgBegin, const char **ArgEnd,
Douglas Gregore47be3e2010-11-11 00:39:14 +0000674 ASTUnit &AST, bool CaptureDiagnostics) {
675 if (!Diags.getPtr()) {
676 // No diagnostics engine was provided, so create our own diagnostics object
677 // with the default options.
678 DiagnosticOptions DiagOpts;
David Blaikie78ad0b92011-09-25 23:39:51 +0000679 DiagnosticConsumer *Client = 0;
Douglas Gregore47be3e2010-11-11 00:39:14 +0000680 if (CaptureDiagnostics)
David Blaikie26e7a902011-09-26 00:01:39 +0000681 Client = new StoredDiagnosticConsumer(AST.StoredDiagnostics);
Benjamin Kramerbcadf962012-04-14 09:11:56 +0000682 Diags = CompilerInstance::createDiagnostics(DiagOpts, ArgEnd-ArgBegin,
683 ArgBegin, Client,
684 /*ShouldOwnClient=*/true,
685 /*ShouldCloneClient=*/false);
Douglas Gregore47be3e2010-11-11 00:39:14 +0000686 } else if (CaptureDiagnostics) {
David Blaikie26e7a902011-09-26 00:01:39 +0000687 Diags->setClient(new StoredDiagnosticConsumer(AST.StoredDiagnostics));
Douglas Gregore47be3e2010-11-11 00:39:14 +0000688 }
689}
690
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000691ASTUnit *ASTUnit::LoadFromASTFile(const std::string &Filename,
Dylan Noblesmithc93dc782012-02-20 14:00:23 +0000692 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +0000693 const FileSystemOptions &FileSystemOpts,
Ted Kremenek5cf48762009-10-17 00:34:24 +0000694 bool OnlyLocalDecls,
Douglas Gregor4db64a42010-01-23 00:14:00 +0000695 RemappedFile *RemappedFiles,
Douglas Gregora88084b2010-02-18 18:08:43 +0000696 unsigned NumRemappedFiles,
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +0000697 bool CaptureDiagnostics,
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +0000698 bool AllowPCHWithCompilerErrors,
699 bool UserFilesAreVolatile) {
Dylan Noblesmith6f42b622012-02-05 02:12:40 +0000700 OwningPtr<ASTUnit> AST(new ASTUnit(true));
Ted Kremenekb547eeb2011-03-18 02:06:56 +0000701
702 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +0000703 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
704 ASTUnitCleanup(AST.get());
David Blaikied6471f72011-09-25 23:23:43 +0000705 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
706 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Ted Kremenek25a11e12011-03-22 01:15:24 +0000707 DiagCleanup(Diags.getPtr());
Ted Kremenekb547eeb2011-03-18 02:06:56 +0000708
Douglas Gregor0b53cf82011-01-19 01:02:47 +0000709 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
Douglas Gregorabc563f2010-07-19 21:46:24 +0000710
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000711 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregore47be3e2010-11-11 00:39:14 +0000712 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor28019772010-04-05 23:52:57 +0000713 AST->Diagnostics = Diags;
Ted Kremenek4f327862011-03-21 18:40:17 +0000714 AST->FileMgr = new FileManager(FileSystemOpts);
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +0000715 AST->UserFilesAreVolatile = UserFilesAreVolatile;
Ted Kremenek4f327862011-03-21 18:40:17 +0000716 AST->SourceMgr = new SourceManager(AST->getDiagnostics(),
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +0000717 AST->getFileManager(),
718 UserFilesAreVolatile);
Douglas Gregor8e238062011-11-11 00:35:06 +0000719 AST->HeaderInfo.reset(new HeaderSearch(AST->getFileManager(),
Douglas Gregor51f564f2011-12-31 04:05:44 +0000720 AST->getDiagnostics(),
Douglas Gregordc58aa72012-01-30 06:01:29 +0000721 AST->ASTFileLangOpts,
722 /*Target=*/0));
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000723
Douglas Gregor4db64a42010-01-23 00:14:00 +0000724 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000725 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
726 if (const llvm::MemoryBuffer *
727 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
728 // Create the file entry for the file that we're mapping from.
729 const FileEntry *FromFile
730 = AST->getFileManager().getVirtualFile(RemappedFiles[I].first,
731 memBuf->getBufferSize(),
732 0);
733 if (!FromFile) {
734 AST->getDiagnostics().Report(diag::err_fe_remap_missing_from_file)
735 << RemappedFiles[I].first;
736 delete memBuf;
737 continue;
738 }
739
740 // Override the contents of the "from" file with the contents of
741 // the "to" file.
742 AST->getSourceManager().overrideFileContents(FromFile, memBuf);
743
744 } else {
745 const char *fname = fileOrBuf.get<const char *>();
746 const FileEntry *ToFile = AST->FileMgr->getFile(fname);
747 if (!ToFile) {
748 AST->getDiagnostics().Report(diag::err_fe_remap_missing_to_file)
749 << RemappedFiles[I].first << fname;
750 continue;
751 }
752
753 // Create the file entry for the file that we're mapping from.
754 const FileEntry *FromFile
755 = AST->getFileManager().getVirtualFile(RemappedFiles[I].first,
756 ToFile->getSize(),
757 0);
758 if (!FromFile) {
759 AST->getDiagnostics().Report(diag::err_fe_remap_missing_from_file)
760 << RemappedFiles[I].first;
761 delete memBuf;
762 continue;
763 }
764
765 // Override the contents of the "from" file with the contents of
766 // the "to" file.
767 AST->getSourceManager().overrideFileContents(FromFile, ToFile);
Douglas Gregor4db64a42010-01-23 00:14:00 +0000768 }
Douglas Gregor4db64a42010-01-23 00:14:00 +0000769 }
770
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000771 // Gather Info for preprocessor construction later on.
Mike Stump1eb44332009-09-09 15:08:12 +0000772
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000773 HeaderSearch &HeaderInfo = *AST->HeaderInfo.get();
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000774 std::string Predefines;
775 unsigned Counter;
776
Dylan Noblesmith6f42b622012-02-05 02:12:40 +0000777 OwningPtr<ASTReader> Reader;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000778
Douglas Gregor998b3d32011-09-01 23:39:15 +0000779 AST->PP = new Preprocessor(AST->getDiagnostics(), AST->ASTFileLangOpts,
780 /*Target=*/0, AST->getSourceManager(), HeaderInfo,
781 *AST,
782 /*IILookup=*/0,
783 /*OwnsHeaderSearch=*/false,
784 /*DelayInitialization=*/true);
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000785 Preprocessor &PP = *AST->PP;
786
787 AST->Ctx = new ASTContext(AST->ASTFileLangOpts,
788 AST->getSourceManager(),
789 /*Target=*/0,
790 PP.getIdentifierTable(),
791 PP.getSelectorTable(),
792 PP.getBuiltinInfo(),
793 /* size_reserve = */0,
794 /*DelayInitialization=*/true);
795 ASTContext &Context = *AST->Ctx;
Douglas Gregor998b3d32011-09-01 23:39:15 +0000796
Argyrios Kyrtzidis98e95bf2012-09-15 01:10:20 +0000797 bool disableValid = false;
798 if (::getenv("LIBCLANG_DISABLE_PCH_VALIDATION"))
799 disableValid = true;
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +0000800 Reader.reset(new ASTReader(PP, Context,
801 /*isysroot=*/"",
Argyrios Kyrtzidis98e95bf2012-09-15 01:10:20 +0000802 /*DisableValidation=*/disableValid,
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +0000803 /*DisableStatCache=*/false,
804 AllowPCHWithCompilerErrors));
Ted Kremenek8c647de2011-05-04 23:27:12 +0000805
806 // Recover resources if we crash before exiting this method.
807 llvm::CrashRecoveryContextCleanupRegistrar<ASTReader>
808 ReaderCleanup(Reader.get());
809
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000810 Reader->setListener(new ASTInfoCollector(*AST->PP, Context,
Douglas Gregor998b3d32011-09-01 23:39:15 +0000811 AST->ASTFileLangOpts, HeaderInfo,
Douglas Gregor9a022bb2012-10-15 16:45:32 +0000812 AST->TargetOpts, AST->Target,
813 Predefines, Counter));
Daniel Dunbarcc318932009-09-03 05:59:35 +0000814
Douglas Gregor38295be2012-10-22 23:51:00 +0000815 switch (Reader->ReadAST(Filename, serialization::MK_MainFile,
816 ASTReader::ARR_None)) {
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000817 case ASTReader::Success:
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000818 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000819
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000820 case ASTReader::Failure:
Douglas Gregor4825fd72012-10-22 22:50:17 +0000821 case ASTReader::OutOfDate:
822 case ASTReader::VersionMismatch:
823 case ASTReader::ConfigurationMismatch:
824 case ASTReader::HadErrors:
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000825 AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000826 return NULL;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000827 }
Mike Stump1eb44332009-09-09 15:08:12 +0000828
Daniel Dunbar68d40e22009-12-02 08:44:16 +0000829 AST->OriginalSourceFile = Reader->getOriginalSourceFile();
830
Daniel Dunbard5b61262009-09-21 03:03:47 +0000831 PP.setPredefines(Reader->getSuggestedPredefines());
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000832 PP.setCounterValue(Counter);
Mike Stump1eb44332009-09-09 15:08:12 +0000833
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000834 // Attach the AST reader to the AST context as an external AST
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000835 // source, so that declarations will be deserialized from the
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000836 // AST file as needed.
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000837 ASTReader *ReaderPtr = Reader.get();
Dylan Noblesmith6f42b622012-02-05 02:12:40 +0000838 OwningPtr<ExternalASTSource> Source(Reader.take());
Ted Kremenek8c647de2011-05-04 23:27:12 +0000839
840 // Unregister the cleanup for ASTReader. It will get cleaned up
841 // by the ASTUnit cleanup.
842 ReaderCleanup.unregister();
843
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000844 Context.setExternalSource(Source);
845
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000846 // Create an AST consumer, even though it isn't used.
847 AST->Consumer.reset(new ASTConsumer);
848
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000849 // Create a semantic analysis object and tell the AST reader about it.
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000850 AST->TheSema.reset(new Sema(PP, Context, *AST->Consumer));
851 AST->TheSema->Initialize();
852 ReaderPtr->InitializeSema(*AST->TheSema);
Argyrios Kyrtzidis62ba9f62011-11-01 17:14:15 +0000853 AST->Reader = ReaderPtr;
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000854
Mike Stump1eb44332009-09-09 15:08:12 +0000855 return AST.take();
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000856}
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000857
858namespace {
859
Douglas Gregor9b7db622011-02-16 18:16:54 +0000860/// \brief Preprocessor callback class that updates a hash value with the names
861/// of all macros that have been defined by the translation unit.
862class MacroDefinitionTrackerPPCallbacks : public PPCallbacks {
863 unsigned &Hash;
864
865public:
866 explicit MacroDefinitionTrackerPPCallbacks(unsigned &Hash) : Hash(Hash) { }
867
868 virtual void MacroDefined(const Token &MacroNameTok, const MacroInfo *MI) {
869 Hash = llvm::HashString(MacroNameTok.getIdentifierInfo()->getName(), Hash);
870 }
871};
872
873/// \brief Add the given declaration to the hash of all top-level entities.
874void AddTopLevelDeclarationToHash(Decl *D, unsigned &Hash) {
875 if (!D)
876 return;
877
878 DeclContext *DC = D->getDeclContext();
879 if (!DC)
880 return;
881
882 if (!(DC->isTranslationUnit() || DC->getLookupParent()->isTranslationUnit()))
883 return;
884
885 if (NamedDecl *ND = dyn_cast<NamedDecl>(D)) {
886 if (ND->getIdentifier())
887 Hash = llvm::HashString(ND->getIdentifier()->getName(), Hash);
888 else if (DeclarationName Name = ND->getDeclName()) {
889 std::string NameStr = Name.getAsString();
890 Hash = llvm::HashString(NameStr, Hash);
891 }
892 return;
Douglas Gregorbd9482d2012-01-01 21:23:57 +0000893 }
Douglas Gregor9b7db622011-02-16 18:16:54 +0000894}
895
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000896class TopLevelDeclTrackerConsumer : public ASTConsumer {
897 ASTUnit &Unit;
Douglas Gregor9b7db622011-02-16 18:16:54 +0000898 unsigned &Hash;
899
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000900public:
Douglas Gregor9b7db622011-02-16 18:16:54 +0000901 TopLevelDeclTrackerConsumer(ASTUnit &_Unit, unsigned &Hash)
902 : Unit(_Unit), Hash(Hash) {
903 Hash = 0;
904 }
Douglas Gregor9b7db622011-02-16 18:16:54 +0000905
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000906 void handleTopLevelDecl(Decl *D) {
Argyrios Kyrtzidis35593a92011-11-16 02:35:10 +0000907 if (!D)
908 return;
909
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000910 // FIXME: Currently ObjC method declarations are incorrectly being
911 // reported as top-level declarations, even though their DeclContext
912 // is the containing ObjC @interface/@implementation. This is a
913 // fundamental problem in the parser right now.
914 if (isa<ObjCMethodDecl>(D))
915 return;
916
917 AddTopLevelDeclarationToHash(D, Hash);
918 Unit.addTopLevelDecl(D);
919
920 handleFileLevelDecl(D);
921 }
922
923 void handleFileLevelDecl(Decl *D) {
924 Unit.addFileLevelDecl(D);
925 if (NamespaceDecl *NSD = dyn_cast<NamespaceDecl>(D)) {
926 for (NamespaceDecl::decl_iterator
927 I = NSD->decls_begin(), E = NSD->decls_end(); I != E; ++I)
928 handleFileLevelDecl(*I);
Ted Kremenekda5a4282010-05-03 20:16:35 +0000929 }
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000930 }
Sebastian Redl27372b42010-08-11 18:52:41 +0000931
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000932 bool HandleTopLevelDecl(DeclGroupRef D) {
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000933 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it)
934 handleTopLevelDecl(*it);
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000935 return true;
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000936 }
937
Sebastian Redl27372b42010-08-11 18:52:41 +0000938 // We're not interested in "interesting" decls.
939 void HandleInterestingDecl(DeclGroupRef) {}
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000940
941 void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) {
942 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it)
943 handleTopLevelDecl(*it);
944 }
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000945
946 virtual ASTDeserializationListener *GetASTDeserializationListener() {
947 return Unit.getDeserializationListener();
948 }
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000949};
950
951class TopLevelDeclTrackerAction : public ASTFrontendAction {
952public:
953 ASTUnit &Unit;
954
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000955 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000956 StringRef InFile) {
Douglas Gregor9b7db622011-02-16 18:16:54 +0000957 CI.getPreprocessor().addPPCallbacks(
958 new MacroDefinitionTrackerPPCallbacks(Unit.getCurrentTopLevelHashValue()));
959 return new TopLevelDeclTrackerConsumer(Unit,
960 Unit.getCurrentTopLevelHashValue());
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000961 }
962
963public:
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000964 TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {}
965
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000966 virtual bool hasCodeCompletionSupport() const { return false; }
Douglas Gregor467dc882011-08-25 22:30:56 +0000967 virtual TranslationUnitKind getTranslationUnitKind() {
968 return Unit.getTranslationUnitKind();
Douglas Gregordf95a132010-08-09 20:45:32 +0000969 }
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000970};
971
Argyrios Kyrtzidis92ddef12011-09-19 20:40:48 +0000972class PrecompilePreambleConsumer : public PCHGenerator {
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000973 ASTUnit &Unit;
Douglas Gregor9b7db622011-02-16 18:16:54 +0000974 unsigned &Hash;
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000975 std::vector<Decl *> TopLevelDecls;
Douglas Gregor89d99802010-11-30 06:16:57 +0000976
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000977public:
Douglas Gregor9293ba82011-08-25 22:35:51 +0000978 PrecompilePreambleConsumer(ASTUnit &Unit, const Preprocessor &PP,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000979 StringRef isysroot, raw_ostream *Out)
Douglas Gregora8cc6ce2011-11-30 04:39:39 +0000980 : PCHGenerator(PP, "", 0, isysroot, Out), Unit(Unit),
Douglas Gregor9b7db622011-02-16 18:16:54 +0000981 Hash(Unit.getCurrentTopLevelHashValue()) {
982 Hash = 0;
983 }
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000984
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000985 virtual bool HandleTopLevelDecl(DeclGroupRef D) {
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000986 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
987 Decl *D = *it;
988 // FIXME: Currently ObjC method declarations are incorrectly being
989 // reported as top-level declarations, even though their DeclContext
990 // is the containing ObjC @interface/@implementation. This is a
991 // fundamental problem in the parser right now.
992 if (isa<ObjCMethodDecl>(D))
993 continue;
Douglas Gregor9b7db622011-02-16 18:16:54 +0000994 AddTopLevelDeclarationToHash(D, Hash);
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000995 TopLevelDecls.push_back(D);
996 }
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000997 return true;
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000998 }
999
1000 virtual void HandleTranslationUnit(ASTContext &Ctx) {
1001 PCHGenerator::HandleTranslationUnit(Ctx);
1002 if (!Unit.getDiagnostics().hasErrorOccurred()) {
1003 // Translate the top-level declarations we captured during
1004 // parsing into declaration IDs in the precompiled
1005 // preamble. This will allow us to deserialize those top-level
1006 // declarations when requested.
1007 for (unsigned I = 0, N = TopLevelDecls.size(); I != N; ++I)
1008 Unit.addTopLevelDeclFromPreamble(
1009 getWriter().getDeclID(TopLevelDecls[I]));
Douglas Gregor1d715ac2010-08-03 08:14:03 +00001010 }
1011 }
1012};
1013
1014class PrecompilePreambleAction : public ASTFrontendAction {
1015 ASTUnit &Unit;
1016
1017public:
1018 explicit PrecompilePreambleAction(ASTUnit &Unit) : Unit(Unit) {}
1019
1020 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001021 StringRef InFile) {
Douglas Gregor1d715ac2010-08-03 08:14:03 +00001022 std::string Sysroot;
Argyrios Kyrtzidis8e3df4d2011-02-15 17:54:22 +00001023 std::string OutputFile;
Chris Lattner5f9e2722011-07-23 10:55:15 +00001024 raw_ostream *OS = 0;
Argyrios Kyrtzidis8e3df4d2011-02-15 17:54:22 +00001025 if (GeneratePCHAction::ComputeASTConsumerArguments(CI, InFile, Sysroot,
1026 OutputFile,
Douglas Gregor9293ba82011-08-25 22:35:51 +00001027 OS))
Douglas Gregor1d715ac2010-08-03 08:14:03 +00001028 return 0;
1029
Douglas Gregor832d6202011-07-22 16:35:34 +00001030 if (!CI.getFrontendOpts().RelocatablePCH)
1031 Sysroot.clear();
1032
Douglas Gregor9b7db622011-02-16 18:16:54 +00001033 CI.getPreprocessor().addPPCallbacks(
1034 new MacroDefinitionTrackerPPCallbacks(Unit.getCurrentTopLevelHashValue()));
Douglas Gregor9293ba82011-08-25 22:35:51 +00001035 return new PrecompilePreambleConsumer(Unit, CI.getPreprocessor(), Sysroot,
1036 OS);
Douglas Gregor1d715ac2010-08-03 08:14:03 +00001037 }
1038
1039 virtual bool hasCodeCompletionSupport() const { return false; }
1040 virtual bool hasASTFileSupport() const { return false; }
Douglas Gregor467dc882011-08-25 22:30:56 +00001041 virtual TranslationUnitKind getTranslationUnitKind() { return TU_Prefix; }
Douglas Gregor1d715ac2010-08-03 08:14:03 +00001042};
1043
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001044}
1045
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00001046static void checkAndRemoveNonDriverDiags(SmallVectorImpl<StoredDiagnostic> &
1047 StoredDiagnostics) {
1048 // Get rid of stored diagnostics except the ones from the driver which do not
1049 // have a source location.
1050 for (unsigned I = 0; I < StoredDiagnostics.size(); ++I) {
1051 if (StoredDiagnostics[I].getLocation().isValid()) {
1052 StoredDiagnostics.erase(StoredDiagnostics.begin()+I);
1053 --I;
1054 }
1055 }
1056}
1057
1058static void checkAndSanitizeDiags(SmallVectorImpl<StoredDiagnostic> &
1059 StoredDiagnostics,
1060 SourceManager &SM) {
1061 // The stored diagnostic has the old source manager in it; update
1062 // the locations to refer into the new source manager. Since we've
1063 // been careful to make sure that the source manager's state
1064 // before and after are identical, so that we can reuse the source
1065 // location itself.
1066 for (unsigned I = 0, N = StoredDiagnostics.size(); I < N; ++I) {
1067 if (StoredDiagnostics[I].getLocation().isValid()) {
1068 FullSourceLoc Loc(StoredDiagnostics[I].getLocation(), SM);
1069 StoredDiagnostics[I].setLocation(Loc);
1070 }
1071 }
1072}
1073
Douglas Gregorabc563f2010-07-19 21:46:24 +00001074/// Parse the source file into a translation unit using the given compiler
1075/// invocation, replacing the current translation unit.
1076///
1077/// \returns True if a failure occurred that causes the ASTUnit not to
1078/// contain any translation-unit information, false otherwise.
Douglas Gregor754f3492010-07-24 00:38:13 +00001079bool ASTUnit::Parse(llvm::MemoryBuffer *OverrideMainBuffer) {
Douglas Gregor28233422010-07-27 14:52:07 +00001080 delete SavedMainFileBuffer;
1081 SavedMainFileBuffer = 0;
1082
Ted Kremenek4f327862011-03-21 18:40:17 +00001083 if (!Invocation) {
Douglas Gregor671947b2010-08-19 01:33:06 +00001084 delete OverrideMainBuffer;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001085 return true;
Douglas Gregor671947b2010-08-19 01:33:06 +00001086 }
Douglas Gregorabc563f2010-07-19 21:46:24 +00001087
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001088 // Create the compiler instance to use for building the AST.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001089 OwningPtr<CompilerInstance> Clang(new CompilerInstance());
Ted Kremenek03201fb2011-03-21 18:40:07 +00001090
1091 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00001092 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1093 CICleanup(Clang.get());
Ted Kremenek03201fb2011-03-21 18:40:07 +00001094
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001095 IntrusiveRefCntPtr<CompilerInvocation>
Argyrios Kyrtzidis26d43cd2011-09-12 18:09:38 +00001096 CCInvocation(new CompilerInvocation(*Invocation));
1097
1098 Clang->setInvocation(CCInvocation.getPtr());
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001099 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].File;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001100
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001101 // Set up diagnostics, capturing any diagnostics that would
1102 // otherwise be dropped.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001103 Clang->setDiagnostics(&getDiagnostics());
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001104
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001105 // Create the target instance.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001106 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
Ted Kremenek4f327862011-03-21 18:40:17 +00001107 Clang->getTargetOpts()));
Ted Kremenek03201fb2011-03-21 18:40:07 +00001108 if (!Clang->hasTarget()) {
Douglas Gregor671947b2010-08-19 01:33:06 +00001109 delete OverrideMainBuffer;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001110 return true;
Douglas Gregor671947b2010-08-19 01:33:06 +00001111 }
1112
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001113 // Inform the target of the language options.
1114 //
1115 // FIXME: We shouldn't need to do this, the target should be immutable once
1116 // created. This complexity should be lifted elsewhere.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001117 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregorabc563f2010-07-19 21:46:24 +00001118
Ted Kremenek03201fb2011-03-21 18:40:07 +00001119 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001120 "Invocation must have exactly one source file!");
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001121 assert(Clang->getFrontendOpts().Inputs[0].Kind != IK_AST &&
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001122 "FIXME: AST inputs not yet supported here!");
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001123 assert(Clang->getFrontendOpts().Inputs[0].Kind != IK_LLVM_IR &&
Daniel Dunbarfaddc3e2010-06-07 23:26:47 +00001124 "IR inputs not support here!");
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001125
Douglas Gregorabc563f2010-07-19 21:46:24 +00001126 // Configure the various subsystems.
1127 // FIXME: Should we retain the previous file manager?
Ted Kremenekd3b74d92011-11-17 23:01:24 +00001128 LangOpts = &Clang->getLangOpts();
Ted Kremenek03201fb2011-03-21 18:40:07 +00001129 FileSystemOpts = Clang->getFileSystemOpts();
Ted Kremenek4f327862011-03-21 18:40:17 +00001130 FileMgr = new FileManager(FileSystemOpts);
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001131 SourceMgr = new SourceManager(getDiagnostics(), *FileMgr,
1132 UserFilesAreVolatile);
Douglas Gregor914ed9d2010-08-13 03:15:25 +00001133 TheSema.reset();
Ted Kremenek4f327862011-03-21 18:40:17 +00001134 Ctx = 0;
1135 PP = 0;
Argyrios Kyrtzidis62ba9f62011-11-01 17:14:15 +00001136 Reader = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001137
1138 // Clear out old caches and data.
1139 TopLevelDecls.clear();
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +00001140 clearFileLevelDecls();
Douglas Gregorabc563f2010-07-19 21:46:24 +00001141 CleanTemporaryFiles();
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001142
Douglas Gregorf128fed2010-08-20 00:02:33 +00001143 if (!OverrideMainBuffer) {
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00001144 checkAndRemoveNonDriverDiags(StoredDiagnostics);
Douglas Gregorf128fed2010-08-20 00:02:33 +00001145 TopLevelDeclsInPreamble.clear();
1146 }
1147
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001148 // Create a file manager object to provide access to and cache the filesystem.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001149 Clang->setFileManager(&getFileManager());
Douglas Gregorabc563f2010-07-19 21:46:24 +00001150
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001151 // Create the source manager.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001152 Clang->setSourceManager(&getSourceManager());
Douglas Gregorabc563f2010-07-19 21:46:24 +00001153
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001154 // If the main file has been overridden due to the use of a preamble,
1155 // make that override happen and introduce the preamble.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001156 PreprocessorOptions &PreprocessorOpts = Clang->getPreprocessorOpts();
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001157 if (OverrideMainBuffer) {
1158 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
1159 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
1160 PreprocessorOpts.PrecompiledPreambleBytes.second
1161 = PreambleEndsAtStartOfLine;
Ted Kremenek1872b312011-10-27 17:55:18 +00001162 PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001163 PreprocessorOpts.DisablePCHValidation = true;
Douglas Gregor28233422010-07-27 14:52:07 +00001164
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001165 // The stored diagnostic has the old source manager in it; update
1166 // the locations to refer into the new source manager. Since we've
1167 // been careful to make sure that the source manager's state
1168 // before and after are identical, so that we can reuse the source
1169 // location itself.
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00001170 checkAndSanitizeDiags(StoredDiagnostics, getSourceManager());
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001171
1172 // Keep track of the override buffer;
1173 SavedMainFileBuffer = OverrideMainBuffer;
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001174 }
1175
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001176 OwningPtr<TopLevelDeclTrackerAction> Act(
Ted Kremenek25a11e12011-03-22 01:15:24 +00001177 new TopLevelDeclTrackerAction(*this));
1178
1179 // Recover resources if we crash before exiting this method.
1180 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1181 ActCleanup(Act.get());
1182
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001183 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0]))
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001184 goto error;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001185
1186 if (OverrideMainBuffer) {
Ted Kremenek1872b312011-10-27 17:55:18 +00001187 std::string ModName = getPreambleFile(this);
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001188 TranslateStoredDiagnostics(Clang->getModuleManager(), ModName,
1189 getSourceManager(), PreambleDiagnostics,
1190 StoredDiagnostics);
1191 }
1192
Argyrios Kyrtzidis374a00b2012-06-08 05:48:06 +00001193 if (!Act->Execute())
1194 goto error;
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001195
1196 transferASTDataFromCompilerInstance(*Clang);
Douglas Gregorabc563f2010-07-19 21:46:24 +00001197
Daniel Dunbarf772d1e2009-12-04 08:17:33 +00001198 Act->EndSourceFile();
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001199
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001200 FailedParseDiagnostics.clear();
1201
Douglas Gregorabc563f2010-07-19 21:46:24 +00001202 return false;
Ted Kremenek4f327862011-03-21 18:40:17 +00001203
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001204error:
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001205 // Remove the overridden buffer we used for the preamble.
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001206 if (OverrideMainBuffer) {
Douglas Gregor671947b2010-08-19 01:33:06 +00001207 delete OverrideMainBuffer;
Douglas Gregor37cf6632010-10-06 21:11:08 +00001208 SavedMainFileBuffer = 0;
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001209 }
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001210
1211 // Keep the ownership of the data in the ASTUnit because the client may
1212 // want to see the diagnostics.
1213 transferASTDataFromCompilerInstance(*Clang);
1214 FailedParseDiagnostics.swap(StoredDiagnostics);
Douglas Gregord54eb442010-10-12 16:25:54 +00001215 StoredDiagnostics.clear();
Argyrios Kyrtzidis3e9d3262011-10-24 17:25:20 +00001216 NumStoredDiagnosticsFromDriver = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001217 return true;
1218}
1219
Douglas Gregor44c181a2010-07-23 00:33:23 +00001220/// \brief Simple function to retrieve a path for a preamble precompiled header.
1221static std::string GetPreamblePCHPath() {
1222 // FIXME: This is lame; sys::Path should provide this function (in particular,
1223 // it should know how to find the temporary files dir).
1224 // FIXME: This is really lame. I copied this code from the Driver!
Douglas Gregor424668c2010-09-11 18:05:19 +00001225 // FIXME: This is a hack so that we can override the preamble file during
1226 // crash-recovery testing, which is the only case where the preamble files
1227 // are not necessarily cleaned up.
1228 const char *TmpFile = ::getenv("CINDEXTEST_PREAMBLE_FILE");
1229 if (TmpFile)
1230 return TmpFile;
1231
Douglas Gregor44c181a2010-07-23 00:33:23 +00001232 std::string Error;
1233 const char *TmpDir = ::getenv("TMPDIR");
1234 if (!TmpDir)
1235 TmpDir = ::getenv("TEMP");
1236 if (!TmpDir)
1237 TmpDir = ::getenv("TMP");
Douglas Gregorc6cb2b02010-09-11 17:51:16 +00001238#ifdef LLVM_ON_WIN32
1239 if (!TmpDir)
1240 TmpDir = ::getenv("USERPROFILE");
1241#endif
Douglas Gregor44c181a2010-07-23 00:33:23 +00001242 if (!TmpDir)
1243 TmpDir = "/tmp";
1244 llvm::sys::Path P(TmpDir);
Douglas Gregorc6cb2b02010-09-11 17:51:16 +00001245 P.createDirectoryOnDisk(true);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001246 P.appendComponent("preamble");
Douglas Gregor6bf18302010-08-11 13:06:56 +00001247 P.appendSuffix("pch");
Argyrios Kyrtzidisbc9d5a32011-07-21 18:44:46 +00001248 if (P.makeUnique(/*reuse_current=*/false, /*ErrMsg*/0))
Douglas Gregor44c181a2010-07-23 00:33:23 +00001249 return std::string();
1250
Douglas Gregor44c181a2010-07-23 00:33:23 +00001251 return P.str();
1252}
1253
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001254/// \brief Compute the preamble for the main file, providing the source buffer
1255/// that corresponds to the main file along with a pair (bytes, start-of-line)
1256/// that describes the preamble.
1257std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> >
Douglas Gregordf95a132010-08-09 20:45:32 +00001258ASTUnit::ComputePreamble(CompilerInvocation &Invocation,
1259 unsigned MaxLines, bool &CreatedBuffer) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001260 FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
Chris Lattner39b49bc2010-11-23 08:35:12 +00001261 PreprocessorOptions &PreprocessorOpts = Invocation.getPreprocessorOpts();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001262 CreatedBuffer = false;
1263
Douglas Gregor44c181a2010-07-23 00:33:23 +00001264 // Try to determine if the main file has been remapped, either from the
1265 // command line (to another file) or directly through the compiler invocation
1266 // (to a memory buffer).
Douglas Gregor175c4a92010-07-23 23:58:40 +00001267 llvm::MemoryBuffer *Buffer = 0;
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001268 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].File);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001269 if (const llvm::sys::FileStatus *MainFileStatus = MainFilePath.getFileStatus()) {
1270 // Check whether there is a file-file remapping of the main file
1271 for (PreprocessorOptions::remapped_file_iterator
Douglas Gregor175c4a92010-07-23 23:58:40 +00001272 M = PreprocessorOpts.remapped_file_begin(),
1273 E = PreprocessorOpts.remapped_file_end();
Douglas Gregor44c181a2010-07-23 00:33:23 +00001274 M != E;
1275 ++M) {
1276 llvm::sys::PathWithStatus MPath(M->first);
1277 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
1278 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
1279 // We found a remapping. Try to load the resulting, remapped source.
Douglas Gregor175c4a92010-07-23 23:58:40 +00001280 if (CreatedBuffer) {
Douglas Gregor44c181a2010-07-23 00:33:23 +00001281 delete Buffer;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001282 CreatedBuffer = false;
1283 }
1284
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00001285 Buffer = getBufferForFile(M->second);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001286 if (!Buffer)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001287 return std::make_pair((llvm::MemoryBuffer*)0,
1288 std::make_pair(0, true));
Douglas Gregor175c4a92010-07-23 23:58:40 +00001289 CreatedBuffer = true;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001290 }
1291 }
1292 }
1293
1294 // Check whether there is a file-buffer remapping. It supercedes the
1295 // file-file remapping.
1296 for (PreprocessorOptions::remapped_file_buffer_iterator
1297 M = PreprocessorOpts.remapped_file_buffer_begin(),
1298 E = PreprocessorOpts.remapped_file_buffer_end();
1299 M != E;
1300 ++M) {
1301 llvm::sys::PathWithStatus MPath(M->first);
1302 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
1303 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
1304 // We found a remapping.
Douglas Gregor175c4a92010-07-23 23:58:40 +00001305 if (CreatedBuffer) {
Douglas Gregor44c181a2010-07-23 00:33:23 +00001306 delete Buffer;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001307 CreatedBuffer = false;
1308 }
Douglas Gregor44c181a2010-07-23 00:33:23 +00001309
Douglas Gregor175c4a92010-07-23 23:58:40 +00001310 Buffer = const_cast<llvm::MemoryBuffer *>(M->second);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001311 }
1312 }
Douglas Gregor175c4a92010-07-23 23:58:40 +00001313 }
Douglas Gregor44c181a2010-07-23 00:33:23 +00001314 }
1315
1316 // If the main source file was not remapped, load it now.
1317 if (!Buffer) {
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001318 Buffer = getBufferForFile(FrontendOpts.Inputs[0].File);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001319 if (!Buffer)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001320 return std::make_pair((llvm::MemoryBuffer*)0, std::make_pair(0, true));
Douglas Gregor175c4a92010-07-23 23:58:40 +00001321
1322 CreatedBuffer = true;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001323 }
1324
Argyrios Kyrtzidis03c107a2011-08-25 20:39:19 +00001325 return std::make_pair(Buffer, Lexer::ComputePreamble(Buffer,
Ted Kremenekd3b74d92011-11-17 23:01:24 +00001326 *Invocation.getLangOpts(),
Argyrios Kyrtzidis03c107a2011-08-25 20:39:19 +00001327 MaxLines));
Douglas Gregor175c4a92010-07-23 23:58:40 +00001328}
1329
Douglas Gregor754f3492010-07-24 00:38:13 +00001330static llvm::MemoryBuffer *CreatePaddedMainFileBuffer(llvm::MemoryBuffer *Old,
Douglas Gregor754f3492010-07-24 00:38:13 +00001331 unsigned NewSize,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001332 StringRef NewName) {
Douglas Gregor754f3492010-07-24 00:38:13 +00001333 llvm::MemoryBuffer *Result
1334 = llvm::MemoryBuffer::getNewUninitMemBuffer(NewSize, NewName);
1335 memcpy(const_cast<char*>(Result->getBufferStart()),
1336 Old->getBufferStart(), Old->getBufferSize());
1337 memset(const_cast<char*>(Result->getBufferStart()) + Old->getBufferSize(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001338 ' ', NewSize - Old->getBufferSize() - 1);
1339 const_cast<char*>(Result->getBufferEnd())[-1] = '\n';
Douglas Gregor754f3492010-07-24 00:38:13 +00001340
Douglas Gregor754f3492010-07-24 00:38:13 +00001341 return Result;
1342}
1343
Douglas Gregor175c4a92010-07-23 23:58:40 +00001344/// \brief Attempt to build or re-use a precompiled preamble when (re-)parsing
1345/// the source file.
1346///
1347/// This routine will compute the preamble of the main source file. If a
1348/// non-trivial preamble is found, it will precompile that preamble into a
1349/// precompiled header so that the precompiled preamble can be used to reduce
1350/// reparsing time. If a precompiled preamble has already been constructed,
1351/// this routine will determine if it is still valid and, if so, avoid
1352/// rebuilding the precompiled preamble.
1353///
Douglas Gregordf95a132010-08-09 20:45:32 +00001354/// \param AllowRebuild When true (the default), this routine is
1355/// allowed to rebuild the precompiled preamble if it is found to be
1356/// out-of-date.
1357///
1358/// \param MaxLines When non-zero, the maximum number of lines that
1359/// can occur within the preamble.
1360///
Douglas Gregor754f3492010-07-24 00:38:13 +00001361/// \returns If the precompiled preamble can be used, returns a newly-allocated
1362/// buffer that should be used in place of the main file when doing so.
1363/// Otherwise, returns a NULL pointer.
Douglas Gregordf95a132010-08-09 20:45:32 +00001364llvm::MemoryBuffer *ASTUnit::getMainBufferWithPrecompiledPreamble(
Douglas Gregor01b6e312011-07-01 18:22:13 +00001365 const CompilerInvocation &PreambleInvocationIn,
Douglas Gregordf95a132010-08-09 20:45:32 +00001366 bool AllowRebuild,
1367 unsigned MaxLines) {
Douglas Gregor01b6e312011-07-01 18:22:13 +00001368
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001369 IntrusiveRefCntPtr<CompilerInvocation>
Douglas Gregor01b6e312011-07-01 18:22:13 +00001370 PreambleInvocation(new CompilerInvocation(PreambleInvocationIn));
1371 FrontendOptions &FrontendOpts = PreambleInvocation->getFrontendOpts();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001372 PreprocessorOptions &PreprocessorOpts
Douglas Gregor01b6e312011-07-01 18:22:13 +00001373 = PreambleInvocation->getPreprocessorOpts();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001374
1375 bool CreatedPreambleBuffer = false;
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001376 std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> > NewPreamble
Douglas Gregor01b6e312011-07-01 18:22:13 +00001377 = ComputePreamble(*PreambleInvocation, MaxLines, CreatedPreambleBuffer);
Douglas Gregor175c4a92010-07-23 23:58:40 +00001378
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001379 // If ComputePreamble() Take ownership of the preamble buffer.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001380 OwningPtr<llvm::MemoryBuffer> OwnedPreambleBuffer;
Douglas Gregor73fc9122010-11-16 20:45:51 +00001381 if (CreatedPreambleBuffer)
1382 OwnedPreambleBuffer.reset(NewPreamble.first);
1383
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001384 if (!NewPreamble.second.first) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001385 // We couldn't find a preamble in the main source. Clear out the current
1386 // preamble, if we have one. It's obviously no good any more.
1387 Preamble.clear();
Ted Kremenek1872b312011-10-27 17:55:18 +00001388 erasePreambleFile(this);
Douglas Gregoreababfb2010-08-04 05:53:38 +00001389
1390 // The next time we actually see a preamble, precompile it.
1391 PreambleRebuildCounter = 1;
Douglas Gregor754f3492010-07-24 00:38:13 +00001392 return 0;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001393 }
1394
1395 if (!Preamble.empty()) {
1396 // We've previously computed a preamble. Check whether we have the same
1397 // preamble now that we did before, and that there's enough space in
1398 // the main-file buffer within the precompiled preamble to fit the
1399 // new main file.
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001400 if (Preamble.size() == NewPreamble.second.first &&
1401 PreambleEndsAtStartOfLine == NewPreamble.second.second &&
Douglas Gregor592508e2010-07-24 00:42:07 +00001402 NewPreamble.first->getBufferSize() < PreambleReservedSize-2 &&
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00001403 memcmp(Preamble.getBufferStart(), NewPreamble.first->getBufferStart(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001404 NewPreamble.second.first) == 0) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001405 // The preamble has not changed. We may be able to re-use the precompiled
1406 // preamble.
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001407
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001408 // Check that none of the files used by the preamble have changed.
1409 bool AnyFileChanged = false;
1410
1411 // First, make a record of those files that have been overridden via
1412 // remapping or unsaved_files.
1413 llvm::StringMap<std::pair<off_t, time_t> > OverriddenFiles;
1414 for (PreprocessorOptions::remapped_file_iterator
1415 R = PreprocessorOpts.remapped_file_begin(),
1416 REnd = PreprocessorOpts.remapped_file_end();
1417 !AnyFileChanged && R != REnd;
1418 ++R) {
1419 struct stat StatBuf;
Anders Carlsson340415c2011-03-18 19:23:38 +00001420 if (FileMgr->getNoncachedStatValue(R->second, StatBuf)) {
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001421 // If we can't stat the file we're remapping to, assume that something
1422 // horrible happened.
1423 AnyFileChanged = true;
1424 break;
1425 }
Douglas Gregor754f3492010-07-24 00:38:13 +00001426
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001427 OverriddenFiles[R->first] = std::make_pair(StatBuf.st_size,
1428 StatBuf.st_mtime);
1429 }
1430 for (PreprocessorOptions::remapped_file_buffer_iterator
1431 R = PreprocessorOpts.remapped_file_buffer_begin(),
1432 REnd = PreprocessorOpts.remapped_file_buffer_end();
1433 !AnyFileChanged && R != REnd;
1434 ++R) {
1435 // FIXME: Should we actually compare the contents of file->buffer
1436 // remappings?
1437 OverriddenFiles[R->first] = std::make_pair(R->second->getBufferSize(),
1438 0);
1439 }
1440
1441 // Check whether anything has changed.
1442 for (llvm::StringMap<std::pair<off_t, time_t> >::iterator
1443 F = FilesInPreamble.begin(), FEnd = FilesInPreamble.end();
1444 !AnyFileChanged && F != FEnd;
1445 ++F) {
1446 llvm::StringMap<std::pair<off_t, time_t> >::iterator Overridden
1447 = OverriddenFiles.find(F->first());
1448 if (Overridden != OverriddenFiles.end()) {
1449 // This file was remapped; check whether the newly-mapped file
1450 // matches up with the previous mapping.
1451 if (Overridden->second != F->second)
1452 AnyFileChanged = true;
1453 continue;
1454 }
1455
1456 // The file was not remapped; check whether it has changed on disk.
1457 struct stat StatBuf;
Anders Carlsson340415c2011-03-18 19:23:38 +00001458 if (FileMgr->getNoncachedStatValue(F->first(), StatBuf)) {
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001459 // If we can't stat the file, assume that something horrible happened.
1460 AnyFileChanged = true;
1461 } else if (StatBuf.st_size != F->second.first ||
1462 StatBuf.st_mtime != F->second.second)
1463 AnyFileChanged = true;
1464 }
1465
1466 if (!AnyFileChanged) {
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001467 // Okay! We can re-use the precompiled preamble.
1468
1469 // Set the state of the diagnostic object to mimic its state
1470 // after parsing the preamble.
1471 getDiagnostics().Reset();
Douglas Gregor32be4a52010-10-11 21:37:58 +00001472 ProcessWarningOptions(getDiagnostics(),
Douglas Gregor01b6e312011-07-01 18:22:13 +00001473 PreambleInvocation->getDiagnosticOpts());
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001474 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001475
1476 // Create a version of the main file buffer that is padded to
1477 // buffer size we reserved when creating the preamble.
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001478 return CreatePaddedMainFileBuffer(NewPreamble.first,
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001479 PreambleReservedSize,
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001480 FrontendOpts.Inputs[0].File);
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001481 }
Douglas Gregor175c4a92010-07-23 23:58:40 +00001482 }
Douglas Gregordf95a132010-08-09 20:45:32 +00001483
1484 // If we aren't allowed to rebuild the precompiled preamble, just
1485 // return now.
1486 if (!AllowRebuild)
1487 return 0;
Douglas Gregoraa3e6ba2010-10-08 04:03:57 +00001488
Douglas Gregor175c4a92010-07-23 23:58:40 +00001489 // We can't reuse the previously-computed preamble. Build a new one.
1490 Preamble.clear();
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001491 PreambleDiagnostics.clear();
Ted Kremenek1872b312011-10-27 17:55:18 +00001492 erasePreambleFile(this);
Douglas Gregoreababfb2010-08-04 05:53:38 +00001493 PreambleRebuildCounter = 1;
Douglas Gregordf95a132010-08-09 20:45:32 +00001494 } else if (!AllowRebuild) {
1495 // We aren't allowed to rebuild the precompiled preamble; just
1496 // return now.
1497 return 0;
1498 }
Douglas Gregoreababfb2010-08-04 05:53:38 +00001499
1500 // If the preamble rebuild counter > 1, it's because we previously
1501 // failed to build a preamble and we're not yet ready to try
1502 // again. Decrement the counter and return a failure.
1503 if (PreambleRebuildCounter > 1) {
1504 --PreambleRebuildCounter;
1505 return 0;
1506 }
1507
Douglas Gregor2cd4fd42010-09-11 17:56:52 +00001508 // Create a temporary file for the precompiled preamble. In rare
1509 // circumstances, this can fail.
1510 std::string PreamblePCHPath = GetPreamblePCHPath();
1511 if (PreamblePCHPath.empty()) {
1512 // Try again next time.
1513 PreambleRebuildCounter = 1;
1514 return 0;
1515 }
1516
Douglas Gregor175c4a92010-07-23 23:58:40 +00001517 // We did not previously compute a preamble, or it can't be reused anyway.
Douglas Gregor213f18b2010-10-28 15:44:59 +00001518 SimpleTimer PreambleTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00001519 PreambleTimer.setOutput("Precompiling preamble");
Douglas Gregor44c181a2010-07-23 00:33:23 +00001520
1521 // Create a new buffer that stores the preamble. The buffer also contains
1522 // extra space for the original contents of the file (which will be present
1523 // when we actually parse the file) along with more room in case the file
Douglas Gregor175c4a92010-07-23 23:58:40 +00001524 // grows.
1525 PreambleReservedSize = NewPreamble.first->getBufferSize();
1526 if (PreambleReservedSize < 4096)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001527 PreambleReservedSize = 8191;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001528 else
Douglas Gregor175c4a92010-07-23 23:58:40 +00001529 PreambleReservedSize *= 2;
1530
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001531 // Save the preamble text for later; we'll need to compare against it for
1532 // subsequent reparses.
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001533 StringRef MainFilename = PreambleInvocation->getFrontendOpts().Inputs[0].File;
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00001534 Preamble.assign(FileMgr->getFile(MainFilename),
1535 NewPreamble.first->getBufferStart(),
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001536 NewPreamble.first->getBufferStart()
1537 + NewPreamble.second.first);
1538 PreambleEndsAtStartOfLine = NewPreamble.second.second;
1539
Douglas Gregor671947b2010-08-19 01:33:06 +00001540 delete PreambleBuffer;
1541 PreambleBuffer
Douglas Gregor175c4a92010-07-23 23:58:40 +00001542 = llvm::MemoryBuffer::getNewUninitMemBuffer(PreambleReservedSize,
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001543 FrontendOpts.Inputs[0].File);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001544 memcpy(const_cast<char*>(PreambleBuffer->getBufferStart()),
Douglas Gregor175c4a92010-07-23 23:58:40 +00001545 NewPreamble.first->getBufferStart(), Preamble.size());
1546 memset(const_cast<char*>(PreambleBuffer->getBufferStart()) + Preamble.size(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001547 ' ', PreambleReservedSize - Preamble.size() - 1);
1548 const_cast<char*>(PreambleBuffer->getBufferEnd())[-1] = '\n';
Douglas Gregor44c181a2010-07-23 00:33:23 +00001549
1550 // Remap the main source file to the preamble buffer.
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001551 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].File);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001552 PreprocessorOpts.addRemappedFile(MainFilePath.str(), PreambleBuffer);
1553
1554 // Tell the compiler invocation to generate a temporary precompiled header.
1555 FrontendOpts.ProgramAction = frontend::GeneratePCH;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001556 // FIXME: Generate the precompiled header into memory?
Douglas Gregor2cd4fd42010-09-11 17:56:52 +00001557 FrontendOpts.OutputFile = PreamblePCHPath;
Douglas Gregoraa3e6ba2010-10-08 04:03:57 +00001558 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
1559 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001560
1561 // Create the compiler instance to use for building the precompiled preamble.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001562 OwningPtr<CompilerInstance> Clang(new CompilerInstance());
Ted Kremenek03201fb2011-03-21 18:40:07 +00001563
1564 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00001565 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1566 CICleanup(Clang.get());
Ted Kremenek03201fb2011-03-21 18:40:07 +00001567
Douglas Gregor01b6e312011-07-01 18:22:13 +00001568 Clang->setInvocation(&*PreambleInvocation);
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001569 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].File;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001570
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001571 // Set up diagnostics, capturing all of the diagnostics produced.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001572 Clang->setDiagnostics(&getDiagnostics());
Douglas Gregor44c181a2010-07-23 00:33:23 +00001573
1574 // Create the target instance.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001575 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
Douglas Gregor57016dd2012-10-16 23:40:58 +00001576 Clang->getTargetOpts()));
Ted Kremenek03201fb2011-03-21 18:40:07 +00001577 if (!Clang->hasTarget()) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001578 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1579 Preamble.clear();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001580 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor671947b2010-08-19 01:33:06 +00001581 PreprocessorOpts.eraseRemappedFile(
1582 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor754f3492010-07-24 00:38:13 +00001583 return 0;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001584 }
1585
1586 // Inform the target of the language options.
1587 //
1588 // FIXME: We shouldn't need to do this, the target should be immutable once
1589 // created. This complexity should be lifted elsewhere.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001590 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregor44c181a2010-07-23 00:33:23 +00001591
Ted Kremenek03201fb2011-03-21 18:40:07 +00001592 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Douglas Gregor44c181a2010-07-23 00:33:23 +00001593 "Invocation must have exactly one source file!");
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001594 assert(Clang->getFrontendOpts().Inputs[0].Kind != IK_AST &&
Douglas Gregor44c181a2010-07-23 00:33:23 +00001595 "FIXME: AST inputs not yet supported here!");
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001596 assert(Clang->getFrontendOpts().Inputs[0].Kind != IK_LLVM_IR &&
Douglas Gregor44c181a2010-07-23 00:33:23 +00001597 "IR inputs not support here!");
1598
1599 // Clear out old caches and data.
Douglas Gregoraa3e6ba2010-10-08 04:03:57 +00001600 getDiagnostics().Reset();
Ted Kremenek03201fb2011-03-21 18:40:07 +00001601 ProcessWarningOptions(getDiagnostics(), Clang->getDiagnosticOpts());
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00001602 checkAndRemoveNonDriverDiags(StoredDiagnostics);
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001603 TopLevelDecls.clear();
1604 TopLevelDeclsInPreamble.clear();
Douglas Gregor44c181a2010-07-23 00:33:23 +00001605
1606 // Create a file manager object to provide access to and cache the filesystem.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001607 Clang->setFileManager(new FileManager(Clang->getFileSystemOpts()));
Douglas Gregor44c181a2010-07-23 00:33:23 +00001608
1609 // Create the source manager.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001610 Clang->setSourceManager(new SourceManager(getDiagnostics(),
Ted Kremenek4f327862011-03-21 18:40:17 +00001611 Clang->getFileManager()));
Douglas Gregor44c181a2010-07-23 00:33:23 +00001612
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001613 OwningPtr<PrecompilePreambleAction> Act;
Douglas Gregor1d715ac2010-08-03 08:14:03 +00001614 Act.reset(new PrecompilePreambleAction(*this));
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001615 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001616 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1617 Preamble.clear();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001618 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor671947b2010-08-19 01:33:06 +00001619 PreprocessorOpts.eraseRemappedFile(
1620 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor754f3492010-07-24 00:38:13 +00001621 return 0;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001622 }
1623
1624 Act->Execute();
1625 Act->EndSourceFile();
Ted Kremenek4f327862011-03-21 18:40:17 +00001626
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001627 if (Diagnostics->hasErrorOccurred()) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001628 // There were errors parsing the preamble, so no precompiled header was
1629 // generated. Forget that we even tried.
Douglas Gregor06e50442010-09-27 16:43:25 +00001630 // FIXME: Should we leave a note for ourselves to try again?
Douglas Gregor175c4a92010-07-23 23:58:40 +00001631 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1632 Preamble.clear();
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001633 TopLevelDeclsInPreamble.clear();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001634 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor671947b2010-08-19 01:33:06 +00001635 PreprocessorOpts.eraseRemappedFile(
1636 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor754f3492010-07-24 00:38:13 +00001637 return 0;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001638 }
1639
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001640 // Transfer any diagnostics generated when parsing the preamble into the set
1641 // of preamble diagnostics.
1642 PreambleDiagnostics.clear();
1643 PreambleDiagnostics.insert(PreambleDiagnostics.end(),
Argyrios Kyrtzidis3e9d3262011-10-24 17:25:20 +00001644 stored_diag_afterDriver_begin(), stored_diag_end());
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00001645 checkAndRemoveNonDriverDiags(StoredDiagnostics);
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001646
Douglas Gregor175c4a92010-07-23 23:58:40 +00001647 // Keep track of the preamble we precompiled.
Ted Kremenek1872b312011-10-27 17:55:18 +00001648 setPreambleFile(this, FrontendOpts.OutputFile);
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001649 NumWarningsInPreamble = getDiagnostics().getNumWarnings();
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001650
1651 // Keep track of all of the files that the source manager knows about,
1652 // so we can verify whether they have changed or not.
1653 FilesInPreamble.clear();
Ted Kremenek03201fb2011-03-21 18:40:07 +00001654 SourceManager &SourceMgr = Clang->getSourceManager();
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001655 const llvm::MemoryBuffer *MainFileBuffer
1656 = SourceMgr.getBuffer(SourceMgr.getMainFileID());
1657 for (SourceManager::fileinfo_iterator F = SourceMgr.fileinfo_begin(),
1658 FEnd = SourceMgr.fileinfo_end();
1659 F != FEnd;
1660 ++F) {
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001661 const FileEntry *File = F->second->OrigEntry;
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001662 if (!File || F->second->getRawBuffer() == MainFileBuffer)
1663 continue;
1664
1665 FilesInPreamble[File->getName()]
1666 = std::make_pair(F->second->getSize(), File->getModificationTime());
1667 }
1668
Douglas Gregoreababfb2010-08-04 05:53:38 +00001669 PreambleRebuildCounter = 1;
Douglas Gregor671947b2010-08-19 01:33:06 +00001670 PreprocessorOpts.eraseRemappedFile(
1671 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor9b7db622011-02-16 18:16:54 +00001672
1673 // If the hash of top-level entities differs from the hash of the top-level
1674 // entities the last time we rebuilt the preamble, clear out the completion
1675 // cache.
1676 if (CurrentTopLevelHashValue != PreambleTopLevelHashValue) {
1677 CompletionCacheTopLevelHashValue = 0;
1678 PreambleTopLevelHashValue = CurrentTopLevelHashValue;
1679 }
1680
Douglas Gregor754f3492010-07-24 00:38:13 +00001681 return CreatePaddedMainFileBuffer(NewPreamble.first,
Douglas Gregor754f3492010-07-24 00:38:13 +00001682 PreambleReservedSize,
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001683 FrontendOpts.Inputs[0].File);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001684}
Douglas Gregorabc563f2010-07-19 21:46:24 +00001685
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001686void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
1687 std::vector<Decl *> Resolved;
1688 Resolved.reserve(TopLevelDeclsInPreamble.size());
1689 ExternalASTSource &Source = *getASTContext().getExternalSource();
1690 for (unsigned I = 0, N = TopLevelDeclsInPreamble.size(); I != N; ++I) {
1691 // Resolve the declaration ID to an actual declaration, possibly
1692 // deserializing the declaration in the process.
1693 Decl *D = Source.GetExternalDecl(TopLevelDeclsInPreamble[I]);
1694 if (D)
1695 Resolved.push_back(D);
1696 }
1697 TopLevelDeclsInPreamble.clear();
1698 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1699}
1700
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001701void ASTUnit::transferASTDataFromCompilerInstance(CompilerInstance &CI) {
1702 // Steal the created target, context, and preprocessor.
1703 TheSema.reset(CI.takeSema());
1704 Consumer.reset(CI.takeASTConsumer());
1705 Ctx = &CI.getASTContext();
1706 PP = &CI.getPreprocessor();
1707 CI.setSourceManager(0);
1708 CI.setFileManager(0);
1709 Target = &CI.getTarget();
1710 Reader = CI.getModuleManager();
1711}
1712
Chris Lattner5f9e2722011-07-23 10:55:15 +00001713StringRef ASTUnit::getMainFileName() const {
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001714 return Invocation->getFrontendOpts().Inputs[0].File;
Douglas Gregor213f18b2010-10-28 15:44:59 +00001715}
1716
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001717ASTUnit *ASTUnit::create(CompilerInvocation *CI,
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001718 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001719 bool CaptureDiagnostics,
1720 bool UserFilesAreVolatile) {
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001721 OwningPtr<ASTUnit> AST;
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001722 AST.reset(new ASTUnit(false));
Argyrios Kyrtzidis991bf492011-11-28 04:55:55 +00001723 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001724 AST->Diagnostics = Diags;
Ted Kremenek4f327862011-03-21 18:40:17 +00001725 AST->Invocation = CI;
Anders Carlsson0d8d7e62011-03-18 18:22:40 +00001726 AST->FileSystemOpts = CI->getFileSystemOpts();
Ted Kremenek4f327862011-03-21 18:40:17 +00001727 AST->FileMgr = new FileManager(AST->FileSystemOpts);
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001728 AST->UserFilesAreVolatile = UserFilesAreVolatile;
1729 AST->SourceMgr = new SourceManager(AST->getDiagnostics(), *AST->FileMgr,
1730 UserFilesAreVolatile);
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001731
1732 return AST.take();
1733}
1734
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001735ASTUnit *ASTUnit::LoadFromCompilerInvocationAction(CompilerInvocation *CI,
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001736 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001737 ASTFrontendAction *Action,
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00001738 ASTUnit *Unit,
1739 bool Persistent,
1740 StringRef ResourceFilesPath,
1741 bool OnlyLocalDecls,
1742 bool CaptureDiagnostics,
1743 bool PrecompilePreamble,
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001744 bool CacheCodeCompletionResults,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00001745 bool IncludeBriefCommentsInCodeCompletion,
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001746 bool UserFilesAreVolatile,
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001747 OwningPtr<ASTUnit> *ErrAST) {
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001748 assert(CI && "A CompilerInvocation is required");
1749
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001750 OwningPtr<ASTUnit> OwnAST;
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001751 ASTUnit *AST = Unit;
1752 if (!AST) {
1753 // Create the AST unit.
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001754 OwnAST.reset(create(CI, Diags, CaptureDiagnostics, UserFilesAreVolatile));
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001755 AST = OwnAST.get();
1756 }
1757
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00001758 if (!ResourceFilesPath.empty()) {
1759 // Override the resources path.
1760 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
1761 }
1762 AST->OnlyLocalDecls = OnlyLocalDecls;
1763 AST->CaptureDiagnostics = CaptureDiagnostics;
1764 if (PrecompilePreamble)
1765 AST->PreambleRebuildCounter = 2;
Douglas Gregor467dc882011-08-25 22:30:56 +00001766 AST->TUKind = Action ? Action->getTranslationUnitKind() : TU_Complete;
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00001767 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00001768 AST->IncludeBriefCommentsInCodeCompletion
1769 = IncludeBriefCommentsInCodeCompletion;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001770
1771 // Recover resources if we crash before exiting this method.
1772 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001773 ASTUnitCleanup(OwnAST.get());
David Blaikied6471f72011-09-25 23:23:43 +00001774 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1775 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001776 DiagCleanup(Diags.getPtr());
1777
1778 // We'll manage file buffers ourselves.
1779 CI->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1780 CI->getFrontendOpts().DisableFree = false;
1781 ProcessWarningOptions(AST->getDiagnostics(), CI->getDiagnosticOpts());
1782
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001783 // Create the compiler instance to use for building the AST.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001784 OwningPtr<CompilerInstance> Clang(new CompilerInstance());
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001785
1786 // Recover resources if we crash before exiting this method.
1787 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1788 CICleanup(Clang.get());
1789
1790 Clang->setInvocation(CI);
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001791 AST->OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].File;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001792
1793 // Set up diagnostics, capturing any diagnostics that would
1794 // otherwise be dropped.
1795 Clang->setDiagnostics(&AST->getDiagnostics());
1796
1797 // Create the target instance.
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001798 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
1799 Clang->getTargetOpts()));
1800 if (!Clang->hasTarget())
1801 return 0;
1802
1803 // Inform the target of the language options.
1804 //
1805 // FIXME: We shouldn't need to do this, the target should be immutable once
1806 // created. This complexity should be lifted elsewhere.
1807 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
1808
1809 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1810 "Invocation must have exactly one source file!");
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001811 assert(Clang->getFrontendOpts().Inputs[0].Kind != IK_AST &&
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001812 "FIXME: AST inputs not yet supported here!");
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001813 assert(Clang->getFrontendOpts().Inputs[0].Kind != IK_LLVM_IR &&
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001814 "IR inputs not supported here!");
1815
1816 // Configure the various subsystems.
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001817 AST->TheSema.reset();
1818 AST->Ctx = 0;
1819 AST->PP = 0;
Argyrios Kyrtzidis62ba9f62011-11-01 17:14:15 +00001820 AST->Reader = 0;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001821
1822 // Create a file manager object to provide access to and cache the filesystem.
1823 Clang->setFileManager(&AST->getFileManager());
1824
1825 // Create the source manager.
1826 Clang->setSourceManager(&AST->getSourceManager());
1827
1828 ASTFrontendAction *Act = Action;
1829
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001830 OwningPtr<TopLevelDeclTrackerAction> TrackerAct;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001831 if (!Act) {
1832 TrackerAct.reset(new TopLevelDeclTrackerAction(*AST));
1833 Act = TrackerAct.get();
1834 }
1835
1836 // Recover resources if we crash before exiting this method.
1837 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1838 ActCleanup(TrackerAct.get());
1839
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001840 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
1841 AST->transferASTDataFromCompilerInstance(*Clang);
1842 if (OwnAST && ErrAST)
1843 ErrAST->swap(OwnAST);
1844
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001845 return 0;
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001846 }
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00001847
1848 if (Persistent && !TrackerAct) {
1849 Clang->getPreprocessor().addPPCallbacks(
1850 new MacroDefinitionTrackerPPCallbacks(AST->getCurrentTopLevelHashValue()));
1851 std::vector<ASTConsumer*> Consumers;
1852 if (Clang->hasASTConsumer())
1853 Consumers.push_back(Clang->takeASTConsumer());
1854 Consumers.push_back(new TopLevelDeclTrackerConsumer(*AST,
1855 AST->getCurrentTopLevelHashValue()));
1856 Clang->setASTConsumer(new MultiplexConsumer(Consumers));
1857 }
Argyrios Kyrtzidis374a00b2012-06-08 05:48:06 +00001858 if (!Act->Execute()) {
1859 AST->transferASTDataFromCompilerInstance(*Clang);
1860 if (OwnAST && ErrAST)
1861 ErrAST->swap(OwnAST);
1862
1863 return 0;
1864 }
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001865
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001866 // Steal the created target, context, and preprocessor.
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001867 AST->transferASTDataFromCompilerInstance(*Clang);
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001868
1869 Act->EndSourceFile();
1870
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001871 if (OwnAST)
1872 return OwnAST.take();
1873 else
1874 return AST;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001875}
1876
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001877bool ASTUnit::LoadFromCompilerInvocation(bool PrecompilePreamble) {
1878 if (!Invocation)
1879 return true;
1880
1881 // We'll manage file buffers ourselves.
1882 Invocation->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1883 Invocation->getFrontendOpts().DisableFree = false;
Douglas Gregor0b53cf82011-01-19 01:02:47 +00001884 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001885
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001886 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Douglas Gregor99ba2022010-10-27 17:24:53 +00001887 if (PrecompilePreamble) {
Douglas Gregor08bb4c62010-11-15 23:00:34 +00001888 PreambleRebuildCounter = 2;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001889 OverrideMainBuffer
1890 = getMainBufferWithPrecompiledPreamble(*Invocation);
1891 }
1892
Douglas Gregor213f18b2010-10-28 15:44:59 +00001893 SimpleTimer ParsingTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00001894 ParsingTimer.setOutput("Parsing " + getMainFileName());
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001895
Ted Kremenek25a11e12011-03-22 01:15:24 +00001896 // Recover resources if we crash before exiting this method.
1897 llvm::CrashRecoveryContextCleanupRegistrar<llvm::MemoryBuffer>
1898 MemBufferCleanup(OverrideMainBuffer);
1899
Douglas Gregor213f18b2010-10-28 15:44:59 +00001900 return Parse(OverrideMainBuffer);
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001901}
1902
Douglas Gregorabc563f2010-07-19 21:46:24 +00001903ASTUnit *ASTUnit::LoadFromCompilerInvocation(CompilerInvocation *CI,
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001904 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Douglas Gregorabc563f2010-07-19 21:46:24 +00001905 bool OnlyLocalDecls,
Douglas Gregor44c181a2010-07-23 00:33:23 +00001906 bool CaptureDiagnostics,
Douglas Gregordf95a132010-08-09 20:45:32 +00001907 bool PrecompilePreamble,
Douglas Gregor467dc882011-08-25 22:30:56 +00001908 TranslationUnitKind TUKind,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00001909 bool CacheCodeCompletionResults,
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001910 bool IncludeBriefCommentsInCodeCompletion,
1911 bool UserFilesAreVolatile) {
Douglas Gregorabc563f2010-07-19 21:46:24 +00001912 // Create the AST unit.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001913 OwningPtr<ASTUnit> AST;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001914 AST.reset(new ASTUnit(false));
Douglas Gregor0b53cf82011-01-19 01:02:47 +00001915 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
Douglas Gregorabc563f2010-07-19 21:46:24 +00001916 AST->Diagnostics = Diags;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001917 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregore47be3e2010-11-11 00:39:14 +00001918 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor467dc882011-08-25 22:30:56 +00001919 AST->TUKind = TUKind;
Douglas Gregor87c08a52010-08-13 22:48:40 +00001920 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00001921 AST->IncludeBriefCommentsInCodeCompletion
1922 = IncludeBriefCommentsInCodeCompletion;
Ted Kremenek4f327862011-03-21 18:40:17 +00001923 AST->Invocation = CI;
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001924 AST->UserFilesAreVolatile = UserFilesAreVolatile;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001925
Ted Kremenekb547eeb2011-03-18 02:06:56 +00001926 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00001927 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1928 ASTUnitCleanup(AST.get());
David Blaikied6471f72011-09-25 23:23:43 +00001929 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1930 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Ted Kremenek25a11e12011-03-22 01:15:24 +00001931 DiagCleanup(Diags.getPtr());
Ted Kremenekb547eeb2011-03-18 02:06:56 +00001932
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001933 return AST->LoadFromCompilerInvocation(PrecompilePreamble)? 0 : AST.take();
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001934}
Daniel Dunbar7b556682009-12-02 03:23:45 +00001935
1936ASTUnit *ASTUnit::LoadFromCommandLine(const char **ArgBegin,
1937 const char **ArgEnd,
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001938 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001939 StringRef ResourceFilesPath,
Daniel Dunbar7b556682009-12-02 03:23:45 +00001940 bool OnlyLocalDecls,
Douglas Gregore47be3e2010-11-11 00:39:14 +00001941 bool CaptureDiagnostics,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001942 RemappedFile *RemappedFiles,
Douglas Gregora88084b2010-02-18 18:08:43 +00001943 unsigned NumRemappedFiles,
Argyrios Kyrtzidis299a4a92011-03-08 23:35:24 +00001944 bool RemappedFilesKeepOriginalName,
Douglas Gregordf95a132010-08-09 20:45:32 +00001945 bool PrecompilePreamble,
Douglas Gregor467dc882011-08-25 22:30:56 +00001946 TranslationUnitKind TUKind,
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +00001947 bool CacheCodeCompletionResults,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00001948 bool IncludeBriefCommentsInCodeCompletion,
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001949 bool AllowPCHWithCompilerErrors,
Erik Verbruggen6a91d382012-04-12 10:11:59 +00001950 bool SkipFunctionBodies,
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001951 bool UserFilesAreVolatile,
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +00001952 bool ForSerialization,
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001953 OwningPtr<ASTUnit> *ErrAST) {
Douglas Gregor28019772010-04-05 23:52:57 +00001954 if (!Diags.getPtr()) {
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001955 // No diagnostics engine was provided, so create our own diagnostics object
1956 // with the default options.
1957 DiagnosticOptions DiagOpts;
Douglas Gregor0b53cf82011-01-19 01:02:47 +00001958 Diags = CompilerInstance::createDiagnostics(DiagOpts, ArgEnd - ArgBegin,
1959 ArgBegin);
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001960 }
Daniel Dunbar7b556682009-12-02 03:23:45 +00001961
Chris Lattner5f9e2722011-07-23 10:55:15 +00001962 SmallVector<StoredDiagnostic, 4> StoredDiagnostics;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001963
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001964 IntrusiveRefCntPtr<CompilerInvocation> CI;
Douglas Gregore47be3e2010-11-11 00:39:14 +00001965
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001966 {
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001967
Douglas Gregore47be3e2010-11-11 00:39:14 +00001968 CaptureDroppedDiagnostics Capture(CaptureDiagnostics, *Diags,
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001969 StoredDiagnostics);
Daniel Dunbar3bd54cc2010-01-25 00:44:02 +00001970
Argyrios Kyrtzidis832316e2011-04-04 23:11:45 +00001971 CI = clang::createInvocationFromCommandLine(
Frits van Bommele9c02652011-07-18 12:00:32 +00001972 llvm::makeArrayRef(ArgBegin, ArgEnd),
1973 Diags);
Argyrios Kyrtzidis054e4f52011-04-04 21:38:51 +00001974 if (!CI)
Argyrios Kyrtzidis4e03c2b2011-03-07 22:45:01 +00001975 return 0;
Daniel Dunbar7b556682009-12-02 03:23:45 +00001976 }
Douglas Gregore47be3e2010-11-11 00:39:14 +00001977
Douglas Gregor4db64a42010-01-23 00:14:00 +00001978 // Override any files that need remapping
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001979 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
1980 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
1981 if (const llvm::MemoryBuffer *
1982 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
1983 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first, memBuf);
1984 } else {
1985 const char *fname = fileOrBuf.get<const char *>();
1986 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first, fname);
1987 }
1988 }
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +00001989 PreprocessorOptions &PPOpts = CI->getPreprocessorOpts();
1990 PPOpts.RemappedFilesKeepOriginalName = RemappedFilesKeepOriginalName;
1991 PPOpts.AllowPCHWithCompilerErrors = AllowPCHWithCompilerErrors;
Douglas Gregor4db64a42010-01-23 00:14:00 +00001992
Daniel Dunbar8b9adfe2009-12-15 00:06:45 +00001993 // Override the resources path.
Daniel Dunbar807b0612010-01-30 21:47:16 +00001994 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
Daniel Dunbar7b556682009-12-02 03:23:45 +00001995
Erik Verbruggen6a91d382012-04-12 10:11:59 +00001996 CI->getFrontendOpts().SkipFunctionBodies = SkipFunctionBodies;
1997
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001998 // Create the AST unit.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001999 OwningPtr<ASTUnit> AST;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00002000 AST.reset(new ASTUnit(false));
Douglas Gregor0b53cf82011-01-19 01:02:47 +00002001 ConfigureDiags(Diags, ArgBegin, ArgEnd, *AST, CaptureDiagnostics);
Douglas Gregor4cd912a2010-10-12 00:50:20 +00002002 AST->Diagnostics = Diags;
Ted Kremenekd04a9822011-11-17 23:01:17 +00002003 Diags = 0; // Zero out now to ease cleanup during crash recovery.
Anders Carlsson0d8d7e62011-03-18 18:22:40 +00002004 AST->FileSystemOpts = CI->getFileSystemOpts();
Ted Kremenek4f327862011-03-21 18:40:17 +00002005 AST->FileMgr = new FileManager(AST->FileSystemOpts);
Douglas Gregor4cd912a2010-10-12 00:50:20 +00002006 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregore47be3e2010-11-11 00:39:14 +00002007 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor467dc882011-08-25 22:30:56 +00002008 AST->TUKind = TUKind;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00002009 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002010 AST->IncludeBriefCommentsInCodeCompletion
2011 = IncludeBriefCommentsInCodeCompletion;
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00002012 AST->UserFilesAreVolatile = UserFilesAreVolatile;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00002013 AST->NumStoredDiagnosticsFromDriver = StoredDiagnostics.size();
Douglas Gregor4cd912a2010-10-12 00:50:20 +00002014 AST->StoredDiagnostics.swap(StoredDiagnostics);
Ted Kremenek4f327862011-03-21 18:40:17 +00002015 AST->Invocation = CI;
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +00002016 if (ForSerialization)
2017 AST->WriterData.reset(new ASTWriterData());
Ted Kremenekd04a9822011-11-17 23:01:17 +00002018 CI = 0; // Zero out now to ease cleanup during crash recovery.
Ted Kremenekb547eeb2011-03-18 02:06:56 +00002019
2020 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00002021 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
2022 ASTUnitCleanup(AST.get());
Ted Kremenekb547eeb2011-03-18 02:06:56 +00002023
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00002024 if (AST->LoadFromCompilerInvocation(PrecompilePreamble)) {
2025 // Some error occurred, if caller wants to examine diagnostics, pass it the
2026 // ASTUnit.
2027 if (ErrAST) {
2028 AST->StoredDiagnostics.swap(AST->FailedParseDiagnostics);
2029 ErrAST->swap(AST);
2030 }
2031 return 0;
2032 }
2033
2034 return AST.take();
Daniel Dunbar7b556682009-12-02 03:23:45 +00002035}
Douglas Gregorabc563f2010-07-19 21:46:24 +00002036
2037bool ASTUnit::Reparse(RemappedFile *RemappedFiles, unsigned NumRemappedFiles) {
Ted Kremenek4f327862011-03-21 18:40:17 +00002038 if (!Invocation)
Douglas Gregorabc563f2010-07-19 21:46:24 +00002039 return true;
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +00002040
2041 clearFileLevelDecls();
Douglas Gregorabc563f2010-07-19 21:46:24 +00002042
Douglas Gregor213f18b2010-10-28 15:44:59 +00002043 SimpleTimer ParsingTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00002044 ParsingTimer.setOutput("Reparsing " + getMainFileName());
Douglas Gregor213f18b2010-10-28 15:44:59 +00002045
Douglas Gregorcc5888d2010-07-31 00:40:00 +00002046 // Remap files.
Douglas Gregorf128fed2010-08-20 00:02:33 +00002047 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
Douglas Gregor8ef6c8c2011-02-05 19:42:43 +00002048 PPOpts.DisableStatCache = true;
Douglas Gregorf128fed2010-08-20 00:02:33 +00002049 for (PreprocessorOptions::remapped_file_buffer_iterator
2050 R = PPOpts.remapped_file_buffer_begin(),
2051 REnd = PPOpts.remapped_file_buffer_end();
2052 R != REnd;
2053 ++R) {
2054 delete R->second;
2055 }
Douglas Gregorcc5888d2010-07-31 00:40:00 +00002056 Invocation->getPreprocessorOpts().clearRemappedFiles();
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00002057 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
2058 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
2059 if (const llvm::MemoryBuffer *
2060 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
2061 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
2062 memBuf);
2063 } else {
2064 const char *fname = fileOrBuf.get<const char *>();
2065 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
2066 fname);
2067 }
2068 }
Douglas Gregorcc5888d2010-07-31 00:40:00 +00002069
Douglas Gregoreababfb2010-08-04 05:53:38 +00002070 // If we have a preamble file lying around, or if we might try to
2071 // build a precompiled preamble, do so now.
Douglas Gregor754f3492010-07-24 00:38:13 +00002072 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Ted Kremenek1872b312011-10-27 17:55:18 +00002073 if (!getPreambleFile(this).empty() || PreambleRebuildCounter > 0)
Douglas Gregor2283d792010-08-20 00:59:43 +00002074 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(*Invocation);
Douglas Gregor175c4a92010-07-23 23:58:40 +00002075
Douglas Gregorabc563f2010-07-19 21:46:24 +00002076 // Clear out the diagnostics state.
Argyrios Kyrtzidise6825d32011-11-03 20:28:19 +00002077 getDiagnostics().Reset();
2078 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Argyrios Kyrtzidis27368f92011-11-03 20:57:33 +00002079 if (OverrideMainBuffer)
2080 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
Argyrios Kyrtzidise6825d32011-11-03 20:28:19 +00002081
Douglas Gregor175c4a92010-07-23 23:58:40 +00002082 // Parse the sources
Douglas Gregor9b7db622011-02-16 18:16:54 +00002083 bool Result = Parse(OverrideMainBuffer);
Argyrios Kyrtzidis2fe17fc2011-10-31 21:25:31 +00002084
2085 // If we're caching global code-completion results, and the top-level
2086 // declarations have changed, clear out the code-completion cache.
2087 if (!Result && ShouldCacheCodeCompletionResults &&
2088 CurrentTopLevelHashValue != CompletionCacheTopLevelHashValue)
2089 CacheCodeCompletionResults();
Douglas Gregor9b7db622011-02-16 18:16:54 +00002090
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00002091 // We now need to clear out the completion info related to this translation
2092 // unit; it'll be recreated if necessary.
2093 CCTUInfo.reset();
Douglas Gregor8fa0a802011-08-04 20:04:59 +00002094
Douglas Gregor175c4a92010-07-23 23:58:40 +00002095 return Result;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002096}
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002097
Douglas Gregor87c08a52010-08-13 22:48:40 +00002098//----------------------------------------------------------------------------//
2099// Code completion
2100//----------------------------------------------------------------------------//
2101
2102namespace {
2103 /// \brief Code completion consumer that combines the cached code-completion
2104 /// results from an ASTUnit with the code-completion results provided to it,
2105 /// then passes the result on to
2106 class AugmentedCodeCompleteConsumer : public CodeCompleteConsumer {
Richard Smith026b3582012-08-14 03:13:00 +00002107 uint64_t NormalContexts;
Douglas Gregor87c08a52010-08-13 22:48:40 +00002108 ASTUnit &AST;
2109 CodeCompleteConsumer &Next;
2110
2111 public:
2112 AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002113 const CodeCompleteOptions &CodeCompleteOpts)
2114 : CodeCompleteConsumer(CodeCompleteOpts, Next.isOutputBinary()),
2115 AST(AST), Next(Next)
Douglas Gregor87c08a52010-08-13 22:48:40 +00002116 {
2117 // Compute the set of contexts in which we will look when we don't have
2118 // any information about the specific context.
2119 NormalContexts
Richard Smith026b3582012-08-14 03:13:00 +00002120 = (1LL << CodeCompletionContext::CCC_TopLevel)
2121 | (1LL << CodeCompletionContext::CCC_ObjCInterface)
2122 | (1LL << CodeCompletionContext::CCC_ObjCImplementation)
2123 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
2124 | (1LL << CodeCompletionContext::CCC_Statement)
2125 | (1LL << CodeCompletionContext::CCC_Expression)
2126 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
2127 | (1LL << CodeCompletionContext::CCC_DotMemberAccess)
2128 | (1LL << CodeCompletionContext::CCC_ArrowMemberAccess)
2129 | (1LL << CodeCompletionContext::CCC_ObjCPropertyAccess)
2130 | (1LL << CodeCompletionContext::CCC_ObjCProtocolName)
2131 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
2132 | (1LL << CodeCompletionContext::CCC_Recovery);
Douglas Gregor02688102010-09-14 23:59:36 +00002133
David Blaikie4e4d0842012-03-11 07:00:24 +00002134 if (AST.getASTContext().getLangOpts().CPlusPlus)
Richard Smith026b3582012-08-14 03:13:00 +00002135 NormalContexts |= (1LL << CodeCompletionContext::CCC_EnumTag)
2136 | (1LL << CodeCompletionContext::CCC_UnionTag)
2137 | (1LL << CodeCompletionContext::CCC_ClassOrStructTag);
Douglas Gregor87c08a52010-08-13 22:48:40 +00002138 }
2139
2140 virtual void ProcessCodeCompleteResults(Sema &S,
2141 CodeCompletionContext Context,
John McCall0a2c5e22010-08-25 06:19:51 +00002142 CodeCompletionResult *Results,
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002143 unsigned NumResults);
Douglas Gregor87c08a52010-08-13 22:48:40 +00002144
2145 virtual void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
2146 OverloadCandidate *Candidates,
2147 unsigned NumCandidates) {
2148 Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates);
2149 }
Douglas Gregor218937c2011-02-01 19:23:04 +00002150
Douglas Gregordae68752011-02-01 22:57:45 +00002151 virtual CodeCompletionAllocator &getAllocator() {
Douglas Gregor218937c2011-02-01 19:23:04 +00002152 return Next.getAllocator();
2153 }
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00002154
2155 virtual CodeCompletionTUInfo &getCodeCompletionTUInfo() {
2156 return Next.getCodeCompletionTUInfo();
2157 }
Douglas Gregor87c08a52010-08-13 22:48:40 +00002158 };
2159}
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002160
Douglas Gregor5f808c22010-08-16 21:18:39 +00002161/// \brief Helper function that computes which global names are hidden by the
2162/// local code-completion results.
Ted Kremenekc198f612010-11-07 06:11:36 +00002163static void CalculateHiddenNames(const CodeCompletionContext &Context,
2164 CodeCompletionResult *Results,
2165 unsigned NumResults,
2166 ASTContext &Ctx,
2167 llvm::StringSet<llvm::BumpPtrAllocator> &HiddenNames){
Douglas Gregor5f808c22010-08-16 21:18:39 +00002168 bool OnlyTagNames = false;
2169 switch (Context.getKind()) {
Douglas Gregor52779fb2010-09-23 23:01:17 +00002170 case CodeCompletionContext::CCC_Recovery:
Douglas Gregor5f808c22010-08-16 21:18:39 +00002171 case CodeCompletionContext::CCC_TopLevel:
2172 case CodeCompletionContext::CCC_ObjCInterface:
2173 case CodeCompletionContext::CCC_ObjCImplementation:
2174 case CodeCompletionContext::CCC_ObjCIvarList:
2175 case CodeCompletionContext::CCC_ClassStructUnion:
2176 case CodeCompletionContext::CCC_Statement:
2177 case CodeCompletionContext::CCC_Expression:
2178 case CodeCompletionContext::CCC_ObjCMessageReceiver:
Douglas Gregor3da626b2011-07-07 16:03:39 +00002179 case CodeCompletionContext::CCC_DotMemberAccess:
2180 case CodeCompletionContext::CCC_ArrowMemberAccess:
2181 case CodeCompletionContext::CCC_ObjCPropertyAccess:
Douglas Gregor5f808c22010-08-16 21:18:39 +00002182 case CodeCompletionContext::CCC_Namespace:
2183 case CodeCompletionContext::CCC_Type:
Douglas Gregor2ccccb32010-08-23 18:23:48 +00002184 case CodeCompletionContext::CCC_Name:
2185 case CodeCompletionContext::CCC_PotentiallyQualifiedName:
Douglas Gregor02688102010-09-14 23:59:36 +00002186 case CodeCompletionContext::CCC_ParenthesizedExpression:
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00002187 case CodeCompletionContext::CCC_ObjCInterfaceName:
Douglas Gregor5f808c22010-08-16 21:18:39 +00002188 break;
2189
2190 case CodeCompletionContext::CCC_EnumTag:
2191 case CodeCompletionContext::CCC_UnionTag:
2192 case CodeCompletionContext::CCC_ClassOrStructTag:
2193 OnlyTagNames = true;
2194 break;
2195
2196 case CodeCompletionContext::CCC_ObjCProtocolName:
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002197 case CodeCompletionContext::CCC_MacroName:
2198 case CodeCompletionContext::CCC_MacroNameUse:
Douglas Gregorf29c5232010-08-24 22:20:20 +00002199 case CodeCompletionContext::CCC_PreprocessorExpression:
Douglas Gregor721f3592010-08-25 18:41:16 +00002200 case CodeCompletionContext::CCC_PreprocessorDirective:
Douglas Gregor59a66942010-08-25 18:04:30 +00002201 case CodeCompletionContext::CCC_NaturalLanguage:
Douglas Gregor458433d2010-08-26 15:07:07 +00002202 case CodeCompletionContext::CCC_SelectorName:
Douglas Gregor1a480c42010-08-27 17:35:51 +00002203 case CodeCompletionContext::CCC_TypeQualifiers:
Douglas Gregor52779fb2010-09-23 23:01:17 +00002204 case CodeCompletionContext::CCC_Other:
Douglas Gregor5c722c702011-02-18 23:30:37 +00002205 case CodeCompletionContext::CCC_OtherWithMacros:
Douglas Gregor3da626b2011-07-07 16:03:39 +00002206 case CodeCompletionContext::CCC_ObjCInstanceMessage:
2207 case CodeCompletionContext::CCC_ObjCClassMessage:
2208 case CodeCompletionContext::CCC_ObjCCategoryName:
Douglas Gregor721f3592010-08-25 18:41:16 +00002209 // We're looking for nothing, or we're looking for names that cannot
2210 // be hidden.
Douglas Gregor5f808c22010-08-16 21:18:39 +00002211 return;
2212 }
2213
John McCall0a2c5e22010-08-25 06:19:51 +00002214 typedef CodeCompletionResult Result;
Douglas Gregor5f808c22010-08-16 21:18:39 +00002215 for (unsigned I = 0; I != NumResults; ++I) {
2216 if (Results[I].Kind != Result::RK_Declaration)
2217 continue;
2218
2219 unsigned IDNS
2220 = Results[I].Declaration->getUnderlyingDecl()->getIdentifierNamespace();
2221
2222 bool Hiding = false;
2223 if (OnlyTagNames)
2224 Hiding = (IDNS & Decl::IDNS_Tag);
2225 else {
2226 unsigned HiddenIDNS = (Decl::IDNS_Type | Decl::IDNS_Member |
Douglas Gregora5fb7c32010-08-16 23:05:20 +00002227 Decl::IDNS_Namespace | Decl::IDNS_Ordinary |
2228 Decl::IDNS_NonMemberOperator);
David Blaikie4e4d0842012-03-11 07:00:24 +00002229 if (Ctx.getLangOpts().CPlusPlus)
Douglas Gregor5f808c22010-08-16 21:18:39 +00002230 HiddenIDNS |= Decl::IDNS_Tag;
2231 Hiding = (IDNS & HiddenIDNS);
2232 }
2233
2234 if (!Hiding)
2235 continue;
2236
2237 DeclarationName Name = Results[I].Declaration->getDeclName();
2238 if (IdentifierInfo *Identifier = Name.getAsIdentifierInfo())
2239 HiddenNames.insert(Identifier->getName());
2240 else
2241 HiddenNames.insert(Name.getAsString());
2242 }
2243}
2244
2245
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002246void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &S,
2247 CodeCompletionContext Context,
John McCall0a2c5e22010-08-25 06:19:51 +00002248 CodeCompletionResult *Results,
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002249 unsigned NumResults) {
2250 // Merge the results we were given with the results we cached.
2251 bool AddedResult = false;
Richard Smith026b3582012-08-14 03:13:00 +00002252 uint64_t InContexts =
2253 Context.getKind() == CodeCompletionContext::CCC_Recovery
2254 ? NormalContexts : (1LL << Context.getKind());
Douglas Gregor5f808c22010-08-16 21:18:39 +00002255 // Contains the set of names that are hidden by "local" completion results.
Ted Kremenekc198f612010-11-07 06:11:36 +00002256 llvm::StringSet<llvm::BumpPtrAllocator> HiddenNames;
John McCall0a2c5e22010-08-25 06:19:51 +00002257 typedef CodeCompletionResult Result;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002258 SmallVector<Result, 8> AllResults;
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002259 for (ASTUnit::cached_completion_iterator
Douglas Gregor5535d572010-08-16 21:23:13 +00002260 C = AST.cached_completion_begin(),
2261 CEnd = AST.cached_completion_end();
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002262 C != CEnd; ++C) {
2263 // If the context we are in matches any of the contexts we are
2264 // interested in, we'll add this result.
2265 if ((C->ShowInContexts & InContexts) == 0)
2266 continue;
2267
2268 // If we haven't added any results previously, do so now.
2269 if (!AddedResult) {
Douglas Gregor5f808c22010-08-16 21:18:39 +00002270 CalculateHiddenNames(Context, Results, NumResults, S.Context,
2271 HiddenNames);
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002272 AllResults.insert(AllResults.end(), Results, Results + NumResults);
2273 AddedResult = true;
2274 }
2275
Douglas Gregor5f808c22010-08-16 21:18:39 +00002276 // Determine whether this global completion result is hidden by a local
2277 // completion result. If so, skip it.
2278 if (C->Kind != CXCursor_MacroDefinition &&
2279 HiddenNames.count(C->Completion->getTypedText()))
2280 continue;
2281
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002282 // Adjust priority based on similar type classes.
2283 unsigned Priority = C->Priority;
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002284 CodeCompletionString *Completion = C->Completion;
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002285 if (!Context.getPreferredType().isNull()) {
2286 if (C->Kind == CXCursor_MacroDefinition) {
2287 Priority = getMacroUsagePriority(C->Completion->getTypedText(),
David Blaikie4e4d0842012-03-11 07:00:24 +00002288 S.getLangOpts(),
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002289 Context.getPreferredType()->isAnyPointerType());
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002290 } else if (C->Type) {
2291 CanQualType Expected
Douglas Gregor5535d572010-08-16 21:23:13 +00002292 = S.Context.getCanonicalType(
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002293 Context.getPreferredType().getUnqualifiedType());
2294 SimplifiedTypeClass ExpectedSTC = getSimplifiedTypeClass(Expected);
2295 if (ExpectedSTC == C->TypeClass) {
2296 // We know this type is similar; check for an exact match.
2297 llvm::StringMap<unsigned> &CachedCompletionTypes
Douglas Gregor5535d572010-08-16 21:23:13 +00002298 = AST.getCachedCompletionTypes();
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002299 llvm::StringMap<unsigned>::iterator Pos
Douglas Gregor5535d572010-08-16 21:23:13 +00002300 = CachedCompletionTypes.find(QualType(Expected).getAsString());
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002301 if (Pos != CachedCompletionTypes.end() && Pos->second == C->Type)
2302 Priority /= CCF_ExactTypeMatch;
2303 else
2304 Priority /= CCF_SimilarTypeMatch;
2305 }
2306 }
2307 }
2308
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002309 // Adjust the completion string, if required.
2310 if (C->Kind == CXCursor_MacroDefinition &&
2311 Context.getKind() == CodeCompletionContext::CCC_MacroNameUse) {
2312 // Create a new code-completion string that just contains the
2313 // macro name, without its arguments.
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00002314 CodeCompletionBuilder Builder(getAllocator(), getCodeCompletionTUInfo(),
2315 CCP_CodePattern, C->Availability);
Douglas Gregor218937c2011-02-01 19:23:04 +00002316 Builder.AddTypedTextChunk(C->Completion->getTypedText());
Douglas Gregor4125c372010-08-25 18:03:13 +00002317 Priority = CCP_CodePattern;
Douglas Gregor218937c2011-02-01 19:23:04 +00002318 Completion = Builder.TakeString();
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002319 }
2320
Argyrios Kyrtzidisc04bb922012-09-27 00:24:09 +00002321 AllResults.push_back(Result(Completion, Priority, C->Kind,
Douglas Gregor58ddb602010-08-23 23:00:57 +00002322 C->Availability));
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002323 }
2324
2325 // If we did not add any cached completion results, just forward the
2326 // results we were given to the next consumer.
2327 if (!AddedResult) {
2328 Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
2329 return;
2330 }
Douglas Gregor1e5e6682010-08-26 13:48:20 +00002331
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002332 Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
2333 AllResults.size());
2334}
2335
2336
2337
Chris Lattner5f9e2722011-07-23 10:55:15 +00002338void ASTUnit::CodeComplete(StringRef File, unsigned Line, unsigned Column,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002339 RemappedFile *RemappedFiles,
2340 unsigned NumRemappedFiles,
Douglas Gregorcee235c2010-08-05 09:09:23 +00002341 bool IncludeMacros,
2342 bool IncludeCodePatterns,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002343 bool IncludeBriefComments,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002344 CodeCompleteConsumer &Consumer,
David Blaikied6471f72011-09-25 23:23:43 +00002345 DiagnosticsEngine &Diag, LangOptions &LangOpts,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002346 SourceManager &SourceMgr, FileManager &FileMgr,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002347 SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
2348 SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers) {
Ted Kremenek4f327862011-03-21 18:40:17 +00002349 if (!Invocation)
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002350 return;
2351
Douglas Gregor213f18b2010-10-28 15:44:59 +00002352 SimpleTimer CompletionTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00002353 CompletionTimer.setOutput("Code completion @ " + File + ":" +
Chris Lattner5f9e2722011-07-23 10:55:15 +00002354 Twine(Line) + ":" + Twine(Column));
Douglas Gregordf95a132010-08-09 20:45:32 +00002355
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00002356 IntrusiveRefCntPtr<CompilerInvocation>
Ted Kremenek4f327862011-03-21 18:40:17 +00002357 CCInvocation(new CompilerInvocation(*Invocation));
2358
2359 FrontendOptions &FrontendOpts = CCInvocation->getFrontendOpts();
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002360 CodeCompleteOptions &CodeCompleteOpts = FrontendOpts.CodeCompleteOpts;
Ted Kremenek4f327862011-03-21 18:40:17 +00002361 PreprocessorOptions &PreprocessorOpts = CCInvocation->getPreprocessorOpts();
Douglas Gregorcee235c2010-08-05 09:09:23 +00002362
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002363 CodeCompleteOpts.IncludeMacros = IncludeMacros &&
2364 CachedCompletionResults.empty();
2365 CodeCompleteOpts.IncludeCodePatterns = IncludeCodePatterns;
2366 CodeCompleteOpts.IncludeGlobals = CachedCompletionResults.empty();
2367 CodeCompleteOpts.IncludeBriefComments = IncludeBriefComments;
2368
2369 assert(IncludeBriefComments == this->IncludeBriefCommentsInCodeCompletion);
2370
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002371 FrontendOpts.CodeCompletionAt.FileName = File;
2372 FrontendOpts.CodeCompletionAt.Line = Line;
2373 FrontendOpts.CodeCompletionAt.Column = Column;
2374
2375 // Set the language options appropriately.
Ted Kremenekd3b74d92011-11-17 23:01:24 +00002376 LangOpts = *CCInvocation->getLangOpts();
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002377
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00002378 OwningPtr<CompilerInstance> Clang(new CompilerInstance());
Ted Kremenek03201fb2011-03-21 18:40:07 +00002379
2380 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00002381 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
2382 CICleanup(Clang.get());
Ted Kremenek03201fb2011-03-21 18:40:07 +00002383
Ted Kremenek4f327862011-03-21 18:40:17 +00002384 Clang->setInvocation(&*CCInvocation);
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00002385 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].File;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002386
2387 // Set up diagnostics, capturing any diagnostics produced.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002388 Clang->setDiagnostics(&Diag);
Ted Kremenek4f327862011-03-21 18:40:17 +00002389 ProcessWarningOptions(Diag, CCInvocation->getDiagnosticOpts());
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002390 CaptureDroppedDiagnostics Capture(true,
Ted Kremenek03201fb2011-03-21 18:40:07 +00002391 Clang->getDiagnostics(),
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002392 StoredDiagnostics);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002393
2394 // Create the target instance.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002395 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
2396 Clang->getTargetOpts()));
2397 if (!Clang->hasTarget()) {
Ted Kremenek4f327862011-03-21 18:40:17 +00002398 Clang->setInvocation(0);
Douglas Gregorbdbb0042010-08-18 22:29:43 +00002399 return;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002400 }
2401
2402 // Inform the target of the language options.
2403 //
2404 // FIXME: We shouldn't need to do this, the target should be immutable once
2405 // created. This complexity should be lifted elsewhere.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002406 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002407
Ted Kremenek03201fb2011-03-21 18:40:07 +00002408 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002409 "Invocation must have exactly one source file!");
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00002410 assert(Clang->getFrontendOpts().Inputs[0].Kind != IK_AST &&
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002411 "FIXME: AST inputs not yet supported here!");
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00002412 assert(Clang->getFrontendOpts().Inputs[0].Kind != IK_LLVM_IR &&
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002413 "IR inputs not support here!");
2414
2415
2416 // Use the source and file managers that we were given.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002417 Clang->setFileManager(&FileMgr);
2418 Clang->setSourceManager(&SourceMgr);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002419
2420 // Remap files.
2421 PreprocessorOpts.clearRemappedFiles();
Douglas Gregorb75d3df2010-08-04 17:07:00 +00002422 PreprocessorOpts.RetainRemappedFileBuffers = true;
Douglas Gregor2283d792010-08-20 00:59:43 +00002423 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00002424 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
2425 if (const llvm::MemoryBuffer *
2426 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
2427 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first, memBuf);
2428 OwnedBuffers.push_back(memBuf);
2429 } else {
2430 const char *fname = fileOrBuf.get<const char *>();
2431 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first, fname);
2432 }
Douglas Gregor2283d792010-08-20 00:59:43 +00002433 }
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002434
Douglas Gregor87c08a52010-08-13 22:48:40 +00002435 // Use the code completion consumer we were given, but adding any cached
2436 // code-completion results.
Douglas Gregor7f946ad2010-11-29 16:13:56 +00002437 AugmentedCodeCompleteConsumer *AugmentedConsumer
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002438 = new AugmentedCodeCompleteConsumer(*this, Consumer, CodeCompleteOpts);
Ted Kremenek03201fb2011-03-21 18:40:07 +00002439 Clang->setCodeCompletionConsumer(AugmentedConsumer);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002440
Erik Verbruggen6a91d382012-04-12 10:11:59 +00002441 Clang->getFrontendOpts().SkipFunctionBodies = true;
2442
Douglas Gregordf95a132010-08-09 20:45:32 +00002443 // If we have a precompiled preamble, try to use it. We only allow
2444 // the use of the precompiled preamble if we're if the completion
2445 // point is within the main file, after the end of the precompiled
2446 // preamble.
2447 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Ted Kremenek1872b312011-10-27 17:55:18 +00002448 if (!getPreambleFile(this).empty()) {
Douglas Gregordf95a132010-08-09 20:45:32 +00002449 using llvm::sys::FileStatus;
2450 llvm::sys::PathWithStatus CompleteFilePath(File);
2451 llvm::sys::PathWithStatus MainPath(OriginalSourceFile);
2452 if (const FileStatus *CompleteFileStatus = CompleteFilePath.getFileStatus())
2453 if (const FileStatus *MainStatus = MainPath.getFileStatus())
Argyrios Kyrtzidisc8c97a02011-09-04 03:32:04 +00002454 if (CompleteFileStatus->getUniqueID() == MainStatus->getUniqueID() &&
2455 Line > 1)
Douglas Gregor2283d792010-08-20 00:59:43 +00002456 OverrideMainBuffer
Ted Kremenek4f327862011-03-21 18:40:17 +00002457 = getMainBufferWithPrecompiledPreamble(*CCInvocation, false,
Douglas Gregorc9c29a82010-08-25 18:04:15 +00002458 Line - 1);
Douglas Gregordf95a132010-08-09 20:45:32 +00002459 }
2460
2461 // If the main file has been overridden due to the use of a preamble,
2462 // make that override happen and introduce the preamble.
Douglas Gregor8ef6c8c2011-02-05 19:42:43 +00002463 PreprocessorOpts.DisableStatCache = true;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00002464 StoredDiagnostics.insert(StoredDiagnostics.end(),
Argyrios Kyrtzidis3e9d3262011-10-24 17:25:20 +00002465 stored_diag_begin(),
2466 stored_diag_afterDriver_begin());
Douglas Gregordf95a132010-08-09 20:45:32 +00002467 if (OverrideMainBuffer) {
2468 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
2469 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
2470 PreprocessorOpts.PrecompiledPreambleBytes.second
2471 = PreambleEndsAtStartOfLine;
Ted Kremenek1872b312011-10-27 17:55:18 +00002472 PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
Douglas Gregordf95a132010-08-09 20:45:32 +00002473 PreprocessorOpts.DisablePCHValidation = true;
2474
Douglas Gregor2283d792010-08-20 00:59:43 +00002475 OwnedBuffers.push_back(OverrideMainBuffer);
Douglas Gregorf128fed2010-08-20 00:02:33 +00002476 } else {
2477 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
2478 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregordf95a132010-08-09 20:45:32 +00002479 }
2480
Douglas Gregordca8ee82011-05-06 16:33:08 +00002481 // Disable the preprocessing record
2482 PreprocessorOpts.DetailedRecord = false;
2483
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00002484 OwningPtr<SyntaxOnlyAction> Act;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002485 Act.reset(new SyntaxOnlyAction);
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00002486 if (Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002487 if (OverrideMainBuffer) {
Ted Kremenek1872b312011-10-27 17:55:18 +00002488 std::string ModName = getPreambleFile(this);
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002489 TranslateStoredDiagnostics(Clang->getModuleManager(), ModName,
2490 getSourceManager(), PreambleDiagnostics,
2491 StoredDiagnostics);
2492 }
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002493 Act->Execute();
2494 Act->EndSourceFile();
2495 }
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00002496
2497 checkAndSanitizeDiags(StoredDiagnostics, getSourceManager());
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002498}
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002499
Argyrios Kyrtzidise6d22022012-09-26 16:39:46 +00002500bool ASTUnit::Save(StringRef File) {
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002501 // Write to a temporary file and later rename it to the actual file, to avoid
2502 // possible race conditions.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002503 SmallString<128> TempPath;
Argyrios Kyrtzidis7e909852011-07-28 00:45:10 +00002504 TempPath = File;
2505 TempPath += "-%%%%%%%%";
2506 int fd;
2507 if (llvm::sys::fs::unique_file(TempPath.str(), fd, TempPath,
2508 /*makeAbsolute=*/false))
Argyrios Kyrtzidise6d22022012-09-26 16:39:46 +00002509 return true;
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002510
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002511 // FIXME: Can we somehow regenerate the stat cache here, or do we need to
2512 // unconditionally create a stat cache when we parse the file?
Argyrios Kyrtzidis7e909852011-07-28 00:45:10 +00002513 llvm::raw_fd_ostream Out(fd, /*shouldClose=*/true);
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00002514
2515 serialize(Out);
2516 Out.close();
Argyrios Kyrtzidis4bd26542012-03-13 02:17:06 +00002517 if (Out.has_error()) {
2518 Out.clear_error();
Argyrios Kyrtzidise6d22022012-09-26 16:39:46 +00002519 return true;
Argyrios Kyrtzidis4bd26542012-03-13 02:17:06 +00002520 }
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002521
Rafael Espindola8d2a7012011-12-25 01:18:52 +00002522 if (llvm::sys::fs::rename(TempPath.str(), File)) {
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002523 bool exists;
2524 llvm::sys::fs::remove(TempPath.str(), exists);
Argyrios Kyrtzidise6d22022012-09-26 16:39:46 +00002525 return true;
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002526 }
2527
Argyrios Kyrtzidise6d22022012-09-26 16:39:46 +00002528 return false;
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00002529}
2530
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +00002531static bool serializeUnit(ASTWriter &Writer,
2532 SmallVectorImpl<char> &Buffer,
2533 Sema &S,
2534 bool hasErrors,
2535 raw_ostream &OS) {
2536 Writer.WriteAST(S, 0, std::string(), 0, "", hasErrors);
2537
2538 // Write the generated bitstream to "Out".
2539 if (!Buffer.empty())
2540 OS.write(Buffer.data(), Buffer.size());
2541
2542 return false;
2543}
2544
Chris Lattner5f9e2722011-07-23 10:55:15 +00002545bool ASTUnit::serialize(raw_ostream &OS) {
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +00002546 bool hasErrors = getDiagnostics().hasErrorOccurred();
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00002547
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +00002548 if (WriterData)
2549 return serializeUnit(WriterData->Writer, WriterData->Buffer,
2550 getSema(), hasErrors, OS);
2551
Daniel Dunbar8d6ff022012-02-29 20:31:23 +00002552 SmallString<128> Buffer;
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002553 llvm::BitstreamWriter Stream(Buffer);
Sebastian Redla4232eb2010-08-18 23:56:21 +00002554 ASTWriter Writer(Stream);
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +00002555 return serializeUnit(Writer, Buffer, getSema(), hasErrors, OS);
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002556}
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002557
2558typedef ContinuousRangeMap<unsigned, int, 2> SLocRemap;
2559
2560static void TranslateSLoc(SourceLocation &L, SLocRemap &Remap) {
2561 unsigned Raw = L.getRawEncoding();
2562 const unsigned MacroBit = 1U << 31;
2563 L = SourceLocation::getFromRawEncoding((Raw & MacroBit) |
2564 ((Raw & ~MacroBit) + Remap.find(Raw & ~MacroBit)->second));
2565}
2566
2567void ASTUnit::TranslateStoredDiagnostics(
2568 ASTReader *MMan,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002569 StringRef ModName,
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002570 SourceManager &SrcMgr,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002571 const SmallVectorImpl<StoredDiagnostic> &Diags,
2572 SmallVectorImpl<StoredDiagnostic> &Out) {
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002573 // The stored diagnostic has the old source manager in it; update
2574 // the locations to refer into the new source manager. We also need to remap
2575 // all the locations to the new view. This includes the diag location, any
2576 // associated source ranges, and the source ranges of associated fix-its.
2577 // FIXME: There should be a cleaner way to do this.
2578
Chris Lattner5f9e2722011-07-23 10:55:15 +00002579 SmallVector<StoredDiagnostic, 4> Result;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002580 Result.reserve(Diags.size());
2581 assert(MMan && "Don't have a module manager");
Douglas Gregor1a4761e2011-11-30 23:21:26 +00002582 serialization::ModuleFile *Mod = MMan->ModuleMgr.lookup(ModName);
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002583 assert(Mod && "Don't have preamble module");
2584 SLocRemap &Remap = Mod->SLocRemap;
2585 for (unsigned I = 0, N = Diags.size(); I != N; ++I) {
2586 // Rebuild the StoredDiagnostic.
2587 const StoredDiagnostic &SD = Diags[I];
2588 SourceLocation L = SD.getLocation();
2589 TranslateSLoc(L, Remap);
2590 FullSourceLoc Loc(L, SrcMgr);
2591
Chris Lattner5f9e2722011-07-23 10:55:15 +00002592 SmallVector<CharSourceRange, 4> Ranges;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002593 Ranges.reserve(SD.range_size());
2594 for (StoredDiagnostic::range_iterator I = SD.range_begin(),
2595 E = SD.range_end();
2596 I != E; ++I) {
2597 SourceLocation BL = I->getBegin();
2598 TranslateSLoc(BL, Remap);
2599 SourceLocation EL = I->getEnd();
2600 TranslateSLoc(EL, Remap);
2601 Ranges.push_back(CharSourceRange(SourceRange(BL, EL), I->isTokenRange()));
2602 }
2603
Chris Lattner5f9e2722011-07-23 10:55:15 +00002604 SmallVector<FixItHint, 2> FixIts;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002605 FixIts.reserve(SD.fixit_size());
2606 for (StoredDiagnostic::fixit_iterator I = SD.fixit_begin(),
2607 E = SD.fixit_end();
2608 I != E; ++I) {
2609 FixIts.push_back(FixItHint());
2610 FixItHint &FH = FixIts.back();
2611 FH.CodeToInsert = I->CodeToInsert;
2612 SourceLocation BL = I->RemoveRange.getBegin();
2613 TranslateSLoc(BL, Remap);
2614 SourceLocation EL = I->RemoveRange.getEnd();
2615 TranslateSLoc(EL, Remap);
2616 FH.RemoveRange = CharSourceRange(SourceRange(BL, EL),
2617 I->RemoveRange.isTokenRange());
2618 }
2619
2620 Result.push_back(StoredDiagnostic(SD.getLevel(), SD.getID(),
2621 SD.getMessage(), Loc, Ranges, FixIts));
2622 }
2623 Result.swap(Out);
2624}
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002625
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +00002626static inline bool compLocDecl(std::pair<unsigned, Decl *> L,
2627 std::pair<unsigned, Decl *> R) {
2628 return L.first < R.first;
2629}
2630
2631void ASTUnit::addFileLevelDecl(Decl *D) {
2632 assert(D);
Douglas Gregor66e87002011-11-07 18:53:57 +00002633
2634 // We only care about local declarations.
2635 if (D->isFromASTFile())
2636 return;
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +00002637
2638 SourceManager &SM = *SourceMgr;
2639 SourceLocation Loc = D->getLocation();
2640 if (Loc.isInvalid() || !SM.isLocalSourceLocation(Loc))
2641 return;
2642
2643 // We only keep track of the file-level declarations of each file.
2644 if (!D->getLexicalDeclContext()->isFileContext())
2645 return;
2646
2647 SourceLocation FileLoc = SM.getFileLoc(Loc);
2648 assert(SM.isLocalSourceLocation(FileLoc));
2649 FileID FID;
2650 unsigned Offset;
2651 llvm::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc);
2652 if (FID.isInvalid())
2653 return;
2654
2655 LocDeclsTy *&Decls = FileDecls[FID];
2656 if (!Decls)
2657 Decls = new LocDeclsTy();
2658
2659 std::pair<unsigned, Decl *> LocDecl(Offset, D);
2660
2661 if (Decls->empty() || Decls->back().first <= Offset) {
2662 Decls->push_back(LocDecl);
2663 return;
2664 }
2665
2666 LocDeclsTy::iterator
2667 I = std::upper_bound(Decls->begin(), Decls->end(), LocDecl, compLocDecl);
2668
2669 Decls->insert(I, LocDecl);
2670}
2671
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +00002672void ASTUnit::findFileRegionDecls(FileID File, unsigned Offset, unsigned Length,
2673 SmallVectorImpl<Decl *> &Decls) {
2674 if (File.isInvalid())
2675 return;
2676
2677 if (SourceMgr->isLoadedFileID(File)) {
2678 assert(Ctx->getExternalSource() && "No external source!");
2679 return Ctx->getExternalSource()->FindFileRegionDecls(File, Offset, Length,
2680 Decls);
2681 }
2682
2683 FileDeclsTy::iterator I = FileDecls.find(File);
2684 if (I == FileDecls.end())
2685 return;
2686
2687 LocDeclsTy &LocDecls = *I->second;
2688 if (LocDecls.empty())
2689 return;
2690
2691 LocDeclsTy::iterator
2692 BeginIt = std::lower_bound(LocDecls.begin(), LocDecls.end(),
2693 std::make_pair(Offset, (Decl*)0), compLocDecl);
2694 if (BeginIt != LocDecls.begin())
2695 --BeginIt;
2696
Argyrios Kyrtzidisc14a03d2011-11-23 20:27:36 +00002697 // If we are pointing at a top-level decl inside an objc container, we need
2698 // to backtrack until we find it otherwise we will fail to report that the
2699 // region overlaps with an objc container.
2700 while (BeginIt != LocDecls.begin() &&
2701 BeginIt->second->isTopLevelDeclInObjCContainer())
2702 --BeginIt;
2703
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +00002704 LocDeclsTy::iterator
2705 EndIt = std::upper_bound(LocDecls.begin(), LocDecls.end(),
2706 std::make_pair(Offset+Length, (Decl*)0),
2707 compLocDecl);
2708 if (EndIt != LocDecls.end())
2709 ++EndIt;
2710
2711 for (LocDeclsTy::iterator DIt = BeginIt; DIt != EndIt; ++DIt)
2712 Decls.push_back(DIt->second);
2713}
2714
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002715SourceLocation ASTUnit::getLocation(const FileEntry *File,
2716 unsigned Line, unsigned Col) const {
2717 const SourceManager &SM = getSourceManager();
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00002718 SourceLocation Loc = SM.translateFileLineCol(File, Line, Col);
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002719 return SM.getMacroArgExpandedLocation(Loc);
2720}
2721
2722SourceLocation ASTUnit::getLocation(const FileEntry *File,
2723 unsigned Offset) const {
2724 const SourceManager &SM = getSourceManager();
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00002725 SourceLocation FileLoc = SM.translateFileLineCol(File, 1, 1);
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002726 return SM.getMacroArgExpandedLocation(FileLoc.getLocWithOffset(Offset));
2727}
2728
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00002729/// \brief If \arg Loc is a loaded location from the preamble, returns
2730/// the corresponding local location of the main file, otherwise it returns
2731/// \arg Loc.
2732SourceLocation ASTUnit::mapLocationFromPreamble(SourceLocation Loc) {
2733 FileID PreambleID;
2734 if (SourceMgr)
2735 PreambleID = SourceMgr->getPreambleFileID();
2736
2737 if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2738 return Loc;
2739
2740 unsigned Offs;
2741 if (SourceMgr->isInFileID(Loc, PreambleID, &Offs) && Offs < Preamble.size()) {
2742 SourceLocation FileLoc
2743 = SourceMgr->getLocForStartOfFile(SourceMgr->getMainFileID());
2744 return FileLoc.getLocWithOffset(Offs);
2745 }
2746
2747 return Loc;
2748}
2749
2750/// \brief If \arg Loc is a local location of the main file but inside the
2751/// preamble chunk, returns the corresponding loaded location from the
2752/// preamble, otherwise it returns \arg Loc.
2753SourceLocation ASTUnit::mapLocationToPreamble(SourceLocation Loc) {
2754 FileID PreambleID;
2755 if (SourceMgr)
2756 PreambleID = SourceMgr->getPreambleFileID();
2757
2758 if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2759 return Loc;
2760
2761 unsigned Offs;
2762 if (SourceMgr->isInFileID(Loc, SourceMgr->getMainFileID(), &Offs) &&
2763 Offs < Preamble.size()) {
2764 SourceLocation FileLoc = SourceMgr->getLocForStartOfFile(PreambleID);
2765 return FileLoc.getLocWithOffset(Offs);
2766 }
2767
2768 return Loc;
2769}
2770
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00002771bool ASTUnit::isInPreambleFileID(SourceLocation Loc) {
2772 FileID FID;
2773 if (SourceMgr)
2774 FID = SourceMgr->getPreambleFileID();
2775
2776 if (Loc.isInvalid() || FID.isInvalid())
2777 return false;
2778
2779 return SourceMgr->isInFileID(Loc, FID);
2780}
2781
2782bool ASTUnit::isInMainFileID(SourceLocation Loc) {
2783 FileID FID;
2784 if (SourceMgr)
2785 FID = SourceMgr->getMainFileID();
2786
2787 if (Loc.isInvalid() || FID.isInvalid())
2788 return false;
2789
2790 return SourceMgr->isInFileID(Loc, FID);
2791}
2792
2793SourceLocation ASTUnit::getEndOfPreambleFileID() {
2794 FileID FID;
2795 if (SourceMgr)
2796 FID = SourceMgr->getPreambleFileID();
2797
2798 if (FID.isInvalid())
2799 return SourceLocation();
2800
2801 return SourceMgr->getLocForEndOfFile(FID);
2802}
2803
2804SourceLocation ASTUnit::getStartOfMainFileID() {
2805 FileID FID;
2806 if (SourceMgr)
2807 FID = SourceMgr->getMainFileID();
2808
2809 if (FID.isInvalid())
2810 return SourceLocation();
2811
2812 return SourceMgr->getLocForStartOfFile(FID);
2813}
2814
Argyrios Kyrtzidis632dcc92012-10-02 16:10:51 +00002815std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
2816ASTUnit::getLocalPreprocessingEntities() const {
2817 if (isMainFileAST()) {
2818 serialization::ModuleFile &
2819 Mod = Reader->getModuleManager().getPrimaryModule();
2820 return Reader->getModulePreprocessedEntities(Mod);
2821 }
2822
2823 if (PreprocessingRecord *PPRec = PP->getPreprocessingRecord())
2824 return std::make_pair(PPRec->local_begin(), PPRec->local_end());
2825
2826 return std::make_pair(PreprocessingRecord::iterator(),
2827 PreprocessingRecord::iterator());
2828}
2829
Argyrios Kyrtzidis95c579c2012-10-03 01:58:28 +00002830bool ASTUnit::visitLocalTopLevelDecls(void *context, DeclVisitorFn Fn) {
Argyrios Kyrtzidis2093e0b2012-10-02 21:09:13 +00002831 if (isMainFileAST()) {
2832 serialization::ModuleFile &
2833 Mod = Reader->getModuleManager().getPrimaryModule();
2834 ASTReader::ModuleDeclIterator MDI, MDE;
2835 llvm::tie(MDI, MDE) = Reader->getModuleFileLevelDecls(Mod);
2836 for (; MDI != MDE; ++MDI) {
2837 if (!Fn(context, *MDI))
2838 return false;
2839 }
2840
2841 return true;
2842 }
2843
2844 for (ASTUnit::top_level_iterator TL = top_level_begin(),
2845 TLEnd = top_level_end();
2846 TL != TLEnd; ++TL) {
2847 if (!Fn(context, *TL))
2848 return false;
2849 }
2850
2851 return true;
2852}
2853
Argyrios Kyrtzidis3da76bf2012-10-03 21:05:51 +00002854namespace {
2855struct PCHLocatorInfo {
2856 serialization::ModuleFile *Mod;
2857 PCHLocatorInfo() : Mod(0) {}
2858};
2859}
2860
2861static bool PCHLocator(serialization::ModuleFile &M, void *UserData) {
2862 PCHLocatorInfo &Info = *static_cast<PCHLocatorInfo*>(UserData);
2863 switch (M.Kind) {
2864 case serialization::MK_Module:
2865 return true; // skip dependencies.
2866 case serialization::MK_PCH:
2867 Info.Mod = &M;
2868 return true; // found it.
2869 case serialization::MK_Preamble:
2870 return false; // look in dependencies.
2871 case serialization::MK_MainFile:
2872 return false; // look in dependencies.
2873 }
2874
2875 return true;
2876}
2877
2878const FileEntry *ASTUnit::getPCHFile() {
2879 if (!Reader)
2880 return 0;
2881
2882 PCHLocatorInfo Info;
2883 Reader->getModuleManager().visit(PCHLocator, &Info);
2884 if (Info.Mod)
2885 return Info.Mod->File;
2886
2887 return 0;
2888}
2889
Argyrios Kyrtzidis62288ed2012-10-10 02:12:47 +00002890bool ASTUnit::isModuleFile() {
2891 return isMainFileAST() && !ASTFileLangOpts.CurrentModule.empty();
2892}
2893
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002894void ASTUnit::PreambleData::countLines() const {
2895 NumLines = 0;
2896 if (empty())
2897 return;
2898
2899 for (std::vector<char>::const_iterator
2900 I = Buffer.begin(), E = Buffer.end(); I != E; ++I) {
2901 if (*I == '\n')
2902 ++NumLines;
2903 }
2904 if (Buffer.back() != '\n')
2905 ++NumLines;
2906}
Argyrios Kyrtzidisa696ece2011-10-10 21:57:12 +00002907
2908#ifndef NDEBUG
2909ASTUnit::ConcurrencyState::ConcurrencyState() {
2910 Mutex = new llvm::sys::MutexImpl(/*recursive=*/true);
2911}
2912
2913ASTUnit::ConcurrencyState::~ConcurrencyState() {
2914 delete static_cast<llvm::sys::MutexImpl *>(Mutex);
2915}
2916
2917void ASTUnit::ConcurrencyState::start() {
2918 bool acquired = static_cast<llvm::sys::MutexImpl *>(Mutex)->tryacquire();
2919 assert(acquired && "Concurrent access to ASTUnit!");
2920}
2921
2922void ASTUnit::ConcurrencyState::finish() {
2923 static_cast<llvm::sys::MutexImpl *>(Mutex)->release();
2924}
2925
2926#else // NDEBUG
2927
2928ASTUnit::ConcurrencyState::ConcurrencyState() {}
2929ASTUnit::ConcurrencyState::~ConcurrencyState() {}
2930void ASTUnit::ConcurrencyState::start() {}
2931void ASTUnit::ConcurrencyState::finish() {}
2932
2933#endif