blob: 7850dc697be498a944fcab9ce45423b59fba1766 [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"
Daniel Dunbar521bf9c2009-12-01 09:51:01 +000015#include "clang/AST/ASTConsumer.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000016#include "clang/AST/ASTContext.h"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000017#include "clang/AST/DeclVisitor.h"
18#include "clang/AST/StmtVisitor.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000019#include "clang/AST/TypeOrdering.h"
20#include "clang/Basic/Diagnostic.h"
21#include "clang/Basic/TargetInfo.h"
22#include "clang/Basic/TargetOptions.h"
Daniel Dunbar521bf9c2009-12-01 09:51:01 +000023#include "clang/Frontend/CompilerInstance.h"
24#include "clang/Frontend/FrontendActions.h"
Daniel Dunbar7b556682009-12-02 03:23:45 +000025#include "clang/Frontend/FrontendDiagnostic.h"
Daniel Dunbar521bf9c2009-12-01 09:51:01 +000026#include "clang/Frontend/FrontendOptions.h"
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +000027#include "clang/Frontend/MultiplexConsumer.h"
Douglas Gregor32be4a52010-10-11 21:37:58 +000028#include "clang/Frontend/Utils.h"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000029#include "clang/Lex/HeaderSearch.h"
30#include "clang/Lex/Preprocessor.h"
Douglas Gregor36a16492012-10-24 17:46:57 +000031#include "clang/Lex/PreprocessorOptions.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000032#include "clang/Serialization/ASTReader.h"
33#include "clang/Serialization/ASTWriter.h"
Chris Lattner7f9fc3f2011-03-23 04:04:01 +000034#include "llvm/ADT/ArrayRef.h"
Douglas Gregor9b7db622011-02-16 18:16:54 +000035#include "llvm/ADT/StringExtras.h"
Douglas Gregor349d38c2010-08-16 23:08:34 +000036#include "llvm/ADT/StringSet.h"
Douglas Gregor1fd9e0d2010-12-07 00:05:48 +000037#include "llvm/Support/Atomic.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000038#include "llvm/Support/CrashRecoveryContext.h"
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +000039#include "llvm/Support/FileSystem.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000040#include "llvm/Support/Host.h"
41#include "llvm/Support/MemoryBuffer.h"
Argyrios Kyrtzidisa696ece2011-10-10 21:57:12 +000042#include "llvm/Support/Mutex.h"
Ted Kremeneke055f8a2011-10-27 19:44:25 +000043#include "llvm/Support/MutexGuard.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000044#include "llvm/Support/Path.h"
45#include "llvm/Support/Timer.h"
46#include "llvm/Support/raw_ostream.h"
Zhongxing Xuad23ebe2010-07-23 02:15:08 +000047#include <cstdio>
Chandler Carruth55fc8732012-12-04 09:13:33 +000048#include <cstdlib>
Douglas Gregorcc5888d2010-07-31 00:40:00 +000049#include <sys/stat.h>
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000050using namespace clang;
51
Douglas Gregor213f18b2010-10-28 15:44:59 +000052using llvm::TimeRecord;
53
54namespace {
55 class SimpleTimer {
56 bool WantTiming;
57 TimeRecord Start;
58 std::string Output;
59
Benjamin Krameredfb7ec2010-11-09 20:00:56 +000060 public:
Douglas Gregor9dba61a2010-11-01 13:48:43 +000061 explicit SimpleTimer(bool WantTiming) : WantTiming(WantTiming) {
Douglas Gregor213f18b2010-10-28 15:44:59 +000062 if (WantTiming)
Benjamin Krameredfb7ec2010-11-09 20:00:56 +000063 Start = TimeRecord::getCurrentTime();
Douglas Gregor213f18b2010-10-28 15:44:59 +000064 }
65
Chris Lattner5f9e2722011-07-23 10:55:15 +000066 void setOutput(const Twine &Output) {
Douglas Gregor213f18b2010-10-28 15:44:59 +000067 if (WantTiming)
Benjamin Krameredfb7ec2010-11-09 20:00:56 +000068 this->Output = Output.str();
Douglas Gregor213f18b2010-10-28 15:44:59 +000069 }
70
Douglas Gregor213f18b2010-10-28 15:44:59 +000071 ~SimpleTimer() {
72 if (WantTiming) {
73 TimeRecord Elapsed = TimeRecord::getCurrentTime();
74 Elapsed -= Start;
75 llvm::errs() << Output << ':';
76 Elapsed.print(Elapsed, llvm::errs());
77 llvm::errs() << '\n';
78 }
79 }
80 };
Ted Kremenek1872b312011-10-27 17:55:18 +000081
82 struct OnDiskData {
83 /// \brief The file in which the precompiled preamble is stored.
84 std::string PreambleFile;
85
86 /// \brief Temporary files that should be removed when the ASTUnit is
87 /// destroyed.
88 SmallVector<llvm::sys::Path, 4> TemporaryFiles;
89
90 /// \brief Erase temporary files.
91 void CleanTemporaryFiles();
92
93 /// \brief Erase the preamble file.
94 void CleanPreambleFile();
95
96 /// \brief Erase temporary files and the preamble file.
97 void Cleanup();
98 };
99}
100
Ted Kremeneke055f8a2011-10-27 19:44:25 +0000101static llvm::sys::SmartMutex<false> &getOnDiskMutex() {
102 static llvm::sys::SmartMutex<false> M(/* recursive = */ true);
103 return M;
104}
105
Dmitri Gribenkoc4a77902012-11-15 14:28:07 +0000106static void cleanupOnDiskMapAtExit();
Ted Kremenek1872b312011-10-27 17:55:18 +0000107
108typedef llvm::DenseMap<const ASTUnit *, OnDiskData *> OnDiskDataMap;
109static OnDiskDataMap &getOnDiskDataMap() {
110 static OnDiskDataMap M;
111 static bool hasRegisteredAtExit = false;
112 if (!hasRegisteredAtExit) {
113 hasRegisteredAtExit = true;
114 atexit(cleanupOnDiskMapAtExit);
115 }
116 return M;
117}
118
Dmitri Gribenkoc4a77902012-11-15 14:28:07 +0000119static void cleanupOnDiskMapAtExit() {
Argyrios Kyrtzidis81788132012-07-03 16:30:52 +0000120 // Use the mutex because there can be an alive thread destroying an ASTUnit.
121 llvm::MutexGuard Guard(getOnDiskMutex());
Ted Kremenek1872b312011-10-27 17:55:18 +0000122 OnDiskDataMap &M = getOnDiskDataMap();
123 for (OnDiskDataMap::iterator I = M.begin(), E = M.end(); I != E; ++I) {
124 // We don't worry about freeing the memory associated with OnDiskDataMap.
125 // All we care about is erasing stale files.
126 I->second->Cleanup();
127 }
128}
129
130static OnDiskData &getOnDiskData(const ASTUnit *AU) {
Ted Kremeneke055f8a2011-10-27 19:44:25 +0000131 // We require the mutex since we are modifying the structure of the
132 // DenseMap.
133 llvm::MutexGuard Guard(getOnDiskMutex());
Ted Kremenek1872b312011-10-27 17:55:18 +0000134 OnDiskDataMap &M = getOnDiskDataMap();
135 OnDiskData *&D = M[AU];
136 if (!D)
137 D = new OnDiskData();
138 return *D;
139}
140
141static void erasePreambleFile(const ASTUnit *AU) {
142 getOnDiskData(AU).CleanPreambleFile();
143}
144
145static void removeOnDiskEntry(const ASTUnit *AU) {
Ted Kremeneke055f8a2011-10-27 19:44:25 +0000146 // We require the mutex since we are modifying the structure of the
147 // DenseMap.
148 llvm::MutexGuard Guard(getOnDiskMutex());
Ted Kremenek1872b312011-10-27 17:55:18 +0000149 OnDiskDataMap &M = getOnDiskDataMap();
150 OnDiskDataMap::iterator I = M.find(AU);
151 if (I != M.end()) {
152 I->second->Cleanup();
153 delete I->second;
154 M.erase(AU);
155 }
156}
157
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000158static void setPreambleFile(const ASTUnit *AU, StringRef preambleFile) {
Ted Kremenek1872b312011-10-27 17:55:18 +0000159 getOnDiskData(AU).PreambleFile = preambleFile;
160}
161
162static const std::string &getPreambleFile(const ASTUnit *AU) {
163 return getOnDiskData(AU).PreambleFile;
164}
165
166void OnDiskData::CleanTemporaryFiles() {
167 for (unsigned I = 0, N = TemporaryFiles.size(); I != N; ++I)
168 TemporaryFiles[I].eraseFromDisk();
169 TemporaryFiles.clear();
170}
171
172void OnDiskData::CleanPreambleFile() {
173 if (!PreambleFile.empty()) {
174 llvm::sys::Path(PreambleFile).eraseFromDisk();
175 PreambleFile.clear();
176 }
177}
178
179void OnDiskData::Cleanup() {
180 CleanTemporaryFiles();
181 CleanPreambleFile();
182}
183
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000184struct ASTUnit::ASTWriterData {
185 SmallString<128> Buffer;
186 llvm::BitstreamWriter Stream;
187 ASTWriter Writer;
188
189 ASTWriterData() : Stream(Buffer), Writer(Stream) { }
190};
191
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000192void ASTUnit::clearFileLevelDecls() {
193 for (FileDeclsTy::iterator
194 I = FileDecls.begin(), E = FileDecls.end(); I != E; ++I)
195 delete I->second;
196 FileDecls.clear();
197}
198
Ted Kremenek1872b312011-10-27 17:55:18 +0000199void ASTUnit::CleanTemporaryFiles() {
200 getOnDiskData(this).CleanTemporaryFiles();
201}
202
203void ASTUnit::addTemporaryFile(const llvm::sys::Path &TempFile) {
204 getOnDiskData(this).TemporaryFiles.push_back(TempFile);
Douglas Gregor213f18b2010-10-28 15:44:59 +0000205}
206
Douglas Gregoreababfb2010-08-04 05:53:38 +0000207/// \brief After failing to build a precompiled preamble (due to
208/// errors in the source that occurs in the preamble), the number of
209/// reparses during which we'll skip even trying to precompile the
210/// preamble.
211const unsigned DefaultPreambleRebuildInterval = 5;
212
Douglas Gregore3c60a72010-11-17 00:13:31 +0000213/// \brief Tracks the number of ASTUnit objects that are currently active.
214///
215/// Used for debugging purposes only.
Douglas Gregor1fd9e0d2010-12-07 00:05:48 +0000216static llvm::sys::cas_flag ActiveASTUnitObjects;
Douglas Gregore3c60a72010-11-17 00:13:31 +0000217
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000218ASTUnit::ASTUnit(bool _MainFileIsAST)
Argyrios Kyrtzidis62ba9f62011-11-01 17:14:15 +0000219 : Reader(0), OnlyLocalDecls(false), CaptureDiagnostics(false),
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +0000220 MainFileIsAST(_MainFileIsAST),
Douglas Gregor467dc882011-08-25 22:30:56 +0000221 TUKind(TU_Complete), WantTiming(getenv("LIBCLANG_TIMING")),
Argyrios Kyrtzidis15727dd2011-03-05 01:03:48 +0000222 OwnsRemappedFileBuffers(true),
Douglas Gregor213f18b2010-10-28 15:44:59 +0000223 NumStoredDiagnosticsFromDriver(0),
Douglas Gregor671947b2010-08-19 01:33:06 +0000224 PreambleRebuildCounter(0), SavedMainFileBuffer(0), PreambleBuffer(0),
Argyrios Kyrtzidis98704012011-11-29 18:18:33 +0000225 NumWarningsInPreamble(0),
Douglas Gregor727d93e2010-08-17 00:40:40 +0000226 ShouldCacheCodeCompletionResults(false),
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +0000227 IncludeBriefCommentsInCodeCompletion(false), UserFilesAreVolatile(false),
Douglas Gregor9b7db622011-02-16 18:16:54 +0000228 CompletionCacheTopLevelHashValue(0),
229 PreambleTopLevelHashValue(0),
230 CurrentTopLevelHashValue(0),
Douglas Gregor8b1540c2010-08-19 00:45:44 +0000231 UnsafeToFree(false) {
Douglas Gregore3c60a72010-11-17 00:13:31 +0000232 if (getenv("LIBCLANG_OBJTRACKING")) {
Douglas Gregor1fd9e0d2010-12-07 00:05:48 +0000233 llvm::sys::AtomicIncrement(&ActiveASTUnitObjects);
Douglas Gregore3c60a72010-11-17 00:13:31 +0000234 fprintf(stderr, "+++ %d translation units\n", ActiveASTUnitObjects);
235 }
Douglas Gregor385103b2010-07-30 20:58:08 +0000236}
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000237
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000238ASTUnit::~ASTUnit() {
Douglas Gregora4a90ca2013-05-03 22:58:43 +0000239 // If we loaded from an AST file, balance out the BeginSourceFile call.
240 if (MainFileIsAST && getDiagnostics().getClient()) {
241 getDiagnostics().getClient()->EndSourceFile();
242 }
243
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000244 clearFileLevelDecls();
245
Ted Kremenek1872b312011-10-27 17:55:18 +0000246 // Clean up the temporary files and the preamble file.
247 removeOnDiskEntry(this);
248
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000249 // Free the buffers associated with remapped files. We are required to
250 // perform this operation here because we explicitly request that the
251 // compiler instance *not* free these buffers for each invocation of the
252 // parser.
Ted Kremenek4f327862011-03-21 18:40:17 +0000253 if (Invocation.getPtr() && OwnsRemappedFileBuffers) {
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000254 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
255 for (PreprocessorOptions::remapped_file_buffer_iterator
256 FB = PPOpts.remapped_file_buffer_begin(),
257 FBEnd = PPOpts.remapped_file_buffer_end();
258 FB != FBEnd;
259 ++FB)
260 delete FB->second;
261 }
Douglas Gregor28233422010-07-27 14:52:07 +0000262
263 delete SavedMainFileBuffer;
Douglas Gregor671947b2010-08-19 01:33:06 +0000264 delete PreambleBuffer;
265
Douglas Gregor213f18b2010-10-28 15:44:59 +0000266 ClearCachedCompletionResults();
Douglas Gregore3c60a72010-11-17 00:13:31 +0000267
268 if (getenv("LIBCLANG_OBJTRACKING")) {
Douglas Gregor1fd9e0d2010-12-07 00:05:48 +0000269 llvm::sys::AtomicDecrement(&ActiveASTUnitObjects);
Douglas Gregore3c60a72010-11-17 00:13:31 +0000270 fprintf(stderr, "--- %d translation units\n", ActiveASTUnitObjects);
271 }
Douglas Gregorabc563f2010-07-19 21:46:24 +0000272}
273
Argyrios Kyrtzidis7fe90f32012-01-17 18:48:07 +0000274void ASTUnit::setPreprocessor(Preprocessor *pp) { PP = pp; }
275
Douglas Gregor8071e422010-08-15 06:18:01 +0000276/// \brief Determine the set of code-completion contexts in which this
277/// declaration should be shown.
Dmitri Gribenko89cf4252013-01-23 17:21:11 +0000278static unsigned getDeclShowContexts(const NamedDecl *ND,
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000279 const LangOptions &LangOpts,
280 bool &IsNestedNameSpecifier) {
281 IsNestedNameSpecifier = false;
282
Douglas Gregor8071e422010-08-15 06:18:01 +0000283 if (isa<UsingShadowDecl>(ND))
284 ND = dyn_cast<NamedDecl>(ND->getUnderlyingDecl());
285 if (!ND)
286 return 0;
287
Richard Smith026b3582012-08-14 03:13:00 +0000288 uint64_t Contexts = 0;
Douglas Gregor8071e422010-08-15 06:18:01 +0000289 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND) ||
290 isa<ClassTemplateDecl>(ND) || isa<TemplateTemplateParmDecl>(ND)) {
291 // Types can appear in these contexts.
292 if (LangOpts.CPlusPlus || !isa<TagDecl>(ND))
Richard Smith026b3582012-08-14 03:13:00 +0000293 Contexts |= (1LL << CodeCompletionContext::CCC_TopLevel)
294 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
295 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
296 | (1LL << CodeCompletionContext::CCC_Statement)
297 | (1LL << CodeCompletionContext::CCC_Type)
298 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression);
Douglas Gregor8071e422010-08-15 06:18:01 +0000299
300 // In C++, types can appear in expressions contexts (for functional casts).
301 if (LangOpts.CPlusPlus)
Richard Smith026b3582012-08-14 03:13:00 +0000302 Contexts |= (1LL << CodeCompletionContext::CCC_Expression);
Douglas Gregor8071e422010-08-15 06:18:01 +0000303
304 // In Objective-C, message sends can send interfaces. In Objective-C++,
305 // all types are available due to functional casts.
306 if (LangOpts.CPlusPlus || isa<ObjCInterfaceDecl>(ND))
Richard Smith026b3582012-08-14 03:13:00 +0000307 Contexts |= (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver);
Douglas Gregor3da626b2011-07-07 16:03:39 +0000308
309 // In Objective-C, you can only be a subclass of another Objective-C class
310 if (isa<ObjCInterfaceDecl>(ND))
Richard Smith026b3582012-08-14 03:13:00 +0000311 Contexts |= (1LL << CodeCompletionContext::CCC_ObjCInterfaceName);
Douglas Gregor8071e422010-08-15 06:18:01 +0000312
313 // Deal with tag names.
314 if (isa<EnumDecl>(ND)) {
Richard Smith026b3582012-08-14 03:13:00 +0000315 Contexts |= (1LL << CodeCompletionContext::CCC_EnumTag);
Douglas Gregor8071e422010-08-15 06:18:01 +0000316
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000317 // Part of the nested-name-specifier in C++0x.
Richard Smith80ad52f2013-01-02 11:42:31 +0000318 if (LangOpts.CPlusPlus11)
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000319 IsNestedNameSpecifier = true;
Dmitri Gribenko89cf4252013-01-23 17:21:11 +0000320 } else if (const RecordDecl *Record = dyn_cast<RecordDecl>(ND)) {
Douglas Gregor8071e422010-08-15 06:18:01 +0000321 if (Record->isUnion())
Richard Smith026b3582012-08-14 03:13:00 +0000322 Contexts |= (1LL << CodeCompletionContext::CCC_UnionTag);
Douglas Gregor8071e422010-08-15 06:18:01 +0000323 else
Richard Smith026b3582012-08-14 03:13:00 +0000324 Contexts |= (1LL << CodeCompletionContext::CCC_ClassOrStructTag);
Douglas Gregor8071e422010-08-15 06:18:01 +0000325
Douglas Gregor8071e422010-08-15 06:18:01 +0000326 if (LangOpts.CPlusPlus)
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000327 IsNestedNameSpecifier = true;
Douglas Gregor52779fb2010-09-23 23:01:17 +0000328 } else if (isa<ClassTemplateDecl>(ND))
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000329 IsNestedNameSpecifier = true;
Douglas Gregor8071e422010-08-15 06:18:01 +0000330 } else if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
331 // Values can appear in these contexts.
Richard Smith026b3582012-08-14 03:13:00 +0000332 Contexts = (1LL << CodeCompletionContext::CCC_Statement)
333 | (1LL << CodeCompletionContext::CCC_Expression)
334 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
335 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver);
Douglas Gregor8071e422010-08-15 06:18:01 +0000336 } else if (isa<ObjCProtocolDecl>(ND)) {
Richard Smith026b3582012-08-14 03:13:00 +0000337 Contexts = (1LL << CodeCompletionContext::CCC_ObjCProtocolName);
Douglas Gregor3da626b2011-07-07 16:03:39 +0000338 } else if (isa<ObjCCategoryDecl>(ND)) {
Richard Smith026b3582012-08-14 03:13:00 +0000339 Contexts = (1LL << CodeCompletionContext::CCC_ObjCCategoryName);
Douglas Gregor8071e422010-08-15 06:18:01 +0000340 } else if (isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) {
Richard Smith026b3582012-08-14 03:13:00 +0000341 Contexts = (1LL << CodeCompletionContext::CCC_Namespace);
Douglas Gregor8071e422010-08-15 06:18:01 +0000342
343 // Part of the nested-name-specifier.
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000344 IsNestedNameSpecifier = true;
Douglas Gregor8071e422010-08-15 06:18:01 +0000345 }
346
347 return Contexts;
348}
349
Douglas Gregor87c08a52010-08-13 22:48:40 +0000350void ASTUnit::CacheCodeCompletionResults() {
351 if (!TheSema)
352 return;
353
Douglas Gregor213f18b2010-10-28 15:44:59 +0000354 SimpleTimer Timer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +0000355 Timer.setOutput("Cache global code completions for " + getMainFileName());
Douglas Gregor87c08a52010-08-13 22:48:40 +0000356
357 // Clear out the previous results.
358 ClearCachedCompletionResults();
359
360 // Gather the set of global code completions.
John McCall0a2c5e22010-08-25 06:19:51 +0000361 typedef CodeCompletionResult Result;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000362 SmallVector<Result, 8> Results;
Douglas Gregor48601b32011-02-16 19:08:06 +0000363 CachedCompletionAllocator = new GlobalCodeCompletionAllocator;
Argyrios Kyrtzidis7fdc8fd2012-11-16 03:34:57 +0000364 CodeCompletionTUInfo CCTUInfo(CachedCompletionAllocator);
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +0000365 TheSema->GatherGlobalCodeCompletions(*CachedCompletionAllocator,
Argyrios Kyrtzidis7fdc8fd2012-11-16 03:34:57 +0000366 CCTUInfo, Results);
Douglas Gregor87c08a52010-08-13 22:48:40 +0000367
368 // Translate global code completions into cached completions.
Douglas Gregorf5586f62010-08-16 18:08:11 +0000369 llvm::DenseMap<CanQualType, unsigned> CompletionTypes;
370
Douglas Gregor87c08a52010-08-13 22:48:40 +0000371 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
372 switch (Results[I].Kind) {
Douglas Gregor8071e422010-08-15 06:18:01 +0000373 case Result::RK_Declaration: {
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000374 bool IsNestedNameSpecifier = false;
Douglas Gregor8071e422010-08-15 06:18:01 +0000375 CachedCodeCompletionResult CachedResult;
Douglas Gregor218937c2011-02-01 19:23:04 +0000376 CachedResult.Completion = Results[I].CreateCodeCompletionString(*TheSema,
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +0000377 *CachedCompletionAllocator,
Argyrios Kyrtzidis7fdc8fd2012-11-16 03:34:57 +0000378 CCTUInfo,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +0000379 IncludeBriefCommentsInCodeCompletion);
Douglas Gregor8071e422010-08-15 06:18:01 +0000380 CachedResult.ShowInContexts = getDeclShowContexts(Results[I].Declaration,
David Blaikie4e4d0842012-03-11 07:00:24 +0000381 Ctx->getLangOpts(),
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000382 IsNestedNameSpecifier);
Douglas Gregor8071e422010-08-15 06:18:01 +0000383 CachedResult.Priority = Results[I].Priority;
384 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregor58ddb602010-08-23 23:00:57 +0000385 CachedResult.Availability = Results[I].Availability;
Douglas Gregorc4421e92010-08-16 16:46:30 +0000386
Douglas Gregorf5586f62010-08-16 18:08:11 +0000387 // Keep track of the type of this completion in an ASTContext-agnostic
388 // way.
Douglas Gregorc4421e92010-08-16 16:46:30 +0000389 QualType UsageType = getDeclUsageType(*Ctx, Results[I].Declaration);
Douglas Gregorf5586f62010-08-16 18:08:11 +0000390 if (UsageType.isNull()) {
Douglas Gregorc4421e92010-08-16 16:46:30 +0000391 CachedResult.TypeClass = STC_Void;
Douglas Gregorf5586f62010-08-16 18:08:11 +0000392 CachedResult.Type = 0;
393 } else {
394 CanQualType CanUsageType
395 = Ctx->getCanonicalType(UsageType.getUnqualifiedType());
396 CachedResult.TypeClass = getSimplifiedTypeClass(CanUsageType);
397
398 // Determine whether we have already seen this type. If so, we save
399 // ourselves the work of formatting the type string by using the
400 // temporary, CanQualType-based hash table to find the associated value.
401 unsigned &TypeValue = CompletionTypes[CanUsageType];
402 if (TypeValue == 0) {
403 TypeValue = CompletionTypes.size();
404 CachedCompletionTypes[QualType(CanUsageType).getAsString()]
405 = TypeValue;
406 }
407
408 CachedResult.Type = TypeValue;
Douglas Gregorc4421e92010-08-16 16:46:30 +0000409 }
Douglas Gregorf5586f62010-08-16 18:08:11 +0000410
Douglas Gregor8071e422010-08-15 06:18:01 +0000411 CachedCompletionResults.push_back(CachedResult);
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000412
413 /// Handle nested-name-specifiers in C++.
David Blaikie4e4d0842012-03-11 07:00:24 +0000414 if (TheSema->Context.getLangOpts().CPlusPlus &&
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000415 IsNestedNameSpecifier && !Results[I].StartsNestedNameSpecifier) {
416 // The contexts in which a nested-name-specifier can appear in C++.
Richard Smith026b3582012-08-14 03:13:00 +0000417 uint64_t NNSContexts
418 = (1LL << CodeCompletionContext::CCC_TopLevel)
419 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
420 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
421 | (1LL << CodeCompletionContext::CCC_Statement)
422 | (1LL << CodeCompletionContext::CCC_Expression)
423 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
424 | (1LL << CodeCompletionContext::CCC_EnumTag)
425 | (1LL << CodeCompletionContext::CCC_UnionTag)
426 | (1LL << CodeCompletionContext::CCC_ClassOrStructTag)
427 | (1LL << CodeCompletionContext::CCC_Type)
428 | (1LL << CodeCompletionContext::CCC_PotentiallyQualifiedName)
429 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression);
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000430
431 if (isa<NamespaceDecl>(Results[I].Declaration) ||
432 isa<NamespaceAliasDecl>(Results[I].Declaration))
Richard Smith026b3582012-08-14 03:13:00 +0000433 NNSContexts |= (1LL << CodeCompletionContext::CCC_Namespace);
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000434
435 if (unsigned RemainingContexts
436 = NNSContexts & ~CachedResult.ShowInContexts) {
437 // If there any contexts where this completion can be a
438 // nested-name-specifier but isn't already an option, create a
439 // nested-name-specifier completion.
440 Results[I].StartsNestedNameSpecifier = true;
Douglas Gregor218937c2011-02-01 19:23:04 +0000441 CachedResult.Completion
442 = Results[I].CreateCodeCompletionString(*TheSema,
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +0000443 *CachedCompletionAllocator,
Argyrios Kyrtzidis7fdc8fd2012-11-16 03:34:57 +0000444 CCTUInfo,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +0000445 IncludeBriefCommentsInCodeCompletion);
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000446 CachedResult.ShowInContexts = RemainingContexts;
447 CachedResult.Priority = CCP_NestedNameSpecifier;
448 CachedResult.TypeClass = STC_Void;
449 CachedResult.Type = 0;
450 CachedCompletionResults.push_back(CachedResult);
451 }
452 }
Douglas Gregor87c08a52010-08-13 22:48:40 +0000453 break;
Douglas Gregor8071e422010-08-15 06:18:01 +0000454 }
455
Douglas Gregor87c08a52010-08-13 22:48:40 +0000456 case Result::RK_Keyword:
457 case Result::RK_Pattern:
458 // Ignore keywords and patterns; we don't care, since they are so
459 // easily regenerated.
460 break;
461
462 case Result::RK_Macro: {
463 CachedCodeCompletionResult CachedResult;
Douglas Gregor218937c2011-02-01 19:23:04 +0000464 CachedResult.Completion
465 = Results[I].CreateCodeCompletionString(*TheSema,
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +0000466 *CachedCompletionAllocator,
Argyrios Kyrtzidis7fdc8fd2012-11-16 03:34:57 +0000467 CCTUInfo,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +0000468 IncludeBriefCommentsInCodeCompletion);
Douglas Gregor87c08a52010-08-13 22:48:40 +0000469 CachedResult.ShowInContexts
Richard Smith026b3582012-08-14 03:13:00 +0000470 = (1LL << CodeCompletionContext::CCC_TopLevel)
471 | (1LL << CodeCompletionContext::CCC_ObjCInterface)
472 | (1LL << CodeCompletionContext::CCC_ObjCImplementation)
473 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
474 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
475 | (1LL << CodeCompletionContext::CCC_Statement)
476 | (1LL << CodeCompletionContext::CCC_Expression)
477 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
478 | (1LL << CodeCompletionContext::CCC_MacroNameUse)
479 | (1LL << CodeCompletionContext::CCC_PreprocessorExpression)
480 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
481 | (1LL << CodeCompletionContext::CCC_OtherWithMacros);
Douglas Gregor2ccccb32010-08-23 18:23:48 +0000482
Douglas Gregor87c08a52010-08-13 22:48:40 +0000483 CachedResult.Priority = Results[I].Priority;
484 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregor58ddb602010-08-23 23:00:57 +0000485 CachedResult.Availability = Results[I].Availability;
Douglas Gregor1827e102010-08-16 16:18:59 +0000486 CachedResult.TypeClass = STC_Void;
Douglas Gregorf5586f62010-08-16 18:08:11 +0000487 CachedResult.Type = 0;
Douglas Gregor87c08a52010-08-13 22:48:40 +0000488 CachedCompletionResults.push_back(CachedResult);
489 break;
490 }
491 }
Douglas Gregor87c08a52010-08-13 22:48:40 +0000492 }
Douglas Gregor9b7db622011-02-16 18:16:54 +0000493
494 // Save the current top-level hash value.
495 CompletionCacheTopLevelHashValue = CurrentTopLevelHashValue;
Douglas Gregor87c08a52010-08-13 22:48:40 +0000496}
497
498void ASTUnit::ClearCachedCompletionResults() {
Douglas Gregor87c08a52010-08-13 22:48:40 +0000499 CachedCompletionResults.clear();
Douglas Gregorf5586f62010-08-16 18:08:11 +0000500 CachedCompletionTypes.clear();
Douglas Gregor48601b32011-02-16 19:08:06 +0000501 CachedCompletionAllocator = 0;
Douglas Gregor87c08a52010-08-13 22:48:40 +0000502}
503
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000504namespace {
505
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000506/// \brief Gathers information from ASTReader that will be used to initialize
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000507/// a Preprocessor.
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000508class ASTInfoCollector : public ASTReaderListener {
Douglas Gregor998b3d32011-09-01 23:39:15 +0000509 Preprocessor &PP;
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000510 ASTContext &Context;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000511 LangOptions &LangOpt;
Douglas Gregor57016dd2012-10-16 23:40:58 +0000512 IntrusiveRefCntPtr<TargetOptions> &TargetOpts;
Dylan Noblesmithc93dc782012-02-20 14:00:23 +0000513 IntrusiveRefCntPtr<TargetInfo> &Target;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000514 unsigned &Counter;
Mike Stump1eb44332009-09-09 15:08:12 +0000515
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000516 bool InitializedLanguage;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000517public:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000518 ASTInfoCollector(Preprocessor &PP, ASTContext &Context, LangOptions &LangOpt,
Douglas Gregor57016dd2012-10-16 23:40:58 +0000519 IntrusiveRefCntPtr<TargetOptions> &TargetOpts,
Dylan Noblesmithc93dc782012-02-20 14:00:23 +0000520 IntrusiveRefCntPtr<TargetInfo> &Target,
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000521 unsigned &Counter)
Argyrios Kyrtzidisf9ba8512013-05-08 23:46:55 +0000522 : PP(PP), Context(Context), LangOpt(LangOpt),
Douglas Gregor9a022bb2012-10-15 16:45:32 +0000523 TargetOpts(TargetOpts), Target(Target),
Argyrios Kyrtzidisf9ba8512013-05-08 23:46:55 +0000524 Counter(Counter),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000525 InitializedLanguage(false) {}
Mike Stump1eb44332009-09-09 15:08:12 +0000526
Douglas Gregor27ffa6c2012-10-23 06:18:24 +0000527 virtual bool ReadLanguageOptions(const LangOptions &LangOpts,
Douglas Gregor38295be2012-10-22 23:51:00 +0000528 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 LangOpt = LangOpts;
533 InitializedLanguage = true;
534
535 updated();
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000536 return false;
537 }
Mike Stump1eb44332009-09-09 15:08:12 +0000538
Douglas Gregor27ffa6c2012-10-23 06:18:24 +0000539 virtual bool ReadTargetOptions(const TargetOptions &TargetOpts,
Douglas Gregor38295be2012-10-22 23:51:00 +0000540 bool Complain) {
Douglas Gregor998b3d32011-09-01 23:39:15 +0000541 // If we've already initialized the target, don't do it again.
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000542 if (Target)
Douglas Gregor998b3d32011-09-01 23:39:15 +0000543 return false;
544
Douglas Gregor57016dd2012-10-16 23:40:58 +0000545 this->TargetOpts = new TargetOptions(TargetOpts);
Douglas Gregor49a87542012-11-16 04:24:59 +0000546 Target = TargetInfo::CreateTargetInfo(PP.getDiagnostics(),
547 &*this->TargetOpts);
Argyrios Kyrtzidis7f186332012-09-14 20:24:53 +0000548
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000549 updated();
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000550 return false;
551 }
Mike Stump1eb44332009-09-09 15:08:12 +0000552
Argyrios Kyrtzidis62288ed2012-10-10 02:12:47 +0000553 virtual void ReadCounter(const serialization::ModuleFile &M, unsigned Value) {
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000554 Counter = Value;
555 }
Argyrios Kyrtzidis7f186332012-09-14 20:24:53 +0000556
557private:
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000558 void updated() {
559 if (!Target || !InitializedLanguage)
560 return;
561
562 // Inform the target of the language options.
563 //
564 // FIXME: We shouldn't need to do this, the target should be immutable once
565 // created. This complexity should be lifted elsewhere.
566 Target->setForcedLangOptions(LangOpt);
567
568 // Initialize the preprocessor.
569 PP.Initialize(*Target);
570
571 // Initialize the ASTContext
572 Context.InitBuiltinTypes(*Target);
Dmitri Gribenko6ebf0912013-02-22 14:21:27 +0000573
574 // We didn't have access to the comment options when the ASTContext was
575 // constructed, so register them now.
576 Context.getCommentCommandTraits().registerCommentOptions(
577 LangOpt.CommentOpts);
Argyrios Kyrtzidis7f186332012-09-14 20:24:53 +0000578 }
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000579};
580
Douglas Gregora4a90ca2013-05-03 22:58:43 +0000581 /// \brief Diagnostic consumer that saves each diagnostic it is given.
David Blaikie26e7a902011-09-26 00:01:39 +0000582class StoredDiagnosticConsumer : public DiagnosticConsumer {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000583 SmallVectorImpl<StoredDiagnostic> &StoredDiags;
Douglas Gregora4a90ca2013-05-03 22:58:43 +0000584 SourceManager *SourceMgr;
585
Douglas Gregora88084b2010-02-18 18:08:43 +0000586public:
David Blaikie26e7a902011-09-26 00:01:39 +0000587 explicit StoredDiagnosticConsumer(
Chris Lattner5f9e2722011-07-23 10:55:15 +0000588 SmallVectorImpl<StoredDiagnostic> &StoredDiags)
Douglas Gregora4a90ca2013-05-03 22:58:43 +0000589 : StoredDiags(StoredDiags), SourceMgr(0) { }
590
591 virtual void BeginSourceFile(const LangOptions &LangOpts,
592 const Preprocessor *PP = 0) {
593 if (PP)
594 SourceMgr = &PP->getSourceManager();
595 }
596
David Blaikied6471f72011-09-25 23:23:43 +0000597 virtual void HandleDiagnostic(DiagnosticsEngine::Level Level,
David Blaikie40847cf2011-09-26 01:18:08 +0000598 const Diagnostic &Info);
Douglas Gregora88084b2010-02-18 18:08:43 +0000599};
600
601/// \brief RAII object that optionally captures diagnostics, if
602/// there is no diagnostic client to capture them already.
603class CaptureDroppedDiagnostics {
David Blaikied6471f72011-09-25 23:23:43 +0000604 DiagnosticsEngine &Diags;
David Blaikie26e7a902011-09-26 00:01:39 +0000605 StoredDiagnosticConsumer Client;
David Blaikie78ad0b92011-09-25 23:39:51 +0000606 DiagnosticConsumer *PreviousClient;
Douglas Gregora88084b2010-02-18 18:08:43 +0000607
608public:
David Blaikied6471f72011-09-25 23:23:43 +0000609 CaptureDroppedDiagnostics(bool RequestCapture, DiagnosticsEngine &Diags,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000610 SmallVectorImpl<StoredDiagnostic> &StoredDiags)
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000611 : Diags(Diags), Client(StoredDiags), PreviousClient(0)
Douglas Gregora88084b2010-02-18 18:08:43 +0000612 {
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000613 if (RequestCapture || Diags.getClient() == 0) {
614 PreviousClient = Diags.takeClient();
Douglas Gregora88084b2010-02-18 18:08:43 +0000615 Diags.setClient(&Client);
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000616 }
Douglas Gregora88084b2010-02-18 18:08:43 +0000617 }
618
619 ~CaptureDroppedDiagnostics() {
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000620 if (Diags.getClient() == &Client) {
621 Diags.takeClient();
622 Diags.setClient(PreviousClient);
623 }
Douglas Gregora88084b2010-02-18 18:08:43 +0000624 }
625};
626
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000627} // anonymous namespace
628
David Blaikie26e7a902011-09-26 00:01:39 +0000629void StoredDiagnosticConsumer::HandleDiagnostic(DiagnosticsEngine::Level Level,
David Blaikie40847cf2011-09-26 01:18:08 +0000630 const Diagnostic &Info) {
Argyrios Kyrtzidisf2224d82010-11-18 20:06:46 +0000631 // Default implementation (Warnings/errors count).
David Blaikie78ad0b92011-09-25 23:39:51 +0000632 DiagnosticConsumer::HandleDiagnostic(Level, Info);
Argyrios Kyrtzidisf2224d82010-11-18 20:06:46 +0000633
Douglas Gregora4a90ca2013-05-03 22:58:43 +0000634 // Only record the diagnostic if it's part of the source manager we know
635 // about. This effectively drops diagnostics from modules we're building.
636 // FIXME: In the long run, ee don't want to drop source managers from modules.
637 if (!Info.hasSourceManager() || &Info.getSourceManager() == SourceMgr)
638 StoredDiags.push_back(StoredDiagnostic(Level, Info));
Douglas Gregora88084b2010-02-18 18:08:43 +0000639}
640
Argyrios Kyrtzidis7eca8d22013-05-10 01:28:51 +0000641ASTMutationListener *ASTUnit::getASTMutationListener() {
642 if (WriterData)
643 return &WriterData->Writer;
644 return 0;
645}
646
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000647ASTDeserializationListener *ASTUnit::getDeserializationListener() {
648 if (WriterData)
649 return &WriterData->Writer;
650 return 0;
651}
652
Chris Lattner5f9e2722011-07-23 10:55:15 +0000653llvm::MemoryBuffer *ASTUnit::getBufferForFile(StringRef Filename,
Chris Lattner75dfb652010-11-23 09:19:42 +0000654 std::string *ErrorStr) {
Chris Lattner39b49bc2010-11-23 08:35:12 +0000655 assert(FileMgr);
Chris Lattner75dfb652010-11-23 09:19:42 +0000656 return FileMgr->getBufferForFile(Filename, ErrorStr);
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +0000657}
658
Douglas Gregore47be3e2010-11-11 00:39:14 +0000659/// \brief Configure the diagnostics object for use with ASTUnit.
Dylan Noblesmithc93dc782012-02-20 14:00:23 +0000660void ASTUnit::ConfigureDiags(IntrusiveRefCntPtr<DiagnosticsEngine> &Diags,
Douglas Gregor0b53cf82011-01-19 01:02:47 +0000661 const char **ArgBegin, const char **ArgEnd,
Douglas Gregore47be3e2010-11-11 00:39:14 +0000662 ASTUnit &AST, bool CaptureDiagnostics) {
663 if (!Diags.getPtr()) {
664 // No diagnostics engine was provided, so create our own diagnostics object
665 // with the default options.
David Blaikie78ad0b92011-09-25 23:39:51 +0000666 DiagnosticConsumer *Client = 0;
Douglas Gregore47be3e2010-11-11 00:39:14 +0000667 if (CaptureDiagnostics)
David Blaikie26e7a902011-09-26 00:01:39 +0000668 Client = new StoredDiagnosticConsumer(AST.StoredDiagnostics);
Douglas Gregor02c23eb2012-10-23 22:26:28 +0000669 Diags = CompilerInstance::createDiagnostics(new DiagnosticOptions(),
Sean Silvad47afb92013-01-20 01:58:28 +0000670 Client,
Douglas Gregorcc2b6532013-05-03 23:07:45 +0000671 /*ShouldOwnClient=*/true);
Douglas Gregore47be3e2010-11-11 00:39:14 +0000672 } else if (CaptureDiagnostics) {
David Blaikie26e7a902011-09-26 00:01:39 +0000673 Diags->setClient(new StoredDiagnosticConsumer(AST.StoredDiagnostics));
Douglas Gregore47be3e2010-11-11 00:39:14 +0000674 }
675}
676
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000677ASTUnit *ASTUnit::LoadFromASTFile(const std::string &Filename,
Dylan Noblesmithc93dc782012-02-20 14:00:23 +0000678 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +0000679 const FileSystemOptions &FileSystemOpts,
Ted Kremenek5cf48762009-10-17 00:34:24 +0000680 bool OnlyLocalDecls,
Douglas Gregor4db64a42010-01-23 00:14:00 +0000681 RemappedFile *RemappedFiles,
Douglas Gregora88084b2010-02-18 18:08:43 +0000682 unsigned NumRemappedFiles,
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +0000683 bool CaptureDiagnostics,
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +0000684 bool AllowPCHWithCompilerErrors,
685 bool UserFilesAreVolatile) {
Dylan Noblesmith6f42b622012-02-05 02:12:40 +0000686 OwningPtr<ASTUnit> AST(new ASTUnit(true));
Ted Kremenekb547eeb2011-03-18 02:06:56 +0000687
688 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +0000689 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
690 ASTUnitCleanup(AST.get());
David Blaikied6471f72011-09-25 23:23:43 +0000691 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
692 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Ted Kremenek25a11e12011-03-22 01:15:24 +0000693 DiagCleanup(Diags.getPtr());
Ted Kremenekb547eeb2011-03-18 02:06:56 +0000694
Douglas Gregor0b53cf82011-01-19 01:02:47 +0000695 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
Douglas Gregorabc563f2010-07-19 21:46:24 +0000696
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000697 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregore47be3e2010-11-11 00:39:14 +0000698 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor28019772010-04-05 23:52:57 +0000699 AST->Diagnostics = Diags;
Ted Kremenek4f327862011-03-21 18:40:17 +0000700 AST->FileMgr = new FileManager(FileSystemOpts);
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +0000701 AST->UserFilesAreVolatile = UserFilesAreVolatile;
Ted Kremenek4f327862011-03-21 18:40:17 +0000702 AST->SourceMgr = new SourceManager(AST->getDiagnostics(),
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +0000703 AST->getFileManager(),
704 UserFilesAreVolatile);
Douglas Gregorc042edd2012-10-24 16:19:39 +0000705 AST->HSOpts = new HeaderSearchOptions();
706
707 AST->HeaderInfo.reset(new HeaderSearch(AST->HSOpts,
708 AST->getFileManager(),
Douglas Gregor51f564f2011-12-31 04:05:44 +0000709 AST->getDiagnostics(),
Douglas Gregordc58aa72012-01-30 06:01:29 +0000710 AST->ASTFileLangOpts,
711 /*Target=*/0));
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000712
Douglas Gregor4db64a42010-01-23 00:14:00 +0000713 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000714 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
715 if (const llvm::MemoryBuffer *
716 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
717 // Create the file entry for the file that we're mapping from.
718 const FileEntry *FromFile
719 = AST->getFileManager().getVirtualFile(RemappedFiles[I].first,
720 memBuf->getBufferSize(),
721 0);
722 if (!FromFile) {
723 AST->getDiagnostics().Report(diag::err_fe_remap_missing_from_file)
724 << RemappedFiles[I].first;
725 delete memBuf;
726 continue;
727 }
728
729 // Override the contents of the "from" file with the contents of
730 // the "to" file.
731 AST->getSourceManager().overrideFileContents(FromFile, memBuf);
732
733 } else {
734 const char *fname = fileOrBuf.get<const char *>();
735 const FileEntry *ToFile = AST->FileMgr->getFile(fname);
736 if (!ToFile) {
737 AST->getDiagnostics().Report(diag::err_fe_remap_missing_to_file)
738 << RemappedFiles[I].first << fname;
739 continue;
740 }
741
742 // Create the file entry for the file that we're mapping from.
743 const FileEntry *FromFile
744 = AST->getFileManager().getVirtualFile(RemappedFiles[I].first,
745 ToFile->getSize(),
746 0);
747 if (!FromFile) {
748 AST->getDiagnostics().Report(diag::err_fe_remap_missing_from_file)
749 << RemappedFiles[I].first;
750 delete memBuf;
751 continue;
752 }
753
754 // Override the contents of the "from" file with the contents of
755 // the "to" file.
756 AST->getSourceManager().overrideFileContents(FromFile, ToFile);
Douglas Gregor4db64a42010-01-23 00:14:00 +0000757 }
Douglas Gregor4db64a42010-01-23 00:14:00 +0000758 }
759
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000760 // Gather Info for preprocessor construction later on.
Mike Stump1eb44332009-09-09 15:08:12 +0000761
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000762 HeaderSearch &HeaderInfo = *AST->HeaderInfo.get();
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000763 unsigned Counter;
764
Dylan Noblesmith6f42b622012-02-05 02:12:40 +0000765 OwningPtr<ASTReader> Reader;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000766
Douglas Gregor36a16492012-10-24 17:46:57 +0000767 AST->PP = new Preprocessor(new PreprocessorOptions(),
768 AST->getDiagnostics(), AST->ASTFileLangOpts,
Douglas Gregor998b3d32011-09-01 23:39:15 +0000769 /*Target=*/0, AST->getSourceManager(), HeaderInfo,
770 *AST,
771 /*IILookup=*/0,
772 /*OwnsHeaderSearch=*/false,
773 /*DelayInitialization=*/true);
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000774 Preprocessor &PP = *AST->PP;
775
776 AST->Ctx = new ASTContext(AST->ASTFileLangOpts,
777 AST->getSourceManager(),
778 /*Target=*/0,
779 PP.getIdentifierTable(),
780 PP.getSelectorTable(),
781 PP.getBuiltinInfo(),
782 /* size_reserve = */0,
783 /*DelayInitialization=*/true);
784 ASTContext &Context = *AST->Ctx;
Douglas Gregor998b3d32011-09-01 23:39:15 +0000785
Argyrios Kyrtzidis98e95bf2012-09-15 01:10:20 +0000786 bool disableValid = false;
787 if (::getenv("LIBCLANG_DISABLE_PCH_VALIDATION"))
788 disableValid = true;
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +0000789 Reader.reset(new ASTReader(PP, Context,
790 /*isysroot=*/"",
Argyrios Kyrtzidis98e95bf2012-09-15 01:10:20 +0000791 /*DisableValidation=*/disableValid,
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +0000792 AllowPCHWithCompilerErrors));
Ted Kremenek8c647de2011-05-04 23:27:12 +0000793
794 // Recover resources if we crash before exiting this method.
795 llvm::CrashRecoveryContextCleanupRegistrar<ASTReader>
796 ReaderCleanup(Reader.get());
797
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000798 Reader->setListener(new ASTInfoCollector(*AST->PP, Context,
Argyrios Kyrtzidisf9ba8512013-05-08 23:46:55 +0000799 AST->ASTFileLangOpts,
Douglas Gregor9a022bb2012-10-15 16:45:32 +0000800 AST->TargetOpts, AST->Target,
Douglas Gregor43998902012-10-25 00:09:28 +0000801 Counter));
Daniel Dunbarcc318932009-09-03 05:59:35 +0000802
Douglas Gregor38295be2012-10-22 23:51:00 +0000803 switch (Reader->ReadAST(Filename, serialization::MK_MainFile,
Argyrios Kyrtzidis958bcaf2012-11-15 18:57:22 +0000804 SourceLocation(), ASTReader::ARR_None)) {
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000805 case ASTReader::Success:
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000806 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000807
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000808 case ASTReader::Failure:
Douglas Gregor677e15f2013-03-19 00:28:20 +0000809 case ASTReader::Missing:
Douglas Gregor4825fd72012-10-22 22:50:17 +0000810 case ASTReader::OutOfDate:
811 case ASTReader::VersionMismatch:
812 case ASTReader::ConfigurationMismatch:
813 case ASTReader::HadErrors:
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000814 AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000815 return NULL;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000816 }
Mike Stump1eb44332009-09-09 15:08:12 +0000817
Daniel Dunbar68d40e22009-12-02 08:44:16 +0000818 AST->OriginalSourceFile = Reader->getOriginalSourceFile();
819
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000820 PP.setCounterValue(Counter);
Mike Stump1eb44332009-09-09 15:08:12 +0000821
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000822 // Attach the AST reader to the AST context as an external AST
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000823 // source, so that declarations will be deserialized from the
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000824 // AST file as needed.
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000825 ASTReader *ReaderPtr = Reader.get();
Dylan Noblesmith6f42b622012-02-05 02:12:40 +0000826 OwningPtr<ExternalASTSource> Source(Reader.take());
Ted Kremenek8c647de2011-05-04 23:27:12 +0000827
828 // Unregister the cleanup for ASTReader. It will get cleaned up
829 // by the ASTUnit cleanup.
830 ReaderCleanup.unregister();
831
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000832 Context.setExternalSource(Source);
833
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000834 // Create an AST consumer, even though it isn't used.
835 AST->Consumer.reset(new ASTConsumer);
836
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000837 // Create a semantic analysis object and tell the AST reader about it.
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000838 AST->TheSema.reset(new Sema(PP, Context, *AST->Consumer));
839 AST->TheSema->Initialize();
840 ReaderPtr->InitializeSema(*AST->TheSema);
Argyrios Kyrtzidis62ba9f62011-11-01 17:14:15 +0000841 AST->Reader = ReaderPtr;
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000842
Douglas Gregora4a90ca2013-05-03 22:58:43 +0000843 // Tell the diagnostic client that we have started a source file.
844 AST->getDiagnostics().getClient()->BeginSourceFile(Context.getLangOpts(),&PP);
845
Mike Stump1eb44332009-09-09 15:08:12 +0000846 return AST.take();
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000847}
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000848
849namespace {
850
Douglas Gregor9b7db622011-02-16 18:16:54 +0000851/// \brief Preprocessor callback class that updates a hash value with the names
852/// of all macros that have been defined by the translation unit.
853class MacroDefinitionTrackerPPCallbacks : public PPCallbacks {
854 unsigned &Hash;
855
856public:
857 explicit MacroDefinitionTrackerPPCallbacks(unsigned &Hash) : Hash(Hash) { }
858
Argyrios Kyrtzidisc5159782013-02-24 00:05:14 +0000859 virtual void MacroDefined(const Token &MacroNameTok,
860 const MacroDirective *MD) {
Douglas Gregor9b7db622011-02-16 18:16:54 +0000861 Hash = llvm::HashString(MacroNameTok.getIdentifierInfo()->getName(), Hash);
862 }
863};
864
865/// \brief Add the given declaration to the hash of all top-level entities.
866void AddTopLevelDeclarationToHash(Decl *D, unsigned &Hash) {
867 if (!D)
868 return;
869
870 DeclContext *DC = D->getDeclContext();
871 if (!DC)
872 return;
873
874 if (!(DC->isTranslationUnit() || DC->getLookupParent()->isTranslationUnit()))
875 return;
876
877 if (NamedDecl *ND = dyn_cast<NamedDecl>(D)) {
878 if (ND->getIdentifier())
879 Hash = llvm::HashString(ND->getIdentifier()->getName(), Hash);
880 else if (DeclarationName Name = ND->getDeclName()) {
881 std::string NameStr = Name.getAsString();
882 Hash = llvm::HashString(NameStr, Hash);
883 }
884 return;
Douglas Gregorbd9482d2012-01-01 21:23:57 +0000885 }
Douglas Gregor9b7db622011-02-16 18:16:54 +0000886}
887
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000888class TopLevelDeclTrackerConsumer : public ASTConsumer {
889 ASTUnit &Unit;
Douglas Gregor9b7db622011-02-16 18:16:54 +0000890 unsigned &Hash;
891
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000892public:
Douglas Gregor9b7db622011-02-16 18:16:54 +0000893 TopLevelDeclTrackerConsumer(ASTUnit &_Unit, unsigned &Hash)
894 : Unit(_Unit), Hash(Hash) {
895 Hash = 0;
896 }
Douglas Gregor9b7db622011-02-16 18:16:54 +0000897
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000898 void handleTopLevelDecl(Decl *D) {
Argyrios Kyrtzidis35593a92011-11-16 02:35:10 +0000899 if (!D)
900 return;
901
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000902 // FIXME: Currently ObjC method declarations are incorrectly being
903 // reported as top-level declarations, even though their DeclContext
904 // is the containing ObjC @interface/@implementation. This is a
905 // fundamental problem in the parser right now.
906 if (isa<ObjCMethodDecl>(D))
907 return;
908
909 AddTopLevelDeclarationToHash(D, Hash);
910 Unit.addTopLevelDecl(D);
911
912 handleFileLevelDecl(D);
913 }
914
915 void handleFileLevelDecl(Decl *D) {
916 Unit.addFileLevelDecl(D);
917 if (NamespaceDecl *NSD = dyn_cast<NamespaceDecl>(D)) {
918 for (NamespaceDecl::decl_iterator
919 I = NSD->decls_begin(), E = NSD->decls_end(); I != E; ++I)
920 handleFileLevelDecl(*I);
Ted Kremenekda5a4282010-05-03 20:16:35 +0000921 }
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000922 }
Sebastian Redl27372b42010-08-11 18:52:41 +0000923
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000924 bool HandleTopLevelDecl(DeclGroupRef D) {
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000925 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it)
926 handleTopLevelDecl(*it);
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000927 return true;
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000928 }
929
Sebastian Redl27372b42010-08-11 18:52:41 +0000930 // We're not interested in "interesting" decls.
931 void HandleInterestingDecl(DeclGroupRef) {}
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000932
933 void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) {
934 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it)
935 handleTopLevelDecl(*it);
936 }
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000937
Argyrios Kyrtzidis7eca8d22013-05-10 01:28:51 +0000938 virtual ASTMutationListener *GetASTMutationListener() {
939 return Unit.getASTMutationListener();
940 }
941
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000942 virtual ASTDeserializationListener *GetASTDeserializationListener() {
943 return Unit.getDeserializationListener();
944 }
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000945};
946
947class TopLevelDeclTrackerAction : public ASTFrontendAction {
948public:
949 ASTUnit &Unit;
950
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000951 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000952 StringRef InFile) {
Douglas Gregor9b7db622011-02-16 18:16:54 +0000953 CI.getPreprocessor().addPPCallbacks(
954 new MacroDefinitionTrackerPPCallbacks(Unit.getCurrentTopLevelHashValue()));
955 return new TopLevelDeclTrackerConsumer(Unit,
956 Unit.getCurrentTopLevelHashValue());
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000957 }
958
959public:
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000960 TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {}
961
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000962 virtual bool hasCodeCompletionSupport() const { return false; }
Douglas Gregor467dc882011-08-25 22:30:56 +0000963 virtual TranslationUnitKind getTranslationUnitKind() {
964 return Unit.getTranslationUnitKind();
Douglas Gregordf95a132010-08-09 20:45:32 +0000965 }
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000966};
967
Argyrios Kyrtzidis92ddef12011-09-19 20:40:48 +0000968class PrecompilePreambleConsumer : public PCHGenerator {
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000969 ASTUnit &Unit;
Douglas Gregor9b7db622011-02-16 18:16:54 +0000970 unsigned &Hash;
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000971 std::vector<Decl *> TopLevelDecls;
Douglas Gregor89d99802010-11-30 06:16:57 +0000972
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000973public:
Douglas Gregor9293ba82011-08-25 22:35:51 +0000974 PrecompilePreambleConsumer(ASTUnit &Unit, const Preprocessor &PP,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000975 StringRef isysroot, raw_ostream *Out)
Douglas Gregora8cc6ce2011-11-30 04:39:39 +0000976 : PCHGenerator(PP, "", 0, isysroot, Out), Unit(Unit),
Douglas Gregor9b7db622011-02-16 18:16:54 +0000977 Hash(Unit.getCurrentTopLevelHashValue()) {
978 Hash = 0;
979 }
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000980
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000981 virtual bool HandleTopLevelDecl(DeclGroupRef D) {
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000982 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
983 Decl *D = *it;
984 // FIXME: Currently ObjC method declarations are incorrectly being
985 // reported as top-level declarations, even though their DeclContext
986 // is the containing ObjC @interface/@implementation. This is a
987 // fundamental problem in the parser right now.
988 if (isa<ObjCMethodDecl>(D))
989 continue;
Douglas Gregor9b7db622011-02-16 18:16:54 +0000990 AddTopLevelDeclarationToHash(D, Hash);
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000991 TopLevelDecls.push_back(D);
992 }
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000993 return true;
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000994 }
995
996 virtual void HandleTranslationUnit(ASTContext &Ctx) {
997 PCHGenerator::HandleTranslationUnit(Ctx);
998 if (!Unit.getDiagnostics().hasErrorOccurred()) {
999 // Translate the top-level declarations we captured during
1000 // parsing into declaration IDs in the precompiled
1001 // preamble. This will allow us to deserialize those top-level
1002 // declarations when requested.
1003 for (unsigned I = 0, N = TopLevelDecls.size(); I != N; ++I)
1004 Unit.addTopLevelDeclFromPreamble(
1005 getWriter().getDeclID(TopLevelDecls[I]));
Douglas Gregor1d715ac2010-08-03 08:14:03 +00001006 }
1007 }
1008};
1009
1010class PrecompilePreambleAction : public ASTFrontendAction {
1011 ASTUnit &Unit;
1012
1013public:
1014 explicit PrecompilePreambleAction(ASTUnit &Unit) : Unit(Unit) {}
1015
1016 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001017 StringRef InFile) {
Douglas Gregor1d715ac2010-08-03 08:14:03 +00001018 std::string Sysroot;
Argyrios Kyrtzidis8e3df4d2011-02-15 17:54:22 +00001019 std::string OutputFile;
Chris Lattner5f9e2722011-07-23 10:55:15 +00001020 raw_ostream *OS = 0;
Argyrios Kyrtzidis8e3df4d2011-02-15 17:54:22 +00001021 if (GeneratePCHAction::ComputeASTConsumerArguments(CI, InFile, Sysroot,
1022 OutputFile,
Douglas Gregor9293ba82011-08-25 22:35:51 +00001023 OS))
Douglas Gregor1d715ac2010-08-03 08:14:03 +00001024 return 0;
1025
Douglas Gregor832d6202011-07-22 16:35:34 +00001026 if (!CI.getFrontendOpts().RelocatablePCH)
1027 Sysroot.clear();
1028
Douglas Gregor9b7db622011-02-16 18:16:54 +00001029 CI.getPreprocessor().addPPCallbacks(
1030 new MacroDefinitionTrackerPPCallbacks(Unit.getCurrentTopLevelHashValue()));
Douglas Gregor9293ba82011-08-25 22:35:51 +00001031 return new PrecompilePreambleConsumer(Unit, CI.getPreprocessor(), Sysroot,
1032 OS);
Douglas Gregor1d715ac2010-08-03 08:14:03 +00001033 }
1034
1035 virtual bool hasCodeCompletionSupport() const { return false; }
1036 virtual bool hasASTFileSupport() const { return false; }
Douglas Gregor467dc882011-08-25 22:30:56 +00001037 virtual TranslationUnitKind getTranslationUnitKind() { return TU_Prefix; }
Douglas Gregor1d715ac2010-08-03 08:14:03 +00001038};
1039
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001040}
1041
Benjamin Kramerfe57db22013-05-05 12:39:28 +00001042static bool isNonDriverDiag(const StoredDiagnostic &StoredDiag) {
1043 return StoredDiag.getLocation().isValid();
1044}
1045
1046static void
1047checkAndRemoveNonDriverDiags(SmallVectorImpl<StoredDiagnostic> &StoredDiags) {
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00001048 // Get rid of stored diagnostics except the ones from the driver which do not
1049 // have a source location.
Benjamin Kramerfe57db22013-05-05 12:39:28 +00001050 StoredDiags.erase(
1051 std::remove_if(StoredDiags.begin(), StoredDiags.end(), isNonDriverDiag),
1052 StoredDiags.end());
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00001053}
1054
1055static void checkAndSanitizeDiags(SmallVectorImpl<StoredDiagnostic> &
1056 StoredDiagnostics,
1057 SourceManager &SM) {
1058 // The stored diagnostic has the old source manager in it; update
1059 // the locations to refer into the new source manager. Since we've
1060 // been careful to make sure that the source manager's state
1061 // before and after are identical, so that we can reuse the source
1062 // location itself.
1063 for (unsigned I = 0, N = StoredDiagnostics.size(); I < N; ++I) {
1064 if (StoredDiagnostics[I].getLocation().isValid()) {
1065 FullSourceLoc Loc(StoredDiagnostics[I].getLocation(), SM);
1066 StoredDiagnostics[I].setLocation(Loc);
1067 }
1068 }
1069}
1070
Douglas Gregorabc563f2010-07-19 21:46:24 +00001071/// Parse the source file into a translation unit using the given compiler
1072/// invocation, replacing the current translation unit.
1073///
1074/// \returns True if a failure occurred that causes the ASTUnit not to
1075/// contain any translation-unit information, false otherwise.
Douglas Gregor754f3492010-07-24 00:38:13 +00001076bool ASTUnit::Parse(llvm::MemoryBuffer *OverrideMainBuffer) {
Douglas Gregor28233422010-07-27 14:52:07 +00001077 delete SavedMainFileBuffer;
1078 SavedMainFileBuffer = 0;
1079
Ted Kremenek4f327862011-03-21 18:40:17 +00001080 if (!Invocation) {
Douglas Gregor671947b2010-08-19 01:33:06 +00001081 delete OverrideMainBuffer;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001082 return true;
Douglas Gregor671947b2010-08-19 01:33:06 +00001083 }
Douglas Gregorabc563f2010-07-19 21:46:24 +00001084
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001085 // Create the compiler instance to use for building the AST.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001086 OwningPtr<CompilerInstance> Clang(new CompilerInstance());
Ted Kremenek03201fb2011-03-21 18:40:07 +00001087
1088 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00001089 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1090 CICleanup(Clang.get());
Ted Kremenek03201fb2011-03-21 18:40:07 +00001091
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001092 IntrusiveRefCntPtr<CompilerInvocation>
Argyrios Kyrtzidis26d43cd2011-09-12 18:09:38 +00001093 CCInvocation(new CompilerInvocation(*Invocation));
1094
1095 Clang->setInvocation(CCInvocation.getPtr());
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001096 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
Douglas Gregorabc563f2010-07-19 21:46:24 +00001097
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001098 // Set up diagnostics, capturing any diagnostics that would
1099 // otherwise be dropped.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001100 Clang->setDiagnostics(&getDiagnostics());
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001101
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001102 // Create the target instance.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001103 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
Douglas Gregor49a87542012-11-16 04:24:59 +00001104 &Clang->getTargetOpts()));
Ted Kremenek03201fb2011-03-21 18:40:07 +00001105 if (!Clang->hasTarget()) {
Douglas Gregor671947b2010-08-19 01:33:06 +00001106 delete OverrideMainBuffer;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001107 return true;
Douglas Gregor671947b2010-08-19 01:33:06 +00001108 }
1109
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001110 // Inform the target of the language options.
1111 //
1112 // FIXME: We shouldn't need to do this, the target should be immutable once
1113 // created. This complexity should be lifted elsewhere.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001114 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregorabc563f2010-07-19 21:46:24 +00001115
Ted Kremenek03201fb2011-03-21 18:40:07 +00001116 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001117 "Invocation must have exactly one source file!");
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001118 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001119 "FIXME: AST inputs not yet supported here!");
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001120 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
Daniel Dunbarfaddc3e2010-06-07 23:26:47 +00001121 "IR inputs not support here!");
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001122
Douglas Gregorabc563f2010-07-19 21:46:24 +00001123 // Configure the various subsystems.
1124 // FIXME: Should we retain the previous file manager?
Ted Kremenekd3b74d92011-11-17 23:01:24 +00001125 LangOpts = &Clang->getLangOpts();
Ted Kremenek03201fb2011-03-21 18:40:07 +00001126 FileSystemOpts = Clang->getFileSystemOpts();
Ted Kremenek4f327862011-03-21 18:40:17 +00001127 FileMgr = new FileManager(FileSystemOpts);
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001128 SourceMgr = new SourceManager(getDiagnostics(), *FileMgr,
1129 UserFilesAreVolatile);
Douglas Gregor914ed9d2010-08-13 03:15:25 +00001130 TheSema.reset();
Ted Kremenek4f327862011-03-21 18:40:17 +00001131 Ctx = 0;
1132 PP = 0;
Argyrios Kyrtzidis62ba9f62011-11-01 17:14:15 +00001133 Reader = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001134
1135 // Clear out old caches and data.
1136 TopLevelDecls.clear();
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +00001137 clearFileLevelDecls();
Douglas Gregorabc563f2010-07-19 21:46:24 +00001138 CleanTemporaryFiles();
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001139
Douglas Gregorf128fed2010-08-20 00:02:33 +00001140 if (!OverrideMainBuffer) {
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00001141 checkAndRemoveNonDriverDiags(StoredDiagnostics);
Douglas Gregorf128fed2010-08-20 00:02:33 +00001142 TopLevelDeclsInPreamble.clear();
1143 }
1144
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001145 // Create a file manager object to provide access to and cache the filesystem.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001146 Clang->setFileManager(&getFileManager());
Douglas Gregorabc563f2010-07-19 21:46:24 +00001147
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001148 // Create the source manager.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001149 Clang->setSourceManager(&getSourceManager());
Douglas Gregorabc563f2010-07-19 21:46:24 +00001150
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001151 // If the main file has been overridden due to the use of a preamble,
1152 // make that override happen and introduce the preamble.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001153 PreprocessorOptions &PreprocessorOpts = Clang->getPreprocessorOpts();
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001154 if (OverrideMainBuffer) {
1155 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
1156 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
1157 PreprocessorOpts.PrecompiledPreambleBytes.second
1158 = PreambleEndsAtStartOfLine;
Ted Kremenek1872b312011-10-27 17:55:18 +00001159 PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001160 PreprocessorOpts.DisablePCHValidation = true;
Douglas Gregor28233422010-07-27 14:52:07 +00001161
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001162 // The stored diagnostic has the old source manager in it; update
1163 // the locations to refer into the new source manager. Since we've
1164 // been careful to make sure that the source manager's state
1165 // before and after are identical, so that we can reuse the source
1166 // location itself.
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00001167 checkAndSanitizeDiags(StoredDiagnostics, getSourceManager());
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001168
1169 // Keep track of the override buffer;
1170 SavedMainFileBuffer = OverrideMainBuffer;
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001171 }
1172
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001173 OwningPtr<TopLevelDeclTrackerAction> Act(
Ted Kremenek25a11e12011-03-22 01:15:24 +00001174 new TopLevelDeclTrackerAction(*this));
1175
1176 // Recover resources if we crash before exiting this method.
1177 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1178 ActCleanup(Act.get());
1179
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001180 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0]))
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001181 goto error;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001182
1183 if (OverrideMainBuffer) {
Ted Kremenek1872b312011-10-27 17:55:18 +00001184 std::string ModName = getPreambleFile(this);
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001185 TranslateStoredDiagnostics(Clang->getModuleManager(), ModName,
1186 getSourceManager(), PreambleDiagnostics,
1187 StoredDiagnostics);
1188 }
1189
Argyrios Kyrtzidis374a00b2012-06-08 05:48:06 +00001190 if (!Act->Execute())
1191 goto error;
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001192
1193 transferASTDataFromCompilerInstance(*Clang);
Douglas Gregorabc563f2010-07-19 21:46:24 +00001194
Daniel Dunbarf772d1e2009-12-04 08:17:33 +00001195 Act->EndSourceFile();
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001196
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001197 FailedParseDiagnostics.clear();
1198
Douglas Gregorabc563f2010-07-19 21:46:24 +00001199 return false;
Ted Kremenek4f327862011-03-21 18:40:17 +00001200
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001201error:
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001202 // Remove the overridden buffer we used for the preamble.
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001203 if (OverrideMainBuffer) {
Douglas Gregor671947b2010-08-19 01:33:06 +00001204 delete OverrideMainBuffer;
Douglas Gregor37cf6632010-10-06 21:11:08 +00001205 SavedMainFileBuffer = 0;
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001206 }
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001207
1208 // Keep the ownership of the data in the ASTUnit because the client may
1209 // want to see the diagnostics.
1210 transferASTDataFromCompilerInstance(*Clang);
1211 FailedParseDiagnostics.swap(StoredDiagnostics);
Douglas Gregord54eb442010-10-12 16:25:54 +00001212 StoredDiagnostics.clear();
Argyrios Kyrtzidis3e9d3262011-10-24 17:25:20 +00001213 NumStoredDiagnosticsFromDriver = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001214 return true;
1215}
1216
Douglas Gregor44c181a2010-07-23 00:33:23 +00001217/// \brief Simple function to retrieve a path for a preamble precompiled header.
1218static std::string GetPreamblePCHPath() {
1219 // FIXME: This is lame; sys::Path should provide this function (in particular,
1220 // it should know how to find the temporary files dir).
1221 // FIXME: This is really lame. I copied this code from the Driver!
Douglas Gregor424668c2010-09-11 18:05:19 +00001222 // FIXME: This is a hack so that we can override the preamble file during
1223 // crash-recovery testing, which is the only case where the preamble files
1224 // are not necessarily cleaned up.
1225 const char *TmpFile = ::getenv("CINDEXTEST_PREAMBLE_FILE");
1226 if (TmpFile)
1227 return TmpFile;
1228
Douglas Gregor44c181a2010-07-23 00:33:23 +00001229 std::string Error;
1230 const char *TmpDir = ::getenv("TMPDIR");
1231 if (!TmpDir)
1232 TmpDir = ::getenv("TEMP");
1233 if (!TmpDir)
1234 TmpDir = ::getenv("TMP");
Douglas Gregorc6cb2b02010-09-11 17:51:16 +00001235#ifdef LLVM_ON_WIN32
1236 if (!TmpDir)
1237 TmpDir = ::getenv("USERPROFILE");
1238#endif
Douglas Gregor44c181a2010-07-23 00:33:23 +00001239 if (!TmpDir)
1240 TmpDir = "/tmp";
1241 llvm::sys::Path P(TmpDir);
Douglas Gregorc6cb2b02010-09-11 17:51:16 +00001242 P.createDirectoryOnDisk(true);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001243 P.appendComponent("preamble");
Douglas Gregor6bf18302010-08-11 13:06:56 +00001244 P.appendSuffix("pch");
Argyrios Kyrtzidisbc9d5a32011-07-21 18:44:46 +00001245 if (P.makeUnique(/*reuse_current=*/false, /*ErrMsg*/0))
Douglas Gregor44c181a2010-07-23 00:33:23 +00001246 return std::string();
1247
Douglas Gregor44c181a2010-07-23 00:33:23 +00001248 return P.str();
1249}
1250
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001251/// \brief Compute the preamble for the main file, providing the source buffer
1252/// that corresponds to the main file along with a pair (bytes, start-of-line)
1253/// that describes the preamble.
1254std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> >
Douglas Gregordf95a132010-08-09 20:45:32 +00001255ASTUnit::ComputePreamble(CompilerInvocation &Invocation,
1256 unsigned MaxLines, bool &CreatedBuffer) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001257 FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
Chris Lattner39b49bc2010-11-23 08:35:12 +00001258 PreprocessorOptions &PreprocessorOpts = Invocation.getPreprocessorOpts();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001259 CreatedBuffer = false;
1260
Douglas Gregor44c181a2010-07-23 00:33:23 +00001261 // Try to determine if the main file has been remapped, either from the
1262 // command line (to another file) or directly through the compiler invocation
1263 // (to a memory buffer).
Douglas Gregor175c4a92010-07-23 23:58:40 +00001264 llvm::MemoryBuffer *Buffer = 0;
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001265 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].getFile());
Douglas Gregor44c181a2010-07-23 00:33:23 +00001266 if (const llvm::sys::FileStatus *MainFileStatus = MainFilePath.getFileStatus()) {
1267 // Check whether there is a file-file remapping of the main file
1268 for (PreprocessorOptions::remapped_file_iterator
Douglas Gregor175c4a92010-07-23 23:58:40 +00001269 M = PreprocessorOpts.remapped_file_begin(),
1270 E = PreprocessorOpts.remapped_file_end();
Douglas Gregor44c181a2010-07-23 00:33:23 +00001271 M != E;
1272 ++M) {
1273 llvm::sys::PathWithStatus MPath(M->first);
1274 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
1275 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
1276 // We found a remapping. Try to load the resulting, remapped source.
Douglas Gregor175c4a92010-07-23 23:58:40 +00001277 if (CreatedBuffer) {
Douglas Gregor44c181a2010-07-23 00:33:23 +00001278 delete Buffer;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001279 CreatedBuffer = false;
1280 }
1281
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00001282 Buffer = getBufferForFile(M->second);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001283 if (!Buffer)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001284 return std::make_pair((llvm::MemoryBuffer*)0,
1285 std::make_pair(0, true));
Douglas Gregor175c4a92010-07-23 23:58:40 +00001286 CreatedBuffer = true;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001287 }
1288 }
1289 }
1290
1291 // Check whether there is a file-buffer remapping. It supercedes the
1292 // file-file remapping.
1293 for (PreprocessorOptions::remapped_file_buffer_iterator
1294 M = PreprocessorOpts.remapped_file_buffer_begin(),
1295 E = PreprocessorOpts.remapped_file_buffer_end();
1296 M != E;
1297 ++M) {
1298 llvm::sys::PathWithStatus MPath(M->first);
1299 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
1300 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
1301 // We found a remapping.
Douglas Gregor175c4a92010-07-23 23:58:40 +00001302 if (CreatedBuffer) {
Douglas Gregor44c181a2010-07-23 00:33:23 +00001303 delete Buffer;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001304 CreatedBuffer = false;
1305 }
Douglas Gregor44c181a2010-07-23 00:33:23 +00001306
Douglas Gregor175c4a92010-07-23 23:58:40 +00001307 Buffer = const_cast<llvm::MemoryBuffer *>(M->second);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001308 }
1309 }
Douglas Gregor175c4a92010-07-23 23:58:40 +00001310 }
Douglas Gregor44c181a2010-07-23 00:33:23 +00001311 }
1312
1313 // If the main source file was not remapped, load it now.
1314 if (!Buffer) {
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001315 Buffer = getBufferForFile(FrontendOpts.Inputs[0].getFile());
Douglas Gregor44c181a2010-07-23 00:33:23 +00001316 if (!Buffer)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001317 return std::make_pair((llvm::MemoryBuffer*)0, std::make_pair(0, true));
Douglas Gregor175c4a92010-07-23 23:58:40 +00001318
1319 CreatedBuffer = true;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001320 }
1321
Argyrios Kyrtzidis03c107a2011-08-25 20:39:19 +00001322 return std::make_pair(Buffer, Lexer::ComputePreamble(Buffer,
Ted Kremenekd3b74d92011-11-17 23:01:24 +00001323 *Invocation.getLangOpts(),
Argyrios Kyrtzidis03c107a2011-08-25 20:39:19 +00001324 MaxLines));
Douglas Gregor175c4a92010-07-23 23:58:40 +00001325}
1326
Douglas Gregor754f3492010-07-24 00:38:13 +00001327static llvm::MemoryBuffer *CreatePaddedMainFileBuffer(llvm::MemoryBuffer *Old,
Douglas Gregor754f3492010-07-24 00:38:13 +00001328 unsigned NewSize,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001329 StringRef NewName) {
Douglas Gregor754f3492010-07-24 00:38:13 +00001330 llvm::MemoryBuffer *Result
1331 = llvm::MemoryBuffer::getNewUninitMemBuffer(NewSize, NewName);
1332 memcpy(const_cast<char*>(Result->getBufferStart()),
1333 Old->getBufferStart(), Old->getBufferSize());
1334 memset(const_cast<char*>(Result->getBufferStart()) + Old->getBufferSize(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001335 ' ', NewSize - Old->getBufferSize() - 1);
1336 const_cast<char*>(Result->getBufferEnd())[-1] = '\n';
Douglas Gregor754f3492010-07-24 00:38:13 +00001337
Douglas Gregor754f3492010-07-24 00:38:13 +00001338 return Result;
1339}
1340
Douglas Gregor175c4a92010-07-23 23:58:40 +00001341/// \brief Attempt to build or re-use a precompiled preamble when (re-)parsing
1342/// the source file.
1343///
1344/// This routine will compute the preamble of the main source file. If a
1345/// non-trivial preamble is found, it will precompile that preamble into a
1346/// precompiled header so that the precompiled preamble can be used to reduce
1347/// reparsing time. If a precompiled preamble has already been constructed,
1348/// this routine will determine if it is still valid and, if so, avoid
1349/// rebuilding the precompiled preamble.
1350///
Douglas Gregordf95a132010-08-09 20:45:32 +00001351/// \param AllowRebuild When true (the default), this routine is
1352/// allowed to rebuild the precompiled preamble if it is found to be
1353/// out-of-date.
1354///
1355/// \param MaxLines When non-zero, the maximum number of lines that
1356/// can occur within the preamble.
1357///
Douglas Gregor754f3492010-07-24 00:38:13 +00001358/// \returns If the precompiled preamble can be used, returns a newly-allocated
1359/// buffer that should be used in place of the main file when doing so.
1360/// Otherwise, returns a NULL pointer.
Douglas Gregordf95a132010-08-09 20:45:32 +00001361llvm::MemoryBuffer *ASTUnit::getMainBufferWithPrecompiledPreamble(
Douglas Gregor01b6e312011-07-01 18:22:13 +00001362 const CompilerInvocation &PreambleInvocationIn,
Douglas Gregordf95a132010-08-09 20:45:32 +00001363 bool AllowRebuild,
1364 unsigned MaxLines) {
Douglas Gregor01b6e312011-07-01 18:22:13 +00001365
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001366 IntrusiveRefCntPtr<CompilerInvocation>
Douglas Gregor01b6e312011-07-01 18:22:13 +00001367 PreambleInvocation(new CompilerInvocation(PreambleInvocationIn));
1368 FrontendOptions &FrontendOpts = PreambleInvocation->getFrontendOpts();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001369 PreprocessorOptions &PreprocessorOpts
Douglas Gregor01b6e312011-07-01 18:22:13 +00001370 = PreambleInvocation->getPreprocessorOpts();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001371
1372 bool CreatedPreambleBuffer = false;
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001373 std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> > NewPreamble
Douglas Gregor01b6e312011-07-01 18:22:13 +00001374 = ComputePreamble(*PreambleInvocation, MaxLines, CreatedPreambleBuffer);
Douglas Gregor175c4a92010-07-23 23:58:40 +00001375
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001376 // If ComputePreamble() Take ownership of the preamble buffer.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001377 OwningPtr<llvm::MemoryBuffer> OwnedPreambleBuffer;
Douglas Gregor73fc9122010-11-16 20:45:51 +00001378 if (CreatedPreambleBuffer)
1379 OwnedPreambleBuffer.reset(NewPreamble.first);
1380
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001381 if (!NewPreamble.second.first) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001382 // We couldn't find a preamble in the main source. Clear out the current
1383 // preamble, if we have one. It's obviously no good any more.
1384 Preamble.clear();
Ted Kremenek1872b312011-10-27 17:55:18 +00001385 erasePreambleFile(this);
Douglas Gregoreababfb2010-08-04 05:53:38 +00001386
1387 // The next time we actually see a preamble, precompile it.
1388 PreambleRebuildCounter = 1;
Douglas Gregor754f3492010-07-24 00:38:13 +00001389 return 0;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001390 }
1391
1392 if (!Preamble.empty()) {
1393 // We've previously computed a preamble. Check whether we have the same
1394 // preamble now that we did before, and that there's enough space in
1395 // the main-file buffer within the precompiled preamble to fit the
1396 // new main file.
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001397 if (Preamble.size() == NewPreamble.second.first &&
1398 PreambleEndsAtStartOfLine == NewPreamble.second.second &&
Douglas Gregor592508e2010-07-24 00:42:07 +00001399 NewPreamble.first->getBufferSize() < PreambleReservedSize-2 &&
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00001400 memcmp(Preamble.getBufferStart(), NewPreamble.first->getBufferStart(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001401 NewPreamble.second.first) == 0) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001402 // The preamble has not changed. We may be able to re-use the precompiled
1403 // preamble.
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001404
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001405 // Check that none of the files used by the preamble have changed.
1406 bool AnyFileChanged = false;
1407
1408 // First, make a record of those files that have been overridden via
1409 // remapping or unsaved_files.
1410 llvm::StringMap<std::pair<off_t, time_t> > OverriddenFiles;
1411 for (PreprocessorOptions::remapped_file_iterator
1412 R = PreprocessorOpts.remapped_file_begin(),
1413 REnd = PreprocessorOpts.remapped_file_end();
1414 !AnyFileChanged && R != REnd;
1415 ++R) {
1416 struct stat StatBuf;
Anders Carlsson340415c2011-03-18 19:23:38 +00001417 if (FileMgr->getNoncachedStatValue(R->second, StatBuf)) {
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001418 // If we can't stat the file we're remapping to, assume that something
1419 // horrible happened.
1420 AnyFileChanged = true;
1421 break;
1422 }
Douglas Gregor754f3492010-07-24 00:38:13 +00001423
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001424 OverriddenFiles[R->first] = std::make_pair(StatBuf.st_size,
1425 StatBuf.st_mtime);
1426 }
1427 for (PreprocessorOptions::remapped_file_buffer_iterator
1428 R = PreprocessorOpts.remapped_file_buffer_begin(),
1429 REnd = PreprocessorOpts.remapped_file_buffer_end();
1430 !AnyFileChanged && R != REnd;
1431 ++R) {
1432 // FIXME: Should we actually compare the contents of file->buffer
1433 // remappings?
1434 OverriddenFiles[R->first] = std::make_pair(R->second->getBufferSize(),
1435 0);
1436 }
1437
1438 // Check whether anything has changed.
1439 for (llvm::StringMap<std::pair<off_t, time_t> >::iterator
1440 F = FilesInPreamble.begin(), FEnd = FilesInPreamble.end();
1441 !AnyFileChanged && F != FEnd;
1442 ++F) {
1443 llvm::StringMap<std::pair<off_t, time_t> >::iterator Overridden
1444 = OverriddenFiles.find(F->first());
1445 if (Overridden != OverriddenFiles.end()) {
1446 // This file was remapped; check whether the newly-mapped file
1447 // matches up with the previous mapping.
1448 if (Overridden->second != F->second)
1449 AnyFileChanged = true;
1450 continue;
1451 }
1452
1453 // The file was not remapped; check whether it has changed on disk.
1454 struct stat StatBuf;
Anders Carlsson340415c2011-03-18 19:23:38 +00001455 if (FileMgr->getNoncachedStatValue(F->first(), StatBuf)) {
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001456 // If we can't stat the file, assume that something horrible happened.
1457 AnyFileChanged = true;
1458 } else if (StatBuf.st_size != F->second.first ||
1459 StatBuf.st_mtime != F->second.second)
1460 AnyFileChanged = true;
1461 }
1462
1463 if (!AnyFileChanged) {
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001464 // Okay! We can re-use the precompiled preamble.
1465
1466 // Set the state of the diagnostic object to mimic its state
1467 // after parsing the preamble.
1468 getDiagnostics().Reset();
Douglas Gregor32be4a52010-10-11 21:37:58 +00001469 ProcessWarningOptions(getDiagnostics(),
Douglas Gregor01b6e312011-07-01 18:22:13 +00001470 PreambleInvocation->getDiagnosticOpts());
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001471 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001472
1473 // Create a version of the main file buffer that is padded to
1474 // buffer size we reserved when creating the preamble.
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001475 return CreatePaddedMainFileBuffer(NewPreamble.first,
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001476 PreambleReservedSize,
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001477 FrontendOpts.Inputs[0].getFile());
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001478 }
Douglas Gregor175c4a92010-07-23 23:58:40 +00001479 }
Douglas Gregordf95a132010-08-09 20:45:32 +00001480
1481 // If we aren't allowed to rebuild the precompiled preamble, just
1482 // return now.
1483 if (!AllowRebuild)
1484 return 0;
Douglas Gregoraa3e6ba2010-10-08 04:03:57 +00001485
Douglas Gregor175c4a92010-07-23 23:58:40 +00001486 // We can't reuse the previously-computed preamble. Build a new one.
1487 Preamble.clear();
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001488 PreambleDiagnostics.clear();
Ted Kremenek1872b312011-10-27 17:55:18 +00001489 erasePreambleFile(this);
Douglas Gregoreababfb2010-08-04 05:53:38 +00001490 PreambleRebuildCounter = 1;
Douglas Gregordf95a132010-08-09 20:45:32 +00001491 } else if (!AllowRebuild) {
1492 // We aren't allowed to rebuild the precompiled preamble; just
1493 // return now.
1494 return 0;
1495 }
Douglas Gregoreababfb2010-08-04 05:53:38 +00001496
1497 // If the preamble rebuild counter > 1, it's because we previously
1498 // failed to build a preamble and we're not yet ready to try
1499 // again. Decrement the counter and return a failure.
1500 if (PreambleRebuildCounter > 1) {
1501 --PreambleRebuildCounter;
1502 return 0;
1503 }
1504
Douglas Gregor2cd4fd42010-09-11 17:56:52 +00001505 // Create a temporary file for the precompiled preamble. In rare
1506 // circumstances, this can fail.
1507 std::string PreamblePCHPath = GetPreamblePCHPath();
1508 if (PreamblePCHPath.empty()) {
1509 // Try again next time.
1510 PreambleRebuildCounter = 1;
1511 return 0;
1512 }
1513
Douglas Gregor175c4a92010-07-23 23:58:40 +00001514 // We did not previously compute a preamble, or it can't be reused anyway.
Douglas Gregor213f18b2010-10-28 15:44:59 +00001515 SimpleTimer PreambleTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00001516 PreambleTimer.setOutput("Precompiling preamble");
Douglas Gregor44c181a2010-07-23 00:33:23 +00001517
1518 // Create a new buffer that stores the preamble. The buffer also contains
1519 // extra space for the original contents of the file (which will be present
1520 // when we actually parse the file) along with more room in case the file
Douglas Gregor175c4a92010-07-23 23:58:40 +00001521 // grows.
1522 PreambleReservedSize = NewPreamble.first->getBufferSize();
1523 if (PreambleReservedSize < 4096)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001524 PreambleReservedSize = 8191;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001525 else
Douglas Gregor175c4a92010-07-23 23:58:40 +00001526 PreambleReservedSize *= 2;
1527
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001528 // Save the preamble text for later; we'll need to compare against it for
1529 // subsequent reparses.
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001530 StringRef MainFilename = PreambleInvocation->getFrontendOpts().Inputs[0].getFile();
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00001531 Preamble.assign(FileMgr->getFile(MainFilename),
1532 NewPreamble.first->getBufferStart(),
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001533 NewPreamble.first->getBufferStart()
1534 + NewPreamble.second.first);
1535 PreambleEndsAtStartOfLine = NewPreamble.second.second;
1536
Douglas Gregor671947b2010-08-19 01:33:06 +00001537 delete PreambleBuffer;
1538 PreambleBuffer
Douglas Gregor175c4a92010-07-23 23:58:40 +00001539 = llvm::MemoryBuffer::getNewUninitMemBuffer(PreambleReservedSize,
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001540 FrontendOpts.Inputs[0].getFile());
Douglas Gregor44c181a2010-07-23 00:33:23 +00001541 memcpy(const_cast<char*>(PreambleBuffer->getBufferStart()),
Douglas Gregor175c4a92010-07-23 23:58:40 +00001542 NewPreamble.first->getBufferStart(), Preamble.size());
1543 memset(const_cast<char*>(PreambleBuffer->getBufferStart()) + Preamble.size(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001544 ' ', PreambleReservedSize - Preamble.size() - 1);
1545 const_cast<char*>(PreambleBuffer->getBufferEnd())[-1] = '\n';
Douglas Gregor44c181a2010-07-23 00:33:23 +00001546
1547 // Remap the main source file to the preamble buffer.
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001548 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].getFile());
Douglas Gregor44c181a2010-07-23 00:33:23 +00001549 PreprocessorOpts.addRemappedFile(MainFilePath.str(), PreambleBuffer);
1550
1551 // Tell the compiler invocation to generate a temporary precompiled header.
1552 FrontendOpts.ProgramAction = frontend::GeneratePCH;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001553 // FIXME: Generate the precompiled header into memory?
Douglas Gregor2cd4fd42010-09-11 17:56:52 +00001554 FrontendOpts.OutputFile = PreamblePCHPath;
Douglas Gregoraa3e6ba2010-10-08 04:03:57 +00001555 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
1556 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001557
1558 // Create the compiler instance to use for building the precompiled preamble.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001559 OwningPtr<CompilerInstance> Clang(new CompilerInstance());
Ted Kremenek03201fb2011-03-21 18:40:07 +00001560
1561 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00001562 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1563 CICleanup(Clang.get());
Ted Kremenek03201fb2011-03-21 18:40:07 +00001564
Douglas Gregor01b6e312011-07-01 18:22:13 +00001565 Clang->setInvocation(&*PreambleInvocation);
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001566 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
Douglas Gregor44c181a2010-07-23 00:33:23 +00001567
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001568 // Set up diagnostics, capturing all of the diagnostics produced.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001569 Clang->setDiagnostics(&getDiagnostics());
Douglas Gregor44c181a2010-07-23 00:33:23 +00001570
1571 // Create the target instance.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001572 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
Douglas Gregor49a87542012-11-16 04:24:59 +00001573 &Clang->getTargetOpts()));
Ted Kremenek03201fb2011-03-21 18:40:07 +00001574 if (!Clang->hasTarget()) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001575 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1576 Preamble.clear();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001577 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor671947b2010-08-19 01:33:06 +00001578 PreprocessorOpts.eraseRemappedFile(
1579 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor754f3492010-07-24 00:38:13 +00001580 return 0;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001581 }
1582
1583 // Inform the target of the language options.
1584 //
1585 // FIXME: We shouldn't need to do this, the target should be immutable once
1586 // created. This complexity should be lifted elsewhere.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001587 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregor44c181a2010-07-23 00:33:23 +00001588
Ted Kremenek03201fb2011-03-21 18:40:07 +00001589 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Douglas Gregor44c181a2010-07-23 00:33:23 +00001590 "Invocation must have exactly one source file!");
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001591 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
Douglas Gregor44c181a2010-07-23 00:33:23 +00001592 "FIXME: AST inputs not yet supported here!");
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001593 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
Douglas Gregor44c181a2010-07-23 00:33:23 +00001594 "IR inputs not support here!");
1595
1596 // Clear out old caches and data.
Douglas Gregoraa3e6ba2010-10-08 04:03:57 +00001597 getDiagnostics().Reset();
Ted Kremenek03201fb2011-03-21 18:40:07 +00001598 ProcessWarningOptions(getDiagnostics(), Clang->getDiagnosticOpts());
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00001599 checkAndRemoveNonDriverDiags(StoredDiagnostics);
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001600 TopLevelDecls.clear();
1601 TopLevelDeclsInPreamble.clear();
Douglas Gregor44c181a2010-07-23 00:33:23 +00001602
1603 // Create a file manager object to provide access to and cache the filesystem.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001604 Clang->setFileManager(new FileManager(Clang->getFileSystemOpts()));
Douglas Gregor44c181a2010-07-23 00:33:23 +00001605
1606 // Create the source manager.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001607 Clang->setSourceManager(new SourceManager(getDiagnostics(),
Ted Kremenek4f327862011-03-21 18:40:17 +00001608 Clang->getFileManager()));
Douglas Gregor44c181a2010-07-23 00:33:23 +00001609
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001610 OwningPtr<PrecompilePreambleAction> Act;
Douglas Gregor1d715ac2010-08-03 08:14:03 +00001611 Act.reset(new PrecompilePreambleAction(*this));
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001612 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001613 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1614 Preamble.clear();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001615 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor671947b2010-08-19 01:33:06 +00001616 PreprocessorOpts.eraseRemappedFile(
1617 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor754f3492010-07-24 00:38:13 +00001618 return 0;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001619 }
1620
1621 Act->Execute();
1622 Act->EndSourceFile();
Ted Kremenek4f327862011-03-21 18:40:17 +00001623
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001624 if (Diagnostics->hasErrorOccurred()) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001625 // There were errors parsing the preamble, so no precompiled header was
1626 // generated. Forget that we even tried.
Douglas Gregor06e50442010-09-27 16:43:25 +00001627 // FIXME: Should we leave a note for ourselves to try again?
Douglas Gregor175c4a92010-07-23 23:58:40 +00001628 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1629 Preamble.clear();
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001630 TopLevelDeclsInPreamble.clear();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001631 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor671947b2010-08-19 01:33:06 +00001632 PreprocessorOpts.eraseRemappedFile(
1633 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor754f3492010-07-24 00:38:13 +00001634 return 0;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001635 }
1636
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001637 // Transfer any diagnostics generated when parsing the preamble into the set
1638 // of preamble diagnostics.
1639 PreambleDiagnostics.clear();
1640 PreambleDiagnostics.insert(PreambleDiagnostics.end(),
Argyrios Kyrtzidis3e9d3262011-10-24 17:25:20 +00001641 stored_diag_afterDriver_begin(), stored_diag_end());
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00001642 checkAndRemoveNonDriverDiags(StoredDiagnostics);
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001643
Douglas Gregor175c4a92010-07-23 23:58:40 +00001644 // Keep track of the preamble we precompiled.
Ted Kremenek1872b312011-10-27 17:55:18 +00001645 setPreambleFile(this, FrontendOpts.OutputFile);
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001646 NumWarningsInPreamble = getDiagnostics().getNumWarnings();
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001647
1648 // Keep track of all of the files that the source manager knows about,
1649 // so we can verify whether they have changed or not.
1650 FilesInPreamble.clear();
Ted Kremenek03201fb2011-03-21 18:40:07 +00001651 SourceManager &SourceMgr = Clang->getSourceManager();
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001652 const llvm::MemoryBuffer *MainFileBuffer
1653 = SourceMgr.getBuffer(SourceMgr.getMainFileID());
1654 for (SourceManager::fileinfo_iterator F = SourceMgr.fileinfo_begin(),
1655 FEnd = SourceMgr.fileinfo_end();
1656 F != FEnd;
1657 ++F) {
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001658 const FileEntry *File = F->second->OrigEntry;
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001659 if (!File || F->second->getRawBuffer() == MainFileBuffer)
1660 continue;
1661
1662 FilesInPreamble[File->getName()]
1663 = std::make_pair(F->second->getSize(), File->getModificationTime());
1664 }
1665
Douglas Gregoreababfb2010-08-04 05:53:38 +00001666 PreambleRebuildCounter = 1;
Douglas Gregor671947b2010-08-19 01:33:06 +00001667 PreprocessorOpts.eraseRemappedFile(
1668 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor9b7db622011-02-16 18:16:54 +00001669
1670 // If the hash of top-level entities differs from the hash of the top-level
1671 // entities the last time we rebuilt the preamble, clear out the completion
1672 // cache.
1673 if (CurrentTopLevelHashValue != PreambleTopLevelHashValue) {
1674 CompletionCacheTopLevelHashValue = 0;
1675 PreambleTopLevelHashValue = CurrentTopLevelHashValue;
1676 }
1677
Douglas Gregor754f3492010-07-24 00:38:13 +00001678 return CreatePaddedMainFileBuffer(NewPreamble.first,
Douglas Gregor754f3492010-07-24 00:38:13 +00001679 PreambleReservedSize,
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001680 FrontendOpts.Inputs[0].getFile());
Douglas Gregor44c181a2010-07-23 00:33:23 +00001681}
Douglas Gregorabc563f2010-07-19 21:46:24 +00001682
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001683void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
1684 std::vector<Decl *> Resolved;
1685 Resolved.reserve(TopLevelDeclsInPreamble.size());
1686 ExternalASTSource &Source = *getASTContext().getExternalSource();
1687 for (unsigned I = 0, N = TopLevelDeclsInPreamble.size(); I != N; ++I) {
1688 // Resolve the declaration ID to an actual declaration, possibly
1689 // deserializing the declaration in the process.
1690 Decl *D = Source.GetExternalDecl(TopLevelDeclsInPreamble[I]);
1691 if (D)
1692 Resolved.push_back(D);
1693 }
1694 TopLevelDeclsInPreamble.clear();
1695 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1696}
1697
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001698void ASTUnit::transferASTDataFromCompilerInstance(CompilerInstance &CI) {
1699 // Steal the created target, context, and preprocessor.
1700 TheSema.reset(CI.takeSema());
1701 Consumer.reset(CI.takeASTConsumer());
1702 Ctx = &CI.getASTContext();
1703 PP = &CI.getPreprocessor();
1704 CI.setSourceManager(0);
1705 CI.setFileManager(0);
1706 Target = &CI.getTarget();
1707 Reader = CI.getModuleManager();
1708}
1709
Chris Lattner5f9e2722011-07-23 10:55:15 +00001710StringRef ASTUnit::getMainFileName() const {
Argyrios Kyrtzidis814b51a2013-01-11 22:11:14 +00001711 if (Invocation && !Invocation->getFrontendOpts().Inputs.empty()) {
1712 const FrontendInputFile &Input = Invocation->getFrontendOpts().Inputs[0];
1713 if (Input.isFile())
1714 return Input.getFile();
1715 else
1716 return Input.getBuffer()->getBufferIdentifier();
1717 }
1718
1719 if (SourceMgr) {
1720 if (const FileEntry *
1721 FE = SourceMgr->getFileEntryForID(SourceMgr->getMainFileID()))
1722 return FE->getName();
1723 }
1724
1725 return StringRef();
Douglas Gregor213f18b2010-10-28 15:44:59 +00001726}
1727
Argyrios Kyrtzidis44f65a52013-03-05 20:21:14 +00001728StringRef ASTUnit::getASTFileName() const {
1729 if (!isMainFileAST())
1730 return StringRef();
1731
1732 serialization::ModuleFile &
1733 Mod = Reader->getModuleManager().getPrimaryModule();
1734 return Mod.FileName;
1735}
1736
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001737ASTUnit *ASTUnit::create(CompilerInvocation *CI,
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001738 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001739 bool CaptureDiagnostics,
1740 bool UserFilesAreVolatile) {
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001741 OwningPtr<ASTUnit> AST;
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001742 AST.reset(new ASTUnit(false));
Argyrios Kyrtzidis991bf492011-11-28 04:55:55 +00001743 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001744 AST->Diagnostics = Diags;
Ted Kremenek4f327862011-03-21 18:40:17 +00001745 AST->Invocation = CI;
Anders Carlsson0d8d7e62011-03-18 18:22:40 +00001746 AST->FileSystemOpts = CI->getFileSystemOpts();
Ted Kremenek4f327862011-03-21 18:40:17 +00001747 AST->FileMgr = new FileManager(AST->FileSystemOpts);
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001748 AST->UserFilesAreVolatile = UserFilesAreVolatile;
1749 AST->SourceMgr = new SourceManager(AST->getDiagnostics(), *AST->FileMgr,
1750 UserFilesAreVolatile);
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001751
1752 return AST.take();
1753}
1754
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001755ASTUnit *ASTUnit::LoadFromCompilerInvocationAction(CompilerInvocation *CI,
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001756 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001757 ASTFrontendAction *Action,
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00001758 ASTUnit *Unit,
1759 bool Persistent,
1760 StringRef ResourceFilesPath,
1761 bool OnlyLocalDecls,
1762 bool CaptureDiagnostics,
1763 bool PrecompilePreamble,
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001764 bool CacheCodeCompletionResults,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00001765 bool IncludeBriefCommentsInCodeCompletion,
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001766 bool UserFilesAreVolatile,
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001767 OwningPtr<ASTUnit> *ErrAST) {
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001768 assert(CI && "A CompilerInvocation is required");
1769
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001770 OwningPtr<ASTUnit> OwnAST;
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001771 ASTUnit *AST = Unit;
1772 if (!AST) {
1773 // Create the AST unit.
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001774 OwnAST.reset(create(CI, Diags, CaptureDiagnostics, UserFilesAreVolatile));
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001775 AST = OwnAST.get();
1776 }
1777
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00001778 if (!ResourceFilesPath.empty()) {
1779 // Override the resources path.
1780 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
1781 }
1782 AST->OnlyLocalDecls = OnlyLocalDecls;
1783 AST->CaptureDiagnostics = CaptureDiagnostics;
1784 if (PrecompilePreamble)
1785 AST->PreambleRebuildCounter = 2;
Douglas Gregor467dc882011-08-25 22:30:56 +00001786 AST->TUKind = Action ? Action->getTranslationUnitKind() : TU_Complete;
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00001787 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00001788 AST->IncludeBriefCommentsInCodeCompletion
1789 = IncludeBriefCommentsInCodeCompletion;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001790
1791 // Recover resources if we crash before exiting this method.
1792 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001793 ASTUnitCleanup(OwnAST.get());
David Blaikied6471f72011-09-25 23:23:43 +00001794 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1795 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001796 DiagCleanup(Diags.getPtr());
1797
1798 // We'll manage file buffers ourselves.
1799 CI->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1800 CI->getFrontendOpts().DisableFree = false;
1801 ProcessWarningOptions(AST->getDiagnostics(), CI->getDiagnosticOpts());
1802
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001803 // Create the compiler instance to use for building the AST.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001804 OwningPtr<CompilerInstance> Clang(new CompilerInstance());
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001805
1806 // Recover resources if we crash before exiting this method.
1807 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1808 CICleanup(Clang.get());
1809
1810 Clang->setInvocation(CI);
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001811 AST->OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001812
1813 // Set up diagnostics, capturing any diagnostics that would
1814 // otherwise be dropped.
1815 Clang->setDiagnostics(&AST->getDiagnostics());
1816
1817 // Create the target instance.
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001818 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
Douglas Gregor49a87542012-11-16 04:24:59 +00001819 &Clang->getTargetOpts()));
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001820 if (!Clang->hasTarget())
1821 return 0;
1822
1823 // Inform the target of the language options.
1824 //
1825 // FIXME: We shouldn't need to do this, the target should be immutable once
1826 // created. This complexity should be lifted elsewhere.
1827 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
1828
1829 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1830 "Invocation must have exactly one source file!");
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001831 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001832 "FIXME: AST inputs not yet supported here!");
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001833 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001834 "IR inputs not supported here!");
1835
1836 // Configure the various subsystems.
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001837 AST->TheSema.reset();
1838 AST->Ctx = 0;
1839 AST->PP = 0;
Argyrios Kyrtzidis62ba9f62011-11-01 17:14:15 +00001840 AST->Reader = 0;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001841
1842 // Create a file manager object to provide access to and cache the filesystem.
1843 Clang->setFileManager(&AST->getFileManager());
1844
1845 // Create the source manager.
1846 Clang->setSourceManager(&AST->getSourceManager());
1847
1848 ASTFrontendAction *Act = Action;
1849
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001850 OwningPtr<TopLevelDeclTrackerAction> TrackerAct;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001851 if (!Act) {
1852 TrackerAct.reset(new TopLevelDeclTrackerAction(*AST));
1853 Act = TrackerAct.get();
1854 }
1855
1856 // Recover resources if we crash before exiting this method.
1857 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1858 ActCleanup(TrackerAct.get());
1859
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001860 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
1861 AST->transferASTDataFromCompilerInstance(*Clang);
1862 if (OwnAST && ErrAST)
1863 ErrAST->swap(OwnAST);
1864
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001865 return 0;
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001866 }
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00001867
1868 if (Persistent && !TrackerAct) {
1869 Clang->getPreprocessor().addPPCallbacks(
1870 new MacroDefinitionTrackerPPCallbacks(AST->getCurrentTopLevelHashValue()));
1871 std::vector<ASTConsumer*> Consumers;
1872 if (Clang->hasASTConsumer())
1873 Consumers.push_back(Clang->takeASTConsumer());
1874 Consumers.push_back(new TopLevelDeclTrackerConsumer(*AST,
1875 AST->getCurrentTopLevelHashValue()));
1876 Clang->setASTConsumer(new MultiplexConsumer(Consumers));
1877 }
Argyrios Kyrtzidis374a00b2012-06-08 05:48:06 +00001878 if (!Act->Execute()) {
1879 AST->transferASTDataFromCompilerInstance(*Clang);
1880 if (OwnAST && ErrAST)
1881 ErrAST->swap(OwnAST);
1882
1883 return 0;
1884 }
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001885
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001886 // Steal the created target, context, and preprocessor.
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001887 AST->transferASTDataFromCompilerInstance(*Clang);
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001888
1889 Act->EndSourceFile();
1890
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001891 if (OwnAST)
1892 return OwnAST.take();
1893 else
1894 return AST;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001895}
1896
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001897bool ASTUnit::LoadFromCompilerInvocation(bool PrecompilePreamble) {
1898 if (!Invocation)
1899 return true;
1900
1901 // We'll manage file buffers ourselves.
1902 Invocation->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1903 Invocation->getFrontendOpts().DisableFree = false;
Douglas Gregor0b53cf82011-01-19 01:02:47 +00001904 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001905
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001906 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Douglas Gregor99ba2022010-10-27 17:24:53 +00001907 if (PrecompilePreamble) {
Douglas Gregor08bb4c62010-11-15 23:00:34 +00001908 PreambleRebuildCounter = 2;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001909 OverrideMainBuffer
1910 = getMainBufferWithPrecompiledPreamble(*Invocation);
1911 }
1912
Douglas Gregor213f18b2010-10-28 15:44:59 +00001913 SimpleTimer ParsingTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00001914 ParsingTimer.setOutput("Parsing " + getMainFileName());
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001915
Ted Kremenek25a11e12011-03-22 01:15:24 +00001916 // Recover resources if we crash before exiting this method.
1917 llvm::CrashRecoveryContextCleanupRegistrar<llvm::MemoryBuffer>
1918 MemBufferCleanup(OverrideMainBuffer);
1919
Douglas Gregor213f18b2010-10-28 15:44:59 +00001920 return Parse(OverrideMainBuffer);
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001921}
1922
Douglas Gregorabc563f2010-07-19 21:46:24 +00001923ASTUnit *ASTUnit::LoadFromCompilerInvocation(CompilerInvocation *CI,
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001924 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Douglas Gregorabc563f2010-07-19 21:46:24 +00001925 bool OnlyLocalDecls,
Douglas Gregor44c181a2010-07-23 00:33:23 +00001926 bool CaptureDiagnostics,
Douglas Gregordf95a132010-08-09 20:45:32 +00001927 bool PrecompilePreamble,
Douglas Gregor467dc882011-08-25 22:30:56 +00001928 TranslationUnitKind TUKind,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00001929 bool CacheCodeCompletionResults,
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001930 bool IncludeBriefCommentsInCodeCompletion,
1931 bool UserFilesAreVolatile) {
Douglas Gregorabc563f2010-07-19 21:46:24 +00001932 // Create the AST unit.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001933 OwningPtr<ASTUnit> AST;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001934 AST.reset(new ASTUnit(false));
Douglas Gregor0b53cf82011-01-19 01:02:47 +00001935 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
Douglas Gregorabc563f2010-07-19 21:46:24 +00001936 AST->Diagnostics = Diags;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001937 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregore47be3e2010-11-11 00:39:14 +00001938 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor467dc882011-08-25 22:30:56 +00001939 AST->TUKind = TUKind;
Douglas Gregor87c08a52010-08-13 22:48:40 +00001940 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00001941 AST->IncludeBriefCommentsInCodeCompletion
1942 = IncludeBriefCommentsInCodeCompletion;
Ted Kremenek4f327862011-03-21 18:40:17 +00001943 AST->Invocation = CI;
Argyrios Kyrtzidiseb8fc582013-01-21 18:45:42 +00001944 AST->FileSystemOpts = CI->getFileSystemOpts();
1945 AST->FileMgr = new FileManager(AST->FileSystemOpts);
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001946 AST->UserFilesAreVolatile = UserFilesAreVolatile;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001947
Ted Kremenekb547eeb2011-03-18 02:06:56 +00001948 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00001949 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1950 ASTUnitCleanup(AST.get());
David Blaikied6471f72011-09-25 23:23:43 +00001951 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1952 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Ted Kremenek25a11e12011-03-22 01:15:24 +00001953 DiagCleanup(Diags.getPtr());
Ted Kremenekb547eeb2011-03-18 02:06:56 +00001954
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001955 return AST->LoadFromCompilerInvocation(PrecompilePreamble)? 0 : AST.take();
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001956}
Daniel Dunbar7b556682009-12-02 03:23:45 +00001957
1958ASTUnit *ASTUnit::LoadFromCommandLine(const char **ArgBegin,
1959 const char **ArgEnd,
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001960 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001961 StringRef ResourceFilesPath,
Daniel Dunbar7b556682009-12-02 03:23:45 +00001962 bool OnlyLocalDecls,
Douglas Gregore47be3e2010-11-11 00:39:14 +00001963 bool CaptureDiagnostics,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001964 RemappedFile *RemappedFiles,
Douglas Gregora88084b2010-02-18 18:08:43 +00001965 unsigned NumRemappedFiles,
Argyrios Kyrtzidis299a4a92011-03-08 23:35:24 +00001966 bool RemappedFilesKeepOriginalName,
Douglas Gregordf95a132010-08-09 20:45:32 +00001967 bool PrecompilePreamble,
Douglas Gregor467dc882011-08-25 22:30:56 +00001968 TranslationUnitKind TUKind,
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +00001969 bool CacheCodeCompletionResults,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00001970 bool IncludeBriefCommentsInCodeCompletion,
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001971 bool AllowPCHWithCompilerErrors,
Erik Verbruggen6a91d382012-04-12 10:11:59 +00001972 bool SkipFunctionBodies,
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001973 bool UserFilesAreVolatile,
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +00001974 bool ForSerialization,
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001975 OwningPtr<ASTUnit> *ErrAST) {
Douglas Gregor28019772010-04-05 23:52:57 +00001976 if (!Diags.getPtr()) {
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001977 // No diagnostics engine was provided, so create our own diagnostics object
1978 // with the default options.
Sean Silvad47afb92013-01-20 01:58:28 +00001979 Diags = CompilerInstance::createDiagnostics(new DiagnosticOptions());
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001980 }
Daniel Dunbar7b556682009-12-02 03:23:45 +00001981
Chris Lattner5f9e2722011-07-23 10:55:15 +00001982 SmallVector<StoredDiagnostic, 4> StoredDiagnostics;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001983
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001984 IntrusiveRefCntPtr<CompilerInvocation> CI;
Douglas Gregore47be3e2010-11-11 00:39:14 +00001985
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001986 {
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001987
Douglas Gregore47be3e2010-11-11 00:39:14 +00001988 CaptureDroppedDiagnostics Capture(CaptureDiagnostics, *Diags,
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001989 StoredDiagnostics);
Daniel Dunbar3bd54cc2010-01-25 00:44:02 +00001990
Argyrios Kyrtzidis832316e2011-04-04 23:11:45 +00001991 CI = clang::createInvocationFromCommandLine(
Frits van Bommele9c02652011-07-18 12:00:32 +00001992 llvm::makeArrayRef(ArgBegin, ArgEnd),
1993 Diags);
Argyrios Kyrtzidis054e4f52011-04-04 21:38:51 +00001994 if (!CI)
Argyrios Kyrtzidis4e03c2b2011-03-07 22:45:01 +00001995 return 0;
Daniel Dunbar7b556682009-12-02 03:23:45 +00001996 }
Douglas Gregore47be3e2010-11-11 00:39:14 +00001997
Douglas Gregor4db64a42010-01-23 00:14:00 +00001998 // Override any files that need remapping
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001999 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
2000 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
2001 if (const llvm::MemoryBuffer *
2002 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
2003 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first, memBuf);
2004 } else {
2005 const char *fname = fileOrBuf.get<const char *>();
2006 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first, fname);
2007 }
2008 }
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +00002009 PreprocessorOptions &PPOpts = CI->getPreprocessorOpts();
2010 PPOpts.RemappedFilesKeepOriginalName = RemappedFilesKeepOriginalName;
2011 PPOpts.AllowPCHWithCompilerErrors = AllowPCHWithCompilerErrors;
Douglas Gregor4db64a42010-01-23 00:14:00 +00002012
Daniel Dunbar8b9adfe2009-12-15 00:06:45 +00002013 // Override the resources path.
Daniel Dunbar807b0612010-01-30 21:47:16 +00002014 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
Daniel Dunbar7b556682009-12-02 03:23:45 +00002015
Erik Verbruggen6a91d382012-04-12 10:11:59 +00002016 CI->getFrontendOpts().SkipFunctionBodies = SkipFunctionBodies;
2017
Douglas Gregor4cd912a2010-10-12 00:50:20 +00002018 // Create the AST unit.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00002019 OwningPtr<ASTUnit> AST;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00002020 AST.reset(new ASTUnit(false));
Douglas Gregor0b53cf82011-01-19 01:02:47 +00002021 ConfigureDiags(Diags, ArgBegin, ArgEnd, *AST, CaptureDiagnostics);
Douglas Gregor4cd912a2010-10-12 00:50:20 +00002022 AST->Diagnostics = Diags;
Ted Kremenekd04a9822011-11-17 23:01:17 +00002023 Diags = 0; // Zero out now to ease cleanup during crash recovery.
Anders Carlsson0d8d7e62011-03-18 18:22:40 +00002024 AST->FileSystemOpts = CI->getFileSystemOpts();
Ted Kremenek4f327862011-03-21 18:40:17 +00002025 AST->FileMgr = new FileManager(AST->FileSystemOpts);
Douglas Gregor4cd912a2010-10-12 00:50:20 +00002026 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregore47be3e2010-11-11 00:39:14 +00002027 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor467dc882011-08-25 22:30:56 +00002028 AST->TUKind = TUKind;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00002029 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002030 AST->IncludeBriefCommentsInCodeCompletion
2031 = IncludeBriefCommentsInCodeCompletion;
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00002032 AST->UserFilesAreVolatile = UserFilesAreVolatile;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00002033 AST->NumStoredDiagnosticsFromDriver = StoredDiagnostics.size();
Douglas Gregor4cd912a2010-10-12 00:50:20 +00002034 AST->StoredDiagnostics.swap(StoredDiagnostics);
Ted Kremenek4f327862011-03-21 18:40:17 +00002035 AST->Invocation = CI;
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +00002036 if (ForSerialization)
2037 AST->WriterData.reset(new ASTWriterData());
Ted Kremenekd04a9822011-11-17 23:01:17 +00002038 CI = 0; // Zero out now to ease cleanup during crash recovery.
Ted Kremenekb547eeb2011-03-18 02:06:56 +00002039
2040 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00002041 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
2042 ASTUnitCleanup(AST.get());
Ted Kremenekb547eeb2011-03-18 02:06:56 +00002043
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00002044 if (AST->LoadFromCompilerInvocation(PrecompilePreamble)) {
2045 // Some error occurred, if caller wants to examine diagnostics, pass it the
2046 // ASTUnit.
2047 if (ErrAST) {
2048 AST->StoredDiagnostics.swap(AST->FailedParseDiagnostics);
2049 ErrAST->swap(AST);
2050 }
2051 return 0;
2052 }
2053
2054 return AST.take();
Daniel Dunbar7b556682009-12-02 03:23:45 +00002055}
Douglas Gregorabc563f2010-07-19 21:46:24 +00002056
2057bool ASTUnit::Reparse(RemappedFile *RemappedFiles, unsigned NumRemappedFiles) {
Ted Kremenek4f327862011-03-21 18:40:17 +00002058 if (!Invocation)
Douglas Gregorabc563f2010-07-19 21:46:24 +00002059 return true;
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +00002060
2061 clearFileLevelDecls();
Douglas Gregorabc563f2010-07-19 21:46:24 +00002062
Douglas Gregor213f18b2010-10-28 15:44:59 +00002063 SimpleTimer ParsingTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00002064 ParsingTimer.setOutput("Reparsing " + getMainFileName());
Douglas Gregor213f18b2010-10-28 15:44:59 +00002065
Douglas Gregorcc5888d2010-07-31 00:40:00 +00002066 // Remap files.
Douglas Gregorf128fed2010-08-20 00:02:33 +00002067 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
2068 for (PreprocessorOptions::remapped_file_buffer_iterator
2069 R = PPOpts.remapped_file_buffer_begin(),
2070 REnd = PPOpts.remapped_file_buffer_end();
2071 R != REnd;
2072 ++R) {
2073 delete R->second;
2074 }
Douglas Gregorcc5888d2010-07-31 00:40:00 +00002075 Invocation->getPreprocessorOpts().clearRemappedFiles();
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00002076 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
2077 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
2078 if (const llvm::MemoryBuffer *
2079 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
2080 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
2081 memBuf);
2082 } else {
2083 const char *fname = fileOrBuf.get<const char *>();
2084 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
2085 fname);
2086 }
2087 }
Douglas Gregorcc5888d2010-07-31 00:40:00 +00002088
Douglas Gregoreababfb2010-08-04 05:53:38 +00002089 // If we have a preamble file lying around, or if we might try to
2090 // build a precompiled preamble, do so now.
Douglas Gregor754f3492010-07-24 00:38:13 +00002091 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Ted Kremenek1872b312011-10-27 17:55:18 +00002092 if (!getPreambleFile(this).empty() || PreambleRebuildCounter > 0)
Douglas Gregor2283d792010-08-20 00:59:43 +00002093 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(*Invocation);
Douglas Gregor175c4a92010-07-23 23:58:40 +00002094
Douglas Gregorabc563f2010-07-19 21:46:24 +00002095 // Clear out the diagnostics state.
Argyrios Kyrtzidise6825d32011-11-03 20:28:19 +00002096 getDiagnostics().Reset();
2097 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Argyrios Kyrtzidis27368f92011-11-03 20:57:33 +00002098 if (OverrideMainBuffer)
2099 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
Argyrios Kyrtzidise6825d32011-11-03 20:28:19 +00002100
Douglas Gregor175c4a92010-07-23 23:58:40 +00002101 // Parse the sources
Douglas Gregor9b7db622011-02-16 18:16:54 +00002102 bool Result = Parse(OverrideMainBuffer);
Argyrios Kyrtzidis2fe17fc2011-10-31 21:25:31 +00002103
2104 // If we're caching global code-completion results, and the top-level
2105 // declarations have changed, clear out the code-completion cache.
2106 if (!Result && ShouldCacheCodeCompletionResults &&
2107 CurrentTopLevelHashValue != CompletionCacheTopLevelHashValue)
2108 CacheCodeCompletionResults();
Douglas Gregor9b7db622011-02-16 18:16:54 +00002109
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00002110 // We now need to clear out the completion info related to this translation
2111 // unit; it'll be recreated if necessary.
2112 CCTUInfo.reset();
Douglas Gregor8fa0a802011-08-04 20:04:59 +00002113
Douglas Gregor175c4a92010-07-23 23:58:40 +00002114 return Result;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002115}
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002116
Douglas Gregor87c08a52010-08-13 22:48:40 +00002117//----------------------------------------------------------------------------//
2118// Code completion
2119//----------------------------------------------------------------------------//
2120
2121namespace {
2122 /// \brief Code completion consumer that combines the cached code-completion
2123 /// results from an ASTUnit with the code-completion results provided to it,
2124 /// then passes the result on to
2125 class AugmentedCodeCompleteConsumer : public CodeCompleteConsumer {
Richard Smith026b3582012-08-14 03:13:00 +00002126 uint64_t NormalContexts;
Douglas Gregor87c08a52010-08-13 22:48:40 +00002127 ASTUnit &AST;
2128 CodeCompleteConsumer &Next;
2129
2130 public:
2131 AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002132 const CodeCompleteOptions &CodeCompleteOpts)
2133 : CodeCompleteConsumer(CodeCompleteOpts, Next.isOutputBinary()),
2134 AST(AST), Next(Next)
Douglas Gregor87c08a52010-08-13 22:48:40 +00002135 {
2136 // Compute the set of contexts in which we will look when we don't have
2137 // any information about the specific context.
2138 NormalContexts
Richard Smith026b3582012-08-14 03:13:00 +00002139 = (1LL << CodeCompletionContext::CCC_TopLevel)
2140 | (1LL << CodeCompletionContext::CCC_ObjCInterface)
2141 | (1LL << CodeCompletionContext::CCC_ObjCImplementation)
2142 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
2143 | (1LL << CodeCompletionContext::CCC_Statement)
2144 | (1LL << CodeCompletionContext::CCC_Expression)
2145 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
2146 | (1LL << CodeCompletionContext::CCC_DotMemberAccess)
2147 | (1LL << CodeCompletionContext::CCC_ArrowMemberAccess)
2148 | (1LL << CodeCompletionContext::CCC_ObjCPropertyAccess)
2149 | (1LL << CodeCompletionContext::CCC_ObjCProtocolName)
2150 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
2151 | (1LL << CodeCompletionContext::CCC_Recovery);
Douglas Gregor02688102010-09-14 23:59:36 +00002152
David Blaikie4e4d0842012-03-11 07:00:24 +00002153 if (AST.getASTContext().getLangOpts().CPlusPlus)
Richard Smith026b3582012-08-14 03:13:00 +00002154 NormalContexts |= (1LL << CodeCompletionContext::CCC_EnumTag)
2155 | (1LL << CodeCompletionContext::CCC_UnionTag)
2156 | (1LL << CodeCompletionContext::CCC_ClassOrStructTag);
Douglas Gregor87c08a52010-08-13 22:48:40 +00002157 }
2158
2159 virtual void ProcessCodeCompleteResults(Sema &S,
2160 CodeCompletionContext Context,
John McCall0a2c5e22010-08-25 06:19:51 +00002161 CodeCompletionResult *Results,
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002162 unsigned NumResults);
Douglas Gregor87c08a52010-08-13 22:48:40 +00002163
2164 virtual void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
2165 OverloadCandidate *Candidates,
2166 unsigned NumCandidates) {
2167 Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates);
2168 }
Douglas Gregor218937c2011-02-01 19:23:04 +00002169
Douglas Gregordae68752011-02-01 22:57:45 +00002170 virtual CodeCompletionAllocator &getAllocator() {
Douglas Gregor218937c2011-02-01 19:23:04 +00002171 return Next.getAllocator();
2172 }
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00002173
2174 virtual CodeCompletionTUInfo &getCodeCompletionTUInfo() {
2175 return Next.getCodeCompletionTUInfo();
2176 }
Douglas Gregor87c08a52010-08-13 22:48:40 +00002177 };
2178}
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002179
Douglas Gregor5f808c22010-08-16 21:18:39 +00002180/// \brief Helper function that computes which global names are hidden by the
2181/// local code-completion results.
Ted Kremenekc198f612010-11-07 06:11:36 +00002182static void CalculateHiddenNames(const CodeCompletionContext &Context,
2183 CodeCompletionResult *Results,
2184 unsigned NumResults,
2185 ASTContext &Ctx,
2186 llvm::StringSet<llvm::BumpPtrAllocator> &HiddenNames){
Douglas Gregor5f808c22010-08-16 21:18:39 +00002187 bool OnlyTagNames = false;
2188 switch (Context.getKind()) {
Douglas Gregor52779fb2010-09-23 23:01:17 +00002189 case CodeCompletionContext::CCC_Recovery:
Douglas Gregor5f808c22010-08-16 21:18:39 +00002190 case CodeCompletionContext::CCC_TopLevel:
2191 case CodeCompletionContext::CCC_ObjCInterface:
2192 case CodeCompletionContext::CCC_ObjCImplementation:
2193 case CodeCompletionContext::CCC_ObjCIvarList:
2194 case CodeCompletionContext::CCC_ClassStructUnion:
2195 case CodeCompletionContext::CCC_Statement:
2196 case CodeCompletionContext::CCC_Expression:
2197 case CodeCompletionContext::CCC_ObjCMessageReceiver:
Douglas Gregor3da626b2011-07-07 16:03:39 +00002198 case CodeCompletionContext::CCC_DotMemberAccess:
2199 case CodeCompletionContext::CCC_ArrowMemberAccess:
2200 case CodeCompletionContext::CCC_ObjCPropertyAccess:
Douglas Gregor5f808c22010-08-16 21:18:39 +00002201 case CodeCompletionContext::CCC_Namespace:
2202 case CodeCompletionContext::CCC_Type:
Douglas Gregor2ccccb32010-08-23 18:23:48 +00002203 case CodeCompletionContext::CCC_Name:
2204 case CodeCompletionContext::CCC_PotentiallyQualifiedName:
Douglas Gregor02688102010-09-14 23:59:36 +00002205 case CodeCompletionContext::CCC_ParenthesizedExpression:
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00002206 case CodeCompletionContext::CCC_ObjCInterfaceName:
Douglas Gregor5f808c22010-08-16 21:18:39 +00002207 break;
2208
2209 case CodeCompletionContext::CCC_EnumTag:
2210 case CodeCompletionContext::CCC_UnionTag:
2211 case CodeCompletionContext::CCC_ClassOrStructTag:
2212 OnlyTagNames = true;
2213 break;
2214
2215 case CodeCompletionContext::CCC_ObjCProtocolName:
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002216 case CodeCompletionContext::CCC_MacroName:
2217 case CodeCompletionContext::CCC_MacroNameUse:
Douglas Gregorf29c5232010-08-24 22:20:20 +00002218 case CodeCompletionContext::CCC_PreprocessorExpression:
Douglas Gregor721f3592010-08-25 18:41:16 +00002219 case CodeCompletionContext::CCC_PreprocessorDirective:
Douglas Gregor59a66942010-08-25 18:04:30 +00002220 case CodeCompletionContext::CCC_NaturalLanguage:
Douglas Gregor458433d2010-08-26 15:07:07 +00002221 case CodeCompletionContext::CCC_SelectorName:
Douglas Gregor1a480c42010-08-27 17:35:51 +00002222 case CodeCompletionContext::CCC_TypeQualifiers:
Douglas Gregor52779fb2010-09-23 23:01:17 +00002223 case CodeCompletionContext::CCC_Other:
Douglas Gregor5c722c702011-02-18 23:30:37 +00002224 case CodeCompletionContext::CCC_OtherWithMacros:
Douglas Gregor3da626b2011-07-07 16:03:39 +00002225 case CodeCompletionContext::CCC_ObjCInstanceMessage:
2226 case CodeCompletionContext::CCC_ObjCClassMessage:
2227 case CodeCompletionContext::CCC_ObjCCategoryName:
Douglas Gregor721f3592010-08-25 18:41:16 +00002228 // We're looking for nothing, or we're looking for names that cannot
2229 // be hidden.
Douglas Gregor5f808c22010-08-16 21:18:39 +00002230 return;
2231 }
2232
John McCall0a2c5e22010-08-25 06:19:51 +00002233 typedef CodeCompletionResult Result;
Douglas Gregor5f808c22010-08-16 21:18:39 +00002234 for (unsigned I = 0; I != NumResults; ++I) {
2235 if (Results[I].Kind != Result::RK_Declaration)
2236 continue;
2237
2238 unsigned IDNS
2239 = Results[I].Declaration->getUnderlyingDecl()->getIdentifierNamespace();
2240
2241 bool Hiding = false;
2242 if (OnlyTagNames)
2243 Hiding = (IDNS & Decl::IDNS_Tag);
2244 else {
2245 unsigned HiddenIDNS = (Decl::IDNS_Type | Decl::IDNS_Member |
Douglas Gregora5fb7c32010-08-16 23:05:20 +00002246 Decl::IDNS_Namespace | Decl::IDNS_Ordinary |
2247 Decl::IDNS_NonMemberOperator);
David Blaikie4e4d0842012-03-11 07:00:24 +00002248 if (Ctx.getLangOpts().CPlusPlus)
Douglas Gregor5f808c22010-08-16 21:18:39 +00002249 HiddenIDNS |= Decl::IDNS_Tag;
2250 Hiding = (IDNS & HiddenIDNS);
2251 }
2252
2253 if (!Hiding)
2254 continue;
2255
2256 DeclarationName Name = Results[I].Declaration->getDeclName();
2257 if (IdentifierInfo *Identifier = Name.getAsIdentifierInfo())
2258 HiddenNames.insert(Identifier->getName());
2259 else
2260 HiddenNames.insert(Name.getAsString());
2261 }
2262}
2263
2264
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002265void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &S,
2266 CodeCompletionContext Context,
John McCall0a2c5e22010-08-25 06:19:51 +00002267 CodeCompletionResult *Results,
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002268 unsigned NumResults) {
2269 // Merge the results we were given with the results we cached.
2270 bool AddedResult = false;
Richard Smith026b3582012-08-14 03:13:00 +00002271 uint64_t InContexts =
2272 Context.getKind() == CodeCompletionContext::CCC_Recovery
2273 ? NormalContexts : (1LL << Context.getKind());
Douglas Gregor5f808c22010-08-16 21:18:39 +00002274 // Contains the set of names that are hidden by "local" completion results.
Ted Kremenekc198f612010-11-07 06:11:36 +00002275 llvm::StringSet<llvm::BumpPtrAllocator> HiddenNames;
John McCall0a2c5e22010-08-25 06:19:51 +00002276 typedef CodeCompletionResult Result;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002277 SmallVector<Result, 8> AllResults;
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002278 for (ASTUnit::cached_completion_iterator
Douglas Gregor5535d572010-08-16 21:23:13 +00002279 C = AST.cached_completion_begin(),
2280 CEnd = AST.cached_completion_end();
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002281 C != CEnd; ++C) {
2282 // If the context we are in matches any of the contexts we are
2283 // interested in, we'll add this result.
2284 if ((C->ShowInContexts & InContexts) == 0)
2285 continue;
2286
2287 // If we haven't added any results previously, do so now.
2288 if (!AddedResult) {
Douglas Gregor5f808c22010-08-16 21:18:39 +00002289 CalculateHiddenNames(Context, Results, NumResults, S.Context,
2290 HiddenNames);
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002291 AllResults.insert(AllResults.end(), Results, Results + NumResults);
2292 AddedResult = true;
2293 }
2294
Douglas Gregor5f808c22010-08-16 21:18:39 +00002295 // Determine whether this global completion result is hidden by a local
2296 // completion result. If so, skip it.
2297 if (C->Kind != CXCursor_MacroDefinition &&
2298 HiddenNames.count(C->Completion->getTypedText()))
2299 continue;
2300
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002301 // Adjust priority based on similar type classes.
2302 unsigned Priority = C->Priority;
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002303 CodeCompletionString *Completion = C->Completion;
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002304 if (!Context.getPreferredType().isNull()) {
2305 if (C->Kind == CXCursor_MacroDefinition) {
2306 Priority = getMacroUsagePriority(C->Completion->getTypedText(),
David Blaikie4e4d0842012-03-11 07:00:24 +00002307 S.getLangOpts(),
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002308 Context.getPreferredType()->isAnyPointerType());
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002309 } else if (C->Type) {
2310 CanQualType Expected
Douglas Gregor5535d572010-08-16 21:23:13 +00002311 = S.Context.getCanonicalType(
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002312 Context.getPreferredType().getUnqualifiedType());
2313 SimplifiedTypeClass ExpectedSTC = getSimplifiedTypeClass(Expected);
2314 if (ExpectedSTC == C->TypeClass) {
2315 // We know this type is similar; check for an exact match.
2316 llvm::StringMap<unsigned> &CachedCompletionTypes
Douglas Gregor5535d572010-08-16 21:23:13 +00002317 = AST.getCachedCompletionTypes();
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002318 llvm::StringMap<unsigned>::iterator Pos
Douglas Gregor5535d572010-08-16 21:23:13 +00002319 = CachedCompletionTypes.find(QualType(Expected).getAsString());
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002320 if (Pos != CachedCompletionTypes.end() && Pos->second == C->Type)
2321 Priority /= CCF_ExactTypeMatch;
2322 else
2323 Priority /= CCF_SimilarTypeMatch;
2324 }
2325 }
2326 }
2327
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002328 // Adjust the completion string, if required.
2329 if (C->Kind == CXCursor_MacroDefinition &&
2330 Context.getKind() == CodeCompletionContext::CCC_MacroNameUse) {
2331 // Create a new code-completion string that just contains the
2332 // macro name, without its arguments.
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00002333 CodeCompletionBuilder Builder(getAllocator(), getCodeCompletionTUInfo(),
2334 CCP_CodePattern, C->Availability);
Douglas Gregor218937c2011-02-01 19:23:04 +00002335 Builder.AddTypedTextChunk(C->Completion->getTypedText());
Douglas Gregor4125c372010-08-25 18:03:13 +00002336 Priority = CCP_CodePattern;
Douglas Gregor218937c2011-02-01 19:23:04 +00002337 Completion = Builder.TakeString();
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002338 }
2339
Argyrios Kyrtzidisc04bb922012-09-27 00:24:09 +00002340 AllResults.push_back(Result(Completion, Priority, C->Kind,
Douglas Gregor58ddb602010-08-23 23:00:57 +00002341 C->Availability));
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002342 }
2343
2344 // If we did not add any cached completion results, just forward the
2345 // results we were given to the next consumer.
2346 if (!AddedResult) {
2347 Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
2348 return;
2349 }
Douglas Gregor1e5e6682010-08-26 13:48:20 +00002350
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002351 Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
2352 AllResults.size());
2353}
2354
2355
2356
Chris Lattner5f9e2722011-07-23 10:55:15 +00002357void ASTUnit::CodeComplete(StringRef File, unsigned Line, unsigned Column,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002358 RemappedFile *RemappedFiles,
2359 unsigned NumRemappedFiles,
Douglas Gregorcee235c2010-08-05 09:09:23 +00002360 bool IncludeMacros,
2361 bool IncludeCodePatterns,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002362 bool IncludeBriefComments,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002363 CodeCompleteConsumer &Consumer,
David Blaikied6471f72011-09-25 23:23:43 +00002364 DiagnosticsEngine &Diag, LangOptions &LangOpts,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002365 SourceManager &SourceMgr, FileManager &FileMgr,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002366 SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
2367 SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers) {
Ted Kremenek4f327862011-03-21 18:40:17 +00002368 if (!Invocation)
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002369 return;
2370
Douglas Gregor213f18b2010-10-28 15:44:59 +00002371 SimpleTimer CompletionTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00002372 CompletionTimer.setOutput("Code completion @ " + File + ":" +
Chris Lattner5f9e2722011-07-23 10:55:15 +00002373 Twine(Line) + ":" + Twine(Column));
Douglas Gregordf95a132010-08-09 20:45:32 +00002374
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00002375 IntrusiveRefCntPtr<CompilerInvocation>
Ted Kremenek4f327862011-03-21 18:40:17 +00002376 CCInvocation(new CompilerInvocation(*Invocation));
2377
2378 FrontendOptions &FrontendOpts = CCInvocation->getFrontendOpts();
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002379 CodeCompleteOptions &CodeCompleteOpts = FrontendOpts.CodeCompleteOpts;
Ted Kremenek4f327862011-03-21 18:40:17 +00002380 PreprocessorOptions &PreprocessorOpts = CCInvocation->getPreprocessorOpts();
Douglas Gregorcee235c2010-08-05 09:09:23 +00002381
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002382 CodeCompleteOpts.IncludeMacros = IncludeMacros &&
2383 CachedCompletionResults.empty();
2384 CodeCompleteOpts.IncludeCodePatterns = IncludeCodePatterns;
2385 CodeCompleteOpts.IncludeGlobals = CachedCompletionResults.empty();
2386 CodeCompleteOpts.IncludeBriefComments = IncludeBriefComments;
2387
2388 assert(IncludeBriefComments == this->IncludeBriefCommentsInCodeCompletion);
2389
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002390 FrontendOpts.CodeCompletionAt.FileName = File;
2391 FrontendOpts.CodeCompletionAt.Line = Line;
2392 FrontendOpts.CodeCompletionAt.Column = Column;
2393
2394 // Set the language options appropriately.
Ted Kremenekd3b74d92011-11-17 23:01:24 +00002395 LangOpts = *CCInvocation->getLangOpts();
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002396
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00002397 OwningPtr<CompilerInstance> Clang(new CompilerInstance());
Ted Kremenek03201fb2011-03-21 18:40:07 +00002398
2399 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00002400 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
2401 CICleanup(Clang.get());
Ted Kremenek03201fb2011-03-21 18:40:07 +00002402
Ted Kremenek4f327862011-03-21 18:40:17 +00002403 Clang->setInvocation(&*CCInvocation);
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00002404 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002405
2406 // Set up diagnostics, capturing any diagnostics produced.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002407 Clang->setDiagnostics(&Diag);
Ted Kremenek4f327862011-03-21 18:40:17 +00002408 ProcessWarningOptions(Diag, CCInvocation->getDiagnosticOpts());
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002409 CaptureDroppedDiagnostics Capture(true,
Ted Kremenek03201fb2011-03-21 18:40:07 +00002410 Clang->getDiagnostics(),
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002411 StoredDiagnostics);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002412
2413 // Create the target instance.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002414 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
Douglas Gregor49a87542012-11-16 04:24:59 +00002415 &Clang->getTargetOpts()));
Ted Kremenek03201fb2011-03-21 18:40:07 +00002416 if (!Clang->hasTarget()) {
Ted Kremenek4f327862011-03-21 18:40:17 +00002417 Clang->setInvocation(0);
Douglas Gregorbdbb0042010-08-18 22:29:43 +00002418 return;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002419 }
2420
2421 // Inform the target of the language options.
2422 //
2423 // FIXME: We shouldn't need to do this, the target should be immutable once
2424 // created. This complexity should be lifted elsewhere.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002425 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002426
Ted Kremenek03201fb2011-03-21 18:40:07 +00002427 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002428 "Invocation must have exactly one source file!");
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00002429 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002430 "FIXME: AST inputs not yet supported here!");
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00002431 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002432 "IR inputs not support here!");
2433
2434
2435 // Use the source and file managers that we were given.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002436 Clang->setFileManager(&FileMgr);
2437 Clang->setSourceManager(&SourceMgr);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002438
2439 // Remap files.
2440 PreprocessorOpts.clearRemappedFiles();
Douglas Gregorb75d3df2010-08-04 17:07:00 +00002441 PreprocessorOpts.RetainRemappedFileBuffers = true;
Douglas Gregor2283d792010-08-20 00:59:43 +00002442 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00002443 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
2444 if (const llvm::MemoryBuffer *
2445 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
2446 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first, memBuf);
2447 OwnedBuffers.push_back(memBuf);
2448 } else {
2449 const char *fname = fileOrBuf.get<const char *>();
2450 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first, fname);
2451 }
Douglas Gregor2283d792010-08-20 00:59:43 +00002452 }
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002453
Douglas Gregor87c08a52010-08-13 22:48:40 +00002454 // Use the code completion consumer we were given, but adding any cached
2455 // code-completion results.
Douglas Gregor7f946ad2010-11-29 16:13:56 +00002456 AugmentedCodeCompleteConsumer *AugmentedConsumer
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002457 = new AugmentedCodeCompleteConsumer(*this, Consumer, CodeCompleteOpts);
Ted Kremenek03201fb2011-03-21 18:40:07 +00002458 Clang->setCodeCompletionConsumer(AugmentedConsumer);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002459
Douglas Gregordf95a132010-08-09 20:45:32 +00002460 // If we have a precompiled preamble, try to use it. We only allow
2461 // the use of the precompiled preamble if we're if the completion
2462 // point is within the main file, after the end of the precompiled
2463 // preamble.
2464 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Ted Kremenek1872b312011-10-27 17:55:18 +00002465 if (!getPreambleFile(this).empty()) {
Douglas Gregordf95a132010-08-09 20:45:32 +00002466 using llvm::sys::FileStatus;
2467 llvm::sys::PathWithStatus CompleteFilePath(File);
2468 llvm::sys::PathWithStatus MainPath(OriginalSourceFile);
2469 if (const FileStatus *CompleteFileStatus = CompleteFilePath.getFileStatus())
2470 if (const FileStatus *MainStatus = MainPath.getFileStatus())
Argyrios Kyrtzidisc8c97a02011-09-04 03:32:04 +00002471 if (CompleteFileStatus->getUniqueID() == MainStatus->getUniqueID() &&
2472 Line > 1)
Douglas Gregor2283d792010-08-20 00:59:43 +00002473 OverrideMainBuffer
Ted Kremenek4f327862011-03-21 18:40:17 +00002474 = getMainBufferWithPrecompiledPreamble(*CCInvocation, false,
Douglas Gregorc9c29a82010-08-25 18:04:15 +00002475 Line - 1);
Douglas Gregordf95a132010-08-09 20:45:32 +00002476 }
2477
2478 // If the main file has been overridden due to the use of a preamble,
2479 // make that override happen and introduce the preamble.
2480 if (OverrideMainBuffer) {
2481 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
2482 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
2483 PreprocessorOpts.PrecompiledPreambleBytes.second
2484 = PreambleEndsAtStartOfLine;
Ted Kremenek1872b312011-10-27 17:55:18 +00002485 PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
Douglas Gregordf95a132010-08-09 20:45:32 +00002486 PreprocessorOpts.DisablePCHValidation = true;
2487
Douglas Gregor2283d792010-08-20 00:59:43 +00002488 OwnedBuffers.push_back(OverrideMainBuffer);
Douglas Gregorf128fed2010-08-20 00:02:33 +00002489 } else {
2490 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
2491 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregordf95a132010-08-09 20:45:32 +00002492 }
2493
Argyrios Kyrtzidise50904f2012-11-02 22:18:44 +00002494 // Disable the preprocessing record if modules are not enabled.
2495 if (!Clang->getLangOpts().Modules)
2496 PreprocessorOpts.DetailedRecord = false;
Douglas Gregordca8ee82011-05-06 16:33:08 +00002497
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00002498 OwningPtr<SyntaxOnlyAction> Act;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002499 Act.reset(new SyntaxOnlyAction);
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00002500 if (Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002501 Act->Execute();
2502 Act->EndSourceFile();
2503 }
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002504}
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002505
Argyrios Kyrtzidise6d22022012-09-26 16:39:46 +00002506bool ASTUnit::Save(StringRef File) {
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002507 // Write to a temporary file and later rename it to the actual file, to avoid
2508 // possible race conditions.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002509 SmallString<128> TempPath;
Argyrios Kyrtzidis7e909852011-07-28 00:45:10 +00002510 TempPath = File;
2511 TempPath += "-%%%%%%%%";
2512 int fd;
2513 if (llvm::sys::fs::unique_file(TempPath.str(), fd, TempPath,
2514 /*makeAbsolute=*/false))
Argyrios Kyrtzidise6d22022012-09-26 16:39:46 +00002515 return true;
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002516
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002517 // FIXME: Can we somehow regenerate the stat cache here, or do we need to
2518 // unconditionally create a stat cache when we parse the file?
Argyrios Kyrtzidis7e909852011-07-28 00:45:10 +00002519 llvm::raw_fd_ostream Out(fd, /*shouldClose=*/true);
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00002520
2521 serialize(Out);
2522 Out.close();
Argyrios Kyrtzidis4bd26542012-03-13 02:17:06 +00002523 if (Out.has_error()) {
2524 Out.clear_error();
Argyrios Kyrtzidise6d22022012-09-26 16:39:46 +00002525 return true;
Argyrios Kyrtzidis4bd26542012-03-13 02:17:06 +00002526 }
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002527
Rafael Espindola8d2a7012011-12-25 01:18:52 +00002528 if (llvm::sys::fs::rename(TempPath.str(), File)) {
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002529 bool exists;
2530 llvm::sys::fs::remove(TempPath.str(), exists);
Argyrios Kyrtzidise6d22022012-09-26 16:39:46 +00002531 return true;
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002532 }
2533
Argyrios Kyrtzidise6d22022012-09-26 16:39:46 +00002534 return false;
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00002535}
2536
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +00002537static bool serializeUnit(ASTWriter &Writer,
2538 SmallVectorImpl<char> &Buffer,
2539 Sema &S,
2540 bool hasErrors,
2541 raw_ostream &OS) {
Argyrios Kyrtzidis4182ed62012-10-31 20:59:50 +00002542 Writer.WriteAST(S, std::string(), 0, "", hasErrors);
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +00002543
2544 // Write the generated bitstream to "Out".
2545 if (!Buffer.empty())
2546 OS.write(Buffer.data(), Buffer.size());
2547
2548 return false;
2549}
2550
Chris Lattner5f9e2722011-07-23 10:55:15 +00002551bool ASTUnit::serialize(raw_ostream &OS) {
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +00002552 bool hasErrors = getDiagnostics().hasErrorOccurred();
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00002553
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +00002554 if (WriterData)
2555 return serializeUnit(WriterData->Writer, WriterData->Buffer,
2556 getSema(), hasErrors, OS);
2557
Daniel Dunbar8d6ff022012-02-29 20:31:23 +00002558 SmallString<128> Buffer;
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002559 llvm::BitstreamWriter Stream(Buffer);
Sebastian Redla4232eb2010-08-18 23:56:21 +00002560 ASTWriter Writer(Stream);
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +00002561 return serializeUnit(Writer, Buffer, getSema(), hasErrors, OS);
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002562}
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002563
2564typedef ContinuousRangeMap<unsigned, int, 2> SLocRemap;
2565
2566static void TranslateSLoc(SourceLocation &L, SLocRemap &Remap) {
2567 unsigned Raw = L.getRawEncoding();
2568 const unsigned MacroBit = 1U << 31;
2569 L = SourceLocation::getFromRawEncoding((Raw & MacroBit) |
2570 ((Raw & ~MacroBit) + Remap.find(Raw & ~MacroBit)->second));
2571}
2572
2573void ASTUnit::TranslateStoredDiagnostics(
2574 ASTReader *MMan,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002575 StringRef ModName,
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002576 SourceManager &SrcMgr,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002577 const SmallVectorImpl<StoredDiagnostic> &Diags,
2578 SmallVectorImpl<StoredDiagnostic> &Out) {
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002579 // The stored diagnostic has the old source manager in it; update
2580 // the locations to refer into the new source manager. We also need to remap
2581 // all the locations to the new view. This includes the diag location, any
2582 // associated source ranges, and the source ranges of associated fix-its.
2583 // FIXME: There should be a cleaner way to do this.
2584
Chris Lattner5f9e2722011-07-23 10:55:15 +00002585 SmallVector<StoredDiagnostic, 4> Result;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002586 Result.reserve(Diags.size());
2587 assert(MMan && "Don't have a module manager");
Douglas Gregor1a4761e2011-11-30 23:21:26 +00002588 serialization::ModuleFile *Mod = MMan->ModuleMgr.lookup(ModName);
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002589 assert(Mod && "Don't have preamble module");
2590 SLocRemap &Remap = Mod->SLocRemap;
2591 for (unsigned I = 0, N = Diags.size(); I != N; ++I) {
2592 // Rebuild the StoredDiagnostic.
2593 const StoredDiagnostic &SD = Diags[I];
2594 SourceLocation L = SD.getLocation();
2595 TranslateSLoc(L, Remap);
2596 FullSourceLoc Loc(L, SrcMgr);
2597
Chris Lattner5f9e2722011-07-23 10:55:15 +00002598 SmallVector<CharSourceRange, 4> Ranges;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002599 Ranges.reserve(SD.range_size());
2600 for (StoredDiagnostic::range_iterator I = SD.range_begin(),
2601 E = SD.range_end();
2602 I != E; ++I) {
2603 SourceLocation BL = I->getBegin();
2604 TranslateSLoc(BL, Remap);
2605 SourceLocation EL = I->getEnd();
2606 TranslateSLoc(EL, Remap);
2607 Ranges.push_back(CharSourceRange(SourceRange(BL, EL), I->isTokenRange()));
2608 }
2609
Chris Lattner5f9e2722011-07-23 10:55:15 +00002610 SmallVector<FixItHint, 2> FixIts;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002611 FixIts.reserve(SD.fixit_size());
2612 for (StoredDiagnostic::fixit_iterator I = SD.fixit_begin(),
2613 E = SD.fixit_end();
2614 I != E; ++I) {
2615 FixIts.push_back(FixItHint());
2616 FixItHint &FH = FixIts.back();
2617 FH.CodeToInsert = I->CodeToInsert;
2618 SourceLocation BL = I->RemoveRange.getBegin();
2619 TranslateSLoc(BL, Remap);
2620 SourceLocation EL = I->RemoveRange.getEnd();
2621 TranslateSLoc(EL, Remap);
2622 FH.RemoveRange = CharSourceRange(SourceRange(BL, EL),
2623 I->RemoveRange.isTokenRange());
2624 }
2625
2626 Result.push_back(StoredDiagnostic(SD.getLevel(), SD.getID(),
2627 SD.getMessage(), Loc, Ranges, FixIts));
2628 }
2629 Result.swap(Out);
2630}
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002631
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +00002632static inline bool compLocDecl(std::pair<unsigned, Decl *> L,
2633 std::pair<unsigned, Decl *> R) {
2634 return L.first < R.first;
2635}
2636
2637void ASTUnit::addFileLevelDecl(Decl *D) {
2638 assert(D);
Douglas Gregor66e87002011-11-07 18:53:57 +00002639
2640 // We only care about local declarations.
2641 if (D->isFromASTFile())
2642 return;
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +00002643
2644 SourceManager &SM = *SourceMgr;
2645 SourceLocation Loc = D->getLocation();
2646 if (Loc.isInvalid() || !SM.isLocalSourceLocation(Loc))
2647 return;
2648
2649 // We only keep track of the file-level declarations of each file.
2650 if (!D->getLexicalDeclContext()->isFileContext())
2651 return;
2652
2653 SourceLocation FileLoc = SM.getFileLoc(Loc);
2654 assert(SM.isLocalSourceLocation(FileLoc));
2655 FileID FID;
2656 unsigned Offset;
2657 llvm::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc);
2658 if (FID.isInvalid())
2659 return;
2660
2661 LocDeclsTy *&Decls = FileDecls[FID];
2662 if (!Decls)
2663 Decls = new LocDeclsTy();
2664
2665 std::pair<unsigned, Decl *> LocDecl(Offset, D);
2666
2667 if (Decls->empty() || Decls->back().first <= Offset) {
2668 Decls->push_back(LocDecl);
2669 return;
2670 }
2671
2672 LocDeclsTy::iterator
2673 I = std::upper_bound(Decls->begin(), Decls->end(), LocDecl, compLocDecl);
2674
2675 Decls->insert(I, LocDecl);
2676}
2677
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +00002678void ASTUnit::findFileRegionDecls(FileID File, unsigned Offset, unsigned Length,
2679 SmallVectorImpl<Decl *> &Decls) {
2680 if (File.isInvalid())
2681 return;
2682
2683 if (SourceMgr->isLoadedFileID(File)) {
2684 assert(Ctx->getExternalSource() && "No external source!");
2685 return Ctx->getExternalSource()->FindFileRegionDecls(File, Offset, Length,
2686 Decls);
2687 }
2688
2689 FileDeclsTy::iterator I = FileDecls.find(File);
2690 if (I == FileDecls.end())
2691 return;
2692
2693 LocDeclsTy &LocDecls = *I->second;
2694 if (LocDecls.empty())
2695 return;
2696
2697 LocDeclsTy::iterator
2698 BeginIt = std::lower_bound(LocDecls.begin(), LocDecls.end(),
2699 std::make_pair(Offset, (Decl*)0), compLocDecl);
2700 if (BeginIt != LocDecls.begin())
2701 --BeginIt;
2702
Argyrios Kyrtzidisc14a03d2011-11-23 20:27:36 +00002703 // If we are pointing at a top-level decl inside an objc container, we need
2704 // to backtrack until we find it otherwise we will fail to report that the
2705 // region overlaps with an objc container.
2706 while (BeginIt != LocDecls.begin() &&
2707 BeginIt->second->isTopLevelDeclInObjCContainer())
2708 --BeginIt;
2709
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +00002710 LocDeclsTy::iterator
2711 EndIt = std::upper_bound(LocDecls.begin(), LocDecls.end(),
2712 std::make_pair(Offset+Length, (Decl*)0),
2713 compLocDecl);
2714 if (EndIt != LocDecls.end())
2715 ++EndIt;
2716
2717 for (LocDeclsTy::iterator DIt = BeginIt; DIt != EndIt; ++DIt)
2718 Decls.push_back(DIt->second);
2719}
2720
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002721SourceLocation ASTUnit::getLocation(const FileEntry *File,
2722 unsigned Line, unsigned Col) const {
2723 const SourceManager &SM = getSourceManager();
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00002724 SourceLocation Loc = SM.translateFileLineCol(File, Line, Col);
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002725 return SM.getMacroArgExpandedLocation(Loc);
2726}
2727
2728SourceLocation ASTUnit::getLocation(const FileEntry *File,
2729 unsigned Offset) const {
2730 const SourceManager &SM = getSourceManager();
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00002731 SourceLocation FileLoc = SM.translateFileLineCol(File, 1, 1);
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002732 return SM.getMacroArgExpandedLocation(FileLoc.getLocWithOffset(Offset));
2733}
2734
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00002735/// \brief If \arg Loc is a loaded location from the preamble, returns
2736/// the corresponding local location of the main file, otherwise it returns
2737/// \arg Loc.
2738SourceLocation ASTUnit::mapLocationFromPreamble(SourceLocation Loc) {
2739 FileID PreambleID;
2740 if (SourceMgr)
2741 PreambleID = SourceMgr->getPreambleFileID();
2742
2743 if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2744 return Loc;
2745
2746 unsigned Offs;
2747 if (SourceMgr->isInFileID(Loc, PreambleID, &Offs) && Offs < Preamble.size()) {
2748 SourceLocation FileLoc
2749 = SourceMgr->getLocForStartOfFile(SourceMgr->getMainFileID());
2750 return FileLoc.getLocWithOffset(Offs);
2751 }
2752
2753 return Loc;
2754}
2755
2756/// \brief If \arg Loc is a local location of the main file but inside the
2757/// preamble chunk, returns the corresponding loaded location from the
2758/// preamble, otherwise it returns \arg Loc.
2759SourceLocation ASTUnit::mapLocationToPreamble(SourceLocation Loc) {
2760 FileID PreambleID;
2761 if (SourceMgr)
2762 PreambleID = SourceMgr->getPreambleFileID();
2763
2764 if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2765 return Loc;
2766
2767 unsigned Offs;
2768 if (SourceMgr->isInFileID(Loc, SourceMgr->getMainFileID(), &Offs) &&
2769 Offs < Preamble.size()) {
2770 SourceLocation FileLoc = SourceMgr->getLocForStartOfFile(PreambleID);
2771 return FileLoc.getLocWithOffset(Offs);
2772 }
2773
2774 return Loc;
2775}
2776
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00002777bool ASTUnit::isInPreambleFileID(SourceLocation Loc) {
2778 FileID FID;
2779 if (SourceMgr)
2780 FID = SourceMgr->getPreambleFileID();
2781
2782 if (Loc.isInvalid() || FID.isInvalid())
2783 return false;
2784
2785 return SourceMgr->isInFileID(Loc, FID);
2786}
2787
2788bool ASTUnit::isInMainFileID(SourceLocation Loc) {
2789 FileID FID;
2790 if (SourceMgr)
2791 FID = SourceMgr->getMainFileID();
2792
2793 if (Loc.isInvalid() || FID.isInvalid())
2794 return false;
2795
2796 return SourceMgr->isInFileID(Loc, FID);
2797}
2798
2799SourceLocation ASTUnit::getEndOfPreambleFileID() {
2800 FileID FID;
2801 if (SourceMgr)
2802 FID = SourceMgr->getPreambleFileID();
2803
2804 if (FID.isInvalid())
2805 return SourceLocation();
2806
2807 return SourceMgr->getLocForEndOfFile(FID);
2808}
2809
2810SourceLocation ASTUnit::getStartOfMainFileID() {
2811 FileID FID;
2812 if (SourceMgr)
2813 FID = SourceMgr->getMainFileID();
2814
2815 if (FID.isInvalid())
2816 return SourceLocation();
2817
2818 return SourceMgr->getLocForStartOfFile(FID);
2819}
2820
Argyrios Kyrtzidis632dcc92012-10-02 16:10:51 +00002821std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
2822ASTUnit::getLocalPreprocessingEntities() const {
2823 if (isMainFileAST()) {
2824 serialization::ModuleFile &
2825 Mod = Reader->getModuleManager().getPrimaryModule();
2826 return Reader->getModulePreprocessedEntities(Mod);
2827 }
2828
2829 if (PreprocessingRecord *PPRec = PP->getPreprocessingRecord())
2830 return std::make_pair(PPRec->local_begin(), PPRec->local_end());
2831
2832 return std::make_pair(PreprocessingRecord::iterator(),
2833 PreprocessingRecord::iterator());
2834}
2835
Argyrios Kyrtzidis95c579c2012-10-03 01:58:28 +00002836bool ASTUnit::visitLocalTopLevelDecls(void *context, DeclVisitorFn Fn) {
Argyrios Kyrtzidis2093e0b2012-10-02 21:09:13 +00002837 if (isMainFileAST()) {
2838 serialization::ModuleFile &
2839 Mod = Reader->getModuleManager().getPrimaryModule();
2840 ASTReader::ModuleDeclIterator MDI, MDE;
2841 llvm::tie(MDI, MDE) = Reader->getModuleFileLevelDecls(Mod);
2842 for (; MDI != MDE; ++MDI) {
2843 if (!Fn(context, *MDI))
2844 return false;
2845 }
2846
2847 return true;
2848 }
2849
2850 for (ASTUnit::top_level_iterator TL = top_level_begin(),
2851 TLEnd = top_level_end();
2852 TL != TLEnd; ++TL) {
2853 if (!Fn(context, *TL))
2854 return false;
2855 }
2856
2857 return true;
2858}
2859
Argyrios Kyrtzidis3da76bf2012-10-03 21:05:51 +00002860namespace {
2861struct PCHLocatorInfo {
2862 serialization::ModuleFile *Mod;
2863 PCHLocatorInfo() : Mod(0) {}
2864};
2865}
2866
2867static bool PCHLocator(serialization::ModuleFile &M, void *UserData) {
2868 PCHLocatorInfo &Info = *static_cast<PCHLocatorInfo*>(UserData);
2869 switch (M.Kind) {
2870 case serialization::MK_Module:
2871 return true; // skip dependencies.
2872 case serialization::MK_PCH:
2873 Info.Mod = &M;
2874 return true; // found it.
2875 case serialization::MK_Preamble:
2876 return false; // look in dependencies.
2877 case serialization::MK_MainFile:
2878 return false; // look in dependencies.
2879 }
2880
2881 return true;
2882}
2883
2884const FileEntry *ASTUnit::getPCHFile() {
2885 if (!Reader)
2886 return 0;
2887
2888 PCHLocatorInfo Info;
2889 Reader->getModuleManager().visit(PCHLocator, &Info);
2890 if (Info.Mod)
2891 return Info.Mod->File;
2892
2893 return 0;
2894}
2895
Argyrios Kyrtzidis62288ed2012-10-10 02:12:47 +00002896bool ASTUnit::isModuleFile() {
2897 return isMainFileAST() && !ASTFileLangOpts.CurrentModule.empty();
2898}
2899
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002900void ASTUnit::PreambleData::countLines() const {
2901 NumLines = 0;
2902 if (empty())
2903 return;
2904
2905 for (std::vector<char>::const_iterator
2906 I = Buffer.begin(), E = Buffer.end(); I != E; ++I) {
2907 if (*I == '\n')
2908 ++NumLines;
2909 }
2910 if (Buffer.back() != '\n')
2911 ++NumLines;
2912}
Argyrios Kyrtzidisa696ece2011-10-10 21:57:12 +00002913
2914#ifndef NDEBUG
2915ASTUnit::ConcurrencyState::ConcurrencyState() {
2916 Mutex = new llvm::sys::MutexImpl(/*recursive=*/true);
2917}
2918
2919ASTUnit::ConcurrencyState::~ConcurrencyState() {
2920 delete static_cast<llvm::sys::MutexImpl *>(Mutex);
2921}
2922
2923void ASTUnit::ConcurrencyState::start() {
2924 bool acquired = static_cast<llvm::sys::MutexImpl *>(Mutex)->tryacquire();
2925 assert(acquired && "Concurrent access to ASTUnit!");
2926}
2927
2928void ASTUnit::ConcurrencyState::finish() {
2929 static_cast<llvm::sys::MutexImpl *>(Mutex)->release();
2930}
2931
2932#else // NDEBUG
2933
2934ASTUnit::ConcurrencyState::ConcurrencyState() {}
2935ASTUnit::ConcurrencyState::~ConcurrencyState() {}
2936void ASTUnit::ConcurrencyState::start() {}
2937void ASTUnit::ConcurrencyState::finish() {}
2938
2939#endif