blob: 0fd19b891594696633fb065fef8287f3772ff6d3 [file] [log] [blame]
Hans Wennborgdcfba332015-10-06 23:40:43 +00001//===--- ASTUnit.cpp - ASTUnit utility --------------------------*- C++ -*-===//
Argyrios Kyrtzidis3a08ec12009-06-20 08:27:14 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// ASTUnit Implementation.
11//
12//===----------------------------------------------------------------------===//
13
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000014#include "clang/Frontend/ASTUnit.h"
Daniel Dunbar764c0822009-12-01 09:51:01 +000015#include "clang/AST/ASTConsumer.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000016#include "clang/AST/ASTContext.h"
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000017#include "clang/AST/DeclVisitor.h"
18#include "clang/AST/StmtVisitor.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000019#include "clang/AST/TypeOrdering.h"
20#include "clang/Basic/Diagnostic.h"
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +000021#include "clang/Basic/MemoryBufferCache.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000022#include "clang/Basic/TargetInfo.h"
23#include "clang/Basic/TargetOptions.h"
Ben Langmuirc8130a72014-02-20 21:59:23 +000024#include "clang/Basic/VirtualFileSystem.h"
Daniel Dunbar764c0822009-12-01 09:51:01 +000025#include "clang/Frontend/CompilerInstance.h"
26#include "clang/Frontend/FrontendActions.h"
Daniel Dunbar55a17b62009-12-02 03:23:45 +000027#include "clang/Frontend/FrontendDiagnostic.h"
Daniel Dunbar764c0822009-12-01 09:51:01 +000028#include "clang/Frontend/FrontendOptions.h"
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +000029#include "clang/Frontend/MultiplexConsumer.h"
Douglas Gregor36e3b5c2010-10-11 21:37:58 +000030#include "clang/Frontend/Utils.h"
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000031#include "clang/Lex/HeaderSearch.h"
32#include "clang/Lex/Preprocessor.h"
Douglas Gregor1452ff12012-10-24 17:46:57 +000033#include "clang/Lex/PreprocessorOptions.h"
David Blaikie0a4e61f2013-09-13 18:32:52 +000034#include "clang/Sema/Sema.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000035#include "clang/Serialization/ASTReader.h"
36#include "clang/Serialization/ASTWriter.h"
Chris Lattnerce6c42f2011-03-23 04:04:01 +000037#include "llvm/ADT/ArrayRef.h"
Douglas Gregordf7a79a2011-02-16 18:16:54 +000038#include "llvm/ADT/StringExtras.h"
Douglas Gregor40a5a7d2010-08-16 23:08:34 +000039#include "llvm/ADT/StringSet.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000040#include "llvm/Support/CrashRecoveryContext.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000041#include "llvm/Support/Host.h"
42#include "llvm/Support/MemoryBuffer.h"
Argyrios Kyrtzidisebf01362011-10-10 21:57:12 +000043#include "llvm/Support/Mutex.h"
Ted Kremenekbd307a52011-10-27 19:44:25 +000044#include "llvm/Support/MutexGuard.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000045#include "llvm/Support/Timer.h"
46#include "llvm/Support/raw_ostream.h"
Benjamin Kramer4527fb22014-03-02 17:08:31 +000047#include <atomic>
Zhongxing Xu318e4032010-07-23 02:15:08 +000048#include <cstdio>
Chandler Carruth3a022472012-12-04 09:13:33 +000049#include <cstdlib>
Hans Wennborgdcfba332015-10-06 23:40:43 +000050
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000051using namespace clang;
52
Douglas Gregor16896c42010-10-28 15:44:59 +000053using llvm::TimeRecord;
54
55namespace {
56 class SimpleTimer {
57 bool WantTiming;
58 TimeRecord Start;
59 std::string Output;
60
Benjamin Kramerf2e5a912010-11-09 20:00:56 +000061 public:
Douglas Gregor1cbdd952010-11-01 13:48:43 +000062 explicit SimpleTimer(bool WantTiming) : WantTiming(WantTiming) {
Douglas Gregor16896c42010-10-28 15:44:59 +000063 if (WantTiming)
Benjamin Kramerf2e5a912010-11-09 20:00:56 +000064 Start = TimeRecord::getCurrentTime();
Douglas Gregor16896c42010-10-28 15:44:59 +000065 }
66
Chris Lattner0e62c1c2011-07-23 10:55:15 +000067 void setOutput(const Twine &Output) {
Douglas Gregor16896c42010-10-28 15:44:59 +000068 if (WantTiming)
Benjamin Kramerf2e5a912010-11-09 20:00:56 +000069 this->Output = Output.str();
Douglas Gregor16896c42010-10-28 15:44:59 +000070 }
71
Douglas Gregor16896c42010-10-28 15:44:59 +000072 ~SimpleTimer() {
73 if (WantTiming) {
74 TimeRecord Elapsed = TimeRecord::getCurrentTime();
75 Elapsed -= Start;
76 llvm::errs() << Output << ':';
77 Elapsed.print(Elapsed, llvm::errs());
78 llvm::errs() << '\n';
79 }
80 }
81 };
Ilya Biryukovaf69e402017-05-23 11:37:52 +000082
83 template <class T>
84 std::unique_ptr<T> valueOrNull(llvm::ErrorOr<std::unique_ptr<T>> Val) {
85 if (!Val)
86 return nullptr;
87 return std::move(*Val);
88 }
89
90 template <class T>
91 bool moveOnNoError(llvm::ErrorOr<T> Val, T &Output) {
92 if (!Val)
93 return false;
94 Output = std::move(*Val);
95 return true;
96 }
Ted Kremenek06b4f912011-10-27 17:55:18 +000097
Ilya Biryukov200b3282017-06-21 10:24:58 +000098/// \brief Get a source buffer for \p MainFilePath, handling all file-to-file
99/// and file-to-buffer remappings inside \p Invocation.
100static std::unique_ptr<llvm::MemoryBuffer>
101getBufferForFileHandlingRemapping(const CompilerInvocation &Invocation,
102 vfs::FileSystem *VFS,
103 StringRef FilePath) {
104 const auto &PreprocessorOpts = Invocation.getPreprocessorOpts();
Ted Kremenekbd307a52011-10-27 19:44:25 +0000105
Ilya Biryukov200b3282017-06-21 10:24:58 +0000106 // Try to determine if the main file has been remapped, either from the
107 // command line (to another file) or directly through the compiler
108 // invocation (to a memory buffer).
109 llvm::MemoryBuffer *Buffer = nullptr;
110 std::unique_ptr<llvm::MemoryBuffer> BufferOwner;
111 auto FileStatus = VFS->status(FilePath);
112 if (FileStatus) {
113 llvm::sys::fs::UniqueID MainFileID = FileStatus->getUniqueID();
Ted Kremenek06b4f912011-10-27 17:55:18 +0000114
Ilya Biryukov200b3282017-06-21 10:24:58 +0000115 // Check whether there is a file-file remapping of the main file
116 for (const auto &RF : PreprocessorOpts.RemappedFiles) {
117 std::string MPath(RF.first);
118 auto MPathStatus = VFS->status(MPath);
119 if (MPathStatus) {
120 llvm::sys::fs::UniqueID MID = MPathStatus->getUniqueID();
121 if (MainFileID == MID) {
122 // We found a remapping. Try to load the resulting, remapped source.
123 BufferOwner = valueOrNull(VFS->getBufferForFile(RF.second));
124 if (!BufferOwner)
125 return nullptr;
126 }
127 }
128 }
129
130 // Check whether there is a file-buffer remapping. It supercedes the
131 // file-file remapping.
132 for (const auto &RB : PreprocessorOpts.RemappedFileBuffers) {
133 std::string MPath(RB.first);
134 auto MPathStatus = VFS->status(MPath);
135 if (MPathStatus) {
136 llvm::sys::fs::UniqueID MID = MPathStatus->getUniqueID();
137 if (MainFileID == MID) {
138 // We found a remapping.
139 BufferOwner.reset();
140 Buffer = const_cast<llvm::MemoryBuffer *>(RB.second);
141 }
142 }
143 }
Ted Kremenek06b4f912011-10-27 17:55:18 +0000144 }
Ted Kremenek06b4f912011-10-27 17:55:18 +0000145
Ilya Biryukov200b3282017-06-21 10:24:58 +0000146 // If the main source file was not remapped, load it now.
147 if (!Buffer && !BufferOwner) {
148 BufferOwner = valueOrNull(VFS->getBufferForFile(FilePath));
149 if (!BufferOwner)
150 return nullptr;
Ted Kremenek06b4f912011-10-27 17:55:18 +0000151 }
Ted Kremenek06b4f912011-10-27 17:55:18 +0000152
Ilya Biryukov200b3282017-06-21 10:24:58 +0000153 if (BufferOwner)
154 return BufferOwner;
155 if (!Buffer)
156 return nullptr;
157 return llvm::MemoryBuffer::getMemBufferCopy(Buffer->getBuffer(), FilePath);
Ted Kremenek06b4f912011-10-27 17:55:18 +0000158}
Ted Kremenek06b4f912011-10-27 17:55:18 +0000159}
160
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000161struct ASTUnit::ASTWriterData {
162 SmallString<128> Buffer;
163 llvm::BitstreamWriter Stream;
164 ASTWriter Writer;
165
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +0000166 ASTWriterData(MemoryBufferCache &PCMCache)
167 : Stream(Buffer), Writer(Stream, Buffer, PCMCache, {}) {}
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000168};
169
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000170void ASTUnit::clearFileLevelDecls() {
Reid Kleckner588c9372014-02-19 23:44:52 +0000171 llvm::DeleteContainerSeconds(FileDecls);
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000172}
173
Douglas Gregorbb420ab2010-08-04 05:53:38 +0000174/// \brief After failing to build a precompiled preamble (due to
175/// errors in the source that occurs in the preamble), the number of
176/// reparses during which we'll skip even trying to precompile the
177/// preamble.
178const unsigned DefaultPreambleRebuildInterval = 5;
179
Douglas Gregor68dbaea2010-11-17 00:13:31 +0000180/// \brief Tracks the number of ASTUnit objects that are currently active.
181///
182/// Used for debugging purposes only.
Benjamin Kramer4527fb22014-03-02 17:08:31 +0000183static std::atomic<unsigned> ActiveASTUnitObjects;
Douglas Gregor68dbaea2010-11-17 00:13:31 +0000184
Douglas Gregord03e8232010-04-05 21:10:19 +0000185ASTUnit::ASTUnit(bool _MainFileIsAST)
Craig Topper49a27902014-05-22 04:46:25 +0000186 : Reader(nullptr), HadModuleLoaderFatalFailure(false),
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +0000187 OnlyLocalDecls(false), CaptureDiagnostics(false),
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +0000188 MainFileIsAST(_MainFileIsAST),
Douglas Gregor69f74f82011-08-25 22:30:56 +0000189 TUKind(TU_Complete), WantTiming(getenv("LIBCLANG_TIMING")),
Argyrios Kyrtzidis4954bc12011-03-05 01:03:48 +0000190 OwnsRemappedFileBuffers(true),
Douglas Gregor16896c42010-10-28 15:44:59 +0000191 NumStoredDiagnosticsFromDriver(0),
Rafael Espindola4674a872014-08-13 17:08:22 +0000192 PreambleRebuildCounter(0),
Rafael Espindolafa49c0b2014-08-13 16:47:00 +0000193 NumWarningsInPreamble(0),
Douglas Gregor2c8bd472010-08-17 00:40:40 +0000194 ShouldCacheCodeCompletionResults(false),
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +0000195 IncludeBriefCommentsInCodeCompletion(false), UserFilesAreVolatile(false),
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000196 CompletionCacheTopLevelHashValue(0),
197 PreambleTopLevelHashValue(0),
198 CurrentTopLevelHashValue(0),
Douglas Gregor4740c452010-08-19 00:45:44 +0000199 UnsafeToFree(false) {
Benjamin Kramer4527fb22014-03-02 17:08:31 +0000200 if (getenv("LIBCLANG_OBJTRACKING"))
201 fprintf(stderr, "+++ %u translation units\n", ++ActiveASTUnitObjects);
Douglas Gregor15ba0b32010-07-30 20:58:08 +0000202}
Douglas Gregord03e8232010-04-05 21:10:19 +0000203
Daniel Dunbar764c0822009-12-01 09:51:01 +0000204ASTUnit::~ASTUnit() {
Douglas Gregor6b930962013-05-03 22:58:43 +0000205 // If we loaded from an AST file, balance out the BeginSourceFile call.
206 if (MainFileIsAST && getDiagnostics().getClient()) {
207 getDiagnostics().getClient()->EndSourceFile();
208 }
209
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000210 clearFileLevelDecls();
211
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000212 // Free the buffers associated with remapped files. We are required to
213 // perform this operation here because we explicitly request that the
214 // compiler instance *not* free these buffers for each invocation of the
215 // parser.
David Blaikieea4395e2017-01-06 19:49:01 +0000216 if (Invocation && OwnsRemappedFileBuffers) {
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000217 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
Alp Toker1b070d22014-07-07 07:47:20 +0000218 for (const auto &RB : PPOpts.RemappedFileBuffers)
219 delete RB.second;
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000220 }
Douglas Gregora0734c52010-08-19 01:33:06 +0000221
Douglas Gregor16896c42010-10-28 15:44:59 +0000222 ClearCachedCompletionResults();
Douglas Gregor68dbaea2010-11-17 00:13:31 +0000223
Benjamin Kramer4527fb22014-03-02 17:08:31 +0000224 if (getenv("LIBCLANG_OBJTRACKING"))
225 fprintf(stderr, "--- %u translation units\n", --ActiveASTUnitObjects);
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000226}
227
David Blaikie41565462017-01-05 19:48:07 +0000228void ASTUnit::setPreprocessor(std::shared_ptr<Preprocessor> PP) {
229 this->PP = std::move(PP);
230}
Argyrios Kyrtzidisda6e0542012-01-17 18:48:07 +0000231
Douglas Gregor39982192010-08-15 06:18:01 +0000232/// \brief Determine the set of code-completion contexts in which this
233/// declaration should be shown.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000234static unsigned getDeclShowContexts(const NamedDecl *ND,
Douglas Gregor59cab552010-08-16 23:05:20 +0000235 const LangOptions &LangOpts,
236 bool &IsNestedNameSpecifier) {
237 IsNestedNameSpecifier = false;
238
Douglas Gregor39982192010-08-15 06:18:01 +0000239 if (isa<UsingShadowDecl>(ND))
240 ND = dyn_cast<NamedDecl>(ND->getUnderlyingDecl());
241 if (!ND)
242 return 0;
243
Richard Smith697cc9e2012-08-14 03:13:00 +0000244 uint64_t Contexts = 0;
Douglas Gregor39982192010-08-15 06:18:01 +0000245 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND) ||
Erik Verbruggenaa603c32017-08-22 10:54:40 +0000246 isa<ClassTemplateDecl>(ND) || isa<TemplateTemplateParmDecl>(ND)) {
Douglas Gregor39982192010-08-15 06:18:01 +0000247 // Types can appear in these contexts.
248 if (LangOpts.CPlusPlus || !isa<TagDecl>(ND))
Richard Smith697cc9e2012-08-14 03:13:00 +0000249 Contexts |= (1LL << CodeCompletionContext::CCC_TopLevel)
250 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
251 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
252 | (1LL << CodeCompletionContext::CCC_Statement)
253 | (1LL << CodeCompletionContext::CCC_Type)
254 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression);
Douglas Gregor39982192010-08-15 06:18:01 +0000255
256 // In C++, types can appear in expressions contexts (for functional casts).
257 if (LangOpts.CPlusPlus)
Richard Smith697cc9e2012-08-14 03:13:00 +0000258 Contexts |= (1LL << CodeCompletionContext::CCC_Expression);
Douglas Gregor39982192010-08-15 06:18:01 +0000259
260 // In Objective-C, message sends can send interfaces. In Objective-C++,
261 // all types are available due to functional casts.
262 if (LangOpts.CPlusPlus || isa<ObjCInterfaceDecl>(ND))
Richard Smith697cc9e2012-08-14 03:13:00 +0000263 Contexts |= (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver);
Douglas Gregor21325842011-07-07 16:03:39 +0000264
265 // In Objective-C, you can only be a subclass of another Objective-C class
266 if (isa<ObjCInterfaceDecl>(ND))
Richard Smith697cc9e2012-08-14 03:13:00 +0000267 Contexts |= (1LL << CodeCompletionContext::CCC_ObjCInterfaceName);
Douglas Gregor39982192010-08-15 06:18:01 +0000268
269 // Deal with tag names.
270 if (isa<EnumDecl>(ND)) {
Richard Smith697cc9e2012-08-14 03:13:00 +0000271 Contexts |= (1LL << CodeCompletionContext::CCC_EnumTag);
Douglas Gregor39982192010-08-15 06:18:01 +0000272
Douglas Gregor59cab552010-08-16 23:05:20 +0000273 // Part of the nested-name-specifier in C++0x.
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000274 if (LangOpts.CPlusPlus11)
Douglas Gregor59cab552010-08-16 23:05:20 +0000275 IsNestedNameSpecifier = true;
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000276 } else if (const RecordDecl *Record = dyn_cast<RecordDecl>(ND)) {
Douglas Gregor39982192010-08-15 06:18:01 +0000277 if (Record->isUnion())
Richard Smith697cc9e2012-08-14 03:13:00 +0000278 Contexts |= (1LL << CodeCompletionContext::CCC_UnionTag);
Douglas Gregor39982192010-08-15 06:18:01 +0000279 else
Richard Smith697cc9e2012-08-14 03:13:00 +0000280 Contexts |= (1LL << CodeCompletionContext::CCC_ClassOrStructTag);
Douglas Gregor39982192010-08-15 06:18:01 +0000281
Douglas Gregor39982192010-08-15 06:18:01 +0000282 if (LangOpts.CPlusPlus)
Douglas Gregor59cab552010-08-16 23:05:20 +0000283 IsNestedNameSpecifier = true;
Douglas Gregor0ac41382010-09-23 23:01:17 +0000284 } else if (isa<ClassTemplateDecl>(ND))
Douglas Gregor59cab552010-08-16 23:05:20 +0000285 IsNestedNameSpecifier = true;
Douglas Gregor39982192010-08-15 06:18:01 +0000286 } else if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
287 // Values can appear in these contexts.
Richard Smith697cc9e2012-08-14 03:13:00 +0000288 Contexts = (1LL << CodeCompletionContext::CCC_Statement)
289 | (1LL << CodeCompletionContext::CCC_Expression)
290 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
291 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver);
Douglas Gregor39982192010-08-15 06:18:01 +0000292 } else if (isa<ObjCProtocolDecl>(ND)) {
Richard Smith697cc9e2012-08-14 03:13:00 +0000293 Contexts = (1LL << CodeCompletionContext::CCC_ObjCProtocolName);
Douglas Gregor21325842011-07-07 16:03:39 +0000294 } else if (isa<ObjCCategoryDecl>(ND)) {
Richard Smith697cc9e2012-08-14 03:13:00 +0000295 Contexts = (1LL << CodeCompletionContext::CCC_ObjCCategoryName);
Douglas Gregor39982192010-08-15 06:18:01 +0000296 } else if (isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) {
Richard Smith697cc9e2012-08-14 03:13:00 +0000297 Contexts = (1LL << CodeCompletionContext::CCC_Namespace);
Douglas Gregor39982192010-08-15 06:18:01 +0000298
299 // Part of the nested-name-specifier.
Douglas Gregor59cab552010-08-16 23:05:20 +0000300 IsNestedNameSpecifier = true;
Douglas Gregor39982192010-08-15 06:18:01 +0000301 }
302
303 return Contexts;
304}
305
Douglas Gregorb14904c2010-08-13 22:48:40 +0000306void ASTUnit::CacheCodeCompletionResults() {
307 if (!TheSema)
308 return;
309
Douglas Gregor16896c42010-10-28 15:44:59 +0000310 SimpleTimer Timer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +0000311 Timer.setOutput("Cache global code completions for " + getMainFileName());
Douglas Gregorb14904c2010-08-13 22:48:40 +0000312
313 // Clear out the previous results.
314 ClearCachedCompletionResults();
315
316 // Gather the set of global code completions.
John McCall276321a2010-08-25 06:19:51 +0000317 typedef CodeCompletionResult Result;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000318 SmallVector<Result, 8> Results;
David Blaikieea4395e2017-01-06 19:49:01 +0000319 CachedCompletionAllocator = std::make_shared<GlobalCodeCompletionAllocator>();
Argyrios Kyrtzidis2bafa002012-11-16 03:34:57 +0000320 CodeCompletionTUInfo CCTUInfo(CachedCompletionAllocator);
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +0000321 TheSema->GatherGlobalCodeCompletions(*CachedCompletionAllocator,
Argyrios Kyrtzidis2bafa002012-11-16 03:34:57 +0000322 CCTUInfo, Results);
Douglas Gregorb14904c2010-08-13 22:48:40 +0000323
324 // Translate global code completions into cached completions.
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000325 llvm::DenseMap<CanQualType, unsigned> CompletionTypes;
Douglas Gregorc3425b12015-07-07 06:20:19 +0000326 CodeCompletionContext CCContext(CodeCompletionContext::CCC_TopLevel);
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000327
328 for (Result &R : Results) {
329 switch (R.Kind) {
Douglas Gregor39982192010-08-15 06:18:01 +0000330 case Result::RK_Declaration: {
Douglas Gregor59cab552010-08-16 23:05:20 +0000331 bool IsNestedNameSpecifier = false;
Douglas Gregor39982192010-08-15 06:18:01 +0000332 CachedCodeCompletionResult CachedResult;
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000333 CachedResult.Completion = R.CreateCodeCompletionString(
Douglas Gregorc3425b12015-07-07 06:20:19 +0000334 *TheSema, CCContext, *CachedCompletionAllocator, CCTUInfo,
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000335 IncludeBriefCommentsInCodeCompletion);
336 CachedResult.ShowInContexts = getDeclShowContexts(
337 R.Declaration, Ctx->getLangOpts(), IsNestedNameSpecifier);
338 CachedResult.Priority = R.Priority;
339 CachedResult.Kind = R.CursorKind;
340 CachedResult.Availability = R.Availability;
Douglas Gregor24747402010-08-16 16:46:30 +0000341
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000342 // Keep track of the type of this completion in an ASTContext-agnostic
343 // way.
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000344 QualType UsageType = getDeclUsageType(*Ctx, R.Declaration);
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000345 if (UsageType.isNull()) {
Douglas Gregor24747402010-08-16 16:46:30 +0000346 CachedResult.TypeClass = STC_Void;
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000347 CachedResult.Type = 0;
348 } else {
349 CanQualType CanUsageType
350 = Ctx->getCanonicalType(UsageType.getUnqualifiedType());
351 CachedResult.TypeClass = getSimplifiedTypeClass(CanUsageType);
352
353 // Determine whether we have already seen this type. If so, we save
354 // ourselves the work of formatting the type string by using the
355 // temporary, CanQualType-based hash table to find the associated value.
356 unsigned &TypeValue = CompletionTypes[CanUsageType];
357 if (TypeValue == 0) {
358 TypeValue = CompletionTypes.size();
359 CachedCompletionTypes[QualType(CanUsageType).getAsString()]
360 = TypeValue;
361 }
362
363 CachedResult.Type = TypeValue;
Douglas Gregor24747402010-08-16 16:46:30 +0000364 }
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000365
Douglas Gregor39982192010-08-15 06:18:01 +0000366 CachedCompletionResults.push_back(CachedResult);
Douglas Gregor59cab552010-08-16 23:05:20 +0000367
368 /// Handle nested-name-specifiers in C++.
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000369 if (TheSema->Context.getLangOpts().CPlusPlus && IsNestedNameSpecifier &&
370 !R.StartsNestedNameSpecifier) {
Douglas Gregor59cab552010-08-16 23:05:20 +0000371 // The contexts in which a nested-name-specifier can appear in C++.
Richard Smith697cc9e2012-08-14 03:13:00 +0000372 uint64_t NNSContexts
373 = (1LL << CodeCompletionContext::CCC_TopLevel)
374 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
375 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
376 | (1LL << CodeCompletionContext::CCC_Statement)
377 | (1LL << CodeCompletionContext::CCC_Expression)
378 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
379 | (1LL << CodeCompletionContext::CCC_EnumTag)
380 | (1LL << CodeCompletionContext::CCC_UnionTag)
381 | (1LL << CodeCompletionContext::CCC_ClassOrStructTag)
382 | (1LL << CodeCompletionContext::CCC_Type)
383 | (1LL << CodeCompletionContext::CCC_PotentiallyQualifiedName)
384 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression);
Douglas Gregor59cab552010-08-16 23:05:20 +0000385
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000386 if (isa<NamespaceDecl>(R.Declaration) ||
387 isa<NamespaceAliasDecl>(R.Declaration))
Richard Smith697cc9e2012-08-14 03:13:00 +0000388 NNSContexts |= (1LL << CodeCompletionContext::CCC_Namespace);
Douglas Gregor59cab552010-08-16 23:05:20 +0000389
390 if (unsigned RemainingContexts
391 = NNSContexts & ~CachedResult.ShowInContexts) {
392 // If there any contexts where this completion can be a
393 // nested-name-specifier but isn't already an option, create a
394 // nested-name-specifier completion.
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000395 R.StartsNestedNameSpecifier = true;
396 CachedResult.Completion = R.CreateCodeCompletionString(
Douglas Gregorc3425b12015-07-07 06:20:19 +0000397 *TheSema, CCContext, *CachedCompletionAllocator, CCTUInfo,
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000398 IncludeBriefCommentsInCodeCompletion);
Douglas Gregor59cab552010-08-16 23:05:20 +0000399 CachedResult.ShowInContexts = RemainingContexts;
400 CachedResult.Priority = CCP_NestedNameSpecifier;
401 CachedResult.TypeClass = STC_Void;
402 CachedResult.Type = 0;
403 CachedCompletionResults.push_back(CachedResult);
404 }
405 }
Douglas Gregorb14904c2010-08-13 22:48:40 +0000406 break;
Douglas Gregor39982192010-08-15 06:18:01 +0000407 }
408
Douglas Gregorb14904c2010-08-13 22:48:40 +0000409 case Result::RK_Keyword:
410 case Result::RK_Pattern:
411 // Ignore keywords and patterns; we don't care, since they are so
412 // easily regenerated.
413 break;
414
415 case Result::RK_Macro: {
416 CachedCodeCompletionResult CachedResult;
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000417 CachedResult.Completion = R.CreateCodeCompletionString(
Douglas Gregorc3425b12015-07-07 06:20:19 +0000418 *TheSema, CCContext, *CachedCompletionAllocator, CCTUInfo,
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000419 IncludeBriefCommentsInCodeCompletion);
Douglas Gregorb14904c2010-08-13 22:48:40 +0000420 CachedResult.ShowInContexts
Richard Smith697cc9e2012-08-14 03:13:00 +0000421 = (1LL << CodeCompletionContext::CCC_TopLevel)
422 | (1LL << CodeCompletionContext::CCC_ObjCInterface)
423 | (1LL << CodeCompletionContext::CCC_ObjCImplementation)
424 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
425 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
426 | (1LL << CodeCompletionContext::CCC_Statement)
427 | (1LL << CodeCompletionContext::CCC_Expression)
428 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
429 | (1LL << CodeCompletionContext::CCC_MacroNameUse)
430 | (1LL << CodeCompletionContext::CCC_PreprocessorExpression)
431 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
432 | (1LL << CodeCompletionContext::CCC_OtherWithMacros);
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000433
434 CachedResult.Priority = R.Priority;
435 CachedResult.Kind = R.CursorKind;
436 CachedResult.Availability = R.Availability;
Douglas Gregor6e240332010-08-16 16:18:59 +0000437 CachedResult.TypeClass = STC_Void;
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000438 CachedResult.Type = 0;
Douglas Gregorb14904c2010-08-13 22:48:40 +0000439 CachedCompletionResults.push_back(CachedResult);
440 break;
441 }
442 }
Douglas Gregorb14904c2010-08-13 22:48:40 +0000443 }
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000444
445 // Save the current top-level hash value.
446 CompletionCacheTopLevelHashValue = CurrentTopLevelHashValue;
Douglas Gregorb14904c2010-08-13 22:48:40 +0000447}
448
449void ASTUnit::ClearCachedCompletionResults() {
Douglas Gregorb14904c2010-08-13 22:48:40 +0000450 CachedCompletionResults.clear();
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000451 CachedCompletionTypes.clear();
Craig Topper49a27902014-05-22 04:46:25 +0000452 CachedCompletionAllocator = nullptr;
Douglas Gregorb14904c2010-08-13 22:48:40 +0000453}
454
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000455namespace {
456
Sebastian Redl2c499f62010-08-18 23:56:43 +0000457/// \brief Gathers information from ASTReader that will be used to initialize
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000458/// a Preprocessor.
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000459class ASTInfoCollector : public ASTReaderListener {
Douglas Gregor83297df2011-09-01 23:39:15 +0000460 Preprocessor &PP;
Richard Smithdbafb6c2017-06-29 23:23:46 +0000461 ASTContext *Context;
Richard Smith18934752017-06-06 00:32:01 +0000462 HeaderSearchOptions &HSOpts;
463 PreprocessorOptions &PPOpts;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000464 LangOptions &LangOpt;
Alp Toker80758082014-07-06 05:26:44 +0000465 std::shared_ptr<TargetOptions> &TargetOpts;
Dylan Noblesmithc95d8192012-02-20 14:00:23 +0000466 IntrusiveRefCntPtr<TargetInfo> &Target;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000467 unsigned &Counter;
Mike Stump11289f42009-09-09 15:08:12 +0000468
Douglas Gregore8bbc122011-09-02 00:18:52 +0000469 bool InitializedLanguage;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000470public:
Richard Smithdbafb6c2017-06-29 23:23:46 +0000471 ASTInfoCollector(Preprocessor &PP, ASTContext *Context,
Richard Smith18934752017-06-06 00:32:01 +0000472 HeaderSearchOptions &HSOpts, PreprocessorOptions &PPOpts,
473 LangOptions &LangOpt,
Alp Toker80758082014-07-06 05:26:44 +0000474 std::shared_ptr<TargetOptions> &TargetOpts,
475 IntrusiveRefCntPtr<TargetInfo> &Target, unsigned &Counter)
Richard Smith18934752017-06-06 00:32:01 +0000476 : PP(PP), Context(Context), HSOpts(HSOpts), PPOpts(PPOpts),
477 LangOpt(LangOpt), TargetOpts(TargetOpts), Target(Target),
478 Counter(Counter), InitializedLanguage(false) {}
Mike Stump11289f42009-09-09 15:08:12 +0000479
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000480 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
481 bool AllowCompatibleDifferences) override {
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000482 if (InitializedLanguage)
Douglas Gregor83297df2011-09-01 23:39:15 +0000483 return false;
484
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000485 LangOpt = LangOpts;
486 InitializedLanguage = true;
487
488 updated();
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000489 return false;
490 }
Mike Stump11289f42009-09-09 15:08:12 +0000491
Richard Smith18934752017-06-06 00:32:01 +0000492 virtual bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
493 StringRef SpecificModuleCachePath,
494 bool Complain) override {
495 this->HSOpts = HSOpts;
496 return false;
497 }
498
499 virtual bool
500 ReadPreprocessorOptions(const PreprocessorOptions &PPOpts, bool Complain,
501 std::string &SuggestedPredefines) override {
502 this->PPOpts = PPOpts;
503 return false;
504 }
505
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000506 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
507 bool AllowCompatibleDifferences) override {
Douglas Gregor83297df2011-09-01 23:39:15 +0000508 // If we've already initialized the target, don't do it again.
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000509 if (Target)
Douglas Gregor83297df2011-09-01 23:39:15 +0000510 return false;
Alp Toker80758082014-07-06 05:26:44 +0000511
512 this->TargetOpts = std::make_shared<TargetOptions>(TargetOpts);
513 Target =
514 TargetInfo::CreateTargetInfo(PP.getDiagnostics(), this->TargetOpts);
Argyrios Kyrtzidis9e1fb562012-09-14 20:24:53 +0000515
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000516 updated();
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000517 return false;
518 }
Mike Stump11289f42009-09-09 15:08:12 +0000519
Craig Topperafa7cb32014-03-13 06:07:04 +0000520 void ReadCounter(const serialization::ModuleFile &M,
521 unsigned Value) override {
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000522 Counter = Value;
523 }
Argyrios Kyrtzidis9e1fb562012-09-14 20:24:53 +0000524
525private:
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000526 void updated() {
527 if (!Target || !InitializedLanguage)
528 return;
529
530 // Inform the target of the language options.
531 //
532 // FIXME: We shouldn't need to do this, the target should be immutable once
533 // created. This complexity should be lifted elsewhere.
Alp Toker74437972014-07-06 05:14:24 +0000534 Target->adjust(LangOpt);
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000535
536 // Initialize the preprocessor.
537 PP.Initialize(*Target);
538
Richard Smithdbafb6c2017-06-29 23:23:46 +0000539 if (!Context)
540 return;
541
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000542 // Initialize the ASTContext
Richard Smithdbafb6c2017-06-29 23:23:46 +0000543 Context->InitBuiltinTypes(*Target);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +0000544
Vedant Kumarfd9fad92017-08-25 18:07:03 +0000545 // Adjust printing policy based on language options.
546 Context->setPrintingPolicy(PrintingPolicy(LangOpt));
547
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +0000548 // We didn't have access to the comment options when the ASTContext was
549 // constructed, so register them now.
Richard Smithdbafb6c2017-06-29 23:23:46 +0000550 Context->getCommentCommandTraits().registerCommentOptions(
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +0000551 LangOpt.CommentOpts);
Argyrios Kyrtzidis9e1fb562012-09-14 20:24:53 +0000552 }
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000553};
554
Douglas Gregor6b930962013-05-03 22:58:43 +0000555 /// \brief Diagnostic consumer that saves each diagnostic it is given.
David Blaikief18d91a2011-09-26 00:01:39 +0000556class StoredDiagnosticConsumer : public DiagnosticConsumer {
Ilya Biryukov200b3282017-06-21 10:24:58 +0000557 SmallVectorImpl<StoredDiagnostic> *StoredDiags;
558 SmallVectorImpl<ASTUnit::StandaloneDiagnostic> *StandaloneDiags;
559 const LangOptions *LangOpts;
Douglas Gregor6b930962013-05-03 22:58:43 +0000560 SourceManager *SourceMgr;
561
Douglas Gregor33cdd812010-02-18 18:08:43 +0000562public:
Ilya Biryukov200b3282017-06-21 10:24:58 +0000563 StoredDiagnosticConsumer(
564 SmallVectorImpl<StoredDiagnostic> *StoredDiags,
565 SmallVectorImpl<ASTUnit::StandaloneDiagnostic> *StandaloneDiags)
566 : StoredDiags(StoredDiags), StandaloneDiags(StandaloneDiags),
567 LangOpts(nullptr), SourceMgr(nullptr) {
568 assert((StoredDiags || StandaloneDiags) &&
569 "No output collections were passed to StoredDiagnosticConsumer.");
570 }
Douglas Gregor6b930962013-05-03 22:58:43 +0000571
Craig Topperafa7cb32014-03-13 06:07:04 +0000572 void BeginSourceFile(const LangOptions &LangOpts,
Craig Topper49a27902014-05-22 04:46:25 +0000573 const Preprocessor *PP = nullptr) override {
Ilya Biryukov200b3282017-06-21 10:24:58 +0000574 this->LangOpts = &LangOpts;
Douglas Gregor6b930962013-05-03 22:58:43 +0000575 if (PP)
576 SourceMgr = &PP->getSourceManager();
577 }
578
Craig Topperafa7cb32014-03-13 06:07:04 +0000579 void HandleDiagnostic(DiagnosticsEngine::Level Level,
580 const Diagnostic &Info) override;
Douglas Gregor33cdd812010-02-18 18:08:43 +0000581};
582
583/// \brief RAII object that optionally captures diagnostics, if
584/// there is no diagnostic client to capture them already.
585class CaptureDroppedDiagnostics {
David Blaikie9c902b52011-09-25 23:23:43 +0000586 DiagnosticsEngine &Diags;
David Blaikief18d91a2011-09-26 00:01:39 +0000587 StoredDiagnosticConsumer Client;
David Blaikiee2eefae2011-09-25 23:39:51 +0000588 DiagnosticConsumer *PreviousClient;
Alexander Kornienko41c247a2014-11-17 23:46:02 +0000589 std::unique_ptr<DiagnosticConsumer> OwningPreviousClient;
Douglas Gregor33cdd812010-02-18 18:08:43 +0000590
591public:
David Blaikie9c902b52011-09-25 23:23:43 +0000592 CaptureDroppedDiagnostics(bool RequestCapture, DiagnosticsEngine &Diags,
Ilya Biryukov200b3282017-06-21 10:24:58 +0000593 SmallVectorImpl<StoredDiagnostic> *StoredDiags,
594 SmallVectorImpl<ASTUnit::StandaloneDiagnostic> *StandaloneDiags)
595 : Diags(Diags), Client(StoredDiags, StandaloneDiags), PreviousClient(nullptr)
Douglas Gregor33cdd812010-02-18 18:08:43 +0000596 {
Craig Topper49a27902014-05-22 04:46:25 +0000597 if (RequestCapture || Diags.getClient() == nullptr) {
Alexander Kornienko41c247a2014-11-17 23:46:02 +0000598 OwningPreviousClient = Diags.takeClient();
599 PreviousClient = Diags.getClient();
600 Diags.setClient(&Client, false);
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000601 }
Douglas Gregor33cdd812010-02-18 18:08:43 +0000602 }
603
604 ~CaptureDroppedDiagnostics() {
Alexander Kornienko41c247a2014-11-17 23:46:02 +0000605 if (Diags.getClient() == &Client)
606 Diags.setClient(PreviousClient, !!OwningPreviousClient.release());
Douglas Gregor33cdd812010-02-18 18:08:43 +0000607 }
608};
609
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000610} // anonymous namespace
611
Ilya Biryukov200b3282017-06-21 10:24:58 +0000612static ASTUnit::StandaloneDiagnostic
613makeStandaloneDiagnostic(const LangOptions &LangOpts,
614 const StoredDiagnostic &InDiag);
615
David Blaikief18d91a2011-09-26 00:01:39 +0000616void StoredDiagnosticConsumer::HandleDiagnostic(DiagnosticsEngine::Level Level,
Ilya Biryukov200b3282017-06-21 10:24:58 +0000617 const Diagnostic &Info) {
Argyrios Kyrtzidisc79346a2010-11-18 20:06:46 +0000618 // Default implementation (Warnings/errors count).
David Blaikiee2eefae2011-09-25 23:39:51 +0000619 DiagnosticConsumer::HandleDiagnostic(Level, Info);
Argyrios Kyrtzidisc79346a2010-11-18 20:06:46 +0000620
Douglas Gregor6b930962013-05-03 22:58:43 +0000621 // Only record the diagnostic if it's part of the source manager we know
622 // about. This effectively drops diagnostics from modules we're building.
623 // FIXME: In the long run, ee don't want to drop source managers from modules.
Ilya Biryukov200b3282017-06-21 10:24:58 +0000624 if (!Info.hasSourceManager() || &Info.getSourceManager() == SourceMgr) {
625 StoredDiagnostic *ResultDiag = nullptr;
626 if (StoredDiags) {
627 StoredDiags->emplace_back(Level, Info);
628 ResultDiag = &StoredDiags->back();
629 }
630
631 if (StandaloneDiags) {
632 llvm::Optional<StoredDiagnostic> StoredDiag = llvm::None;
633 if (!ResultDiag) {
634 StoredDiag.emplace(Level, Info);
635 ResultDiag = StoredDiag.getPointer();
636 }
637 StandaloneDiags->push_back(
638 makeStandaloneDiagnostic(*LangOpts, *ResultDiag));
639 }
640 }
Douglas Gregor33cdd812010-02-18 18:08:43 +0000641}
642
Argyrios Kyrtzidisa38cb202017-01-30 06:05:58 +0000643IntrusiveRefCntPtr<ASTReader> ASTUnit::getASTReader() const {
644 return Reader;
645}
646
Argyrios Kyrtzidis1c7455f2013-05-10 01:28:51 +0000647ASTMutationListener *ASTUnit::getASTMutationListener() {
648 if (WriterData)
649 return &WriterData->Writer;
Craig Topper49a27902014-05-22 04:46:25 +0000650 return nullptr;
Argyrios Kyrtzidis1c7455f2013-05-10 01:28:51 +0000651}
652
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000653ASTDeserializationListener *ASTUnit::getDeserializationListener() {
654 if (WriterData)
655 return &WriterData->Writer;
Craig Topper49a27902014-05-22 04:46:25 +0000656 return nullptr;
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000657}
658
Rafael Espindola16e1ba12014-08-26 20:17:44 +0000659std::unique_ptr<llvm::MemoryBuffer>
660ASTUnit::getBufferForFile(StringRef Filename, std::string *ErrorStr) {
Chris Lattner5159f612010-11-23 08:35:12 +0000661 assert(FileMgr);
Benjamin Kramera8857962014-10-26 22:44:13 +0000662 auto Buffer = FileMgr->getBufferForFile(Filename);
663 if (Buffer)
664 return std::move(*Buffer);
665 if (ErrorStr)
666 *ErrorStr = Buffer.getError().message();
667 return nullptr;
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000668}
669
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000670/// \brief Configure the diagnostics object for use with ASTUnit.
Justin Bognerd512c1e2014-10-15 00:33:06 +0000671void ASTUnit::ConfigureDiags(IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000672 ASTUnit &AST, bool CaptureDiagnostics) {
Justin Bognerd512c1e2014-10-15 00:33:06 +0000673 assert(Diags.get() && "no DiagnosticsEngine was provided");
674 if (CaptureDiagnostics)
Ilya Biryukov200b3282017-06-21 10:24:58 +0000675 Diags->setClient(new StoredDiagnosticConsumer(&AST.StoredDiagnostics, nullptr));
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000676}
677
David Blaikie6f7382d2014-08-10 19:08:04 +0000678std::unique_ptr<ASTUnit> ASTUnit::LoadFromASTFile(
Adrian Prantl6b21ab22015-08-27 19:46:20 +0000679 const std::string &Filename, const PCHContainerReader &PCHContainerRdr,
Richard Smithdbafb6c2017-06-29 23:23:46 +0000680 WhatToLoad ToLoad, IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Adrian Prantl6b21ab22015-08-27 19:46:20 +0000681 const FileSystemOptions &FileSystemOpts, bool UseDebugInfo,
682 bool OnlyLocalDecls, ArrayRef<RemappedFile> RemappedFiles,
683 bool CaptureDiagnostics, bool AllowPCHWithCompilerErrors,
684 bool UserFilesAreVolatile) {
Ahmed Charlesb8984322014-03-07 20:03:18 +0000685 std::unique_ptr<ASTUnit> AST(new ASTUnit(true));
Ted Kremenek4422bfe2011-03-18 02:06:56 +0000686
687 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +0000688 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
689 ASTUnitCleanup(AST.get());
David Blaikie9c902b52011-09-25 23:23:43 +0000690 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
691 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Alp Tokerf994cef2014-07-05 03:08:06 +0000692 DiagCleanup(Diags.get());
Ted Kremenek4422bfe2011-03-18 02:06:56 +0000693
Justin Bognerdbbcb112014-10-14 23:36:06 +0000694 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000695
Richard Smithab755972017-06-05 18:10:11 +0000696 AST->LangOpts = std::make_shared<LangOptions>();
Douglas Gregor16bef852009-10-16 20:01:17 +0000697 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000698 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor7f95d262010-04-05 23:52:57 +0000699 AST->Diagnostics = Diags;
Ben Langmuir8832c062014-04-15 18:16:25 +0000700 IntrusiveRefCntPtr<vfs::FileSystem> VFS = vfs::getRealFileSystem();
701 AST->FileMgr = new FileManager(FileSystemOpts, VFS);
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +0000702 AST->UserFilesAreVolatile = UserFilesAreVolatile;
Ted Kremenek5e14d392011-03-21 18:40:17 +0000703 AST->SourceMgr = new SourceManager(AST->getDiagnostics(),
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +0000704 AST->getFileManager(),
705 UserFilesAreVolatile);
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +0000706 AST->PCMCache = new MemoryBufferCache;
David Blaikie9c28cb32017-01-06 01:04:46 +0000707 AST->HSOpts = std::make_shared<HeaderSearchOptions>();
Adrian Prantlfb2398d2015-07-17 01:19:54 +0000708 AST->HSOpts->ModuleFormat = PCHContainerRdr.getFormat();
Douglas Gregorb85b9cc2012-10-24 16:19:39 +0000709 AST->HeaderInfo.reset(new HeaderSearch(AST->HSOpts,
Manuel Klimek1f76c4e2013-10-24 07:51:24 +0000710 AST->getSourceManager(),
Douglas Gregor1fb5c3a2011-12-31 04:05:44 +0000711 AST->getDiagnostics(),
Richard Smithab755972017-06-05 18:10:11 +0000712 AST->getLangOpts(),
Craig Topper49a27902014-05-22 04:46:25 +0000713 /*Target=*/nullptr));
Richard Smith18934752017-06-06 00:32:01 +0000714 AST->PPOpts = std::make_shared<PreprocessorOptions>();
Dmitri Gribenkoc444b572014-02-08 00:38:15 +0000715
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000716 for (const auto &RemappedFile : RemappedFiles)
Richard Smith18934752017-06-06 00:32:01 +0000717 AST->PPOpts->addRemappedFile(RemappedFile.first, RemappedFile.second);
Dmitri Gribenkoc444b572014-02-08 00:38:15 +0000718
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000719 // Gather Info for preprocessor construction later on.
Mike Stump11289f42009-09-09 15:08:12 +0000720
David Blaikie6f7382d2014-08-10 19:08:04 +0000721 HeaderSearch &HeaderInfo = *AST->HeaderInfo;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000722 unsigned Counter;
723
David Blaikie41565462017-01-05 19:48:07 +0000724 AST->PP = std::make_shared<Preprocessor>(
Richard Smith18934752017-06-06 00:32:01 +0000725 AST->PPOpts, AST->getDiagnostics(), *AST->LangOpts,
Richard Smith5d2ed482017-06-09 19:22:32 +0000726 AST->getSourceManager(), *AST->PCMCache, HeaderInfo, AST->ModuleLoader,
David Blaikie41565462017-01-05 19:48:07 +0000727 /*IILookup=*/nullptr,
728 /*OwnsHeaderSearch=*/false);
Douglas Gregore8bbc122011-09-02 00:18:52 +0000729 Preprocessor &PP = *AST->PP;
730
Richard Smithdbafb6c2017-06-29 23:23:46 +0000731 if (ToLoad >= LoadASTOnly)
732 AST->Ctx = new ASTContext(*AST->LangOpts, AST->getSourceManager(),
733 PP.getIdentifierTable(), PP.getSelectorTable(),
734 PP.getBuiltinInfo());
Douglas Gregor83297df2011-09-01 23:39:15 +0000735
Argyrios Kyrtzidis945a8192012-09-15 01:10:20 +0000736 bool disableValid = false;
737 if (::getenv("LIBCLANG_DISABLE_PCH_VALIDATION"))
738 disableValid = true;
Richard Smithdbafb6c2017-06-29 23:23:46 +0000739 AST->Reader = new ASTReader(PP, AST->Ctx.get(), PCHContainerRdr, { },
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000740 /*isysroot=*/"",
741 /*DisableValidation=*/disableValid,
742 AllowPCHWithCompilerErrors);
Ted Kremenek2159b8d2011-05-04 23:27:12 +0000743
David Blaikie2721c322014-08-10 16:54:39 +0000744 AST->Reader->setListener(llvm::make_unique<ASTInfoCollector>(
Richard Smithdbafb6c2017-06-29 23:23:46 +0000745 *AST->PP, AST->Ctx.get(), *AST->HSOpts, *AST->PPOpts, *AST->LangOpts,
Richard Smith18934752017-06-06 00:32:01 +0000746 AST->TargetOpts, AST->Target, Counter));
Daniel Dunbar2d9c7402009-09-03 05:59:35 +0000747
Argyrios Kyrtzidisf0b4cd12015-03-03 08:04:19 +0000748 // Attach the AST reader to the AST context as an external AST
749 // source, so that declarations will be deserialized from the
750 // AST file as needed.
751 // We need the external source to be set up before we read the AST, because
752 // eagerly-deserialized declarations may use it.
Richard Smithdbafb6c2017-06-29 23:23:46 +0000753 if (AST->Ctx)
754 AST->Ctx->setExternalSource(AST->Reader);
Argyrios Kyrtzidisf0b4cd12015-03-03 08:04:19 +0000755
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000756 switch (AST->Reader->ReadAST(Filename, serialization::MK_MainFile,
Argyrios Kyrtzidis2ec29362012-11-15 18:57:22 +0000757 SourceLocation(), ASTReader::ARR_None)) {
Sebastian Redl2c499f62010-08-18 23:56:43 +0000758 case ASTReader::Success:
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000759 break;
Mike Stump11289f42009-09-09 15:08:12 +0000760
Sebastian Redl2c499f62010-08-18 23:56:43 +0000761 case ASTReader::Failure:
Douglas Gregor7029ce12013-03-19 00:28:20 +0000762 case ASTReader::Missing:
Douglas Gregorc9ad5fb2012-10-22 22:50:17 +0000763 case ASTReader::OutOfDate:
764 case ASTReader::VersionMismatch:
765 case ASTReader::ConfigurationMismatch:
766 case ASTReader::HadErrors:
Douglas Gregord03e8232010-04-05 21:10:19 +0000767 AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
Craig Topper49a27902014-05-22 04:46:25 +0000768 return nullptr;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000769 }
Mike Stump11289f42009-09-09 15:08:12 +0000770
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000771 AST->OriginalSourceFile = AST->Reader->getOriginalSourceFile();
Daniel Dunbara8a50932009-12-02 08:44:16 +0000772
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000773 PP.setCounterValue(Counter);
Mike Stump11289f42009-09-09 15:08:12 +0000774
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000775 // Create an AST consumer, even though it isn't used.
Richard Smithdbafb6c2017-06-29 23:23:46 +0000776 if (ToLoad >= LoadASTOnly)
777 AST->Consumer.reset(new ASTConsumer);
778
Sebastian Redl2c499f62010-08-18 23:56:43 +0000779 // Create a semantic analysis object and tell the AST reader about it.
Richard Smithdbafb6c2017-06-29 23:23:46 +0000780 if (ToLoad >= LoadEverything) {
781 AST->TheSema.reset(new Sema(PP, *AST->Ctx, *AST->Consumer));
782 AST->TheSema->Initialize();
783 AST->Reader->InitializeSema(*AST->TheSema);
784 }
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000785
Douglas Gregor6b930962013-05-03 22:58:43 +0000786 // Tell the diagnostic client that we have started a source file.
Richard Smithdbafb6c2017-06-29 23:23:46 +0000787 AST->getDiagnostics().getClient()->BeginSourceFile(PP.getLangOpts(), &PP);
Douglas Gregor6b930962013-05-03 22:58:43 +0000788
David Blaikie6f7382d2014-08-10 19:08:04 +0000789 return AST;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000790}
Daniel Dunbar764c0822009-12-01 09:51:01 +0000791
792namespace {
793
Ilya Biryukov200b3282017-06-21 10:24:58 +0000794/// \brief Add the given macro to the hash of all top-level entities.
795void AddDefinedMacroToHash(const Token &MacroNameTok, unsigned &Hash) {
796 Hash = llvm::HashString(MacroNameTok.getIdentifierInfo()->getName(), Hash);
797}
798
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000799/// \brief Preprocessor callback class that updates a hash value with the names
800/// of all macros that have been defined by the translation unit.
801class MacroDefinitionTrackerPPCallbacks : public PPCallbacks {
802 unsigned &Hash;
803
804public:
805 explicit MacroDefinitionTrackerPPCallbacks(unsigned &Hash) : Hash(Hash) { }
Craig Topperafa7cb32014-03-13 06:07:04 +0000806
807 void MacroDefined(const Token &MacroNameTok,
808 const MacroDirective *MD) override {
Ilya Biryukov200b3282017-06-21 10:24:58 +0000809 AddDefinedMacroToHash(MacroNameTok, Hash);
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000810 }
811};
812
813/// \brief Add the given declaration to the hash of all top-level entities.
814void AddTopLevelDeclarationToHash(Decl *D, unsigned &Hash) {
815 if (!D)
816 return;
817
818 DeclContext *DC = D->getDeclContext();
819 if (!DC)
820 return;
821
822 if (!(DC->isTranslationUnit() || DC->getLookupParent()->isTranslationUnit()))
823 return;
824
825 if (NamedDecl *ND = dyn_cast<NamedDecl>(D)) {
Argyrios Kyrtzidisca5c7be2013-10-15 17:37:55 +0000826 if (EnumDecl *EnumD = dyn_cast<EnumDecl>(D)) {
827 // For an unscoped enum include the enumerators in the hash since they
828 // enter the top-level namespace.
829 if (!EnumD->isScoped()) {
Aaron Ballman23a6dcb2014-03-08 18:45:14 +0000830 for (const auto *EI : EnumD->enumerators()) {
831 if (EI->getIdentifier())
832 Hash = llvm::HashString(EI->getIdentifier()->getName(), Hash);
Argyrios Kyrtzidisca5c7be2013-10-15 17:37:55 +0000833 }
834 }
835 }
836
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000837 if (ND->getIdentifier())
838 Hash = llvm::HashString(ND->getIdentifier()->getName(), Hash);
839 else if (DeclarationName Name = ND->getDeclName()) {
840 std::string NameStr = Name.getAsString();
841 Hash = llvm::HashString(NameStr, Hash);
842 }
843 return;
Argyrios Kyrtzidis48d88de2013-06-24 21:19:12 +0000844 }
845
846 if (ImportDecl *ImportD = dyn_cast<ImportDecl>(D)) {
847 if (Module *Mod = ImportD->getImportedModule()) {
848 std::string ModName = Mod->getFullModuleName();
849 Hash = llvm::HashString(ModName, Hash);
850 }
851 return;
852 }
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000853}
854
Daniel Dunbar644dca02009-12-04 08:17:33 +0000855class TopLevelDeclTrackerConsumer : public ASTConsumer {
856 ASTUnit &Unit;
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000857 unsigned &Hash;
858
Daniel Dunbar644dca02009-12-04 08:17:33 +0000859public:
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000860 TopLevelDeclTrackerConsumer(ASTUnit &_Unit, unsigned &Hash)
861 : Unit(_Unit), Hash(Hash) {
862 Hash = 0;
863 }
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000864
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000865 void handleTopLevelDecl(Decl *D) {
Argyrios Kyrtzidis516eec22011-11-16 02:35:10 +0000866 if (!D)
867 return;
868
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000869 // FIXME: Currently ObjC method declarations are incorrectly being
870 // reported as top-level declarations, even though their DeclContext
871 // is the containing ObjC @interface/@implementation. This is a
872 // fundamental problem in the parser right now.
873 if (isa<ObjCMethodDecl>(D))
874 return;
875
876 AddTopLevelDeclarationToHash(D, Hash);
877 Unit.addTopLevelDecl(D);
878
879 handleFileLevelDecl(D);
880 }
881
882 void handleFileLevelDecl(Decl *D) {
883 Unit.addFileLevelDecl(D);
884 if (NamespaceDecl *NSD = dyn_cast<NamespaceDecl>(D)) {
Aaron Ballman629afae2014-03-07 19:56:05 +0000885 for (auto *I : NSD->decls())
886 handleFileLevelDecl(I);
Ted Kremenekacc59c32010-05-03 20:16:35 +0000887 }
Daniel Dunbar644dca02009-12-04 08:17:33 +0000888 }
Sebastian Redleaa4ade2010-08-11 18:52:41 +0000889
Craig Topperafa7cb32014-03-13 06:07:04 +0000890 bool HandleTopLevelDecl(DeclGroupRef D) override {
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000891 for (Decl *TopLevelDecl : D)
892 handleTopLevelDecl(TopLevelDecl);
Argyrios Kyrtzidis841dd882011-11-18 00:26:59 +0000893 return true;
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000894 }
895
Sebastian Redleaa4ade2010-08-11 18:52:41 +0000896 // We're not interested in "interesting" decls.
Craig Topperafa7cb32014-03-13 06:07:04 +0000897 void HandleInterestingDecl(DeclGroupRef) override {}
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000898
Craig Topperafa7cb32014-03-13 06:07:04 +0000899 void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) override {
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000900 for (Decl *TopLevelDecl : D)
901 handleTopLevelDecl(TopLevelDecl);
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000902 }
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000903
Craig Topperafa7cb32014-03-13 06:07:04 +0000904 ASTMutationListener *GetASTMutationListener() override {
Argyrios Kyrtzidis1c7455f2013-05-10 01:28:51 +0000905 return Unit.getASTMutationListener();
906 }
907
Craig Topperafa7cb32014-03-13 06:07:04 +0000908 ASTDeserializationListener *GetASTDeserializationListener() override {
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000909 return Unit.getDeserializationListener();
910 }
Daniel Dunbar644dca02009-12-04 08:17:33 +0000911};
912
913class TopLevelDeclTrackerAction : public ASTFrontendAction {
914public:
915 ASTUnit &Unit;
916
David Blaikie6beb6aa2014-08-10 19:56:51 +0000917 std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
918 StringRef InFile) override {
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000919 CI.getPreprocessor().addPPCallbacks(
Craig Topperb8a70532014-09-10 04:53:53 +0000920 llvm::make_unique<MacroDefinitionTrackerPPCallbacks>(
921 Unit.getCurrentTopLevelHashValue()));
David Blaikie6beb6aa2014-08-10 19:56:51 +0000922 return llvm::make_unique<TopLevelDeclTrackerConsumer>(
923 Unit, Unit.getCurrentTopLevelHashValue());
Daniel Dunbar764c0822009-12-01 09:51:01 +0000924 }
925
926public:
Daniel Dunbar644dca02009-12-04 08:17:33 +0000927 TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {}
928
Craig Topperafa7cb32014-03-13 06:07:04 +0000929 bool hasCodeCompletionSupport() const override { return false; }
930 TranslationUnitKind getTranslationUnitKind() override {
Douglas Gregor69f74f82011-08-25 22:30:56 +0000931 return Unit.getTranslationUnitKind();
Douglas Gregor028d3e42010-08-09 20:45:32 +0000932 }
Daniel Dunbar764c0822009-12-01 09:51:01 +0000933};
934
Ilya Biryukov200b3282017-06-21 10:24:58 +0000935class ASTUnitPreambleCallbacks : public PreambleCallbacks {
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000936public:
Ilya Biryukov200b3282017-06-21 10:24:58 +0000937 unsigned getHash() const { return Hash; }
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000938
Ilya Biryukov200b3282017-06-21 10:24:58 +0000939 std::vector<Decl *> takeTopLevelDecls() { return std::move(TopLevelDecls); }
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000940
Ilya Biryukov200b3282017-06-21 10:24:58 +0000941 std::vector<serialization::DeclID> takeTopLevelDeclIDs() {
942 return std::move(TopLevelDeclIDs);
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000943 }
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000944
Ilya Biryukov200b3282017-06-21 10:24:58 +0000945 void AfterPCHEmitted(ASTWriter &Writer) override {
946 TopLevelDeclIDs.reserve(TopLevelDecls.size());
947 for (Decl *D : TopLevelDecls) {
948 // Invalid top-level decls may not have been serialized.
949 if (D->isInvalidDecl())
950 continue;
951 TopLevelDeclIDs.push_back(Writer.getDeclID(D));
952 }
953 }
954
955 void HandleTopLevelDecl(DeclGroupRef DG) override {
Benjamin Kramera401b9b2015-02-06 18:58:04 +0000956 for (Decl *D : DG) {
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000957 // FIXME: Currently ObjC method declarations are incorrectly being
958 // reported as top-level declarations, even though their DeclContext
959 // is the containing ObjC @interface/@implementation. This is a
960 // fundamental problem in the parser right now.
961 if (isa<ObjCMethodDecl>(D))
962 continue;
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000963 AddTopLevelDeclarationToHash(D, Hash);
Douglas Gregore9db88f2010-08-03 19:06:41 +0000964 TopLevelDecls.push_back(D);
965 }
966 }
967
Ilya Biryukov200b3282017-06-21 10:24:58 +0000968 void HandleMacroDefined(const Token &MacroNameTok,
969 const MacroDirective *MD) override {
970 AddDefinedMacroToHash(MacroNameTok, Hash);
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000971 }
Ilya Biryukov200b3282017-06-21 10:24:58 +0000972
973private:
Ilya Biryukov200b3282017-06-21 10:24:58 +0000974 unsigned Hash = 0;
975 std::vector<Decl *> TopLevelDecls;
976 std::vector<serialization::DeclID> TopLevelDeclIDs;
977 llvm::SmallVector<ASTUnit::StandaloneDiagnostic, 4> PreambleDiags;
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000978};
979
Hans Wennborgdcfba332015-10-06 23:40:43 +0000980} // anonymous namespace
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000981
Benjamin Kramer1ce5d802013-05-05 12:39:28 +0000982static bool isNonDriverDiag(const StoredDiagnostic &StoredDiag) {
983 return StoredDiag.getLocation().isValid();
984}
985
986static void
987checkAndRemoveNonDriverDiags(SmallVectorImpl<StoredDiagnostic> &StoredDiags) {
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +0000988 // Get rid of stored diagnostics except the ones from the driver which do not
989 // have a source location.
Benjamin Kramer1ce5d802013-05-05 12:39:28 +0000990 StoredDiags.erase(
991 std::remove_if(StoredDiags.begin(), StoredDiags.end(), isNonDriverDiag),
992 StoredDiags.end());
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +0000993}
994
995static void checkAndSanitizeDiags(SmallVectorImpl<StoredDiagnostic> &
996 StoredDiagnostics,
997 SourceManager &SM) {
998 // The stored diagnostic has the old source manager in it; update
999 // the locations to refer into the new source manager. Since we've
1000 // been careful to make sure that the source manager's state
1001 // before and after are identical, so that we can reuse the source
1002 // location itself.
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00001003 for (StoredDiagnostic &SD : StoredDiagnostics) {
1004 if (SD.getLocation().isValid()) {
1005 FullSourceLoc Loc(SD.getLocation(), SM);
1006 SD.setLocation(Loc);
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +00001007 }
1008 }
1009}
1010
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001011/// Parse the source file into a translation unit using the given compiler
1012/// invocation, replacing the current translation unit.
1013///
1014/// \returns True if a failure occurred that causes the ASTUnit not to
1015/// contain any translation-unit information, false otherwise.
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001016bool ASTUnit::Parse(std::shared_ptr<PCHContainerOperations> PCHContainerOps,
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001017 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer,
1018 IntrusiveRefCntPtr<vfs::FileSystem> VFS) {
Rafael Espindola32482082014-08-18 16:23:45 +00001019 if (!Invocation)
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001020 return true;
Rafael Espindola32482082014-08-18 16:23:45 +00001021
Daniel Dunbar764c0822009-12-01 09:51:01 +00001022 // Create the compiler instance to use for building the AST.
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001023 std::unique_ptr<CompilerInstance> Clang(
Benjamin Kramerd6da1a02016-06-12 20:05:23 +00001024 new CompilerInstance(std::move(PCHContainerOps)));
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001025 if (FileMgr && VFS) {
1026 assert(VFS == FileMgr->getVirtualFileSystem() &&
1027 "VFS passed to Parse and VFS in FileMgr are different");
1028 } else if (VFS) {
1029 Clang->setVirtualFileSystem(VFS);
1030 }
Ted Kremenek84de4a12011-03-21 18:40:07 +00001031
1032 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00001033 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1034 CICleanup(Clang.get());
Ted Kremenek84de4a12011-03-21 18:40:07 +00001035
David Blaikieea4395e2017-01-06 19:49:01 +00001036 Clang->setInvocation(std::make_shared<CompilerInvocation>(*Invocation));
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001037 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001038
Douglas Gregor8e984da2010-08-04 16:47:14 +00001039 // Set up diagnostics, capturing any diagnostics that would
1040 // otherwise be dropped.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001041 Clang->setDiagnostics(&getDiagnostics());
Douglas Gregord03e8232010-04-05 21:10:19 +00001042
Daniel Dunbar764c0822009-12-01 09:51:01 +00001043 // Create the target instance.
Alp Toker80758082014-07-06 05:26:44 +00001044 Clang->setTarget(TargetInfo::CreateTargetInfo(
Saleem Abdulrasool10a49722016-04-08 16:52:00 +00001045 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
Rafael Espindola32482082014-08-18 16:23:45 +00001046 if (!Clang->hasTarget())
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001047 return true;
Douglas Gregora0734c52010-08-19 01:33:06 +00001048
Daniel Dunbar764c0822009-12-01 09:51:01 +00001049 // Inform the target of the language options.
1050 //
1051 // FIXME: We shouldn't need to do this, the target should be immutable once
1052 // created. This complexity should be lifted elsewhere.
Alp Toker74437972014-07-06 05:14:24 +00001053 Clang->getTarget().adjust(Clang->getLangOpts());
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001054
Ted Kremenek84de4a12011-03-21 18:40:07 +00001055 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Daniel Dunbar764c0822009-12-01 09:51:01 +00001056 "Invocation must have exactly one source file!");
Richard Smith40c0efa2017-04-26 18:57:40 +00001057 assert(Clang->getFrontendOpts().Inputs[0].getKind().getFormat() ==
1058 InputKind::Source &&
Daniel Dunbar764c0822009-12-01 09:51:01 +00001059 "FIXME: AST inputs not yet supported here!");
Richard Smith40c0efa2017-04-26 18:57:40 +00001060 assert(Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() !=
1061 InputKind::LLVM_IR &&
Daniel Dunbar9507f9c2010-06-07 23:26:47 +00001062 "IR inputs not support here!");
Daniel Dunbar764c0822009-12-01 09:51:01 +00001063
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001064 // Configure the various subsystems.
Alp Toker269d8402014-07-06 05:26:07 +00001065 LangOpts = Clang->getInvocation().LangOpts;
Ted Kremenek84de4a12011-03-21 18:40:07 +00001066 FileSystemOpts = Clang->getFileSystemOpts();
Benjamin Kramerbc632902015-10-06 14:45:20 +00001067 if (!FileMgr) {
1068 Clang->createFileManager();
1069 FileMgr = &Clang->getFileManager();
1070 }
Erik Verbruggen346066b2017-05-30 14:25:54 +00001071
1072 ResetForParse();
1073
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +00001074 SourceMgr = new SourceManager(getDiagnostics(), *FileMgr,
1075 UserFilesAreVolatile);
Douglas Gregor7b02b582010-08-20 00:02:33 +00001076 if (!OverrideMainBuffer) {
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +00001077 checkAndRemoveNonDriverDiags(StoredDiagnostics);
Douglas Gregor7b02b582010-08-20 00:02:33 +00001078 TopLevelDeclsInPreamble.clear();
1079 }
1080
Daniel Dunbar764c0822009-12-01 09:51:01 +00001081 // Create a file manager object to provide access to and cache the filesystem.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001082 Clang->setFileManager(&getFileManager());
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001083
Daniel Dunbar764c0822009-12-01 09:51:01 +00001084 // Create the source manager.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001085 Clang->setSourceManager(&getSourceManager());
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001086
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001087 // If the main file has been overridden due to the use of a preamble,
1088 // make that override happen and introduce the preamble.
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001089 if (OverrideMainBuffer) {
Ilya Biryukov200b3282017-06-21 10:24:58 +00001090 assert(Preamble && "No preamble was built, but OverrideMainBuffer is not null");
1091 Preamble->AddImplicitPreamble(Clang->getInvocation(), OverrideMainBuffer.get());
Douglas Gregor96c04262010-07-27 14:52:07 +00001092
Douglas Gregord9a30af2010-08-02 20:51:39 +00001093 // The stored diagnostic has the old source manager in it; update
1094 // the locations to refer into the new source manager. Since we've
1095 // been careful to make sure that the source manager's state
1096 // before and after are identical, so that we can reuse the source
1097 // location itself.
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +00001098 checkAndSanitizeDiags(StoredDiagnostics, getSourceManager());
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001099
1100 // Keep track of the override buffer;
Rafael Espindola32482082014-08-18 16:23:45 +00001101 SavedMainFileBuffer = std::move(OverrideMainBuffer);
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001102 }
Ahmed Charlesb8984322014-03-07 20:03:18 +00001103
1104 std::unique_ptr<TopLevelDeclTrackerAction> Act(
1105 new TopLevelDeclTrackerAction(*this));
1106
Ted Kremenek022a4902011-03-22 01:15:24 +00001107 // Recover resources if we crash before exiting this method.
1108 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1109 ActCleanup(Act.get());
1110
Douglas Gregor32fbe312012-01-20 16:28:04 +00001111 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0]))
Daniel Dunbar764c0822009-12-01 09:51:01 +00001112 goto error;
Douglas Gregor925296b2011-07-19 16:10:42 +00001113
Richard Smith26b8f782016-03-25 21:46:44 +00001114 if (SavedMainFileBuffer)
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001115 TranslateStoredDiagnostics(getFileManager(), getSourceManager(),
1116 PreambleDiagnostics, StoredDiagnostics);
Erik Verbruggenefe6fa52017-06-09 08:29:58 +00001117 else
1118 PreambleSrcLocCache.clear();
Douglas Gregor925296b2011-07-19 16:10:42 +00001119
Argyrios Kyrtzidis1416e172012-06-08 05:48:06 +00001120 if (!Act->Execute())
1121 goto error;
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001122
1123 transferASTDataFromCompilerInstance(*Clang);
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001124
Daniel Dunbar644dca02009-12-04 08:17:33 +00001125 Act->EndSourceFile();
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001126
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001127 FailedParseDiagnostics.clear();
1128
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001129 return false;
Ted Kremenek5e14d392011-03-21 18:40:17 +00001130
Daniel Dunbar764c0822009-12-01 09:51:01 +00001131error:
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001132 // Remove the overridden buffer we used for the preamble.
Rafael Espindola32482082014-08-18 16:23:45 +00001133 SavedMainFileBuffer = nullptr;
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001134
1135 // Keep the ownership of the data in the ASTUnit because the client may
1136 // want to see the diagnostics.
1137 transferASTDataFromCompilerInstance(*Clang);
1138 FailedParseDiagnostics.swap(StoredDiagnostics);
Douglas Gregorefc46952010-10-12 16:25:54 +00001139 StoredDiagnostics.clear();
Argyrios Kyrtzidis067cbfa2011-10-24 17:25:20 +00001140 NumStoredDiagnosticsFromDriver = 0;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001141 return true;
1142}
1143
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001144static std::pair<unsigned, unsigned>
1145makeStandaloneRange(CharSourceRange Range, const SourceManager &SM,
1146 const LangOptions &LangOpts) {
1147 CharSourceRange FileRange = Lexer::makeFileCharRange(Range, SM, LangOpts);
1148 unsigned Offset = SM.getFileOffset(FileRange.getBegin());
1149 unsigned EndOffset = SM.getFileOffset(FileRange.getEnd());
1150 return std::make_pair(Offset, EndOffset);
1151}
1152
Benjamin Kramer1a6e0a92014-10-03 18:52:54 +00001153static ASTUnit::StandaloneFixIt makeStandaloneFixIt(const SourceManager &SM,
1154 const LangOptions &LangOpts,
1155 const FixItHint &InFix) {
1156 ASTUnit::StandaloneFixIt OutFix;
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001157 OutFix.RemoveRange = makeStandaloneRange(InFix.RemoveRange, SM, LangOpts);
1158 OutFix.InsertFromRange = makeStandaloneRange(InFix.InsertFromRange, SM,
1159 LangOpts);
1160 OutFix.CodeToInsert = InFix.CodeToInsert;
1161 OutFix.BeforePreviousInsertions = InFix.BeforePreviousInsertions;
Benjamin Kramer1a6e0a92014-10-03 18:52:54 +00001162 return OutFix;
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001163}
1164
Benjamin Kramer1a6e0a92014-10-03 18:52:54 +00001165static ASTUnit::StandaloneDiagnostic
1166makeStandaloneDiagnostic(const LangOptions &LangOpts,
1167 const StoredDiagnostic &InDiag) {
1168 ASTUnit::StandaloneDiagnostic OutDiag;
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001169 OutDiag.ID = InDiag.getID();
1170 OutDiag.Level = InDiag.getLevel();
1171 OutDiag.Message = InDiag.getMessage();
1172 OutDiag.LocOffset = 0;
1173 if (InDiag.getLocation().isInvalid())
Benjamin Kramer1a6e0a92014-10-03 18:52:54 +00001174 return OutDiag;
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001175 const SourceManager &SM = InDiag.getLocation().getManager();
1176 SourceLocation FileLoc = SM.getFileLoc(InDiag.getLocation());
1177 OutDiag.Filename = SM.getFilename(FileLoc);
1178 if (OutDiag.Filename.empty())
Benjamin Kramer1a6e0a92014-10-03 18:52:54 +00001179 return OutDiag;
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001180 OutDiag.LocOffset = SM.getFileOffset(FileLoc);
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00001181 for (const CharSourceRange &Range : InDiag.getRanges())
1182 OutDiag.Ranges.push_back(makeStandaloneRange(Range, SM, LangOpts));
1183 for (const FixItHint &FixIt : InDiag.getFixIts())
1184 OutDiag.FixIts.push_back(makeStandaloneFixIt(SM, LangOpts, FixIt));
Benjamin Kramer1a6e0a92014-10-03 18:52:54 +00001185
1186 return OutDiag;
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001187}
1188
Douglas Gregor4dde7492010-07-23 23:58:40 +00001189/// \brief Attempt to build or re-use a precompiled preamble when (re-)parsing
1190/// the source file.
1191///
1192/// This routine will compute the preamble of the main source file. If a
1193/// non-trivial preamble is found, it will precompile that preamble into a
1194/// precompiled header so that the precompiled preamble can be used to reduce
1195/// reparsing time. If a precompiled preamble has already been constructed,
1196/// this routine will determine if it is still valid and, if so, avoid
1197/// rebuilding the precompiled preamble.
1198///
Douglas Gregor028d3e42010-08-09 20:45:32 +00001199/// \param AllowRebuild When true (the default), this routine is
1200/// allowed to rebuild the precompiled preamble if it is found to be
1201/// out-of-date.
1202///
1203/// \param MaxLines When non-zero, the maximum number of lines that
1204/// can occur within the preamble.
1205///
Douglas Gregor6481ef12010-07-24 00:38:13 +00001206/// \returns If the precompiled preamble can be used, returns a newly-allocated
1207/// buffer that should be used in place of the main file when doing so.
1208/// Otherwise, returns a NULL pointer.
Rafael Espindola2346a372014-08-18 18:47:08 +00001209std::unique_ptr<llvm::MemoryBuffer>
1210ASTUnit::getMainBufferWithPrecompiledPreamble(
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001211 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001212 const CompilerInvocation &PreambleInvocationIn,
1213 IntrusiveRefCntPtr<vfs::FileSystem> VFS, bool AllowRebuild,
Rafael Espindola2346a372014-08-18 18:47:08 +00001214 unsigned MaxLines) {
1215
Ilya Biryukov200b3282017-06-21 10:24:58 +00001216 auto MainFilePath =
1217 PreambleInvocationIn.getFrontendOpts().Inputs[0].getFile();
1218 std::unique_ptr<llvm::MemoryBuffer> MainFileBuffer =
1219 getBufferForFileHandlingRemapping(PreambleInvocationIn, VFS.get(),
1220 MainFilePath);
1221 if (!MainFileBuffer)
Craig Topper49a27902014-05-22 04:46:25 +00001222 return nullptr;
Douglas Gregord9a30af2010-08-02 20:51:39 +00001223
Ilya Biryukov200b3282017-06-21 10:24:58 +00001224 PreambleBounds Bounds =
1225 ComputePreambleBounds(*PreambleInvocationIn.getLangOpts(),
1226 MainFileBuffer.get(), MaxLines);
1227 if (!Bounds.Size)
1228 return nullptr;
Alp Toker1b070d22014-07-07 07:47:20 +00001229
Ilya Biryukov200b3282017-06-21 10:24:58 +00001230 if (Preamble) {
1231 if (Preamble->CanReuse(PreambleInvocationIn, MainFileBuffer.get(), Bounds,
1232 VFS.get())) {
1233 // Okay! We can re-use the precompiled preamble.
Rafael Espindolae4777f42013-07-29 18:22:23 +00001234
Ilya Biryukov200b3282017-06-21 10:24:58 +00001235 // Set the state of the diagnostic object to mimic its state
1236 // after parsing the preamble.
1237 getDiagnostics().Reset();
1238 ProcessWarningOptions(getDiagnostics(),
1239 PreambleInvocationIn.getDiagnosticOpts());
1240 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
Alp Toker1b070d22014-07-07 07:47:20 +00001241
Ilya Biryukov200b3282017-06-21 10:24:58 +00001242 PreambleRebuildCounter = 1;
1243 return MainFileBuffer;
1244 } else {
1245 Preamble.reset();
1246 PreambleDiagnostics.clear();
1247 TopLevelDeclsInPreamble.clear();
1248 PreambleRebuildCounter = 1;
Douglas Gregor4dde7492010-07-23 23:58:40 +00001249 }
Douglas Gregor028d3e42010-08-09 20:45:32 +00001250 }
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001251
1252 // If the preamble rebuild counter > 1, it's because we previously
1253 // failed to build a preamble and we're not yet ready to try
1254 // again. Decrement the counter and return a failure.
1255 if (PreambleRebuildCounter > 1) {
1256 --PreambleRebuildCounter;
Craig Topper49a27902014-05-22 04:46:25 +00001257 return nullptr;
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001258 }
1259
Ilya Biryukov200b3282017-06-21 10:24:58 +00001260 assert(!Preamble && "No Preamble should be stored at that point");
1261 // If we aren't allowed to rebuild the precompiled preamble, just
1262 // return now.
1263 if (!AllowRebuild)
Ben Langmuir8832c062014-04-15 18:16:25 +00001264 return nullptr;
1265
Ilya Biryukov200b3282017-06-21 10:24:58 +00001266 SmallVector<StandaloneDiagnostic, 4> NewPreambleDiagsStandalone;
1267 SmallVector<StoredDiagnostic, 4> NewPreambleDiags;
Ilya Biryukovf81d46f2017-06-21 12:34:27 +00001268 ASTUnitPreambleCallbacks Callbacks;
Ilya Biryukov200b3282017-06-21 10:24:58 +00001269 {
1270 llvm::Optional<CaptureDroppedDiagnostics> Capture;
1271 if (CaptureDiagnostics)
1272 Capture.emplace(/*RequestCapture=*/true, *Diagnostics, &NewPreambleDiags,
1273 &NewPreambleDiagsStandalone);
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001274
Ilya Biryukov200b3282017-06-21 10:24:58 +00001275 // We did not previously compute a preamble, or it can't be reused anyway.
1276 SimpleTimer PreambleTimer(WantTiming);
1277 PreambleTimer.setOutput("Precompiling preamble");
Ahmed Charlesb8984322014-03-07 20:03:18 +00001278
Ilya Biryukov200b3282017-06-21 10:24:58 +00001279 llvm::ErrorOr<PrecompiledPreamble> NewPreamble = PrecompiledPreamble::Build(
1280 PreambleInvocationIn, MainFileBuffer.get(), Bounds, *Diagnostics, VFS,
1281 PCHContainerOps, Callbacks);
1282 if (NewPreamble) {
1283 Preamble = std::move(*NewPreamble);
1284 PreambleRebuildCounter = 1;
Dmitri Gribenko47652522013-12-20 00:16:25 +00001285 } else {
Ilya Biryukov200b3282017-06-21 10:24:58 +00001286 switch (static_cast<BuildPreambleError>(NewPreamble.getError().value())) {
1287 case BuildPreambleError::CouldntCreateTempFile:
1288 case BuildPreambleError::PreambleIsEmpty:
1289 // Try again next time.
1290 PreambleRebuildCounter = 1;
Ilya Biryukovf81d46f2017-06-21 12:34:27 +00001291 return nullptr;
Ilya Biryukov200b3282017-06-21 10:24:58 +00001292 case BuildPreambleError::CouldntCreateTargetInfo:
1293 case BuildPreambleError::BeginSourceFileFailed:
1294 case BuildPreambleError::CouldntEmitPCH:
1295 case BuildPreambleError::CouldntCreateVFSOverlay:
1296 // These erros are more likely to repeat, retry after some period.
1297 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Ilya Biryukovf81d46f2017-06-21 12:34:27 +00001298 return nullptr;
Ilya Biryukov200b3282017-06-21 10:24:58 +00001299 }
Ilya Biryukovf81d46f2017-06-21 12:34:27 +00001300 llvm_unreachable("unexpected BuildPreambleError");
Dmitri Gribenko47652522013-12-20 00:16:25 +00001301 }
Douglas Gregor0e119552010-07-31 00:40:00 +00001302 }
Ben Langmuir33c80902014-06-30 20:04:14 +00001303
Ilya Biryukov200b3282017-06-21 10:24:58 +00001304 assert(Preamble && "Preamble wasn't built");
1305
1306 TopLevelDecls.clear();
1307 TopLevelDeclsInPreamble = Callbacks.takeTopLevelDeclIDs();
1308 PreambleTopLevelHashValue = Callbacks.getHash();
1309
1310 NumWarningsInPreamble = getDiagnostics().getNumWarnings();
1311
1312 checkAndRemoveNonDriverDiags(NewPreambleDiags);
1313 StoredDiagnostics = std::move(NewPreambleDiags);
1314 PreambleDiagnostics = std::move(NewPreambleDiagsStandalone);
Alp Toker1b070d22014-07-07 07:47:20 +00001315
Douglas Gregordf7a79a2011-02-16 18:16:54 +00001316 // If the hash of top-level entities differs from the hash of the top-level
1317 // entities the last time we rebuilt the preamble, clear out the completion
1318 // cache.
1319 if (CurrentTopLevelHashValue != PreambleTopLevelHashValue) {
1320 CompletionCacheTopLevelHashValue = 0;
1321 PreambleTopLevelHashValue = CurrentTopLevelHashValue;
1322 }
Rafael Espindola2346a372014-08-18 18:47:08 +00001323
Ilya Biryukov200b3282017-06-21 10:24:58 +00001324 return MainFileBuffer;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001325}
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001326
Douglas Gregore9db88f2010-08-03 19:06:41 +00001327void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
Ilya Biryukov200b3282017-06-21 10:24:58 +00001328 assert(Preamble && "Should only be called when preamble was built");
1329
Douglas Gregore9db88f2010-08-03 19:06:41 +00001330 std::vector<Decl *> Resolved;
1331 Resolved.reserve(TopLevelDeclsInPreamble.size());
1332 ExternalASTSource &Source = *getASTContext().getExternalSource();
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00001333 for (serialization::DeclID TopLevelDecl : TopLevelDeclsInPreamble) {
Douglas Gregore9db88f2010-08-03 19:06:41 +00001334 // Resolve the declaration ID to an actual declaration, possibly
1335 // deserializing the declaration in the process.
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00001336 if (Decl *D = Source.GetExternalDecl(TopLevelDecl))
Douglas Gregore9db88f2010-08-03 19:06:41 +00001337 Resolved.push_back(D);
1338 }
1339 TopLevelDeclsInPreamble.clear();
1340 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1341}
1342
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001343void ASTUnit::transferASTDataFromCompilerInstance(CompilerInstance &CI) {
Ben Langmuir749323f2014-04-22 17:40:12 +00001344 // Steal the created target, context, and preprocessor if they have been
1345 // created.
1346 assert(CI.hasInvocation() && "missing invocation");
Alp Toker269d8402014-07-06 05:26:07 +00001347 LangOpts = CI.getInvocation().LangOpts;
David Blaikieec99b5e2014-08-10 19:14:48 +00001348 TheSema = CI.takeSema();
David Blaikie6beb6aa2014-08-10 19:56:51 +00001349 Consumer = CI.takeASTConsumer();
Ben Langmuir532fdc02014-04-18 20:39:48 +00001350 if (CI.hasASTContext())
1351 Ctx = &CI.getASTContext();
1352 if (CI.hasPreprocessor())
David Blaikie41565462017-01-05 19:48:07 +00001353 PP = CI.getPreprocessorPtr();
Craig Topper49a27902014-05-22 04:46:25 +00001354 CI.setSourceManager(nullptr);
1355 CI.setFileManager(nullptr);
Ben Langmuir532fdc02014-04-18 20:39:48 +00001356 if (CI.hasTarget())
1357 Target = &CI.getTarget();
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001358 Reader = CI.getModuleManager();
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00001359 HadModuleLoaderFatalFailure = CI.hadModuleLoaderFatalFailure();
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001360}
1361
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001362StringRef ASTUnit::getMainFileName() const {
Argyrios Kyrtzidis928e1fd2013-01-11 22:11:14 +00001363 if (Invocation && !Invocation->getFrontendOpts().Inputs.empty()) {
1364 const FrontendInputFile &Input = Invocation->getFrontendOpts().Inputs[0];
1365 if (Input.isFile())
1366 return Input.getFile();
1367 else
1368 return Input.getBuffer()->getBufferIdentifier();
1369 }
1370
1371 if (SourceMgr) {
1372 if (const FileEntry *
1373 FE = SourceMgr->getFileEntryForID(SourceMgr->getMainFileID()))
1374 return FE->getName();
1375 }
1376
1377 return StringRef();
Douglas Gregor16896c42010-10-28 15:44:59 +00001378}
1379
Argyrios Kyrtzidis37f2ab42013-03-05 20:21:14 +00001380StringRef ASTUnit::getASTFileName() const {
1381 if (!isMainFileAST())
1382 return StringRef();
1383
1384 serialization::ModuleFile &
1385 Mod = Reader->getModuleManager().getPrimaryModule();
1386 return Mod.FileName;
1387}
1388
David Blaikieea4395e2017-01-06 19:49:01 +00001389std::unique_ptr<ASTUnit>
1390ASTUnit::create(std::shared_ptr<CompilerInvocation> CI,
1391 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
1392 bool CaptureDiagnostics, bool UserFilesAreVolatile) {
1393 std::unique_ptr<ASTUnit> AST(new ASTUnit(false));
Justin Bognerdbbcb112014-10-14 23:36:06 +00001394 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
Ben Langmuir8832c062014-04-15 18:16:25 +00001395 IntrusiveRefCntPtr<vfs::FileSystem> VFS =
1396 createVFSFromCompilerInvocation(*CI, *Diags);
1397 if (!VFS)
1398 return nullptr;
David Blaikieea4395e2017-01-06 19:49:01 +00001399 AST->Diagnostics = Diags;
1400 AST->FileSystemOpts = CI->getFileSystemOpts();
1401 AST->Invocation = std::move(CI);
Ben Langmuir8832c062014-04-15 18:16:25 +00001402 AST->FileMgr = new FileManager(AST->FileSystemOpts, VFS);
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +00001403 AST->UserFilesAreVolatile = UserFilesAreVolatile;
1404 AST->SourceMgr = new SourceManager(AST->getDiagnostics(), *AST->FileMgr,
1405 UserFilesAreVolatile);
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00001406 AST->PCMCache = new MemoryBufferCache;
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00001407
David Blaikieea4395e2017-01-06 19:49:01 +00001408 return AST;
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00001409}
1410
Ahmed Charlesb8984322014-03-07 20:03:18 +00001411ASTUnit *ASTUnit::LoadFromCompilerInvocationAction(
David Blaikieea4395e2017-01-06 19:49:01 +00001412 std::shared_ptr<CompilerInvocation> CI,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001413 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
Argyrios Kyrtzidisc382abf2016-02-09 19:07:13 +00001414 IntrusiveRefCntPtr<DiagnosticsEngine> Diags, FrontendAction *Action,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001415 ASTUnit *Unit, bool Persistent, StringRef ResourceFilesPath,
Benjamin Kramer5c248d82015-12-15 09:30:31 +00001416 bool OnlyLocalDecls, bool CaptureDiagnostics,
1417 unsigned PrecompilePreambleAfterNParses, bool CacheCodeCompletionResults,
1418 bool IncludeBriefCommentsInCodeCompletion, bool UserFilesAreVolatile,
1419 std::unique_ptr<ASTUnit> *ErrAST) {
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001420 assert(CI && "A CompilerInvocation is required");
1421
Ahmed Charlesb8984322014-03-07 20:03:18 +00001422 std::unique_ptr<ASTUnit> OwnAST;
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001423 ASTUnit *AST = Unit;
1424 if (!AST) {
1425 // Create the AST unit.
David Blaikieea4395e2017-01-06 19:49:01 +00001426 OwnAST = create(CI, Diags, CaptureDiagnostics, UserFilesAreVolatile);
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001427 AST = OwnAST.get();
Ben Langmuir8832c062014-04-15 18:16:25 +00001428 if (!AST)
1429 return nullptr;
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001430 }
1431
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00001432 if (!ResourceFilesPath.empty()) {
1433 // Override the resources path.
1434 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
1435 }
1436 AST->OnlyLocalDecls = OnlyLocalDecls;
1437 AST->CaptureDiagnostics = CaptureDiagnostics;
Benjamin Kramer5c248d82015-12-15 09:30:31 +00001438 if (PrecompilePreambleAfterNParses > 0)
1439 AST->PreambleRebuildCounter = PrecompilePreambleAfterNParses;
Douglas Gregor69f74f82011-08-25 22:30:56 +00001440 AST->TUKind = Action ? Action->getTranslationUnitKind() : TU_Complete;
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00001441 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenko3292d062012-07-02 17:35:10 +00001442 AST->IncludeBriefCommentsInCodeCompletion
1443 = IncludeBriefCommentsInCodeCompletion;
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001444
1445 // Recover resources if we crash before exiting this method.
1446 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001447 ASTUnitCleanup(OwnAST.get());
David Blaikie9c902b52011-09-25 23:23:43 +00001448 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1449 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Alp Tokerf994cef2014-07-05 03:08:06 +00001450 DiagCleanup(Diags.get());
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001451
1452 // We'll manage file buffers ourselves.
1453 CI->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1454 CI->getFrontendOpts().DisableFree = false;
1455 ProcessWarningOptions(AST->getDiagnostics(), CI->getDiagnosticOpts());
1456
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001457 // Create the compiler instance to use for building the AST.
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001458 std::unique_ptr<CompilerInstance> Clang(
Benjamin Kramerd6da1a02016-06-12 20:05:23 +00001459 new CompilerInstance(std::move(PCHContainerOps)));
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001460
1461 // Recover resources if we crash before exiting this method.
1462 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1463 CICleanup(Clang.get());
1464
David Blaikieea4395e2017-01-06 19:49:01 +00001465 Clang->setInvocation(std::move(CI));
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001466 AST->OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001467
1468 // Set up diagnostics, capturing any diagnostics that would
1469 // otherwise be dropped.
1470 Clang->setDiagnostics(&AST->getDiagnostics());
1471
1472 // Create the target instance.
Alp Toker80758082014-07-06 05:26:44 +00001473 Clang->setTarget(TargetInfo::CreateTargetInfo(
Saleem Abdulrasool10a49722016-04-08 16:52:00 +00001474 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001475 if (!Clang->hasTarget())
Craig Topper49a27902014-05-22 04:46:25 +00001476 return nullptr;
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001477
1478 // Inform the target of the language options.
1479 //
1480 // FIXME: We shouldn't need to do this, the target should be immutable once
1481 // created. This complexity should be lifted elsewhere.
Alp Toker74437972014-07-06 05:14:24 +00001482 Clang->getTarget().adjust(Clang->getLangOpts());
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001483
1484 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1485 "Invocation must have exactly one source file!");
Richard Smith40c0efa2017-04-26 18:57:40 +00001486 assert(Clang->getFrontendOpts().Inputs[0].getKind().getFormat() ==
1487 InputKind::Source &&
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001488 "FIXME: AST inputs not yet supported here!");
Richard Smith40c0efa2017-04-26 18:57:40 +00001489 assert(Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() !=
1490 InputKind::LLVM_IR &&
1491 "IR inputs not support here!");
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001492
1493 // Configure the various subsystems.
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001494 AST->TheSema.reset();
Craig Topper49a27902014-05-22 04:46:25 +00001495 AST->Ctx = nullptr;
1496 AST->PP = nullptr;
1497 AST->Reader = nullptr;
1498
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001499 // Create a file manager object to provide access to and cache the filesystem.
1500 Clang->setFileManager(&AST->getFileManager());
1501
1502 // Create the source manager.
1503 Clang->setSourceManager(&AST->getSourceManager());
1504
Argyrios Kyrtzidisc382abf2016-02-09 19:07:13 +00001505 FrontendAction *Act = Action;
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001506
Ahmed Charlesb8984322014-03-07 20:03:18 +00001507 std::unique_ptr<TopLevelDeclTrackerAction> TrackerAct;
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001508 if (!Act) {
1509 TrackerAct.reset(new TopLevelDeclTrackerAction(*AST));
1510 Act = TrackerAct.get();
1511 }
1512
1513 // Recover resources if we crash before exiting this method.
1514 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1515 ActCleanup(TrackerAct.get());
1516
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001517 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
1518 AST->transferASTDataFromCompilerInstance(*Clang);
1519 if (OwnAST && ErrAST)
1520 ErrAST->swap(OwnAST);
1521
Craig Topper49a27902014-05-22 04:46:25 +00001522 return nullptr;
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001523 }
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00001524
1525 if (Persistent && !TrackerAct) {
1526 Clang->getPreprocessor().addPPCallbacks(
Craig Topperb8a70532014-09-10 04:53:53 +00001527 llvm::make_unique<MacroDefinitionTrackerPPCallbacks>(
1528 AST->getCurrentTopLevelHashValue()));
David Blaikie6beb6aa2014-08-10 19:56:51 +00001529 std::vector<std::unique_ptr<ASTConsumer>> Consumers;
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00001530 if (Clang->hasASTConsumer())
1531 Consumers.push_back(Clang->takeASTConsumer());
David Blaikie6beb6aa2014-08-10 19:56:51 +00001532 Consumers.push_back(llvm::make_unique<TopLevelDeclTrackerConsumer>(
1533 *AST, AST->getCurrentTopLevelHashValue()));
1534 Clang->setASTConsumer(
1535 llvm::make_unique<MultiplexConsumer>(std::move(Consumers)));
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00001536 }
Argyrios Kyrtzidis1416e172012-06-08 05:48:06 +00001537 if (!Act->Execute()) {
1538 AST->transferASTDataFromCompilerInstance(*Clang);
1539 if (OwnAST && ErrAST)
1540 ErrAST->swap(OwnAST);
1541
Craig Topper49a27902014-05-22 04:46:25 +00001542 return nullptr;
Argyrios Kyrtzidis1416e172012-06-08 05:48:06 +00001543 }
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001544
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001545 // Steal the created target, context, and preprocessor.
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001546 AST->transferASTDataFromCompilerInstance(*Clang);
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001547
1548 Act->EndSourceFile();
1549
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001550 if (OwnAST)
Ahmed Charles9a16beb2014-03-07 19:33:25 +00001551 return OwnAST.release();
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001552 else
1553 return AST;
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001554}
1555
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001556bool ASTUnit::LoadFromCompilerInvocation(
1557 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001558 unsigned PrecompilePreambleAfterNParses,
1559 IntrusiveRefCntPtr<vfs::FileSystem> VFS) {
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001560 if (!Invocation)
1561 return true;
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001562
1563 assert(VFS && "VFS is null");
1564
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001565 // We'll manage file buffers ourselves.
1566 Invocation->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1567 Invocation->getFrontendOpts().DisableFree = false;
Benjamin Kramer8de9c9b2017-01-18 16:25:48 +00001568 getDiagnostics().Reset();
Douglas Gregor345c1bc2011-01-19 01:02:47 +00001569 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001570
Rafael Espindola32482082014-08-18 16:23:45 +00001571 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
Benjamin Kramer5c248d82015-12-15 09:30:31 +00001572 if (PrecompilePreambleAfterNParses > 0) {
1573 PreambleRebuildCounter = PrecompilePreambleAfterNParses;
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001574 OverrideMainBuffer =
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001575 getMainBufferWithPrecompiledPreamble(PCHContainerOps, *Invocation, VFS);
Benjamin Kramer8484a322017-02-13 16:16:43 +00001576 getDiagnostics().Reset();
1577 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001578 }
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001579
Douglas Gregor16896c42010-10-28 15:44:59 +00001580 SimpleTimer ParsingTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00001581 ParsingTimer.setOutput("Parsing " + getMainFileName());
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001582
Ted Kremenek022a4902011-03-22 01:15:24 +00001583 // Recover resources if we crash before exiting this method.
1584 llvm::CrashRecoveryContextCleanupRegistrar<llvm::MemoryBuffer>
Rafael Espindola32482082014-08-18 16:23:45 +00001585 MemBufferCleanup(OverrideMainBuffer.get());
1586
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001587 return Parse(std::move(PCHContainerOps), std::move(OverrideMainBuffer), VFS);
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001588}
1589
David Blaikie103a2de2014-04-25 17:01:33 +00001590std::unique_ptr<ASTUnit> ASTUnit::LoadFromCompilerInvocation(
David Blaikieea4395e2017-01-06 19:49:01 +00001591 std::shared_ptr<CompilerInvocation> CI,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001592 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
Benjamin Kramerbc632902015-10-06 14:45:20 +00001593 IntrusiveRefCntPtr<DiagnosticsEngine> Diags, FileManager *FileMgr,
Benjamin Kramer5c248d82015-12-15 09:30:31 +00001594 bool OnlyLocalDecls, bool CaptureDiagnostics,
1595 unsigned PrecompilePreambleAfterNParses, TranslationUnitKind TUKind,
1596 bool CacheCodeCompletionResults, bool IncludeBriefCommentsInCodeCompletion,
1597 bool UserFilesAreVolatile) {
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001598 // Create the AST unit.
David Blaikie103a2de2014-04-25 17:01:33 +00001599 std::unique_ptr<ASTUnit> AST(new ASTUnit(false));
Justin Bognerdbbcb112014-10-14 23:36:06 +00001600 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001601 AST->Diagnostics = Diags;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001602 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001603 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor69f74f82011-08-25 22:30:56 +00001604 AST->TUKind = TUKind;
Douglas Gregorb14904c2010-08-13 22:48:40 +00001605 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenko3292d062012-07-02 17:35:10 +00001606 AST->IncludeBriefCommentsInCodeCompletion
1607 = IncludeBriefCommentsInCodeCompletion;
David Blaikieea4395e2017-01-06 19:49:01 +00001608 AST->Invocation = std::move(CI);
Benjamin Kramerbc632902015-10-06 14:45:20 +00001609 AST->FileSystemOpts = FileMgr->getFileSystemOpts();
1610 AST->FileMgr = FileMgr;
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +00001611 AST->UserFilesAreVolatile = UserFilesAreVolatile;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001612
Ted Kremenek4422bfe2011-03-18 02:06:56 +00001613 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00001614 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1615 ASTUnitCleanup(AST.get());
David Blaikie9c902b52011-09-25 23:23:43 +00001616 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1617 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Alp Tokerf994cef2014-07-05 03:08:06 +00001618 DiagCleanup(Diags.get());
Ted Kremenek4422bfe2011-03-18 02:06:56 +00001619
Benjamin Kramerd6da1a02016-06-12 20:05:23 +00001620 if (AST->LoadFromCompilerInvocation(std::move(PCHContainerOps),
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001621 PrecompilePreambleAfterNParses,
1622 AST->FileMgr->getVirtualFileSystem()))
David Blaikie103a2de2014-04-25 17:01:33 +00001623 return nullptr;
1624 return AST;
Daniel Dunbar764c0822009-12-01 09:51:01 +00001625}
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001626
Ahmed Charlesb8984322014-03-07 20:03:18 +00001627ASTUnit *ASTUnit::LoadFromCommandLine(
1628 const char **ArgBegin, const char **ArgEnd,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001629 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
Ahmed Charlesb8984322014-03-07 20:03:18 +00001630 IntrusiveRefCntPtr<DiagnosticsEngine> Diags, StringRef ResourceFilesPath,
1631 bool OnlyLocalDecls, bool CaptureDiagnostics,
1632 ArrayRef<RemappedFile> RemappedFiles, bool RemappedFilesKeepOriginalName,
Benjamin Kramer5c248d82015-12-15 09:30:31 +00001633 unsigned PrecompilePreambleAfterNParses, TranslationUnitKind TUKind,
Ahmed Charlesb8984322014-03-07 20:03:18 +00001634 bool CacheCodeCompletionResults, bool IncludeBriefCommentsInCodeCompletion,
1635 bool AllowPCHWithCompilerErrors, bool SkipFunctionBodies,
Argyrios Kyrtzidis735e92c2017-06-09 01:20:48 +00001636 bool SingleFileParse, bool UserFilesAreVolatile, bool ForSerialization,
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001637 llvm::Optional<StringRef> ModuleFormat, std::unique_ptr<ASTUnit> *ErrAST,
1638 IntrusiveRefCntPtr<vfs::FileSystem> VFS) {
Justin Bognerd512c1e2014-10-15 00:33:06 +00001639 assert(Diags.get() && "no DiagnosticsEngine was provided");
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001640
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001641 SmallVector<StoredDiagnostic, 4> StoredDiagnostics;
David Blaikieea4395e2017-01-06 19:49:01 +00001642
1643 std::shared_ptr<CompilerInvocation> CI;
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001644
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001645 {
Douglas Gregor925296b2011-07-19 16:10:42 +00001646
Ilya Biryukov200b3282017-06-21 10:24:58 +00001647 CaptureDroppedDiagnostics Capture(CaptureDiagnostics, *Diags,
1648 &StoredDiagnostics, nullptr);
Daniel Dunbarfcf2d422010-01-25 00:44:02 +00001649
Argyrios Kyrtzidis5cf423e2011-04-04 23:11:45 +00001650 CI = clang::createInvocationFromCommandLine(
Ilya Biryukovafdadf52017-06-28 15:06:34 +00001651 llvm::makeArrayRef(ArgBegin, ArgEnd), Diags, VFS);
Argyrios Kyrtzidisf606b822011-04-04 21:38:51 +00001652 if (!CI)
Craig Topper49a27902014-05-22 04:46:25 +00001653 return nullptr;
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001654 }
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001655
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001656 // Override any files that need remapping
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00001657 for (const auto &RemappedFile : RemappedFiles) {
1658 CI->getPreprocessorOpts().addRemappedFile(RemappedFile.first,
1659 RemappedFile.second);
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00001660 }
Argyrios Kyrtzidis4a280ff2012-03-07 01:51:17 +00001661 PreprocessorOptions &PPOpts = CI->getPreprocessorOpts();
1662 PPOpts.RemappedFilesKeepOriginalName = RemappedFilesKeepOriginalName;
1663 PPOpts.AllowPCHWithCompilerErrors = AllowPCHWithCompilerErrors;
Erik Verbruggenb34c79f2017-05-30 11:54:55 +00001664 PPOpts.GeneratePreamble = PrecompilePreambleAfterNParses != 0;
Argyrios Kyrtzidis735e92c2017-06-09 01:20:48 +00001665 PPOpts.SingleFileParseMode = SingleFileParse;
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001666
Daniel Dunbara5a166d2009-12-15 00:06:45 +00001667 // Override the resources path.
Daniel Dunbar6b03ece2010-01-30 21:47:16 +00001668 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001669
Erik Verbruggen6e922512012-04-12 10:11:59 +00001670 CI->getFrontendOpts().SkipFunctionBodies = SkipFunctionBodies;
1671
Argyrios Kyrtzidisa3e2ff12015-11-20 03:36:21 +00001672 if (ModuleFormat)
1673 CI->getHeaderSearchOpts().ModuleFormat = ModuleFormat.getValue();
1674
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001675 // Create the AST unit.
Ahmed Charlesb8984322014-03-07 20:03:18 +00001676 std::unique_ptr<ASTUnit> AST;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001677 AST.reset(new ASTUnit(false));
Justin Bognerdbbcb112014-10-14 23:36:06 +00001678 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001679 AST->Diagnostics = Diags;
Anders Carlssonc30dcec2011-03-18 18:22:40 +00001680 AST->FileSystemOpts = CI->getFileSystemOpts();
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001681 if (!VFS)
1682 VFS = vfs::getRealFileSystem();
1683 VFS = createVFSFromCompilerInvocation(*CI, *Diags, VFS);
Ben Langmuir8832c062014-04-15 18:16:25 +00001684 if (!VFS)
1685 return nullptr;
1686 AST->FileMgr = new FileManager(AST->FileSystemOpts, VFS);
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00001687 AST->PCMCache = new MemoryBufferCache;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001688 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001689 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor69f74f82011-08-25 22:30:56 +00001690 AST->TUKind = TUKind;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001691 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenko3292d062012-07-02 17:35:10 +00001692 AST->IncludeBriefCommentsInCodeCompletion
1693 = IncludeBriefCommentsInCodeCompletion;
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +00001694 AST->UserFilesAreVolatile = UserFilesAreVolatile;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001695 AST->NumStoredDiagnosticsFromDriver = StoredDiagnostics.size();
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001696 AST->StoredDiagnostics.swap(StoredDiagnostics);
Ted Kremenek5e14d392011-03-21 18:40:17 +00001697 AST->Invocation = CI;
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00001698 if (ForSerialization)
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00001699 AST->WriterData.reset(new ASTWriterData(*AST->PCMCache));
Alexey Samsonovb4f99dd2014-08-28 23:51:01 +00001700 // Zero out now to ease cleanup during crash recovery.
1701 CI = nullptr;
1702 Diags = nullptr;
Craig Topper49a27902014-05-22 04:46:25 +00001703
Ted Kremenek4422bfe2011-03-18 02:06:56 +00001704 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00001705 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1706 ASTUnitCleanup(AST.get());
Ted Kremenek4422bfe2011-03-18 02:06:56 +00001707
Benjamin Kramerd6da1a02016-06-12 20:05:23 +00001708 if (AST->LoadFromCompilerInvocation(std::move(PCHContainerOps),
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001709 PrecompilePreambleAfterNParses,
1710 VFS)) {
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001711 // Some error occurred, if caller wants to examine diagnostics, pass it the
1712 // ASTUnit.
1713 if (ErrAST) {
1714 AST->StoredDiagnostics.swap(AST->FailedParseDiagnostics);
1715 ErrAST->swap(AST);
1716 }
Craig Topper49a27902014-05-22 04:46:25 +00001717 return nullptr;
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001718 }
1719
Ahmed Charles9a16beb2014-03-07 19:33:25 +00001720 return AST.release();
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001721}
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001722
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001723bool ASTUnit::Reparse(std::shared_ptr<PCHContainerOperations> PCHContainerOps,
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001724 ArrayRef<RemappedFile> RemappedFiles,
1725 IntrusiveRefCntPtr<vfs::FileSystem> VFS) {
Ted Kremenek5e14d392011-03-21 18:40:17 +00001726 if (!Invocation)
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001727 return true;
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00001728
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001729 if (!VFS) {
1730 assert(FileMgr && "FileMgr is null on Reparse call");
1731 VFS = FileMgr->getVirtualFileSystem();
1732 }
1733
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00001734 clearFileLevelDecls();
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001735
Douglas Gregor16896c42010-10-28 15:44:59 +00001736 SimpleTimer ParsingTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00001737 ParsingTimer.setOutput("Reparsing " + getMainFileName());
Douglas Gregor16896c42010-10-28 15:44:59 +00001738
Douglas Gregor0e119552010-07-31 00:40:00 +00001739 // Remap files.
Douglas Gregor7b02b582010-08-20 00:02:33 +00001740 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
Alp Toker1b070d22014-07-07 07:47:20 +00001741 for (const auto &RB : PPOpts.RemappedFileBuffers)
1742 delete RB.second;
1743
Douglas Gregor0e119552010-07-31 00:40:00 +00001744 Invocation->getPreprocessorOpts().clearRemappedFiles();
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00001745 for (const auto &RemappedFile : RemappedFiles) {
1746 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFile.first,
1747 RemappedFile.second);
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00001748 }
Dmitri Gribenkoc444b572014-02-08 00:38:15 +00001749
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001750 // If we have a preamble file lying around, or if we might try to
1751 // build a precompiled preamble, do so now.
Rafael Espindola32482082014-08-18 16:23:45 +00001752 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
Ilya Biryukov200b3282017-06-21 10:24:58 +00001753 if (Preamble || PreambleRebuildCounter > 0)
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001754 OverrideMainBuffer =
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001755 getMainBufferWithPrecompiledPreamble(PCHContainerOps, *Invocation, VFS);
1756
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001757
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001758 // Clear out the diagnostics state.
Benjamin Kramerbc632902015-10-06 14:45:20 +00001759 FileMgr.reset();
Argyrios Kyrtzidisf50f7b22011-11-03 20:28:19 +00001760 getDiagnostics().Reset();
1761 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Argyrios Kyrtzidis462ff352011-11-03 20:57:33 +00001762 if (OverrideMainBuffer)
1763 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
Argyrios Kyrtzidisf50f7b22011-11-03 20:28:19 +00001764
Douglas Gregor4dde7492010-07-23 23:58:40 +00001765 // Parse the sources
Benjamin Kramerd6da1a02016-06-12 20:05:23 +00001766 bool Result =
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001767 Parse(std::move(PCHContainerOps), std::move(OverrideMainBuffer), VFS);
Rafael Espindola32482082014-08-18 16:23:45 +00001768
Argyrios Kyrtzidis36893372011-10-31 21:25:31 +00001769 // If we're caching global code-completion results, and the top-level
1770 // declarations have changed, clear out the code-completion cache.
1771 if (!Result && ShouldCacheCodeCompletionResults &&
1772 CurrentTopLevelHashValue != CompletionCacheTopLevelHashValue)
1773 CacheCodeCompletionResults();
Douglas Gregordf7a79a2011-02-16 18:16:54 +00001774
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00001775 // We now need to clear out the completion info related to this translation
1776 // unit; it'll be recreated if necessary.
1777 CCTUInfo.reset();
Douglas Gregor3f35bb22011-08-04 20:04:59 +00001778
Douglas Gregor4dde7492010-07-23 23:58:40 +00001779 return Result;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001780}
Douglas Gregor8e984da2010-08-04 16:47:14 +00001781
Erik Verbruggen346066b2017-05-30 14:25:54 +00001782void ASTUnit::ResetForParse() {
1783 SavedMainFileBuffer.reset();
1784
1785 SourceMgr.reset();
1786 TheSema.reset();
1787 Ctx.reset();
1788 PP.reset();
1789 Reader.reset();
1790
1791 TopLevelDecls.clear();
1792 clearFileLevelDecls();
1793}
1794
Douglas Gregorb14904c2010-08-13 22:48:40 +00001795//----------------------------------------------------------------------------//
1796// Code completion
1797//----------------------------------------------------------------------------//
1798
1799namespace {
1800 /// \brief Code completion consumer that combines the cached code-completion
1801 /// results from an ASTUnit with the code-completion results provided to it,
1802 /// then passes the result on to
1803 class AugmentedCodeCompleteConsumer : public CodeCompleteConsumer {
Richard Smith697cc9e2012-08-14 03:13:00 +00001804 uint64_t NormalContexts;
Douglas Gregorb14904c2010-08-13 22:48:40 +00001805 ASTUnit &AST;
1806 CodeCompleteConsumer &Next;
1807
1808 public:
1809 AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next,
Dmitri Gribenko3292d062012-07-02 17:35:10 +00001810 const CodeCompleteOptions &CodeCompleteOpts)
1811 : CodeCompleteConsumer(CodeCompleteOpts, Next.isOutputBinary()),
1812 AST(AST), Next(Next)
Douglas Gregorb14904c2010-08-13 22:48:40 +00001813 {
1814 // Compute the set of contexts in which we will look when we don't have
1815 // any information about the specific context.
1816 NormalContexts
Richard Smith697cc9e2012-08-14 03:13:00 +00001817 = (1LL << CodeCompletionContext::CCC_TopLevel)
1818 | (1LL << CodeCompletionContext::CCC_ObjCInterface)
1819 | (1LL << CodeCompletionContext::CCC_ObjCImplementation)
1820 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
1821 | (1LL << CodeCompletionContext::CCC_Statement)
1822 | (1LL << CodeCompletionContext::CCC_Expression)
1823 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
1824 | (1LL << CodeCompletionContext::CCC_DotMemberAccess)
1825 | (1LL << CodeCompletionContext::CCC_ArrowMemberAccess)
1826 | (1LL << CodeCompletionContext::CCC_ObjCPropertyAccess)
1827 | (1LL << CodeCompletionContext::CCC_ObjCProtocolName)
1828 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
1829 | (1LL << CodeCompletionContext::CCC_Recovery);
Douglas Gregor5e35d592010-09-14 23:59:36 +00001830
David Blaikiebbafb8a2012-03-11 07:00:24 +00001831 if (AST.getASTContext().getLangOpts().CPlusPlus)
Richard Smith697cc9e2012-08-14 03:13:00 +00001832 NormalContexts |= (1LL << CodeCompletionContext::CCC_EnumTag)
1833 | (1LL << CodeCompletionContext::CCC_UnionTag)
1834 | (1LL << CodeCompletionContext::CCC_ClassOrStructTag);
Douglas Gregorb14904c2010-08-13 22:48:40 +00001835 }
Craig Topperafa7cb32014-03-13 06:07:04 +00001836
1837 void ProcessCodeCompleteResults(Sema &S, CodeCompletionContext Context,
1838 CodeCompletionResult *Results,
1839 unsigned NumResults) override;
1840
1841 void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
1842 OverloadCandidate *Candidates,
1843 unsigned NumCandidates) override {
Douglas Gregorb14904c2010-08-13 22:48:40 +00001844 Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates);
1845 }
Craig Topperafa7cb32014-03-13 06:07:04 +00001846
1847 CodeCompletionAllocator &getAllocator() override {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001848 return Next.getAllocator();
1849 }
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00001850
Craig Topperafa7cb32014-03-13 06:07:04 +00001851 CodeCompletionTUInfo &getCodeCompletionTUInfo() override {
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00001852 return Next.getCodeCompletionTUInfo();
1853 }
Douglas Gregorb14904c2010-08-13 22:48:40 +00001854 };
Hans Wennborgdcfba332015-10-06 23:40:43 +00001855} // anonymous namespace
Douglas Gregord46cf182010-08-16 20:01:48 +00001856
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001857/// \brief Helper function that computes which global names are hidden by the
1858/// local code-completion results.
Ted Kremenek6a153372010-11-07 06:11:36 +00001859static void CalculateHiddenNames(const CodeCompletionContext &Context,
1860 CodeCompletionResult *Results,
1861 unsigned NumResults,
1862 ASTContext &Ctx,
1863 llvm::StringSet<llvm::BumpPtrAllocator> &HiddenNames){
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001864 bool OnlyTagNames = false;
1865 switch (Context.getKind()) {
Douglas Gregor0ac41382010-09-23 23:01:17 +00001866 case CodeCompletionContext::CCC_Recovery:
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001867 case CodeCompletionContext::CCC_TopLevel:
1868 case CodeCompletionContext::CCC_ObjCInterface:
1869 case CodeCompletionContext::CCC_ObjCImplementation:
1870 case CodeCompletionContext::CCC_ObjCIvarList:
1871 case CodeCompletionContext::CCC_ClassStructUnion:
1872 case CodeCompletionContext::CCC_Statement:
1873 case CodeCompletionContext::CCC_Expression:
1874 case CodeCompletionContext::CCC_ObjCMessageReceiver:
Douglas Gregor21325842011-07-07 16:03:39 +00001875 case CodeCompletionContext::CCC_DotMemberAccess:
1876 case CodeCompletionContext::CCC_ArrowMemberAccess:
1877 case CodeCompletionContext::CCC_ObjCPropertyAccess:
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001878 case CodeCompletionContext::CCC_Namespace:
1879 case CodeCompletionContext::CCC_Type:
Douglas Gregorc49f5b22010-08-23 18:23:48 +00001880 case CodeCompletionContext::CCC_Name:
1881 case CodeCompletionContext::CCC_PotentiallyQualifiedName:
Douglas Gregor5e35d592010-09-14 23:59:36 +00001882 case CodeCompletionContext::CCC_ParenthesizedExpression:
Douglas Gregor2c595ad2011-07-30 06:55:39 +00001883 case CodeCompletionContext::CCC_ObjCInterfaceName:
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001884 break;
1885
1886 case CodeCompletionContext::CCC_EnumTag:
1887 case CodeCompletionContext::CCC_UnionTag:
1888 case CodeCompletionContext::CCC_ClassOrStructTag:
1889 OnlyTagNames = true;
1890 break;
1891
1892 case CodeCompletionContext::CCC_ObjCProtocolName:
Douglas Gregor12785102010-08-24 20:21:13 +00001893 case CodeCompletionContext::CCC_MacroName:
1894 case CodeCompletionContext::CCC_MacroNameUse:
Douglas Gregorec00a262010-08-24 22:20:20 +00001895 case CodeCompletionContext::CCC_PreprocessorExpression:
Douglas Gregor0de55ce2010-08-25 18:41:16 +00001896 case CodeCompletionContext::CCC_PreprocessorDirective:
Douglas Gregorea147052010-08-25 18:04:30 +00001897 case CodeCompletionContext::CCC_NaturalLanguage:
Douglas Gregor67c692c2010-08-26 15:07:07 +00001898 case CodeCompletionContext::CCC_SelectorName:
Douglas Gregor28c78432010-08-27 17:35:51 +00001899 case CodeCompletionContext::CCC_TypeQualifiers:
Douglas Gregor0ac41382010-09-23 23:01:17 +00001900 case CodeCompletionContext::CCC_Other:
Douglas Gregor3a69eaf2011-02-18 23:30:37 +00001901 case CodeCompletionContext::CCC_OtherWithMacros:
Douglas Gregor21325842011-07-07 16:03:39 +00001902 case CodeCompletionContext::CCC_ObjCInstanceMessage:
1903 case CodeCompletionContext::CCC_ObjCClassMessage:
1904 case CodeCompletionContext::CCC_ObjCCategoryName:
Douglas Gregor0de55ce2010-08-25 18:41:16 +00001905 // We're looking for nothing, or we're looking for names that cannot
1906 // be hidden.
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001907 return;
1908 }
1909
John McCall276321a2010-08-25 06:19:51 +00001910 typedef CodeCompletionResult Result;
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001911 for (unsigned I = 0; I != NumResults; ++I) {
1912 if (Results[I].Kind != Result::RK_Declaration)
1913 continue;
1914
1915 unsigned IDNS
1916 = Results[I].Declaration->getUnderlyingDecl()->getIdentifierNamespace();
1917
1918 bool Hiding = false;
1919 if (OnlyTagNames)
1920 Hiding = (IDNS & Decl::IDNS_Tag);
1921 else {
1922 unsigned HiddenIDNS = (Decl::IDNS_Type | Decl::IDNS_Member |
Douglas Gregor59cab552010-08-16 23:05:20 +00001923 Decl::IDNS_Namespace | Decl::IDNS_Ordinary |
1924 Decl::IDNS_NonMemberOperator);
David Blaikiebbafb8a2012-03-11 07:00:24 +00001925 if (Ctx.getLangOpts().CPlusPlus)
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001926 HiddenIDNS |= Decl::IDNS_Tag;
1927 Hiding = (IDNS & HiddenIDNS);
1928 }
1929
1930 if (!Hiding)
1931 continue;
1932
1933 DeclarationName Name = Results[I].Declaration->getDeclName();
1934 if (IdentifierInfo *Identifier = Name.getAsIdentifierInfo())
1935 HiddenNames.insert(Identifier->getName());
1936 else
1937 HiddenNames.insert(Name.getAsString());
1938 }
1939}
1940
Douglas Gregord46cf182010-08-16 20:01:48 +00001941void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &S,
1942 CodeCompletionContext Context,
John McCall276321a2010-08-25 06:19:51 +00001943 CodeCompletionResult *Results,
Douglas Gregord46cf182010-08-16 20:01:48 +00001944 unsigned NumResults) {
1945 // Merge the results we were given with the results we cached.
1946 bool AddedResult = false;
Richard Smith697cc9e2012-08-14 03:13:00 +00001947 uint64_t InContexts =
1948 Context.getKind() == CodeCompletionContext::CCC_Recovery
1949 ? NormalContexts : (1LL << Context.getKind());
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001950 // Contains the set of names that are hidden by "local" completion results.
Ted Kremenek6a153372010-11-07 06:11:36 +00001951 llvm::StringSet<llvm::BumpPtrAllocator> HiddenNames;
John McCall276321a2010-08-25 06:19:51 +00001952 typedef CodeCompletionResult Result;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001953 SmallVector<Result, 8> AllResults;
Douglas Gregord46cf182010-08-16 20:01:48 +00001954 for (ASTUnit::cached_completion_iterator
Douglas Gregordf239672010-08-16 21:23:13 +00001955 C = AST.cached_completion_begin(),
1956 CEnd = AST.cached_completion_end();
Douglas Gregord46cf182010-08-16 20:01:48 +00001957 C != CEnd; ++C) {
1958 // If the context we are in matches any of the contexts we are
1959 // interested in, we'll add this result.
1960 if ((C->ShowInContexts & InContexts) == 0)
1961 continue;
1962
1963 // If we haven't added any results previously, do so now.
1964 if (!AddedResult) {
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001965 CalculateHiddenNames(Context, Results, NumResults, S.Context,
1966 HiddenNames);
Douglas Gregord46cf182010-08-16 20:01:48 +00001967 AllResults.insert(AllResults.end(), Results, Results + NumResults);
1968 AddedResult = true;
1969 }
1970
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001971 // Determine whether this global completion result is hidden by a local
1972 // completion result. If so, skip it.
1973 if (C->Kind != CXCursor_MacroDefinition &&
1974 HiddenNames.count(C->Completion->getTypedText()))
1975 continue;
1976
Douglas Gregord46cf182010-08-16 20:01:48 +00001977 // Adjust priority based on similar type classes.
1978 unsigned Priority = C->Priority;
Douglas Gregor12785102010-08-24 20:21:13 +00001979 CodeCompletionString *Completion = C->Completion;
Douglas Gregord46cf182010-08-16 20:01:48 +00001980 if (!Context.getPreferredType().isNull()) {
1981 if (C->Kind == CXCursor_MacroDefinition) {
1982 Priority = getMacroUsagePriority(C->Completion->getTypedText(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00001983 S.getLangOpts(),
Douglas Gregor12785102010-08-24 20:21:13 +00001984 Context.getPreferredType()->isAnyPointerType());
Douglas Gregord46cf182010-08-16 20:01:48 +00001985 } else if (C->Type) {
1986 CanQualType Expected
Douglas Gregordf239672010-08-16 21:23:13 +00001987 = S.Context.getCanonicalType(
Douglas Gregord46cf182010-08-16 20:01:48 +00001988 Context.getPreferredType().getUnqualifiedType());
1989 SimplifiedTypeClass ExpectedSTC = getSimplifiedTypeClass(Expected);
1990 if (ExpectedSTC == C->TypeClass) {
1991 // We know this type is similar; check for an exact match.
1992 llvm::StringMap<unsigned> &CachedCompletionTypes
Douglas Gregordf239672010-08-16 21:23:13 +00001993 = AST.getCachedCompletionTypes();
Douglas Gregord46cf182010-08-16 20:01:48 +00001994 llvm::StringMap<unsigned>::iterator Pos
Douglas Gregordf239672010-08-16 21:23:13 +00001995 = CachedCompletionTypes.find(QualType(Expected).getAsString());
Douglas Gregord46cf182010-08-16 20:01:48 +00001996 if (Pos != CachedCompletionTypes.end() && Pos->second == C->Type)
1997 Priority /= CCF_ExactTypeMatch;
1998 else
1999 Priority /= CCF_SimilarTypeMatch;
2000 }
2001 }
2002 }
2003
Douglas Gregor12785102010-08-24 20:21:13 +00002004 // Adjust the completion string, if required.
2005 if (C->Kind == CXCursor_MacroDefinition &&
2006 Context.getKind() == CodeCompletionContext::CCC_MacroNameUse) {
2007 // Create a new code-completion string that just contains the
2008 // macro name, without its arguments.
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00002009 CodeCompletionBuilder Builder(getAllocator(), getCodeCompletionTUInfo(),
2010 CCP_CodePattern, C->Availability);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002011 Builder.AddTypedTextChunk(C->Completion->getTypedText());
Douglas Gregor8850aa32010-08-25 18:03:13 +00002012 Priority = CCP_CodePattern;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002013 Completion = Builder.TakeString();
Douglas Gregor12785102010-08-24 20:21:13 +00002014 }
2015
Argyrios Kyrtzidis5c8b1cd2012-09-27 00:24:09 +00002016 AllResults.push_back(Result(Completion, Priority, C->Kind,
Douglas Gregorf757a122010-08-23 23:00:57 +00002017 C->Availability));
Douglas Gregord46cf182010-08-16 20:01:48 +00002018 }
2019
2020 // If we did not add any cached completion results, just forward the
2021 // results we were given to the next consumer.
2022 if (!AddedResult) {
2023 Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
2024 return;
2025 }
Douglas Gregor49f67ce2010-08-26 13:48:20 +00002026
Douglas Gregord46cf182010-08-16 20:01:48 +00002027 Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
2028 AllResults.size());
2029}
2030
Adrian Prantlbb165fb2015-06-20 18:53:08 +00002031void ASTUnit::CodeComplete(
2032 StringRef File, unsigned Line, unsigned Column,
2033 ArrayRef<RemappedFile> RemappedFiles, bool IncludeMacros,
2034 bool IncludeCodePatterns, bool IncludeBriefComments,
2035 CodeCompleteConsumer &Consumer,
2036 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
2037 DiagnosticsEngine &Diag, LangOptions &LangOpts, SourceManager &SourceMgr,
2038 FileManager &FileMgr, SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
2039 SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers) {
Ted Kremenek5e14d392011-03-21 18:40:17 +00002040 if (!Invocation)
Douglas Gregor8e984da2010-08-04 16:47:14 +00002041 return;
2042
Douglas Gregor16896c42010-10-28 15:44:59 +00002043 SimpleTimer CompletionTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00002044 CompletionTimer.setOutput("Code completion @ " + File + ":" +
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002045 Twine(Line) + ":" + Twine(Column));
Douglas Gregor028d3e42010-08-09 20:45:32 +00002046
David Blaikieea4395e2017-01-06 19:49:01 +00002047 auto CCInvocation = std::make_shared<CompilerInvocation>(*Invocation);
Ted Kremenek5e14d392011-03-21 18:40:17 +00002048
2049 FrontendOptions &FrontendOpts = CCInvocation->getFrontendOpts();
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002050 CodeCompleteOptions &CodeCompleteOpts = FrontendOpts.CodeCompleteOpts;
Ted Kremenek5e14d392011-03-21 18:40:17 +00002051 PreprocessorOptions &PreprocessorOpts = CCInvocation->getPreprocessorOpts();
Douglas Gregorb68bc592010-08-05 09:09:23 +00002052
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002053 CodeCompleteOpts.IncludeMacros = IncludeMacros &&
2054 CachedCompletionResults.empty();
2055 CodeCompleteOpts.IncludeCodePatterns = IncludeCodePatterns;
2056 CodeCompleteOpts.IncludeGlobals = CachedCompletionResults.empty();
2057 CodeCompleteOpts.IncludeBriefComments = IncludeBriefComments;
2058
2059 assert(IncludeBriefComments == this->IncludeBriefCommentsInCodeCompletion);
2060
Douglas Gregor8e984da2010-08-04 16:47:14 +00002061 FrontendOpts.CodeCompletionAt.FileName = File;
2062 FrontendOpts.CodeCompletionAt.Line = Line;
2063 FrontendOpts.CodeCompletionAt.Column = Column;
2064
2065 // Set the language options appropriately.
Ted Kremenek8cf47df2011-11-17 23:01:24 +00002066 LangOpts = *CCInvocation->getLangOpts();
Douglas Gregor8e984da2010-08-04 16:47:14 +00002067
Argyrios Kyrtzidis06e8d692014-10-31 16:44:32 +00002068 // Spell-checking and warnings are wasteful during code-completion.
2069 LangOpts.SpellChecking = false;
2070 CCInvocation->getDiagnosticOpts().IgnoreWarnings = true;
2071
Adrian Prantlbb165fb2015-06-20 18:53:08 +00002072 std::unique_ptr<CompilerInstance> Clang(
2073 new CompilerInstance(PCHContainerOps));
Ted Kremenek84de4a12011-03-21 18:40:07 +00002074
2075 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00002076 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
2077 CICleanup(Clang.get());
Ted Kremenek84de4a12011-03-21 18:40:07 +00002078
David Blaikieea4395e2017-01-06 19:49:01 +00002079 auto &Inv = *CCInvocation;
2080 Clang->setInvocation(std::move(CCInvocation));
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00002081 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
Douglas Gregor8e984da2010-08-04 16:47:14 +00002082
2083 // Set up diagnostics, capturing any diagnostics produced.
Ted Kremenek84de4a12011-03-21 18:40:07 +00002084 Clang->setDiagnostics(&Diag);
Douglas Gregor8e984da2010-08-04 16:47:14 +00002085 CaptureDroppedDiagnostics Capture(true,
Ted Kremenek84de4a12011-03-21 18:40:07 +00002086 Clang->getDiagnostics(),
Ilya Biryukov200b3282017-06-21 10:24:58 +00002087 &StoredDiagnostics, nullptr);
David Blaikieea4395e2017-01-06 19:49:01 +00002088 ProcessWarningOptions(Diag, Inv.getDiagnosticOpts());
2089
Douglas Gregor8e984da2010-08-04 16:47:14 +00002090 // Create the target instance.
Alp Toker80758082014-07-06 05:26:44 +00002091 Clang->setTarget(TargetInfo::CreateTargetInfo(
Saleem Abdulrasool10a49722016-04-08 16:52:00 +00002092 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
Ted Kremenek84de4a12011-03-21 18:40:07 +00002093 if (!Clang->hasTarget()) {
Craig Topper49a27902014-05-22 04:46:25 +00002094 Clang->setInvocation(nullptr);
Douglas Gregor2dd19f12010-08-18 22:29:43 +00002095 return;
Douglas Gregor8e984da2010-08-04 16:47:14 +00002096 }
2097
2098 // Inform the target of the language options.
2099 //
2100 // FIXME: We shouldn't need to do this, the target should be immutable once
2101 // created. This complexity should be lifted elsewhere.
Alp Toker74437972014-07-06 05:14:24 +00002102 Clang->getTarget().adjust(Clang->getLangOpts());
Douglas Gregor8e984da2010-08-04 16:47:14 +00002103
Ted Kremenek84de4a12011-03-21 18:40:07 +00002104 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Douglas Gregor8e984da2010-08-04 16:47:14 +00002105 "Invocation must have exactly one source file!");
Richard Smith40c0efa2017-04-26 18:57:40 +00002106 assert(Clang->getFrontendOpts().Inputs[0].getKind().getFormat() ==
2107 InputKind::Source &&
Douglas Gregor8e984da2010-08-04 16:47:14 +00002108 "FIXME: AST inputs not yet supported here!");
Richard Smith40c0efa2017-04-26 18:57:40 +00002109 assert(Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() !=
2110 InputKind::LLVM_IR &&
Douglas Gregor8e984da2010-08-04 16:47:14 +00002111 "IR inputs not support here!");
Douglas Gregor8e984da2010-08-04 16:47:14 +00002112
2113 // Use the source and file managers that we were given.
Ted Kremenek84de4a12011-03-21 18:40:07 +00002114 Clang->setFileManager(&FileMgr);
2115 Clang->setSourceManager(&SourceMgr);
Douglas Gregor8e984da2010-08-04 16:47:14 +00002116
2117 // Remap files.
2118 PreprocessorOpts.clearRemappedFiles();
Douglas Gregord8a5dba2010-08-04 17:07:00 +00002119 PreprocessorOpts.RetainRemappedFileBuffers = true;
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00002120 for (const auto &RemappedFile : RemappedFiles) {
2121 PreprocessorOpts.addRemappedFile(RemappedFile.first, RemappedFile.second);
2122 OwnedBuffers.push_back(RemappedFile.second);
Douglas Gregorb97b6662010-08-20 00:59:43 +00002123 }
Dmitri Gribenkoc444b572014-02-08 00:38:15 +00002124
Douglas Gregorb14904c2010-08-13 22:48:40 +00002125 // Use the code completion consumer we were given, but adding any cached
2126 // code-completion results.
Douglas Gregore9186e62010-11-29 16:13:56 +00002127 AugmentedCodeCompleteConsumer *AugmentedConsumer
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002128 = new AugmentedCodeCompleteConsumer(*this, Consumer, CodeCompleteOpts);
Ted Kremenek84de4a12011-03-21 18:40:07 +00002129 Clang->setCodeCompletionConsumer(AugmentedConsumer);
Douglas Gregor8e984da2010-08-04 16:47:14 +00002130
Douglas Gregor028d3e42010-08-09 20:45:32 +00002131 // If we have a precompiled preamble, try to use it. We only allow
2132 // the use of the precompiled preamble if we're if the completion
2133 // point is within the main file, after the end of the precompiled
2134 // preamble.
Rafael Espindola2346a372014-08-18 18:47:08 +00002135 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
Ilya Biryukov200b3282017-06-21 10:24:58 +00002136 if (Preamble) {
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00002137 std::string CompleteFilePath(File);
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00002138
Ilya Biryukovaf69e402017-05-23 11:37:52 +00002139 auto VFS = FileMgr.getVirtualFileSystem();
2140 auto CompleteFileStatus = VFS->status(CompleteFilePath);
2141 if (CompleteFileStatus) {
2142 llvm::sys::fs::UniqueID CompleteFileID = CompleteFileStatus->getUniqueID();
2143
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00002144 std::string MainPath(OriginalSourceFile);
Ilya Biryukovaf69e402017-05-23 11:37:52 +00002145 auto MainStatus = VFS->status(MainPath);
2146 if (MainStatus) {
2147 llvm::sys::fs::UniqueID MainID = MainStatus->getUniqueID();
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00002148 if (CompleteFileID == MainID && Line > 1)
Rafael Espindola2346a372014-08-18 18:47:08 +00002149 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(
Ilya Biryukovaf69e402017-05-23 11:37:52 +00002150 PCHContainerOps, Inv, VFS, false, Line - 1);
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00002151 }
2152 }
Douglas Gregor028d3e42010-08-09 20:45:32 +00002153 }
2154
2155 // If the main file has been overridden due to the use of a preamble,
2156 // make that override happen and introduce the preamble.
2157 if (OverrideMainBuffer) {
Ilya Biryukov200b3282017-06-21 10:24:58 +00002158 assert(Preamble && "No preamble was built, but OverrideMainBuffer is not null");
2159 Preamble->AddImplicitPreamble(Clang->getInvocation(), OverrideMainBuffer.get());
Rafael Espindola2346a372014-08-18 18:47:08 +00002160 OwnedBuffers.push_back(OverrideMainBuffer.release());
Douglas Gregor7b02b582010-08-20 00:02:33 +00002161 } else {
2162 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
2163 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregor028d3e42010-08-09 20:45:32 +00002164 }
2165
Argyrios Kyrtzidis870704f2012-11-02 22:18:44 +00002166 // Disable the preprocessing record if modules are not enabled.
2167 if (!Clang->getLangOpts().Modules)
2168 PreprocessorOpts.DetailedRecord = false;
Ahmed Charlesb8984322014-03-07 20:03:18 +00002169
2170 std::unique_ptr<SyntaxOnlyAction> Act;
Douglas Gregor8e984da2010-08-04 16:47:14 +00002171 Act.reset(new SyntaxOnlyAction);
Douglas Gregor32fbe312012-01-20 16:28:04 +00002172 if (Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
Douglas Gregor8e984da2010-08-04 16:47:14 +00002173 Act->Execute();
2174 Act->EndSourceFile();
2175 }
Douglas Gregor8e984da2010-08-04 16:47:14 +00002176}
Douglas Gregore9386682010-08-13 05:36:37 +00002177
Argyrios Kyrtzidis39a76382012-09-26 16:39:46 +00002178bool ASTUnit::Save(StringRef File) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00002179 if (HadModuleLoaderFatalFailure)
2180 return true;
2181
Argyrios Kyrtzidis55e75572011-07-21 18:44:49 +00002182 // Write to a temporary file and later rename it to the actual file, to avoid
2183 // possible race conditions.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00002184 SmallString<128> TempPath;
Argyrios Kyrtzidis08a2bfd2011-07-28 00:45:10 +00002185 TempPath = File;
2186 TempPath += "-%%%%%%%%";
2187 int fd;
Yaron Keren92e1b622015-03-18 10:17:07 +00002188 if (llvm::sys::fs::createUniqueFile(TempPath, fd, TempPath))
Argyrios Kyrtzidis39a76382012-09-26 16:39:46 +00002189 return true;
Argyrios Kyrtzidis55e75572011-07-21 18:44:49 +00002190
Douglas Gregore9386682010-08-13 05:36:37 +00002191 // FIXME: Can we somehow regenerate the stat cache here, or do we need to
2192 // unconditionally create a stat cache when we parse the file?
Argyrios Kyrtzidis08a2bfd2011-07-28 00:45:10 +00002193 llvm::raw_fd_ostream Out(fd, /*shouldClose=*/true);
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00002194
2195 serialize(Out);
2196 Out.close();
Argyrios Kyrtzidiseeea16a2012-03-13 02:17:06 +00002197 if (Out.has_error()) {
2198 Out.clear_error();
Argyrios Kyrtzidis39a76382012-09-26 16:39:46 +00002199 return true;
Argyrios Kyrtzidiseeea16a2012-03-13 02:17:06 +00002200 }
Argyrios Kyrtzidis55e75572011-07-21 18:44:49 +00002201
Yaron Keren92e1b622015-03-18 10:17:07 +00002202 if (llvm::sys::fs::rename(TempPath, File)) {
2203 llvm::sys::fs::remove(TempPath);
Argyrios Kyrtzidis39a76382012-09-26 16:39:46 +00002204 return true;
Argyrios Kyrtzidis55e75572011-07-21 18:44:49 +00002205 }
2206
Argyrios Kyrtzidis39a76382012-09-26 16:39:46 +00002207 return false;
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00002208}
2209
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00002210static bool serializeUnit(ASTWriter &Writer,
2211 SmallVectorImpl<char> &Buffer,
2212 Sema &S,
2213 bool hasErrors,
2214 raw_ostream &OS) {
Craig Topper49a27902014-05-22 04:46:25 +00002215 Writer.WriteAST(S, std::string(), nullptr, "", hasErrors);
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00002216
2217 // Write the generated bitstream to "Out".
2218 if (!Buffer.empty())
2219 OS.write(Buffer.data(), Buffer.size());
2220
2221 return false;
2222}
2223
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002224bool ASTUnit::serialize(raw_ostream &OS) {
Argyrios Kyrtzidis70ec1c72016-07-13 20:35:26 +00002225 // For serialization we are lenient if the errors were only warn-as-error kind.
2226 bool hasErrors = getDiagnostics().hasUncompilableErrorOccurred();
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00002227
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00002228 if (WriterData)
2229 return serializeUnit(WriterData->Writer, WriterData->Buffer,
2230 getSema(), hasErrors, OS);
2231
Daniel Dunbar9a963862012-02-29 20:31:23 +00002232 SmallString<128> Buffer;
Douglas Gregore9386682010-08-13 05:36:37 +00002233 llvm::BitstreamWriter Stream(Buffer);
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00002234 MemoryBufferCache PCMCache;
2235 ASTWriter Writer(Stream, Buffer, PCMCache, {});
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00002236 return serializeUnit(Writer, Buffer, getSema(), hasErrors, OS);
Douglas Gregore9386682010-08-13 05:36:37 +00002237}
Douglas Gregor925296b2011-07-19 16:10:42 +00002238
2239typedef ContinuousRangeMap<unsigned, int, 2> SLocRemap;
2240
Douglas Gregor925296b2011-07-19 16:10:42 +00002241void ASTUnit::TranslateStoredDiagnostics(
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002242 FileManager &FileMgr,
Douglas Gregor925296b2011-07-19 16:10:42 +00002243 SourceManager &SrcMgr,
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002244 const SmallVectorImpl<StandaloneDiagnostic> &Diags,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002245 SmallVectorImpl<StoredDiagnostic> &Out) {
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002246 // Map the standalone diagnostic into the new source manager. We also need to
2247 // remap all the locations to the new view. This includes the diag location,
2248 // any associated source ranges, and the source ranges of associated fix-its.
Douglas Gregor925296b2011-07-19 16:10:42 +00002249 // FIXME: There should be a cleaner way to do this.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002250 SmallVector<StoredDiagnostic, 4> Result;
Douglas Gregor925296b2011-07-19 16:10:42 +00002251 Result.reserve(Diags.size());
Erik Verbruggenefe6fa52017-06-09 08:29:58 +00002252
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00002253 for (const StandaloneDiagnostic &SD : Diags) {
Douglas Gregor925296b2011-07-19 16:10:42 +00002254 // Rebuild the StoredDiagnostic.
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002255 if (SD.Filename.empty())
2256 continue;
2257 const FileEntry *FE = FileMgr.getFile(SD.Filename);
2258 if (!FE)
2259 continue;
Erik Verbruggenefe6fa52017-06-09 08:29:58 +00002260 SourceLocation FileLoc;
2261 auto ItFileID = PreambleSrcLocCache.find(SD.Filename);
2262 if (ItFileID == PreambleSrcLocCache.end()) {
2263 FileID FID = SrcMgr.translateFile(FE);
2264 FileLoc = SrcMgr.getLocForStartOfFile(FID);
2265 PreambleSrcLocCache[SD.Filename] = FileLoc;
2266 } else {
2267 FileLoc = ItFileID->getValue();
Erik Verbruggen2c7c38d2017-02-16 09:49:30 +00002268 }
Erik Verbruggenefe6fa52017-06-09 08:29:58 +00002269
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002270 if (FileLoc.isInvalid())
2271 continue;
2272 SourceLocation L = FileLoc.getLocWithOffset(SD.LocOffset);
Douglas Gregor925296b2011-07-19 16:10:42 +00002273 FullSourceLoc Loc(L, SrcMgr);
2274
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002275 SmallVector<CharSourceRange, 4> Ranges;
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002276 Ranges.reserve(SD.Ranges.size());
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00002277 for (const auto &Range : SD.Ranges) {
2278 SourceLocation BL = FileLoc.getLocWithOffset(Range.first);
2279 SourceLocation EL = FileLoc.getLocWithOffset(Range.second);
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002280 Ranges.push_back(CharSourceRange::getCharRange(BL, EL));
Douglas Gregor925296b2011-07-19 16:10:42 +00002281 }
2282
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002283 SmallVector<FixItHint, 2> FixIts;
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002284 FixIts.reserve(SD.FixIts.size());
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00002285 for (const StandaloneFixIt &FixIt : SD.FixIts) {
Douglas Gregor925296b2011-07-19 16:10:42 +00002286 FixIts.push_back(FixItHint());
2287 FixItHint &FH = FixIts.back();
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00002288 FH.CodeToInsert = FixIt.CodeToInsert;
2289 SourceLocation BL = FileLoc.getLocWithOffset(FixIt.RemoveRange.first);
2290 SourceLocation EL = FileLoc.getLocWithOffset(FixIt.RemoveRange.second);
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002291 FH.RemoveRange = CharSourceRange::getCharRange(BL, EL);
Douglas Gregor925296b2011-07-19 16:10:42 +00002292 }
2293
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002294 Result.push_back(StoredDiagnostic(SD.Level, SD.ID,
2295 SD.Message, Loc, Ranges, FixIts));
Douglas Gregor925296b2011-07-19 16:10:42 +00002296 }
2297 Result.swap(Out);
2298}
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002299
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00002300void ASTUnit::addFileLevelDecl(Decl *D) {
2301 assert(D);
Douglas Gregor61d63d02011-11-07 18:53:57 +00002302
2303 // We only care about local declarations.
2304 if (D->isFromASTFile())
2305 return;
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00002306
2307 SourceManager &SM = *SourceMgr;
2308 SourceLocation Loc = D->getLocation();
2309 if (Loc.isInvalid() || !SM.isLocalSourceLocation(Loc))
2310 return;
2311
2312 // We only keep track of the file-level declarations of each file.
2313 if (!D->getLexicalDeclContext()->isFileContext())
2314 return;
2315
2316 SourceLocation FileLoc = SM.getFileLoc(Loc);
2317 assert(SM.isLocalSourceLocation(FileLoc));
2318 FileID FID;
2319 unsigned Offset;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002320 std::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc);
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00002321 if (FID.isInvalid())
2322 return;
2323
2324 LocDeclsTy *&Decls = FileDecls[FID];
2325 if (!Decls)
2326 Decls = new LocDeclsTy();
2327
2328 std::pair<unsigned, Decl *> LocDecl(Offset, D);
2329
2330 if (Decls->empty() || Decls->back().first <= Offset) {
2331 Decls->push_back(LocDecl);
2332 return;
2333 }
2334
Benjamin Kramer45025c02013-08-24 13:22:59 +00002335 LocDeclsTy::iterator I = std::upper_bound(Decls->begin(), Decls->end(),
2336 LocDecl, llvm::less_first());
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00002337
2338 Decls->insert(I, LocDecl);
2339}
2340
Argyrios Kyrtzidise9681522011-11-03 02:20:32 +00002341void ASTUnit::findFileRegionDecls(FileID File, unsigned Offset, unsigned Length,
2342 SmallVectorImpl<Decl *> &Decls) {
2343 if (File.isInvalid())
2344 return;
2345
2346 if (SourceMgr->isLoadedFileID(File)) {
2347 assert(Ctx->getExternalSource() && "No external source!");
2348 return Ctx->getExternalSource()->FindFileRegionDecls(File, Offset, Length,
2349 Decls);
2350 }
2351
2352 FileDeclsTy::iterator I = FileDecls.find(File);
2353 if (I == FileDecls.end())
2354 return;
2355
2356 LocDeclsTy &LocDecls = *I->second;
2357 if (LocDecls.empty())
2358 return;
2359
Benjamin Kramere3e855b2013-08-24 13:12:34 +00002360 LocDeclsTy::iterator BeginIt =
2361 std::lower_bound(LocDecls.begin(), LocDecls.end(),
Craig Topper49a27902014-05-22 04:46:25 +00002362 std::make_pair(Offset, (Decl *)nullptr),
2363 llvm::less_first());
Argyrios Kyrtzidise9681522011-11-03 02:20:32 +00002364 if (BeginIt != LocDecls.begin())
2365 --BeginIt;
2366
Argyrios Kyrtzidis8ad3bab2011-11-23 20:27:36 +00002367 // If we are pointing at a top-level decl inside an objc container, we need
2368 // to backtrack until we find it otherwise we will fail to report that the
2369 // region overlaps with an objc container.
2370 while (BeginIt != LocDecls.begin() &&
2371 BeginIt->second->isTopLevelDeclInObjCContainer())
2372 --BeginIt;
2373
Benjamin Kramere3e855b2013-08-24 13:12:34 +00002374 LocDeclsTy::iterator EndIt = std::upper_bound(
2375 LocDecls.begin(), LocDecls.end(),
Craig Topper49a27902014-05-22 04:46:25 +00002376 std::make_pair(Offset + Length, (Decl *)nullptr), llvm::less_first());
Argyrios Kyrtzidise9681522011-11-03 02:20:32 +00002377 if (EndIt != LocDecls.end())
2378 ++EndIt;
2379
2380 for (LocDeclsTy::iterator DIt = BeginIt; DIt != EndIt; ++DIt)
2381 Decls.push_back(DIt->second);
2382}
2383
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002384SourceLocation ASTUnit::getLocation(const FileEntry *File,
2385 unsigned Line, unsigned Col) const {
2386 const SourceManager &SM = getSourceManager();
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00002387 SourceLocation Loc = SM.translateFileLineCol(File, Line, Col);
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002388 return SM.getMacroArgExpandedLocation(Loc);
2389}
2390
2391SourceLocation ASTUnit::getLocation(const FileEntry *File,
2392 unsigned Offset) const {
2393 const SourceManager &SM = getSourceManager();
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00002394 SourceLocation FileLoc = SM.translateFileLineCol(File, 1, 1);
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002395 return SM.getMacroArgExpandedLocation(FileLoc.getLocWithOffset(Offset));
2396}
2397
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00002398/// \brief If \arg Loc is a loaded location from the preamble, returns
2399/// the corresponding local location of the main file, otherwise it returns
2400/// \arg Loc.
Vedant Kumar525a7f62017-07-25 19:53:27 +00002401SourceLocation ASTUnit::mapLocationFromPreamble(SourceLocation Loc) const {
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00002402 FileID PreambleID;
2403 if (SourceMgr)
2404 PreambleID = SourceMgr->getPreambleFileID();
2405
Ilya Biryukov200b3282017-06-21 10:24:58 +00002406 if (Loc.isInvalid() || !Preamble || PreambleID.isInvalid())
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00002407 return Loc;
2408
2409 unsigned Offs;
Ilya Biryukov200b3282017-06-21 10:24:58 +00002410 if (SourceMgr->isInFileID(Loc, PreambleID, &Offs) && Offs < Preamble->getBounds().Size) {
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00002411 SourceLocation FileLoc
2412 = SourceMgr->getLocForStartOfFile(SourceMgr->getMainFileID());
2413 return FileLoc.getLocWithOffset(Offs);
2414 }
2415
2416 return Loc;
2417}
2418
2419/// \brief If \arg Loc is a local location of the main file but inside the
2420/// preamble chunk, returns the corresponding loaded location from the
2421/// preamble, otherwise it returns \arg Loc.
Vedant Kumar525a7f62017-07-25 19:53:27 +00002422SourceLocation ASTUnit::mapLocationToPreamble(SourceLocation Loc) const {
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00002423 FileID PreambleID;
2424 if (SourceMgr)
2425 PreambleID = SourceMgr->getPreambleFileID();
2426
Ilya Biryukov200b3282017-06-21 10:24:58 +00002427 if (Loc.isInvalid() || !Preamble || PreambleID.isInvalid())
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00002428 return Loc;
2429
2430 unsigned Offs;
2431 if (SourceMgr->isInFileID(Loc, SourceMgr->getMainFileID(), &Offs) &&
Ilya Biryukov200b3282017-06-21 10:24:58 +00002432 Offs < Preamble->getBounds().Size) {
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00002433 SourceLocation FileLoc = SourceMgr->getLocForStartOfFile(PreambleID);
2434 return FileLoc.getLocWithOffset(Offs);
2435 }
2436
2437 return Loc;
2438}
2439
Vedant Kumar525a7f62017-07-25 19:53:27 +00002440bool ASTUnit::isInPreambleFileID(SourceLocation Loc) const {
Argyrios Kyrtzidis429ec022011-10-25 00:29:50 +00002441 FileID FID;
2442 if (SourceMgr)
2443 FID = SourceMgr->getPreambleFileID();
2444
2445 if (Loc.isInvalid() || FID.isInvalid())
2446 return false;
2447
2448 return SourceMgr->isInFileID(Loc, FID);
2449}
2450
Vedant Kumar525a7f62017-07-25 19:53:27 +00002451bool ASTUnit::isInMainFileID(SourceLocation Loc) const {
Argyrios Kyrtzidis429ec022011-10-25 00:29:50 +00002452 FileID FID;
2453 if (SourceMgr)
2454 FID = SourceMgr->getMainFileID();
2455
2456 if (Loc.isInvalid() || FID.isInvalid())
2457 return false;
2458
2459 return SourceMgr->isInFileID(Loc, FID);
2460}
2461
Vedant Kumar525a7f62017-07-25 19:53:27 +00002462SourceLocation ASTUnit::getEndOfPreambleFileID() const {
Argyrios Kyrtzidis429ec022011-10-25 00:29:50 +00002463 FileID FID;
2464 if (SourceMgr)
2465 FID = SourceMgr->getPreambleFileID();
2466
2467 if (FID.isInvalid())
2468 return SourceLocation();
2469
2470 return SourceMgr->getLocForEndOfFile(FID);
2471}
2472
Vedant Kumar525a7f62017-07-25 19:53:27 +00002473SourceLocation ASTUnit::getStartOfMainFileID() const {
Argyrios Kyrtzidis429ec022011-10-25 00:29:50 +00002474 FileID FID;
2475 if (SourceMgr)
2476 FID = SourceMgr->getMainFileID();
2477
2478 if (FID.isInvalid())
2479 return SourceLocation();
2480
2481 return SourceMgr->getLocForStartOfFile(FID);
2482}
2483
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00002484llvm::iterator_range<PreprocessingRecord::iterator>
Argyrios Kyrtzidisd4fcf5802012-10-02 16:10:51 +00002485ASTUnit::getLocalPreprocessingEntities() const {
2486 if (isMainFileAST()) {
2487 serialization::ModuleFile &
2488 Mod = Reader->getModuleManager().getPrimaryModule();
2489 return Reader->getModulePreprocessedEntities(Mod);
2490 }
2491
2492 if (PreprocessingRecord *PPRec = PP->getPreprocessingRecord())
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00002493 return llvm::make_range(PPRec->local_begin(), PPRec->local_end());
Argyrios Kyrtzidisd4fcf5802012-10-02 16:10:51 +00002494
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00002495 return llvm::make_range(PreprocessingRecord::iterator(),
2496 PreprocessingRecord::iterator());
Argyrios Kyrtzidisd4fcf5802012-10-02 16:10:51 +00002497}
2498
Argyrios Kyrtzidise514b202012-10-03 01:58:28 +00002499bool ASTUnit::visitLocalTopLevelDecls(void *context, DeclVisitorFn Fn) {
Argyrios Kyrtzidis10e78462012-10-02 21:09:13 +00002500 if (isMainFileAST()) {
2501 serialization::ModuleFile &
2502 Mod = Reader->getModuleManager().getPrimaryModule();
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00002503 for (const Decl *D : Reader->getModuleFileLevelDecls(Mod)) {
2504 if (!Fn(context, D))
Argyrios Kyrtzidis10e78462012-10-02 21:09:13 +00002505 return false;
2506 }
2507
2508 return true;
2509 }
2510
2511 for (ASTUnit::top_level_iterator TL = top_level_begin(),
2512 TLEnd = top_level_end();
2513 TL != TLEnd; ++TL) {
2514 if (!Fn(context, *TL))
2515 return false;
2516 }
2517
2518 return true;
2519}
2520
Argyrios Kyrtzidisf484b132012-10-03 21:05:51 +00002521const FileEntry *ASTUnit::getPCHFile() {
2522 if (!Reader)
Craig Topper49a27902014-05-22 04:46:25 +00002523 return nullptr;
Argyrios Kyrtzidisf484b132012-10-03 21:05:51 +00002524
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00002525 serialization::ModuleFile *Mod = nullptr;
2526 Reader->getModuleManager().visit([&Mod](serialization::ModuleFile &M) {
2527 switch (M.Kind) {
2528 case serialization::MK_ImplicitModule:
2529 case serialization::MK_ExplicitModule:
Manman Ren11f2a472016-08-18 17:42:15 +00002530 case serialization::MK_PrebuiltModule:
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00002531 return true; // skip dependencies.
2532 case serialization::MK_PCH:
2533 Mod = &M;
2534 return true; // found it.
2535 case serialization::MK_Preamble:
2536 return false; // look in dependencies.
2537 case serialization::MK_MainFile:
2538 return false; // look in dependencies.
2539 }
2540
2541 return true;
2542 });
2543 if (Mod)
2544 return Mod->File;
Argyrios Kyrtzidisf484b132012-10-03 21:05:51 +00002545
Craig Topper49a27902014-05-22 04:46:25 +00002546 return nullptr;
Argyrios Kyrtzidisf484b132012-10-03 21:05:51 +00002547}
2548
Vedant Kumar525a7f62017-07-25 19:53:27 +00002549bool ASTUnit::isModuleFile() const {
Richard Smithab755972017-06-05 18:10:11 +00002550 return isMainFileAST() && getLangOpts().isCompilingModule();
2551}
2552
2553InputKind ASTUnit::getInputKind() const {
2554 auto &LangOpts = getLangOpts();
2555
2556 InputKind::Language Lang;
2557 if (LangOpts.OpenCL)
2558 Lang = InputKind::OpenCL;
2559 else if (LangOpts.CUDA)
2560 Lang = InputKind::CUDA;
2561 else if (LangOpts.RenderScript)
2562 Lang = InputKind::RenderScript;
2563 else if (LangOpts.CPlusPlus)
2564 Lang = LangOpts.ObjC1 ? InputKind::ObjCXX : InputKind::CXX;
2565 else
2566 Lang = LangOpts.ObjC1 ? InputKind::ObjC : InputKind::C;
2567
2568 InputKind::Format Fmt = InputKind::Source;
2569 if (LangOpts.getCompilingModule() == LangOptions::CMK_ModuleMap)
2570 Fmt = InputKind::ModuleMap;
2571
2572 // We don't know if input was preprocessed. Assume not.
2573 bool PP = false;
2574
2575 return InputKind(Lang, Fmt, PP);
Argyrios Kyrtzidise445c722012-10-10 02:12:47 +00002576}
2577
Argyrios Kyrtzidisebf01362011-10-10 21:57:12 +00002578#ifndef NDEBUG
2579ASTUnit::ConcurrencyState::ConcurrencyState() {
2580 Mutex = new llvm::sys::MutexImpl(/*recursive=*/true);
2581}
2582
2583ASTUnit::ConcurrencyState::~ConcurrencyState() {
2584 delete static_cast<llvm::sys::MutexImpl *>(Mutex);
2585}
2586
2587void ASTUnit::ConcurrencyState::start() {
2588 bool acquired = static_cast<llvm::sys::MutexImpl *>(Mutex)->tryacquire();
2589 assert(acquired && "Concurrent access to ASTUnit!");
2590}
2591
2592void ASTUnit::ConcurrencyState::finish() {
2593 static_cast<llvm::sys::MutexImpl *>(Mutex)->release();
2594}
2595
2596#else // NDEBUG
2597
Hans Wennborgdcfba332015-10-06 23:40:43 +00002598ASTUnit::ConcurrencyState::ConcurrencyState() { Mutex = nullptr; }
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +00002599ASTUnit::ConcurrencyState::~ConcurrencyState() {}
Argyrios Kyrtzidisebf01362011-10-10 21:57:12 +00002600void ASTUnit::ConcurrencyState::start() {}
2601void ASTUnit::ConcurrencyState::finish() {}
2602
Hans Wennborgdcfba332015-10-06 23:40:43 +00002603#endif // NDEBUG