blob: cd3664bd3fc31fc6476d53efb36775fff62004db [file] [log] [blame]
Eugene Zelenko4f233182018-03-22 00:53:26 +00001//===- ASTUnit.cpp - ASTUnit utility --------------------------------------===//
Argyrios Kyrtzidis3a08ec12009-06-20 08:27:14 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// ASTUnit Implementation.
11//
12//===----------------------------------------------------------------------===//
13
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000014#include "clang/Frontend/ASTUnit.h"
Daniel Dunbar764c0822009-12-01 09:51:01 +000015#include "clang/AST/ASTConsumer.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000016#include "clang/AST/ASTContext.h"
Eugene Zelenko4f233182018-03-22 00:53:26 +000017#include "clang/AST/CommentCommandTraits.h"
18#include "clang/AST/Decl.h"
19#include "clang/AST/DeclBase.h"
20#include "clang/AST/DeclCXX.h"
21#include "clang/AST/DeclGroup.h"
22#include "clang/AST/DeclObjC.h"
23#include "clang/AST/DeclTemplate.h"
24#include "clang/AST/DeclarationName.h"
25#include "clang/AST/ExternalASTSource.h"
26#include "clang/AST/PrettyPrinter.h"
27#include "clang/AST/Type.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000028#include "clang/AST/TypeOrdering.h"
29#include "clang/Basic/Diagnostic.h"
Eugene Zelenko4f233182018-03-22 00:53:26 +000030#include "clang/Basic/FileManager.h"
31#include "clang/Basic/IdentifierTable.h"
32#include "clang/Basic/LLVM.h"
33#include "clang/Basic/LangOptions.h"
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +000034#include "clang/Basic/MemoryBufferCache.h"
Eugene Zelenko4f233182018-03-22 00:53:26 +000035#include "clang/Basic/Module.h"
36#include "clang/Basic/SourceLocation.h"
37#include "clang/Basic/SourceManager.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000038#include "clang/Basic/TargetInfo.h"
39#include "clang/Basic/TargetOptions.h"
Ben Langmuirc8130a72014-02-20 21:59:23 +000040#include "clang/Basic/VirtualFileSystem.h"
Daniel Dunbar764c0822009-12-01 09:51:01 +000041#include "clang/Frontend/CompilerInstance.h"
Eugene Zelenko4f233182018-03-22 00:53:26 +000042#include "clang/Frontend/CompilerInvocation.h"
43#include "clang/Frontend/FrontendAction.h"
Daniel Dunbar764c0822009-12-01 09:51:01 +000044#include "clang/Frontend/FrontendActions.h"
Daniel Dunbar55a17b62009-12-02 03:23:45 +000045#include "clang/Frontend/FrontendDiagnostic.h"
Daniel Dunbar764c0822009-12-01 09:51:01 +000046#include "clang/Frontend/FrontendOptions.h"
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +000047#include "clang/Frontend/MultiplexConsumer.h"
Eugene Zelenko4f233182018-03-22 00:53:26 +000048#include "clang/Frontend/PCHContainerOperations.h"
49#include "clang/Frontend/PrecompiledPreamble.h"
Douglas Gregor36e3b5c2010-10-11 21:37:58 +000050#include "clang/Frontend/Utils.h"
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000051#include "clang/Lex/HeaderSearch.h"
Eugene Zelenko4f233182018-03-22 00:53:26 +000052#include "clang/Lex/HeaderSearchOptions.h"
53#include "clang/Lex/Lexer.h"
54#include "clang/Lex/PPCallbacks.h"
55#include "clang/Lex/PreprocessingRecord.h"
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000056#include "clang/Lex/Preprocessor.h"
Douglas Gregor1452ff12012-10-24 17:46:57 +000057#include "clang/Lex/PreprocessorOptions.h"
Eugene Zelenko4f233182018-03-22 00:53:26 +000058#include "clang/Lex/Token.h"
59#include "clang/Sema/CodeCompleteConsumer.h"
60#include "clang/Sema/CodeCompleteOptions.h"
David Blaikie0a4e61f2013-09-13 18:32:52 +000061#include "clang/Sema/Sema.h"
Eugene Zelenko4f233182018-03-22 00:53:26 +000062#include "clang/Serialization/ASTBitCodes.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000063#include "clang/Serialization/ASTReader.h"
64#include "clang/Serialization/ASTWriter.h"
Eugene Zelenko4f233182018-03-22 00:53:26 +000065#include "clang/Serialization/ContinuousRangeMap.h"
66#include "clang/Serialization/Module.h"
Chris Lattnerce6c42f2011-03-23 04:04:01 +000067#include "llvm/ADT/ArrayRef.h"
Eugene Zelenko4f233182018-03-22 00:53:26 +000068#include "llvm/ADT/DenseMap.h"
69#include "llvm/ADT/IntrusiveRefCntPtr.h"
70#include "llvm/ADT/None.h"
71#include "llvm/ADT/Optional.h"
72#include "llvm/ADT/STLExtras.h"
73#include "llvm/ADT/SmallString.h"
74#include "llvm/ADT/SmallVector.h"
75#include "llvm/ADT/StringMap.h"
76#include "llvm/ADT/StringRef.h"
Douglas Gregor40a5a7d2010-08-16 23:08:34 +000077#include "llvm/ADT/StringSet.h"
Eugene Zelenko4f233182018-03-22 00:53:26 +000078#include "llvm/ADT/Twine.h"
79#include "llvm/ADT/iterator_range.h"
80#include "llvm/Bitcode/BitstreamWriter.h"
81#include "llvm/Support/Allocator.h"
82#include "llvm/Support/Casting.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000083#include "llvm/Support/CrashRecoveryContext.h"
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +000084#include "llvm/Support/DJB.h"
Eugene Zelenko4f233182018-03-22 00:53:26 +000085#include "llvm/Support/ErrorHandling.h"
86#include "llvm/Support/ErrorOr.h"
87#include "llvm/Support/FileSystem.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000088#include "llvm/Support/MemoryBuffer.h"
Argyrios Kyrtzidisebf01362011-10-10 21:57:12 +000089#include "llvm/Support/Mutex.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000090#include "llvm/Support/Timer.h"
91#include "llvm/Support/raw_ostream.h"
Eugene Zelenko4f233182018-03-22 00:53:26 +000092#include <algorithm>
Benjamin Kramer4527fb22014-03-02 17:08:31 +000093#include <atomic>
Eugene Zelenko4f233182018-03-22 00:53:26 +000094#include <cassert>
95#include <cstdint>
Zhongxing Xu318e4032010-07-23 02:15:08 +000096#include <cstdio>
Chandler Carruth3a022472012-12-04 09:13:33 +000097#include <cstdlib>
Eugene Zelenko4f233182018-03-22 00:53:26 +000098#include <memory>
99#include <string>
100#include <tuple>
101#include <utility>
102#include <vector>
Hans Wennborgdcfba332015-10-06 23:40:43 +0000103
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000104using namespace clang;
105
Douglas Gregor16896c42010-10-28 15:44:59 +0000106using llvm::TimeRecord;
107
108namespace {
Eugene Zelenko4f233182018-03-22 00:53:26 +0000109
Douglas Gregor16896c42010-10-28 15:44:59 +0000110 class SimpleTimer {
111 bool WantTiming;
112 TimeRecord Start;
113 std::string Output;
114
Benjamin Kramerf2e5a912010-11-09 20:00:56 +0000115 public:
Douglas Gregor1cbdd952010-11-01 13:48:43 +0000116 explicit SimpleTimer(bool WantTiming) : WantTiming(WantTiming) {
Douglas Gregor16896c42010-10-28 15:44:59 +0000117 if (WantTiming)
Benjamin Kramerf2e5a912010-11-09 20:00:56 +0000118 Start = TimeRecord::getCurrentTime();
Douglas Gregor16896c42010-10-28 15:44:59 +0000119 }
120
Douglas Gregor16896c42010-10-28 15:44:59 +0000121 ~SimpleTimer() {
122 if (WantTiming) {
123 TimeRecord Elapsed = TimeRecord::getCurrentTime();
124 Elapsed -= Start;
125 llvm::errs() << Output << ':';
126 Elapsed.print(Elapsed, llvm::errs());
127 llvm::errs() << '\n';
128 }
129 }
Eugene Zelenko4f233182018-03-22 00:53:26 +0000130
131 void setOutput(const Twine &Output) {
132 if (WantTiming)
133 this->Output = Output.str();
134 }
Douglas Gregor16896c42010-10-28 15:44:59 +0000135 };
Ilya Biryukovaf69e402017-05-23 11:37:52 +0000136
Eugene Zelenko4f233182018-03-22 00:53:26 +0000137} // namespace
Ilya Biryukovaf69e402017-05-23 11:37:52 +0000138
Eugene Zelenko4f233182018-03-22 00:53:26 +0000139template <class T>
140static std::unique_ptr<T> valueOrNull(llvm::ErrorOr<std::unique_ptr<T>> Val) {
141 if (!Val)
142 return nullptr;
143 return std::move(*Val);
144}
145
146template <class T>
147static bool moveOnNoError(llvm::ErrorOr<T> Val, T &Output) {
148 if (!Val)
149 return false;
150 Output = std::move(*Val);
151 return true;
152}
Ted Kremenek06b4f912011-10-27 17:55:18 +0000153
Ilya Biryukov200b3282017-06-21 10:24:58 +0000154/// \brief Get a source buffer for \p MainFilePath, handling all file-to-file
155/// and file-to-buffer remappings inside \p Invocation.
156static std::unique_ptr<llvm::MemoryBuffer>
157getBufferForFileHandlingRemapping(const CompilerInvocation &Invocation,
158 vfs::FileSystem *VFS,
159 StringRef FilePath) {
160 const auto &PreprocessorOpts = Invocation.getPreprocessorOpts();
Ted Kremenekbd307a52011-10-27 19:44:25 +0000161
Ilya Biryukov200b3282017-06-21 10:24:58 +0000162 // Try to determine if the main file has been remapped, either from the
163 // command line (to another file) or directly through the compiler
164 // invocation (to a memory buffer).
165 llvm::MemoryBuffer *Buffer = nullptr;
166 std::unique_ptr<llvm::MemoryBuffer> BufferOwner;
167 auto FileStatus = VFS->status(FilePath);
168 if (FileStatus) {
169 llvm::sys::fs::UniqueID MainFileID = FileStatus->getUniqueID();
Ted Kremenek06b4f912011-10-27 17:55:18 +0000170
Ilya Biryukov200b3282017-06-21 10:24:58 +0000171 // Check whether there is a file-file remapping of the main file
172 for (const auto &RF : PreprocessorOpts.RemappedFiles) {
173 std::string MPath(RF.first);
174 auto MPathStatus = VFS->status(MPath);
175 if (MPathStatus) {
176 llvm::sys::fs::UniqueID MID = MPathStatus->getUniqueID();
177 if (MainFileID == MID) {
178 // We found a remapping. Try to load the resulting, remapped source.
179 BufferOwner = valueOrNull(VFS->getBufferForFile(RF.second));
180 if (!BufferOwner)
181 return nullptr;
182 }
183 }
184 }
185
186 // Check whether there is a file-buffer remapping. It supercedes the
187 // file-file remapping.
188 for (const auto &RB : PreprocessorOpts.RemappedFileBuffers) {
189 std::string MPath(RB.first);
190 auto MPathStatus = VFS->status(MPath);
191 if (MPathStatus) {
192 llvm::sys::fs::UniqueID MID = MPathStatus->getUniqueID();
193 if (MainFileID == MID) {
194 // We found a remapping.
195 BufferOwner.reset();
196 Buffer = const_cast<llvm::MemoryBuffer *>(RB.second);
197 }
198 }
199 }
Ted Kremenek06b4f912011-10-27 17:55:18 +0000200 }
Ted Kremenek06b4f912011-10-27 17:55:18 +0000201
Ilya Biryukov200b3282017-06-21 10:24:58 +0000202 // If the main source file was not remapped, load it now.
203 if (!Buffer && !BufferOwner) {
204 BufferOwner = valueOrNull(VFS->getBufferForFile(FilePath));
205 if (!BufferOwner)
206 return nullptr;
Ted Kremenek06b4f912011-10-27 17:55:18 +0000207 }
Ted Kremenek06b4f912011-10-27 17:55:18 +0000208
Ilya Biryukov200b3282017-06-21 10:24:58 +0000209 if (BufferOwner)
210 return BufferOwner;
211 if (!Buffer)
212 return nullptr;
213 return llvm::MemoryBuffer::getMemBufferCopy(Buffer->getBuffer(), FilePath);
Ted Kremenek06b4f912011-10-27 17:55:18 +0000214}
Ted Kremenek06b4f912011-10-27 17:55:18 +0000215
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000216struct ASTUnit::ASTWriterData {
217 SmallString<128> Buffer;
218 llvm::BitstreamWriter Stream;
219 ASTWriter Writer;
220
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +0000221 ASTWriterData(MemoryBufferCache &PCMCache)
222 : Stream(Buffer), Writer(Stream, Buffer, PCMCache, {}) {}
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000223};
224
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000225void ASTUnit::clearFileLevelDecls() {
Reid Kleckner588c9372014-02-19 23:44:52 +0000226 llvm::DeleteContainerSeconds(FileDecls);
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000227}
228
Douglas Gregorbb420ab2010-08-04 05:53:38 +0000229/// \brief After failing to build a precompiled preamble (due to
230/// errors in the source that occurs in the preamble), the number of
231/// reparses during which we'll skip even trying to precompile the
232/// preamble.
233const unsigned DefaultPreambleRebuildInterval = 5;
234
Douglas Gregor68dbaea2010-11-17 00:13:31 +0000235/// \brief Tracks the number of ASTUnit objects that are currently active.
236///
237/// Used for debugging purposes only.
Benjamin Kramer4527fb22014-03-02 17:08:31 +0000238static std::atomic<unsigned> ActiveASTUnitObjects;
Douglas Gregor68dbaea2010-11-17 00:13:31 +0000239
Douglas Gregord03e8232010-04-05 21:10:19 +0000240ASTUnit::ASTUnit(bool _MainFileIsAST)
Eugene Zelenko4f233182018-03-22 00:53:26 +0000241 : MainFileIsAST(_MainFileIsAST), WantTiming(getenv("LIBCLANG_TIMING")),
242 ShouldCacheCodeCompletionResults(false),
243 IncludeBriefCommentsInCodeCompletion(false), UserFilesAreVolatile(false),
244 UnsafeToFree(false) {
Benjamin Kramer4527fb22014-03-02 17:08:31 +0000245 if (getenv("LIBCLANG_OBJTRACKING"))
246 fprintf(stderr, "+++ %u translation units\n", ++ActiveASTUnitObjects);
Douglas Gregor15ba0b32010-07-30 20:58:08 +0000247}
Douglas Gregord03e8232010-04-05 21:10:19 +0000248
Daniel Dunbar764c0822009-12-01 09:51:01 +0000249ASTUnit::~ASTUnit() {
Douglas Gregor6b930962013-05-03 22:58:43 +0000250 // If we loaded from an AST file, balance out the BeginSourceFile call.
251 if (MainFileIsAST && getDiagnostics().getClient()) {
252 getDiagnostics().getClient()->EndSourceFile();
253 }
254
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000255 clearFileLevelDecls();
256
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000257 // Free the buffers associated with remapped files. We are required to
258 // perform this operation here because we explicitly request that the
259 // compiler instance *not* free these buffers for each invocation of the
260 // parser.
David Blaikieea4395e2017-01-06 19:49:01 +0000261 if (Invocation && OwnsRemappedFileBuffers) {
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000262 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
Alp Toker1b070d22014-07-07 07:47:20 +0000263 for (const auto &RB : PPOpts.RemappedFileBuffers)
264 delete RB.second;
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000265 }
Douglas Gregora0734c52010-08-19 01:33:06 +0000266
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000267 ClearCachedCompletionResults();
268
Benjamin Kramer4527fb22014-03-02 17:08:31 +0000269 if (getenv("LIBCLANG_OBJTRACKING"))
270 fprintf(stderr, "--- %u translation units\n", --ActiveASTUnitObjects);
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000271}
272
David Blaikie41565462017-01-05 19:48:07 +0000273void ASTUnit::setPreprocessor(std::shared_ptr<Preprocessor> PP) {
274 this->PP = std::move(PP);
275}
Argyrios Kyrtzidisda6e0542012-01-17 18:48:07 +0000276
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000277/// \brief Determine the set of code-completion contexts in which this
Douglas Gregor39982192010-08-15 06:18:01 +0000278/// declaration should be shown.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000279static unsigned getDeclShowContexts(const NamedDecl *ND,
Douglas Gregor59cab552010-08-16 23:05:20 +0000280 const LangOptions &LangOpts,
281 bool &IsNestedNameSpecifier) {
282 IsNestedNameSpecifier = false;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000283
Douglas Gregor39982192010-08-15 06:18:01 +0000284 if (isa<UsingShadowDecl>(ND))
George Burgess IV00f70bd2018-03-01 05:43:23 +0000285 ND = ND->getUnderlyingDecl();
Douglas Gregor39982192010-08-15 06:18:01 +0000286 if (!ND)
287 return 0;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000288
Richard Smith697cc9e2012-08-14 03:13:00 +0000289 uint64_t Contexts = 0;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000290 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND) ||
Erik Verbruggen51ee12a2017-09-08 09:31:13 +0000291 isa<ClassTemplateDecl>(ND) || isa<TemplateTemplateParmDecl>(ND) ||
292 isa<TypeAliasTemplateDecl>(ND)) {
Douglas Gregor39982192010-08-15 06:18:01 +0000293 // Types can appear in these contexts.
294 if (LangOpts.CPlusPlus || !isa<TagDecl>(ND))
Richard Smith697cc9e2012-08-14 03:13:00 +0000295 Contexts |= (1LL << CodeCompletionContext::CCC_TopLevel)
296 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
297 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
298 | (1LL << CodeCompletionContext::CCC_Statement)
299 | (1LL << CodeCompletionContext::CCC_Type)
300 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression);
Douglas Gregor39982192010-08-15 06:18:01 +0000301
302 // In C++, types can appear in expressions contexts (for functional casts).
303 if (LangOpts.CPlusPlus)
Richard Smith697cc9e2012-08-14 03:13:00 +0000304 Contexts |= (1LL << CodeCompletionContext::CCC_Expression);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000305
Douglas Gregor39982192010-08-15 06:18:01 +0000306 // In Objective-C, message sends can send interfaces. In Objective-C++,
307 // all types are available due to functional casts.
308 if (LangOpts.CPlusPlus || isa<ObjCInterfaceDecl>(ND))
Richard Smith697cc9e2012-08-14 03:13:00 +0000309 Contexts |= (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000310
Douglas Gregor21325842011-07-07 16:03:39 +0000311 // In Objective-C, you can only be a subclass of another Objective-C class
Alex Lorenzf3df1f72017-11-14 01:46:24 +0000312 if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(ND)) {
313 // Objective-C interfaces can be used in a class property expression.
314 if (ID->getDefinition())
315 Contexts |= (1LL << CodeCompletionContext::CCC_Expression);
Richard Smith697cc9e2012-08-14 03:13:00 +0000316 Contexts |= (1LL << CodeCompletionContext::CCC_ObjCInterfaceName);
Alex Lorenzf3df1f72017-11-14 01:46:24 +0000317 }
Douglas Gregor39982192010-08-15 06:18:01 +0000318
319 // Deal with tag names.
320 if (isa<EnumDecl>(ND)) {
Richard Smith697cc9e2012-08-14 03:13:00 +0000321 Contexts |= (1LL << CodeCompletionContext::CCC_EnumTag);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000322
Douglas Gregor59cab552010-08-16 23:05:20 +0000323 // Part of the nested-name-specifier in C++0x.
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000324 if (LangOpts.CPlusPlus11)
Douglas Gregor59cab552010-08-16 23:05:20 +0000325 IsNestedNameSpecifier = true;
Eugene Zelenko4f233182018-03-22 00:53:26 +0000326 } else if (const auto *Record = dyn_cast<RecordDecl>(ND)) {
Douglas Gregor39982192010-08-15 06:18:01 +0000327 if (Record->isUnion())
Richard Smith697cc9e2012-08-14 03:13:00 +0000328 Contexts |= (1LL << CodeCompletionContext::CCC_UnionTag);
Douglas Gregor39982192010-08-15 06:18:01 +0000329 else
Richard Smith697cc9e2012-08-14 03:13:00 +0000330 Contexts |= (1LL << CodeCompletionContext::CCC_ClassOrStructTag);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000331
Douglas Gregor39982192010-08-15 06:18:01 +0000332 if (LangOpts.CPlusPlus)
Douglas Gregor59cab552010-08-16 23:05:20 +0000333 IsNestedNameSpecifier = true;
Douglas Gregor0ac41382010-09-23 23:01:17 +0000334 } else if (isa<ClassTemplateDecl>(ND))
Douglas Gregor59cab552010-08-16 23:05:20 +0000335 IsNestedNameSpecifier = true;
Douglas Gregor39982192010-08-15 06:18:01 +0000336 } else if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
337 // Values can appear in these contexts.
Richard Smith697cc9e2012-08-14 03:13:00 +0000338 Contexts = (1LL << CodeCompletionContext::CCC_Statement)
339 | (1LL << CodeCompletionContext::CCC_Expression)
340 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
341 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver);
Douglas Gregor39982192010-08-15 06:18:01 +0000342 } else if (isa<ObjCProtocolDecl>(ND)) {
Richard Smith697cc9e2012-08-14 03:13:00 +0000343 Contexts = (1LL << CodeCompletionContext::CCC_ObjCProtocolName);
Douglas Gregor21325842011-07-07 16:03:39 +0000344 } else if (isa<ObjCCategoryDecl>(ND)) {
Richard Smith697cc9e2012-08-14 03:13:00 +0000345 Contexts = (1LL << CodeCompletionContext::CCC_ObjCCategoryName);
Douglas Gregor39982192010-08-15 06:18:01 +0000346 } else if (isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) {
Richard Smith697cc9e2012-08-14 03:13:00 +0000347 Contexts = (1LL << CodeCompletionContext::CCC_Namespace);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000348
Douglas Gregor39982192010-08-15 06:18:01 +0000349 // Part of the nested-name-specifier.
Douglas Gregor59cab552010-08-16 23:05:20 +0000350 IsNestedNameSpecifier = true;
Douglas Gregor39982192010-08-15 06:18:01 +0000351 }
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000352
Douglas Gregor39982192010-08-15 06:18:01 +0000353 return Contexts;
354}
355
Douglas Gregorb14904c2010-08-13 22:48:40 +0000356void ASTUnit::CacheCodeCompletionResults() {
357 if (!TheSema)
358 return;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000359
Douglas Gregor16896c42010-10-28 15:44:59 +0000360 SimpleTimer Timer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +0000361 Timer.setOutput("Cache global code completions for " + getMainFileName());
Douglas Gregorb14904c2010-08-13 22:48:40 +0000362
363 // Clear out the previous results.
364 ClearCachedCompletionResults();
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000365
Douglas Gregorb14904c2010-08-13 22:48:40 +0000366 // Gather the set of global code completions.
Eugene Zelenko4f233182018-03-22 00:53:26 +0000367 using Result = CodeCompletionResult;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000368 SmallVector<Result, 8> Results;
David Blaikieea4395e2017-01-06 19:49:01 +0000369 CachedCompletionAllocator = std::make_shared<GlobalCodeCompletionAllocator>();
Argyrios Kyrtzidis2bafa002012-11-16 03:34:57 +0000370 CodeCompletionTUInfo CCTUInfo(CachedCompletionAllocator);
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +0000371 TheSema->GatherGlobalCodeCompletions(*CachedCompletionAllocator,
Argyrios Kyrtzidis2bafa002012-11-16 03:34:57 +0000372 CCTUInfo, Results);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000373
Douglas Gregorb14904c2010-08-13 22:48:40 +0000374 // Translate global code completions into cached completions.
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000375 llvm::DenseMap<CanQualType, unsigned> CompletionTypes;
Douglas Gregorc3425b12015-07-07 06:20:19 +0000376 CodeCompletionContext CCContext(CodeCompletionContext::CCC_TopLevel);
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000377
Eugene Zelenko4f233182018-03-22 00:53:26 +0000378 for (auto &R : Results) {
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000379 switch (R.Kind) {
Douglas Gregor39982192010-08-15 06:18:01 +0000380 case Result::RK_Declaration: {
Douglas Gregor59cab552010-08-16 23:05:20 +0000381 bool IsNestedNameSpecifier = false;
Douglas Gregor39982192010-08-15 06:18:01 +0000382 CachedCodeCompletionResult CachedResult;
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000383 CachedResult.Completion = R.CreateCodeCompletionString(
Douglas Gregorc3425b12015-07-07 06:20:19 +0000384 *TheSema, CCContext, *CachedCompletionAllocator, CCTUInfo,
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000385 IncludeBriefCommentsInCodeCompletion);
386 CachedResult.ShowInContexts = getDeclShowContexts(
387 R.Declaration, Ctx->getLangOpts(), IsNestedNameSpecifier);
388 CachedResult.Priority = R.Priority;
389 CachedResult.Kind = R.CursorKind;
390 CachedResult.Availability = R.Availability;
Douglas Gregor24747402010-08-16 16:46:30 +0000391
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000392 // Keep track of the type of this completion in an ASTContext-agnostic
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000393 // way.
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000394 QualType UsageType = getDeclUsageType(*Ctx, R.Declaration);
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000395 if (UsageType.isNull()) {
Douglas Gregor24747402010-08-16 16:46:30 +0000396 CachedResult.TypeClass = STC_Void;
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000397 CachedResult.Type = 0;
398 } else {
399 CanQualType CanUsageType
400 = Ctx->getCanonicalType(UsageType.getUnqualifiedType());
401 CachedResult.TypeClass = getSimplifiedTypeClass(CanUsageType);
402
403 // Determine whether we have already seen this type. If so, we save
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000404 // ourselves the work of formatting the type string by using the
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000405 // temporary, CanQualType-based hash table to find the associated value.
406 unsigned &TypeValue = CompletionTypes[CanUsageType];
407 if (TypeValue == 0) {
408 TypeValue = CompletionTypes.size();
409 CachedCompletionTypes[QualType(CanUsageType).getAsString()]
410 = TypeValue;
411 }
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000412
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000413 CachedResult.Type = TypeValue;
Douglas Gregor24747402010-08-16 16:46:30 +0000414 }
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000415
Douglas Gregor39982192010-08-15 06:18:01 +0000416 CachedCompletionResults.push_back(CachedResult);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000417
Douglas Gregor59cab552010-08-16 23:05:20 +0000418 /// Handle nested-name-specifiers in C++.
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000419 if (TheSema->Context.getLangOpts().CPlusPlus && IsNestedNameSpecifier &&
420 !R.StartsNestedNameSpecifier) {
Douglas Gregor59cab552010-08-16 23:05:20 +0000421 // The contexts in which a nested-name-specifier can appear in C++.
Richard Smith697cc9e2012-08-14 03:13:00 +0000422 uint64_t NNSContexts
423 = (1LL << CodeCompletionContext::CCC_TopLevel)
424 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
425 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
426 | (1LL << CodeCompletionContext::CCC_Statement)
427 | (1LL << CodeCompletionContext::CCC_Expression)
428 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
429 | (1LL << CodeCompletionContext::CCC_EnumTag)
430 | (1LL << CodeCompletionContext::CCC_UnionTag)
431 | (1LL << CodeCompletionContext::CCC_ClassOrStructTag)
432 | (1LL << CodeCompletionContext::CCC_Type)
433 | (1LL << CodeCompletionContext::CCC_PotentiallyQualifiedName)
434 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression);
Douglas Gregor59cab552010-08-16 23:05:20 +0000435
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000436 if (isa<NamespaceDecl>(R.Declaration) ||
437 isa<NamespaceAliasDecl>(R.Declaration))
Richard Smith697cc9e2012-08-14 03:13:00 +0000438 NNSContexts |= (1LL << CodeCompletionContext::CCC_Namespace);
Douglas Gregor59cab552010-08-16 23:05:20 +0000439
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000440 if (unsigned RemainingContexts
Douglas Gregor59cab552010-08-16 23:05:20 +0000441 = NNSContexts & ~CachedResult.ShowInContexts) {
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000442 // If there any contexts where this completion can be a
443 // nested-name-specifier but isn't already an option, create a
Douglas Gregor59cab552010-08-16 23:05:20 +0000444 // nested-name-specifier completion.
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000445 R.StartsNestedNameSpecifier = true;
446 CachedResult.Completion = R.CreateCodeCompletionString(
Douglas Gregorc3425b12015-07-07 06:20:19 +0000447 *TheSema, CCContext, *CachedCompletionAllocator, CCTUInfo,
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000448 IncludeBriefCommentsInCodeCompletion);
Douglas Gregor59cab552010-08-16 23:05:20 +0000449 CachedResult.ShowInContexts = RemainingContexts;
450 CachedResult.Priority = CCP_NestedNameSpecifier;
451 CachedResult.TypeClass = STC_Void;
452 CachedResult.Type = 0;
453 CachedCompletionResults.push_back(CachedResult);
454 }
455 }
Douglas Gregorb14904c2010-08-13 22:48:40 +0000456 break;
Douglas Gregor39982192010-08-15 06:18:01 +0000457 }
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000458
Douglas Gregorb14904c2010-08-13 22:48:40 +0000459 case Result::RK_Keyword:
460 case Result::RK_Pattern:
461 // Ignore keywords and patterns; we don't care, since they are so
462 // easily regenerated.
463 break;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000464
Douglas Gregorb14904c2010-08-13 22:48:40 +0000465 case Result::RK_Macro: {
466 CachedCodeCompletionResult CachedResult;
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000467 CachedResult.Completion = R.CreateCodeCompletionString(
Douglas Gregorc3425b12015-07-07 06:20:19 +0000468 *TheSema, CCContext, *CachedCompletionAllocator, CCTUInfo,
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000469 IncludeBriefCommentsInCodeCompletion);
Douglas Gregorb14904c2010-08-13 22:48:40 +0000470 CachedResult.ShowInContexts
Richard Smith697cc9e2012-08-14 03:13:00 +0000471 = (1LL << CodeCompletionContext::CCC_TopLevel)
472 | (1LL << CodeCompletionContext::CCC_ObjCInterface)
473 | (1LL << CodeCompletionContext::CCC_ObjCImplementation)
474 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
475 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
476 | (1LL << CodeCompletionContext::CCC_Statement)
477 | (1LL << CodeCompletionContext::CCC_Expression)
478 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
479 | (1LL << CodeCompletionContext::CCC_MacroNameUse)
480 | (1LL << CodeCompletionContext::CCC_PreprocessorExpression)
481 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
482 | (1LL << CodeCompletionContext::CCC_OtherWithMacros);
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000483
484 CachedResult.Priority = R.Priority;
485 CachedResult.Kind = R.CursorKind;
486 CachedResult.Availability = R.Availability;
Douglas Gregor6e240332010-08-16 16:18:59 +0000487 CachedResult.TypeClass = STC_Void;
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000488 CachedResult.Type = 0;
Douglas Gregorb14904c2010-08-13 22:48:40 +0000489 CachedCompletionResults.push_back(CachedResult);
490 break;
491 }
492 }
Douglas Gregorb14904c2010-08-13 22:48:40 +0000493 }
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000494
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000495 // Save the current top-level hash value.
496 CompletionCacheTopLevelHashValue = CurrentTopLevelHashValue;
Douglas Gregorb14904c2010-08-13 22:48:40 +0000497}
498
499void ASTUnit::ClearCachedCompletionResults() {
Douglas Gregorb14904c2010-08-13 22:48:40 +0000500 CachedCompletionResults.clear();
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000501 CachedCompletionTypes.clear();
Craig Topper49a27902014-05-22 04:46:25 +0000502 CachedCompletionAllocator = nullptr;
Douglas Gregorb14904c2010-08-13 22:48:40 +0000503}
504
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000505namespace {
506
Sebastian Redl2c499f62010-08-18 23:56:43 +0000507/// \brief Gathers information from ASTReader that will be used to initialize
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000508/// a Preprocessor.
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000509class ASTInfoCollector : public ASTReaderListener {
Douglas Gregor83297df2011-09-01 23:39:15 +0000510 Preprocessor &PP;
Richard Smithdbafb6c2017-06-29 23:23:46 +0000511 ASTContext *Context;
Richard Smith18934752017-06-06 00:32:01 +0000512 HeaderSearchOptions &HSOpts;
513 PreprocessorOptions &PPOpts;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000514 LangOptions &LangOpt;
Alp Toker80758082014-07-06 05:26:44 +0000515 std::shared_ptr<TargetOptions> &TargetOpts;
Dylan Noblesmithc95d8192012-02-20 14:00:23 +0000516 IntrusiveRefCntPtr<TargetInfo> &Target;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000517 unsigned &Counter;
Eugene Zelenko4f233182018-03-22 00:53:26 +0000518 bool InitializedLanguage = false;
Mike Stump11289f42009-09-09 15:08:12 +0000519
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000520public:
Richard Smithdbafb6c2017-06-29 23:23:46 +0000521 ASTInfoCollector(Preprocessor &PP, ASTContext *Context,
Richard Smith18934752017-06-06 00:32:01 +0000522 HeaderSearchOptions &HSOpts, PreprocessorOptions &PPOpts,
523 LangOptions &LangOpt,
Alp Toker80758082014-07-06 05:26:44 +0000524 std::shared_ptr<TargetOptions> &TargetOpts,
525 IntrusiveRefCntPtr<TargetInfo> &Target, unsigned &Counter)
Richard Smith18934752017-06-06 00:32:01 +0000526 : PP(PP), Context(Context), HSOpts(HSOpts), PPOpts(PPOpts),
527 LangOpt(LangOpt), TargetOpts(TargetOpts), Target(Target),
Eugene Zelenko4f233182018-03-22 00:53:26 +0000528 Counter(Counter) {}
Mike Stump11289f42009-09-09 15:08:12 +0000529
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000530 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
531 bool AllowCompatibleDifferences) override {
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000532 if (InitializedLanguage)
Douglas Gregor83297df2011-09-01 23:39:15 +0000533 return false;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000534
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000535 LangOpt = LangOpts;
536 InitializedLanguage = true;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000537
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000538 updated();
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000539 return false;
540 }
Mike Stump11289f42009-09-09 15:08:12 +0000541
Eugene Zelenko4f233182018-03-22 00:53:26 +0000542 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
543 StringRef SpecificModuleCachePath,
544 bool Complain) override {
Richard Smith18934752017-06-06 00:32:01 +0000545 this->HSOpts = HSOpts;
546 return false;
547 }
548
Eugene Zelenko4f233182018-03-22 00:53:26 +0000549 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts, bool Complain,
550 std::string &SuggestedPredefines) override {
Richard Smith18934752017-06-06 00:32:01 +0000551 this->PPOpts = PPOpts;
552 return false;
553 }
554
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000555 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
556 bool AllowCompatibleDifferences) override {
Douglas Gregor83297df2011-09-01 23:39:15 +0000557 // If we've already initialized the target, don't do it again.
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000558 if (Target)
Douglas Gregor83297df2011-09-01 23:39:15 +0000559 return false;
Alp Toker80758082014-07-06 05:26:44 +0000560
561 this->TargetOpts = std::make_shared<TargetOptions>(TargetOpts);
562 Target =
563 TargetInfo::CreateTargetInfo(PP.getDiagnostics(), this->TargetOpts);
Argyrios Kyrtzidis9e1fb562012-09-14 20:24:53 +0000564
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000565 updated();
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000566 return false;
567 }
Mike Stump11289f42009-09-09 15:08:12 +0000568
Craig Topperafa7cb32014-03-13 06:07:04 +0000569 void ReadCounter(const serialization::ModuleFile &M,
570 unsigned Value) override {
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000571 Counter = Value;
572 }
Argyrios Kyrtzidis9e1fb562012-09-14 20:24:53 +0000573
574private:
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000575 void updated() {
576 if (!Target || !InitializedLanguage)
577 return;
578
579 // Inform the target of the language options.
580 //
581 // FIXME: We shouldn't need to do this, the target should be immutable once
582 // created. This complexity should be lifted elsewhere.
Alp Toker74437972014-07-06 05:14:24 +0000583 Target->adjust(LangOpt);
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000584
585 // Initialize the preprocessor.
586 PP.Initialize(*Target);
587
Richard Smithdbafb6c2017-06-29 23:23:46 +0000588 if (!Context)
589 return;
590
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000591 // Initialize the ASTContext
Richard Smithdbafb6c2017-06-29 23:23:46 +0000592 Context->InitBuiltinTypes(*Target);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +0000593
Vedant Kumarfd9fad92017-08-25 18:07:03 +0000594 // Adjust printing policy based on language options.
595 Context->setPrintingPolicy(PrintingPolicy(LangOpt));
596
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +0000597 // We didn't have access to the comment options when the ASTContext was
598 // constructed, so register them now.
Richard Smithdbafb6c2017-06-29 23:23:46 +0000599 Context->getCommentCommandTraits().registerCommentOptions(
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +0000600 LangOpt.CommentOpts);
Argyrios Kyrtzidis9e1fb562012-09-14 20:24:53 +0000601 }
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000602};
603
Eugene Zelenko4f233182018-03-22 00:53:26 +0000604/// \brief Diagnostic consumer that saves each diagnostic it is given.
David Blaikief18d91a2011-09-26 00:01:39 +0000605class StoredDiagnosticConsumer : public DiagnosticConsumer {
Ilya Biryukov200b3282017-06-21 10:24:58 +0000606 SmallVectorImpl<StoredDiagnostic> *StoredDiags;
607 SmallVectorImpl<ASTUnit::StandaloneDiagnostic> *StandaloneDiags;
Eugene Zelenko4f233182018-03-22 00:53:26 +0000608 const LangOptions *LangOpts = nullptr;
609 SourceManager *SourceMgr = nullptr;
Douglas Gregor6b930962013-05-03 22:58:43 +0000610
Douglas Gregor33cdd812010-02-18 18:08:43 +0000611public:
Ilya Biryukov200b3282017-06-21 10:24:58 +0000612 StoredDiagnosticConsumer(
613 SmallVectorImpl<StoredDiagnostic> *StoredDiags,
614 SmallVectorImpl<ASTUnit::StandaloneDiagnostic> *StandaloneDiags)
Eugene Zelenko4f233182018-03-22 00:53:26 +0000615 : StoredDiags(StoredDiags), StandaloneDiags(StandaloneDiags) {
Ilya Biryukov200b3282017-06-21 10:24:58 +0000616 assert((StoredDiags || StandaloneDiags) &&
617 "No output collections were passed to StoredDiagnosticConsumer.");
618 }
Douglas Gregor6b930962013-05-03 22:58:43 +0000619
Craig Topperafa7cb32014-03-13 06:07:04 +0000620 void BeginSourceFile(const LangOptions &LangOpts,
Craig Topper49a27902014-05-22 04:46:25 +0000621 const Preprocessor *PP = nullptr) override {
Ilya Biryukov200b3282017-06-21 10:24:58 +0000622 this->LangOpts = &LangOpts;
Douglas Gregor6b930962013-05-03 22:58:43 +0000623 if (PP)
624 SourceMgr = &PP->getSourceManager();
625 }
626
Craig Topperafa7cb32014-03-13 06:07:04 +0000627 void HandleDiagnostic(DiagnosticsEngine::Level Level,
628 const Diagnostic &Info) override;
Douglas Gregor33cdd812010-02-18 18:08:43 +0000629};
630
631/// \brief RAII object that optionally captures diagnostics, if
632/// there is no diagnostic client to capture them already.
633class CaptureDroppedDiagnostics {
David Blaikie9c902b52011-09-25 23:23:43 +0000634 DiagnosticsEngine &Diags;
David Blaikief18d91a2011-09-26 00:01:39 +0000635 StoredDiagnosticConsumer Client;
Eugene Zelenko4f233182018-03-22 00:53:26 +0000636 DiagnosticConsumer *PreviousClient = nullptr;
Alexander Kornienko41c247a2014-11-17 23:46:02 +0000637 std::unique_ptr<DiagnosticConsumer> OwningPreviousClient;
Douglas Gregor33cdd812010-02-18 18:08:43 +0000638
639public:
Eugene Zelenko4f233182018-03-22 00:53:26 +0000640 CaptureDroppedDiagnostics(
641 bool RequestCapture, DiagnosticsEngine &Diags,
642 SmallVectorImpl<StoredDiagnostic> *StoredDiags,
643 SmallVectorImpl<ASTUnit::StandaloneDiagnostic> *StandaloneDiags)
644 : Diags(Diags), Client(StoredDiags, StandaloneDiags) {
Craig Topper49a27902014-05-22 04:46:25 +0000645 if (RequestCapture || Diags.getClient() == nullptr) {
Alexander Kornienko41c247a2014-11-17 23:46:02 +0000646 OwningPreviousClient = Diags.takeClient();
647 PreviousClient = Diags.getClient();
648 Diags.setClient(&Client, false);
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000649 }
Douglas Gregor33cdd812010-02-18 18:08:43 +0000650 }
651
652 ~CaptureDroppedDiagnostics() {
Alexander Kornienko41c247a2014-11-17 23:46:02 +0000653 if (Diags.getClient() == &Client)
654 Diags.setClient(PreviousClient, !!OwningPreviousClient.release());
Douglas Gregor33cdd812010-02-18 18:08:43 +0000655 }
656};
657
Eugene Zelenko4f233182018-03-22 00:53:26 +0000658} // namespace
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000659
Ilya Biryukov200b3282017-06-21 10:24:58 +0000660static ASTUnit::StandaloneDiagnostic
661makeStandaloneDiagnostic(const LangOptions &LangOpts,
662 const StoredDiagnostic &InDiag);
663
David Blaikief18d91a2011-09-26 00:01:39 +0000664void StoredDiagnosticConsumer::HandleDiagnostic(DiagnosticsEngine::Level Level,
Ilya Biryukov200b3282017-06-21 10:24:58 +0000665 const Diagnostic &Info) {
Argyrios Kyrtzidisc79346a2010-11-18 20:06:46 +0000666 // Default implementation (Warnings/errors count).
David Blaikiee2eefae2011-09-25 23:39:51 +0000667 DiagnosticConsumer::HandleDiagnostic(Level, Info);
Argyrios Kyrtzidisc79346a2010-11-18 20:06:46 +0000668
Douglas Gregor6b930962013-05-03 22:58:43 +0000669 // Only record the diagnostic if it's part of the source manager we know
670 // about. This effectively drops diagnostics from modules we're building.
671 // FIXME: In the long run, ee don't want to drop source managers from modules.
Ilya Biryukov200b3282017-06-21 10:24:58 +0000672 if (!Info.hasSourceManager() || &Info.getSourceManager() == SourceMgr) {
673 StoredDiagnostic *ResultDiag = nullptr;
674 if (StoredDiags) {
675 StoredDiags->emplace_back(Level, Info);
676 ResultDiag = &StoredDiags->back();
677 }
678
679 if (StandaloneDiags) {
Eugene Zelenko4f233182018-03-22 00:53:26 +0000680 llvm::Optional<StoredDiagnostic> StoredDiag = None;
Ilya Biryukov200b3282017-06-21 10:24:58 +0000681 if (!ResultDiag) {
682 StoredDiag.emplace(Level, Info);
683 ResultDiag = StoredDiag.getPointer();
684 }
685 StandaloneDiags->push_back(
686 makeStandaloneDiagnostic(*LangOpts, *ResultDiag));
687 }
688 }
Douglas Gregor33cdd812010-02-18 18:08:43 +0000689}
690
Argyrios Kyrtzidisa38cb202017-01-30 06:05:58 +0000691IntrusiveRefCntPtr<ASTReader> ASTUnit::getASTReader() const {
692 return Reader;
693}
694
Argyrios Kyrtzidis1c7455f2013-05-10 01:28:51 +0000695ASTMutationListener *ASTUnit::getASTMutationListener() {
696 if (WriterData)
697 return &WriterData->Writer;
Craig Topper49a27902014-05-22 04:46:25 +0000698 return nullptr;
Argyrios Kyrtzidis1c7455f2013-05-10 01:28:51 +0000699}
700
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000701ASTDeserializationListener *ASTUnit::getDeserializationListener() {
702 if (WriterData)
703 return &WriterData->Writer;
Craig Topper49a27902014-05-22 04:46:25 +0000704 return nullptr;
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000705}
706
Rafael Espindola16e1ba12014-08-26 20:17:44 +0000707std::unique_ptr<llvm::MemoryBuffer>
708ASTUnit::getBufferForFile(StringRef Filename, std::string *ErrorStr) {
Chris Lattner5159f612010-11-23 08:35:12 +0000709 assert(FileMgr);
Benjamin Kramera8857962014-10-26 22:44:13 +0000710 auto Buffer = FileMgr->getBufferForFile(Filename);
711 if (Buffer)
712 return std::move(*Buffer);
713 if (ErrorStr)
714 *ErrorStr = Buffer.getError().message();
715 return nullptr;
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000716}
717
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000718/// \brief Configure the diagnostics object for use with ASTUnit.
Justin Bognerd512c1e2014-10-15 00:33:06 +0000719void ASTUnit::ConfigureDiags(IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000720 ASTUnit &AST, bool CaptureDiagnostics) {
Justin Bognerd512c1e2014-10-15 00:33:06 +0000721 assert(Diags.get() && "no DiagnosticsEngine was provided");
722 if (CaptureDiagnostics)
Ilya Biryukov200b3282017-06-21 10:24:58 +0000723 Diags->setClient(new StoredDiagnosticConsumer(&AST.StoredDiagnostics, nullptr));
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000724}
725
David Blaikie6f7382d2014-08-10 19:08:04 +0000726std::unique_ptr<ASTUnit> ASTUnit::LoadFromASTFile(
Adrian Prantl6b21ab22015-08-27 19:46:20 +0000727 const std::string &Filename, const PCHContainerReader &PCHContainerRdr,
Richard Smithdbafb6c2017-06-29 23:23:46 +0000728 WhatToLoad ToLoad, IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Adrian Prantl6b21ab22015-08-27 19:46:20 +0000729 const FileSystemOptions &FileSystemOpts, bool UseDebugInfo,
730 bool OnlyLocalDecls, ArrayRef<RemappedFile> RemappedFiles,
731 bool CaptureDiagnostics, bool AllowPCHWithCompilerErrors,
732 bool UserFilesAreVolatile) {
Ahmed Charlesb8984322014-03-07 20:03:18 +0000733 std::unique_ptr<ASTUnit> AST(new ASTUnit(true));
Ted Kremenek4422bfe2011-03-18 02:06:56 +0000734
735 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +0000736 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
737 ASTUnitCleanup(AST.get());
David Blaikie9c902b52011-09-25 23:23:43 +0000738 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
Eugene Zelenko4f233182018-03-22 00:53:26 +0000739 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine>>
Alp Tokerf994cef2014-07-05 03:08:06 +0000740 DiagCleanup(Diags.get());
Ted Kremenek4422bfe2011-03-18 02:06:56 +0000741
Justin Bognerdbbcb112014-10-14 23:36:06 +0000742 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000743
Richard Smithab755972017-06-05 18:10:11 +0000744 AST->LangOpts = std::make_shared<LangOptions>();
Douglas Gregor16bef852009-10-16 20:01:17 +0000745 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000746 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor7f95d262010-04-05 23:52:57 +0000747 AST->Diagnostics = Diags;
Ben Langmuir8832c062014-04-15 18:16:25 +0000748 IntrusiveRefCntPtr<vfs::FileSystem> VFS = vfs::getRealFileSystem();
749 AST->FileMgr = new FileManager(FileSystemOpts, VFS);
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +0000750 AST->UserFilesAreVolatile = UserFilesAreVolatile;
Ted Kremenek5e14d392011-03-21 18:40:17 +0000751 AST->SourceMgr = new SourceManager(AST->getDiagnostics(),
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +0000752 AST->getFileManager(),
753 UserFilesAreVolatile);
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +0000754 AST->PCMCache = new MemoryBufferCache;
David Blaikie9c28cb32017-01-06 01:04:46 +0000755 AST->HSOpts = std::make_shared<HeaderSearchOptions>();
Adrian Prantlfb2398d2015-07-17 01:19:54 +0000756 AST->HSOpts->ModuleFormat = PCHContainerRdr.getFormat();
Douglas Gregorb85b9cc2012-10-24 16:19:39 +0000757 AST->HeaderInfo.reset(new HeaderSearch(AST->HSOpts,
Manuel Klimek1f76c4e2013-10-24 07:51:24 +0000758 AST->getSourceManager(),
Douglas Gregor1fb5c3a2011-12-31 04:05:44 +0000759 AST->getDiagnostics(),
Richard Smithab755972017-06-05 18:10:11 +0000760 AST->getLangOpts(),
Craig Topper49a27902014-05-22 04:46:25 +0000761 /*Target=*/nullptr));
Richard Smith18934752017-06-06 00:32:01 +0000762 AST->PPOpts = std::make_shared<PreprocessorOptions>();
Dmitri Gribenkoc444b572014-02-08 00:38:15 +0000763
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000764 for (const auto &RemappedFile : RemappedFiles)
Richard Smith18934752017-06-06 00:32:01 +0000765 AST->PPOpts->addRemappedFile(RemappedFile.first, RemappedFile.second);
Dmitri Gribenkoc444b572014-02-08 00:38:15 +0000766
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000767 // Gather Info for preprocessor construction later on.
Mike Stump11289f42009-09-09 15:08:12 +0000768
David Blaikie6f7382d2014-08-10 19:08:04 +0000769 HeaderSearch &HeaderInfo = *AST->HeaderInfo;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000770 unsigned Counter;
771
David Blaikie41565462017-01-05 19:48:07 +0000772 AST->PP = std::make_shared<Preprocessor>(
Richard Smith18934752017-06-06 00:32:01 +0000773 AST->PPOpts, AST->getDiagnostics(), *AST->LangOpts,
Richard Smith5d2ed482017-06-09 19:22:32 +0000774 AST->getSourceManager(), *AST->PCMCache, HeaderInfo, AST->ModuleLoader,
David Blaikie41565462017-01-05 19:48:07 +0000775 /*IILookup=*/nullptr,
776 /*OwnsHeaderSearch=*/false);
Douglas Gregore8bbc122011-09-02 00:18:52 +0000777 Preprocessor &PP = *AST->PP;
778
Richard Smithdbafb6c2017-06-29 23:23:46 +0000779 if (ToLoad >= LoadASTOnly)
780 AST->Ctx = new ASTContext(*AST->LangOpts, AST->getSourceManager(),
781 PP.getIdentifierTable(), PP.getSelectorTable(),
782 PP.getBuiltinInfo());
Douglas Gregor83297df2011-09-01 23:39:15 +0000783
Argyrios Kyrtzidis945a8192012-09-15 01:10:20 +0000784 bool disableValid = false;
785 if (::getenv("LIBCLANG_DISABLE_PCH_VALIDATION"))
786 disableValid = true;
Eugene Zelenko4f233182018-03-22 00:53:26 +0000787 AST->Reader = new ASTReader(PP, AST->Ctx.get(), PCHContainerRdr, {},
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000788 /*isysroot=*/"",
789 /*DisableValidation=*/disableValid,
790 AllowPCHWithCompilerErrors);
Ted Kremenek2159b8d2011-05-04 23:27:12 +0000791
David Blaikie2721c322014-08-10 16:54:39 +0000792 AST->Reader->setListener(llvm::make_unique<ASTInfoCollector>(
Richard Smithdbafb6c2017-06-29 23:23:46 +0000793 *AST->PP, AST->Ctx.get(), *AST->HSOpts, *AST->PPOpts, *AST->LangOpts,
Richard Smith18934752017-06-06 00:32:01 +0000794 AST->TargetOpts, AST->Target, Counter));
Daniel Dunbar2d9c7402009-09-03 05:59:35 +0000795
Argyrios Kyrtzidisf0b4cd12015-03-03 08:04:19 +0000796 // Attach the AST reader to the AST context as an external AST
797 // source, so that declarations will be deserialized from the
798 // AST file as needed.
799 // We need the external source to be set up before we read the AST, because
800 // eagerly-deserialized declarations may use it.
Richard Smithdbafb6c2017-06-29 23:23:46 +0000801 if (AST->Ctx)
802 AST->Ctx->setExternalSource(AST->Reader);
Argyrios Kyrtzidisf0b4cd12015-03-03 08:04:19 +0000803
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000804 switch (AST->Reader->ReadAST(Filename, serialization::MK_MainFile,
Argyrios Kyrtzidis2ec29362012-11-15 18:57:22 +0000805 SourceLocation(), ASTReader::ARR_None)) {
Sebastian Redl2c499f62010-08-18 23:56:43 +0000806 case ASTReader::Success:
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000807 break;
Mike Stump11289f42009-09-09 15:08:12 +0000808
Sebastian Redl2c499f62010-08-18 23:56:43 +0000809 case ASTReader::Failure:
Douglas Gregor7029ce12013-03-19 00:28:20 +0000810 case ASTReader::Missing:
Douglas Gregorc9ad5fb2012-10-22 22:50:17 +0000811 case ASTReader::OutOfDate:
812 case ASTReader::VersionMismatch:
813 case ASTReader::ConfigurationMismatch:
814 case ASTReader::HadErrors:
Douglas Gregord03e8232010-04-05 21:10:19 +0000815 AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
Craig Topper49a27902014-05-22 04:46:25 +0000816 return nullptr;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000817 }
Mike Stump11289f42009-09-09 15:08:12 +0000818
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000819 AST->OriginalSourceFile = AST->Reader->getOriginalSourceFile();
Daniel Dunbara8a50932009-12-02 08:44:16 +0000820
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000821 PP.setCounterValue(Counter);
Mike Stump11289f42009-09-09 15:08:12 +0000822
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000823 // Create an AST consumer, even though it isn't used.
Richard Smithdbafb6c2017-06-29 23:23:46 +0000824 if (ToLoad >= LoadASTOnly)
825 AST->Consumer.reset(new ASTConsumer);
826
Sebastian Redl2c499f62010-08-18 23:56:43 +0000827 // Create a semantic analysis object and tell the AST reader about it.
Richard Smithdbafb6c2017-06-29 23:23:46 +0000828 if (ToLoad >= LoadEverything) {
829 AST->TheSema.reset(new Sema(PP, *AST->Ctx, *AST->Consumer));
830 AST->TheSema->Initialize();
831 AST->Reader->InitializeSema(*AST->TheSema);
832 }
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000833
Douglas Gregor6b930962013-05-03 22:58:43 +0000834 // Tell the diagnostic client that we have started a source file.
Richard Smithdbafb6c2017-06-29 23:23:46 +0000835 AST->getDiagnostics().getClient()->BeginSourceFile(PP.getLangOpts(), &PP);
Douglas Gregor6b930962013-05-03 22:58:43 +0000836
David Blaikie6f7382d2014-08-10 19:08:04 +0000837 return AST;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000838}
Daniel Dunbar764c0822009-12-01 09:51:01 +0000839
Ilya Biryukov200b3282017-06-21 10:24:58 +0000840/// \brief Add the given macro to the hash of all top-level entities.
Eugene Zelenko4f233182018-03-22 00:53:26 +0000841static void AddDefinedMacroToHash(const Token &MacroNameTok, unsigned &Hash) {
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000842 Hash = llvm::djbHash(MacroNameTok.getIdentifierInfo()->getName(), Hash);
Ilya Biryukov200b3282017-06-21 10:24:58 +0000843}
844
Eugene Zelenko4f233182018-03-22 00:53:26 +0000845namespace {
846
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000847/// \brief Preprocessor callback class that updates a hash value with the names
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000848/// of all macros that have been defined by the translation unit.
849class MacroDefinitionTrackerPPCallbacks : public PPCallbacks {
850 unsigned &Hash;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000851
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000852public:
Eugene Zelenko4f233182018-03-22 00:53:26 +0000853 explicit MacroDefinitionTrackerPPCallbacks(unsigned &Hash) : Hash(Hash) {}
Craig Topperafa7cb32014-03-13 06:07:04 +0000854
855 void MacroDefined(const Token &MacroNameTok,
856 const MacroDirective *MD) override {
Ilya Biryukov200b3282017-06-21 10:24:58 +0000857 AddDefinedMacroToHash(MacroNameTok, Hash);
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000858 }
859};
860
Eugene Zelenko4f233182018-03-22 00:53:26 +0000861} // namespace
862
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000863/// \brief Add the given declaration to the hash of all top-level entities.
Eugene Zelenko4f233182018-03-22 00:53:26 +0000864static void AddTopLevelDeclarationToHash(Decl *D, unsigned &Hash) {
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000865 if (!D)
866 return;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000867
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000868 DeclContext *DC = D->getDeclContext();
869 if (!DC)
870 return;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000871
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000872 if (!(DC->isTranslationUnit() || DC->getLookupParent()->isTranslationUnit()))
873 return;
874
Eugene Zelenko4f233182018-03-22 00:53:26 +0000875 if (const auto *ND = dyn_cast<NamedDecl>(D)) {
876 if (const auto *EnumD = dyn_cast<EnumDecl>(D)) {
Argyrios Kyrtzidisca5c7be2013-10-15 17:37:55 +0000877 // For an unscoped enum include the enumerators in the hash since they
878 // enter the top-level namespace.
879 if (!EnumD->isScoped()) {
Aaron Ballman23a6dcb2014-03-08 18:45:14 +0000880 for (const auto *EI : EnumD->enumerators()) {
881 if (EI->getIdentifier())
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000882 Hash = llvm::djbHash(EI->getIdentifier()->getName(), Hash);
Argyrios Kyrtzidisca5c7be2013-10-15 17:37:55 +0000883 }
884 }
885 }
886
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000887 if (ND->getIdentifier())
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000888 Hash = llvm::djbHash(ND->getIdentifier()->getName(), Hash);
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000889 else if (DeclarationName Name = ND->getDeclName()) {
890 std::string NameStr = Name.getAsString();
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000891 Hash = llvm::djbHash(NameStr, Hash);
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000892 }
893 return;
Argyrios Kyrtzidis48d88de2013-06-24 21:19:12 +0000894 }
895
Eugene Zelenko4f233182018-03-22 00:53:26 +0000896 if (const auto *ImportD = dyn_cast<ImportDecl>(D)) {
897 if (const Module *Mod = ImportD->getImportedModule()) {
Argyrios Kyrtzidis48d88de2013-06-24 21:19:12 +0000898 std::string ModName = Mod->getFullModuleName();
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000899 Hash = llvm::djbHash(ModName, Hash);
Argyrios Kyrtzidis48d88de2013-06-24 21:19:12 +0000900 }
901 return;
902 }
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000903}
904
Eugene Zelenko4f233182018-03-22 00:53:26 +0000905namespace {
906
Daniel Dunbar644dca02009-12-04 08:17:33 +0000907class TopLevelDeclTrackerConsumer : public ASTConsumer {
908 ASTUnit &Unit;
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000909 unsigned &Hash;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000910
Daniel Dunbar644dca02009-12-04 08:17:33 +0000911public:
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000912 TopLevelDeclTrackerConsumer(ASTUnit &_Unit, unsigned &Hash)
Eugene Zelenko4f233182018-03-22 00:53:26 +0000913 : Unit(_Unit), Hash(Hash) {
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000914 Hash = 0;
915 }
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000916
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000917 void handleTopLevelDecl(Decl *D) {
Argyrios Kyrtzidis516eec22011-11-16 02:35:10 +0000918 if (!D)
919 return;
920
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000921 // FIXME: Currently ObjC method declarations are incorrectly being
922 // reported as top-level declarations, even though their DeclContext
923 // is the containing ObjC @interface/@implementation. This is a
924 // fundamental problem in the parser right now.
925 if (isa<ObjCMethodDecl>(D))
926 return;
927
928 AddTopLevelDeclarationToHash(D, Hash);
929 Unit.addTopLevelDecl(D);
930
931 handleFileLevelDecl(D);
932 }
933
934 void handleFileLevelDecl(Decl *D) {
935 Unit.addFileLevelDecl(D);
Eugene Zelenko4f233182018-03-22 00:53:26 +0000936 if (auto *NSD = dyn_cast<NamespaceDecl>(D)) {
Aaron Ballman629afae2014-03-07 19:56:05 +0000937 for (auto *I : NSD->decls())
938 handleFileLevelDecl(I);
Ted Kremenekacc59c32010-05-03 20:16:35 +0000939 }
Daniel Dunbar644dca02009-12-04 08:17:33 +0000940 }
Sebastian Redleaa4ade2010-08-11 18:52:41 +0000941
Craig Topperafa7cb32014-03-13 06:07:04 +0000942 bool HandleTopLevelDecl(DeclGroupRef D) override {
Eugene Zelenko4f233182018-03-22 00:53:26 +0000943 for (auto *TopLevelDecl : D)
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000944 handleTopLevelDecl(TopLevelDecl);
Argyrios Kyrtzidis841dd882011-11-18 00:26:59 +0000945 return true;
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000946 }
947
Sebastian Redleaa4ade2010-08-11 18:52:41 +0000948 // We're not interested in "interesting" decls.
Craig Topperafa7cb32014-03-13 06:07:04 +0000949 void HandleInterestingDecl(DeclGroupRef) override {}
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000950
Craig Topperafa7cb32014-03-13 06:07:04 +0000951 void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) override {
Eugene Zelenko4f233182018-03-22 00:53:26 +0000952 for (auto *TopLevelDecl : D)
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000953 handleTopLevelDecl(TopLevelDecl);
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000954 }
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000955
Craig Topperafa7cb32014-03-13 06:07:04 +0000956 ASTMutationListener *GetASTMutationListener() override {
Argyrios Kyrtzidis1c7455f2013-05-10 01:28:51 +0000957 return Unit.getASTMutationListener();
958 }
959
Craig Topperafa7cb32014-03-13 06:07:04 +0000960 ASTDeserializationListener *GetASTDeserializationListener() override {
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000961 return Unit.getDeserializationListener();
962 }
Daniel Dunbar644dca02009-12-04 08:17:33 +0000963};
964
965class TopLevelDeclTrackerAction : public ASTFrontendAction {
966public:
967 ASTUnit &Unit;
968
David Blaikie6beb6aa2014-08-10 19:56:51 +0000969 std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
970 StringRef InFile) override {
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000971 CI.getPreprocessor().addPPCallbacks(
Craig Topperb8a70532014-09-10 04:53:53 +0000972 llvm::make_unique<MacroDefinitionTrackerPPCallbacks>(
973 Unit.getCurrentTopLevelHashValue()));
David Blaikie6beb6aa2014-08-10 19:56:51 +0000974 return llvm::make_unique<TopLevelDeclTrackerConsumer>(
975 Unit, Unit.getCurrentTopLevelHashValue());
Daniel Dunbar764c0822009-12-01 09:51:01 +0000976 }
977
978public:
Daniel Dunbar644dca02009-12-04 08:17:33 +0000979 TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {}
980
Craig Topperafa7cb32014-03-13 06:07:04 +0000981 bool hasCodeCompletionSupport() const override { return false; }
Eugene Zelenko4f233182018-03-22 00:53:26 +0000982
Craig Topperafa7cb32014-03-13 06:07:04 +0000983 TranslationUnitKind getTranslationUnitKind() override {
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000984 return Unit.getTranslationUnitKind();
Douglas Gregor028d3e42010-08-09 20:45:32 +0000985 }
Daniel Dunbar764c0822009-12-01 09:51:01 +0000986};
987
Ilya Biryukov200b3282017-06-21 10:24:58 +0000988class ASTUnitPreambleCallbacks : public PreambleCallbacks {
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000989public:
Ilya Biryukov200b3282017-06-21 10:24:58 +0000990 unsigned getHash() const { return Hash; }
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000991
Ilya Biryukov200b3282017-06-21 10:24:58 +0000992 std::vector<Decl *> takeTopLevelDecls() { return std::move(TopLevelDecls); }
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000993
Ilya Biryukov200b3282017-06-21 10:24:58 +0000994 std::vector<serialization::DeclID> takeTopLevelDeclIDs() {
995 return std::move(TopLevelDeclIDs);
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000996 }
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000997
Ilya Biryukov200b3282017-06-21 10:24:58 +0000998 void AfterPCHEmitted(ASTWriter &Writer) override {
999 TopLevelDeclIDs.reserve(TopLevelDecls.size());
Eugene Zelenko4f233182018-03-22 00:53:26 +00001000 for (const auto *D : TopLevelDecls) {
Ilya Biryukov200b3282017-06-21 10:24:58 +00001001 // Invalid top-level decls may not have been serialized.
1002 if (D->isInvalidDecl())
1003 continue;
1004 TopLevelDeclIDs.push_back(Writer.getDeclID(D));
1005 }
1006 }
1007
1008 void HandleTopLevelDecl(DeclGroupRef DG) override {
Eugene Zelenko4f233182018-03-22 00:53:26 +00001009 for (auto *D : DG) {
Douglas Gregor48c8cd32010-08-03 08:14:03 +00001010 // FIXME: Currently ObjC method declarations are incorrectly being
1011 // reported as top-level declarations, even though their DeclContext
1012 // is the containing ObjC @interface/@implementation. This is a
1013 // fundamental problem in the parser right now.
1014 if (isa<ObjCMethodDecl>(D))
1015 continue;
Douglas Gregordf7a79a2011-02-16 18:16:54 +00001016 AddTopLevelDeclarationToHash(D, Hash);
Douglas Gregore9db88f2010-08-03 19:06:41 +00001017 TopLevelDecls.push_back(D);
1018 }
1019 }
1020
Ilya Biryukov41e90bc2017-12-15 11:27:51 +00001021 std::unique_ptr<PPCallbacks> createPPCallbacks() override {
1022 return llvm::make_unique<MacroDefinitionTrackerPPCallbacks>(Hash);
Douglas Gregor48c8cd32010-08-03 08:14:03 +00001023 }
Ilya Biryukov200b3282017-06-21 10:24:58 +00001024
1025private:
Ilya Biryukov200b3282017-06-21 10:24:58 +00001026 unsigned Hash = 0;
1027 std::vector<Decl *> TopLevelDecls;
1028 std::vector<serialization::DeclID> TopLevelDeclIDs;
1029 llvm::SmallVector<ASTUnit::StandaloneDiagnostic, 4> PreambleDiags;
Douglas Gregor48c8cd32010-08-03 08:14:03 +00001030};
1031
Eugene Zelenko4f233182018-03-22 00:53:26 +00001032} // namespace
Douglas Gregor48c8cd32010-08-03 08:14:03 +00001033
Benjamin Kramer1ce5d802013-05-05 12:39:28 +00001034static bool isNonDriverDiag(const StoredDiagnostic &StoredDiag) {
1035 return StoredDiag.getLocation().isValid();
1036}
1037
1038static void
1039checkAndRemoveNonDriverDiags(SmallVectorImpl<StoredDiagnostic> &StoredDiags) {
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +00001040 // Get rid of stored diagnostics except the ones from the driver which do not
1041 // have a source location.
Benjamin Kramer1ce5d802013-05-05 12:39:28 +00001042 StoredDiags.erase(
1043 std::remove_if(StoredDiags.begin(), StoredDiags.end(), isNonDriverDiag),
1044 StoredDiags.end());
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +00001045}
1046
1047static void checkAndSanitizeDiags(SmallVectorImpl<StoredDiagnostic> &
1048 StoredDiagnostics,
1049 SourceManager &SM) {
1050 // The stored diagnostic has the old source manager in it; update
1051 // the locations to refer into the new source manager. Since we've
1052 // been careful to make sure that the source manager's state
1053 // before and after are identical, so that we can reuse the source
1054 // location itself.
Eugene Zelenko4f233182018-03-22 00:53:26 +00001055 for (auto &SD : StoredDiagnostics) {
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00001056 if (SD.getLocation().isValid()) {
1057 FullSourceLoc Loc(SD.getLocation(), SM);
1058 SD.setLocation(Loc);
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +00001059 }
1060 }
1061}
1062
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001063/// Parse the source file into a translation unit using the given compiler
1064/// invocation, replacing the current translation unit.
1065///
1066/// \returns True if a failure occurred that causes the ASTUnit not to
1067/// contain any translation-unit information, false otherwise.
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001068bool ASTUnit::Parse(std::shared_ptr<PCHContainerOperations> PCHContainerOps,
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001069 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer,
1070 IntrusiveRefCntPtr<vfs::FileSystem> VFS) {
Rafael Espindola32482082014-08-18 16:23:45 +00001071 if (!Invocation)
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001072 return true;
Rafael Espindola32482082014-08-18 16:23:45 +00001073
Ilya Biryukov417085a2017-11-16 16:25:01 +00001074 auto CCInvocation = std::make_shared<CompilerInvocation>(*Invocation);
1075 if (OverrideMainBuffer) {
1076 assert(Preamble &&
1077 "No preamble was built, but OverrideMainBuffer is not null");
1078 IntrusiveRefCntPtr<vfs::FileSystem> OldVFS = VFS;
1079 Preamble->AddImplicitPreamble(*CCInvocation, VFS, OverrideMainBuffer.get());
1080 if (OldVFS != VFS && FileMgr) {
1081 assert(OldVFS == FileMgr->getVirtualFileSystem() &&
1082 "VFS passed to Parse and VFS in FileMgr are different");
1083 FileMgr = new FileManager(FileMgr->getFileSystemOpts(), VFS);
1084 }
1085 }
1086
Daniel Dunbar764c0822009-12-01 09:51:01 +00001087 // Create the compiler instance to use for building the AST.
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001088 std::unique_ptr<CompilerInstance> Clang(
Benjamin Kramerd6da1a02016-06-12 20:05:23 +00001089 new CompilerInstance(std::move(PCHContainerOps)));
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001090 if (FileMgr && VFS) {
1091 assert(VFS == FileMgr->getVirtualFileSystem() &&
1092 "VFS passed to Parse and VFS in FileMgr are different");
1093 } else if (VFS) {
1094 Clang->setVirtualFileSystem(VFS);
1095 }
Ted Kremenek84de4a12011-03-21 18:40:07 +00001096
1097 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00001098 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1099 CICleanup(Clang.get());
Ted Kremenek84de4a12011-03-21 18:40:07 +00001100
Ilya Biryukov417085a2017-11-16 16:25:01 +00001101 Clang->setInvocation(CCInvocation);
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001102 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001103
Douglas Gregor8e984da2010-08-04 16:47:14 +00001104 // Set up diagnostics, capturing any diagnostics that would
1105 // otherwise be dropped.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001106 Clang->setDiagnostics(&getDiagnostics());
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001107
Daniel Dunbar764c0822009-12-01 09:51:01 +00001108 // Create the target instance.
Alp Toker80758082014-07-06 05:26:44 +00001109 Clang->setTarget(TargetInfo::CreateTargetInfo(
Saleem Abdulrasool10a49722016-04-08 16:52:00 +00001110 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
Rafael Espindola32482082014-08-18 16:23:45 +00001111 if (!Clang->hasTarget())
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001112 return true;
Douglas Gregora0734c52010-08-19 01:33:06 +00001113
Daniel Dunbar764c0822009-12-01 09:51:01 +00001114 // Inform the target of the language options.
1115 //
1116 // FIXME: We shouldn't need to do this, the target should be immutable once
1117 // created. This complexity should be lifted elsewhere.
Alp Toker74437972014-07-06 05:14:24 +00001118 Clang->getTarget().adjust(Clang->getLangOpts());
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001119
Ted Kremenek84de4a12011-03-21 18:40:07 +00001120 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Daniel Dunbar764c0822009-12-01 09:51:01 +00001121 "Invocation must have exactly one source file!");
Richard Smith40c0efa2017-04-26 18:57:40 +00001122 assert(Clang->getFrontendOpts().Inputs[0].getKind().getFormat() ==
1123 InputKind::Source &&
Daniel Dunbar764c0822009-12-01 09:51:01 +00001124 "FIXME: AST inputs not yet supported here!");
Richard Smith40c0efa2017-04-26 18:57:40 +00001125 assert(Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() !=
1126 InputKind::LLVM_IR &&
Daniel Dunbar9507f9c2010-06-07 23:26:47 +00001127 "IR inputs not support here!");
Daniel Dunbar764c0822009-12-01 09:51:01 +00001128
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001129 // Configure the various subsystems.
Alp Toker269d8402014-07-06 05:26:07 +00001130 LangOpts = Clang->getInvocation().LangOpts;
Ted Kremenek84de4a12011-03-21 18:40:07 +00001131 FileSystemOpts = Clang->getFileSystemOpts();
Benjamin Kramerbc632902015-10-06 14:45:20 +00001132 if (!FileMgr) {
1133 Clang->createFileManager();
1134 FileMgr = &Clang->getFileManager();
1135 }
Erik Verbruggen346066b2017-05-30 14:25:54 +00001136
1137 ResetForParse();
1138
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +00001139 SourceMgr = new SourceManager(getDiagnostics(), *FileMgr,
1140 UserFilesAreVolatile);
Douglas Gregor7b02b582010-08-20 00:02:33 +00001141 if (!OverrideMainBuffer) {
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +00001142 checkAndRemoveNonDriverDiags(StoredDiagnostics);
Douglas Gregor7b02b582010-08-20 00:02:33 +00001143 TopLevelDeclsInPreamble.clear();
1144 }
1145
Daniel Dunbar764c0822009-12-01 09:51:01 +00001146 // Create a file manager object to provide access to and cache the filesystem.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001147 Clang->setFileManager(&getFileManager());
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001148
Daniel Dunbar764c0822009-12-01 09:51:01 +00001149 // Create the source manager.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001150 Clang->setSourceManager(&getSourceManager());
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001151
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001152 // If the main file has been overridden due to the use of a preamble,
1153 // make that override happen and introduce the preamble.
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001154 if (OverrideMainBuffer) {
Douglas Gregord9a30af2010-08-02 20:51:39 +00001155 // The stored diagnostic has the old source manager in it; update
1156 // the locations to refer into the new source manager. Since we've
1157 // been careful to make sure that the source manager's state
1158 // before and after are identical, so that we can reuse the source
1159 // location itself.
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +00001160 checkAndSanitizeDiags(StoredDiagnostics, getSourceManager());
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001161
1162 // Keep track of the override buffer;
Rafael Espindola32482082014-08-18 16:23:45 +00001163 SavedMainFileBuffer = std::move(OverrideMainBuffer);
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001164 }
Ahmed Charlesb8984322014-03-07 20:03:18 +00001165
1166 std::unique_ptr<TopLevelDeclTrackerAction> Act(
1167 new TopLevelDeclTrackerAction(*this));
1168
Ted Kremenek022a4902011-03-22 01:15:24 +00001169 // Recover resources if we crash before exiting this method.
1170 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1171 ActCleanup(Act.get());
1172
Douglas Gregor32fbe312012-01-20 16:28:04 +00001173 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0]))
Daniel Dunbar764c0822009-12-01 09:51:01 +00001174 goto error;
Douglas Gregor925296b2011-07-19 16:10:42 +00001175
Richard Smith26b8f782016-03-25 21:46:44 +00001176 if (SavedMainFileBuffer)
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001177 TranslateStoredDiagnostics(getFileManager(), getSourceManager(),
1178 PreambleDiagnostics, StoredDiagnostics);
Erik Verbruggenefe6fa52017-06-09 08:29:58 +00001179 else
1180 PreambleSrcLocCache.clear();
Douglas Gregor925296b2011-07-19 16:10:42 +00001181
Argyrios Kyrtzidis1416e172012-06-08 05:48:06 +00001182 if (!Act->Execute())
1183 goto error;
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001184
1185 transferASTDataFromCompilerInstance(*Clang);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001186
Daniel Dunbar644dca02009-12-04 08:17:33 +00001187 Act->EndSourceFile();
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001188
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001189 FailedParseDiagnostics.clear();
1190
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001191 return false;
Ted Kremenek5e14d392011-03-21 18:40:17 +00001192
Daniel Dunbar764c0822009-12-01 09:51:01 +00001193error:
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001194 // Remove the overridden buffer we used for the preamble.
Rafael Espindola32482082014-08-18 16:23:45 +00001195 SavedMainFileBuffer = nullptr;
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001196
1197 // Keep the ownership of the data in the ASTUnit because the client may
1198 // want to see the diagnostics.
1199 transferASTDataFromCompilerInstance(*Clang);
1200 FailedParseDiagnostics.swap(StoredDiagnostics);
Douglas Gregorefc46952010-10-12 16:25:54 +00001201 StoredDiagnostics.clear();
Argyrios Kyrtzidis067cbfa2011-10-24 17:25:20 +00001202 NumStoredDiagnosticsFromDriver = 0;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001203 return true;
1204}
1205
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001206static std::pair<unsigned, unsigned>
1207makeStandaloneRange(CharSourceRange Range, const SourceManager &SM,
1208 const LangOptions &LangOpts) {
1209 CharSourceRange FileRange = Lexer::makeFileCharRange(Range, SM, LangOpts);
1210 unsigned Offset = SM.getFileOffset(FileRange.getBegin());
1211 unsigned EndOffset = SM.getFileOffset(FileRange.getEnd());
1212 return std::make_pair(Offset, EndOffset);
1213}
1214
Benjamin Kramer1a6e0a92014-10-03 18:52:54 +00001215static ASTUnit::StandaloneFixIt makeStandaloneFixIt(const SourceManager &SM,
1216 const LangOptions &LangOpts,
1217 const FixItHint &InFix) {
1218 ASTUnit::StandaloneFixIt OutFix;
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001219 OutFix.RemoveRange = makeStandaloneRange(InFix.RemoveRange, SM, LangOpts);
1220 OutFix.InsertFromRange = makeStandaloneRange(InFix.InsertFromRange, SM,
1221 LangOpts);
1222 OutFix.CodeToInsert = InFix.CodeToInsert;
1223 OutFix.BeforePreviousInsertions = InFix.BeforePreviousInsertions;
Benjamin Kramer1a6e0a92014-10-03 18:52:54 +00001224 return OutFix;
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001225}
1226
Benjamin Kramer1a6e0a92014-10-03 18:52:54 +00001227static ASTUnit::StandaloneDiagnostic
1228makeStandaloneDiagnostic(const LangOptions &LangOpts,
1229 const StoredDiagnostic &InDiag) {
1230 ASTUnit::StandaloneDiagnostic OutDiag;
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001231 OutDiag.ID = InDiag.getID();
1232 OutDiag.Level = InDiag.getLevel();
1233 OutDiag.Message = InDiag.getMessage();
1234 OutDiag.LocOffset = 0;
1235 if (InDiag.getLocation().isInvalid())
Benjamin Kramer1a6e0a92014-10-03 18:52:54 +00001236 return OutDiag;
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001237 const SourceManager &SM = InDiag.getLocation().getManager();
1238 SourceLocation FileLoc = SM.getFileLoc(InDiag.getLocation());
1239 OutDiag.Filename = SM.getFilename(FileLoc);
1240 if (OutDiag.Filename.empty())
Benjamin Kramer1a6e0a92014-10-03 18:52:54 +00001241 return OutDiag;
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001242 OutDiag.LocOffset = SM.getFileOffset(FileLoc);
Eugene Zelenko4f233182018-03-22 00:53:26 +00001243 for (const auto &Range : InDiag.getRanges())
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00001244 OutDiag.Ranges.push_back(makeStandaloneRange(Range, SM, LangOpts));
Eugene Zelenko4f233182018-03-22 00:53:26 +00001245 for (const auto &FixIt : InDiag.getFixIts())
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00001246 OutDiag.FixIts.push_back(makeStandaloneFixIt(SM, LangOpts, FixIt));
Benjamin Kramer1a6e0a92014-10-03 18:52:54 +00001247
1248 return OutDiag;
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001249}
1250
Douglas Gregor4dde7492010-07-23 23:58:40 +00001251/// \brief Attempt to build or re-use a precompiled preamble when (re-)parsing
1252/// the source file.
1253///
1254/// This routine will compute the preamble of the main source file. If a
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001255/// non-trivial preamble is found, it will precompile that preamble into a
Douglas Gregor4dde7492010-07-23 23:58:40 +00001256/// precompiled header so that the precompiled preamble can be used to reduce
1257/// reparsing time. If a precompiled preamble has already been constructed,
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001258/// this routine will determine if it is still valid and, if so, avoid
Douglas Gregor4dde7492010-07-23 23:58:40 +00001259/// rebuilding the precompiled preamble.
1260///
Douglas Gregor028d3e42010-08-09 20:45:32 +00001261/// \param AllowRebuild When true (the default), this routine is
1262/// allowed to rebuild the precompiled preamble if it is found to be
1263/// out-of-date.
1264///
1265/// \param MaxLines When non-zero, the maximum number of lines that
1266/// can occur within the preamble.
1267///
Douglas Gregor6481ef12010-07-24 00:38:13 +00001268/// \returns If the precompiled preamble can be used, returns a newly-allocated
1269/// buffer that should be used in place of the main file when doing so.
1270/// Otherwise, returns a NULL pointer.
Rafael Espindola2346a372014-08-18 18:47:08 +00001271std::unique_ptr<llvm::MemoryBuffer>
1272ASTUnit::getMainBufferWithPrecompiledPreamble(
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001273 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001274 const CompilerInvocation &PreambleInvocationIn,
1275 IntrusiveRefCntPtr<vfs::FileSystem> VFS, bool AllowRebuild,
Rafael Espindola2346a372014-08-18 18:47:08 +00001276 unsigned MaxLines) {
Ilya Biryukov200b3282017-06-21 10:24:58 +00001277 auto MainFilePath =
1278 PreambleInvocationIn.getFrontendOpts().Inputs[0].getFile();
1279 std::unique_ptr<llvm::MemoryBuffer> MainFileBuffer =
1280 getBufferForFileHandlingRemapping(PreambleInvocationIn, VFS.get(),
1281 MainFilePath);
1282 if (!MainFileBuffer)
Craig Topper49a27902014-05-22 04:46:25 +00001283 return nullptr;
Douglas Gregord9a30af2010-08-02 20:51:39 +00001284
Ilya Biryukov200b3282017-06-21 10:24:58 +00001285 PreambleBounds Bounds =
1286 ComputePreambleBounds(*PreambleInvocationIn.getLangOpts(),
1287 MainFileBuffer.get(), MaxLines);
1288 if (!Bounds.Size)
1289 return nullptr;
Alp Toker1b070d22014-07-07 07:47:20 +00001290
Ilya Biryukov200b3282017-06-21 10:24:58 +00001291 if (Preamble) {
1292 if (Preamble->CanReuse(PreambleInvocationIn, MainFileBuffer.get(), Bounds,
1293 VFS.get())) {
1294 // Okay! We can re-use the precompiled preamble.
Rafael Espindolae4777f42013-07-29 18:22:23 +00001295
Ilya Biryukov200b3282017-06-21 10:24:58 +00001296 // Set the state of the diagnostic object to mimic its state
1297 // after parsing the preamble.
1298 getDiagnostics().Reset();
1299 ProcessWarningOptions(getDiagnostics(),
1300 PreambleInvocationIn.getDiagnosticOpts());
1301 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
Alp Toker1b070d22014-07-07 07:47:20 +00001302
Ilya Biryukov200b3282017-06-21 10:24:58 +00001303 PreambleRebuildCounter = 1;
1304 return MainFileBuffer;
1305 } else {
1306 Preamble.reset();
1307 PreambleDiagnostics.clear();
1308 TopLevelDeclsInPreamble.clear();
Alex Lorenza44c4322018-03-12 19:36:29 +00001309 PreambleSrcLocCache.clear();
Ilya Biryukov200b3282017-06-21 10:24:58 +00001310 PreambleRebuildCounter = 1;
Douglas Gregor4dde7492010-07-23 23:58:40 +00001311 }
Douglas Gregor028d3e42010-08-09 20:45:32 +00001312 }
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001313
1314 // If the preamble rebuild counter > 1, it's because we previously
1315 // failed to build a preamble and we're not yet ready to try
1316 // again. Decrement the counter and return a failure.
1317 if (PreambleRebuildCounter > 1) {
1318 --PreambleRebuildCounter;
Craig Topper49a27902014-05-22 04:46:25 +00001319 return nullptr;
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001320 }
1321
Ilya Biryukov200b3282017-06-21 10:24:58 +00001322 assert(!Preamble && "No Preamble should be stored at that point");
1323 // If we aren't allowed to rebuild the precompiled preamble, just
1324 // return now.
1325 if (!AllowRebuild)
Ben Langmuir8832c062014-04-15 18:16:25 +00001326 return nullptr;
1327
Ilya Biryukov200b3282017-06-21 10:24:58 +00001328 SmallVector<StandaloneDiagnostic, 4> NewPreambleDiagsStandalone;
1329 SmallVector<StoredDiagnostic, 4> NewPreambleDiags;
Ilya Biryukovf81d46f2017-06-21 12:34:27 +00001330 ASTUnitPreambleCallbacks Callbacks;
Ilya Biryukov200b3282017-06-21 10:24:58 +00001331 {
1332 llvm::Optional<CaptureDroppedDiagnostics> Capture;
1333 if (CaptureDiagnostics)
1334 Capture.emplace(/*RequestCapture=*/true, *Diagnostics, &NewPreambleDiags,
1335 &NewPreambleDiagsStandalone);
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001336
Ilya Biryukov200b3282017-06-21 10:24:58 +00001337 // We did not previously compute a preamble, or it can't be reused anyway.
1338 SimpleTimer PreambleTimer(WantTiming);
1339 PreambleTimer.setOutput("Precompiling preamble");
Ahmed Charlesb8984322014-03-07 20:03:18 +00001340
Ilya Biryukov200b3282017-06-21 10:24:58 +00001341 llvm::ErrorOr<PrecompiledPreamble> NewPreamble = PrecompiledPreamble::Build(
1342 PreambleInvocationIn, MainFileBuffer.get(), Bounds, *Diagnostics, VFS,
Ilya Biryukov417085a2017-11-16 16:25:01 +00001343 PCHContainerOps, /*StoreInMemory=*/false, Callbacks);
Ilya Biryukov200b3282017-06-21 10:24:58 +00001344 if (NewPreamble) {
1345 Preamble = std::move(*NewPreamble);
1346 PreambleRebuildCounter = 1;
Dmitri Gribenko47652522013-12-20 00:16:25 +00001347 } else {
Ilya Biryukov200b3282017-06-21 10:24:58 +00001348 switch (static_cast<BuildPreambleError>(NewPreamble.getError().value())) {
1349 case BuildPreambleError::CouldntCreateTempFile:
1350 case BuildPreambleError::PreambleIsEmpty:
1351 // Try again next time.
1352 PreambleRebuildCounter = 1;
Ilya Biryukovf81d46f2017-06-21 12:34:27 +00001353 return nullptr;
Ilya Biryukov200b3282017-06-21 10:24:58 +00001354 case BuildPreambleError::CouldntCreateTargetInfo:
1355 case BuildPreambleError::BeginSourceFileFailed:
1356 case BuildPreambleError::CouldntEmitPCH:
1357 case BuildPreambleError::CouldntCreateVFSOverlay:
1358 // These erros are more likely to repeat, retry after some period.
1359 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Ilya Biryukovf81d46f2017-06-21 12:34:27 +00001360 return nullptr;
Ilya Biryukov200b3282017-06-21 10:24:58 +00001361 }
Ilya Biryukovf81d46f2017-06-21 12:34:27 +00001362 llvm_unreachable("unexpected BuildPreambleError");
Dmitri Gribenko47652522013-12-20 00:16:25 +00001363 }
Douglas Gregor0e119552010-07-31 00:40:00 +00001364 }
Ben Langmuir33c80902014-06-30 20:04:14 +00001365
Ilya Biryukov200b3282017-06-21 10:24:58 +00001366 assert(Preamble && "Preamble wasn't built");
1367
1368 TopLevelDecls.clear();
1369 TopLevelDeclsInPreamble = Callbacks.takeTopLevelDeclIDs();
1370 PreambleTopLevelHashValue = Callbacks.getHash();
1371
1372 NumWarningsInPreamble = getDiagnostics().getNumWarnings();
1373
1374 checkAndRemoveNonDriverDiags(NewPreambleDiags);
1375 StoredDiagnostics = std::move(NewPreambleDiags);
1376 PreambleDiagnostics = std::move(NewPreambleDiagsStandalone);
Alp Toker1b070d22014-07-07 07:47:20 +00001377
Douglas Gregordf7a79a2011-02-16 18:16:54 +00001378 // If the hash of top-level entities differs from the hash of the top-level
1379 // entities the last time we rebuilt the preamble, clear out the completion
1380 // cache.
1381 if (CurrentTopLevelHashValue != PreambleTopLevelHashValue) {
1382 CompletionCacheTopLevelHashValue = 0;
1383 PreambleTopLevelHashValue = CurrentTopLevelHashValue;
1384 }
Rafael Espindola2346a372014-08-18 18:47:08 +00001385
Ilya Biryukov200b3282017-06-21 10:24:58 +00001386 return MainFileBuffer;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001387}
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001388
Douglas Gregore9db88f2010-08-03 19:06:41 +00001389void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
Ilya Biryukov200b3282017-06-21 10:24:58 +00001390 assert(Preamble && "Should only be called when preamble was built");
1391
Douglas Gregore9db88f2010-08-03 19:06:41 +00001392 std::vector<Decl *> Resolved;
1393 Resolved.reserve(TopLevelDeclsInPreamble.size());
1394 ExternalASTSource &Source = *getASTContext().getExternalSource();
Eugene Zelenko4f233182018-03-22 00:53:26 +00001395 for (const auto TopLevelDecl : TopLevelDeclsInPreamble) {
Douglas Gregore9db88f2010-08-03 19:06:41 +00001396 // Resolve the declaration ID to an actual declaration, possibly
1397 // deserializing the declaration in the process.
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00001398 if (Decl *D = Source.GetExternalDecl(TopLevelDecl))
Douglas Gregore9db88f2010-08-03 19:06:41 +00001399 Resolved.push_back(D);
1400 }
1401 TopLevelDeclsInPreamble.clear();
1402 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1403}
1404
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001405void ASTUnit::transferASTDataFromCompilerInstance(CompilerInstance &CI) {
Ben Langmuir749323f2014-04-22 17:40:12 +00001406 // Steal the created target, context, and preprocessor if they have been
1407 // created.
1408 assert(CI.hasInvocation() && "missing invocation");
Alp Toker269d8402014-07-06 05:26:07 +00001409 LangOpts = CI.getInvocation().LangOpts;
David Blaikieec99b5e2014-08-10 19:14:48 +00001410 TheSema = CI.takeSema();
David Blaikie6beb6aa2014-08-10 19:56:51 +00001411 Consumer = CI.takeASTConsumer();
Ben Langmuir532fdc02014-04-18 20:39:48 +00001412 if (CI.hasASTContext())
1413 Ctx = &CI.getASTContext();
1414 if (CI.hasPreprocessor())
David Blaikie41565462017-01-05 19:48:07 +00001415 PP = CI.getPreprocessorPtr();
Craig Topper49a27902014-05-22 04:46:25 +00001416 CI.setSourceManager(nullptr);
1417 CI.setFileManager(nullptr);
Ben Langmuir532fdc02014-04-18 20:39:48 +00001418 if (CI.hasTarget())
1419 Target = &CI.getTarget();
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001420 Reader = CI.getModuleManager();
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00001421 HadModuleLoaderFatalFailure = CI.hadModuleLoaderFatalFailure();
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001422}
1423
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001424StringRef ASTUnit::getMainFileName() const {
Argyrios Kyrtzidis928e1fd2013-01-11 22:11:14 +00001425 if (Invocation && !Invocation->getFrontendOpts().Inputs.empty()) {
1426 const FrontendInputFile &Input = Invocation->getFrontendOpts().Inputs[0];
1427 if (Input.isFile())
1428 return Input.getFile();
1429 else
1430 return Input.getBuffer()->getBufferIdentifier();
1431 }
1432
1433 if (SourceMgr) {
1434 if (const FileEntry *
1435 FE = SourceMgr->getFileEntryForID(SourceMgr->getMainFileID()))
1436 return FE->getName();
1437 }
1438
Eugene Zelenko4f233182018-03-22 00:53:26 +00001439 return {};
Douglas Gregor16896c42010-10-28 15:44:59 +00001440}
1441
Argyrios Kyrtzidis37f2ab42013-03-05 20:21:14 +00001442StringRef ASTUnit::getASTFileName() const {
1443 if (!isMainFileAST())
Eugene Zelenko4f233182018-03-22 00:53:26 +00001444 return {};
Argyrios Kyrtzidis37f2ab42013-03-05 20:21:14 +00001445
1446 serialization::ModuleFile &
1447 Mod = Reader->getModuleManager().getPrimaryModule();
1448 return Mod.FileName;
1449}
1450
David Blaikieea4395e2017-01-06 19:49:01 +00001451std::unique_ptr<ASTUnit>
1452ASTUnit::create(std::shared_ptr<CompilerInvocation> CI,
1453 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
1454 bool CaptureDiagnostics, bool UserFilesAreVolatile) {
1455 std::unique_ptr<ASTUnit> AST(new ASTUnit(false));
Justin Bognerdbbcb112014-10-14 23:36:06 +00001456 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
Ben Langmuir8832c062014-04-15 18:16:25 +00001457 IntrusiveRefCntPtr<vfs::FileSystem> VFS =
1458 createVFSFromCompilerInvocation(*CI, *Diags);
1459 if (!VFS)
1460 return nullptr;
David Blaikieea4395e2017-01-06 19:49:01 +00001461 AST->Diagnostics = Diags;
1462 AST->FileSystemOpts = CI->getFileSystemOpts();
1463 AST->Invocation = std::move(CI);
Ben Langmuir8832c062014-04-15 18:16:25 +00001464 AST->FileMgr = new FileManager(AST->FileSystemOpts, VFS);
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +00001465 AST->UserFilesAreVolatile = UserFilesAreVolatile;
1466 AST->SourceMgr = new SourceManager(AST->getDiagnostics(), *AST->FileMgr,
1467 UserFilesAreVolatile);
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00001468 AST->PCMCache = new MemoryBufferCache;
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00001469
David Blaikieea4395e2017-01-06 19:49:01 +00001470 return AST;
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00001471}
1472
Ahmed Charlesb8984322014-03-07 20:03:18 +00001473ASTUnit *ASTUnit::LoadFromCompilerInvocationAction(
David Blaikieea4395e2017-01-06 19:49:01 +00001474 std::shared_ptr<CompilerInvocation> CI,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001475 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
Argyrios Kyrtzidisc382abf2016-02-09 19:07:13 +00001476 IntrusiveRefCntPtr<DiagnosticsEngine> Diags, FrontendAction *Action,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001477 ASTUnit *Unit, bool Persistent, StringRef ResourceFilesPath,
Benjamin Kramer5c248d82015-12-15 09:30:31 +00001478 bool OnlyLocalDecls, bool CaptureDiagnostics,
1479 unsigned PrecompilePreambleAfterNParses, bool CacheCodeCompletionResults,
1480 bool IncludeBriefCommentsInCodeCompletion, bool UserFilesAreVolatile,
1481 std::unique_ptr<ASTUnit> *ErrAST) {
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001482 assert(CI && "A CompilerInvocation is required");
1483
Ahmed Charlesb8984322014-03-07 20:03:18 +00001484 std::unique_ptr<ASTUnit> OwnAST;
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001485 ASTUnit *AST = Unit;
1486 if (!AST) {
1487 // Create the AST unit.
David Blaikieea4395e2017-01-06 19:49:01 +00001488 OwnAST = create(CI, Diags, CaptureDiagnostics, UserFilesAreVolatile);
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001489 AST = OwnAST.get();
Ben Langmuir8832c062014-04-15 18:16:25 +00001490 if (!AST)
1491 return nullptr;
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001492 }
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001493
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00001494 if (!ResourceFilesPath.empty()) {
1495 // Override the resources path.
1496 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
1497 }
1498 AST->OnlyLocalDecls = OnlyLocalDecls;
1499 AST->CaptureDiagnostics = CaptureDiagnostics;
Benjamin Kramer5c248d82015-12-15 09:30:31 +00001500 if (PrecompilePreambleAfterNParses > 0)
1501 AST->PreambleRebuildCounter = PrecompilePreambleAfterNParses;
Douglas Gregor69f74f82011-08-25 22:30:56 +00001502 AST->TUKind = Action ? Action->getTranslationUnitKind() : TU_Complete;
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00001503 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenko3292d062012-07-02 17:35:10 +00001504 AST->IncludeBriefCommentsInCodeCompletion
1505 = IncludeBriefCommentsInCodeCompletion;
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001506
1507 // Recover resources if we crash before exiting this method.
1508 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001509 ASTUnitCleanup(OwnAST.get());
David Blaikie9c902b52011-09-25 23:23:43 +00001510 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
Eugene Zelenko4f233182018-03-22 00:53:26 +00001511 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine>>
Alp Tokerf994cef2014-07-05 03:08:06 +00001512 DiagCleanup(Diags.get());
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001513
1514 // We'll manage file buffers ourselves.
1515 CI->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1516 CI->getFrontendOpts().DisableFree = false;
1517 ProcessWarningOptions(AST->getDiagnostics(), CI->getDiagnosticOpts());
1518
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001519 // Create the compiler instance to use for building the AST.
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001520 std::unique_ptr<CompilerInstance> Clang(
Benjamin Kramerd6da1a02016-06-12 20:05:23 +00001521 new CompilerInstance(std::move(PCHContainerOps)));
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001522
1523 // Recover resources if we crash before exiting this method.
1524 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1525 CICleanup(Clang.get());
1526
David Blaikieea4395e2017-01-06 19:49:01 +00001527 Clang->setInvocation(std::move(CI));
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001528 AST->OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001529
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001530 // Set up diagnostics, capturing any diagnostics that would
1531 // otherwise be dropped.
1532 Clang->setDiagnostics(&AST->getDiagnostics());
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001533
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001534 // Create the target instance.
Alp Toker80758082014-07-06 05:26:44 +00001535 Clang->setTarget(TargetInfo::CreateTargetInfo(
Saleem Abdulrasool10a49722016-04-08 16:52:00 +00001536 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001537 if (!Clang->hasTarget())
Craig Topper49a27902014-05-22 04:46:25 +00001538 return nullptr;
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001539
1540 // Inform the target of the language options.
1541 //
1542 // FIXME: We shouldn't need to do this, the target should be immutable once
1543 // created. This complexity should be lifted elsewhere.
Alp Toker74437972014-07-06 05:14:24 +00001544 Clang->getTarget().adjust(Clang->getLangOpts());
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001545
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001546 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1547 "Invocation must have exactly one source file!");
Richard Smith40c0efa2017-04-26 18:57:40 +00001548 assert(Clang->getFrontendOpts().Inputs[0].getKind().getFormat() ==
1549 InputKind::Source &&
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001550 "FIXME: AST inputs not yet supported here!");
Richard Smith40c0efa2017-04-26 18:57:40 +00001551 assert(Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() !=
1552 InputKind::LLVM_IR &&
1553 "IR inputs not support here!");
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001554
1555 // Configure the various subsystems.
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001556 AST->TheSema.reset();
Craig Topper49a27902014-05-22 04:46:25 +00001557 AST->Ctx = nullptr;
1558 AST->PP = nullptr;
1559 AST->Reader = nullptr;
1560
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001561 // Create a file manager object to provide access to and cache the filesystem.
1562 Clang->setFileManager(&AST->getFileManager());
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001563
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001564 // Create the source manager.
1565 Clang->setSourceManager(&AST->getSourceManager());
1566
Argyrios Kyrtzidisc382abf2016-02-09 19:07:13 +00001567 FrontendAction *Act = Action;
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001568
Ahmed Charlesb8984322014-03-07 20:03:18 +00001569 std::unique_ptr<TopLevelDeclTrackerAction> TrackerAct;
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001570 if (!Act) {
1571 TrackerAct.reset(new TopLevelDeclTrackerAction(*AST));
1572 Act = TrackerAct.get();
1573 }
1574
1575 // Recover resources if we crash before exiting this method.
1576 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1577 ActCleanup(TrackerAct.get());
1578
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001579 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
1580 AST->transferASTDataFromCompilerInstance(*Clang);
1581 if (OwnAST && ErrAST)
1582 ErrAST->swap(OwnAST);
1583
Craig Topper49a27902014-05-22 04:46:25 +00001584 return nullptr;
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001585 }
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00001586
1587 if (Persistent && !TrackerAct) {
1588 Clang->getPreprocessor().addPPCallbacks(
Craig Topperb8a70532014-09-10 04:53:53 +00001589 llvm::make_unique<MacroDefinitionTrackerPPCallbacks>(
1590 AST->getCurrentTopLevelHashValue()));
David Blaikie6beb6aa2014-08-10 19:56:51 +00001591 std::vector<std::unique_ptr<ASTConsumer>> Consumers;
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00001592 if (Clang->hasASTConsumer())
1593 Consumers.push_back(Clang->takeASTConsumer());
David Blaikie6beb6aa2014-08-10 19:56:51 +00001594 Consumers.push_back(llvm::make_unique<TopLevelDeclTrackerConsumer>(
1595 *AST, AST->getCurrentTopLevelHashValue()));
1596 Clang->setASTConsumer(
1597 llvm::make_unique<MultiplexConsumer>(std::move(Consumers)));
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00001598 }
Argyrios Kyrtzidis1416e172012-06-08 05:48:06 +00001599 if (!Act->Execute()) {
1600 AST->transferASTDataFromCompilerInstance(*Clang);
1601 if (OwnAST && ErrAST)
1602 ErrAST->swap(OwnAST);
1603
Craig Topper49a27902014-05-22 04:46:25 +00001604 return nullptr;
Argyrios Kyrtzidis1416e172012-06-08 05:48:06 +00001605 }
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001606
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001607 // Steal the created target, context, and preprocessor.
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001608 AST->transferASTDataFromCompilerInstance(*Clang);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001609
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001610 Act->EndSourceFile();
1611
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001612 if (OwnAST)
Ahmed Charles9a16beb2014-03-07 19:33:25 +00001613 return OwnAST.release();
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001614 else
1615 return AST;
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001616}
1617
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001618bool ASTUnit::LoadFromCompilerInvocation(
1619 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001620 unsigned PrecompilePreambleAfterNParses,
1621 IntrusiveRefCntPtr<vfs::FileSystem> VFS) {
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001622 if (!Invocation)
1623 return true;
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001624
1625 assert(VFS && "VFS is null");
1626
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001627 // We'll manage file buffers ourselves.
1628 Invocation->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1629 Invocation->getFrontendOpts().DisableFree = false;
Benjamin Kramer8de9c9b2017-01-18 16:25:48 +00001630 getDiagnostics().Reset();
Douglas Gregor345c1bc2011-01-19 01:02:47 +00001631 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001632
Rafael Espindola32482082014-08-18 16:23:45 +00001633 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
Benjamin Kramer5c248d82015-12-15 09:30:31 +00001634 if (PrecompilePreambleAfterNParses > 0) {
1635 PreambleRebuildCounter = PrecompilePreambleAfterNParses;
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001636 OverrideMainBuffer =
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001637 getMainBufferWithPrecompiledPreamble(PCHContainerOps, *Invocation, VFS);
Benjamin Kramer8484a322017-02-13 16:16:43 +00001638 getDiagnostics().Reset();
1639 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001640 }
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001641
Douglas Gregor16896c42010-10-28 15:44:59 +00001642 SimpleTimer ParsingTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00001643 ParsingTimer.setOutput("Parsing " + getMainFileName());
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001644
Ted Kremenek022a4902011-03-22 01:15:24 +00001645 // Recover resources if we crash before exiting this method.
1646 llvm::CrashRecoveryContextCleanupRegistrar<llvm::MemoryBuffer>
Rafael Espindola32482082014-08-18 16:23:45 +00001647 MemBufferCleanup(OverrideMainBuffer.get());
1648
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001649 return Parse(std::move(PCHContainerOps), std::move(OverrideMainBuffer), VFS);
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001650}
1651
David Blaikie103a2de2014-04-25 17:01:33 +00001652std::unique_ptr<ASTUnit> ASTUnit::LoadFromCompilerInvocation(
David Blaikieea4395e2017-01-06 19:49:01 +00001653 std::shared_ptr<CompilerInvocation> CI,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001654 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
Benjamin Kramerbc632902015-10-06 14:45:20 +00001655 IntrusiveRefCntPtr<DiagnosticsEngine> Diags, FileManager *FileMgr,
Benjamin Kramer5c248d82015-12-15 09:30:31 +00001656 bool OnlyLocalDecls, bool CaptureDiagnostics,
1657 unsigned PrecompilePreambleAfterNParses, TranslationUnitKind TUKind,
1658 bool CacheCodeCompletionResults, bool IncludeBriefCommentsInCodeCompletion,
1659 bool UserFilesAreVolatile) {
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001660 // Create the AST unit.
David Blaikie103a2de2014-04-25 17:01:33 +00001661 std::unique_ptr<ASTUnit> AST(new ASTUnit(false));
Justin Bognerdbbcb112014-10-14 23:36:06 +00001662 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001663 AST->Diagnostics = Diags;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001664 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001665 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor69f74f82011-08-25 22:30:56 +00001666 AST->TUKind = TUKind;
Douglas Gregorb14904c2010-08-13 22:48:40 +00001667 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenko3292d062012-07-02 17:35:10 +00001668 AST->IncludeBriefCommentsInCodeCompletion
1669 = IncludeBriefCommentsInCodeCompletion;
David Blaikieea4395e2017-01-06 19:49:01 +00001670 AST->Invocation = std::move(CI);
Benjamin Kramerbc632902015-10-06 14:45:20 +00001671 AST->FileSystemOpts = FileMgr->getFileSystemOpts();
1672 AST->FileMgr = FileMgr;
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +00001673 AST->UserFilesAreVolatile = UserFilesAreVolatile;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001674
Ted Kremenek4422bfe2011-03-18 02:06:56 +00001675 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00001676 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1677 ASTUnitCleanup(AST.get());
David Blaikie9c902b52011-09-25 23:23:43 +00001678 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
Eugene Zelenko4f233182018-03-22 00:53:26 +00001679 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine>>
Alp Tokerf994cef2014-07-05 03:08:06 +00001680 DiagCleanup(Diags.get());
Ted Kremenek4422bfe2011-03-18 02:06:56 +00001681
Benjamin Kramerd6da1a02016-06-12 20:05:23 +00001682 if (AST->LoadFromCompilerInvocation(std::move(PCHContainerOps),
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001683 PrecompilePreambleAfterNParses,
1684 AST->FileMgr->getVirtualFileSystem()))
David Blaikie103a2de2014-04-25 17:01:33 +00001685 return nullptr;
1686 return AST;
Daniel Dunbar764c0822009-12-01 09:51:01 +00001687}
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001688
Ahmed Charlesb8984322014-03-07 20:03:18 +00001689ASTUnit *ASTUnit::LoadFromCommandLine(
1690 const char **ArgBegin, const char **ArgEnd,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001691 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
Ahmed Charlesb8984322014-03-07 20:03:18 +00001692 IntrusiveRefCntPtr<DiagnosticsEngine> Diags, StringRef ResourceFilesPath,
1693 bool OnlyLocalDecls, bool CaptureDiagnostics,
1694 ArrayRef<RemappedFile> RemappedFiles, bool RemappedFilesKeepOriginalName,
Benjamin Kramer5c248d82015-12-15 09:30:31 +00001695 unsigned PrecompilePreambleAfterNParses, TranslationUnitKind TUKind,
Ahmed Charlesb8984322014-03-07 20:03:18 +00001696 bool CacheCodeCompletionResults, bool IncludeBriefCommentsInCodeCompletion,
1697 bool AllowPCHWithCompilerErrors, bool SkipFunctionBodies,
Argyrios Kyrtzidis735e92c2017-06-09 01:20:48 +00001698 bool SingleFileParse, bool UserFilesAreVolatile, bool ForSerialization,
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001699 llvm::Optional<StringRef> ModuleFormat, std::unique_ptr<ASTUnit> *ErrAST,
1700 IntrusiveRefCntPtr<vfs::FileSystem> VFS) {
Justin Bognerd512c1e2014-10-15 00:33:06 +00001701 assert(Diags.get() && "no DiagnosticsEngine was provided");
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001702
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001703 SmallVector<StoredDiagnostic, 4> StoredDiagnostics;
David Blaikieea4395e2017-01-06 19:49:01 +00001704
1705 std::shared_ptr<CompilerInvocation> CI;
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001706
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001707 {
Ilya Biryukov200b3282017-06-21 10:24:58 +00001708 CaptureDroppedDiagnostics Capture(CaptureDiagnostics, *Diags,
1709 &StoredDiagnostics, nullptr);
Daniel Dunbarfcf2d422010-01-25 00:44:02 +00001710
Eugene Zelenko4f233182018-03-22 00:53:26 +00001711 CI = createInvocationFromCommandLine(
Ilya Biryukovafdadf52017-06-28 15:06:34 +00001712 llvm::makeArrayRef(ArgBegin, ArgEnd), Diags, VFS);
Argyrios Kyrtzidisf606b822011-04-04 21:38:51 +00001713 if (!CI)
Craig Topper49a27902014-05-22 04:46:25 +00001714 return nullptr;
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001715 }
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001716
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001717 // Override any files that need remapping
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00001718 for (const auto &RemappedFile : RemappedFiles) {
1719 CI->getPreprocessorOpts().addRemappedFile(RemappedFile.first,
1720 RemappedFile.second);
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00001721 }
Argyrios Kyrtzidis4a280ff2012-03-07 01:51:17 +00001722 PreprocessorOptions &PPOpts = CI->getPreprocessorOpts();
1723 PPOpts.RemappedFilesKeepOriginalName = RemappedFilesKeepOriginalName;
1724 PPOpts.AllowPCHWithCompilerErrors = AllowPCHWithCompilerErrors;
Argyrios Kyrtzidis735e92c2017-06-09 01:20:48 +00001725 PPOpts.SingleFileParseMode = SingleFileParse;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001726
Daniel Dunbara5a166d2009-12-15 00:06:45 +00001727 // Override the resources path.
Daniel Dunbar6b03ece2010-01-30 21:47:16 +00001728 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001729
Erik Verbruggen6e922512012-04-12 10:11:59 +00001730 CI->getFrontendOpts().SkipFunctionBodies = SkipFunctionBodies;
1731
Argyrios Kyrtzidisa3e2ff12015-11-20 03:36:21 +00001732 if (ModuleFormat)
1733 CI->getHeaderSearchOpts().ModuleFormat = ModuleFormat.getValue();
1734
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001735 // Create the AST unit.
Ahmed Charlesb8984322014-03-07 20:03:18 +00001736 std::unique_ptr<ASTUnit> AST;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001737 AST.reset(new ASTUnit(false));
Justin Bognerdbbcb112014-10-14 23:36:06 +00001738 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001739 AST->Diagnostics = Diags;
Anders Carlssonc30dcec2011-03-18 18:22:40 +00001740 AST->FileSystemOpts = CI->getFileSystemOpts();
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001741 if (!VFS)
1742 VFS = vfs::getRealFileSystem();
1743 VFS = createVFSFromCompilerInvocation(*CI, *Diags, VFS);
Ben Langmuir8832c062014-04-15 18:16:25 +00001744 if (!VFS)
1745 return nullptr;
1746 AST->FileMgr = new FileManager(AST->FileSystemOpts, VFS);
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00001747 AST->PCMCache = new MemoryBufferCache;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001748 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001749 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor69f74f82011-08-25 22:30:56 +00001750 AST->TUKind = TUKind;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001751 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenko3292d062012-07-02 17:35:10 +00001752 AST->IncludeBriefCommentsInCodeCompletion
1753 = IncludeBriefCommentsInCodeCompletion;
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +00001754 AST->UserFilesAreVolatile = UserFilesAreVolatile;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001755 AST->NumStoredDiagnosticsFromDriver = StoredDiagnostics.size();
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001756 AST->StoredDiagnostics.swap(StoredDiagnostics);
Ted Kremenek5e14d392011-03-21 18:40:17 +00001757 AST->Invocation = CI;
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00001758 if (ForSerialization)
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00001759 AST->WriterData.reset(new ASTWriterData(*AST->PCMCache));
Alexey Samsonovb4f99dd2014-08-28 23:51:01 +00001760 // Zero out now to ease cleanup during crash recovery.
1761 CI = nullptr;
1762 Diags = nullptr;
Craig Topper49a27902014-05-22 04:46:25 +00001763
Ted Kremenek4422bfe2011-03-18 02:06:56 +00001764 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00001765 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1766 ASTUnitCleanup(AST.get());
Ted Kremenek4422bfe2011-03-18 02:06:56 +00001767
Benjamin Kramerd6da1a02016-06-12 20:05:23 +00001768 if (AST->LoadFromCompilerInvocation(std::move(PCHContainerOps),
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001769 PrecompilePreambleAfterNParses,
1770 VFS)) {
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001771 // Some error occurred, if caller wants to examine diagnostics, pass it the
1772 // ASTUnit.
1773 if (ErrAST) {
1774 AST->StoredDiagnostics.swap(AST->FailedParseDiagnostics);
1775 ErrAST->swap(AST);
1776 }
Craig Topper49a27902014-05-22 04:46:25 +00001777 return nullptr;
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001778 }
1779
Ahmed Charles9a16beb2014-03-07 19:33:25 +00001780 return AST.release();
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001781}
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001782
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001783bool ASTUnit::Reparse(std::shared_ptr<PCHContainerOperations> PCHContainerOps,
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001784 ArrayRef<RemappedFile> RemappedFiles,
1785 IntrusiveRefCntPtr<vfs::FileSystem> VFS) {
Ted Kremenek5e14d392011-03-21 18:40:17 +00001786 if (!Invocation)
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001787 return true;
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00001788
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001789 if (!VFS) {
1790 assert(FileMgr && "FileMgr is null on Reparse call");
1791 VFS = FileMgr->getVirtualFileSystem();
1792 }
1793
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00001794 clearFileLevelDecls();
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001795
Douglas Gregor16896c42010-10-28 15:44:59 +00001796 SimpleTimer ParsingTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00001797 ParsingTimer.setOutput("Reparsing " + getMainFileName());
Douglas Gregor16896c42010-10-28 15:44:59 +00001798
Douglas Gregor0e119552010-07-31 00:40:00 +00001799 // Remap files.
Douglas Gregor7b02b582010-08-20 00:02:33 +00001800 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
Alp Toker1b070d22014-07-07 07:47:20 +00001801 for (const auto &RB : PPOpts.RemappedFileBuffers)
1802 delete RB.second;
1803
Douglas Gregor0e119552010-07-31 00:40:00 +00001804 Invocation->getPreprocessorOpts().clearRemappedFiles();
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00001805 for (const auto &RemappedFile : RemappedFiles) {
1806 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFile.first,
1807 RemappedFile.second);
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00001808 }
Dmitri Gribenkoc444b572014-02-08 00:38:15 +00001809
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001810 // If we have a preamble file lying around, or if we might try to
1811 // build a precompiled preamble, do so now.
Rafael Espindola32482082014-08-18 16:23:45 +00001812 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
Ilya Biryukov200b3282017-06-21 10:24:58 +00001813 if (Preamble || PreambleRebuildCounter > 0)
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001814 OverrideMainBuffer =
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001815 getMainBufferWithPrecompiledPreamble(PCHContainerOps, *Invocation, VFS);
1816
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001817 // Clear out the diagnostics state.
Benjamin Kramerbc632902015-10-06 14:45:20 +00001818 FileMgr.reset();
Argyrios Kyrtzidisf50f7b22011-11-03 20:28:19 +00001819 getDiagnostics().Reset();
1820 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Argyrios Kyrtzidis462ff352011-11-03 20:57:33 +00001821 if (OverrideMainBuffer)
1822 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
Argyrios Kyrtzidisf50f7b22011-11-03 20:28:19 +00001823
Douglas Gregor4dde7492010-07-23 23:58:40 +00001824 // Parse the sources
Benjamin Kramerd6da1a02016-06-12 20:05:23 +00001825 bool Result =
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001826 Parse(std::move(PCHContainerOps), std::move(OverrideMainBuffer), VFS);
Rafael Espindola32482082014-08-18 16:23:45 +00001827
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001828 // If we're caching global code-completion results, and the top-level
Argyrios Kyrtzidis36893372011-10-31 21:25:31 +00001829 // declarations have changed, clear out the code-completion cache.
1830 if (!Result && ShouldCacheCodeCompletionResults &&
1831 CurrentTopLevelHashValue != CompletionCacheTopLevelHashValue)
1832 CacheCodeCompletionResults();
Douglas Gregordf7a79a2011-02-16 18:16:54 +00001833
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00001834 // We now need to clear out the completion info related to this translation
1835 // unit; it'll be recreated if necessary.
1836 CCTUInfo.reset();
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001837
Douglas Gregor4dde7492010-07-23 23:58:40 +00001838 return Result;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001839}
Douglas Gregor8e984da2010-08-04 16:47:14 +00001840
Erik Verbruggen346066b2017-05-30 14:25:54 +00001841void ASTUnit::ResetForParse() {
1842 SavedMainFileBuffer.reset();
1843
1844 SourceMgr.reset();
1845 TheSema.reset();
1846 Ctx.reset();
1847 PP.reset();
1848 Reader.reset();
1849
1850 TopLevelDecls.clear();
1851 clearFileLevelDecls();
1852}
1853
Douglas Gregorb14904c2010-08-13 22:48:40 +00001854//----------------------------------------------------------------------------//
1855// Code completion
1856//----------------------------------------------------------------------------//
1857
1858namespace {
Eugene Zelenko4f233182018-03-22 00:53:26 +00001859
Douglas Gregorb14904c2010-08-13 22:48:40 +00001860 /// \brief Code completion consumer that combines the cached code-completion
1861 /// results from an ASTUnit with the code-completion results provided to it,
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001862 /// then passes the result on to
Douglas Gregorb14904c2010-08-13 22:48:40 +00001863 class AugmentedCodeCompleteConsumer : public CodeCompleteConsumer {
Richard Smith697cc9e2012-08-14 03:13:00 +00001864 uint64_t NormalContexts;
Douglas Gregorb14904c2010-08-13 22:48:40 +00001865 ASTUnit &AST;
1866 CodeCompleteConsumer &Next;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001867
Douglas Gregorb14904c2010-08-13 22:48:40 +00001868 public:
1869 AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next,
Dmitri Gribenko3292d062012-07-02 17:35:10 +00001870 const CodeCompleteOptions &CodeCompleteOpts)
Eugene Zelenko4f233182018-03-22 00:53:26 +00001871 : CodeCompleteConsumer(CodeCompleteOpts, Next.isOutputBinary()),
1872 AST(AST), Next(Next) {
Douglas Gregorb14904c2010-08-13 22:48:40 +00001873 // Compute the set of contexts in which we will look when we don't have
1874 // any information about the specific context.
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001875 NormalContexts
Richard Smith697cc9e2012-08-14 03:13:00 +00001876 = (1LL << CodeCompletionContext::CCC_TopLevel)
1877 | (1LL << CodeCompletionContext::CCC_ObjCInterface)
1878 | (1LL << CodeCompletionContext::CCC_ObjCImplementation)
1879 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
1880 | (1LL << CodeCompletionContext::CCC_Statement)
1881 | (1LL << CodeCompletionContext::CCC_Expression)
1882 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
1883 | (1LL << CodeCompletionContext::CCC_DotMemberAccess)
1884 | (1LL << CodeCompletionContext::CCC_ArrowMemberAccess)
1885 | (1LL << CodeCompletionContext::CCC_ObjCPropertyAccess)
1886 | (1LL << CodeCompletionContext::CCC_ObjCProtocolName)
1887 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
1888 | (1LL << CodeCompletionContext::CCC_Recovery);
Douglas Gregor5e35d592010-09-14 23:59:36 +00001889
David Blaikiebbafb8a2012-03-11 07:00:24 +00001890 if (AST.getASTContext().getLangOpts().CPlusPlus)
Richard Smith697cc9e2012-08-14 03:13:00 +00001891 NormalContexts |= (1LL << CodeCompletionContext::CCC_EnumTag)
1892 | (1LL << CodeCompletionContext::CCC_UnionTag)
1893 | (1LL << CodeCompletionContext::CCC_ClassOrStructTag);
Douglas Gregorb14904c2010-08-13 22:48:40 +00001894 }
Craig Topperafa7cb32014-03-13 06:07:04 +00001895
1896 void ProcessCodeCompleteResults(Sema &S, CodeCompletionContext Context,
1897 CodeCompletionResult *Results,
1898 unsigned NumResults) override;
1899
1900 void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
1901 OverloadCandidate *Candidates,
1902 unsigned NumCandidates) override {
Douglas Gregorb14904c2010-08-13 22:48:40 +00001903 Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates);
1904 }
Craig Topperafa7cb32014-03-13 06:07:04 +00001905
1906 CodeCompletionAllocator &getAllocator() override {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001907 return Next.getAllocator();
1908 }
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00001909
Craig Topperafa7cb32014-03-13 06:07:04 +00001910 CodeCompletionTUInfo &getCodeCompletionTUInfo() override {
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00001911 return Next.getCodeCompletionTUInfo();
1912 }
Douglas Gregorb14904c2010-08-13 22:48:40 +00001913 };
Eugene Zelenko4f233182018-03-22 00:53:26 +00001914
1915} // namespace
Douglas Gregord46cf182010-08-16 20:01:48 +00001916
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001917/// \brief Helper function that computes which global names are hidden by the
1918/// local code-completion results.
Ted Kremenek6a153372010-11-07 06:11:36 +00001919static void CalculateHiddenNames(const CodeCompletionContext &Context,
1920 CodeCompletionResult *Results,
1921 unsigned NumResults,
1922 ASTContext &Ctx,
1923 llvm::StringSet<llvm::BumpPtrAllocator> &HiddenNames){
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001924 bool OnlyTagNames = false;
1925 switch (Context.getKind()) {
Douglas Gregor0ac41382010-09-23 23:01:17 +00001926 case CodeCompletionContext::CCC_Recovery:
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001927 case CodeCompletionContext::CCC_TopLevel:
1928 case CodeCompletionContext::CCC_ObjCInterface:
1929 case CodeCompletionContext::CCC_ObjCImplementation:
1930 case CodeCompletionContext::CCC_ObjCIvarList:
1931 case CodeCompletionContext::CCC_ClassStructUnion:
1932 case CodeCompletionContext::CCC_Statement:
1933 case CodeCompletionContext::CCC_Expression:
1934 case CodeCompletionContext::CCC_ObjCMessageReceiver:
Douglas Gregor21325842011-07-07 16:03:39 +00001935 case CodeCompletionContext::CCC_DotMemberAccess:
1936 case CodeCompletionContext::CCC_ArrowMemberAccess:
1937 case CodeCompletionContext::CCC_ObjCPropertyAccess:
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001938 case CodeCompletionContext::CCC_Namespace:
1939 case CodeCompletionContext::CCC_Type:
Douglas Gregorc49f5b22010-08-23 18:23:48 +00001940 case CodeCompletionContext::CCC_Name:
1941 case CodeCompletionContext::CCC_PotentiallyQualifiedName:
Douglas Gregor5e35d592010-09-14 23:59:36 +00001942 case CodeCompletionContext::CCC_ParenthesizedExpression:
Douglas Gregor2c595ad2011-07-30 06:55:39 +00001943 case CodeCompletionContext::CCC_ObjCInterfaceName:
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001944 break;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001945
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001946 case CodeCompletionContext::CCC_EnumTag:
1947 case CodeCompletionContext::CCC_UnionTag:
1948 case CodeCompletionContext::CCC_ClassOrStructTag:
1949 OnlyTagNames = true;
1950 break;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001951
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001952 case CodeCompletionContext::CCC_ObjCProtocolName:
Douglas Gregor12785102010-08-24 20:21:13 +00001953 case CodeCompletionContext::CCC_MacroName:
1954 case CodeCompletionContext::CCC_MacroNameUse:
Douglas Gregorec00a262010-08-24 22:20:20 +00001955 case CodeCompletionContext::CCC_PreprocessorExpression:
Douglas Gregor0de55ce2010-08-25 18:41:16 +00001956 case CodeCompletionContext::CCC_PreprocessorDirective:
Douglas Gregorea147052010-08-25 18:04:30 +00001957 case CodeCompletionContext::CCC_NaturalLanguage:
Douglas Gregor67c692c2010-08-26 15:07:07 +00001958 case CodeCompletionContext::CCC_SelectorName:
Douglas Gregor28c78432010-08-27 17:35:51 +00001959 case CodeCompletionContext::CCC_TypeQualifiers:
Douglas Gregor0ac41382010-09-23 23:01:17 +00001960 case CodeCompletionContext::CCC_Other:
Douglas Gregor3a69eaf2011-02-18 23:30:37 +00001961 case CodeCompletionContext::CCC_OtherWithMacros:
Douglas Gregor21325842011-07-07 16:03:39 +00001962 case CodeCompletionContext::CCC_ObjCInstanceMessage:
1963 case CodeCompletionContext::CCC_ObjCClassMessage:
1964 case CodeCompletionContext::CCC_ObjCCategoryName:
Douglas Gregor0de55ce2010-08-25 18:41:16 +00001965 // We're looking for nothing, or we're looking for names that cannot
1966 // be hidden.
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001967 return;
1968 }
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001969
Eugene Zelenko4f233182018-03-22 00:53:26 +00001970 using Result = CodeCompletionResult;
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001971 for (unsigned I = 0; I != NumResults; ++I) {
1972 if (Results[I].Kind != Result::RK_Declaration)
1973 continue;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001974
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001975 unsigned IDNS
1976 = Results[I].Declaration->getUnderlyingDecl()->getIdentifierNamespace();
1977
1978 bool Hiding = false;
1979 if (OnlyTagNames)
1980 Hiding = (IDNS & Decl::IDNS_Tag);
1981 else {
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001982 unsigned HiddenIDNS = (Decl::IDNS_Type | Decl::IDNS_Member |
Douglas Gregor59cab552010-08-16 23:05:20 +00001983 Decl::IDNS_Namespace | Decl::IDNS_Ordinary |
1984 Decl::IDNS_NonMemberOperator);
David Blaikiebbafb8a2012-03-11 07:00:24 +00001985 if (Ctx.getLangOpts().CPlusPlus)
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001986 HiddenIDNS |= Decl::IDNS_Tag;
1987 Hiding = (IDNS & HiddenIDNS);
1988 }
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001989
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001990 if (!Hiding)
1991 continue;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001992
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001993 DeclarationName Name = Results[I].Declaration->getDeclName();
1994 if (IdentifierInfo *Identifier = Name.getAsIdentifierInfo())
1995 HiddenNames.insert(Identifier->getName());
1996 else
1997 HiddenNames.insert(Name.getAsString());
1998 }
1999}
2000
Douglas Gregord46cf182010-08-16 20:01:48 +00002001void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &S,
2002 CodeCompletionContext Context,
John McCall276321a2010-08-25 06:19:51 +00002003 CodeCompletionResult *Results,
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002004 unsigned NumResults) {
Douglas Gregord46cf182010-08-16 20:01:48 +00002005 // Merge the results we were given with the results we cached.
2006 bool AddedResult = false;
Richard Smith697cc9e2012-08-14 03:13:00 +00002007 uint64_t InContexts =
2008 Context.getKind() == CodeCompletionContext::CCC_Recovery
2009 ? NormalContexts : (1LL << Context.getKind());
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002010 // Contains the set of names that are hidden by "local" completion results.
Ted Kremenek6a153372010-11-07 06:11:36 +00002011 llvm::StringSet<llvm::BumpPtrAllocator> HiddenNames;
Eugene Zelenko4f233182018-03-22 00:53:26 +00002012 using Result = CodeCompletionResult;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002013 SmallVector<Result, 8> AllResults;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002014 for (ASTUnit::cached_completion_iterator
Douglas Gregordf239672010-08-16 21:23:13 +00002015 C = AST.cached_completion_begin(),
2016 CEnd = AST.cached_completion_end();
Douglas Gregord46cf182010-08-16 20:01:48 +00002017 C != CEnd; ++C) {
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002018 // If the context we are in matches any of the contexts we are
Douglas Gregord46cf182010-08-16 20:01:48 +00002019 // interested in, we'll add this result.
2020 if ((C->ShowInContexts & InContexts) == 0)
2021 continue;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002022
Douglas Gregord46cf182010-08-16 20:01:48 +00002023 // If we haven't added any results previously, do so now.
2024 if (!AddedResult) {
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002025 CalculateHiddenNames(Context, Results, NumResults, S.Context,
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002026 HiddenNames);
Douglas Gregord46cf182010-08-16 20:01:48 +00002027 AllResults.insert(AllResults.end(), Results, Results + NumResults);
2028 AddedResult = true;
2029 }
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002030
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002031 // Determine whether this global completion result is hidden by a local
2032 // completion result. If so, skip it.
2033 if (C->Kind != CXCursor_MacroDefinition &&
2034 HiddenNames.count(C->Completion->getTypedText()))
2035 continue;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002036
Douglas Gregord46cf182010-08-16 20:01:48 +00002037 // Adjust priority based on similar type classes.
2038 unsigned Priority = C->Priority;
Douglas Gregor12785102010-08-24 20:21:13 +00002039 CodeCompletionString *Completion = C->Completion;
Douglas Gregord46cf182010-08-16 20:01:48 +00002040 if (!Context.getPreferredType().isNull()) {
2041 if (C->Kind == CXCursor_MacroDefinition) {
2042 Priority = getMacroUsagePriority(C->Completion->getTypedText(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00002043 S.getLangOpts(),
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002044 Context.getPreferredType()->isAnyPointerType());
Douglas Gregord46cf182010-08-16 20:01:48 +00002045 } else if (C->Type) {
2046 CanQualType Expected
Douglas Gregordf239672010-08-16 21:23:13 +00002047 = S.Context.getCanonicalType(
Douglas Gregord46cf182010-08-16 20:01:48 +00002048 Context.getPreferredType().getUnqualifiedType());
2049 SimplifiedTypeClass ExpectedSTC = getSimplifiedTypeClass(Expected);
2050 if (ExpectedSTC == C->TypeClass) {
2051 // We know this type is similar; check for an exact match.
2052 llvm::StringMap<unsigned> &CachedCompletionTypes
Douglas Gregordf239672010-08-16 21:23:13 +00002053 = AST.getCachedCompletionTypes();
Douglas Gregord46cf182010-08-16 20:01:48 +00002054 llvm::StringMap<unsigned>::iterator Pos
Douglas Gregordf239672010-08-16 21:23:13 +00002055 = CachedCompletionTypes.find(QualType(Expected).getAsString());
Douglas Gregord46cf182010-08-16 20:01:48 +00002056 if (Pos != CachedCompletionTypes.end() && Pos->second == C->Type)
2057 Priority /= CCF_ExactTypeMatch;
2058 else
2059 Priority /= CCF_SimilarTypeMatch;
2060 }
2061 }
2062 }
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002063
Douglas Gregor12785102010-08-24 20:21:13 +00002064 // Adjust the completion string, if required.
2065 if (C->Kind == CXCursor_MacroDefinition &&
2066 Context.getKind() == CodeCompletionContext::CCC_MacroNameUse) {
2067 // Create a new code-completion string that just contains the
2068 // macro name, without its arguments.
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00002069 CodeCompletionBuilder Builder(getAllocator(), getCodeCompletionTUInfo(),
2070 CCP_CodePattern, C->Availability);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002071 Builder.AddTypedTextChunk(C->Completion->getTypedText());
Douglas Gregor8850aa32010-08-25 18:03:13 +00002072 Priority = CCP_CodePattern;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002073 Completion = Builder.TakeString();
Douglas Gregor12785102010-08-24 20:21:13 +00002074 }
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002075
Argyrios Kyrtzidis5c8b1cd2012-09-27 00:24:09 +00002076 AllResults.push_back(Result(Completion, Priority, C->Kind,
Douglas Gregorf757a122010-08-23 23:00:57 +00002077 C->Availability));
Douglas Gregord46cf182010-08-16 20:01:48 +00002078 }
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002079
Douglas Gregord46cf182010-08-16 20:01:48 +00002080 // If we did not add any cached completion results, just forward the
2081 // results we were given to the next consumer.
2082 if (!AddedResult) {
2083 Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
2084 return;
2085 }
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002086
Douglas Gregord46cf182010-08-16 20:01:48 +00002087 Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
2088 AllResults.size());
2089}
2090
Adrian Prantlbb165fb2015-06-20 18:53:08 +00002091void ASTUnit::CodeComplete(
2092 StringRef File, unsigned Line, unsigned Column,
2093 ArrayRef<RemappedFile> RemappedFiles, bool IncludeMacros,
2094 bool IncludeCodePatterns, bool IncludeBriefComments,
2095 CodeCompleteConsumer &Consumer,
2096 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
2097 DiagnosticsEngine &Diag, LangOptions &LangOpts, SourceManager &SourceMgr,
2098 FileManager &FileMgr, SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
2099 SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers) {
Ted Kremenek5e14d392011-03-21 18:40:17 +00002100 if (!Invocation)
Douglas Gregor8e984da2010-08-04 16:47:14 +00002101 return;
2102
Douglas Gregor16896c42010-10-28 15:44:59 +00002103 SimpleTimer CompletionTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00002104 CompletionTimer.setOutput("Code completion @ " + File + ":" +
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002105 Twine(Line) + ":" + Twine(Column));
Douglas Gregor028d3e42010-08-09 20:45:32 +00002106
David Blaikieea4395e2017-01-06 19:49:01 +00002107 auto CCInvocation = std::make_shared<CompilerInvocation>(*Invocation);
Ted Kremenek5e14d392011-03-21 18:40:17 +00002108
2109 FrontendOptions &FrontendOpts = CCInvocation->getFrontendOpts();
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002110 CodeCompleteOptions &CodeCompleteOpts = FrontendOpts.CodeCompleteOpts;
Ted Kremenek5e14d392011-03-21 18:40:17 +00002111 PreprocessorOptions &PreprocessorOpts = CCInvocation->getPreprocessorOpts();
Douglas Gregorb68bc592010-08-05 09:09:23 +00002112
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002113 CodeCompleteOpts.IncludeMacros = IncludeMacros &&
2114 CachedCompletionResults.empty();
2115 CodeCompleteOpts.IncludeCodePatterns = IncludeCodePatterns;
2116 CodeCompleteOpts.IncludeGlobals = CachedCompletionResults.empty();
2117 CodeCompleteOpts.IncludeBriefComments = IncludeBriefComments;
Sam McCallbb2cf632018-01-12 14:51:47 +00002118 CodeCompleteOpts.LoadExternal = Consumer.loadExternal();
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002119
2120 assert(IncludeBriefComments == this->IncludeBriefCommentsInCodeCompletion);
2121
Douglas Gregor8e984da2010-08-04 16:47:14 +00002122 FrontendOpts.CodeCompletionAt.FileName = File;
2123 FrontendOpts.CodeCompletionAt.Line = Line;
2124 FrontendOpts.CodeCompletionAt.Column = Column;
2125
2126 // Set the language options appropriately.
Ted Kremenek8cf47df2011-11-17 23:01:24 +00002127 LangOpts = *CCInvocation->getLangOpts();
Douglas Gregor8e984da2010-08-04 16:47:14 +00002128
Argyrios Kyrtzidis06e8d692014-10-31 16:44:32 +00002129 // Spell-checking and warnings are wasteful during code-completion.
2130 LangOpts.SpellChecking = false;
2131 CCInvocation->getDiagnosticOpts().IgnoreWarnings = true;
2132
Adrian Prantlbb165fb2015-06-20 18:53:08 +00002133 std::unique_ptr<CompilerInstance> Clang(
2134 new CompilerInstance(PCHContainerOps));
Ted Kremenek84de4a12011-03-21 18:40:07 +00002135
2136 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00002137 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
2138 CICleanup(Clang.get());
Ted Kremenek84de4a12011-03-21 18:40:07 +00002139
David Blaikieea4395e2017-01-06 19:49:01 +00002140 auto &Inv = *CCInvocation;
2141 Clang->setInvocation(std::move(CCInvocation));
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00002142 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002143
Douglas Gregor8e984da2010-08-04 16:47:14 +00002144 // Set up diagnostics, capturing any diagnostics produced.
Ted Kremenek84de4a12011-03-21 18:40:07 +00002145 Clang->setDiagnostics(&Diag);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002146 CaptureDroppedDiagnostics Capture(true,
2147 Clang->getDiagnostics(),
Ilya Biryukov200b3282017-06-21 10:24:58 +00002148 &StoredDiagnostics, nullptr);
David Blaikieea4395e2017-01-06 19:49:01 +00002149 ProcessWarningOptions(Diag, Inv.getDiagnosticOpts());
2150
Douglas Gregor8e984da2010-08-04 16:47:14 +00002151 // Create the target instance.
Alp Toker80758082014-07-06 05:26:44 +00002152 Clang->setTarget(TargetInfo::CreateTargetInfo(
Saleem Abdulrasool10a49722016-04-08 16:52:00 +00002153 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
Ted Kremenek84de4a12011-03-21 18:40:07 +00002154 if (!Clang->hasTarget()) {
Craig Topper49a27902014-05-22 04:46:25 +00002155 Clang->setInvocation(nullptr);
Douglas Gregor2dd19f12010-08-18 22:29:43 +00002156 return;
Douglas Gregor8e984da2010-08-04 16:47:14 +00002157 }
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002158
Douglas Gregor8e984da2010-08-04 16:47:14 +00002159 // Inform the target of the language options.
2160 //
2161 // FIXME: We shouldn't need to do this, the target should be immutable once
2162 // created. This complexity should be lifted elsewhere.
Alp Toker74437972014-07-06 05:14:24 +00002163 Clang->getTarget().adjust(Clang->getLangOpts());
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002164
Ted Kremenek84de4a12011-03-21 18:40:07 +00002165 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Douglas Gregor8e984da2010-08-04 16:47:14 +00002166 "Invocation must have exactly one source file!");
Richard Smith40c0efa2017-04-26 18:57:40 +00002167 assert(Clang->getFrontendOpts().Inputs[0].getKind().getFormat() ==
2168 InputKind::Source &&
Douglas Gregor8e984da2010-08-04 16:47:14 +00002169 "FIXME: AST inputs not yet supported here!");
Richard Smith40c0efa2017-04-26 18:57:40 +00002170 assert(Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() !=
2171 InputKind::LLVM_IR &&
Douglas Gregor8e984da2010-08-04 16:47:14 +00002172 "IR inputs not support here!");
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002173
Douglas Gregor8e984da2010-08-04 16:47:14 +00002174 // Use the source and file managers that we were given.
Ted Kremenek84de4a12011-03-21 18:40:07 +00002175 Clang->setFileManager(&FileMgr);
2176 Clang->setSourceManager(&SourceMgr);
Douglas Gregor8e984da2010-08-04 16:47:14 +00002177
2178 // Remap files.
2179 PreprocessorOpts.clearRemappedFiles();
Douglas Gregord8a5dba2010-08-04 17:07:00 +00002180 PreprocessorOpts.RetainRemappedFileBuffers = true;
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00002181 for (const auto &RemappedFile : RemappedFiles) {
2182 PreprocessorOpts.addRemappedFile(RemappedFile.first, RemappedFile.second);
2183 OwnedBuffers.push_back(RemappedFile.second);
Douglas Gregorb97b6662010-08-20 00:59:43 +00002184 }
Dmitri Gribenkoc444b572014-02-08 00:38:15 +00002185
Douglas Gregorb14904c2010-08-13 22:48:40 +00002186 // Use the code completion consumer we were given, but adding any cached
2187 // code-completion results.
Douglas Gregore9186e62010-11-29 16:13:56 +00002188 AugmentedCodeCompleteConsumer *AugmentedConsumer
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002189 = new AugmentedCodeCompleteConsumer(*this, Consumer, CodeCompleteOpts);
Ted Kremenek84de4a12011-03-21 18:40:07 +00002190 Clang->setCodeCompletionConsumer(AugmentedConsumer);
Douglas Gregor8e984da2010-08-04 16:47:14 +00002191
Douglas Gregor028d3e42010-08-09 20:45:32 +00002192 // If we have a precompiled preamble, try to use it. We only allow
2193 // the use of the precompiled preamble if we're if the completion
2194 // point is within the main file, after the end of the precompiled
2195 // preamble.
Rafael Espindola2346a372014-08-18 18:47:08 +00002196 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
Ilya Biryukov200b3282017-06-21 10:24:58 +00002197 if (Preamble) {
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00002198 std::string CompleteFilePath(File);
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00002199
Ilya Biryukovaf69e402017-05-23 11:37:52 +00002200 auto VFS = FileMgr.getVirtualFileSystem();
2201 auto CompleteFileStatus = VFS->status(CompleteFilePath);
2202 if (CompleteFileStatus) {
2203 llvm::sys::fs::UniqueID CompleteFileID = CompleteFileStatus->getUniqueID();
2204
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00002205 std::string MainPath(OriginalSourceFile);
Ilya Biryukovaf69e402017-05-23 11:37:52 +00002206 auto MainStatus = VFS->status(MainPath);
2207 if (MainStatus) {
2208 llvm::sys::fs::UniqueID MainID = MainStatus->getUniqueID();
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00002209 if (CompleteFileID == MainID && Line > 1)
Rafael Espindola2346a372014-08-18 18:47:08 +00002210 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(
Ilya Biryukovaf69e402017-05-23 11:37:52 +00002211 PCHContainerOps, Inv, VFS, false, Line - 1);
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00002212 }
2213 }
Douglas Gregor028d3e42010-08-09 20:45:32 +00002214 }
2215
2216 // If the main file has been overridden due to the use of a preamble,
2217 // make that override happen and introduce the preamble.
2218 if (OverrideMainBuffer) {
Ilya Biryukov417085a2017-11-16 16:25:01 +00002219 assert(Preamble &&
2220 "No preamble was built, but OverrideMainBuffer is not null");
2221
2222 auto VFS = FileMgr.getVirtualFileSystem();
2223 Preamble->AddImplicitPreamble(Clang->getInvocation(), VFS,
2224 OverrideMainBuffer.get());
2225 // FIXME: there is no way to update VFS if it was changed by
2226 // AddImplicitPreamble as FileMgr is accepted as a parameter by this method.
2227 // We use on-disk preambles instead and rely on FileMgr's VFS to ensure the
2228 // PCH files are always readable.
Rafael Espindola2346a372014-08-18 18:47:08 +00002229 OwnedBuffers.push_back(OverrideMainBuffer.release());
Douglas Gregor7b02b582010-08-20 00:02:33 +00002230 } else {
2231 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
2232 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregor028d3e42010-08-09 20:45:32 +00002233 }
2234
Argyrios Kyrtzidis870704f2012-11-02 22:18:44 +00002235 // Disable the preprocessing record if modules are not enabled.
2236 if (!Clang->getLangOpts().Modules)
2237 PreprocessorOpts.DetailedRecord = false;
Ahmed Charlesb8984322014-03-07 20:03:18 +00002238
2239 std::unique_ptr<SyntaxOnlyAction> Act;
Douglas Gregor8e984da2010-08-04 16:47:14 +00002240 Act.reset(new SyntaxOnlyAction);
Douglas Gregor32fbe312012-01-20 16:28:04 +00002241 if (Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
Douglas Gregor8e984da2010-08-04 16:47:14 +00002242 Act->Execute();
2243 Act->EndSourceFile();
2244 }
Douglas Gregor8e984da2010-08-04 16:47:14 +00002245}
Douglas Gregore9386682010-08-13 05:36:37 +00002246
Argyrios Kyrtzidis39a76382012-09-26 16:39:46 +00002247bool ASTUnit::Save(StringRef File) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00002248 if (HadModuleLoaderFatalFailure)
2249 return true;
2250
Argyrios Kyrtzidis55e75572011-07-21 18:44:49 +00002251 // Write to a temporary file and later rename it to the actual file, to avoid
2252 // possible race conditions.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00002253 SmallString<128> TempPath;
Argyrios Kyrtzidis08a2bfd2011-07-28 00:45:10 +00002254 TempPath = File;
2255 TempPath += "-%%%%%%%%";
2256 int fd;
Yaron Keren92e1b622015-03-18 10:17:07 +00002257 if (llvm::sys::fs::createUniqueFile(TempPath, fd, TempPath))
Argyrios Kyrtzidis39a76382012-09-26 16:39:46 +00002258 return true;
Argyrios Kyrtzidis55e75572011-07-21 18:44:49 +00002259
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002260 // FIXME: Can we somehow regenerate the stat cache here, or do we need to
Douglas Gregore9386682010-08-13 05:36:37 +00002261 // unconditionally create a stat cache when we parse the file?
Argyrios Kyrtzidis08a2bfd2011-07-28 00:45:10 +00002262 llvm::raw_fd_ostream Out(fd, /*shouldClose=*/true);
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00002263
2264 serialize(Out);
2265 Out.close();
Argyrios Kyrtzidiseeea16a2012-03-13 02:17:06 +00002266 if (Out.has_error()) {
2267 Out.clear_error();
Argyrios Kyrtzidis39a76382012-09-26 16:39:46 +00002268 return true;
Argyrios Kyrtzidiseeea16a2012-03-13 02:17:06 +00002269 }
Argyrios Kyrtzidis55e75572011-07-21 18:44:49 +00002270
Yaron Keren92e1b622015-03-18 10:17:07 +00002271 if (llvm::sys::fs::rename(TempPath, File)) {
2272 llvm::sys::fs::remove(TempPath);
Argyrios Kyrtzidis39a76382012-09-26 16:39:46 +00002273 return true;
Argyrios Kyrtzidis55e75572011-07-21 18:44:49 +00002274 }
2275
Argyrios Kyrtzidis39a76382012-09-26 16:39:46 +00002276 return false;
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00002277}
2278
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00002279static bool serializeUnit(ASTWriter &Writer,
2280 SmallVectorImpl<char> &Buffer,
2281 Sema &S,
2282 bool hasErrors,
2283 raw_ostream &OS) {
Craig Topper49a27902014-05-22 04:46:25 +00002284 Writer.WriteAST(S, std::string(), nullptr, "", hasErrors);
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00002285
2286 // Write the generated bitstream to "Out".
2287 if (!Buffer.empty())
2288 OS.write(Buffer.data(), Buffer.size());
2289
2290 return false;
2291}
2292
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002293bool ASTUnit::serialize(raw_ostream &OS) {
Argyrios Kyrtzidis70ec1c72016-07-13 20:35:26 +00002294 // For serialization we are lenient if the errors were only warn-as-error kind.
2295 bool hasErrors = getDiagnostics().hasUncompilableErrorOccurred();
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00002296
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00002297 if (WriterData)
2298 return serializeUnit(WriterData->Writer, WriterData->Buffer,
2299 getSema(), hasErrors, OS);
2300
Daniel Dunbar9a963862012-02-29 20:31:23 +00002301 SmallString<128> Buffer;
Douglas Gregore9386682010-08-13 05:36:37 +00002302 llvm::BitstreamWriter Stream(Buffer);
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00002303 MemoryBufferCache PCMCache;
2304 ASTWriter Writer(Stream, Buffer, PCMCache, {});
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00002305 return serializeUnit(Writer, Buffer, getSema(), hasErrors, OS);
Douglas Gregore9386682010-08-13 05:36:37 +00002306}
Douglas Gregor925296b2011-07-19 16:10:42 +00002307
Eugene Zelenko4f233182018-03-22 00:53:26 +00002308using SLocRemap = ContinuousRangeMap<unsigned, int, 2>;
Douglas Gregor925296b2011-07-19 16:10:42 +00002309
Douglas Gregor925296b2011-07-19 16:10:42 +00002310void ASTUnit::TranslateStoredDiagnostics(
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002311 FileManager &FileMgr,
Douglas Gregor925296b2011-07-19 16:10:42 +00002312 SourceManager &SrcMgr,
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002313 const SmallVectorImpl<StandaloneDiagnostic> &Diags,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002314 SmallVectorImpl<StoredDiagnostic> &Out) {
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002315 // Map the standalone diagnostic into the new source manager. We also need to
2316 // remap all the locations to the new view. This includes the diag location,
2317 // any associated source ranges, and the source ranges of associated fix-its.
Douglas Gregor925296b2011-07-19 16:10:42 +00002318 // FIXME: There should be a cleaner way to do this.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002319 SmallVector<StoredDiagnostic, 4> Result;
Douglas Gregor925296b2011-07-19 16:10:42 +00002320 Result.reserve(Diags.size());
Erik Verbruggenefe6fa52017-06-09 08:29:58 +00002321
Eugene Zelenko4f233182018-03-22 00:53:26 +00002322 for (const auto &SD : Diags) {
Douglas Gregor925296b2011-07-19 16:10:42 +00002323 // Rebuild the StoredDiagnostic.
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002324 if (SD.Filename.empty())
2325 continue;
2326 const FileEntry *FE = FileMgr.getFile(SD.Filename);
2327 if (!FE)
2328 continue;
Erik Verbruggenefe6fa52017-06-09 08:29:58 +00002329 SourceLocation FileLoc;
2330 auto ItFileID = PreambleSrcLocCache.find(SD.Filename);
2331 if (ItFileID == PreambleSrcLocCache.end()) {
2332 FileID FID = SrcMgr.translateFile(FE);
2333 FileLoc = SrcMgr.getLocForStartOfFile(FID);
2334 PreambleSrcLocCache[SD.Filename] = FileLoc;
2335 } else {
2336 FileLoc = ItFileID->getValue();
Erik Verbruggen2c7c38d2017-02-16 09:49:30 +00002337 }
Erik Verbruggenefe6fa52017-06-09 08:29:58 +00002338
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002339 if (FileLoc.isInvalid())
2340 continue;
2341 SourceLocation L = FileLoc.getLocWithOffset(SD.LocOffset);
Douglas Gregor925296b2011-07-19 16:10:42 +00002342 FullSourceLoc Loc(L, SrcMgr);
2343
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002344 SmallVector<CharSourceRange, 4> Ranges;
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002345 Ranges.reserve(SD.Ranges.size());
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00002346 for (const auto &Range : SD.Ranges) {
2347 SourceLocation BL = FileLoc.getLocWithOffset(Range.first);
2348 SourceLocation EL = FileLoc.getLocWithOffset(Range.second);
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002349 Ranges.push_back(CharSourceRange::getCharRange(BL, EL));
Douglas Gregor925296b2011-07-19 16:10:42 +00002350 }
2351
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002352 SmallVector<FixItHint, 2> FixIts;
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002353 FixIts.reserve(SD.FixIts.size());
Eugene Zelenko4f233182018-03-22 00:53:26 +00002354 for (const auto &FixIt : SD.FixIts) {
Douglas Gregor925296b2011-07-19 16:10:42 +00002355 FixIts.push_back(FixItHint());
2356 FixItHint &FH = FixIts.back();
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00002357 FH.CodeToInsert = FixIt.CodeToInsert;
2358 SourceLocation BL = FileLoc.getLocWithOffset(FixIt.RemoveRange.first);
2359 SourceLocation EL = FileLoc.getLocWithOffset(FixIt.RemoveRange.second);
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002360 FH.RemoveRange = CharSourceRange::getCharRange(BL, EL);
Douglas Gregor925296b2011-07-19 16:10:42 +00002361 }
2362
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002363 Result.push_back(StoredDiagnostic(SD.Level, SD.ID,
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002364 SD.Message, Loc, Ranges, FixIts));
Douglas Gregor925296b2011-07-19 16:10:42 +00002365 }
2366 Result.swap(Out);
2367}
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002368
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00002369void ASTUnit::addFileLevelDecl(Decl *D) {
2370 assert(D);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002371
Douglas Gregor61d63d02011-11-07 18:53:57 +00002372 // We only care about local declarations.
2373 if (D->isFromASTFile())
2374 return;
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00002375
2376 SourceManager &SM = *SourceMgr;
2377 SourceLocation Loc = D->getLocation();
2378 if (Loc.isInvalid() || !SM.isLocalSourceLocation(Loc))
2379 return;
2380
2381 // We only keep track of the file-level declarations of each file.
2382 if (!D->getLexicalDeclContext()->isFileContext())
2383 return;
2384
2385 SourceLocation FileLoc = SM.getFileLoc(Loc);
2386 assert(SM.isLocalSourceLocation(FileLoc));
2387 FileID FID;
2388 unsigned Offset;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002389 std::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc);
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00002390 if (FID.isInvalid())
2391 return;
2392
2393 LocDeclsTy *&Decls = FileDecls[FID];
2394 if (!Decls)
2395 Decls = new LocDeclsTy();
2396
2397 std::pair<unsigned, Decl *> LocDecl(Offset, D);
2398
2399 if (Decls->empty() || Decls->back().first <= Offset) {
2400 Decls->push_back(LocDecl);
2401 return;
2402 }
2403
Benjamin Kramer45025c02013-08-24 13:22:59 +00002404 LocDeclsTy::iterator I = std::upper_bound(Decls->begin(), Decls->end(),
2405 LocDecl, llvm::less_first());
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00002406
2407 Decls->insert(I, LocDecl);
2408}
2409
Argyrios Kyrtzidise9681522011-11-03 02:20:32 +00002410void ASTUnit::findFileRegionDecls(FileID File, unsigned Offset, unsigned Length,
2411 SmallVectorImpl<Decl *> &Decls) {
2412 if (File.isInvalid())
2413 return;
2414
2415 if (SourceMgr->isLoadedFileID(File)) {
2416 assert(Ctx->getExternalSource() && "No external source!");
2417 return Ctx->getExternalSource()->FindFileRegionDecls(File, Offset, Length,
2418 Decls);
2419 }
2420
2421 FileDeclsTy::iterator I = FileDecls.find(File);
2422 if (I == FileDecls.end())
2423 return;
2424
2425 LocDeclsTy &LocDecls = *I->second;
2426 if (LocDecls.empty())
2427 return;
2428
Benjamin Kramere3e855b2013-08-24 13:12:34 +00002429 LocDeclsTy::iterator BeginIt =
2430 std::lower_bound(LocDecls.begin(), LocDecls.end(),
Craig Topper49a27902014-05-22 04:46:25 +00002431 std::make_pair(Offset, (Decl *)nullptr),
2432 llvm::less_first());
Argyrios Kyrtzidise9681522011-11-03 02:20:32 +00002433 if (BeginIt != LocDecls.begin())
2434 --BeginIt;
2435
Argyrios Kyrtzidis8ad3bab2011-11-23 20:27:36 +00002436 // If we are pointing at a top-level decl inside an objc container, we need
2437 // to backtrack until we find it otherwise we will fail to report that the
2438 // region overlaps with an objc container.
2439 while (BeginIt != LocDecls.begin() &&
2440 BeginIt->second->isTopLevelDeclInObjCContainer())
2441 --BeginIt;
2442
Benjamin Kramere3e855b2013-08-24 13:12:34 +00002443 LocDeclsTy::iterator EndIt = std::upper_bound(
2444 LocDecls.begin(), LocDecls.end(),
Craig Topper49a27902014-05-22 04:46:25 +00002445 std::make_pair(Offset + Length, (Decl *)nullptr), llvm::less_first());
Argyrios Kyrtzidise9681522011-11-03 02:20:32 +00002446 if (EndIt != LocDecls.end())
2447 ++EndIt;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002448
Argyrios Kyrtzidise9681522011-11-03 02:20:32 +00002449 for (LocDeclsTy::iterator DIt = BeginIt; DIt != EndIt; ++DIt)
2450 Decls.push_back(DIt->second);
2451}
2452
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002453SourceLocation ASTUnit::getLocation(const FileEntry *File,
2454 unsigned Line, unsigned Col) const {
2455 const SourceManager &SM = getSourceManager();
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00002456 SourceLocation Loc = SM.translateFileLineCol(File, Line, Col);
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002457 return SM.getMacroArgExpandedLocation(Loc);
2458}
2459
2460SourceLocation ASTUnit::getLocation(const FileEntry *File,
2461 unsigned Offset) const {
2462 const SourceManager &SM = getSourceManager();
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00002463 SourceLocation FileLoc = SM.translateFileLineCol(File, 1, 1);
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002464 return SM.getMacroArgExpandedLocation(FileLoc.getLocWithOffset(Offset));
2465}
2466
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00002467/// \brief If \arg Loc is a loaded location from the preamble, returns
2468/// the corresponding local location of the main file, otherwise it returns
2469/// \arg Loc.
Vedant Kumar525a7f62017-07-25 19:53:27 +00002470SourceLocation ASTUnit::mapLocationFromPreamble(SourceLocation Loc) const {
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00002471 FileID PreambleID;
2472 if (SourceMgr)
2473 PreambleID = SourceMgr->getPreambleFileID();
2474
Ilya Biryukov200b3282017-06-21 10:24:58 +00002475 if (Loc.isInvalid() || !Preamble || PreambleID.isInvalid())
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00002476 return Loc;
2477
2478 unsigned Offs;
Ilya Biryukov200b3282017-06-21 10:24:58 +00002479 if (SourceMgr->isInFileID(Loc, PreambleID, &Offs) && Offs < Preamble->getBounds().Size) {
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00002480 SourceLocation FileLoc
2481 = SourceMgr->getLocForStartOfFile(SourceMgr->getMainFileID());
2482 return FileLoc.getLocWithOffset(Offs);
2483 }
2484
2485 return Loc;
2486}
2487
2488/// \brief If \arg Loc is a local location of the main file but inside the
2489/// preamble chunk, returns the corresponding loaded location from the
2490/// preamble, otherwise it returns \arg Loc.
Vedant Kumar525a7f62017-07-25 19:53:27 +00002491SourceLocation ASTUnit::mapLocationToPreamble(SourceLocation Loc) const {
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00002492 FileID PreambleID;
2493 if (SourceMgr)
2494 PreambleID = SourceMgr->getPreambleFileID();
2495
Ilya Biryukov200b3282017-06-21 10:24:58 +00002496 if (Loc.isInvalid() || !Preamble || PreambleID.isInvalid())
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00002497 return Loc;
2498
2499 unsigned Offs;
2500 if (SourceMgr->isInFileID(Loc, SourceMgr->getMainFileID(), &Offs) &&
Ilya Biryukov200b3282017-06-21 10:24:58 +00002501 Offs < Preamble->getBounds().Size) {
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00002502 SourceLocation FileLoc = SourceMgr->getLocForStartOfFile(PreambleID);
2503 return FileLoc.getLocWithOffset(Offs);
2504 }
2505
2506 return Loc;
2507}
2508
Vedant Kumar525a7f62017-07-25 19:53:27 +00002509bool ASTUnit::isInPreambleFileID(SourceLocation Loc) const {
Argyrios Kyrtzidis429ec022011-10-25 00:29:50 +00002510 FileID FID;
2511 if (SourceMgr)
2512 FID = SourceMgr->getPreambleFileID();
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002513
Argyrios Kyrtzidis429ec022011-10-25 00:29:50 +00002514 if (Loc.isInvalid() || FID.isInvalid())
2515 return false;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002516
Argyrios Kyrtzidis429ec022011-10-25 00:29:50 +00002517 return SourceMgr->isInFileID(Loc, FID);
2518}
2519
Vedant Kumar525a7f62017-07-25 19:53:27 +00002520bool ASTUnit::isInMainFileID(SourceLocation Loc) const {
Argyrios Kyrtzidis429ec022011-10-25 00:29:50 +00002521 FileID FID;
2522 if (SourceMgr)
2523 FID = SourceMgr->getMainFileID();
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002524
Argyrios Kyrtzidis429ec022011-10-25 00:29:50 +00002525 if (Loc.isInvalid() || FID.isInvalid())
2526 return false;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002527
Argyrios Kyrtzidis429ec022011-10-25 00:29:50 +00002528 return SourceMgr->isInFileID(Loc, FID);
2529}
2530
Vedant Kumar525a7f62017-07-25 19:53:27 +00002531SourceLocation ASTUnit::getEndOfPreambleFileID() const {
Argyrios Kyrtzidis429ec022011-10-25 00:29:50 +00002532 FileID FID;
2533 if (SourceMgr)
2534 FID = SourceMgr->getPreambleFileID();
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002535
Argyrios Kyrtzidis429ec022011-10-25 00:29:50 +00002536 if (FID.isInvalid())
Eugene Zelenko4f233182018-03-22 00:53:26 +00002537 return {};
Argyrios Kyrtzidis429ec022011-10-25 00:29:50 +00002538
2539 return SourceMgr->getLocForEndOfFile(FID);
2540}
2541
Vedant Kumar525a7f62017-07-25 19:53:27 +00002542SourceLocation ASTUnit::getStartOfMainFileID() const {
Argyrios Kyrtzidis429ec022011-10-25 00:29:50 +00002543 FileID FID;
2544 if (SourceMgr)
2545 FID = SourceMgr->getMainFileID();
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002546
Argyrios Kyrtzidis429ec022011-10-25 00:29:50 +00002547 if (FID.isInvalid())
Eugene Zelenko4f233182018-03-22 00:53:26 +00002548 return {};
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002549
Argyrios Kyrtzidis429ec022011-10-25 00:29:50 +00002550 return SourceMgr->getLocForStartOfFile(FID);
2551}
2552
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00002553llvm::iterator_range<PreprocessingRecord::iterator>
Argyrios Kyrtzidisd4fcf5802012-10-02 16:10:51 +00002554ASTUnit::getLocalPreprocessingEntities() const {
2555 if (isMainFileAST()) {
2556 serialization::ModuleFile &
2557 Mod = Reader->getModuleManager().getPrimaryModule();
2558 return Reader->getModulePreprocessedEntities(Mod);
2559 }
2560
2561 if (PreprocessingRecord *PPRec = PP->getPreprocessingRecord())
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00002562 return llvm::make_range(PPRec->local_begin(), PPRec->local_end());
Argyrios Kyrtzidisd4fcf5802012-10-02 16:10:51 +00002563
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00002564 return llvm::make_range(PreprocessingRecord::iterator(),
2565 PreprocessingRecord::iterator());
Argyrios Kyrtzidisd4fcf5802012-10-02 16:10:51 +00002566}
2567
Argyrios Kyrtzidise514b202012-10-03 01:58:28 +00002568bool ASTUnit::visitLocalTopLevelDecls(void *context, DeclVisitorFn Fn) {
Argyrios Kyrtzidis10e78462012-10-02 21:09:13 +00002569 if (isMainFileAST()) {
2570 serialization::ModuleFile &
2571 Mod = Reader->getModuleManager().getPrimaryModule();
Eugene Zelenko4f233182018-03-22 00:53:26 +00002572 for (const auto *D : Reader->getModuleFileLevelDecls(Mod)) {
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00002573 if (!Fn(context, D))
Argyrios Kyrtzidis10e78462012-10-02 21:09:13 +00002574 return false;
2575 }
2576
2577 return true;
2578 }
2579
2580 for (ASTUnit::top_level_iterator TL = top_level_begin(),
2581 TLEnd = top_level_end();
2582 TL != TLEnd; ++TL) {
2583 if (!Fn(context, *TL))
2584 return false;
2585 }
2586
2587 return true;
2588}
2589
Argyrios Kyrtzidisf484b132012-10-03 21:05:51 +00002590const FileEntry *ASTUnit::getPCHFile() {
2591 if (!Reader)
Craig Topper49a27902014-05-22 04:46:25 +00002592 return nullptr;
Argyrios Kyrtzidisf484b132012-10-03 21:05:51 +00002593
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00002594 serialization::ModuleFile *Mod = nullptr;
2595 Reader->getModuleManager().visit([&Mod](serialization::ModuleFile &M) {
2596 switch (M.Kind) {
2597 case serialization::MK_ImplicitModule:
2598 case serialization::MK_ExplicitModule:
Manman Ren11f2a472016-08-18 17:42:15 +00002599 case serialization::MK_PrebuiltModule:
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00002600 return true; // skip dependencies.
2601 case serialization::MK_PCH:
2602 Mod = &M;
2603 return true; // found it.
2604 case serialization::MK_Preamble:
2605 return false; // look in dependencies.
2606 case serialization::MK_MainFile:
2607 return false; // look in dependencies.
2608 }
2609
2610 return true;
2611 });
2612 if (Mod)
2613 return Mod->File;
Argyrios Kyrtzidisf484b132012-10-03 21:05:51 +00002614
Craig Topper49a27902014-05-22 04:46:25 +00002615 return nullptr;
Argyrios Kyrtzidisf484b132012-10-03 21:05:51 +00002616}
2617
Vedant Kumar525a7f62017-07-25 19:53:27 +00002618bool ASTUnit::isModuleFile() const {
Richard Smithab755972017-06-05 18:10:11 +00002619 return isMainFileAST() && getLangOpts().isCompilingModule();
2620}
2621
2622InputKind ASTUnit::getInputKind() const {
2623 auto &LangOpts = getLangOpts();
2624
2625 InputKind::Language Lang;
2626 if (LangOpts.OpenCL)
2627 Lang = InputKind::OpenCL;
2628 else if (LangOpts.CUDA)
2629 Lang = InputKind::CUDA;
2630 else if (LangOpts.RenderScript)
2631 Lang = InputKind::RenderScript;
2632 else if (LangOpts.CPlusPlus)
2633 Lang = LangOpts.ObjC1 ? InputKind::ObjCXX : InputKind::CXX;
2634 else
2635 Lang = LangOpts.ObjC1 ? InputKind::ObjC : InputKind::C;
2636
2637 InputKind::Format Fmt = InputKind::Source;
2638 if (LangOpts.getCompilingModule() == LangOptions::CMK_ModuleMap)
2639 Fmt = InputKind::ModuleMap;
2640
2641 // We don't know if input was preprocessed. Assume not.
2642 bool PP = false;
2643
2644 return InputKind(Lang, Fmt, PP);
Argyrios Kyrtzidise445c722012-10-10 02:12:47 +00002645}
2646
Argyrios Kyrtzidisebf01362011-10-10 21:57:12 +00002647#ifndef NDEBUG
2648ASTUnit::ConcurrencyState::ConcurrencyState() {
2649 Mutex = new llvm::sys::MutexImpl(/*recursive=*/true);
2650}
2651
2652ASTUnit::ConcurrencyState::~ConcurrencyState() {
2653 delete static_cast<llvm::sys::MutexImpl *>(Mutex);
2654}
2655
2656void ASTUnit::ConcurrencyState::start() {
2657 bool acquired = static_cast<llvm::sys::MutexImpl *>(Mutex)->tryacquire();
2658 assert(acquired && "Concurrent access to ASTUnit!");
2659}
2660
2661void ASTUnit::ConcurrencyState::finish() {
2662 static_cast<llvm::sys::MutexImpl *>(Mutex)->release();
2663}
2664
2665#else // NDEBUG
2666
Hans Wennborgdcfba332015-10-06 23:40:43 +00002667ASTUnit::ConcurrencyState::ConcurrencyState() { Mutex = nullptr; }
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +00002668ASTUnit::ConcurrencyState::~ConcurrencyState() {}
Argyrios Kyrtzidisebf01362011-10-10 21:57:12 +00002669void ASTUnit::ConcurrencyState::start() {}
2670void ASTUnit::ConcurrencyState::finish() {}
2671
Hans Wennborgdcfba332015-10-06 23:40:43 +00002672#endif // NDEBUG