blob: 783d1f9d09197b0678efce2985c75776252de0ff [file] [log] [blame]
Eugene Zelenko4f233182018-03-22 00:53:26 +00001//===- ASTUnit.cpp - ASTUnit utility --------------------------------------===//
Argyrios Kyrtzidis3a08ec12009-06-20 08:27:14 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Argyrios Kyrtzidis3a08ec12009-06-20 08:27:14 +00006//
7//===----------------------------------------------------------------------===//
8//
9// ASTUnit Implementation.
10//
11//===----------------------------------------------------------------------===//
12
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000013#include "clang/Frontend/ASTUnit.h"
Daniel Dunbar764c0822009-12-01 09:51:01 +000014#include "clang/AST/ASTConsumer.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000015#include "clang/AST/ASTContext.h"
Eugene Zelenko4f233182018-03-22 00:53:26 +000016#include "clang/AST/CommentCommandTraits.h"
17#include "clang/AST/Decl.h"
18#include "clang/AST/DeclBase.h"
19#include "clang/AST/DeclCXX.h"
20#include "clang/AST/DeclGroup.h"
21#include "clang/AST/DeclObjC.h"
22#include "clang/AST/DeclTemplate.h"
23#include "clang/AST/DeclarationName.h"
24#include "clang/AST/ExternalASTSource.h"
25#include "clang/AST/PrettyPrinter.h"
26#include "clang/AST/Type.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000027#include "clang/AST/TypeOrdering.h"
28#include "clang/Basic/Diagnostic.h"
Eugene Zelenko4f233182018-03-22 00:53:26 +000029#include "clang/Basic/FileManager.h"
30#include "clang/Basic/IdentifierTable.h"
31#include "clang/Basic/LLVM.h"
32#include "clang/Basic/LangOptions.h"
Eugene Zelenko4f233182018-03-22 00:53:26 +000033#include "clang/Basic/Module.h"
34#include "clang/Basic/SourceLocation.h"
35#include "clang/Basic/SourceManager.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000036#include "clang/Basic/TargetInfo.h"
37#include "clang/Basic/TargetOptions.h"
Daniel Dunbar764c0822009-12-01 09:51:01 +000038#include "clang/Frontend/CompilerInstance.h"
Eugene Zelenko4f233182018-03-22 00:53:26 +000039#include "clang/Frontend/CompilerInvocation.h"
40#include "clang/Frontend/FrontendAction.h"
Daniel Dunbar764c0822009-12-01 09:51:01 +000041#include "clang/Frontend/FrontendActions.h"
Daniel Dunbar55a17b62009-12-02 03:23:45 +000042#include "clang/Frontend/FrontendDiagnostic.h"
Daniel Dunbar764c0822009-12-01 09:51:01 +000043#include "clang/Frontend/FrontendOptions.h"
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +000044#include "clang/Frontend/MultiplexConsumer.h"
Eugene Zelenko4f233182018-03-22 00:53:26 +000045#include "clang/Frontend/PrecompiledPreamble.h"
Douglas Gregor36e3b5c2010-10-11 21:37:58 +000046#include "clang/Frontend/Utils.h"
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000047#include "clang/Lex/HeaderSearch.h"
Eugene Zelenko4f233182018-03-22 00:53:26 +000048#include "clang/Lex/HeaderSearchOptions.h"
49#include "clang/Lex/Lexer.h"
50#include "clang/Lex/PPCallbacks.h"
51#include "clang/Lex/PreprocessingRecord.h"
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000052#include "clang/Lex/Preprocessor.h"
Douglas Gregor1452ff12012-10-24 17:46:57 +000053#include "clang/Lex/PreprocessorOptions.h"
Eugene Zelenko4f233182018-03-22 00:53:26 +000054#include "clang/Lex/Token.h"
55#include "clang/Sema/CodeCompleteConsumer.h"
56#include "clang/Sema/CodeCompleteOptions.h"
David Blaikie0a4e61f2013-09-13 18:32:52 +000057#include "clang/Sema/Sema.h"
Eugene Zelenko4f233182018-03-22 00:53:26 +000058#include "clang/Serialization/ASTBitCodes.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000059#include "clang/Serialization/ASTReader.h"
60#include "clang/Serialization/ASTWriter.h"
Eugene Zelenko4f233182018-03-22 00:53:26 +000061#include "clang/Serialization/ContinuousRangeMap.h"
Duncan P. N. Exon Smith8bef5cd2019-03-09 17:33:56 +000062#include "clang/Serialization/InMemoryModuleCache.h"
Eugene Zelenko4f233182018-03-22 00:53:26 +000063#include "clang/Serialization/Module.h"
Richard Trieuf3b00462018-12-12 02:53:59 +000064#include "clang/Serialization/PCHContainerOperations.h"
Chris Lattnerce6c42f2011-03-23 04:04:01 +000065#include "llvm/ADT/ArrayRef.h"
Eugene Zelenko4f233182018-03-22 00:53:26 +000066#include "llvm/ADT/DenseMap.h"
67#include "llvm/ADT/IntrusiveRefCntPtr.h"
68#include "llvm/ADT/None.h"
69#include "llvm/ADT/Optional.h"
70#include "llvm/ADT/STLExtras.h"
71#include "llvm/ADT/SmallString.h"
72#include "llvm/ADT/SmallVector.h"
73#include "llvm/ADT/StringMap.h"
74#include "llvm/ADT/StringRef.h"
Douglas Gregor40a5a7d2010-08-16 23:08:34 +000075#include "llvm/ADT/StringSet.h"
Eugene Zelenko4f233182018-03-22 00:53:26 +000076#include "llvm/ADT/Twine.h"
77#include "llvm/ADT/iterator_range.h"
Francis Visoiu Mistrihe0308272019-07-03 22:40:07 +000078#include "llvm/Bitstream/BitstreamWriter.h"
Eugene Zelenko4f233182018-03-22 00:53:26 +000079#include "llvm/Support/Allocator.h"
80#include "llvm/Support/Casting.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000081#include "llvm/Support/CrashRecoveryContext.h"
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +000082#include "llvm/Support/DJB.h"
Eugene Zelenko4f233182018-03-22 00:53:26 +000083#include "llvm/Support/ErrorHandling.h"
84#include "llvm/Support/ErrorOr.h"
85#include "llvm/Support/FileSystem.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000086#include "llvm/Support/MemoryBuffer.h"
Argyrios Kyrtzidisebf01362011-10-10 21:57:12 +000087#include "llvm/Support/Mutex.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000088#include "llvm/Support/Timer.h"
Jonas Devliegherefc514902018-10-10 13:27:25 +000089#include "llvm/Support/VirtualFileSystem.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000090#include "llvm/Support/raw_ostream.h"
Eugene Zelenko4f233182018-03-22 00:53:26 +000091#include <algorithm>
Benjamin Kramer4527fb22014-03-02 17:08:31 +000092#include <atomic>
Eugene Zelenko4f233182018-03-22 00:53:26 +000093#include <cassert>
94#include <cstdint>
Zhongxing Xu318e4032010-07-23 02:15:08 +000095#include <cstdio>
Chandler Carruth3a022472012-12-04 09:13:33 +000096#include <cstdlib>
Eugene Zelenko4f233182018-03-22 00:53:26 +000097#include <memory>
98#include <string>
99#include <tuple>
100#include <utility>
101#include <vector>
Hans Wennborgdcfba332015-10-06 23:40:43 +0000102
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000103using namespace clang;
104
Douglas Gregor16896c42010-10-28 15:44:59 +0000105using llvm::TimeRecord;
106
107namespace {
Eugene Zelenko4f233182018-03-22 00:53:26 +0000108
Douglas Gregor16896c42010-10-28 15:44:59 +0000109 class SimpleTimer {
110 bool WantTiming;
111 TimeRecord Start;
112 std::string Output;
113
Benjamin Kramerf2e5a912010-11-09 20:00:56 +0000114 public:
Douglas Gregor1cbdd952010-11-01 13:48:43 +0000115 explicit SimpleTimer(bool WantTiming) : WantTiming(WantTiming) {
Douglas Gregor16896c42010-10-28 15:44:59 +0000116 if (WantTiming)
Benjamin Kramerf2e5a912010-11-09 20:00:56 +0000117 Start = TimeRecord::getCurrentTime();
Douglas Gregor16896c42010-10-28 15:44:59 +0000118 }
119
Douglas Gregor16896c42010-10-28 15:44:59 +0000120 ~SimpleTimer() {
121 if (WantTiming) {
122 TimeRecord Elapsed = TimeRecord::getCurrentTime();
123 Elapsed -= Start;
124 llvm::errs() << Output << ':';
125 Elapsed.print(Elapsed, llvm::errs());
126 llvm::errs() << '\n';
127 }
128 }
Eugene Zelenko4f233182018-03-22 00:53:26 +0000129
130 void setOutput(const Twine &Output) {
131 if (WantTiming)
132 this->Output = Output.str();
133 }
Douglas Gregor16896c42010-10-28 15:44:59 +0000134 };
Ilya Biryukovaf69e402017-05-23 11:37:52 +0000135
Eugene Zelenko4f233182018-03-22 00:53:26 +0000136} // namespace
Ilya Biryukovaf69e402017-05-23 11:37:52 +0000137
Eugene Zelenko4f233182018-03-22 00:53:26 +0000138template <class T>
139static std::unique_ptr<T> valueOrNull(llvm::ErrorOr<std::unique_ptr<T>> Val) {
140 if (!Val)
141 return nullptr;
142 return std::move(*Val);
143}
144
145template <class T>
146static bool moveOnNoError(llvm::ErrorOr<T> Val, T &Output) {
147 if (!Val)
148 return false;
149 Output = std::move(*Val);
150 return true;
151}
Ted Kremenek06b4f912011-10-27 17:55:18 +0000152
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000153/// Get a source buffer for \p MainFilePath, handling all file-to-file
Ilya Biryukov200b3282017-06-21 10:24:58 +0000154/// and file-to-buffer remappings inside \p Invocation.
155static std::unique_ptr<llvm::MemoryBuffer>
156getBufferForFileHandlingRemapping(const CompilerInvocation &Invocation,
Jonas Devliegherefc514902018-10-10 13:27:25 +0000157 llvm::vfs::FileSystem *VFS,
158 StringRef FilePath, bool isVolatile) {
Ilya Biryukov200b3282017-06-21 10:24:58 +0000159 const auto &PreprocessorOpts = Invocation.getPreprocessorOpts();
Ted Kremenekbd307a52011-10-27 19:44:25 +0000160
Ilya Biryukov200b3282017-06-21 10:24:58 +0000161 // Try to determine if the main file has been remapped, either from the
162 // command line (to another file) or directly through the compiler
163 // invocation (to a memory buffer).
164 llvm::MemoryBuffer *Buffer = nullptr;
165 std::unique_ptr<llvm::MemoryBuffer> BufferOwner;
166 auto FileStatus = VFS->status(FilePath);
167 if (FileStatus) {
168 llvm::sys::fs::UniqueID MainFileID = FileStatus->getUniqueID();
Ted Kremenek06b4f912011-10-27 17:55:18 +0000169
Ilya Biryukov200b3282017-06-21 10:24:58 +0000170 // Check whether there is a file-file remapping of the main file
171 for (const auto &RF : PreprocessorOpts.RemappedFiles) {
172 std::string MPath(RF.first);
173 auto MPathStatus = VFS->status(MPath);
174 if (MPathStatus) {
175 llvm::sys::fs::UniqueID MID = MPathStatus->getUniqueID();
176 if (MainFileID == MID) {
177 // We found a remapping. Try to load the resulting, remapped source.
Ivan Donchevskii2ebe3a02018-06-06 07:17:26 +0000178 BufferOwner = valueOrNull(VFS->getBufferForFile(RF.second, -1, true, isVolatile));
Ilya Biryukov200b3282017-06-21 10:24:58 +0000179 if (!BufferOwner)
180 return nullptr;
181 }
182 }
183 }
184
185 // Check whether there is a file-buffer remapping. It supercedes the
186 // file-file remapping.
187 for (const auto &RB : PreprocessorOpts.RemappedFileBuffers) {
188 std::string MPath(RB.first);
189 auto MPathStatus = VFS->status(MPath);
190 if (MPathStatus) {
191 llvm::sys::fs::UniqueID MID = MPathStatus->getUniqueID();
192 if (MainFileID == MID) {
193 // We found a remapping.
194 BufferOwner.reset();
195 Buffer = const_cast<llvm::MemoryBuffer *>(RB.second);
196 }
197 }
198 }
Ted Kremenek06b4f912011-10-27 17:55:18 +0000199 }
Ted Kremenek06b4f912011-10-27 17:55:18 +0000200
Ilya Biryukov200b3282017-06-21 10:24:58 +0000201 // If the main source file was not remapped, load it now.
202 if (!Buffer && !BufferOwner) {
Ivan Donchevskii2ebe3a02018-06-06 07:17:26 +0000203 BufferOwner = valueOrNull(VFS->getBufferForFile(FilePath, -1, true, isVolatile));
Ilya Biryukov200b3282017-06-21 10:24:58 +0000204 if (!BufferOwner)
205 return nullptr;
Ted Kremenek06b4f912011-10-27 17:55:18 +0000206 }
Ted Kremenek06b4f912011-10-27 17:55:18 +0000207
Ilya Biryukov200b3282017-06-21 10:24:58 +0000208 if (BufferOwner)
209 return BufferOwner;
210 if (!Buffer)
211 return nullptr;
212 return llvm::MemoryBuffer::getMemBufferCopy(Buffer->getBuffer(), FilePath);
Ted Kremenek06b4f912011-10-27 17:55:18 +0000213}
Ted Kremenek06b4f912011-10-27 17:55:18 +0000214
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000215struct ASTUnit::ASTWriterData {
216 SmallString<128> Buffer;
217 llvm::BitstreamWriter Stream;
218 ASTWriter Writer;
219
Duncan P. N. Exon Smith8bef5cd2019-03-09 17:33:56 +0000220 ASTWriterData(InMemoryModuleCache &ModuleCache)
221 : Stream(Buffer), Writer(Stream, Buffer, ModuleCache, {}) {}
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000222};
223
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000224void ASTUnit::clearFileLevelDecls() {
Reid Kleckner588c9372014-02-19 23:44:52 +0000225 llvm::DeleteContainerSeconds(FileDecls);
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000226}
227
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000228/// After failing to build a precompiled preamble (due to
Douglas Gregorbb420ab2010-08-04 05:53:38 +0000229/// errors in the source that occurs in the preamble), the number of
230/// reparses during which we'll skip even trying to precompile the
231/// preamble.
232const unsigned DefaultPreambleRebuildInterval = 5;
233
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000234/// Tracks the number of ASTUnit objects that are currently active.
Douglas Gregor68dbaea2010-11-17 00:13:31 +0000235///
236/// Used for debugging purposes only.
Benjamin Kramer4527fb22014-03-02 17:08:31 +0000237static std::atomic<unsigned> ActiveASTUnitObjects;
Douglas Gregor68dbaea2010-11-17 00:13:31 +0000238
Douglas Gregord03e8232010-04-05 21:10:19 +0000239ASTUnit::ASTUnit(bool _MainFileIsAST)
Eugene Zelenko4f233182018-03-22 00:53:26 +0000240 : MainFileIsAST(_MainFileIsAST), WantTiming(getenv("LIBCLANG_TIMING")),
241 ShouldCacheCodeCompletionResults(false),
242 IncludeBriefCommentsInCodeCompletion(false), UserFilesAreVolatile(false),
243 UnsafeToFree(false) {
Benjamin Kramer4527fb22014-03-02 17:08:31 +0000244 if (getenv("LIBCLANG_OBJTRACKING"))
245 fprintf(stderr, "+++ %u translation units\n", ++ActiveASTUnitObjects);
Douglas Gregor15ba0b32010-07-30 20:58:08 +0000246}
Douglas Gregord03e8232010-04-05 21:10:19 +0000247
Daniel Dunbar764c0822009-12-01 09:51:01 +0000248ASTUnit::~ASTUnit() {
Douglas Gregor6b930962013-05-03 22:58:43 +0000249 // If we loaded from an AST file, balance out the BeginSourceFile call.
250 if (MainFileIsAST && getDiagnostics().getClient()) {
251 getDiagnostics().getClient()->EndSourceFile();
252 }
253
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000254 clearFileLevelDecls();
255
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000256 // Free the buffers associated with remapped files. We are required to
257 // perform this operation here because we explicitly request that the
258 // compiler instance *not* free these buffers for each invocation of the
259 // parser.
David Blaikieea4395e2017-01-06 19:49:01 +0000260 if (Invocation && OwnsRemappedFileBuffers) {
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000261 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
Alp Toker1b070d22014-07-07 07:47:20 +0000262 for (const auto &RB : PPOpts.RemappedFileBuffers)
263 delete RB.second;
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000264 }
Douglas Gregora0734c52010-08-19 01:33:06 +0000265
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000266 ClearCachedCompletionResults();
267
Benjamin Kramer4527fb22014-03-02 17:08:31 +0000268 if (getenv("LIBCLANG_OBJTRACKING"))
269 fprintf(stderr, "--- %u translation units\n", --ActiveASTUnitObjects);
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000270}
271
David Blaikie41565462017-01-05 19:48:07 +0000272void ASTUnit::setPreprocessor(std::shared_ptr<Preprocessor> PP) {
273 this->PP = std::move(PP);
274}
Argyrios Kyrtzidisda6e0542012-01-17 18:48:07 +0000275
Adam Baloghe4192a82018-06-15 06:45:39 +0000276void ASTUnit::enableSourceFileDiagnostics() {
277 assert(getDiagnostics().getClient() && Ctx &&
278 "Bad context for source file");
279 getDiagnostics().getClient()->BeginSourceFile(Ctx->getLangOpts(), PP.get());
280}
281
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000282/// Determine the set of code-completion contexts in which this
Douglas Gregor39982192010-08-15 06:18:01 +0000283/// declaration should be shown.
Kadir Cetinkayab006e092018-10-24 15:23:49 +0000284static uint64_t getDeclShowContexts(const NamedDecl *ND,
Douglas Gregor59cab552010-08-16 23:05:20 +0000285 const LangOptions &LangOpts,
286 bool &IsNestedNameSpecifier) {
287 IsNestedNameSpecifier = false;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000288
Douglas Gregor39982192010-08-15 06:18:01 +0000289 if (isa<UsingShadowDecl>(ND))
George Burgess IV00f70bd2018-03-01 05:43:23 +0000290 ND = ND->getUnderlyingDecl();
Douglas Gregor39982192010-08-15 06:18:01 +0000291 if (!ND)
292 return 0;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000293
Richard Smith697cc9e2012-08-14 03:13:00 +0000294 uint64_t Contexts = 0;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000295 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND) ||
Erik Verbruggen51ee12a2017-09-08 09:31:13 +0000296 isa<ClassTemplateDecl>(ND) || isa<TemplateTemplateParmDecl>(ND) ||
297 isa<TypeAliasTemplateDecl>(ND)) {
Douglas Gregor39982192010-08-15 06:18:01 +0000298 // Types can appear in these contexts.
299 if (LangOpts.CPlusPlus || !isa<TagDecl>(ND))
Richard Smith697cc9e2012-08-14 03:13:00 +0000300 Contexts |= (1LL << CodeCompletionContext::CCC_TopLevel)
301 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
302 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
303 | (1LL << CodeCompletionContext::CCC_Statement)
304 | (1LL << CodeCompletionContext::CCC_Type)
305 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression);
Douglas Gregor39982192010-08-15 06:18:01 +0000306
307 // In C++, types can appear in expressions contexts (for functional casts).
308 if (LangOpts.CPlusPlus)
Richard Smith697cc9e2012-08-14 03:13:00 +0000309 Contexts |= (1LL << CodeCompletionContext::CCC_Expression);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000310
Douglas Gregor39982192010-08-15 06:18:01 +0000311 // In Objective-C, message sends can send interfaces. In Objective-C++,
312 // all types are available due to functional casts.
313 if (LangOpts.CPlusPlus || isa<ObjCInterfaceDecl>(ND))
Richard Smith697cc9e2012-08-14 03:13:00 +0000314 Contexts |= (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000315
Douglas Gregor21325842011-07-07 16:03:39 +0000316 // In Objective-C, you can only be a subclass of another Objective-C class
Alex Lorenzf3df1f72017-11-14 01:46:24 +0000317 if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(ND)) {
318 // Objective-C interfaces can be used in a class property expression.
319 if (ID->getDefinition())
320 Contexts |= (1LL << CodeCompletionContext::CCC_Expression);
Richard Smith697cc9e2012-08-14 03:13:00 +0000321 Contexts |= (1LL << CodeCompletionContext::CCC_ObjCInterfaceName);
Alex Lorenzf3df1f72017-11-14 01:46:24 +0000322 }
Douglas Gregor39982192010-08-15 06:18:01 +0000323
324 // Deal with tag names.
325 if (isa<EnumDecl>(ND)) {
Richard Smith697cc9e2012-08-14 03:13:00 +0000326 Contexts |= (1LL << CodeCompletionContext::CCC_EnumTag);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000327
Douglas Gregor59cab552010-08-16 23:05:20 +0000328 // Part of the nested-name-specifier in C++0x.
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000329 if (LangOpts.CPlusPlus11)
Douglas Gregor59cab552010-08-16 23:05:20 +0000330 IsNestedNameSpecifier = true;
Eugene Zelenko4f233182018-03-22 00:53:26 +0000331 } else if (const auto *Record = dyn_cast<RecordDecl>(ND)) {
Douglas Gregor39982192010-08-15 06:18:01 +0000332 if (Record->isUnion())
Richard Smith697cc9e2012-08-14 03:13:00 +0000333 Contexts |= (1LL << CodeCompletionContext::CCC_UnionTag);
Douglas Gregor39982192010-08-15 06:18:01 +0000334 else
Richard Smith697cc9e2012-08-14 03:13:00 +0000335 Contexts |= (1LL << CodeCompletionContext::CCC_ClassOrStructTag);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000336
Douglas Gregor39982192010-08-15 06:18:01 +0000337 if (LangOpts.CPlusPlus)
Douglas Gregor59cab552010-08-16 23:05:20 +0000338 IsNestedNameSpecifier = true;
Douglas Gregor0ac41382010-09-23 23:01:17 +0000339 } else if (isa<ClassTemplateDecl>(ND))
Douglas Gregor59cab552010-08-16 23:05:20 +0000340 IsNestedNameSpecifier = true;
Douglas Gregor39982192010-08-15 06:18:01 +0000341 } else if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
342 // Values can appear in these contexts.
Richard Smith697cc9e2012-08-14 03:13:00 +0000343 Contexts = (1LL << CodeCompletionContext::CCC_Statement)
344 | (1LL << CodeCompletionContext::CCC_Expression)
345 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
346 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver);
Douglas Gregor39982192010-08-15 06:18:01 +0000347 } else if (isa<ObjCProtocolDecl>(ND)) {
Richard Smith697cc9e2012-08-14 03:13:00 +0000348 Contexts = (1LL << CodeCompletionContext::CCC_ObjCProtocolName);
Douglas Gregor21325842011-07-07 16:03:39 +0000349 } else if (isa<ObjCCategoryDecl>(ND)) {
Richard Smith697cc9e2012-08-14 03:13:00 +0000350 Contexts = (1LL << CodeCompletionContext::CCC_ObjCCategoryName);
Douglas Gregor39982192010-08-15 06:18:01 +0000351 } else if (isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) {
Richard Smith697cc9e2012-08-14 03:13:00 +0000352 Contexts = (1LL << CodeCompletionContext::CCC_Namespace);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000353
Douglas Gregor39982192010-08-15 06:18:01 +0000354 // Part of the nested-name-specifier.
Douglas Gregor59cab552010-08-16 23:05:20 +0000355 IsNestedNameSpecifier = true;
Douglas Gregor39982192010-08-15 06:18:01 +0000356 }
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000357
Douglas Gregor39982192010-08-15 06:18:01 +0000358 return Contexts;
359}
360
Douglas Gregorb14904c2010-08-13 22:48:40 +0000361void ASTUnit::CacheCodeCompletionResults() {
362 if (!TheSema)
363 return;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000364
Douglas Gregor16896c42010-10-28 15:44:59 +0000365 SimpleTimer Timer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +0000366 Timer.setOutput("Cache global code completions for " + getMainFileName());
Douglas Gregorb14904c2010-08-13 22:48:40 +0000367
368 // Clear out the previous results.
369 ClearCachedCompletionResults();
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000370
Douglas Gregorb14904c2010-08-13 22:48:40 +0000371 // Gather the set of global code completions.
Eugene Zelenko4f233182018-03-22 00:53:26 +0000372 using Result = CodeCompletionResult;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000373 SmallVector<Result, 8> Results;
David Blaikieea4395e2017-01-06 19:49:01 +0000374 CachedCompletionAllocator = std::make_shared<GlobalCodeCompletionAllocator>();
Argyrios Kyrtzidis2bafa002012-11-16 03:34:57 +0000375 CodeCompletionTUInfo CCTUInfo(CachedCompletionAllocator);
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +0000376 TheSema->GatherGlobalCodeCompletions(*CachedCompletionAllocator,
Argyrios Kyrtzidis2bafa002012-11-16 03:34:57 +0000377 CCTUInfo, Results);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000378
Douglas Gregorb14904c2010-08-13 22:48:40 +0000379 // Translate global code completions into cached completions.
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000380 llvm::DenseMap<CanQualType, unsigned> CompletionTypes;
Douglas Gregorc3425b12015-07-07 06:20:19 +0000381 CodeCompletionContext CCContext(CodeCompletionContext::CCC_TopLevel);
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000382
Eugene Zelenko4f233182018-03-22 00:53:26 +0000383 for (auto &R : Results) {
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000384 switch (R.Kind) {
Douglas Gregor39982192010-08-15 06:18:01 +0000385 case Result::RK_Declaration: {
Douglas Gregor59cab552010-08-16 23:05:20 +0000386 bool IsNestedNameSpecifier = false;
Douglas Gregor39982192010-08-15 06:18:01 +0000387 CachedCodeCompletionResult CachedResult;
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000388 CachedResult.Completion = R.CreateCodeCompletionString(
Douglas Gregorc3425b12015-07-07 06:20:19 +0000389 *TheSema, CCContext, *CachedCompletionAllocator, CCTUInfo,
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000390 IncludeBriefCommentsInCodeCompletion);
391 CachedResult.ShowInContexts = getDeclShowContexts(
392 R.Declaration, Ctx->getLangOpts(), IsNestedNameSpecifier);
393 CachedResult.Priority = R.Priority;
394 CachedResult.Kind = R.CursorKind;
395 CachedResult.Availability = R.Availability;
Douglas Gregor24747402010-08-16 16:46:30 +0000396
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000397 // Keep track of the type of this completion in an ASTContext-agnostic
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000398 // way.
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000399 QualType UsageType = getDeclUsageType(*Ctx, R.Declaration);
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000400 if (UsageType.isNull()) {
Douglas Gregor24747402010-08-16 16:46:30 +0000401 CachedResult.TypeClass = STC_Void;
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000402 CachedResult.Type = 0;
403 } else {
404 CanQualType CanUsageType
405 = Ctx->getCanonicalType(UsageType.getUnqualifiedType());
406 CachedResult.TypeClass = getSimplifiedTypeClass(CanUsageType);
407
408 // Determine whether we have already seen this type. If so, we save
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000409 // ourselves the work of formatting the type string by using the
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000410 // temporary, CanQualType-based hash table to find the associated value.
411 unsigned &TypeValue = CompletionTypes[CanUsageType];
412 if (TypeValue == 0) {
413 TypeValue = CompletionTypes.size();
414 CachedCompletionTypes[QualType(CanUsageType).getAsString()]
415 = TypeValue;
416 }
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000417
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000418 CachedResult.Type = TypeValue;
Douglas Gregor24747402010-08-16 16:46:30 +0000419 }
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000420
Douglas Gregor39982192010-08-15 06:18:01 +0000421 CachedCompletionResults.push_back(CachedResult);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000422
Douglas Gregor59cab552010-08-16 23:05:20 +0000423 /// Handle nested-name-specifiers in C++.
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000424 if (TheSema->Context.getLangOpts().CPlusPlus && IsNestedNameSpecifier &&
425 !R.StartsNestedNameSpecifier) {
Douglas Gregor59cab552010-08-16 23:05:20 +0000426 // The contexts in which a nested-name-specifier can appear in C++.
Richard Smith697cc9e2012-08-14 03:13:00 +0000427 uint64_t NNSContexts
428 = (1LL << CodeCompletionContext::CCC_TopLevel)
429 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
430 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
431 | (1LL << CodeCompletionContext::CCC_Statement)
432 | (1LL << CodeCompletionContext::CCC_Expression)
433 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
434 | (1LL << CodeCompletionContext::CCC_EnumTag)
435 | (1LL << CodeCompletionContext::CCC_UnionTag)
436 | (1LL << CodeCompletionContext::CCC_ClassOrStructTag)
437 | (1LL << CodeCompletionContext::CCC_Type)
Kadir Cetinkayab006e092018-10-24 15:23:49 +0000438 | (1LL << CodeCompletionContext::CCC_SymbolOrNewName)
Richard Smith697cc9e2012-08-14 03:13:00 +0000439 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression);
Douglas Gregor59cab552010-08-16 23:05:20 +0000440
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000441 if (isa<NamespaceDecl>(R.Declaration) ||
442 isa<NamespaceAliasDecl>(R.Declaration))
Richard Smith697cc9e2012-08-14 03:13:00 +0000443 NNSContexts |= (1LL << CodeCompletionContext::CCC_Namespace);
Douglas Gregor59cab552010-08-16 23:05:20 +0000444
Kadir Cetinkayab006e092018-10-24 15:23:49 +0000445 if (uint64_t RemainingContexts
Douglas Gregor59cab552010-08-16 23:05:20 +0000446 = NNSContexts & ~CachedResult.ShowInContexts) {
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000447 // If there any contexts where this completion can be a
448 // nested-name-specifier but isn't already an option, create a
Douglas Gregor59cab552010-08-16 23:05:20 +0000449 // nested-name-specifier completion.
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000450 R.StartsNestedNameSpecifier = true;
451 CachedResult.Completion = R.CreateCodeCompletionString(
Douglas Gregorc3425b12015-07-07 06:20:19 +0000452 *TheSema, CCContext, *CachedCompletionAllocator, CCTUInfo,
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000453 IncludeBriefCommentsInCodeCompletion);
Douglas Gregor59cab552010-08-16 23:05:20 +0000454 CachedResult.ShowInContexts = RemainingContexts;
455 CachedResult.Priority = CCP_NestedNameSpecifier;
456 CachedResult.TypeClass = STC_Void;
457 CachedResult.Type = 0;
458 CachedCompletionResults.push_back(CachedResult);
459 }
460 }
Douglas Gregorb14904c2010-08-13 22:48:40 +0000461 break;
Douglas Gregor39982192010-08-15 06:18:01 +0000462 }
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000463
Douglas Gregorb14904c2010-08-13 22:48:40 +0000464 case Result::RK_Keyword:
465 case Result::RK_Pattern:
466 // Ignore keywords and patterns; we don't care, since they are so
467 // easily regenerated.
468 break;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000469
Douglas Gregorb14904c2010-08-13 22:48:40 +0000470 case Result::RK_Macro: {
471 CachedCodeCompletionResult CachedResult;
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000472 CachedResult.Completion = R.CreateCodeCompletionString(
Douglas Gregorc3425b12015-07-07 06:20:19 +0000473 *TheSema, CCContext, *CachedCompletionAllocator, CCTUInfo,
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000474 IncludeBriefCommentsInCodeCompletion);
Douglas Gregorb14904c2010-08-13 22:48:40 +0000475 CachedResult.ShowInContexts
Richard Smith697cc9e2012-08-14 03:13:00 +0000476 = (1LL << CodeCompletionContext::CCC_TopLevel)
477 | (1LL << CodeCompletionContext::CCC_ObjCInterface)
478 | (1LL << CodeCompletionContext::CCC_ObjCImplementation)
479 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
480 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
481 | (1LL << CodeCompletionContext::CCC_Statement)
482 | (1LL << CodeCompletionContext::CCC_Expression)
483 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
484 | (1LL << CodeCompletionContext::CCC_MacroNameUse)
485 | (1LL << CodeCompletionContext::CCC_PreprocessorExpression)
486 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
487 | (1LL << CodeCompletionContext::CCC_OtherWithMacros);
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000488
489 CachedResult.Priority = R.Priority;
490 CachedResult.Kind = R.CursorKind;
491 CachedResult.Availability = R.Availability;
Douglas Gregor6e240332010-08-16 16:18:59 +0000492 CachedResult.TypeClass = STC_Void;
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000493 CachedResult.Type = 0;
Douglas Gregorb14904c2010-08-13 22:48:40 +0000494 CachedCompletionResults.push_back(CachedResult);
495 break;
496 }
497 }
Douglas Gregorb14904c2010-08-13 22:48:40 +0000498 }
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000499
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000500 // Save the current top-level hash value.
501 CompletionCacheTopLevelHashValue = CurrentTopLevelHashValue;
Douglas Gregorb14904c2010-08-13 22:48:40 +0000502}
503
504void ASTUnit::ClearCachedCompletionResults() {
Douglas Gregorb14904c2010-08-13 22:48:40 +0000505 CachedCompletionResults.clear();
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000506 CachedCompletionTypes.clear();
Craig Topper49a27902014-05-22 04:46:25 +0000507 CachedCompletionAllocator = nullptr;
Douglas Gregorb14904c2010-08-13 22:48:40 +0000508}
509
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000510namespace {
511
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000512/// Gathers information from ASTReader that will be used to initialize
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000513/// a Preprocessor.
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000514class ASTInfoCollector : public ASTReaderListener {
Douglas Gregor83297df2011-09-01 23:39:15 +0000515 Preprocessor &PP;
Richard Smithdbafb6c2017-06-29 23:23:46 +0000516 ASTContext *Context;
Richard Smith18934752017-06-06 00:32:01 +0000517 HeaderSearchOptions &HSOpts;
518 PreprocessorOptions &PPOpts;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000519 LangOptions &LangOpt;
Alp Toker80758082014-07-06 05:26:44 +0000520 std::shared_ptr<TargetOptions> &TargetOpts;
Dylan Noblesmithc95d8192012-02-20 14:00:23 +0000521 IntrusiveRefCntPtr<TargetInfo> &Target;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000522 unsigned &Counter;
Eugene Zelenko4f233182018-03-22 00:53:26 +0000523 bool InitializedLanguage = false;
Mike Stump11289f42009-09-09 15:08:12 +0000524
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000525public:
Richard Smithdbafb6c2017-06-29 23:23:46 +0000526 ASTInfoCollector(Preprocessor &PP, ASTContext *Context,
Richard Smith18934752017-06-06 00:32:01 +0000527 HeaderSearchOptions &HSOpts, PreprocessorOptions &PPOpts,
528 LangOptions &LangOpt,
Alp Toker80758082014-07-06 05:26:44 +0000529 std::shared_ptr<TargetOptions> &TargetOpts,
530 IntrusiveRefCntPtr<TargetInfo> &Target, unsigned &Counter)
Richard Smith18934752017-06-06 00:32:01 +0000531 : PP(PP), Context(Context), HSOpts(HSOpts), PPOpts(PPOpts),
532 LangOpt(LangOpt), TargetOpts(TargetOpts), Target(Target),
Eugene Zelenko4f233182018-03-22 00:53:26 +0000533 Counter(Counter) {}
Mike Stump11289f42009-09-09 15:08:12 +0000534
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000535 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
536 bool AllowCompatibleDifferences) override {
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000537 if (InitializedLanguage)
Douglas Gregor83297df2011-09-01 23:39:15 +0000538 return false;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000539
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000540 LangOpt = LangOpts;
541 InitializedLanguage = true;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000542
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000543 updated();
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000544 return false;
545 }
Mike Stump11289f42009-09-09 15:08:12 +0000546
Eugene Zelenko4f233182018-03-22 00:53:26 +0000547 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
548 StringRef SpecificModuleCachePath,
549 bool Complain) override {
Richard Smith18934752017-06-06 00:32:01 +0000550 this->HSOpts = HSOpts;
551 return false;
552 }
553
Eugene Zelenko4f233182018-03-22 00:53:26 +0000554 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts, bool Complain,
555 std::string &SuggestedPredefines) override {
Richard Smith18934752017-06-06 00:32:01 +0000556 this->PPOpts = PPOpts;
557 return false;
558 }
559
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000560 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
561 bool AllowCompatibleDifferences) override {
Douglas Gregor83297df2011-09-01 23:39:15 +0000562 // If we've already initialized the target, don't do it again.
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000563 if (Target)
Douglas Gregor83297df2011-09-01 23:39:15 +0000564 return false;
Alp Toker80758082014-07-06 05:26:44 +0000565
566 this->TargetOpts = std::make_shared<TargetOptions>(TargetOpts);
567 Target =
568 TargetInfo::CreateTargetInfo(PP.getDiagnostics(), this->TargetOpts);
Argyrios Kyrtzidis9e1fb562012-09-14 20:24:53 +0000569
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000570 updated();
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000571 return false;
572 }
Mike Stump11289f42009-09-09 15:08:12 +0000573
Craig Topperafa7cb32014-03-13 06:07:04 +0000574 void ReadCounter(const serialization::ModuleFile &M,
575 unsigned Value) override {
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000576 Counter = Value;
577 }
Argyrios Kyrtzidis9e1fb562012-09-14 20:24:53 +0000578
579private:
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000580 void updated() {
581 if (!Target || !InitializedLanguage)
582 return;
583
584 // Inform the target of the language options.
585 //
586 // FIXME: We shouldn't need to do this, the target should be immutable once
587 // created. This complexity should be lifted elsewhere.
Alp Toker74437972014-07-06 05:14:24 +0000588 Target->adjust(LangOpt);
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000589
590 // Initialize the preprocessor.
591 PP.Initialize(*Target);
592
Richard Smithdbafb6c2017-06-29 23:23:46 +0000593 if (!Context)
594 return;
595
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000596 // Initialize the ASTContext
Richard Smithdbafb6c2017-06-29 23:23:46 +0000597 Context->InitBuiltinTypes(*Target);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +0000598
Vedant Kumarfd9fad92017-08-25 18:07:03 +0000599 // Adjust printing policy based on language options.
600 Context->setPrintingPolicy(PrintingPolicy(LangOpt));
601
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +0000602 // We didn't have access to the comment options when the ASTContext was
603 // constructed, so register them now.
Richard Smithdbafb6c2017-06-29 23:23:46 +0000604 Context->getCommentCommandTraits().registerCommentOptions(
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +0000605 LangOpt.CommentOpts);
Argyrios Kyrtzidis9e1fb562012-09-14 20:24:53 +0000606 }
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000607};
608
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000609/// Diagnostic consumer that saves each diagnostic it is given.
Nikolai Kosjar8edd8da2019-06-11 14:14:24 +0000610class FilterAndStoreDiagnosticConsumer : public DiagnosticConsumer {
Ilya Biryukov200b3282017-06-21 10:24:58 +0000611 SmallVectorImpl<StoredDiagnostic> *StoredDiags;
612 SmallVectorImpl<ASTUnit::StandaloneDiagnostic> *StandaloneDiags;
Nikolai Kosjar8edd8da2019-06-11 14:14:24 +0000613 bool CaptureNonErrorsFromIncludes = true;
Eugene Zelenko4f233182018-03-22 00:53:26 +0000614 const LangOptions *LangOpts = nullptr;
615 SourceManager *SourceMgr = nullptr;
Douglas Gregor6b930962013-05-03 22:58:43 +0000616
Douglas Gregor33cdd812010-02-18 18:08:43 +0000617public:
Nikolai Kosjar8edd8da2019-06-11 14:14:24 +0000618 FilterAndStoreDiagnosticConsumer(
Ilya Biryukov200b3282017-06-21 10:24:58 +0000619 SmallVectorImpl<StoredDiagnostic> *StoredDiags,
Nikolai Kosjar8edd8da2019-06-11 14:14:24 +0000620 SmallVectorImpl<ASTUnit::StandaloneDiagnostic> *StandaloneDiags,
621 bool CaptureNonErrorsFromIncludes)
622 : StoredDiags(StoredDiags), StandaloneDiags(StandaloneDiags),
623 CaptureNonErrorsFromIncludes(CaptureNonErrorsFromIncludes) {
Ilya Biryukov200b3282017-06-21 10:24:58 +0000624 assert((StoredDiags || StandaloneDiags) &&
625 "No output collections were passed to StoredDiagnosticConsumer.");
626 }
Douglas Gregor6b930962013-05-03 22:58:43 +0000627
Craig Topperafa7cb32014-03-13 06:07:04 +0000628 void BeginSourceFile(const LangOptions &LangOpts,
Craig Topper49a27902014-05-22 04:46:25 +0000629 const Preprocessor *PP = nullptr) override {
Ilya Biryukov200b3282017-06-21 10:24:58 +0000630 this->LangOpts = &LangOpts;
Douglas Gregor6b930962013-05-03 22:58:43 +0000631 if (PP)
632 SourceMgr = &PP->getSourceManager();
633 }
634
Craig Topperafa7cb32014-03-13 06:07:04 +0000635 void HandleDiagnostic(DiagnosticsEngine::Level Level,
636 const Diagnostic &Info) override;
Douglas Gregor33cdd812010-02-18 18:08:43 +0000637};
638
Nikolai Kosjar8edd8da2019-06-11 14:14:24 +0000639/// RAII object that optionally captures and filters diagnostics, if
Douglas Gregor33cdd812010-02-18 18:08:43 +0000640/// there is no diagnostic client to capture them already.
641class CaptureDroppedDiagnostics {
David Blaikie9c902b52011-09-25 23:23:43 +0000642 DiagnosticsEngine &Diags;
Nikolai Kosjar8edd8da2019-06-11 14:14:24 +0000643 FilterAndStoreDiagnosticConsumer Client;
Eugene Zelenko4f233182018-03-22 00:53:26 +0000644 DiagnosticConsumer *PreviousClient = nullptr;
Alexander Kornienko41c247a2014-11-17 23:46:02 +0000645 std::unique_ptr<DiagnosticConsumer> OwningPreviousClient;
Douglas Gregor33cdd812010-02-18 18:08:43 +0000646
647public:
Eugene Zelenko4f233182018-03-22 00:53:26 +0000648 CaptureDroppedDiagnostics(
Nikolai Kosjar8edd8da2019-06-11 14:14:24 +0000649 CaptureDiagsKind CaptureDiagnostics, DiagnosticsEngine &Diags,
Eugene Zelenko4f233182018-03-22 00:53:26 +0000650 SmallVectorImpl<StoredDiagnostic> *StoredDiags,
651 SmallVectorImpl<ASTUnit::StandaloneDiagnostic> *StandaloneDiags)
Nikolai Kosjar8edd8da2019-06-11 14:14:24 +0000652 : Diags(Diags),
653 Client(StoredDiags, StandaloneDiags,
654 CaptureDiagnostics !=
655 CaptureDiagsKind::AllWithoutNonErrorsFromIncludes) {
656 if (CaptureDiagnostics != CaptureDiagsKind::None ||
657 Diags.getClient() == nullptr) {
Alexander Kornienko41c247a2014-11-17 23:46:02 +0000658 OwningPreviousClient = Diags.takeClient();
659 PreviousClient = Diags.getClient();
660 Diags.setClient(&Client, false);
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000661 }
Douglas Gregor33cdd812010-02-18 18:08:43 +0000662 }
663
664 ~CaptureDroppedDiagnostics() {
Alexander Kornienko41c247a2014-11-17 23:46:02 +0000665 if (Diags.getClient() == &Client)
666 Diags.setClient(PreviousClient, !!OwningPreviousClient.release());
Douglas Gregor33cdd812010-02-18 18:08:43 +0000667 }
668};
669
Eugene Zelenko4f233182018-03-22 00:53:26 +0000670} // namespace
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000671
Ilya Biryukov200b3282017-06-21 10:24:58 +0000672static ASTUnit::StandaloneDiagnostic
673makeStandaloneDiagnostic(const LangOptions &LangOpts,
674 const StoredDiagnostic &InDiag);
675
Nikolai Kosjar8edd8da2019-06-11 14:14:24 +0000676static bool isInMainFile(const clang::Diagnostic &D) {
677 if (!D.hasSourceManager() || !D.getLocation().isValid())
678 return false;
679
680 auto &M = D.getSourceManager();
681 return M.isWrittenInMainFile(M.getExpansionLoc(D.getLocation()));
682}
683
684void FilterAndStoreDiagnosticConsumer::HandleDiagnostic(
685 DiagnosticsEngine::Level Level, const Diagnostic &Info) {
Argyrios Kyrtzidisc79346a2010-11-18 20:06:46 +0000686 // Default implementation (Warnings/errors count).
David Blaikiee2eefae2011-09-25 23:39:51 +0000687 DiagnosticConsumer::HandleDiagnostic(Level, Info);
Argyrios Kyrtzidisc79346a2010-11-18 20:06:46 +0000688
Douglas Gregor6b930962013-05-03 22:58:43 +0000689 // Only record the diagnostic if it's part of the source manager we know
690 // about. This effectively drops diagnostics from modules we're building.
691 // FIXME: In the long run, ee don't want to drop source managers from modules.
Ilya Biryukov200b3282017-06-21 10:24:58 +0000692 if (!Info.hasSourceManager() || &Info.getSourceManager() == SourceMgr) {
Nikolai Kosjar8edd8da2019-06-11 14:14:24 +0000693 if (!CaptureNonErrorsFromIncludes && Level <= DiagnosticsEngine::Warning &&
694 !isInMainFile(Info)) {
695 return;
696 }
697
Ilya Biryukov200b3282017-06-21 10:24:58 +0000698 StoredDiagnostic *ResultDiag = nullptr;
699 if (StoredDiags) {
700 StoredDiags->emplace_back(Level, Info);
701 ResultDiag = &StoredDiags->back();
702 }
703
704 if (StandaloneDiags) {
Eugene Zelenko4f233182018-03-22 00:53:26 +0000705 llvm::Optional<StoredDiagnostic> StoredDiag = None;
Ilya Biryukov200b3282017-06-21 10:24:58 +0000706 if (!ResultDiag) {
707 StoredDiag.emplace(Level, Info);
708 ResultDiag = StoredDiag.getPointer();
709 }
710 StandaloneDiags->push_back(
711 makeStandaloneDiagnostic(*LangOpts, *ResultDiag));
712 }
713 }
Douglas Gregor33cdd812010-02-18 18:08:43 +0000714}
715
Argyrios Kyrtzidisa38cb202017-01-30 06:05:58 +0000716IntrusiveRefCntPtr<ASTReader> ASTUnit::getASTReader() const {
717 return Reader;
718}
719
Argyrios Kyrtzidis1c7455f2013-05-10 01:28:51 +0000720ASTMutationListener *ASTUnit::getASTMutationListener() {
721 if (WriterData)
722 return &WriterData->Writer;
Craig Topper49a27902014-05-22 04:46:25 +0000723 return nullptr;
Argyrios Kyrtzidis1c7455f2013-05-10 01:28:51 +0000724}
725
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000726ASTDeserializationListener *ASTUnit::getDeserializationListener() {
727 if (WriterData)
728 return &WriterData->Writer;
Craig Topper49a27902014-05-22 04:46:25 +0000729 return nullptr;
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000730}
731
Rafael Espindola16e1ba12014-08-26 20:17:44 +0000732std::unique_ptr<llvm::MemoryBuffer>
733ASTUnit::getBufferForFile(StringRef Filename, std::string *ErrorStr) {
Chris Lattner5159f612010-11-23 08:35:12 +0000734 assert(FileMgr);
Ivan Donchevskii2ebe3a02018-06-06 07:17:26 +0000735 auto Buffer = FileMgr->getBufferForFile(Filename, UserFilesAreVolatile);
Benjamin Kramera8857962014-10-26 22:44:13 +0000736 if (Buffer)
737 return std::move(*Buffer);
738 if (ErrorStr)
739 *ErrorStr = Buffer.getError().message();
740 return nullptr;
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000741}
742
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000743/// Configure the diagnostics object for use with ASTUnit.
Justin Bognerd512c1e2014-10-15 00:33:06 +0000744void ASTUnit::ConfigureDiags(IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Nikolai Kosjar8edd8da2019-06-11 14:14:24 +0000745 ASTUnit &AST,
746 CaptureDiagsKind CaptureDiagnostics) {
Justin Bognerd512c1e2014-10-15 00:33:06 +0000747 assert(Diags.get() && "no DiagnosticsEngine was provided");
Nikolai Kosjar8edd8da2019-06-11 14:14:24 +0000748 if (CaptureDiagnostics != CaptureDiagsKind::None)
749 Diags->setClient(new FilterAndStoreDiagnosticConsumer(
750 &AST.StoredDiagnostics, nullptr,
751 CaptureDiagnostics != CaptureDiagsKind::AllWithoutNonErrorsFromIncludes));
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000752}
753
David Blaikie6f7382d2014-08-10 19:08:04 +0000754std::unique_ptr<ASTUnit> ASTUnit::LoadFromASTFile(
Adrian Prantl6b21ab22015-08-27 19:46:20 +0000755 const std::string &Filename, const PCHContainerReader &PCHContainerRdr,
Richard Smithdbafb6c2017-06-29 23:23:46 +0000756 WhatToLoad ToLoad, IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Adrian Prantl6b21ab22015-08-27 19:46:20 +0000757 const FileSystemOptions &FileSystemOpts, bool UseDebugInfo,
758 bool OnlyLocalDecls, ArrayRef<RemappedFile> RemappedFiles,
Nikolai Kosjar8edd8da2019-06-11 14:14:24 +0000759 CaptureDiagsKind CaptureDiagnostics, bool AllowPCHWithCompilerErrors,
Adrian Prantl6b21ab22015-08-27 19:46:20 +0000760 bool UserFilesAreVolatile) {
Ahmed Charlesb8984322014-03-07 20:03:18 +0000761 std::unique_ptr<ASTUnit> AST(new ASTUnit(true));
Ted Kremenek4422bfe2011-03-18 02:06:56 +0000762
763 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +0000764 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
765 ASTUnitCleanup(AST.get());
David Blaikie9c902b52011-09-25 23:23:43 +0000766 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
Eugene Zelenko4f233182018-03-22 00:53:26 +0000767 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine>>
Alp Tokerf994cef2014-07-05 03:08:06 +0000768 DiagCleanup(Diags.get());
Ted Kremenek4422bfe2011-03-18 02:06:56 +0000769
Justin Bognerdbbcb112014-10-14 23:36:06 +0000770 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000771
Richard Smithab755972017-06-05 18:10:11 +0000772 AST->LangOpts = std::make_shared<LangOptions>();
Douglas Gregor16bef852009-10-16 20:01:17 +0000773 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000774 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor7f95d262010-04-05 23:52:57 +0000775 AST->Diagnostics = Diags;
Jonas Devliegherefc514902018-10-10 13:27:25 +0000776 IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS =
777 llvm::vfs::getRealFileSystem();
Ben Langmuir8832c062014-04-15 18:16:25 +0000778 AST->FileMgr = new FileManager(FileSystemOpts, VFS);
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +0000779 AST->UserFilesAreVolatile = UserFilesAreVolatile;
Ted Kremenek5e14d392011-03-21 18:40:17 +0000780 AST->SourceMgr = new SourceManager(AST->getDiagnostics(),
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +0000781 AST->getFileManager(),
782 UserFilesAreVolatile);
Duncan P. N. Exon Smith8bef5cd2019-03-09 17:33:56 +0000783 AST->ModuleCache = new InMemoryModuleCache;
David Blaikie9c28cb32017-01-06 01:04:46 +0000784 AST->HSOpts = std::make_shared<HeaderSearchOptions>();
Adrian Prantlfb2398d2015-07-17 01:19:54 +0000785 AST->HSOpts->ModuleFormat = PCHContainerRdr.getFormat();
Douglas Gregorb85b9cc2012-10-24 16:19:39 +0000786 AST->HeaderInfo.reset(new HeaderSearch(AST->HSOpts,
Manuel Klimek1f76c4e2013-10-24 07:51:24 +0000787 AST->getSourceManager(),
Douglas Gregor1fb5c3a2011-12-31 04:05:44 +0000788 AST->getDiagnostics(),
Richard Smithab755972017-06-05 18:10:11 +0000789 AST->getLangOpts(),
Craig Topper49a27902014-05-22 04:46:25 +0000790 /*Target=*/nullptr));
Richard Smith18934752017-06-06 00:32:01 +0000791 AST->PPOpts = std::make_shared<PreprocessorOptions>();
Dmitri Gribenkoc444b572014-02-08 00:38:15 +0000792
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000793 for (const auto &RemappedFile : RemappedFiles)
Richard Smith18934752017-06-06 00:32:01 +0000794 AST->PPOpts->addRemappedFile(RemappedFile.first, RemappedFile.second);
Dmitri Gribenkoc444b572014-02-08 00:38:15 +0000795
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000796 // Gather Info for preprocessor construction later on.
Mike Stump11289f42009-09-09 15:08:12 +0000797
David Blaikie6f7382d2014-08-10 19:08:04 +0000798 HeaderSearch &HeaderInfo = *AST->HeaderInfo;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000799 unsigned Counter;
800
David Blaikie41565462017-01-05 19:48:07 +0000801 AST->PP = std::make_shared<Preprocessor>(
Richard Smith18934752017-06-06 00:32:01 +0000802 AST->PPOpts, AST->getDiagnostics(), *AST->LangOpts,
Duncan P. N. Exon Smith8bef5cd2019-03-09 17:33:56 +0000803 AST->getSourceManager(), HeaderInfo, AST->ModuleLoader,
David Blaikie41565462017-01-05 19:48:07 +0000804 /*IILookup=*/nullptr,
805 /*OwnsHeaderSearch=*/false);
Douglas Gregore8bbc122011-09-02 00:18:52 +0000806 Preprocessor &PP = *AST->PP;
807
Richard Smithdbafb6c2017-06-29 23:23:46 +0000808 if (ToLoad >= LoadASTOnly)
809 AST->Ctx = new ASTContext(*AST->LangOpts, AST->getSourceManager(),
810 PP.getIdentifierTable(), PP.getSelectorTable(),
811 PP.getBuiltinInfo());
Douglas Gregor83297df2011-09-01 23:39:15 +0000812
Argyrios Kyrtzidis945a8192012-09-15 01:10:20 +0000813 bool disableValid = false;
814 if (::getenv("LIBCLANG_DISABLE_PCH_VALIDATION"))
815 disableValid = true;
Duncan P. N. Exon Smith8bef5cd2019-03-09 17:33:56 +0000816 AST->Reader = new ASTReader(
817 PP, *AST->ModuleCache, AST->Ctx.get(), PCHContainerRdr, {},
818 /*isysroot=*/"",
819 /*DisableValidation=*/disableValid, AllowPCHWithCompilerErrors);
Ted Kremenek2159b8d2011-05-04 23:27:12 +0000820
David Blaikie2721c322014-08-10 16:54:39 +0000821 AST->Reader->setListener(llvm::make_unique<ASTInfoCollector>(
Richard Smithdbafb6c2017-06-29 23:23:46 +0000822 *AST->PP, AST->Ctx.get(), *AST->HSOpts, *AST->PPOpts, *AST->LangOpts,
Richard Smith18934752017-06-06 00:32:01 +0000823 AST->TargetOpts, AST->Target, Counter));
Daniel Dunbar2d9c7402009-09-03 05:59:35 +0000824
Argyrios Kyrtzidisf0b4cd12015-03-03 08:04:19 +0000825 // Attach the AST reader to the AST context as an external AST
826 // source, so that declarations will be deserialized from the
827 // AST file as needed.
828 // We need the external source to be set up before we read the AST, because
829 // eagerly-deserialized declarations may use it.
Richard Smithdbafb6c2017-06-29 23:23:46 +0000830 if (AST->Ctx)
831 AST->Ctx->setExternalSource(AST->Reader);
Argyrios Kyrtzidisf0b4cd12015-03-03 08:04:19 +0000832
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000833 switch (AST->Reader->ReadAST(Filename, serialization::MK_MainFile,
Argyrios Kyrtzidis2ec29362012-11-15 18:57:22 +0000834 SourceLocation(), ASTReader::ARR_None)) {
Sebastian Redl2c499f62010-08-18 23:56:43 +0000835 case ASTReader::Success:
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000836 break;
Mike Stump11289f42009-09-09 15:08:12 +0000837
Sebastian Redl2c499f62010-08-18 23:56:43 +0000838 case ASTReader::Failure:
Douglas Gregor7029ce12013-03-19 00:28:20 +0000839 case ASTReader::Missing:
Douglas Gregorc9ad5fb2012-10-22 22:50:17 +0000840 case ASTReader::OutOfDate:
841 case ASTReader::VersionMismatch:
842 case ASTReader::ConfigurationMismatch:
843 case ASTReader::HadErrors:
Douglas Gregord03e8232010-04-05 21:10:19 +0000844 AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
Craig Topper49a27902014-05-22 04:46:25 +0000845 return nullptr;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000846 }
Mike Stump11289f42009-09-09 15:08:12 +0000847
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000848 AST->OriginalSourceFile = AST->Reader->getOriginalSourceFile();
Daniel Dunbara8a50932009-12-02 08:44:16 +0000849
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000850 PP.setCounterValue(Counter);
Mike Stump11289f42009-09-09 15:08:12 +0000851
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000852 // Create an AST consumer, even though it isn't used.
Richard Smithdbafb6c2017-06-29 23:23:46 +0000853 if (ToLoad >= LoadASTOnly)
854 AST->Consumer.reset(new ASTConsumer);
855
Sebastian Redl2c499f62010-08-18 23:56:43 +0000856 // Create a semantic analysis object and tell the AST reader about it.
Richard Smithdbafb6c2017-06-29 23:23:46 +0000857 if (ToLoad >= LoadEverything) {
858 AST->TheSema.reset(new Sema(PP, *AST->Ctx, *AST->Consumer));
859 AST->TheSema->Initialize();
860 AST->Reader->InitializeSema(*AST->TheSema);
861 }
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000862
Douglas Gregor6b930962013-05-03 22:58:43 +0000863 // Tell the diagnostic client that we have started a source file.
Richard Smithdbafb6c2017-06-29 23:23:46 +0000864 AST->getDiagnostics().getClient()->BeginSourceFile(PP.getLangOpts(), &PP);
Douglas Gregor6b930962013-05-03 22:58:43 +0000865
David Blaikie6f7382d2014-08-10 19:08:04 +0000866 return AST;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000867}
Daniel Dunbar764c0822009-12-01 09:51:01 +0000868
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000869/// Add the given macro to the hash of all top-level entities.
Eugene Zelenko4f233182018-03-22 00:53:26 +0000870static void AddDefinedMacroToHash(const Token &MacroNameTok, unsigned &Hash) {
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000871 Hash = llvm::djbHash(MacroNameTok.getIdentifierInfo()->getName(), Hash);
Ilya Biryukov200b3282017-06-21 10:24:58 +0000872}
873
Eugene Zelenko4f233182018-03-22 00:53:26 +0000874namespace {
875
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000876/// Preprocessor callback class that updates a hash value with the names
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000877/// of all macros that have been defined by the translation unit.
878class MacroDefinitionTrackerPPCallbacks : public PPCallbacks {
879 unsigned &Hash;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000880
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000881public:
Eugene Zelenko4f233182018-03-22 00:53:26 +0000882 explicit MacroDefinitionTrackerPPCallbacks(unsigned &Hash) : Hash(Hash) {}
Craig Topperafa7cb32014-03-13 06:07:04 +0000883
884 void MacroDefined(const Token &MacroNameTok,
885 const MacroDirective *MD) override {
Ilya Biryukov200b3282017-06-21 10:24:58 +0000886 AddDefinedMacroToHash(MacroNameTok, Hash);
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000887 }
888};
889
Eugene Zelenko4f233182018-03-22 00:53:26 +0000890} // namespace
891
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000892/// Add the given declaration to the hash of all top-level entities.
Eugene Zelenko4f233182018-03-22 00:53:26 +0000893static void AddTopLevelDeclarationToHash(Decl *D, unsigned &Hash) {
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000894 if (!D)
895 return;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000896
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000897 DeclContext *DC = D->getDeclContext();
898 if (!DC)
899 return;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000900
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000901 if (!(DC->isTranslationUnit() || DC->getLookupParent()->isTranslationUnit()))
902 return;
903
Eugene Zelenko4f233182018-03-22 00:53:26 +0000904 if (const auto *ND = dyn_cast<NamedDecl>(D)) {
905 if (const auto *EnumD = dyn_cast<EnumDecl>(D)) {
Argyrios Kyrtzidisca5c7be2013-10-15 17:37:55 +0000906 // For an unscoped enum include the enumerators in the hash since they
907 // enter the top-level namespace.
908 if (!EnumD->isScoped()) {
Aaron Ballman23a6dcb2014-03-08 18:45:14 +0000909 for (const auto *EI : EnumD->enumerators()) {
910 if (EI->getIdentifier())
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000911 Hash = llvm::djbHash(EI->getIdentifier()->getName(), Hash);
Argyrios Kyrtzidisca5c7be2013-10-15 17:37:55 +0000912 }
913 }
914 }
915
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000916 if (ND->getIdentifier())
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000917 Hash = llvm::djbHash(ND->getIdentifier()->getName(), Hash);
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000918 else if (DeclarationName Name = ND->getDeclName()) {
919 std::string NameStr = Name.getAsString();
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000920 Hash = llvm::djbHash(NameStr, Hash);
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000921 }
922 return;
Argyrios Kyrtzidis48d88de2013-06-24 21:19:12 +0000923 }
924
Eugene Zelenko4f233182018-03-22 00:53:26 +0000925 if (const auto *ImportD = dyn_cast<ImportDecl>(D)) {
926 if (const Module *Mod = ImportD->getImportedModule()) {
Argyrios Kyrtzidis48d88de2013-06-24 21:19:12 +0000927 std::string ModName = Mod->getFullModuleName();
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000928 Hash = llvm::djbHash(ModName, Hash);
Argyrios Kyrtzidis48d88de2013-06-24 21:19:12 +0000929 }
930 return;
931 }
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000932}
933
Eugene Zelenko4f233182018-03-22 00:53:26 +0000934namespace {
935
Daniel Dunbar644dca02009-12-04 08:17:33 +0000936class TopLevelDeclTrackerConsumer : public ASTConsumer {
937 ASTUnit &Unit;
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000938 unsigned &Hash;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000939
Daniel Dunbar644dca02009-12-04 08:17:33 +0000940public:
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000941 TopLevelDeclTrackerConsumer(ASTUnit &_Unit, unsigned &Hash)
Eugene Zelenko4f233182018-03-22 00:53:26 +0000942 : Unit(_Unit), Hash(Hash) {
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000943 Hash = 0;
944 }
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000945
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000946 void handleTopLevelDecl(Decl *D) {
Argyrios Kyrtzidis516eec22011-11-16 02:35:10 +0000947 if (!D)
948 return;
949
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000950 // FIXME: Currently ObjC method declarations are incorrectly being
951 // reported as top-level declarations, even though their DeclContext
952 // is the containing ObjC @interface/@implementation. This is a
953 // fundamental problem in the parser right now.
954 if (isa<ObjCMethodDecl>(D))
955 return;
956
957 AddTopLevelDeclarationToHash(D, Hash);
958 Unit.addTopLevelDecl(D);
959
960 handleFileLevelDecl(D);
961 }
962
963 void handleFileLevelDecl(Decl *D) {
964 Unit.addFileLevelDecl(D);
Eugene Zelenko4f233182018-03-22 00:53:26 +0000965 if (auto *NSD = dyn_cast<NamespaceDecl>(D)) {
Aaron Ballman629afae2014-03-07 19:56:05 +0000966 for (auto *I : NSD->decls())
967 handleFileLevelDecl(I);
Ted Kremenekacc59c32010-05-03 20:16:35 +0000968 }
Daniel Dunbar644dca02009-12-04 08:17:33 +0000969 }
Sebastian Redleaa4ade2010-08-11 18:52:41 +0000970
Craig Topperafa7cb32014-03-13 06:07:04 +0000971 bool HandleTopLevelDecl(DeclGroupRef D) override {
Eugene Zelenko4f233182018-03-22 00:53:26 +0000972 for (auto *TopLevelDecl : D)
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000973 handleTopLevelDecl(TopLevelDecl);
Argyrios Kyrtzidis841dd882011-11-18 00:26:59 +0000974 return true;
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000975 }
976
Sebastian Redleaa4ade2010-08-11 18:52:41 +0000977 // We're not interested in "interesting" decls.
Craig Topperafa7cb32014-03-13 06:07:04 +0000978 void HandleInterestingDecl(DeclGroupRef) override {}
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000979
Craig Topperafa7cb32014-03-13 06:07:04 +0000980 void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) override {
Eugene Zelenko4f233182018-03-22 00:53:26 +0000981 for (auto *TopLevelDecl : D)
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000982 handleTopLevelDecl(TopLevelDecl);
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000983 }
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000984
Craig Topperafa7cb32014-03-13 06:07:04 +0000985 ASTMutationListener *GetASTMutationListener() override {
Argyrios Kyrtzidis1c7455f2013-05-10 01:28:51 +0000986 return Unit.getASTMutationListener();
987 }
988
Craig Topperafa7cb32014-03-13 06:07:04 +0000989 ASTDeserializationListener *GetASTDeserializationListener() override {
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000990 return Unit.getDeserializationListener();
991 }
Daniel Dunbar644dca02009-12-04 08:17:33 +0000992};
993
994class TopLevelDeclTrackerAction : public ASTFrontendAction {
995public:
996 ASTUnit &Unit;
997
David Blaikie6beb6aa2014-08-10 19:56:51 +0000998 std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
999 StringRef InFile) override {
Douglas Gregordf7a79a2011-02-16 18:16:54 +00001000 CI.getPreprocessor().addPPCallbacks(
Craig Topperb8a70532014-09-10 04:53:53 +00001001 llvm::make_unique<MacroDefinitionTrackerPPCallbacks>(
1002 Unit.getCurrentTopLevelHashValue()));
David Blaikie6beb6aa2014-08-10 19:56:51 +00001003 return llvm::make_unique<TopLevelDeclTrackerConsumer>(
1004 Unit, Unit.getCurrentTopLevelHashValue());
Daniel Dunbar764c0822009-12-01 09:51:01 +00001005 }
1006
1007public:
Daniel Dunbar644dca02009-12-04 08:17:33 +00001008 TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {}
1009
Craig Topperafa7cb32014-03-13 06:07:04 +00001010 bool hasCodeCompletionSupport() const override { return false; }
Eugene Zelenko4f233182018-03-22 00:53:26 +00001011
Craig Topperafa7cb32014-03-13 06:07:04 +00001012 TranslationUnitKind getTranslationUnitKind() override {
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001013 return Unit.getTranslationUnitKind();
Douglas Gregor028d3e42010-08-09 20:45:32 +00001014 }
Daniel Dunbar764c0822009-12-01 09:51:01 +00001015};
1016
Ilya Biryukov200b3282017-06-21 10:24:58 +00001017class ASTUnitPreambleCallbacks : public PreambleCallbacks {
Benjamin Kramer65745dc2013-06-11 13:07:19 +00001018public:
Ilya Biryukov200b3282017-06-21 10:24:58 +00001019 unsigned getHash() const { return Hash; }
Benjamin Kramer65745dc2013-06-11 13:07:19 +00001020
Ilya Biryukov200b3282017-06-21 10:24:58 +00001021 std::vector<Decl *> takeTopLevelDecls() { return std::move(TopLevelDecls); }
Benjamin Kramer65745dc2013-06-11 13:07:19 +00001022
Ilya Biryukov200b3282017-06-21 10:24:58 +00001023 std::vector<serialization::DeclID> takeTopLevelDeclIDs() {
1024 return std::move(TopLevelDeclIDs);
Douglas Gregordf7a79a2011-02-16 18:16:54 +00001025 }
Douglas Gregor48c8cd32010-08-03 08:14:03 +00001026
Ilya Biryukov200b3282017-06-21 10:24:58 +00001027 void AfterPCHEmitted(ASTWriter &Writer) override {
1028 TopLevelDeclIDs.reserve(TopLevelDecls.size());
Eugene Zelenko4f233182018-03-22 00:53:26 +00001029 for (const auto *D : TopLevelDecls) {
Ilya Biryukov200b3282017-06-21 10:24:58 +00001030 // Invalid top-level decls may not have been serialized.
1031 if (D->isInvalidDecl())
1032 continue;
1033 TopLevelDeclIDs.push_back(Writer.getDeclID(D));
1034 }
1035 }
1036
1037 void HandleTopLevelDecl(DeclGroupRef DG) override {
Eugene Zelenko4f233182018-03-22 00:53:26 +00001038 for (auto *D : DG) {
Douglas Gregor48c8cd32010-08-03 08:14:03 +00001039 // FIXME: Currently ObjC method declarations are incorrectly being
1040 // reported as top-level declarations, even though their DeclContext
1041 // is the containing ObjC @interface/@implementation. This is a
1042 // fundamental problem in the parser right now.
1043 if (isa<ObjCMethodDecl>(D))
1044 continue;
Douglas Gregordf7a79a2011-02-16 18:16:54 +00001045 AddTopLevelDeclarationToHash(D, Hash);
Douglas Gregore9db88f2010-08-03 19:06:41 +00001046 TopLevelDecls.push_back(D);
1047 }
1048 }
1049
Ilya Biryukov41e90bc2017-12-15 11:27:51 +00001050 std::unique_ptr<PPCallbacks> createPPCallbacks() override {
1051 return llvm::make_unique<MacroDefinitionTrackerPPCallbacks>(Hash);
Douglas Gregor48c8cd32010-08-03 08:14:03 +00001052 }
Ilya Biryukov200b3282017-06-21 10:24:58 +00001053
1054private:
Ilya Biryukov200b3282017-06-21 10:24:58 +00001055 unsigned Hash = 0;
1056 std::vector<Decl *> TopLevelDecls;
1057 std::vector<serialization::DeclID> TopLevelDeclIDs;
1058 llvm::SmallVector<ASTUnit::StandaloneDiagnostic, 4> PreambleDiags;
Douglas Gregor48c8cd32010-08-03 08:14:03 +00001059};
1060
Eugene Zelenko4f233182018-03-22 00:53:26 +00001061} // namespace
Douglas Gregor48c8cd32010-08-03 08:14:03 +00001062
Benjamin Kramer1ce5d802013-05-05 12:39:28 +00001063static bool isNonDriverDiag(const StoredDiagnostic &StoredDiag) {
1064 return StoredDiag.getLocation().isValid();
1065}
1066
1067static void
1068checkAndRemoveNonDriverDiags(SmallVectorImpl<StoredDiagnostic> &StoredDiags) {
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +00001069 // Get rid of stored diagnostics except the ones from the driver which do not
1070 // have a source location.
Benjamin Kramer1ce5d802013-05-05 12:39:28 +00001071 StoredDiags.erase(
1072 std::remove_if(StoredDiags.begin(), StoredDiags.end(), isNonDriverDiag),
1073 StoredDiags.end());
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +00001074}
1075
1076static void checkAndSanitizeDiags(SmallVectorImpl<StoredDiagnostic> &
1077 StoredDiagnostics,
1078 SourceManager &SM) {
1079 // The stored diagnostic has the old source manager in it; update
1080 // the locations to refer into the new source manager. Since we've
1081 // been careful to make sure that the source manager's state
1082 // before and after are identical, so that we can reuse the source
1083 // location itself.
Eugene Zelenko4f233182018-03-22 00:53:26 +00001084 for (auto &SD : StoredDiagnostics) {
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00001085 if (SD.getLocation().isValid()) {
1086 FullSourceLoc Loc(SD.getLocation(), SM);
1087 SD.setLocation(Loc);
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +00001088 }
1089 }
1090}
1091
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001092/// Parse the source file into a translation unit using the given compiler
1093/// invocation, replacing the current translation unit.
1094///
1095/// \returns True if a failure occurred that causes the ASTUnit not to
1096/// contain any translation-unit information, false otherwise.
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001097bool ASTUnit::Parse(std::shared_ptr<PCHContainerOperations> PCHContainerOps,
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001098 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer,
Jonas Devliegherefc514902018-10-10 13:27:25 +00001099 IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS) {
Rafael Espindola32482082014-08-18 16:23:45 +00001100 if (!Invocation)
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001101 return true;
Rafael Espindola32482082014-08-18 16:23:45 +00001102
Duncan P. N. Exon Smith1da7eac2019-03-26 22:18:52 +00001103 if (VFS && FileMgr)
Duncan P. N. Exon Smithdb8a7422019-03-26 22:32:06 +00001104 assert(VFS == &FileMgr->getVirtualFileSystem() &&
Duncan P. N. Exon Smith1da7eac2019-03-26 22:18:52 +00001105 "VFS passed to Parse and VFS in FileMgr are different");
1106
Ilya Biryukov417085a2017-11-16 16:25:01 +00001107 auto CCInvocation = std::make_shared<CompilerInvocation>(*Invocation);
1108 if (OverrideMainBuffer) {
1109 assert(Preamble &&
1110 "No preamble was built, but OverrideMainBuffer is not null");
Ilya Biryukov417085a2017-11-16 16:25:01 +00001111 Preamble->AddImplicitPreamble(*CCInvocation, VFS, OverrideMainBuffer.get());
Duncan P. N. Exon Smith1da7eac2019-03-26 22:18:52 +00001112 // VFS may have changed...
Ilya Biryukov417085a2017-11-16 16:25:01 +00001113 }
1114
Daniel Dunbar764c0822009-12-01 09:51:01 +00001115 // Create the compiler instance to use for building the AST.
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001116 std::unique_ptr<CompilerInstance> Clang(
Benjamin Kramerd6da1a02016-06-12 20:05:23 +00001117 new CompilerInstance(std::move(PCHContainerOps)));
Duncan P. N. Exon Smith1da7eac2019-03-26 22:18:52 +00001118
1119 // Ensure that Clang has a FileManager with the right VFS, which may have
1120 // changed above in AddImplicitPreamble. If VFS is nullptr, rely on
1121 // createFileManager to create one.
Duncan P. N. Exon Smithdb8a7422019-03-26 22:32:06 +00001122 if (VFS && FileMgr && &FileMgr->getVirtualFileSystem() == VFS)
Duncan P. N. Exon Smith1da7eac2019-03-26 22:18:52 +00001123 Clang->setFileManager(&*FileMgr);
1124 else
1125 FileMgr = Clang->createFileManager(std::move(VFS));
Ted Kremenek84de4a12011-03-21 18:40:07 +00001126
1127 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00001128 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1129 CICleanup(Clang.get());
Ted Kremenek84de4a12011-03-21 18:40:07 +00001130
Ilya Biryukov417085a2017-11-16 16:25:01 +00001131 Clang->setInvocation(CCInvocation);
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001132 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001133
Douglas Gregor8e984da2010-08-04 16:47:14 +00001134 // Set up diagnostics, capturing any diagnostics that would
1135 // otherwise be dropped.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001136 Clang->setDiagnostics(&getDiagnostics());
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001137
Daniel Dunbar764c0822009-12-01 09:51:01 +00001138 // Create the target instance.
Alp Toker80758082014-07-06 05:26:44 +00001139 Clang->setTarget(TargetInfo::CreateTargetInfo(
Saleem Abdulrasool10a49722016-04-08 16:52:00 +00001140 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
Rafael Espindola32482082014-08-18 16:23:45 +00001141 if (!Clang->hasTarget())
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001142 return true;
Douglas Gregora0734c52010-08-19 01:33:06 +00001143
Daniel Dunbar764c0822009-12-01 09:51:01 +00001144 // Inform the target of the language options.
1145 //
1146 // FIXME: We shouldn't need to do this, the target should be immutable once
1147 // created. This complexity should be lifted elsewhere.
Alp Toker74437972014-07-06 05:14:24 +00001148 Clang->getTarget().adjust(Clang->getLangOpts());
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001149
Ted Kremenek84de4a12011-03-21 18:40:07 +00001150 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Daniel Dunbar764c0822009-12-01 09:51:01 +00001151 "Invocation must have exactly one source file!");
Richard Smith40c0efa2017-04-26 18:57:40 +00001152 assert(Clang->getFrontendOpts().Inputs[0].getKind().getFormat() ==
1153 InputKind::Source &&
Daniel Dunbar764c0822009-12-01 09:51:01 +00001154 "FIXME: AST inputs not yet supported here!");
Richard Smith40c0efa2017-04-26 18:57:40 +00001155 assert(Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() !=
1156 InputKind::LLVM_IR &&
Daniel Dunbar9507f9c2010-06-07 23:26:47 +00001157 "IR inputs not support here!");
Daniel Dunbar764c0822009-12-01 09:51:01 +00001158
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001159 // Configure the various subsystems.
Alp Toker269d8402014-07-06 05:26:07 +00001160 LangOpts = Clang->getInvocation().LangOpts;
Ted Kremenek84de4a12011-03-21 18:40:07 +00001161 FileSystemOpts = Clang->getFileSystemOpts();
Erik Verbruggen346066b2017-05-30 14:25:54 +00001162
1163 ResetForParse();
1164
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +00001165 SourceMgr = new SourceManager(getDiagnostics(), *FileMgr,
1166 UserFilesAreVolatile);
Douglas Gregor7b02b582010-08-20 00:02:33 +00001167 if (!OverrideMainBuffer) {
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +00001168 checkAndRemoveNonDriverDiags(StoredDiagnostics);
Douglas Gregor7b02b582010-08-20 00:02:33 +00001169 TopLevelDeclsInPreamble.clear();
1170 }
1171
Daniel Dunbar764c0822009-12-01 09:51:01 +00001172 // Create a file manager object to provide access to and cache the filesystem.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001173 Clang->setFileManager(&getFileManager());
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001174
Daniel Dunbar764c0822009-12-01 09:51:01 +00001175 // Create the source manager.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001176 Clang->setSourceManager(&getSourceManager());
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001177
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001178 // If the main file has been overridden due to the use of a preamble,
1179 // make that override happen and introduce the preamble.
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001180 if (OverrideMainBuffer) {
Douglas Gregord9a30af2010-08-02 20:51:39 +00001181 // The stored diagnostic has the old source manager in it; update
1182 // the locations to refer into the new source manager. Since we've
1183 // been careful to make sure that the source manager's state
1184 // before and after are identical, so that we can reuse the source
1185 // location itself.
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +00001186 checkAndSanitizeDiags(StoredDiagnostics, getSourceManager());
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001187
1188 // Keep track of the override buffer;
Rafael Espindola32482082014-08-18 16:23:45 +00001189 SavedMainFileBuffer = std::move(OverrideMainBuffer);
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001190 }
Ahmed Charlesb8984322014-03-07 20:03:18 +00001191
1192 std::unique_ptr<TopLevelDeclTrackerAction> Act(
1193 new TopLevelDeclTrackerAction(*this));
1194
Ted Kremenek022a4902011-03-22 01:15:24 +00001195 // Recover resources if we crash before exiting this method.
1196 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1197 ActCleanup(Act.get());
1198
Douglas Gregor32fbe312012-01-20 16:28:04 +00001199 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0]))
Daniel Dunbar764c0822009-12-01 09:51:01 +00001200 goto error;
Douglas Gregor925296b2011-07-19 16:10:42 +00001201
Richard Smith26b8f782016-03-25 21:46:44 +00001202 if (SavedMainFileBuffer)
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001203 TranslateStoredDiagnostics(getFileManager(), getSourceManager(),
1204 PreambleDiagnostics, StoredDiagnostics);
Erik Verbruggenefe6fa52017-06-09 08:29:58 +00001205 else
1206 PreambleSrcLocCache.clear();
Douglas Gregor925296b2011-07-19 16:10:42 +00001207
JF Bastien0e828952019-06-26 19:50:12 +00001208 if (llvm::Error Err = Act->Execute()) {
1209 consumeError(std::move(Err)); // FIXME this drops errors on the floor.
Argyrios Kyrtzidis1416e172012-06-08 05:48:06 +00001210 goto error;
JF Bastien0e828952019-06-26 19:50:12 +00001211 }
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001212
1213 transferASTDataFromCompilerInstance(*Clang);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001214
Daniel Dunbar644dca02009-12-04 08:17:33 +00001215 Act->EndSourceFile();
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001216
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001217 FailedParseDiagnostics.clear();
1218
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001219 return false;
Ted Kremenek5e14d392011-03-21 18:40:17 +00001220
Daniel Dunbar764c0822009-12-01 09:51:01 +00001221error:
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001222 // Remove the overridden buffer we used for the preamble.
Rafael Espindola32482082014-08-18 16:23:45 +00001223 SavedMainFileBuffer = nullptr;
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001224
1225 // Keep the ownership of the data in the ASTUnit because the client may
1226 // want to see the diagnostics.
1227 transferASTDataFromCompilerInstance(*Clang);
1228 FailedParseDiagnostics.swap(StoredDiagnostics);
Douglas Gregorefc46952010-10-12 16:25:54 +00001229 StoredDiagnostics.clear();
Argyrios Kyrtzidis067cbfa2011-10-24 17:25:20 +00001230 NumStoredDiagnosticsFromDriver = 0;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001231 return true;
1232}
1233
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001234static std::pair<unsigned, unsigned>
1235makeStandaloneRange(CharSourceRange Range, const SourceManager &SM,
1236 const LangOptions &LangOpts) {
1237 CharSourceRange FileRange = Lexer::makeFileCharRange(Range, SM, LangOpts);
1238 unsigned Offset = SM.getFileOffset(FileRange.getBegin());
1239 unsigned EndOffset = SM.getFileOffset(FileRange.getEnd());
1240 return std::make_pair(Offset, EndOffset);
1241}
1242
Benjamin Kramer1a6e0a92014-10-03 18:52:54 +00001243static ASTUnit::StandaloneFixIt makeStandaloneFixIt(const SourceManager &SM,
1244 const LangOptions &LangOpts,
1245 const FixItHint &InFix) {
1246 ASTUnit::StandaloneFixIt OutFix;
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001247 OutFix.RemoveRange = makeStandaloneRange(InFix.RemoveRange, SM, LangOpts);
1248 OutFix.InsertFromRange = makeStandaloneRange(InFix.InsertFromRange, SM,
1249 LangOpts);
1250 OutFix.CodeToInsert = InFix.CodeToInsert;
1251 OutFix.BeforePreviousInsertions = InFix.BeforePreviousInsertions;
Benjamin Kramer1a6e0a92014-10-03 18:52:54 +00001252 return OutFix;
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001253}
1254
Benjamin Kramer1a6e0a92014-10-03 18:52:54 +00001255static ASTUnit::StandaloneDiagnostic
1256makeStandaloneDiagnostic(const LangOptions &LangOpts,
1257 const StoredDiagnostic &InDiag) {
1258 ASTUnit::StandaloneDiagnostic OutDiag;
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001259 OutDiag.ID = InDiag.getID();
1260 OutDiag.Level = InDiag.getLevel();
1261 OutDiag.Message = InDiag.getMessage();
1262 OutDiag.LocOffset = 0;
1263 if (InDiag.getLocation().isInvalid())
Benjamin Kramer1a6e0a92014-10-03 18:52:54 +00001264 return OutDiag;
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001265 const SourceManager &SM = InDiag.getLocation().getManager();
1266 SourceLocation FileLoc = SM.getFileLoc(InDiag.getLocation());
1267 OutDiag.Filename = SM.getFilename(FileLoc);
1268 if (OutDiag.Filename.empty())
Benjamin Kramer1a6e0a92014-10-03 18:52:54 +00001269 return OutDiag;
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001270 OutDiag.LocOffset = SM.getFileOffset(FileLoc);
Eugene Zelenko4f233182018-03-22 00:53:26 +00001271 for (const auto &Range : InDiag.getRanges())
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00001272 OutDiag.Ranges.push_back(makeStandaloneRange(Range, SM, LangOpts));
Eugene Zelenko4f233182018-03-22 00:53:26 +00001273 for (const auto &FixIt : InDiag.getFixIts())
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00001274 OutDiag.FixIts.push_back(makeStandaloneFixIt(SM, LangOpts, FixIt));
Benjamin Kramer1a6e0a92014-10-03 18:52:54 +00001275
1276 return OutDiag;
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001277}
1278
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001279/// Attempt to build or re-use a precompiled preamble when (re-)parsing
Douglas Gregor4dde7492010-07-23 23:58:40 +00001280/// the source file.
1281///
1282/// This routine will compute the preamble of the main source file. If a
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001283/// non-trivial preamble is found, it will precompile that preamble into a
Douglas Gregor4dde7492010-07-23 23:58:40 +00001284/// precompiled header so that the precompiled preamble can be used to reduce
1285/// reparsing time. If a precompiled preamble has already been constructed,
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001286/// this routine will determine if it is still valid and, if so, avoid
Douglas Gregor4dde7492010-07-23 23:58:40 +00001287/// rebuilding the precompiled preamble.
1288///
Douglas Gregor028d3e42010-08-09 20:45:32 +00001289/// \param AllowRebuild When true (the default), this routine is
1290/// allowed to rebuild the precompiled preamble if it is found to be
1291/// out-of-date.
1292///
1293/// \param MaxLines When non-zero, the maximum number of lines that
1294/// can occur within the preamble.
1295///
Douglas Gregor6481ef12010-07-24 00:38:13 +00001296/// \returns If the precompiled preamble can be used, returns a newly-allocated
1297/// buffer that should be used in place of the main file when doing so.
1298/// Otherwise, returns a NULL pointer.
Ivan Donchevskiif70d28b2018-05-17 09:15:22 +00001299std::unique_ptr<llvm::MemoryBuffer>
1300ASTUnit::getMainBufferWithPrecompiledPreamble(
1301 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
Ivan Donchevskii6e895282018-05-17 09:24:37 +00001302 CompilerInvocation &PreambleInvocationIn,
Jonas Devliegherefc514902018-10-10 13:27:25 +00001303 IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS, bool AllowRebuild,
Ivan Donchevskiif70d28b2018-05-17 09:15:22 +00001304 unsigned MaxLines) {
1305 auto MainFilePath =
Ilya Biryukov200b3282017-06-21 10:24:58 +00001306 PreambleInvocationIn.getFrontendOpts().Inputs[0].getFile();
1307 std::unique_ptr<llvm::MemoryBuffer> MainFileBuffer =
1308 getBufferForFileHandlingRemapping(PreambleInvocationIn, VFS.get(),
Ivan Donchevskii2ebe3a02018-06-06 07:17:26 +00001309 MainFilePath, UserFilesAreVolatile);
Ilya Biryukov200b3282017-06-21 10:24:58 +00001310 if (!MainFileBuffer)
Craig Topper49a27902014-05-22 04:46:25 +00001311 return nullptr;
Douglas Gregord9a30af2010-08-02 20:51:39 +00001312
Ilya Biryukov200b3282017-06-21 10:24:58 +00001313 PreambleBounds Bounds =
1314 ComputePreambleBounds(*PreambleInvocationIn.getLangOpts(),
1315 MainFileBuffer.get(), MaxLines);
1316 if (!Bounds.Size)
1317 return nullptr;
Alp Toker1b070d22014-07-07 07:47:20 +00001318
Ilya Biryukov200b3282017-06-21 10:24:58 +00001319 if (Preamble) {
1320 if (Preamble->CanReuse(PreambleInvocationIn, MainFileBuffer.get(), Bounds,
1321 VFS.get())) {
1322 // Okay! We can re-use the precompiled preamble.
Rafael Espindolae4777f42013-07-29 18:22:23 +00001323
Ilya Biryukov200b3282017-06-21 10:24:58 +00001324 // Set the state of the diagnostic object to mimic its state
1325 // after parsing the preamble.
1326 getDiagnostics().Reset();
1327 ProcessWarningOptions(getDiagnostics(),
1328 PreambleInvocationIn.getDiagnosticOpts());
1329 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
Alp Toker1b070d22014-07-07 07:47:20 +00001330
Nikolai Kosjar295c19e2019-05-21 07:26:59 +00001331 PreambleRebuildCountdown = 1;
Ilya Biryukov200b3282017-06-21 10:24:58 +00001332 return MainFileBuffer;
1333 } else {
1334 Preamble.reset();
1335 PreambleDiagnostics.clear();
1336 TopLevelDeclsInPreamble.clear();
Alex Lorenza44c4322018-03-12 19:36:29 +00001337 PreambleSrcLocCache.clear();
Nikolai Kosjar295c19e2019-05-21 07:26:59 +00001338 PreambleRebuildCountdown = 1;
Douglas Gregor4dde7492010-07-23 23:58:40 +00001339 }
Douglas Gregor028d3e42010-08-09 20:45:32 +00001340 }
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001341
1342 // If the preamble rebuild counter > 1, it's because we previously
1343 // failed to build a preamble and we're not yet ready to try
1344 // again. Decrement the counter and return a failure.
Nikolai Kosjar295c19e2019-05-21 07:26:59 +00001345 if (PreambleRebuildCountdown > 1) {
1346 --PreambleRebuildCountdown;
Craig Topper49a27902014-05-22 04:46:25 +00001347 return nullptr;
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001348 }
1349
Ilya Biryukov200b3282017-06-21 10:24:58 +00001350 assert(!Preamble && "No Preamble should be stored at that point");
1351 // If we aren't allowed to rebuild the precompiled preamble, just
1352 // return now.
1353 if (!AllowRebuild)
Ben Langmuir8832c062014-04-15 18:16:25 +00001354 return nullptr;
1355
Nikolai Kosjar295c19e2019-05-21 07:26:59 +00001356 ++PreambleCounter;
1357
Ilya Biryukov200b3282017-06-21 10:24:58 +00001358 SmallVector<StandaloneDiagnostic, 4> NewPreambleDiagsStandalone;
1359 SmallVector<StoredDiagnostic, 4> NewPreambleDiags;
Ilya Biryukovf81d46f2017-06-21 12:34:27 +00001360 ASTUnitPreambleCallbacks Callbacks;
Ilya Biryukov200b3282017-06-21 10:24:58 +00001361 {
1362 llvm::Optional<CaptureDroppedDiagnostics> Capture;
Nikolai Kosjar8edd8da2019-06-11 14:14:24 +00001363 if (CaptureDiagnostics != CaptureDiagsKind::None)
1364 Capture.emplace(CaptureDiagnostics, *Diagnostics, &NewPreambleDiags,
Ilya Biryukov200b3282017-06-21 10:24:58 +00001365 &NewPreambleDiagsStandalone);
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001366
Ilya Biryukov200b3282017-06-21 10:24:58 +00001367 // We did not previously compute a preamble, or it can't be reused anyway.
Ivan Donchevskiif70d28b2018-05-17 09:15:22 +00001368 SimpleTimer PreambleTimer(WantTiming);
1369 PreambleTimer.setOutput("Precompiling preamble");
1370
Ivan Donchevskii6e895282018-05-17 09:24:37 +00001371 const bool PreviousSkipFunctionBodies =
1372 PreambleInvocationIn.getFrontendOpts().SkipFunctionBodies;
1373 if (SkipFunctionBodies == SkipFunctionBodiesScope::Preamble)
1374 PreambleInvocationIn.getFrontendOpts().SkipFunctionBodies = true;
1375
Ivan Donchevskiif70d28b2018-05-17 09:15:22 +00001376 llvm::ErrorOr<PrecompiledPreamble> NewPreamble = PrecompiledPreamble::Build(
1377 PreambleInvocationIn, MainFileBuffer.get(), Bounds, *Diagnostics, VFS,
1378 PCHContainerOps, /*StoreInMemory=*/false, Callbacks);
Ivan Donchevskii6e895282018-05-17 09:24:37 +00001379
1380 PreambleInvocationIn.getFrontendOpts().SkipFunctionBodies =
1381 PreviousSkipFunctionBodies;
1382
Ivan Donchevskiif70d28b2018-05-17 09:15:22 +00001383 if (NewPreamble) {
1384 Preamble = std::move(*NewPreamble);
Nikolai Kosjar295c19e2019-05-21 07:26:59 +00001385 PreambleRebuildCountdown = 1;
Dmitri Gribenko47652522013-12-20 00:16:25 +00001386 } else {
Ilya Biryukov200b3282017-06-21 10:24:58 +00001387 switch (static_cast<BuildPreambleError>(NewPreamble.getError().value())) {
1388 case BuildPreambleError::CouldntCreateTempFile:
Ilya Biryukov200b3282017-06-21 10:24:58 +00001389 // Try again next time.
Nikolai Kosjar295c19e2019-05-21 07:26:59 +00001390 PreambleRebuildCountdown = 1;
Ilya Biryukovf81d46f2017-06-21 12:34:27 +00001391 return nullptr;
Ilya Biryukov200b3282017-06-21 10:24:58 +00001392 case BuildPreambleError::CouldntCreateTargetInfo:
1393 case BuildPreambleError::BeginSourceFileFailed:
1394 case BuildPreambleError::CouldntEmitPCH:
Ilya Biryukov29175262019-05-22 12:50:01 +00001395 case BuildPreambleError::BadInputs:
Ilya Biryukov200b3282017-06-21 10:24:58 +00001396 // These erros are more likely to repeat, retry after some period.
Nikolai Kosjar295c19e2019-05-21 07:26:59 +00001397 PreambleRebuildCountdown = DefaultPreambleRebuildInterval;
Ilya Biryukovf81d46f2017-06-21 12:34:27 +00001398 return nullptr;
Ilya Biryukov200b3282017-06-21 10:24:58 +00001399 }
Ilya Biryukovf81d46f2017-06-21 12:34:27 +00001400 llvm_unreachable("unexpected BuildPreambleError");
Dmitri Gribenko47652522013-12-20 00:16:25 +00001401 }
Douglas Gregor0e119552010-07-31 00:40:00 +00001402 }
Ben Langmuir33c80902014-06-30 20:04:14 +00001403
Ilya Biryukov200b3282017-06-21 10:24:58 +00001404 assert(Preamble && "Preamble wasn't built");
1405
1406 TopLevelDecls.clear();
1407 TopLevelDeclsInPreamble = Callbacks.takeTopLevelDeclIDs();
1408 PreambleTopLevelHashValue = Callbacks.getHash();
1409
1410 NumWarningsInPreamble = getDiagnostics().getNumWarnings();
1411
1412 checkAndRemoveNonDriverDiags(NewPreambleDiags);
1413 StoredDiagnostics = std::move(NewPreambleDiags);
1414 PreambleDiagnostics = std::move(NewPreambleDiagsStandalone);
Alp Toker1b070d22014-07-07 07:47:20 +00001415
Douglas Gregordf7a79a2011-02-16 18:16:54 +00001416 // If the hash of top-level entities differs from the hash of the top-level
1417 // entities the last time we rebuilt the preamble, clear out the completion
1418 // cache.
1419 if (CurrentTopLevelHashValue != PreambleTopLevelHashValue) {
1420 CompletionCacheTopLevelHashValue = 0;
1421 PreambleTopLevelHashValue = CurrentTopLevelHashValue;
1422 }
Rafael Espindola2346a372014-08-18 18:47:08 +00001423
Ilya Biryukov200b3282017-06-21 10:24:58 +00001424 return MainFileBuffer;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001425}
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001426
Douglas Gregore9db88f2010-08-03 19:06:41 +00001427void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
Ilya Biryukov200b3282017-06-21 10:24:58 +00001428 assert(Preamble && "Should only be called when preamble was built");
1429
Douglas Gregore9db88f2010-08-03 19:06:41 +00001430 std::vector<Decl *> Resolved;
1431 Resolved.reserve(TopLevelDeclsInPreamble.size());
1432 ExternalASTSource &Source = *getASTContext().getExternalSource();
Eugene Zelenko4f233182018-03-22 00:53:26 +00001433 for (const auto TopLevelDecl : TopLevelDeclsInPreamble) {
Douglas Gregore9db88f2010-08-03 19:06:41 +00001434 // Resolve the declaration ID to an actual declaration, possibly
1435 // deserializing the declaration in the process.
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00001436 if (Decl *D = Source.GetExternalDecl(TopLevelDecl))
Douglas Gregore9db88f2010-08-03 19:06:41 +00001437 Resolved.push_back(D);
1438 }
1439 TopLevelDeclsInPreamble.clear();
1440 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1441}
1442
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001443void ASTUnit::transferASTDataFromCompilerInstance(CompilerInstance &CI) {
Ben Langmuir749323f2014-04-22 17:40:12 +00001444 // Steal the created target, context, and preprocessor if they have been
1445 // created.
1446 assert(CI.hasInvocation() && "missing invocation");
Alp Toker269d8402014-07-06 05:26:07 +00001447 LangOpts = CI.getInvocation().LangOpts;
David Blaikieec99b5e2014-08-10 19:14:48 +00001448 TheSema = CI.takeSema();
David Blaikie6beb6aa2014-08-10 19:56:51 +00001449 Consumer = CI.takeASTConsumer();
Ben Langmuir532fdc02014-04-18 20:39:48 +00001450 if (CI.hasASTContext())
1451 Ctx = &CI.getASTContext();
1452 if (CI.hasPreprocessor())
David Blaikie41565462017-01-05 19:48:07 +00001453 PP = CI.getPreprocessorPtr();
Craig Topper49a27902014-05-22 04:46:25 +00001454 CI.setSourceManager(nullptr);
1455 CI.setFileManager(nullptr);
Ben Langmuir532fdc02014-04-18 20:39:48 +00001456 if (CI.hasTarget())
1457 Target = &CI.getTarget();
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001458 Reader = CI.getModuleManager();
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00001459 HadModuleLoaderFatalFailure = CI.hadModuleLoaderFatalFailure();
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001460}
1461
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001462StringRef ASTUnit::getMainFileName() const {
Argyrios Kyrtzidis928e1fd2013-01-11 22:11:14 +00001463 if (Invocation && !Invocation->getFrontendOpts().Inputs.empty()) {
1464 const FrontendInputFile &Input = Invocation->getFrontendOpts().Inputs[0];
1465 if (Input.isFile())
1466 return Input.getFile();
1467 else
1468 return Input.getBuffer()->getBufferIdentifier();
1469 }
1470
1471 if (SourceMgr) {
1472 if (const FileEntry *
1473 FE = SourceMgr->getFileEntryForID(SourceMgr->getMainFileID()))
1474 return FE->getName();
1475 }
1476
Eugene Zelenko4f233182018-03-22 00:53:26 +00001477 return {};
Douglas Gregor16896c42010-10-28 15:44:59 +00001478}
1479
Argyrios Kyrtzidis37f2ab42013-03-05 20:21:14 +00001480StringRef ASTUnit::getASTFileName() const {
1481 if (!isMainFileAST())
Eugene Zelenko4f233182018-03-22 00:53:26 +00001482 return {};
Argyrios Kyrtzidis37f2ab42013-03-05 20:21:14 +00001483
1484 serialization::ModuleFile &
1485 Mod = Reader->getModuleManager().getPrimaryModule();
1486 return Mod.FileName;
1487}
1488
David Blaikieea4395e2017-01-06 19:49:01 +00001489std::unique_ptr<ASTUnit>
1490ASTUnit::create(std::shared_ptr<CompilerInvocation> CI,
1491 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Nikolai Kosjar8edd8da2019-06-11 14:14:24 +00001492 CaptureDiagsKind CaptureDiagnostics,
1493 bool UserFilesAreVolatile) {
David Blaikieea4395e2017-01-06 19:49:01 +00001494 std::unique_ptr<ASTUnit> AST(new ASTUnit(false));
Justin Bognerdbbcb112014-10-14 23:36:06 +00001495 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
Jonas Devliegherefc514902018-10-10 13:27:25 +00001496 IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS =
Ben Langmuir8832c062014-04-15 18:16:25 +00001497 createVFSFromCompilerInvocation(*CI, *Diags);
David Blaikieea4395e2017-01-06 19:49:01 +00001498 AST->Diagnostics = Diags;
1499 AST->FileSystemOpts = CI->getFileSystemOpts();
1500 AST->Invocation = std::move(CI);
Ben Langmuir8832c062014-04-15 18:16:25 +00001501 AST->FileMgr = new FileManager(AST->FileSystemOpts, VFS);
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +00001502 AST->UserFilesAreVolatile = UserFilesAreVolatile;
1503 AST->SourceMgr = new SourceManager(AST->getDiagnostics(), *AST->FileMgr,
1504 UserFilesAreVolatile);
Duncan P. N. Exon Smith8bef5cd2019-03-09 17:33:56 +00001505 AST->ModuleCache = new InMemoryModuleCache;
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00001506
David Blaikieea4395e2017-01-06 19:49:01 +00001507 return AST;
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00001508}
1509
Ahmed Charlesb8984322014-03-07 20:03:18 +00001510ASTUnit *ASTUnit::LoadFromCompilerInvocationAction(
David Blaikieea4395e2017-01-06 19:49:01 +00001511 std::shared_ptr<CompilerInvocation> CI,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001512 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
Argyrios Kyrtzidisc382abf2016-02-09 19:07:13 +00001513 IntrusiveRefCntPtr<DiagnosticsEngine> Diags, FrontendAction *Action,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001514 ASTUnit *Unit, bool Persistent, StringRef ResourceFilesPath,
Nikolai Kosjar8edd8da2019-06-11 14:14:24 +00001515 bool OnlyLocalDecls, CaptureDiagsKind CaptureDiagnostics,
Benjamin Kramer5c248d82015-12-15 09:30:31 +00001516 unsigned PrecompilePreambleAfterNParses, bool CacheCodeCompletionResults,
1517 bool IncludeBriefCommentsInCodeCompletion, bool UserFilesAreVolatile,
1518 std::unique_ptr<ASTUnit> *ErrAST) {
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001519 assert(CI && "A CompilerInvocation is required");
1520
Ahmed Charlesb8984322014-03-07 20:03:18 +00001521 std::unique_ptr<ASTUnit> OwnAST;
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001522 ASTUnit *AST = Unit;
1523 if (!AST) {
1524 // Create the AST unit.
David Blaikieea4395e2017-01-06 19:49:01 +00001525 OwnAST = create(CI, Diags, CaptureDiagnostics, UserFilesAreVolatile);
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001526 AST = OwnAST.get();
Ben Langmuir8832c062014-04-15 18:16:25 +00001527 if (!AST)
1528 return nullptr;
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001529 }
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001530
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00001531 if (!ResourceFilesPath.empty()) {
1532 // Override the resources path.
1533 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
1534 }
1535 AST->OnlyLocalDecls = OnlyLocalDecls;
1536 AST->CaptureDiagnostics = CaptureDiagnostics;
Benjamin Kramer5c248d82015-12-15 09:30:31 +00001537 if (PrecompilePreambleAfterNParses > 0)
Nikolai Kosjar295c19e2019-05-21 07:26:59 +00001538 AST->PreambleRebuildCountdown = PrecompilePreambleAfterNParses;
Douglas Gregor69f74f82011-08-25 22:30:56 +00001539 AST->TUKind = Action ? Action->getTranslationUnitKind() : TU_Complete;
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00001540 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenko3292d062012-07-02 17:35:10 +00001541 AST->IncludeBriefCommentsInCodeCompletion
1542 = IncludeBriefCommentsInCodeCompletion;
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001543
1544 // Recover resources if we crash before exiting this method.
1545 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001546 ASTUnitCleanup(OwnAST.get());
David Blaikie9c902b52011-09-25 23:23:43 +00001547 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
Eugene Zelenko4f233182018-03-22 00:53:26 +00001548 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine>>
Alp Tokerf994cef2014-07-05 03:08:06 +00001549 DiagCleanup(Diags.get());
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001550
1551 // We'll manage file buffers ourselves.
1552 CI->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1553 CI->getFrontendOpts().DisableFree = false;
1554 ProcessWarningOptions(AST->getDiagnostics(), CI->getDiagnosticOpts());
1555
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001556 // Create the compiler instance to use for building the AST.
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001557 std::unique_ptr<CompilerInstance> Clang(
Benjamin Kramerd6da1a02016-06-12 20:05:23 +00001558 new CompilerInstance(std::move(PCHContainerOps)));
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001559
1560 // Recover resources if we crash before exiting this method.
1561 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1562 CICleanup(Clang.get());
1563
David Blaikieea4395e2017-01-06 19:49:01 +00001564 Clang->setInvocation(std::move(CI));
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001565 AST->OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001566
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001567 // Set up diagnostics, capturing any diagnostics that would
1568 // otherwise be dropped.
1569 Clang->setDiagnostics(&AST->getDiagnostics());
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001570
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001571 // Create the target instance.
Alp Toker80758082014-07-06 05:26:44 +00001572 Clang->setTarget(TargetInfo::CreateTargetInfo(
Saleem Abdulrasool10a49722016-04-08 16:52:00 +00001573 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001574 if (!Clang->hasTarget())
Craig Topper49a27902014-05-22 04:46:25 +00001575 return nullptr;
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001576
1577 // Inform the target of the language options.
1578 //
1579 // FIXME: We shouldn't need to do this, the target should be immutable once
1580 // created. This complexity should be lifted elsewhere.
Alp Toker74437972014-07-06 05:14:24 +00001581 Clang->getTarget().adjust(Clang->getLangOpts());
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001582
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001583 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1584 "Invocation must have exactly one source file!");
Richard Smith40c0efa2017-04-26 18:57:40 +00001585 assert(Clang->getFrontendOpts().Inputs[0].getKind().getFormat() ==
1586 InputKind::Source &&
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001587 "FIXME: AST inputs not yet supported here!");
Richard Smith40c0efa2017-04-26 18:57:40 +00001588 assert(Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() !=
1589 InputKind::LLVM_IR &&
1590 "IR inputs not support here!");
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001591
1592 // Configure the various subsystems.
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001593 AST->TheSema.reset();
Craig Topper49a27902014-05-22 04:46:25 +00001594 AST->Ctx = nullptr;
1595 AST->PP = nullptr;
1596 AST->Reader = nullptr;
1597
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001598 // Create a file manager object to provide access to and cache the filesystem.
1599 Clang->setFileManager(&AST->getFileManager());
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001600
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001601 // Create the source manager.
1602 Clang->setSourceManager(&AST->getSourceManager());
1603
Argyrios Kyrtzidisc382abf2016-02-09 19:07:13 +00001604 FrontendAction *Act = Action;
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001605
Ahmed Charlesb8984322014-03-07 20:03:18 +00001606 std::unique_ptr<TopLevelDeclTrackerAction> TrackerAct;
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001607 if (!Act) {
1608 TrackerAct.reset(new TopLevelDeclTrackerAction(*AST));
1609 Act = TrackerAct.get();
1610 }
1611
1612 // Recover resources if we crash before exiting this method.
1613 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1614 ActCleanup(TrackerAct.get());
1615
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001616 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
1617 AST->transferASTDataFromCompilerInstance(*Clang);
1618 if (OwnAST && ErrAST)
1619 ErrAST->swap(OwnAST);
1620
Craig Topper49a27902014-05-22 04:46:25 +00001621 return nullptr;
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001622 }
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00001623
1624 if (Persistent && !TrackerAct) {
1625 Clang->getPreprocessor().addPPCallbacks(
Craig Topperb8a70532014-09-10 04:53:53 +00001626 llvm::make_unique<MacroDefinitionTrackerPPCallbacks>(
1627 AST->getCurrentTopLevelHashValue()));
David Blaikie6beb6aa2014-08-10 19:56:51 +00001628 std::vector<std::unique_ptr<ASTConsumer>> Consumers;
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00001629 if (Clang->hasASTConsumer())
1630 Consumers.push_back(Clang->takeASTConsumer());
David Blaikie6beb6aa2014-08-10 19:56:51 +00001631 Consumers.push_back(llvm::make_unique<TopLevelDeclTrackerConsumer>(
1632 *AST, AST->getCurrentTopLevelHashValue()));
1633 Clang->setASTConsumer(
1634 llvm::make_unique<MultiplexConsumer>(std::move(Consumers)));
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00001635 }
JF Bastien0e828952019-06-26 19:50:12 +00001636 if (llvm::Error Err = Act->Execute()) {
1637 consumeError(std::move(Err)); // FIXME this drops errors on the floor.
Argyrios Kyrtzidis1416e172012-06-08 05:48:06 +00001638 AST->transferASTDataFromCompilerInstance(*Clang);
1639 if (OwnAST && ErrAST)
1640 ErrAST->swap(OwnAST);
1641
Craig Topper49a27902014-05-22 04:46:25 +00001642 return nullptr;
Argyrios Kyrtzidis1416e172012-06-08 05:48:06 +00001643 }
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001644
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001645 // Steal the created target, context, and preprocessor.
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001646 AST->transferASTDataFromCompilerInstance(*Clang);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001647
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001648 Act->EndSourceFile();
1649
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001650 if (OwnAST)
Ahmed Charles9a16beb2014-03-07 19:33:25 +00001651 return OwnAST.release();
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001652 else
1653 return AST;
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001654}
1655
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001656bool ASTUnit::LoadFromCompilerInvocation(
1657 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001658 unsigned PrecompilePreambleAfterNParses,
Jonas Devliegherefc514902018-10-10 13:27:25 +00001659 IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS) {
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001660 if (!Invocation)
1661 return true;
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001662
1663 assert(VFS && "VFS is null");
1664
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001665 // We'll manage file buffers ourselves.
1666 Invocation->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1667 Invocation->getFrontendOpts().DisableFree = false;
Benjamin Kramer8de9c9b2017-01-18 16:25:48 +00001668 getDiagnostics().Reset();
Douglas Gregor345c1bc2011-01-19 01:02:47 +00001669 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001670
Rafael Espindola32482082014-08-18 16:23:45 +00001671 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
Benjamin Kramer5c248d82015-12-15 09:30:31 +00001672 if (PrecompilePreambleAfterNParses > 0) {
Nikolai Kosjar295c19e2019-05-21 07:26:59 +00001673 PreambleRebuildCountdown = PrecompilePreambleAfterNParses;
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001674 OverrideMainBuffer =
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001675 getMainBufferWithPrecompiledPreamble(PCHContainerOps, *Invocation, VFS);
Benjamin Kramer8484a322017-02-13 16:16:43 +00001676 getDiagnostics().Reset();
1677 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001678 }
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001679
Douglas Gregor16896c42010-10-28 15:44:59 +00001680 SimpleTimer ParsingTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00001681 ParsingTimer.setOutput("Parsing " + getMainFileName());
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001682
Ted Kremenek022a4902011-03-22 01:15:24 +00001683 // Recover resources if we crash before exiting this method.
1684 llvm::CrashRecoveryContextCleanupRegistrar<llvm::MemoryBuffer>
Rafael Espindola32482082014-08-18 16:23:45 +00001685 MemBufferCleanup(OverrideMainBuffer.get());
1686
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001687 return Parse(std::move(PCHContainerOps), std::move(OverrideMainBuffer), VFS);
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001688}
1689
David Blaikie103a2de2014-04-25 17:01:33 +00001690std::unique_ptr<ASTUnit> ASTUnit::LoadFromCompilerInvocation(
David Blaikieea4395e2017-01-06 19:49:01 +00001691 std::shared_ptr<CompilerInvocation> CI,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001692 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
Benjamin Kramerbc632902015-10-06 14:45:20 +00001693 IntrusiveRefCntPtr<DiagnosticsEngine> Diags, FileManager *FileMgr,
Nikolai Kosjar8edd8da2019-06-11 14:14:24 +00001694 bool OnlyLocalDecls, CaptureDiagsKind CaptureDiagnostics,
Benjamin Kramer5c248d82015-12-15 09:30:31 +00001695 unsigned PrecompilePreambleAfterNParses, TranslationUnitKind TUKind,
1696 bool CacheCodeCompletionResults, bool IncludeBriefCommentsInCodeCompletion,
1697 bool UserFilesAreVolatile) {
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001698 // Create the AST unit.
David Blaikie103a2de2014-04-25 17:01:33 +00001699 std::unique_ptr<ASTUnit> AST(new ASTUnit(false));
Justin Bognerdbbcb112014-10-14 23:36:06 +00001700 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001701 AST->Diagnostics = Diags;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001702 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001703 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor69f74f82011-08-25 22:30:56 +00001704 AST->TUKind = TUKind;
Douglas Gregorb14904c2010-08-13 22:48:40 +00001705 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenko3292d062012-07-02 17:35:10 +00001706 AST->IncludeBriefCommentsInCodeCompletion
1707 = IncludeBriefCommentsInCodeCompletion;
David Blaikieea4395e2017-01-06 19:49:01 +00001708 AST->Invocation = std::move(CI);
Benjamin Kramerbc632902015-10-06 14:45:20 +00001709 AST->FileSystemOpts = FileMgr->getFileSystemOpts();
1710 AST->FileMgr = FileMgr;
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +00001711 AST->UserFilesAreVolatile = UserFilesAreVolatile;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001712
Ted Kremenek4422bfe2011-03-18 02:06:56 +00001713 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00001714 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1715 ASTUnitCleanup(AST.get());
David Blaikie9c902b52011-09-25 23:23:43 +00001716 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
Eugene Zelenko4f233182018-03-22 00:53:26 +00001717 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine>>
Alp Tokerf994cef2014-07-05 03:08:06 +00001718 DiagCleanup(Diags.get());
Ted Kremenek4422bfe2011-03-18 02:06:56 +00001719
Benjamin Kramerd6da1a02016-06-12 20:05:23 +00001720 if (AST->LoadFromCompilerInvocation(std::move(PCHContainerOps),
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001721 PrecompilePreambleAfterNParses,
Duncan P. N. Exon Smithdb8a7422019-03-26 22:32:06 +00001722 &AST->FileMgr->getVirtualFileSystem()))
David Blaikie103a2de2014-04-25 17:01:33 +00001723 return nullptr;
1724 return AST;
Daniel Dunbar764c0822009-12-01 09:51:01 +00001725}
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001726
Ahmed Charlesb8984322014-03-07 20:03:18 +00001727ASTUnit *ASTUnit::LoadFromCommandLine(
1728 const char **ArgBegin, const char **ArgEnd,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001729 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
Ahmed Charlesb8984322014-03-07 20:03:18 +00001730 IntrusiveRefCntPtr<DiagnosticsEngine> Diags, StringRef ResourceFilesPath,
Nikolai Kosjar8edd8da2019-06-11 14:14:24 +00001731 bool OnlyLocalDecls, CaptureDiagsKind CaptureDiagnostics,
Ivan Donchevskiif70d28b2018-05-17 09:15:22 +00001732 ArrayRef<RemappedFile> RemappedFiles, bool RemappedFilesKeepOriginalName,
1733 unsigned PrecompilePreambleAfterNParses, TranslationUnitKind TUKind,
1734 bool CacheCodeCompletionResults, bool IncludeBriefCommentsInCodeCompletion,
Ivan Donchevskii6e895282018-05-17 09:24:37 +00001735 bool AllowPCHWithCompilerErrors, SkipFunctionBodiesScope SkipFunctionBodies,
Ivan Donchevskiif70d28b2018-05-17 09:15:22 +00001736 bool SingleFileParse, bool UserFilesAreVolatile, bool ForSerialization,
1737 llvm::Optional<StringRef> ModuleFormat, std::unique_ptr<ASTUnit> *ErrAST,
Jonas Devliegherefc514902018-10-10 13:27:25 +00001738 IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS) {
Justin Bognerd512c1e2014-10-15 00:33:06 +00001739 assert(Diags.get() && "no DiagnosticsEngine was provided");
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001740
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001741 SmallVector<StoredDiagnostic, 4> StoredDiagnostics;
David Blaikieea4395e2017-01-06 19:49:01 +00001742
1743 std::shared_ptr<CompilerInvocation> CI;
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001744
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001745 {
Ilya Biryukov200b3282017-06-21 10:24:58 +00001746 CaptureDroppedDiagnostics Capture(CaptureDiagnostics, *Diags,
1747 &StoredDiagnostics, nullptr);
Daniel Dunbarfcf2d422010-01-25 00:44:02 +00001748
Eugene Zelenko4f233182018-03-22 00:53:26 +00001749 CI = createInvocationFromCommandLine(
Ilya Biryukovafdadf52017-06-28 15:06:34 +00001750 llvm::makeArrayRef(ArgBegin, ArgEnd), Diags, VFS);
Argyrios Kyrtzidisf606b822011-04-04 21:38:51 +00001751 if (!CI)
Craig Topper49a27902014-05-22 04:46:25 +00001752 return nullptr;
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001753 }
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001754
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001755 // Override any files that need remapping
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00001756 for (const auto &RemappedFile : RemappedFiles) {
1757 CI->getPreprocessorOpts().addRemappedFile(RemappedFile.first,
1758 RemappedFile.second);
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00001759 }
Argyrios Kyrtzidis4a280ff2012-03-07 01:51:17 +00001760 PreprocessorOptions &PPOpts = CI->getPreprocessorOpts();
1761 PPOpts.RemappedFilesKeepOriginalName = RemappedFilesKeepOriginalName;
1762 PPOpts.AllowPCHWithCompilerErrors = AllowPCHWithCompilerErrors;
Argyrios Kyrtzidis735e92c2017-06-09 01:20:48 +00001763 PPOpts.SingleFileParseMode = SingleFileParse;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001764
Ivan Donchevskiif70d28b2018-05-17 09:15:22 +00001765 // Override the resources path.
1766 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
1767
Ivan Donchevskii6e895282018-05-17 09:24:37 +00001768 CI->getFrontendOpts().SkipFunctionBodies =
1769 SkipFunctionBodies == SkipFunctionBodiesScope::PreambleAndMainFile;
Ivan Donchevskiif70d28b2018-05-17 09:15:22 +00001770
1771 if (ModuleFormat)
1772 CI->getHeaderSearchOpts().ModuleFormat = ModuleFormat.getValue();
Argyrios Kyrtzidisa3e2ff12015-11-20 03:36:21 +00001773
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001774 // Create the AST unit.
Ahmed Charlesb8984322014-03-07 20:03:18 +00001775 std::unique_ptr<ASTUnit> AST;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001776 AST.reset(new ASTUnit(false));
Ben Langmuir005c2e52018-03-23 17:37:27 +00001777 AST->NumStoredDiagnosticsFromDriver = StoredDiagnostics.size();
1778 AST->StoredDiagnostics.swap(StoredDiagnostics);
Justin Bognerdbbcb112014-10-14 23:36:06 +00001779 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001780 AST->Diagnostics = Diags;
Anders Carlssonc30dcec2011-03-18 18:22:40 +00001781 AST->FileSystemOpts = CI->getFileSystemOpts();
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001782 if (!VFS)
Jonas Devliegherefc514902018-10-10 13:27:25 +00001783 VFS = llvm::vfs::getRealFileSystem();
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001784 VFS = createVFSFromCompilerInvocation(*CI, *Diags, VFS);
Ben Langmuir8832c062014-04-15 18:16:25 +00001785 AST->FileMgr = new FileManager(AST->FileSystemOpts, VFS);
Duncan P. N. Exon Smith8bef5cd2019-03-09 17:33:56 +00001786 AST->ModuleCache = new InMemoryModuleCache;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001787 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001788 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor69f74f82011-08-25 22:30:56 +00001789 AST->TUKind = TUKind;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001790 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenko3292d062012-07-02 17:35:10 +00001791 AST->IncludeBriefCommentsInCodeCompletion
Ivan Donchevskiif70d28b2018-05-17 09:15:22 +00001792 = IncludeBriefCommentsInCodeCompletion;
1793 AST->UserFilesAreVolatile = UserFilesAreVolatile;
1794 AST->Invocation = CI;
Ivan Donchevskii6e895282018-05-17 09:24:37 +00001795 AST->SkipFunctionBodies = SkipFunctionBodies;
Ivan Donchevskiif70d28b2018-05-17 09:15:22 +00001796 if (ForSerialization)
Duncan P. N. Exon Smith8bef5cd2019-03-09 17:33:56 +00001797 AST->WriterData.reset(new ASTWriterData(*AST->ModuleCache));
Ivan Donchevskiif70d28b2018-05-17 09:15:22 +00001798 // Zero out now to ease cleanup during crash recovery.
Alexey Samsonovb4f99dd2014-08-28 23:51:01 +00001799 CI = nullptr;
1800 Diags = nullptr;
Craig Topper49a27902014-05-22 04:46:25 +00001801
Ted Kremenek4422bfe2011-03-18 02:06:56 +00001802 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00001803 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1804 ASTUnitCleanup(AST.get());
Ted Kremenek4422bfe2011-03-18 02:06:56 +00001805
Benjamin Kramerd6da1a02016-06-12 20:05:23 +00001806 if (AST->LoadFromCompilerInvocation(std::move(PCHContainerOps),
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001807 PrecompilePreambleAfterNParses,
1808 VFS)) {
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001809 // Some error occurred, if caller wants to examine diagnostics, pass it the
1810 // ASTUnit.
1811 if (ErrAST) {
1812 AST->StoredDiagnostics.swap(AST->FailedParseDiagnostics);
1813 ErrAST->swap(AST);
1814 }
Craig Topper49a27902014-05-22 04:46:25 +00001815 return nullptr;
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001816 }
1817
Ahmed Charles9a16beb2014-03-07 19:33:25 +00001818 return AST.release();
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001819}
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001820
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001821bool ASTUnit::Reparse(std::shared_ptr<PCHContainerOperations> PCHContainerOps,
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001822 ArrayRef<RemappedFile> RemappedFiles,
Jonas Devliegherefc514902018-10-10 13:27:25 +00001823 IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS) {
Ted Kremenek5e14d392011-03-21 18:40:17 +00001824 if (!Invocation)
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001825 return true;
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00001826
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001827 if (!VFS) {
1828 assert(FileMgr && "FileMgr is null on Reparse call");
Duncan P. N. Exon Smithdb8a7422019-03-26 22:32:06 +00001829 VFS = &FileMgr->getVirtualFileSystem();
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001830 }
1831
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00001832 clearFileLevelDecls();
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001833
Douglas Gregor16896c42010-10-28 15:44:59 +00001834 SimpleTimer ParsingTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00001835 ParsingTimer.setOutput("Reparsing " + getMainFileName());
Douglas Gregor16896c42010-10-28 15:44:59 +00001836
Douglas Gregor0e119552010-07-31 00:40:00 +00001837 // Remap files.
Douglas Gregor7b02b582010-08-20 00:02:33 +00001838 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
Alp Toker1b070d22014-07-07 07:47:20 +00001839 for (const auto &RB : PPOpts.RemappedFileBuffers)
1840 delete RB.second;
1841
Douglas Gregor0e119552010-07-31 00:40:00 +00001842 Invocation->getPreprocessorOpts().clearRemappedFiles();
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00001843 for (const auto &RemappedFile : RemappedFiles) {
1844 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFile.first,
1845 RemappedFile.second);
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00001846 }
Dmitri Gribenkoc444b572014-02-08 00:38:15 +00001847
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001848 // If we have a preamble file lying around, or if we might try to
1849 // build a precompiled preamble, do so now.
Rafael Espindola32482082014-08-18 16:23:45 +00001850 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
Nikolai Kosjar295c19e2019-05-21 07:26:59 +00001851 if (Preamble || PreambleRebuildCountdown > 0)
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001852 OverrideMainBuffer =
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001853 getMainBufferWithPrecompiledPreamble(PCHContainerOps, *Invocation, VFS);
1854
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001855 // Clear out the diagnostics state.
Benjamin Kramerbc632902015-10-06 14:45:20 +00001856 FileMgr.reset();
Argyrios Kyrtzidisf50f7b22011-11-03 20:28:19 +00001857 getDiagnostics().Reset();
1858 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Argyrios Kyrtzidis462ff352011-11-03 20:57:33 +00001859 if (OverrideMainBuffer)
1860 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
Argyrios Kyrtzidisf50f7b22011-11-03 20:28:19 +00001861
Douglas Gregor4dde7492010-07-23 23:58:40 +00001862 // Parse the sources
Benjamin Kramerd6da1a02016-06-12 20:05:23 +00001863 bool Result =
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001864 Parse(std::move(PCHContainerOps), std::move(OverrideMainBuffer), VFS);
Rafael Espindola32482082014-08-18 16:23:45 +00001865
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001866 // If we're caching global code-completion results, and the top-level
Argyrios Kyrtzidis36893372011-10-31 21:25:31 +00001867 // declarations have changed, clear out the code-completion cache.
1868 if (!Result && ShouldCacheCodeCompletionResults &&
1869 CurrentTopLevelHashValue != CompletionCacheTopLevelHashValue)
1870 CacheCodeCompletionResults();
Douglas Gregordf7a79a2011-02-16 18:16:54 +00001871
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00001872 // We now need to clear out the completion info related to this translation
1873 // unit; it'll be recreated if necessary.
1874 CCTUInfo.reset();
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001875
Douglas Gregor4dde7492010-07-23 23:58:40 +00001876 return Result;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001877}
Douglas Gregor8e984da2010-08-04 16:47:14 +00001878
Erik Verbruggen346066b2017-05-30 14:25:54 +00001879void ASTUnit::ResetForParse() {
1880 SavedMainFileBuffer.reset();
1881
1882 SourceMgr.reset();
1883 TheSema.reset();
1884 Ctx.reset();
1885 PP.reset();
1886 Reader.reset();
1887
1888 TopLevelDecls.clear();
1889 clearFileLevelDecls();
1890}
1891
Douglas Gregorb14904c2010-08-13 22:48:40 +00001892//----------------------------------------------------------------------------//
1893// Code completion
1894//----------------------------------------------------------------------------//
1895
1896namespace {
Eugene Zelenko4f233182018-03-22 00:53:26 +00001897
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001898 /// Code completion consumer that combines the cached code-completion
Douglas Gregorb14904c2010-08-13 22:48:40 +00001899 /// results from an ASTUnit with the code-completion results provided to it,
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001900 /// then passes the result on to
Douglas Gregorb14904c2010-08-13 22:48:40 +00001901 class AugmentedCodeCompleteConsumer : public CodeCompleteConsumer {
Richard Smith697cc9e2012-08-14 03:13:00 +00001902 uint64_t NormalContexts;
Douglas Gregorb14904c2010-08-13 22:48:40 +00001903 ASTUnit &AST;
1904 CodeCompleteConsumer &Next;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001905
Douglas Gregorb14904c2010-08-13 22:48:40 +00001906 public:
1907 AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next,
Dmitri Gribenko3292d062012-07-02 17:35:10 +00001908 const CodeCompleteOptions &CodeCompleteOpts)
Sam McCall3a753302019-04-18 17:35:55 +00001909 : CodeCompleteConsumer(CodeCompleteOpts), AST(AST), Next(Next) {
Douglas Gregorb14904c2010-08-13 22:48:40 +00001910 // Compute the set of contexts in which we will look when we don't have
1911 // any information about the specific context.
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001912 NormalContexts
Richard Smith697cc9e2012-08-14 03:13:00 +00001913 = (1LL << CodeCompletionContext::CCC_TopLevel)
1914 | (1LL << CodeCompletionContext::CCC_ObjCInterface)
1915 | (1LL << CodeCompletionContext::CCC_ObjCImplementation)
1916 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
1917 | (1LL << CodeCompletionContext::CCC_Statement)
1918 | (1LL << CodeCompletionContext::CCC_Expression)
1919 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
1920 | (1LL << CodeCompletionContext::CCC_DotMemberAccess)
1921 | (1LL << CodeCompletionContext::CCC_ArrowMemberAccess)
1922 | (1LL << CodeCompletionContext::CCC_ObjCPropertyAccess)
1923 | (1LL << CodeCompletionContext::CCC_ObjCProtocolName)
1924 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
1925 | (1LL << CodeCompletionContext::CCC_Recovery);
Douglas Gregor5e35d592010-09-14 23:59:36 +00001926
David Blaikiebbafb8a2012-03-11 07:00:24 +00001927 if (AST.getASTContext().getLangOpts().CPlusPlus)
Richard Smith697cc9e2012-08-14 03:13:00 +00001928 NormalContexts |= (1LL << CodeCompletionContext::CCC_EnumTag)
1929 | (1LL << CodeCompletionContext::CCC_UnionTag)
1930 | (1LL << CodeCompletionContext::CCC_ClassOrStructTag);
Douglas Gregorb14904c2010-08-13 22:48:40 +00001931 }
Craig Topperafa7cb32014-03-13 06:07:04 +00001932
1933 void ProcessCodeCompleteResults(Sema &S, CodeCompletionContext Context,
1934 CodeCompletionResult *Results,
1935 unsigned NumResults) override;
1936
1937 void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
1938 OverloadCandidate *Candidates,
Ilya Biryukov2fab2352018-08-30 13:08:03 +00001939 unsigned NumCandidates,
1940 SourceLocation OpenParLoc) override {
1941 Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates,
1942 OpenParLoc);
Douglas Gregorb14904c2010-08-13 22:48:40 +00001943 }
Craig Topperafa7cb32014-03-13 06:07:04 +00001944
1945 CodeCompletionAllocator &getAllocator() override {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001946 return Next.getAllocator();
1947 }
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00001948
Craig Topperafa7cb32014-03-13 06:07:04 +00001949 CodeCompletionTUInfo &getCodeCompletionTUInfo() override {
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00001950 return Next.getCodeCompletionTUInfo();
1951 }
Douglas Gregorb14904c2010-08-13 22:48:40 +00001952 };
Eugene Zelenko4f233182018-03-22 00:53:26 +00001953
1954} // namespace
Douglas Gregord46cf182010-08-16 20:01:48 +00001955
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001956/// Helper function that computes which global names are hidden by the
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001957/// local code-completion results.
Ted Kremenek6a153372010-11-07 06:11:36 +00001958static void CalculateHiddenNames(const CodeCompletionContext &Context,
1959 CodeCompletionResult *Results,
1960 unsigned NumResults,
1961 ASTContext &Ctx,
1962 llvm::StringSet<llvm::BumpPtrAllocator> &HiddenNames){
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001963 bool OnlyTagNames = false;
1964 switch (Context.getKind()) {
Douglas Gregor0ac41382010-09-23 23:01:17 +00001965 case CodeCompletionContext::CCC_Recovery:
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001966 case CodeCompletionContext::CCC_TopLevel:
1967 case CodeCompletionContext::CCC_ObjCInterface:
1968 case CodeCompletionContext::CCC_ObjCImplementation:
1969 case CodeCompletionContext::CCC_ObjCIvarList:
1970 case CodeCompletionContext::CCC_ClassStructUnion:
1971 case CodeCompletionContext::CCC_Statement:
1972 case CodeCompletionContext::CCC_Expression:
1973 case CodeCompletionContext::CCC_ObjCMessageReceiver:
Douglas Gregor21325842011-07-07 16:03:39 +00001974 case CodeCompletionContext::CCC_DotMemberAccess:
1975 case CodeCompletionContext::CCC_ArrowMemberAccess:
1976 case CodeCompletionContext::CCC_ObjCPropertyAccess:
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001977 case CodeCompletionContext::CCC_Namespace:
1978 case CodeCompletionContext::CCC_Type:
Kadir Cetinkayab006e092018-10-24 15:23:49 +00001979 case CodeCompletionContext::CCC_Symbol:
1980 case CodeCompletionContext::CCC_SymbolOrNewName:
Douglas Gregor5e35d592010-09-14 23:59:36 +00001981 case CodeCompletionContext::CCC_ParenthesizedExpression:
Douglas Gregor2c595ad2011-07-30 06:55:39 +00001982 case CodeCompletionContext::CCC_ObjCInterfaceName:
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001983 break;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001984
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001985 case CodeCompletionContext::CCC_EnumTag:
1986 case CodeCompletionContext::CCC_UnionTag:
1987 case CodeCompletionContext::CCC_ClassOrStructTag:
1988 OnlyTagNames = true;
1989 break;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001990
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001991 case CodeCompletionContext::CCC_ObjCProtocolName:
Douglas Gregor12785102010-08-24 20:21:13 +00001992 case CodeCompletionContext::CCC_MacroName:
1993 case CodeCompletionContext::CCC_MacroNameUse:
Douglas Gregorec00a262010-08-24 22:20:20 +00001994 case CodeCompletionContext::CCC_PreprocessorExpression:
Douglas Gregor0de55ce2010-08-25 18:41:16 +00001995 case CodeCompletionContext::CCC_PreprocessorDirective:
Douglas Gregorea147052010-08-25 18:04:30 +00001996 case CodeCompletionContext::CCC_NaturalLanguage:
Douglas Gregor67c692c2010-08-26 15:07:07 +00001997 case CodeCompletionContext::CCC_SelectorName:
Douglas Gregor28c78432010-08-27 17:35:51 +00001998 case CodeCompletionContext::CCC_TypeQualifiers:
Douglas Gregor0ac41382010-09-23 23:01:17 +00001999 case CodeCompletionContext::CCC_Other:
Douglas Gregor3a69eaf2011-02-18 23:30:37 +00002000 case CodeCompletionContext::CCC_OtherWithMacros:
Douglas Gregor21325842011-07-07 16:03:39 +00002001 case CodeCompletionContext::CCC_ObjCInstanceMessage:
2002 case CodeCompletionContext::CCC_ObjCClassMessage:
2003 case CodeCompletionContext::CCC_ObjCCategoryName:
Sam McCall3d8051a2018-09-18 08:40:41 +00002004 case CodeCompletionContext::CCC_IncludedFile:
Kadir Cetinkayab006e092018-10-24 15:23:49 +00002005 case CodeCompletionContext::CCC_NewName:
Douglas Gregor0de55ce2010-08-25 18:41:16 +00002006 // We're looking for nothing, or we're looking for names that cannot
2007 // be hidden.
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002008 return;
2009 }
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002010
Eugene Zelenko4f233182018-03-22 00:53:26 +00002011 using Result = CodeCompletionResult;
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002012 for (unsigned I = 0; I != NumResults; ++I) {
2013 if (Results[I].Kind != Result::RK_Declaration)
2014 continue;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002015
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002016 unsigned IDNS
2017 = Results[I].Declaration->getUnderlyingDecl()->getIdentifierNamespace();
2018
2019 bool Hiding = false;
2020 if (OnlyTagNames)
2021 Hiding = (IDNS & Decl::IDNS_Tag);
2022 else {
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002023 unsigned HiddenIDNS = (Decl::IDNS_Type | Decl::IDNS_Member |
Douglas Gregor59cab552010-08-16 23:05:20 +00002024 Decl::IDNS_Namespace | Decl::IDNS_Ordinary |
2025 Decl::IDNS_NonMemberOperator);
David Blaikiebbafb8a2012-03-11 07:00:24 +00002026 if (Ctx.getLangOpts().CPlusPlus)
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002027 HiddenIDNS |= Decl::IDNS_Tag;
2028 Hiding = (IDNS & HiddenIDNS);
2029 }
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002030
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002031 if (!Hiding)
2032 continue;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002033
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002034 DeclarationName Name = Results[I].Declaration->getDeclName();
2035 if (IdentifierInfo *Identifier = Name.getAsIdentifierInfo())
2036 HiddenNames.insert(Identifier->getName());
2037 else
2038 HiddenNames.insert(Name.getAsString());
2039 }
2040}
2041
Douglas Gregord46cf182010-08-16 20:01:48 +00002042void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &S,
2043 CodeCompletionContext Context,
John McCall276321a2010-08-25 06:19:51 +00002044 CodeCompletionResult *Results,
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002045 unsigned NumResults) {
Douglas Gregord46cf182010-08-16 20:01:48 +00002046 // Merge the results we were given with the results we cached.
2047 bool AddedResult = false;
Richard Smith697cc9e2012-08-14 03:13:00 +00002048 uint64_t InContexts =
2049 Context.getKind() == CodeCompletionContext::CCC_Recovery
2050 ? NormalContexts : (1LL << Context.getKind());
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002051 // Contains the set of names that are hidden by "local" completion results.
Ted Kremenek6a153372010-11-07 06:11:36 +00002052 llvm::StringSet<llvm::BumpPtrAllocator> HiddenNames;
Eugene Zelenko4f233182018-03-22 00:53:26 +00002053 using Result = CodeCompletionResult;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002054 SmallVector<Result, 8> AllResults;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002055 for (ASTUnit::cached_completion_iterator
Douglas Gregordf239672010-08-16 21:23:13 +00002056 C = AST.cached_completion_begin(),
2057 CEnd = AST.cached_completion_end();
Douglas Gregord46cf182010-08-16 20:01:48 +00002058 C != CEnd; ++C) {
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002059 // If the context we are in matches any of the contexts we are
Douglas Gregord46cf182010-08-16 20:01:48 +00002060 // interested in, we'll add this result.
2061 if ((C->ShowInContexts & InContexts) == 0)
2062 continue;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002063
Douglas Gregord46cf182010-08-16 20:01:48 +00002064 // If we haven't added any results previously, do so now.
2065 if (!AddedResult) {
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002066 CalculateHiddenNames(Context, Results, NumResults, S.Context,
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002067 HiddenNames);
Douglas Gregord46cf182010-08-16 20:01:48 +00002068 AllResults.insert(AllResults.end(), Results, Results + NumResults);
2069 AddedResult = true;
2070 }
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002071
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002072 // Determine whether this global completion result is hidden by a local
2073 // completion result. If so, skip it.
2074 if (C->Kind != CXCursor_MacroDefinition &&
2075 HiddenNames.count(C->Completion->getTypedText()))
2076 continue;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002077
Douglas Gregord46cf182010-08-16 20:01:48 +00002078 // Adjust priority based on similar type classes.
2079 unsigned Priority = C->Priority;
Douglas Gregor12785102010-08-24 20:21:13 +00002080 CodeCompletionString *Completion = C->Completion;
Douglas Gregord46cf182010-08-16 20:01:48 +00002081 if (!Context.getPreferredType().isNull()) {
2082 if (C->Kind == CXCursor_MacroDefinition) {
2083 Priority = getMacroUsagePriority(C->Completion->getTypedText(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00002084 S.getLangOpts(),
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002085 Context.getPreferredType()->isAnyPointerType());
Douglas Gregord46cf182010-08-16 20:01:48 +00002086 } else if (C->Type) {
2087 CanQualType Expected
Douglas Gregordf239672010-08-16 21:23:13 +00002088 = S.Context.getCanonicalType(
Douglas Gregord46cf182010-08-16 20:01:48 +00002089 Context.getPreferredType().getUnqualifiedType());
2090 SimplifiedTypeClass ExpectedSTC = getSimplifiedTypeClass(Expected);
2091 if (ExpectedSTC == C->TypeClass) {
2092 // We know this type is similar; check for an exact match.
2093 llvm::StringMap<unsigned> &CachedCompletionTypes
Douglas Gregordf239672010-08-16 21:23:13 +00002094 = AST.getCachedCompletionTypes();
Douglas Gregord46cf182010-08-16 20:01:48 +00002095 llvm::StringMap<unsigned>::iterator Pos
Douglas Gregordf239672010-08-16 21:23:13 +00002096 = CachedCompletionTypes.find(QualType(Expected).getAsString());
Douglas Gregord46cf182010-08-16 20:01:48 +00002097 if (Pos != CachedCompletionTypes.end() && Pos->second == C->Type)
2098 Priority /= CCF_ExactTypeMatch;
2099 else
2100 Priority /= CCF_SimilarTypeMatch;
2101 }
2102 }
2103 }
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002104
Douglas Gregor12785102010-08-24 20:21:13 +00002105 // Adjust the completion string, if required.
2106 if (C->Kind == CXCursor_MacroDefinition &&
2107 Context.getKind() == CodeCompletionContext::CCC_MacroNameUse) {
2108 // Create a new code-completion string that just contains the
2109 // macro name, without its arguments.
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00002110 CodeCompletionBuilder Builder(getAllocator(), getCodeCompletionTUInfo(),
2111 CCP_CodePattern, C->Availability);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002112 Builder.AddTypedTextChunk(C->Completion->getTypedText());
Douglas Gregor8850aa32010-08-25 18:03:13 +00002113 Priority = CCP_CodePattern;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002114 Completion = Builder.TakeString();
Douglas Gregor12785102010-08-24 20:21:13 +00002115 }
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002116
Argyrios Kyrtzidis5c8b1cd2012-09-27 00:24:09 +00002117 AllResults.push_back(Result(Completion, Priority, C->Kind,
Douglas Gregorf757a122010-08-23 23:00:57 +00002118 C->Availability));
Douglas Gregord46cf182010-08-16 20:01:48 +00002119 }
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002120
Douglas Gregord46cf182010-08-16 20:01:48 +00002121 // If we did not add any cached completion results, just forward the
2122 // results we were given to the next consumer.
2123 if (!AddedResult) {
2124 Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
2125 return;
2126 }
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002127
Douglas Gregord46cf182010-08-16 20:01:48 +00002128 Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
2129 AllResults.size());
2130}
2131
Adrian Prantlbb165fb2015-06-20 18:53:08 +00002132void ASTUnit::CodeComplete(
2133 StringRef File, unsigned Line, unsigned Column,
2134 ArrayRef<RemappedFile> RemappedFiles, bool IncludeMacros,
2135 bool IncludeCodePatterns, bool IncludeBriefComments,
2136 CodeCompleteConsumer &Consumer,
2137 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
2138 DiagnosticsEngine &Diag, LangOptions &LangOpts, SourceManager &SourceMgr,
2139 FileManager &FileMgr, SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
2140 SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers) {
Ted Kremenek5e14d392011-03-21 18:40:17 +00002141 if (!Invocation)
Douglas Gregor8e984da2010-08-04 16:47:14 +00002142 return;
2143
Douglas Gregor16896c42010-10-28 15:44:59 +00002144 SimpleTimer CompletionTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00002145 CompletionTimer.setOutput("Code completion @ " + File + ":" +
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002146 Twine(Line) + ":" + Twine(Column));
Douglas Gregor028d3e42010-08-09 20:45:32 +00002147
David Blaikieea4395e2017-01-06 19:49:01 +00002148 auto CCInvocation = std::make_shared<CompilerInvocation>(*Invocation);
Ted Kremenek5e14d392011-03-21 18:40:17 +00002149
2150 FrontendOptions &FrontendOpts = CCInvocation->getFrontendOpts();
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002151 CodeCompleteOptions &CodeCompleteOpts = FrontendOpts.CodeCompleteOpts;
Ted Kremenek5e14d392011-03-21 18:40:17 +00002152 PreprocessorOptions &PreprocessorOpts = CCInvocation->getPreprocessorOpts();
Douglas Gregorb68bc592010-08-05 09:09:23 +00002153
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002154 CodeCompleteOpts.IncludeMacros = IncludeMacros &&
2155 CachedCompletionResults.empty();
2156 CodeCompleteOpts.IncludeCodePatterns = IncludeCodePatterns;
2157 CodeCompleteOpts.IncludeGlobals = CachedCompletionResults.empty();
2158 CodeCompleteOpts.IncludeBriefComments = IncludeBriefComments;
Sam McCallbb2cf632018-01-12 14:51:47 +00002159 CodeCompleteOpts.LoadExternal = Consumer.loadExternal();
Ivan Donchevskiib4670fc2018-05-25 12:56:26 +00002160 CodeCompleteOpts.IncludeFixIts = Consumer.includeFixIts();
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002161
2162 assert(IncludeBriefComments == this->IncludeBriefCommentsInCodeCompletion);
2163
Douglas Gregor8e984da2010-08-04 16:47:14 +00002164 FrontendOpts.CodeCompletionAt.FileName = File;
2165 FrontendOpts.CodeCompletionAt.Line = Line;
2166 FrontendOpts.CodeCompletionAt.Column = Column;
2167
2168 // Set the language options appropriately.
Ted Kremenek8cf47df2011-11-17 23:01:24 +00002169 LangOpts = *CCInvocation->getLangOpts();
Douglas Gregor8e984da2010-08-04 16:47:14 +00002170
Argyrios Kyrtzidis06e8d692014-10-31 16:44:32 +00002171 // Spell-checking and warnings are wasteful during code-completion.
2172 LangOpts.SpellChecking = false;
2173 CCInvocation->getDiagnosticOpts().IgnoreWarnings = true;
2174
Adrian Prantlbb165fb2015-06-20 18:53:08 +00002175 std::unique_ptr<CompilerInstance> Clang(
2176 new CompilerInstance(PCHContainerOps));
Ted Kremenek84de4a12011-03-21 18:40:07 +00002177
2178 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00002179 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
2180 CICleanup(Clang.get());
Ted Kremenek84de4a12011-03-21 18:40:07 +00002181
David Blaikieea4395e2017-01-06 19:49:01 +00002182 auto &Inv = *CCInvocation;
2183 Clang->setInvocation(std::move(CCInvocation));
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00002184 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002185
Douglas Gregor8e984da2010-08-04 16:47:14 +00002186 // Set up diagnostics, capturing any diagnostics produced.
Ted Kremenek84de4a12011-03-21 18:40:07 +00002187 Clang->setDiagnostics(&Diag);
Nikolai Kosjar8edd8da2019-06-11 14:14:24 +00002188 CaptureDroppedDiagnostics Capture(CaptureDiagsKind::All,
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002189 Clang->getDiagnostics(),
Ilya Biryukov200b3282017-06-21 10:24:58 +00002190 &StoredDiagnostics, nullptr);
David Blaikieea4395e2017-01-06 19:49:01 +00002191 ProcessWarningOptions(Diag, Inv.getDiagnosticOpts());
2192
Douglas Gregor8e984da2010-08-04 16:47:14 +00002193 // Create the target instance.
Alp Toker80758082014-07-06 05:26:44 +00002194 Clang->setTarget(TargetInfo::CreateTargetInfo(
Saleem Abdulrasool10a49722016-04-08 16:52:00 +00002195 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
Ted Kremenek84de4a12011-03-21 18:40:07 +00002196 if (!Clang->hasTarget()) {
Craig Topper49a27902014-05-22 04:46:25 +00002197 Clang->setInvocation(nullptr);
Douglas Gregor2dd19f12010-08-18 22:29:43 +00002198 return;
Douglas Gregor8e984da2010-08-04 16:47:14 +00002199 }
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002200
Douglas Gregor8e984da2010-08-04 16:47:14 +00002201 // Inform the target of the language options.
2202 //
2203 // FIXME: We shouldn't need to do this, the target should be immutable once
2204 // created. This complexity should be lifted elsewhere.
Alp Toker74437972014-07-06 05:14:24 +00002205 Clang->getTarget().adjust(Clang->getLangOpts());
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002206
Ted Kremenek84de4a12011-03-21 18:40:07 +00002207 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Douglas Gregor8e984da2010-08-04 16:47:14 +00002208 "Invocation must have exactly one source file!");
Richard Smith40c0efa2017-04-26 18:57:40 +00002209 assert(Clang->getFrontendOpts().Inputs[0].getKind().getFormat() ==
2210 InputKind::Source &&
Douglas Gregor8e984da2010-08-04 16:47:14 +00002211 "FIXME: AST inputs not yet supported here!");
Richard Smith40c0efa2017-04-26 18:57:40 +00002212 assert(Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() !=
2213 InputKind::LLVM_IR &&
Douglas Gregor8e984da2010-08-04 16:47:14 +00002214 "IR inputs not support here!");
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002215
Douglas Gregor8e984da2010-08-04 16:47:14 +00002216 // Use the source and file managers that we were given.
Ted Kremenek84de4a12011-03-21 18:40:07 +00002217 Clang->setFileManager(&FileMgr);
2218 Clang->setSourceManager(&SourceMgr);
Douglas Gregor8e984da2010-08-04 16:47:14 +00002219
2220 // Remap files.
2221 PreprocessorOpts.clearRemappedFiles();
Douglas Gregord8a5dba2010-08-04 17:07:00 +00002222 PreprocessorOpts.RetainRemappedFileBuffers = true;
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00002223 for (const auto &RemappedFile : RemappedFiles) {
2224 PreprocessorOpts.addRemappedFile(RemappedFile.first, RemappedFile.second);
2225 OwnedBuffers.push_back(RemappedFile.second);
Douglas Gregorb97b6662010-08-20 00:59:43 +00002226 }
Dmitri Gribenkoc444b572014-02-08 00:38:15 +00002227
Douglas Gregorb14904c2010-08-13 22:48:40 +00002228 // Use the code completion consumer we were given, but adding any cached
2229 // code-completion results.
Douglas Gregore9186e62010-11-29 16:13:56 +00002230 AugmentedCodeCompleteConsumer *AugmentedConsumer
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002231 = new AugmentedCodeCompleteConsumer(*this, Consumer, CodeCompleteOpts);
Ted Kremenek84de4a12011-03-21 18:40:07 +00002232 Clang->setCodeCompletionConsumer(AugmentedConsumer);
Douglas Gregor8e984da2010-08-04 16:47:14 +00002233
Douglas Gregor028d3e42010-08-09 20:45:32 +00002234 // If we have a precompiled preamble, try to use it. We only allow
2235 // the use of the precompiled preamble if we're if the completion
2236 // point is within the main file, after the end of the precompiled
2237 // preamble.
Rafael Espindola2346a372014-08-18 18:47:08 +00002238 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
Ilya Biryukov200b3282017-06-21 10:24:58 +00002239 if (Preamble) {
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00002240 std::string CompleteFilePath(File);
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00002241
Duncan P. N. Exon Smithdb8a7422019-03-26 22:32:06 +00002242 auto &VFS = FileMgr.getVirtualFileSystem();
2243 auto CompleteFileStatus = VFS.status(CompleteFilePath);
Ilya Biryukovaf69e402017-05-23 11:37:52 +00002244 if (CompleteFileStatus) {
2245 llvm::sys::fs::UniqueID CompleteFileID = CompleteFileStatus->getUniqueID();
2246
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00002247 std::string MainPath(OriginalSourceFile);
Duncan P. N. Exon Smithdb8a7422019-03-26 22:32:06 +00002248 auto MainStatus = VFS.status(MainPath);
Ilya Biryukovaf69e402017-05-23 11:37:52 +00002249 if (MainStatus) {
2250 llvm::sys::fs::UniqueID MainID = MainStatus->getUniqueID();
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00002251 if (CompleteFileID == MainID && Line > 1)
Rafael Espindola2346a372014-08-18 18:47:08 +00002252 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(
Duncan P. N. Exon Smithdb8a7422019-03-26 22:32:06 +00002253 PCHContainerOps, Inv, &VFS, false, Line - 1);
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00002254 }
2255 }
Douglas Gregor028d3e42010-08-09 20:45:32 +00002256 }
2257
2258 // If the main file has been overridden due to the use of a preamble,
2259 // make that override happen and introduce the preamble.
2260 if (OverrideMainBuffer) {
Ilya Biryukov417085a2017-11-16 16:25:01 +00002261 assert(Preamble &&
2262 "No preamble was built, but OverrideMainBuffer is not null");
2263
Duncan P. N. Exon Smithdb8a7422019-03-26 22:32:06 +00002264 IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS =
2265 &FileMgr.getVirtualFileSystem();
Ilya Biryukov417085a2017-11-16 16:25:01 +00002266 Preamble->AddImplicitPreamble(Clang->getInvocation(), VFS,
2267 OverrideMainBuffer.get());
2268 // FIXME: there is no way to update VFS if it was changed by
2269 // AddImplicitPreamble as FileMgr is accepted as a parameter by this method.
2270 // We use on-disk preambles instead and rely on FileMgr's VFS to ensure the
2271 // PCH files are always readable.
Rafael Espindola2346a372014-08-18 18:47:08 +00002272 OwnedBuffers.push_back(OverrideMainBuffer.release());
Douglas Gregor7b02b582010-08-20 00:02:33 +00002273 } else {
2274 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
2275 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregor028d3e42010-08-09 20:45:32 +00002276 }
2277
Argyrios Kyrtzidis870704f2012-11-02 22:18:44 +00002278 // Disable the preprocessing record if modules are not enabled.
2279 if (!Clang->getLangOpts().Modules)
2280 PreprocessorOpts.DetailedRecord = false;
Ahmed Charlesb8984322014-03-07 20:03:18 +00002281
2282 std::unique_ptr<SyntaxOnlyAction> Act;
Douglas Gregor8e984da2010-08-04 16:47:14 +00002283 Act.reset(new SyntaxOnlyAction);
Douglas Gregor32fbe312012-01-20 16:28:04 +00002284 if (Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
JF Bastien0e828952019-06-26 19:50:12 +00002285 if (llvm::Error Err = Act->Execute()) {
2286 consumeError(std::move(Err)); // FIXME this drops errors on the floor.
2287 }
Douglas Gregor8e984da2010-08-04 16:47:14 +00002288 Act->EndSourceFile();
2289 }
Douglas Gregor8e984da2010-08-04 16:47:14 +00002290}
Douglas Gregore9386682010-08-13 05:36:37 +00002291
Argyrios Kyrtzidis39a76382012-09-26 16:39:46 +00002292bool ASTUnit::Save(StringRef File) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00002293 if (HadModuleLoaderFatalFailure)
2294 return true;
2295
Argyrios Kyrtzidis55e75572011-07-21 18:44:49 +00002296 // Write to a temporary file and later rename it to the actual file, to avoid
2297 // possible race conditions.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00002298 SmallString<128> TempPath;
Argyrios Kyrtzidis08a2bfd2011-07-28 00:45:10 +00002299 TempPath = File;
2300 TempPath += "-%%%%%%%%";
2301 int fd;
Yaron Keren92e1b622015-03-18 10:17:07 +00002302 if (llvm::sys::fs::createUniqueFile(TempPath, fd, TempPath))
Argyrios Kyrtzidis39a76382012-09-26 16:39:46 +00002303 return true;
Argyrios Kyrtzidis55e75572011-07-21 18:44:49 +00002304
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002305 // FIXME: Can we somehow regenerate the stat cache here, or do we need to
Douglas Gregore9386682010-08-13 05:36:37 +00002306 // unconditionally create a stat cache when we parse the file?
Argyrios Kyrtzidis08a2bfd2011-07-28 00:45:10 +00002307 llvm::raw_fd_ostream Out(fd, /*shouldClose=*/true);
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00002308
2309 serialize(Out);
2310 Out.close();
Argyrios Kyrtzidiseeea16a2012-03-13 02:17:06 +00002311 if (Out.has_error()) {
2312 Out.clear_error();
Argyrios Kyrtzidis39a76382012-09-26 16:39:46 +00002313 return true;
Argyrios Kyrtzidiseeea16a2012-03-13 02:17:06 +00002314 }
Argyrios Kyrtzidis55e75572011-07-21 18:44:49 +00002315
Yaron Keren92e1b622015-03-18 10:17:07 +00002316 if (llvm::sys::fs::rename(TempPath, File)) {
2317 llvm::sys::fs::remove(TempPath);
Argyrios Kyrtzidis39a76382012-09-26 16:39:46 +00002318 return true;
Argyrios Kyrtzidis55e75572011-07-21 18:44:49 +00002319 }
2320
Argyrios Kyrtzidis39a76382012-09-26 16:39:46 +00002321 return false;
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00002322}
2323
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00002324static bool serializeUnit(ASTWriter &Writer,
2325 SmallVectorImpl<char> &Buffer,
2326 Sema &S,
2327 bool hasErrors,
2328 raw_ostream &OS) {
Craig Topper49a27902014-05-22 04:46:25 +00002329 Writer.WriteAST(S, std::string(), nullptr, "", hasErrors);
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00002330
2331 // Write the generated bitstream to "Out".
2332 if (!Buffer.empty())
2333 OS.write(Buffer.data(), Buffer.size());
2334
2335 return false;
2336}
2337
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002338bool ASTUnit::serialize(raw_ostream &OS) {
Argyrios Kyrtzidis70ec1c72016-07-13 20:35:26 +00002339 // For serialization we are lenient if the errors were only warn-as-error kind.
2340 bool hasErrors = getDiagnostics().hasUncompilableErrorOccurred();
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00002341
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00002342 if (WriterData)
2343 return serializeUnit(WriterData->Writer, WriterData->Buffer,
2344 getSema(), hasErrors, OS);
2345
Daniel Dunbar9a963862012-02-29 20:31:23 +00002346 SmallString<128> Buffer;
Douglas Gregore9386682010-08-13 05:36:37 +00002347 llvm::BitstreamWriter Stream(Buffer);
Duncan P. N. Exon Smith8bef5cd2019-03-09 17:33:56 +00002348 InMemoryModuleCache ModuleCache;
2349 ASTWriter Writer(Stream, Buffer, ModuleCache, {});
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00002350 return serializeUnit(Writer, Buffer, getSema(), hasErrors, OS);
Douglas Gregore9386682010-08-13 05:36:37 +00002351}
Douglas Gregor925296b2011-07-19 16:10:42 +00002352
Eugene Zelenko4f233182018-03-22 00:53:26 +00002353using SLocRemap = ContinuousRangeMap<unsigned, int, 2>;
Douglas Gregor925296b2011-07-19 16:10:42 +00002354
Douglas Gregor925296b2011-07-19 16:10:42 +00002355void ASTUnit::TranslateStoredDiagnostics(
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002356 FileManager &FileMgr,
Douglas Gregor925296b2011-07-19 16:10:42 +00002357 SourceManager &SrcMgr,
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002358 const SmallVectorImpl<StandaloneDiagnostic> &Diags,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002359 SmallVectorImpl<StoredDiagnostic> &Out) {
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002360 // Map the standalone diagnostic into the new source manager. We also need to
2361 // remap all the locations to the new view. This includes the diag location,
2362 // any associated source ranges, and the source ranges of associated fix-its.
Douglas Gregor925296b2011-07-19 16:10:42 +00002363 // FIXME: There should be a cleaner way to do this.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002364 SmallVector<StoredDiagnostic, 4> Result;
Douglas Gregor925296b2011-07-19 16:10:42 +00002365 Result.reserve(Diags.size());
Erik Verbruggenefe6fa52017-06-09 08:29:58 +00002366
Eugene Zelenko4f233182018-03-22 00:53:26 +00002367 for (const auto &SD : Diags) {
Douglas Gregor925296b2011-07-19 16:10:42 +00002368 // Rebuild the StoredDiagnostic.
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002369 if (SD.Filename.empty())
2370 continue;
2371 const FileEntry *FE = FileMgr.getFile(SD.Filename);
2372 if (!FE)
2373 continue;
Erik Verbruggenefe6fa52017-06-09 08:29:58 +00002374 SourceLocation FileLoc;
2375 auto ItFileID = PreambleSrcLocCache.find(SD.Filename);
2376 if (ItFileID == PreambleSrcLocCache.end()) {
2377 FileID FID = SrcMgr.translateFile(FE);
2378 FileLoc = SrcMgr.getLocForStartOfFile(FID);
2379 PreambleSrcLocCache[SD.Filename] = FileLoc;
2380 } else {
2381 FileLoc = ItFileID->getValue();
Erik Verbruggen2c7c38d2017-02-16 09:49:30 +00002382 }
Erik Verbruggenefe6fa52017-06-09 08:29:58 +00002383
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002384 if (FileLoc.isInvalid())
2385 continue;
2386 SourceLocation L = FileLoc.getLocWithOffset(SD.LocOffset);
Douglas Gregor925296b2011-07-19 16:10:42 +00002387 FullSourceLoc Loc(L, SrcMgr);
2388
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002389 SmallVector<CharSourceRange, 4> Ranges;
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002390 Ranges.reserve(SD.Ranges.size());
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00002391 for (const auto &Range : SD.Ranges) {
2392 SourceLocation BL = FileLoc.getLocWithOffset(Range.first);
2393 SourceLocation EL = FileLoc.getLocWithOffset(Range.second);
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002394 Ranges.push_back(CharSourceRange::getCharRange(BL, EL));
Douglas Gregor925296b2011-07-19 16:10:42 +00002395 }
2396
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002397 SmallVector<FixItHint, 2> FixIts;
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002398 FixIts.reserve(SD.FixIts.size());
Eugene Zelenko4f233182018-03-22 00:53:26 +00002399 for (const auto &FixIt : SD.FixIts) {
Douglas Gregor925296b2011-07-19 16:10:42 +00002400 FixIts.push_back(FixItHint());
2401 FixItHint &FH = FixIts.back();
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00002402 FH.CodeToInsert = FixIt.CodeToInsert;
2403 SourceLocation BL = FileLoc.getLocWithOffset(FixIt.RemoveRange.first);
2404 SourceLocation EL = FileLoc.getLocWithOffset(FixIt.RemoveRange.second);
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002405 FH.RemoveRange = CharSourceRange::getCharRange(BL, EL);
Douglas Gregor925296b2011-07-19 16:10:42 +00002406 }
2407
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002408 Result.push_back(StoredDiagnostic(SD.Level, SD.ID,
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002409 SD.Message, Loc, Ranges, FixIts));
Douglas Gregor925296b2011-07-19 16:10:42 +00002410 }
2411 Result.swap(Out);
2412}
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002413
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00002414void ASTUnit::addFileLevelDecl(Decl *D) {
2415 assert(D);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002416
Douglas Gregor61d63d02011-11-07 18:53:57 +00002417 // We only care about local declarations.
2418 if (D->isFromASTFile())
2419 return;
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00002420
2421 SourceManager &SM = *SourceMgr;
2422 SourceLocation Loc = D->getLocation();
2423 if (Loc.isInvalid() || !SM.isLocalSourceLocation(Loc))
2424 return;
2425
2426 // We only keep track of the file-level declarations of each file.
2427 if (!D->getLexicalDeclContext()->isFileContext())
2428 return;
2429
2430 SourceLocation FileLoc = SM.getFileLoc(Loc);
2431 assert(SM.isLocalSourceLocation(FileLoc));
2432 FileID FID;
2433 unsigned Offset;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002434 std::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc);
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00002435 if (FID.isInvalid())
2436 return;
2437
2438 LocDeclsTy *&Decls = FileDecls[FID];
2439 if (!Decls)
2440 Decls = new LocDeclsTy();
2441
2442 std::pair<unsigned, Decl *> LocDecl(Offset, D);
2443
2444 if (Decls->empty() || Decls->back().first <= Offset) {
2445 Decls->push_back(LocDecl);
2446 return;
2447 }
2448
Fangrui Song7264a472019-07-03 08:13:17 +00002449 LocDeclsTy::iterator I =
2450 llvm::upper_bound(*Decls, LocDecl, llvm::less_first());
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00002451
2452 Decls->insert(I, LocDecl);
2453}
2454
Argyrios Kyrtzidise9681522011-11-03 02:20:32 +00002455void ASTUnit::findFileRegionDecls(FileID File, unsigned Offset, unsigned Length,
2456 SmallVectorImpl<Decl *> &Decls) {
2457 if (File.isInvalid())
2458 return;
2459
2460 if (SourceMgr->isLoadedFileID(File)) {
2461 assert(Ctx->getExternalSource() && "No external source!");
2462 return Ctx->getExternalSource()->FindFileRegionDecls(File, Offset, Length,
2463 Decls);
2464 }
2465
2466 FileDeclsTy::iterator I = FileDecls.find(File);
2467 if (I == FileDecls.end())
2468 return;
2469
2470 LocDeclsTy &LocDecls = *I->second;
2471 if (LocDecls.empty())
2472 return;
2473
Benjamin Kramere3e855b2013-08-24 13:12:34 +00002474 LocDeclsTy::iterator BeginIt =
Fangrui Song7264a472019-07-03 08:13:17 +00002475 llvm::partition_point(LocDecls, [=](std::pair<unsigned, Decl *> LD) {
2476 return LD.first < Offset;
2477 });
Argyrios Kyrtzidise9681522011-11-03 02:20:32 +00002478 if (BeginIt != LocDecls.begin())
2479 --BeginIt;
2480
Argyrios Kyrtzidis8ad3bab2011-11-23 20:27:36 +00002481 // If we are pointing at a top-level decl inside an objc container, we need
2482 // to backtrack until we find it otherwise we will fail to report that the
2483 // region overlaps with an objc container.
2484 while (BeginIt != LocDecls.begin() &&
2485 BeginIt->second->isTopLevelDeclInObjCContainer())
2486 --BeginIt;
2487
Fangrui Song7264a472019-07-03 08:13:17 +00002488 LocDeclsTy::iterator EndIt = llvm::upper_bound(
2489 LocDecls, std::make_pair(Offset + Length, (Decl *)nullptr),
2490 llvm::less_first());
Argyrios Kyrtzidise9681522011-11-03 02:20:32 +00002491 if (EndIt != LocDecls.end())
2492 ++EndIt;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002493
Argyrios Kyrtzidise9681522011-11-03 02:20:32 +00002494 for (LocDeclsTy::iterator DIt = BeginIt; DIt != EndIt; ++DIt)
2495 Decls.push_back(DIt->second);
2496}
2497
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002498SourceLocation ASTUnit::getLocation(const FileEntry *File,
2499 unsigned Line, unsigned Col) const {
2500 const SourceManager &SM = getSourceManager();
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00002501 SourceLocation Loc = SM.translateFileLineCol(File, Line, Col);
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002502 return SM.getMacroArgExpandedLocation(Loc);
2503}
2504
2505SourceLocation ASTUnit::getLocation(const FileEntry *File,
2506 unsigned Offset) const {
2507 const SourceManager &SM = getSourceManager();
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00002508 SourceLocation FileLoc = SM.translateFileLineCol(File, 1, 1);
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002509 return SM.getMacroArgExpandedLocation(FileLoc.getLocWithOffset(Offset));
2510}
2511
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002512/// If \arg Loc is a loaded location from the preamble, returns
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00002513/// the corresponding local location of the main file, otherwise it returns
2514/// \arg Loc.
Vedant Kumar525a7f62017-07-25 19:53:27 +00002515SourceLocation ASTUnit::mapLocationFromPreamble(SourceLocation Loc) const {
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00002516 FileID PreambleID;
2517 if (SourceMgr)
2518 PreambleID = SourceMgr->getPreambleFileID();
2519
Ilya Biryukov200b3282017-06-21 10:24:58 +00002520 if (Loc.isInvalid() || !Preamble || PreambleID.isInvalid())
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00002521 return Loc;
2522
2523 unsigned Offs;
Ilya Biryukov200b3282017-06-21 10:24:58 +00002524 if (SourceMgr->isInFileID(Loc, PreambleID, &Offs) && Offs < Preamble->getBounds().Size) {
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00002525 SourceLocation FileLoc
2526 = SourceMgr->getLocForStartOfFile(SourceMgr->getMainFileID());
2527 return FileLoc.getLocWithOffset(Offs);
2528 }
2529
2530 return Loc;
2531}
2532
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002533/// If \arg Loc is a local location of the main file but inside the
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00002534/// preamble chunk, returns the corresponding loaded location from the
2535/// preamble, otherwise it returns \arg Loc.
Vedant Kumar525a7f62017-07-25 19:53:27 +00002536SourceLocation ASTUnit::mapLocationToPreamble(SourceLocation Loc) const {
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00002537 FileID PreambleID;
2538 if (SourceMgr)
2539 PreambleID = SourceMgr->getPreambleFileID();
2540
Ilya Biryukov200b3282017-06-21 10:24:58 +00002541 if (Loc.isInvalid() || !Preamble || PreambleID.isInvalid())
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00002542 return Loc;
2543
2544 unsigned Offs;
2545 if (SourceMgr->isInFileID(Loc, SourceMgr->getMainFileID(), &Offs) &&
Ilya Biryukov200b3282017-06-21 10:24:58 +00002546 Offs < Preamble->getBounds().Size) {
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00002547 SourceLocation FileLoc = SourceMgr->getLocForStartOfFile(PreambleID);
2548 return FileLoc.getLocWithOffset(Offs);
2549 }
2550
2551 return Loc;
2552}
2553
Vedant Kumar525a7f62017-07-25 19:53:27 +00002554bool ASTUnit::isInPreambleFileID(SourceLocation Loc) const {
Argyrios Kyrtzidis429ec022011-10-25 00:29:50 +00002555 FileID FID;
2556 if (SourceMgr)
2557 FID = SourceMgr->getPreambleFileID();
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002558
Argyrios Kyrtzidis429ec022011-10-25 00:29:50 +00002559 if (Loc.isInvalid() || FID.isInvalid())
2560 return false;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002561
Argyrios Kyrtzidis429ec022011-10-25 00:29:50 +00002562 return SourceMgr->isInFileID(Loc, FID);
2563}
2564
Vedant Kumar525a7f62017-07-25 19:53:27 +00002565bool ASTUnit::isInMainFileID(SourceLocation Loc) const {
Argyrios Kyrtzidis429ec022011-10-25 00:29:50 +00002566 FileID FID;
2567 if (SourceMgr)
2568 FID = SourceMgr->getMainFileID();
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002569
Argyrios Kyrtzidis429ec022011-10-25 00:29:50 +00002570 if (Loc.isInvalid() || FID.isInvalid())
2571 return false;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002572
Argyrios Kyrtzidis429ec022011-10-25 00:29:50 +00002573 return SourceMgr->isInFileID(Loc, FID);
2574}
2575
Vedant Kumar525a7f62017-07-25 19:53:27 +00002576SourceLocation ASTUnit::getEndOfPreambleFileID() const {
Argyrios Kyrtzidis429ec022011-10-25 00:29:50 +00002577 FileID FID;
2578 if (SourceMgr)
2579 FID = SourceMgr->getPreambleFileID();
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002580
Argyrios Kyrtzidis429ec022011-10-25 00:29:50 +00002581 if (FID.isInvalid())
Eugene Zelenko4f233182018-03-22 00:53:26 +00002582 return {};
Argyrios Kyrtzidis429ec022011-10-25 00:29:50 +00002583
2584 return SourceMgr->getLocForEndOfFile(FID);
2585}
2586
Vedant Kumar525a7f62017-07-25 19:53:27 +00002587SourceLocation ASTUnit::getStartOfMainFileID() const {
Argyrios Kyrtzidis429ec022011-10-25 00:29:50 +00002588 FileID FID;
2589 if (SourceMgr)
2590 FID = SourceMgr->getMainFileID();
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002591
Argyrios Kyrtzidis429ec022011-10-25 00:29:50 +00002592 if (FID.isInvalid())
Eugene Zelenko4f233182018-03-22 00:53:26 +00002593 return {};
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002594
Argyrios Kyrtzidis429ec022011-10-25 00:29:50 +00002595 return SourceMgr->getLocForStartOfFile(FID);
2596}
2597
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00002598llvm::iterator_range<PreprocessingRecord::iterator>
Argyrios Kyrtzidisd4fcf5802012-10-02 16:10:51 +00002599ASTUnit::getLocalPreprocessingEntities() const {
2600 if (isMainFileAST()) {
2601 serialization::ModuleFile &
2602 Mod = Reader->getModuleManager().getPrimaryModule();
2603 return Reader->getModulePreprocessedEntities(Mod);
2604 }
2605
2606 if (PreprocessingRecord *PPRec = PP->getPreprocessingRecord())
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00002607 return llvm::make_range(PPRec->local_begin(), PPRec->local_end());
Argyrios Kyrtzidisd4fcf5802012-10-02 16:10:51 +00002608
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00002609 return llvm::make_range(PreprocessingRecord::iterator(),
2610 PreprocessingRecord::iterator());
Argyrios Kyrtzidisd4fcf5802012-10-02 16:10:51 +00002611}
2612
Argyrios Kyrtzidise514b202012-10-03 01:58:28 +00002613bool ASTUnit::visitLocalTopLevelDecls(void *context, DeclVisitorFn Fn) {
Argyrios Kyrtzidis10e78462012-10-02 21:09:13 +00002614 if (isMainFileAST()) {
2615 serialization::ModuleFile &
2616 Mod = Reader->getModuleManager().getPrimaryModule();
Eugene Zelenko4f233182018-03-22 00:53:26 +00002617 for (const auto *D : Reader->getModuleFileLevelDecls(Mod)) {
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00002618 if (!Fn(context, D))
Argyrios Kyrtzidis10e78462012-10-02 21:09:13 +00002619 return false;
2620 }
2621
2622 return true;
2623 }
2624
2625 for (ASTUnit::top_level_iterator TL = top_level_begin(),
2626 TLEnd = top_level_end();
2627 TL != TLEnd; ++TL) {
2628 if (!Fn(context, *TL))
2629 return false;
2630 }
2631
2632 return true;
2633}
2634
Argyrios Kyrtzidisf484b132012-10-03 21:05:51 +00002635const FileEntry *ASTUnit::getPCHFile() {
2636 if (!Reader)
Craig Topper49a27902014-05-22 04:46:25 +00002637 return nullptr;
Argyrios Kyrtzidisf484b132012-10-03 21:05:51 +00002638
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00002639 serialization::ModuleFile *Mod = nullptr;
2640 Reader->getModuleManager().visit([&Mod](serialization::ModuleFile &M) {
2641 switch (M.Kind) {
2642 case serialization::MK_ImplicitModule:
2643 case serialization::MK_ExplicitModule:
Manman Ren11f2a472016-08-18 17:42:15 +00002644 case serialization::MK_PrebuiltModule:
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00002645 return true; // skip dependencies.
2646 case serialization::MK_PCH:
2647 Mod = &M;
2648 return true; // found it.
2649 case serialization::MK_Preamble:
2650 return false; // look in dependencies.
2651 case serialization::MK_MainFile:
2652 return false; // look in dependencies.
2653 }
2654
2655 return true;
2656 });
2657 if (Mod)
2658 return Mod->File;
Argyrios Kyrtzidisf484b132012-10-03 21:05:51 +00002659
Craig Topper49a27902014-05-22 04:46:25 +00002660 return nullptr;
Argyrios Kyrtzidisf484b132012-10-03 21:05:51 +00002661}
2662
Vedant Kumar525a7f62017-07-25 19:53:27 +00002663bool ASTUnit::isModuleFile() const {
Richard Smithab755972017-06-05 18:10:11 +00002664 return isMainFileAST() && getLangOpts().isCompilingModule();
2665}
2666
2667InputKind ASTUnit::getInputKind() const {
2668 auto &LangOpts = getLangOpts();
2669
2670 InputKind::Language Lang;
2671 if (LangOpts.OpenCL)
2672 Lang = InputKind::OpenCL;
2673 else if (LangOpts.CUDA)
2674 Lang = InputKind::CUDA;
2675 else if (LangOpts.RenderScript)
2676 Lang = InputKind::RenderScript;
2677 else if (LangOpts.CPlusPlus)
Erik Pilkingtonfa983902018-10-30 20:31:30 +00002678 Lang = LangOpts.ObjC ? InputKind::ObjCXX : InputKind::CXX;
Richard Smithab755972017-06-05 18:10:11 +00002679 else
Erik Pilkingtonfa983902018-10-30 20:31:30 +00002680 Lang = LangOpts.ObjC ? InputKind::ObjC : InputKind::C;
Richard Smithab755972017-06-05 18:10:11 +00002681
2682 InputKind::Format Fmt = InputKind::Source;
2683 if (LangOpts.getCompilingModule() == LangOptions::CMK_ModuleMap)
2684 Fmt = InputKind::ModuleMap;
2685
2686 // We don't know if input was preprocessed. Assume not.
2687 bool PP = false;
2688
2689 return InputKind(Lang, Fmt, PP);
Argyrios Kyrtzidise445c722012-10-10 02:12:47 +00002690}
2691
Argyrios Kyrtzidisebf01362011-10-10 21:57:12 +00002692#ifndef NDEBUG
2693ASTUnit::ConcurrencyState::ConcurrencyState() {
2694 Mutex = new llvm::sys::MutexImpl(/*recursive=*/true);
2695}
2696
2697ASTUnit::ConcurrencyState::~ConcurrencyState() {
2698 delete static_cast<llvm::sys::MutexImpl *>(Mutex);
2699}
2700
2701void ASTUnit::ConcurrencyState::start() {
2702 bool acquired = static_cast<llvm::sys::MutexImpl *>(Mutex)->tryacquire();
2703 assert(acquired && "Concurrent access to ASTUnit!");
2704}
2705
2706void ASTUnit::ConcurrencyState::finish() {
2707 static_cast<llvm::sys::MutexImpl *>(Mutex)->release();
2708}
2709
2710#else // NDEBUG
2711
Hans Wennborgdcfba332015-10-06 23:40:43 +00002712ASTUnit::ConcurrencyState::ConcurrencyState() { Mutex = nullptr; }
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +00002713ASTUnit::ConcurrencyState::~ConcurrencyState() {}
Argyrios Kyrtzidisebf01362011-10-10 21:57:12 +00002714void ASTUnit::ConcurrencyState::start() {}
2715void ASTUnit::ConcurrencyState::finish() {}
2716
Hans Wennborgdcfba332015-10-06 23:40:43 +00002717#endif // NDEBUG