blob: 1094e6d089a65d32efbf803d27691c1b694dd4a4 [file] [log] [blame]
Hans Wennborgdcfba332015-10-06 23:40:43 +00001//===--- ASTUnit.cpp - ASTUnit utility --------------------------*- C++ -*-===//
Argyrios Kyrtzidis3a08ec12009-06-20 08:27:14 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// ASTUnit Implementation.
11//
12//===----------------------------------------------------------------------===//
13
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000014#include "clang/Frontend/ASTUnit.h"
Daniel Dunbar764c0822009-12-01 09:51:01 +000015#include "clang/AST/ASTConsumer.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000016#include "clang/AST/ASTContext.h"
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000017#include "clang/AST/DeclVisitor.h"
18#include "clang/AST/StmtVisitor.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000019#include "clang/AST/TypeOrdering.h"
20#include "clang/Basic/Diagnostic.h"
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +000021#include "clang/Basic/MemoryBufferCache.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000022#include "clang/Basic/TargetInfo.h"
23#include "clang/Basic/TargetOptions.h"
Ben Langmuirc8130a72014-02-20 21:59:23 +000024#include "clang/Basic/VirtualFileSystem.h"
Daniel Dunbar764c0822009-12-01 09:51:01 +000025#include "clang/Frontend/CompilerInstance.h"
26#include "clang/Frontend/FrontendActions.h"
Daniel Dunbar55a17b62009-12-02 03:23:45 +000027#include "clang/Frontend/FrontendDiagnostic.h"
Daniel Dunbar764c0822009-12-01 09:51:01 +000028#include "clang/Frontend/FrontendOptions.h"
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +000029#include "clang/Frontend/MultiplexConsumer.h"
Douglas Gregor36e3b5c2010-10-11 21:37:58 +000030#include "clang/Frontend/Utils.h"
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000031#include "clang/Lex/HeaderSearch.h"
32#include "clang/Lex/Preprocessor.h"
Douglas Gregor1452ff12012-10-24 17:46:57 +000033#include "clang/Lex/PreprocessorOptions.h"
David Blaikie0a4e61f2013-09-13 18:32:52 +000034#include "clang/Sema/Sema.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000035#include "clang/Serialization/ASTReader.h"
36#include "clang/Serialization/ASTWriter.h"
Chris Lattnerce6c42f2011-03-23 04:04:01 +000037#include "llvm/ADT/ArrayRef.h"
Douglas Gregordf7a79a2011-02-16 18:16:54 +000038#include "llvm/ADT/StringExtras.h"
Douglas Gregor40a5a7d2010-08-16 23:08:34 +000039#include "llvm/ADT/StringSet.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000040#include "llvm/Support/CrashRecoveryContext.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000041#include "llvm/Support/Host.h"
42#include "llvm/Support/MemoryBuffer.h"
Argyrios Kyrtzidisebf01362011-10-10 21:57:12 +000043#include "llvm/Support/Mutex.h"
Ted Kremenekbd307a52011-10-27 19:44:25 +000044#include "llvm/Support/MutexGuard.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000045#include "llvm/Support/Timer.h"
46#include "llvm/Support/raw_ostream.h"
Benjamin Kramer4527fb22014-03-02 17:08:31 +000047#include <atomic>
Zhongxing Xu318e4032010-07-23 02:15:08 +000048#include <cstdio>
Chandler Carruth3a022472012-12-04 09:13:33 +000049#include <cstdlib>
Hans Wennborgdcfba332015-10-06 23:40:43 +000050
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000051using namespace clang;
52
Douglas Gregor16896c42010-10-28 15:44:59 +000053using llvm::TimeRecord;
54
55namespace {
56 class SimpleTimer {
57 bool WantTiming;
58 TimeRecord Start;
59 std::string Output;
60
Benjamin Kramerf2e5a912010-11-09 20:00:56 +000061 public:
Douglas Gregor1cbdd952010-11-01 13:48:43 +000062 explicit SimpleTimer(bool WantTiming) : WantTiming(WantTiming) {
Douglas Gregor16896c42010-10-28 15:44:59 +000063 if (WantTiming)
Benjamin Kramerf2e5a912010-11-09 20:00:56 +000064 Start = TimeRecord::getCurrentTime();
Douglas Gregor16896c42010-10-28 15:44:59 +000065 }
66
Chris Lattner0e62c1c2011-07-23 10:55:15 +000067 void setOutput(const Twine &Output) {
Douglas Gregor16896c42010-10-28 15:44:59 +000068 if (WantTiming)
Benjamin Kramerf2e5a912010-11-09 20:00:56 +000069 this->Output = Output.str();
Douglas Gregor16896c42010-10-28 15:44:59 +000070 }
71
Douglas Gregor16896c42010-10-28 15:44:59 +000072 ~SimpleTimer() {
73 if (WantTiming) {
74 TimeRecord Elapsed = TimeRecord::getCurrentTime();
75 Elapsed -= Start;
76 llvm::errs() << Output << ':';
77 Elapsed.print(Elapsed, llvm::errs());
78 llvm::errs() << '\n';
79 }
80 }
81 };
Ilya Biryukovaf69e402017-05-23 11:37:52 +000082
83 template <class T>
84 std::unique_ptr<T> valueOrNull(llvm::ErrorOr<std::unique_ptr<T>> Val) {
85 if (!Val)
86 return nullptr;
87 return std::move(*Val);
88 }
89
90 template <class T>
91 bool moveOnNoError(llvm::ErrorOr<T> Val, T &Output) {
92 if (!Val)
93 return false;
94 Output = std::move(*Val);
95 return true;
96 }
Ted Kremenek06b4f912011-10-27 17:55:18 +000097
Ilya Biryukov200b3282017-06-21 10:24:58 +000098/// \brief Get a source buffer for \p MainFilePath, handling all file-to-file
99/// and file-to-buffer remappings inside \p Invocation.
100static std::unique_ptr<llvm::MemoryBuffer>
101getBufferForFileHandlingRemapping(const CompilerInvocation &Invocation,
102 vfs::FileSystem *VFS,
103 StringRef FilePath) {
104 const auto &PreprocessorOpts = Invocation.getPreprocessorOpts();
Ted Kremenekbd307a52011-10-27 19:44:25 +0000105
Ilya Biryukov200b3282017-06-21 10:24:58 +0000106 // Try to determine if the main file has been remapped, either from the
107 // command line (to another file) or directly through the compiler
108 // invocation (to a memory buffer).
109 llvm::MemoryBuffer *Buffer = nullptr;
110 std::unique_ptr<llvm::MemoryBuffer> BufferOwner;
111 auto FileStatus = VFS->status(FilePath);
112 if (FileStatus) {
113 llvm::sys::fs::UniqueID MainFileID = FileStatus->getUniqueID();
Ted Kremenek06b4f912011-10-27 17:55:18 +0000114
Ilya Biryukov200b3282017-06-21 10:24:58 +0000115 // Check whether there is a file-file remapping of the main file
116 for (const auto &RF : PreprocessorOpts.RemappedFiles) {
117 std::string MPath(RF.first);
118 auto MPathStatus = VFS->status(MPath);
119 if (MPathStatus) {
120 llvm::sys::fs::UniqueID MID = MPathStatus->getUniqueID();
121 if (MainFileID == MID) {
122 // We found a remapping. Try to load the resulting, remapped source.
123 BufferOwner = valueOrNull(VFS->getBufferForFile(RF.second));
124 if (!BufferOwner)
125 return nullptr;
126 }
127 }
128 }
129
130 // Check whether there is a file-buffer remapping. It supercedes the
131 // file-file remapping.
132 for (const auto &RB : PreprocessorOpts.RemappedFileBuffers) {
133 std::string MPath(RB.first);
134 auto MPathStatus = VFS->status(MPath);
135 if (MPathStatus) {
136 llvm::sys::fs::UniqueID MID = MPathStatus->getUniqueID();
137 if (MainFileID == MID) {
138 // We found a remapping.
139 BufferOwner.reset();
140 Buffer = const_cast<llvm::MemoryBuffer *>(RB.second);
141 }
142 }
143 }
Ted Kremenek06b4f912011-10-27 17:55:18 +0000144 }
Ted Kremenek06b4f912011-10-27 17:55:18 +0000145
Ilya Biryukov200b3282017-06-21 10:24:58 +0000146 // If the main source file was not remapped, load it now.
147 if (!Buffer && !BufferOwner) {
148 BufferOwner = valueOrNull(VFS->getBufferForFile(FilePath));
149 if (!BufferOwner)
150 return nullptr;
Ted Kremenek06b4f912011-10-27 17:55:18 +0000151 }
Ted Kremenek06b4f912011-10-27 17:55:18 +0000152
Ilya Biryukov200b3282017-06-21 10:24:58 +0000153 if (BufferOwner)
154 return BufferOwner;
155 if (!Buffer)
156 return nullptr;
157 return llvm::MemoryBuffer::getMemBufferCopy(Buffer->getBuffer(), FilePath);
Ted Kremenek06b4f912011-10-27 17:55:18 +0000158}
Ted Kremenek06b4f912011-10-27 17:55:18 +0000159}
160
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000161struct ASTUnit::ASTWriterData {
162 SmallString<128> Buffer;
163 llvm::BitstreamWriter Stream;
164 ASTWriter Writer;
165
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +0000166 ASTWriterData(MemoryBufferCache &PCMCache)
167 : Stream(Buffer), Writer(Stream, Buffer, PCMCache, {}) {}
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000168};
169
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000170void ASTUnit::clearFileLevelDecls() {
Reid Kleckner588c9372014-02-19 23:44:52 +0000171 llvm::DeleteContainerSeconds(FileDecls);
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000172}
173
Douglas Gregorbb420ab2010-08-04 05:53:38 +0000174/// \brief After failing to build a precompiled preamble (due to
175/// errors in the source that occurs in the preamble), the number of
176/// reparses during which we'll skip even trying to precompile the
177/// preamble.
178const unsigned DefaultPreambleRebuildInterval = 5;
179
Douglas Gregor68dbaea2010-11-17 00:13:31 +0000180/// \brief Tracks the number of ASTUnit objects that are currently active.
181///
182/// Used for debugging purposes only.
Benjamin Kramer4527fb22014-03-02 17:08:31 +0000183static std::atomic<unsigned> ActiveASTUnitObjects;
Douglas Gregor68dbaea2010-11-17 00:13:31 +0000184
Douglas Gregord03e8232010-04-05 21:10:19 +0000185ASTUnit::ASTUnit(bool _MainFileIsAST)
Craig Topper49a27902014-05-22 04:46:25 +0000186 : Reader(nullptr), HadModuleLoaderFatalFailure(false),
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +0000187 OnlyLocalDecls(false), CaptureDiagnostics(false),
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +0000188 MainFileIsAST(_MainFileIsAST),
Douglas Gregor69f74f82011-08-25 22:30:56 +0000189 TUKind(TU_Complete), WantTiming(getenv("LIBCLANG_TIMING")),
Argyrios Kyrtzidis4954bc12011-03-05 01:03:48 +0000190 OwnsRemappedFileBuffers(true),
Douglas Gregor16896c42010-10-28 15:44:59 +0000191 NumStoredDiagnosticsFromDriver(0),
Rafael Espindola4674a872014-08-13 17:08:22 +0000192 PreambleRebuildCounter(0),
Rafael Espindolafa49c0b2014-08-13 16:47:00 +0000193 NumWarningsInPreamble(0),
Douglas Gregor2c8bd472010-08-17 00:40:40 +0000194 ShouldCacheCodeCompletionResults(false),
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +0000195 IncludeBriefCommentsInCodeCompletion(false), UserFilesAreVolatile(false),
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000196 CompletionCacheTopLevelHashValue(0),
197 PreambleTopLevelHashValue(0),
198 CurrentTopLevelHashValue(0),
Douglas Gregor4740c452010-08-19 00:45:44 +0000199 UnsafeToFree(false) {
Benjamin Kramer4527fb22014-03-02 17:08:31 +0000200 if (getenv("LIBCLANG_OBJTRACKING"))
201 fprintf(stderr, "+++ %u translation units\n", ++ActiveASTUnitObjects);
Douglas Gregor15ba0b32010-07-30 20:58:08 +0000202}
Douglas Gregord03e8232010-04-05 21:10:19 +0000203
Daniel Dunbar764c0822009-12-01 09:51:01 +0000204ASTUnit::~ASTUnit() {
Douglas Gregor6b930962013-05-03 22:58:43 +0000205 // If we loaded from an AST file, balance out the BeginSourceFile call.
206 if (MainFileIsAST && getDiagnostics().getClient()) {
207 getDiagnostics().getClient()->EndSourceFile();
208 }
209
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000210 clearFileLevelDecls();
211
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000212 // Free the buffers associated with remapped files. We are required to
213 // perform this operation here because we explicitly request that the
214 // compiler instance *not* free these buffers for each invocation of the
215 // parser.
David Blaikieea4395e2017-01-06 19:49:01 +0000216 if (Invocation && OwnsRemappedFileBuffers) {
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000217 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
Alp Toker1b070d22014-07-07 07:47:20 +0000218 for (const auto &RB : PPOpts.RemappedFileBuffers)
219 delete RB.second;
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000220 }
Douglas Gregora0734c52010-08-19 01:33:06 +0000221
Douglas Gregor16896c42010-10-28 15:44:59 +0000222 ClearCachedCompletionResults();
Douglas Gregor68dbaea2010-11-17 00:13:31 +0000223
Benjamin Kramer4527fb22014-03-02 17:08:31 +0000224 if (getenv("LIBCLANG_OBJTRACKING"))
225 fprintf(stderr, "--- %u translation units\n", --ActiveASTUnitObjects);
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000226}
227
David Blaikie41565462017-01-05 19:48:07 +0000228void ASTUnit::setPreprocessor(std::shared_ptr<Preprocessor> PP) {
229 this->PP = std::move(PP);
230}
Argyrios Kyrtzidisda6e0542012-01-17 18:48:07 +0000231
Douglas Gregor39982192010-08-15 06:18:01 +0000232/// \brief Determine the set of code-completion contexts in which this
233/// declaration should be shown.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000234static unsigned getDeclShowContexts(const NamedDecl *ND,
Douglas Gregor59cab552010-08-16 23:05:20 +0000235 const LangOptions &LangOpts,
236 bool &IsNestedNameSpecifier) {
237 IsNestedNameSpecifier = false;
238
Douglas Gregor39982192010-08-15 06:18:01 +0000239 if (isa<UsingShadowDecl>(ND))
240 ND = dyn_cast<NamedDecl>(ND->getUnderlyingDecl());
241 if (!ND)
242 return 0;
243
Richard Smith697cc9e2012-08-14 03:13:00 +0000244 uint64_t Contexts = 0;
Douglas Gregor39982192010-08-15 06:18:01 +0000245 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND) ||
246 isa<ClassTemplateDecl>(ND) || isa<TemplateTemplateParmDecl>(ND)) {
247 // Types can appear in these contexts.
248 if (LangOpts.CPlusPlus || !isa<TagDecl>(ND))
Richard Smith697cc9e2012-08-14 03:13:00 +0000249 Contexts |= (1LL << CodeCompletionContext::CCC_TopLevel)
250 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
251 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
252 | (1LL << CodeCompletionContext::CCC_Statement)
253 | (1LL << CodeCompletionContext::CCC_Type)
254 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression);
Douglas Gregor39982192010-08-15 06:18:01 +0000255
256 // In C++, types can appear in expressions contexts (for functional casts).
257 if (LangOpts.CPlusPlus)
Richard Smith697cc9e2012-08-14 03:13:00 +0000258 Contexts |= (1LL << CodeCompletionContext::CCC_Expression);
Douglas Gregor39982192010-08-15 06:18:01 +0000259
260 // In Objective-C, message sends can send interfaces. In Objective-C++,
261 // all types are available due to functional casts.
262 if (LangOpts.CPlusPlus || isa<ObjCInterfaceDecl>(ND))
Richard Smith697cc9e2012-08-14 03:13:00 +0000263 Contexts |= (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver);
Douglas Gregor21325842011-07-07 16:03:39 +0000264
265 // In Objective-C, you can only be a subclass of another Objective-C class
266 if (isa<ObjCInterfaceDecl>(ND))
Richard Smith697cc9e2012-08-14 03:13:00 +0000267 Contexts |= (1LL << CodeCompletionContext::CCC_ObjCInterfaceName);
Douglas Gregor39982192010-08-15 06:18:01 +0000268
269 // Deal with tag names.
270 if (isa<EnumDecl>(ND)) {
Richard Smith697cc9e2012-08-14 03:13:00 +0000271 Contexts |= (1LL << CodeCompletionContext::CCC_EnumTag);
Douglas Gregor39982192010-08-15 06:18:01 +0000272
Douglas Gregor59cab552010-08-16 23:05:20 +0000273 // Part of the nested-name-specifier in C++0x.
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000274 if (LangOpts.CPlusPlus11)
Douglas Gregor59cab552010-08-16 23:05:20 +0000275 IsNestedNameSpecifier = true;
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000276 } else if (const RecordDecl *Record = dyn_cast<RecordDecl>(ND)) {
Douglas Gregor39982192010-08-15 06:18:01 +0000277 if (Record->isUnion())
Richard Smith697cc9e2012-08-14 03:13:00 +0000278 Contexts |= (1LL << CodeCompletionContext::CCC_UnionTag);
Douglas Gregor39982192010-08-15 06:18:01 +0000279 else
Richard Smith697cc9e2012-08-14 03:13:00 +0000280 Contexts |= (1LL << CodeCompletionContext::CCC_ClassOrStructTag);
Douglas Gregor39982192010-08-15 06:18:01 +0000281
Douglas Gregor39982192010-08-15 06:18:01 +0000282 if (LangOpts.CPlusPlus)
Douglas Gregor59cab552010-08-16 23:05:20 +0000283 IsNestedNameSpecifier = true;
Douglas Gregor0ac41382010-09-23 23:01:17 +0000284 } else if (isa<ClassTemplateDecl>(ND))
Douglas Gregor59cab552010-08-16 23:05:20 +0000285 IsNestedNameSpecifier = true;
Douglas Gregor39982192010-08-15 06:18:01 +0000286 } else if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
287 // Values can appear in these contexts.
Richard Smith697cc9e2012-08-14 03:13:00 +0000288 Contexts = (1LL << CodeCompletionContext::CCC_Statement)
289 | (1LL << CodeCompletionContext::CCC_Expression)
290 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
291 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver);
Douglas Gregor39982192010-08-15 06:18:01 +0000292 } else if (isa<ObjCProtocolDecl>(ND)) {
Richard Smith697cc9e2012-08-14 03:13:00 +0000293 Contexts = (1LL << CodeCompletionContext::CCC_ObjCProtocolName);
Douglas Gregor21325842011-07-07 16:03:39 +0000294 } else if (isa<ObjCCategoryDecl>(ND)) {
Richard Smith697cc9e2012-08-14 03:13:00 +0000295 Contexts = (1LL << CodeCompletionContext::CCC_ObjCCategoryName);
Douglas Gregor39982192010-08-15 06:18:01 +0000296 } else if (isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) {
Richard Smith697cc9e2012-08-14 03:13:00 +0000297 Contexts = (1LL << CodeCompletionContext::CCC_Namespace);
Douglas Gregor39982192010-08-15 06:18:01 +0000298
299 // Part of the nested-name-specifier.
Douglas Gregor59cab552010-08-16 23:05:20 +0000300 IsNestedNameSpecifier = true;
Douglas Gregor39982192010-08-15 06:18:01 +0000301 }
302
303 return Contexts;
304}
305
Douglas Gregorb14904c2010-08-13 22:48:40 +0000306void ASTUnit::CacheCodeCompletionResults() {
307 if (!TheSema)
308 return;
309
Douglas Gregor16896c42010-10-28 15:44:59 +0000310 SimpleTimer Timer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +0000311 Timer.setOutput("Cache global code completions for " + getMainFileName());
Douglas Gregorb14904c2010-08-13 22:48:40 +0000312
313 // Clear out the previous results.
314 ClearCachedCompletionResults();
315
316 // Gather the set of global code completions.
John McCall276321a2010-08-25 06:19:51 +0000317 typedef CodeCompletionResult Result;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000318 SmallVector<Result, 8> Results;
David Blaikieea4395e2017-01-06 19:49:01 +0000319 CachedCompletionAllocator = std::make_shared<GlobalCodeCompletionAllocator>();
Argyrios Kyrtzidis2bafa002012-11-16 03:34:57 +0000320 CodeCompletionTUInfo CCTUInfo(CachedCompletionAllocator);
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +0000321 TheSema->GatherGlobalCodeCompletions(*CachedCompletionAllocator,
Argyrios Kyrtzidis2bafa002012-11-16 03:34:57 +0000322 CCTUInfo, Results);
Douglas Gregorb14904c2010-08-13 22:48:40 +0000323
324 // Translate global code completions into cached completions.
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000325 llvm::DenseMap<CanQualType, unsigned> CompletionTypes;
Douglas Gregorc3425b12015-07-07 06:20:19 +0000326 CodeCompletionContext CCContext(CodeCompletionContext::CCC_TopLevel);
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000327
328 for (Result &R : Results) {
329 switch (R.Kind) {
Douglas Gregor39982192010-08-15 06:18:01 +0000330 case Result::RK_Declaration: {
Douglas Gregor59cab552010-08-16 23:05:20 +0000331 bool IsNestedNameSpecifier = false;
Douglas Gregor39982192010-08-15 06:18:01 +0000332 CachedCodeCompletionResult CachedResult;
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000333 CachedResult.Completion = R.CreateCodeCompletionString(
Douglas Gregorc3425b12015-07-07 06:20:19 +0000334 *TheSema, CCContext, *CachedCompletionAllocator, CCTUInfo,
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000335 IncludeBriefCommentsInCodeCompletion);
336 CachedResult.ShowInContexts = getDeclShowContexts(
337 R.Declaration, Ctx->getLangOpts(), IsNestedNameSpecifier);
338 CachedResult.Priority = R.Priority;
339 CachedResult.Kind = R.CursorKind;
340 CachedResult.Availability = R.Availability;
Douglas Gregor24747402010-08-16 16:46:30 +0000341
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000342 // Keep track of the type of this completion in an ASTContext-agnostic
343 // way.
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000344 QualType UsageType = getDeclUsageType(*Ctx, R.Declaration);
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000345 if (UsageType.isNull()) {
Douglas Gregor24747402010-08-16 16:46:30 +0000346 CachedResult.TypeClass = STC_Void;
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000347 CachedResult.Type = 0;
348 } else {
349 CanQualType CanUsageType
350 = Ctx->getCanonicalType(UsageType.getUnqualifiedType());
351 CachedResult.TypeClass = getSimplifiedTypeClass(CanUsageType);
352
353 // Determine whether we have already seen this type. If so, we save
354 // ourselves the work of formatting the type string by using the
355 // temporary, CanQualType-based hash table to find the associated value.
356 unsigned &TypeValue = CompletionTypes[CanUsageType];
357 if (TypeValue == 0) {
358 TypeValue = CompletionTypes.size();
359 CachedCompletionTypes[QualType(CanUsageType).getAsString()]
360 = TypeValue;
361 }
362
363 CachedResult.Type = TypeValue;
Douglas Gregor24747402010-08-16 16:46:30 +0000364 }
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000365
Douglas Gregor39982192010-08-15 06:18:01 +0000366 CachedCompletionResults.push_back(CachedResult);
Douglas Gregor59cab552010-08-16 23:05:20 +0000367
368 /// Handle nested-name-specifiers in C++.
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000369 if (TheSema->Context.getLangOpts().CPlusPlus && IsNestedNameSpecifier &&
370 !R.StartsNestedNameSpecifier) {
Douglas Gregor59cab552010-08-16 23:05:20 +0000371 // The contexts in which a nested-name-specifier can appear in C++.
Richard Smith697cc9e2012-08-14 03:13:00 +0000372 uint64_t NNSContexts
373 = (1LL << CodeCompletionContext::CCC_TopLevel)
374 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
375 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
376 | (1LL << CodeCompletionContext::CCC_Statement)
377 | (1LL << CodeCompletionContext::CCC_Expression)
378 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
379 | (1LL << CodeCompletionContext::CCC_EnumTag)
380 | (1LL << CodeCompletionContext::CCC_UnionTag)
381 | (1LL << CodeCompletionContext::CCC_ClassOrStructTag)
382 | (1LL << CodeCompletionContext::CCC_Type)
383 | (1LL << CodeCompletionContext::CCC_PotentiallyQualifiedName)
384 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression);
Douglas Gregor59cab552010-08-16 23:05:20 +0000385
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000386 if (isa<NamespaceDecl>(R.Declaration) ||
387 isa<NamespaceAliasDecl>(R.Declaration))
Richard Smith697cc9e2012-08-14 03:13:00 +0000388 NNSContexts |= (1LL << CodeCompletionContext::CCC_Namespace);
Douglas Gregor59cab552010-08-16 23:05:20 +0000389
390 if (unsigned RemainingContexts
391 = NNSContexts & ~CachedResult.ShowInContexts) {
392 // If there any contexts where this completion can be a
393 // nested-name-specifier but isn't already an option, create a
394 // nested-name-specifier completion.
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000395 R.StartsNestedNameSpecifier = true;
396 CachedResult.Completion = R.CreateCodeCompletionString(
Douglas Gregorc3425b12015-07-07 06:20:19 +0000397 *TheSema, CCContext, *CachedCompletionAllocator, CCTUInfo,
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000398 IncludeBriefCommentsInCodeCompletion);
Douglas Gregor59cab552010-08-16 23:05:20 +0000399 CachedResult.ShowInContexts = RemainingContexts;
400 CachedResult.Priority = CCP_NestedNameSpecifier;
401 CachedResult.TypeClass = STC_Void;
402 CachedResult.Type = 0;
403 CachedCompletionResults.push_back(CachedResult);
404 }
405 }
Douglas Gregorb14904c2010-08-13 22:48:40 +0000406 break;
Douglas Gregor39982192010-08-15 06:18:01 +0000407 }
408
Douglas Gregorb14904c2010-08-13 22:48:40 +0000409 case Result::RK_Keyword:
410 case Result::RK_Pattern:
411 // Ignore keywords and patterns; we don't care, since they are so
412 // easily regenerated.
413 break;
414
415 case Result::RK_Macro: {
416 CachedCodeCompletionResult CachedResult;
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000417 CachedResult.Completion = R.CreateCodeCompletionString(
Douglas Gregorc3425b12015-07-07 06:20:19 +0000418 *TheSema, CCContext, *CachedCompletionAllocator, CCTUInfo,
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000419 IncludeBriefCommentsInCodeCompletion);
Douglas Gregorb14904c2010-08-13 22:48:40 +0000420 CachedResult.ShowInContexts
Richard Smith697cc9e2012-08-14 03:13:00 +0000421 = (1LL << CodeCompletionContext::CCC_TopLevel)
422 | (1LL << CodeCompletionContext::CCC_ObjCInterface)
423 | (1LL << CodeCompletionContext::CCC_ObjCImplementation)
424 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
425 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
426 | (1LL << CodeCompletionContext::CCC_Statement)
427 | (1LL << CodeCompletionContext::CCC_Expression)
428 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
429 | (1LL << CodeCompletionContext::CCC_MacroNameUse)
430 | (1LL << CodeCompletionContext::CCC_PreprocessorExpression)
431 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
432 | (1LL << CodeCompletionContext::CCC_OtherWithMacros);
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000433
434 CachedResult.Priority = R.Priority;
435 CachedResult.Kind = R.CursorKind;
436 CachedResult.Availability = R.Availability;
Douglas Gregor6e240332010-08-16 16:18:59 +0000437 CachedResult.TypeClass = STC_Void;
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000438 CachedResult.Type = 0;
Douglas Gregorb14904c2010-08-13 22:48:40 +0000439 CachedCompletionResults.push_back(CachedResult);
440 break;
441 }
442 }
Douglas Gregorb14904c2010-08-13 22:48:40 +0000443 }
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000444
445 // Save the current top-level hash value.
446 CompletionCacheTopLevelHashValue = CurrentTopLevelHashValue;
Douglas Gregorb14904c2010-08-13 22:48:40 +0000447}
448
449void ASTUnit::ClearCachedCompletionResults() {
Douglas Gregorb14904c2010-08-13 22:48:40 +0000450 CachedCompletionResults.clear();
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000451 CachedCompletionTypes.clear();
Craig Topper49a27902014-05-22 04:46:25 +0000452 CachedCompletionAllocator = nullptr;
Douglas Gregorb14904c2010-08-13 22:48:40 +0000453}
454
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000455namespace {
456
Sebastian Redl2c499f62010-08-18 23:56:43 +0000457/// \brief Gathers information from ASTReader that will be used to initialize
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000458/// a Preprocessor.
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000459class ASTInfoCollector : public ASTReaderListener {
Douglas Gregor83297df2011-09-01 23:39:15 +0000460 Preprocessor &PP;
Richard Smithdbafb6c2017-06-29 23:23:46 +0000461 ASTContext *Context;
Richard Smith18934752017-06-06 00:32:01 +0000462 HeaderSearchOptions &HSOpts;
463 PreprocessorOptions &PPOpts;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000464 LangOptions &LangOpt;
Alp Toker80758082014-07-06 05:26:44 +0000465 std::shared_ptr<TargetOptions> &TargetOpts;
Dylan Noblesmithc95d8192012-02-20 14:00:23 +0000466 IntrusiveRefCntPtr<TargetInfo> &Target;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000467 unsigned &Counter;
Mike Stump11289f42009-09-09 15:08:12 +0000468
Douglas Gregore8bbc122011-09-02 00:18:52 +0000469 bool InitializedLanguage;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000470public:
Richard Smithdbafb6c2017-06-29 23:23:46 +0000471 ASTInfoCollector(Preprocessor &PP, ASTContext *Context,
Richard Smith18934752017-06-06 00:32:01 +0000472 HeaderSearchOptions &HSOpts, PreprocessorOptions &PPOpts,
473 LangOptions &LangOpt,
Alp Toker80758082014-07-06 05:26:44 +0000474 std::shared_ptr<TargetOptions> &TargetOpts,
475 IntrusiveRefCntPtr<TargetInfo> &Target, unsigned &Counter)
Richard Smith18934752017-06-06 00:32:01 +0000476 : PP(PP), Context(Context), HSOpts(HSOpts), PPOpts(PPOpts),
477 LangOpt(LangOpt), TargetOpts(TargetOpts), Target(Target),
478 Counter(Counter), InitializedLanguage(false) {}
Mike Stump11289f42009-09-09 15:08:12 +0000479
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000480 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
481 bool AllowCompatibleDifferences) override {
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000482 if (InitializedLanguage)
Douglas Gregor83297df2011-09-01 23:39:15 +0000483 return false;
484
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000485 LangOpt = LangOpts;
486 InitializedLanguage = true;
487
488 updated();
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000489 return false;
490 }
Mike Stump11289f42009-09-09 15:08:12 +0000491
Richard Smith18934752017-06-06 00:32:01 +0000492 virtual bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
493 StringRef SpecificModuleCachePath,
494 bool Complain) override {
495 this->HSOpts = HSOpts;
496 return false;
497 }
498
499 virtual bool
500 ReadPreprocessorOptions(const PreprocessorOptions &PPOpts, bool Complain,
501 std::string &SuggestedPredefines) override {
502 this->PPOpts = PPOpts;
503 return false;
504 }
505
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000506 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
507 bool AllowCompatibleDifferences) override {
Douglas Gregor83297df2011-09-01 23:39:15 +0000508 // If we've already initialized the target, don't do it again.
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000509 if (Target)
Douglas Gregor83297df2011-09-01 23:39:15 +0000510 return false;
Alp Toker80758082014-07-06 05:26:44 +0000511
512 this->TargetOpts = std::make_shared<TargetOptions>(TargetOpts);
513 Target =
514 TargetInfo::CreateTargetInfo(PP.getDiagnostics(), this->TargetOpts);
Argyrios Kyrtzidis9e1fb562012-09-14 20:24:53 +0000515
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000516 updated();
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000517 return false;
518 }
Mike Stump11289f42009-09-09 15:08:12 +0000519
Craig Topperafa7cb32014-03-13 06:07:04 +0000520 void ReadCounter(const serialization::ModuleFile &M,
521 unsigned Value) override {
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000522 Counter = Value;
523 }
Argyrios Kyrtzidis9e1fb562012-09-14 20:24:53 +0000524
525private:
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000526 void updated() {
527 if (!Target || !InitializedLanguage)
528 return;
529
530 // Inform the target of the language options.
531 //
532 // FIXME: We shouldn't need to do this, the target should be immutable once
533 // created. This complexity should be lifted elsewhere.
Alp Toker74437972014-07-06 05:14:24 +0000534 Target->adjust(LangOpt);
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000535
536 // Initialize the preprocessor.
537 PP.Initialize(*Target);
538
Richard Smithdbafb6c2017-06-29 23:23:46 +0000539 if (!Context)
540 return;
541
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000542 // Initialize the ASTContext
Richard Smithdbafb6c2017-06-29 23:23:46 +0000543 Context->InitBuiltinTypes(*Target);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +0000544
545 // We didn't have access to the comment options when the ASTContext was
546 // constructed, so register them now.
Richard Smithdbafb6c2017-06-29 23:23:46 +0000547 Context->getCommentCommandTraits().registerCommentOptions(
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +0000548 LangOpt.CommentOpts);
Argyrios Kyrtzidis9e1fb562012-09-14 20:24:53 +0000549 }
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000550};
551
Douglas Gregor6b930962013-05-03 22:58:43 +0000552 /// \brief Diagnostic consumer that saves each diagnostic it is given.
David Blaikief18d91a2011-09-26 00:01:39 +0000553class StoredDiagnosticConsumer : public DiagnosticConsumer {
Ilya Biryukov200b3282017-06-21 10:24:58 +0000554 SmallVectorImpl<StoredDiagnostic> *StoredDiags;
555 SmallVectorImpl<ASTUnit::StandaloneDiagnostic> *StandaloneDiags;
556 const LangOptions *LangOpts;
Douglas Gregor6b930962013-05-03 22:58:43 +0000557 SourceManager *SourceMgr;
558
Douglas Gregor33cdd812010-02-18 18:08:43 +0000559public:
Ilya Biryukov200b3282017-06-21 10:24:58 +0000560 StoredDiagnosticConsumer(
561 SmallVectorImpl<StoredDiagnostic> *StoredDiags,
562 SmallVectorImpl<ASTUnit::StandaloneDiagnostic> *StandaloneDiags)
563 : StoredDiags(StoredDiags), StandaloneDiags(StandaloneDiags),
564 LangOpts(nullptr), SourceMgr(nullptr) {
565 assert((StoredDiags || StandaloneDiags) &&
566 "No output collections were passed to StoredDiagnosticConsumer.");
567 }
Douglas Gregor6b930962013-05-03 22:58:43 +0000568
Craig Topperafa7cb32014-03-13 06:07:04 +0000569 void BeginSourceFile(const LangOptions &LangOpts,
Craig Topper49a27902014-05-22 04:46:25 +0000570 const Preprocessor *PP = nullptr) override {
Ilya Biryukov200b3282017-06-21 10:24:58 +0000571 this->LangOpts = &LangOpts;
Douglas Gregor6b930962013-05-03 22:58:43 +0000572 if (PP)
573 SourceMgr = &PP->getSourceManager();
574 }
575
Craig Topperafa7cb32014-03-13 06:07:04 +0000576 void HandleDiagnostic(DiagnosticsEngine::Level Level,
577 const Diagnostic &Info) override;
Douglas Gregor33cdd812010-02-18 18:08:43 +0000578};
579
580/// \brief RAII object that optionally captures diagnostics, if
581/// there is no diagnostic client to capture them already.
582class CaptureDroppedDiagnostics {
David Blaikie9c902b52011-09-25 23:23:43 +0000583 DiagnosticsEngine &Diags;
David Blaikief18d91a2011-09-26 00:01:39 +0000584 StoredDiagnosticConsumer Client;
David Blaikiee2eefae2011-09-25 23:39:51 +0000585 DiagnosticConsumer *PreviousClient;
Alexander Kornienko41c247a2014-11-17 23:46:02 +0000586 std::unique_ptr<DiagnosticConsumer> OwningPreviousClient;
Douglas Gregor33cdd812010-02-18 18:08:43 +0000587
588public:
David Blaikie9c902b52011-09-25 23:23:43 +0000589 CaptureDroppedDiagnostics(bool RequestCapture, DiagnosticsEngine &Diags,
Ilya Biryukov200b3282017-06-21 10:24:58 +0000590 SmallVectorImpl<StoredDiagnostic> *StoredDiags,
591 SmallVectorImpl<ASTUnit::StandaloneDiagnostic> *StandaloneDiags)
592 : Diags(Diags), Client(StoredDiags, StandaloneDiags), PreviousClient(nullptr)
Douglas Gregor33cdd812010-02-18 18:08:43 +0000593 {
Craig Topper49a27902014-05-22 04:46:25 +0000594 if (RequestCapture || Diags.getClient() == nullptr) {
Alexander Kornienko41c247a2014-11-17 23:46:02 +0000595 OwningPreviousClient = Diags.takeClient();
596 PreviousClient = Diags.getClient();
597 Diags.setClient(&Client, false);
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000598 }
Douglas Gregor33cdd812010-02-18 18:08:43 +0000599 }
600
601 ~CaptureDroppedDiagnostics() {
Alexander Kornienko41c247a2014-11-17 23:46:02 +0000602 if (Diags.getClient() == &Client)
603 Diags.setClient(PreviousClient, !!OwningPreviousClient.release());
Douglas Gregor33cdd812010-02-18 18:08:43 +0000604 }
605};
606
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000607} // anonymous namespace
608
Ilya Biryukov200b3282017-06-21 10:24:58 +0000609static ASTUnit::StandaloneDiagnostic
610makeStandaloneDiagnostic(const LangOptions &LangOpts,
611 const StoredDiagnostic &InDiag);
612
David Blaikief18d91a2011-09-26 00:01:39 +0000613void StoredDiagnosticConsumer::HandleDiagnostic(DiagnosticsEngine::Level Level,
Ilya Biryukov200b3282017-06-21 10:24:58 +0000614 const Diagnostic &Info) {
Argyrios Kyrtzidisc79346a2010-11-18 20:06:46 +0000615 // Default implementation (Warnings/errors count).
David Blaikiee2eefae2011-09-25 23:39:51 +0000616 DiagnosticConsumer::HandleDiagnostic(Level, Info);
Argyrios Kyrtzidisc79346a2010-11-18 20:06:46 +0000617
Douglas Gregor6b930962013-05-03 22:58:43 +0000618 // Only record the diagnostic if it's part of the source manager we know
619 // about. This effectively drops diagnostics from modules we're building.
620 // FIXME: In the long run, ee don't want to drop source managers from modules.
Ilya Biryukov200b3282017-06-21 10:24:58 +0000621 if (!Info.hasSourceManager() || &Info.getSourceManager() == SourceMgr) {
622 StoredDiagnostic *ResultDiag = nullptr;
623 if (StoredDiags) {
624 StoredDiags->emplace_back(Level, Info);
625 ResultDiag = &StoredDiags->back();
626 }
627
628 if (StandaloneDiags) {
629 llvm::Optional<StoredDiagnostic> StoredDiag = llvm::None;
630 if (!ResultDiag) {
631 StoredDiag.emplace(Level, Info);
632 ResultDiag = StoredDiag.getPointer();
633 }
634 StandaloneDiags->push_back(
635 makeStandaloneDiagnostic(*LangOpts, *ResultDiag));
636 }
637 }
Douglas Gregor33cdd812010-02-18 18:08:43 +0000638}
639
Argyrios Kyrtzidisa38cb202017-01-30 06:05:58 +0000640IntrusiveRefCntPtr<ASTReader> ASTUnit::getASTReader() const {
641 return Reader;
642}
643
Argyrios Kyrtzidis1c7455f2013-05-10 01:28:51 +0000644ASTMutationListener *ASTUnit::getASTMutationListener() {
645 if (WriterData)
646 return &WriterData->Writer;
Craig Topper49a27902014-05-22 04:46:25 +0000647 return nullptr;
Argyrios Kyrtzidis1c7455f2013-05-10 01:28:51 +0000648}
649
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000650ASTDeserializationListener *ASTUnit::getDeserializationListener() {
651 if (WriterData)
652 return &WriterData->Writer;
Craig Topper49a27902014-05-22 04:46:25 +0000653 return nullptr;
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000654}
655
Rafael Espindola16e1ba12014-08-26 20:17:44 +0000656std::unique_ptr<llvm::MemoryBuffer>
657ASTUnit::getBufferForFile(StringRef Filename, std::string *ErrorStr) {
Chris Lattner5159f612010-11-23 08:35:12 +0000658 assert(FileMgr);
Benjamin Kramera8857962014-10-26 22:44:13 +0000659 auto Buffer = FileMgr->getBufferForFile(Filename);
660 if (Buffer)
661 return std::move(*Buffer);
662 if (ErrorStr)
663 *ErrorStr = Buffer.getError().message();
664 return nullptr;
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000665}
666
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000667/// \brief Configure the diagnostics object for use with ASTUnit.
Justin Bognerd512c1e2014-10-15 00:33:06 +0000668void ASTUnit::ConfigureDiags(IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000669 ASTUnit &AST, bool CaptureDiagnostics) {
Justin Bognerd512c1e2014-10-15 00:33:06 +0000670 assert(Diags.get() && "no DiagnosticsEngine was provided");
671 if (CaptureDiagnostics)
Ilya Biryukov200b3282017-06-21 10:24:58 +0000672 Diags->setClient(new StoredDiagnosticConsumer(&AST.StoredDiagnostics, nullptr));
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000673}
674
David Blaikie6f7382d2014-08-10 19:08:04 +0000675std::unique_ptr<ASTUnit> ASTUnit::LoadFromASTFile(
Adrian Prantl6b21ab22015-08-27 19:46:20 +0000676 const std::string &Filename, const PCHContainerReader &PCHContainerRdr,
Richard Smithdbafb6c2017-06-29 23:23:46 +0000677 WhatToLoad ToLoad, IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Adrian Prantl6b21ab22015-08-27 19:46:20 +0000678 const FileSystemOptions &FileSystemOpts, bool UseDebugInfo,
679 bool OnlyLocalDecls, ArrayRef<RemappedFile> RemappedFiles,
680 bool CaptureDiagnostics, bool AllowPCHWithCompilerErrors,
681 bool UserFilesAreVolatile) {
Ahmed Charlesb8984322014-03-07 20:03:18 +0000682 std::unique_ptr<ASTUnit> AST(new ASTUnit(true));
Ted Kremenek4422bfe2011-03-18 02:06:56 +0000683
684 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +0000685 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
686 ASTUnitCleanup(AST.get());
David Blaikie9c902b52011-09-25 23:23:43 +0000687 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
688 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Alp Tokerf994cef2014-07-05 03:08:06 +0000689 DiagCleanup(Diags.get());
Ted Kremenek4422bfe2011-03-18 02:06:56 +0000690
Justin Bognerdbbcb112014-10-14 23:36:06 +0000691 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000692
Richard Smithab755972017-06-05 18:10:11 +0000693 AST->LangOpts = std::make_shared<LangOptions>();
Douglas Gregor16bef852009-10-16 20:01:17 +0000694 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000695 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor7f95d262010-04-05 23:52:57 +0000696 AST->Diagnostics = Diags;
Ben Langmuir8832c062014-04-15 18:16:25 +0000697 IntrusiveRefCntPtr<vfs::FileSystem> VFS = vfs::getRealFileSystem();
698 AST->FileMgr = new FileManager(FileSystemOpts, VFS);
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +0000699 AST->UserFilesAreVolatile = UserFilesAreVolatile;
Ted Kremenek5e14d392011-03-21 18:40:17 +0000700 AST->SourceMgr = new SourceManager(AST->getDiagnostics(),
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +0000701 AST->getFileManager(),
702 UserFilesAreVolatile);
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +0000703 AST->PCMCache = new MemoryBufferCache;
David Blaikie9c28cb32017-01-06 01:04:46 +0000704 AST->HSOpts = std::make_shared<HeaderSearchOptions>();
Adrian Prantlfb2398d2015-07-17 01:19:54 +0000705 AST->HSOpts->ModuleFormat = PCHContainerRdr.getFormat();
Douglas Gregorb85b9cc2012-10-24 16:19:39 +0000706 AST->HeaderInfo.reset(new HeaderSearch(AST->HSOpts,
Manuel Klimek1f76c4e2013-10-24 07:51:24 +0000707 AST->getSourceManager(),
Douglas Gregor1fb5c3a2011-12-31 04:05:44 +0000708 AST->getDiagnostics(),
Richard Smithab755972017-06-05 18:10:11 +0000709 AST->getLangOpts(),
Craig Topper49a27902014-05-22 04:46:25 +0000710 /*Target=*/nullptr));
Richard Smith18934752017-06-06 00:32:01 +0000711 AST->PPOpts = std::make_shared<PreprocessorOptions>();
Dmitri Gribenkoc444b572014-02-08 00:38:15 +0000712
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000713 for (const auto &RemappedFile : RemappedFiles)
Richard Smith18934752017-06-06 00:32:01 +0000714 AST->PPOpts->addRemappedFile(RemappedFile.first, RemappedFile.second);
Dmitri Gribenkoc444b572014-02-08 00:38:15 +0000715
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000716 // Gather Info for preprocessor construction later on.
Mike Stump11289f42009-09-09 15:08:12 +0000717
David Blaikie6f7382d2014-08-10 19:08:04 +0000718 HeaderSearch &HeaderInfo = *AST->HeaderInfo;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000719 unsigned Counter;
720
David Blaikie41565462017-01-05 19:48:07 +0000721 AST->PP = std::make_shared<Preprocessor>(
Richard Smith18934752017-06-06 00:32:01 +0000722 AST->PPOpts, AST->getDiagnostics(), *AST->LangOpts,
Richard Smith5d2ed482017-06-09 19:22:32 +0000723 AST->getSourceManager(), *AST->PCMCache, HeaderInfo, AST->ModuleLoader,
David Blaikie41565462017-01-05 19:48:07 +0000724 /*IILookup=*/nullptr,
725 /*OwnsHeaderSearch=*/false);
Douglas Gregore8bbc122011-09-02 00:18:52 +0000726 Preprocessor &PP = *AST->PP;
727
Richard Smithdbafb6c2017-06-29 23:23:46 +0000728 if (ToLoad >= LoadASTOnly)
729 AST->Ctx = new ASTContext(*AST->LangOpts, AST->getSourceManager(),
730 PP.getIdentifierTable(), PP.getSelectorTable(),
731 PP.getBuiltinInfo());
Douglas Gregor83297df2011-09-01 23:39:15 +0000732
Argyrios Kyrtzidis945a8192012-09-15 01:10:20 +0000733 bool disableValid = false;
734 if (::getenv("LIBCLANG_DISABLE_PCH_VALIDATION"))
735 disableValid = true;
Richard Smithdbafb6c2017-06-29 23:23:46 +0000736 AST->Reader = new ASTReader(PP, AST->Ctx.get(), PCHContainerRdr, { },
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000737 /*isysroot=*/"",
738 /*DisableValidation=*/disableValid,
739 AllowPCHWithCompilerErrors);
Ted Kremenek2159b8d2011-05-04 23:27:12 +0000740
David Blaikie2721c322014-08-10 16:54:39 +0000741 AST->Reader->setListener(llvm::make_unique<ASTInfoCollector>(
Richard Smithdbafb6c2017-06-29 23:23:46 +0000742 *AST->PP, AST->Ctx.get(), *AST->HSOpts, *AST->PPOpts, *AST->LangOpts,
Richard Smith18934752017-06-06 00:32:01 +0000743 AST->TargetOpts, AST->Target, Counter));
Daniel Dunbar2d9c7402009-09-03 05:59:35 +0000744
Argyrios Kyrtzidisf0b4cd12015-03-03 08:04:19 +0000745 // Attach the AST reader to the AST context as an external AST
746 // source, so that declarations will be deserialized from the
747 // AST file as needed.
748 // We need the external source to be set up before we read the AST, because
749 // eagerly-deserialized declarations may use it.
Richard Smithdbafb6c2017-06-29 23:23:46 +0000750 if (AST->Ctx)
751 AST->Ctx->setExternalSource(AST->Reader);
Argyrios Kyrtzidisf0b4cd12015-03-03 08:04:19 +0000752
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000753 switch (AST->Reader->ReadAST(Filename, serialization::MK_MainFile,
Argyrios Kyrtzidis2ec29362012-11-15 18:57:22 +0000754 SourceLocation(), ASTReader::ARR_None)) {
Sebastian Redl2c499f62010-08-18 23:56:43 +0000755 case ASTReader::Success:
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000756 break;
Mike Stump11289f42009-09-09 15:08:12 +0000757
Sebastian Redl2c499f62010-08-18 23:56:43 +0000758 case ASTReader::Failure:
Douglas Gregor7029ce12013-03-19 00:28:20 +0000759 case ASTReader::Missing:
Douglas Gregorc9ad5fb2012-10-22 22:50:17 +0000760 case ASTReader::OutOfDate:
761 case ASTReader::VersionMismatch:
762 case ASTReader::ConfigurationMismatch:
763 case ASTReader::HadErrors:
Douglas Gregord03e8232010-04-05 21:10:19 +0000764 AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
Craig Topper49a27902014-05-22 04:46:25 +0000765 return nullptr;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000766 }
Mike Stump11289f42009-09-09 15:08:12 +0000767
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000768 AST->OriginalSourceFile = AST->Reader->getOriginalSourceFile();
Daniel Dunbara8a50932009-12-02 08:44:16 +0000769
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000770 PP.setCounterValue(Counter);
Mike Stump11289f42009-09-09 15:08:12 +0000771
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000772 // Create an AST consumer, even though it isn't used.
Richard Smithdbafb6c2017-06-29 23:23:46 +0000773 if (ToLoad >= LoadASTOnly)
774 AST->Consumer.reset(new ASTConsumer);
775
Sebastian Redl2c499f62010-08-18 23:56:43 +0000776 // Create a semantic analysis object and tell the AST reader about it.
Richard Smithdbafb6c2017-06-29 23:23:46 +0000777 if (ToLoad >= LoadEverything) {
778 AST->TheSema.reset(new Sema(PP, *AST->Ctx, *AST->Consumer));
779 AST->TheSema->Initialize();
780 AST->Reader->InitializeSema(*AST->TheSema);
781 }
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000782
Douglas Gregor6b930962013-05-03 22:58:43 +0000783 // Tell the diagnostic client that we have started a source file.
Richard Smithdbafb6c2017-06-29 23:23:46 +0000784 AST->getDiagnostics().getClient()->BeginSourceFile(PP.getLangOpts(), &PP);
Douglas Gregor6b930962013-05-03 22:58:43 +0000785
David Blaikie6f7382d2014-08-10 19:08:04 +0000786 return AST;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000787}
Daniel Dunbar764c0822009-12-01 09:51:01 +0000788
789namespace {
790
Ilya Biryukov200b3282017-06-21 10:24:58 +0000791/// \brief Add the given macro to the hash of all top-level entities.
792void AddDefinedMacroToHash(const Token &MacroNameTok, unsigned &Hash) {
793 Hash = llvm::HashString(MacroNameTok.getIdentifierInfo()->getName(), Hash);
794}
795
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000796/// \brief Preprocessor callback class that updates a hash value with the names
797/// of all macros that have been defined by the translation unit.
798class MacroDefinitionTrackerPPCallbacks : public PPCallbacks {
799 unsigned &Hash;
800
801public:
802 explicit MacroDefinitionTrackerPPCallbacks(unsigned &Hash) : Hash(Hash) { }
Craig Topperafa7cb32014-03-13 06:07:04 +0000803
804 void MacroDefined(const Token &MacroNameTok,
805 const MacroDirective *MD) override {
Ilya Biryukov200b3282017-06-21 10:24:58 +0000806 AddDefinedMacroToHash(MacroNameTok, Hash);
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000807 }
808};
809
810/// \brief Add the given declaration to the hash of all top-level entities.
811void AddTopLevelDeclarationToHash(Decl *D, unsigned &Hash) {
812 if (!D)
813 return;
814
815 DeclContext *DC = D->getDeclContext();
816 if (!DC)
817 return;
818
819 if (!(DC->isTranslationUnit() || DC->getLookupParent()->isTranslationUnit()))
820 return;
821
822 if (NamedDecl *ND = dyn_cast<NamedDecl>(D)) {
Argyrios Kyrtzidisca5c7be2013-10-15 17:37:55 +0000823 if (EnumDecl *EnumD = dyn_cast<EnumDecl>(D)) {
824 // For an unscoped enum include the enumerators in the hash since they
825 // enter the top-level namespace.
826 if (!EnumD->isScoped()) {
Aaron Ballman23a6dcb2014-03-08 18:45:14 +0000827 for (const auto *EI : EnumD->enumerators()) {
828 if (EI->getIdentifier())
829 Hash = llvm::HashString(EI->getIdentifier()->getName(), Hash);
Argyrios Kyrtzidisca5c7be2013-10-15 17:37:55 +0000830 }
831 }
832 }
833
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000834 if (ND->getIdentifier())
835 Hash = llvm::HashString(ND->getIdentifier()->getName(), Hash);
836 else if (DeclarationName Name = ND->getDeclName()) {
837 std::string NameStr = Name.getAsString();
838 Hash = llvm::HashString(NameStr, Hash);
839 }
840 return;
Argyrios Kyrtzidis48d88de2013-06-24 21:19:12 +0000841 }
842
843 if (ImportDecl *ImportD = dyn_cast<ImportDecl>(D)) {
844 if (Module *Mod = ImportD->getImportedModule()) {
845 std::string ModName = Mod->getFullModuleName();
846 Hash = llvm::HashString(ModName, Hash);
847 }
848 return;
849 }
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000850}
851
Daniel Dunbar644dca02009-12-04 08:17:33 +0000852class TopLevelDeclTrackerConsumer : public ASTConsumer {
853 ASTUnit &Unit;
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000854 unsigned &Hash;
855
Daniel Dunbar644dca02009-12-04 08:17:33 +0000856public:
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000857 TopLevelDeclTrackerConsumer(ASTUnit &_Unit, unsigned &Hash)
858 : Unit(_Unit), Hash(Hash) {
859 Hash = 0;
860 }
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000861
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000862 void handleTopLevelDecl(Decl *D) {
Argyrios Kyrtzidis516eec22011-11-16 02:35:10 +0000863 if (!D)
864 return;
865
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000866 // FIXME: Currently ObjC method declarations are incorrectly being
867 // reported as top-level declarations, even though their DeclContext
868 // is the containing ObjC @interface/@implementation. This is a
869 // fundamental problem in the parser right now.
870 if (isa<ObjCMethodDecl>(D))
871 return;
872
873 AddTopLevelDeclarationToHash(D, Hash);
874 Unit.addTopLevelDecl(D);
875
876 handleFileLevelDecl(D);
877 }
878
879 void handleFileLevelDecl(Decl *D) {
880 Unit.addFileLevelDecl(D);
881 if (NamespaceDecl *NSD = dyn_cast<NamespaceDecl>(D)) {
Aaron Ballman629afae2014-03-07 19:56:05 +0000882 for (auto *I : NSD->decls())
883 handleFileLevelDecl(I);
Ted Kremenekacc59c32010-05-03 20:16:35 +0000884 }
Daniel Dunbar644dca02009-12-04 08:17:33 +0000885 }
Sebastian Redleaa4ade2010-08-11 18:52:41 +0000886
Craig Topperafa7cb32014-03-13 06:07:04 +0000887 bool HandleTopLevelDecl(DeclGroupRef D) override {
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000888 for (Decl *TopLevelDecl : D)
889 handleTopLevelDecl(TopLevelDecl);
Argyrios Kyrtzidis841dd882011-11-18 00:26:59 +0000890 return true;
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000891 }
892
Sebastian Redleaa4ade2010-08-11 18:52:41 +0000893 // We're not interested in "interesting" decls.
Craig Topperafa7cb32014-03-13 06:07:04 +0000894 void HandleInterestingDecl(DeclGroupRef) override {}
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000895
Craig Topperafa7cb32014-03-13 06:07:04 +0000896 void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) override {
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000897 for (Decl *TopLevelDecl : D)
898 handleTopLevelDecl(TopLevelDecl);
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000899 }
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000900
Craig Topperafa7cb32014-03-13 06:07:04 +0000901 ASTMutationListener *GetASTMutationListener() override {
Argyrios Kyrtzidis1c7455f2013-05-10 01:28:51 +0000902 return Unit.getASTMutationListener();
903 }
904
Craig Topperafa7cb32014-03-13 06:07:04 +0000905 ASTDeserializationListener *GetASTDeserializationListener() override {
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000906 return Unit.getDeserializationListener();
907 }
Daniel Dunbar644dca02009-12-04 08:17:33 +0000908};
909
910class TopLevelDeclTrackerAction : public ASTFrontendAction {
911public:
912 ASTUnit &Unit;
913
David Blaikie6beb6aa2014-08-10 19:56:51 +0000914 std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
915 StringRef InFile) override {
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000916 CI.getPreprocessor().addPPCallbacks(
Craig Topperb8a70532014-09-10 04:53:53 +0000917 llvm::make_unique<MacroDefinitionTrackerPPCallbacks>(
918 Unit.getCurrentTopLevelHashValue()));
David Blaikie6beb6aa2014-08-10 19:56:51 +0000919 return llvm::make_unique<TopLevelDeclTrackerConsumer>(
920 Unit, Unit.getCurrentTopLevelHashValue());
Daniel Dunbar764c0822009-12-01 09:51:01 +0000921 }
922
923public:
Daniel Dunbar644dca02009-12-04 08:17:33 +0000924 TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {}
925
Craig Topperafa7cb32014-03-13 06:07:04 +0000926 bool hasCodeCompletionSupport() const override { return false; }
927 TranslationUnitKind getTranslationUnitKind() override {
Douglas Gregor69f74f82011-08-25 22:30:56 +0000928 return Unit.getTranslationUnitKind();
Douglas Gregor028d3e42010-08-09 20:45:32 +0000929 }
Daniel Dunbar764c0822009-12-01 09:51:01 +0000930};
931
Ilya Biryukov200b3282017-06-21 10:24:58 +0000932class ASTUnitPreambleCallbacks : public PreambleCallbacks {
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000933public:
Ilya Biryukov200b3282017-06-21 10:24:58 +0000934 unsigned getHash() const { return Hash; }
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000935
Ilya Biryukov200b3282017-06-21 10:24:58 +0000936 std::vector<Decl *> takeTopLevelDecls() { return std::move(TopLevelDecls); }
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000937
Ilya Biryukov200b3282017-06-21 10:24:58 +0000938 std::vector<serialization::DeclID> takeTopLevelDeclIDs() {
939 return std::move(TopLevelDeclIDs);
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000940 }
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000941
Ilya Biryukov200b3282017-06-21 10:24:58 +0000942 void AfterPCHEmitted(ASTWriter &Writer) override {
943 TopLevelDeclIDs.reserve(TopLevelDecls.size());
944 for (Decl *D : TopLevelDecls) {
945 // Invalid top-level decls may not have been serialized.
946 if (D->isInvalidDecl())
947 continue;
948 TopLevelDeclIDs.push_back(Writer.getDeclID(D));
949 }
950 }
951
952 void HandleTopLevelDecl(DeclGroupRef DG) override {
Benjamin Kramera401b9b2015-02-06 18:58:04 +0000953 for (Decl *D : DG) {
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000954 // FIXME: Currently ObjC method declarations are incorrectly being
955 // reported as top-level declarations, even though their DeclContext
956 // is the containing ObjC @interface/@implementation. This is a
957 // fundamental problem in the parser right now.
958 if (isa<ObjCMethodDecl>(D))
959 continue;
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000960 AddTopLevelDeclarationToHash(D, Hash);
Douglas Gregore9db88f2010-08-03 19:06:41 +0000961 TopLevelDecls.push_back(D);
962 }
963 }
964
Ilya Biryukov200b3282017-06-21 10:24:58 +0000965 void HandleMacroDefined(const Token &MacroNameTok,
966 const MacroDirective *MD) override {
967 AddDefinedMacroToHash(MacroNameTok, Hash);
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000968 }
Ilya Biryukov200b3282017-06-21 10:24:58 +0000969
970private:
Ilya Biryukov200b3282017-06-21 10:24:58 +0000971 unsigned Hash = 0;
972 std::vector<Decl *> TopLevelDecls;
973 std::vector<serialization::DeclID> TopLevelDeclIDs;
974 llvm::SmallVector<ASTUnit::StandaloneDiagnostic, 4> PreambleDiags;
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000975};
976
Hans Wennborgdcfba332015-10-06 23:40:43 +0000977} // anonymous namespace
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000978
Benjamin Kramer1ce5d802013-05-05 12:39:28 +0000979static bool isNonDriverDiag(const StoredDiagnostic &StoredDiag) {
980 return StoredDiag.getLocation().isValid();
981}
982
983static void
984checkAndRemoveNonDriverDiags(SmallVectorImpl<StoredDiagnostic> &StoredDiags) {
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +0000985 // Get rid of stored diagnostics except the ones from the driver which do not
986 // have a source location.
Benjamin Kramer1ce5d802013-05-05 12:39:28 +0000987 StoredDiags.erase(
988 std::remove_if(StoredDiags.begin(), StoredDiags.end(), isNonDriverDiag),
989 StoredDiags.end());
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +0000990}
991
992static void checkAndSanitizeDiags(SmallVectorImpl<StoredDiagnostic> &
993 StoredDiagnostics,
994 SourceManager &SM) {
995 // The stored diagnostic has the old source manager in it; update
996 // the locations to refer into the new source manager. Since we've
997 // been careful to make sure that the source manager's state
998 // before and after are identical, so that we can reuse the source
999 // location itself.
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00001000 for (StoredDiagnostic &SD : StoredDiagnostics) {
1001 if (SD.getLocation().isValid()) {
1002 FullSourceLoc Loc(SD.getLocation(), SM);
1003 SD.setLocation(Loc);
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +00001004 }
1005 }
1006}
1007
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001008/// Parse the source file into a translation unit using the given compiler
1009/// invocation, replacing the current translation unit.
1010///
1011/// \returns True if a failure occurred that causes the ASTUnit not to
1012/// contain any translation-unit information, false otherwise.
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001013bool ASTUnit::Parse(std::shared_ptr<PCHContainerOperations> PCHContainerOps,
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001014 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer,
1015 IntrusiveRefCntPtr<vfs::FileSystem> VFS) {
Rafael Espindola32482082014-08-18 16:23:45 +00001016 if (!Invocation)
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001017 return true;
Rafael Espindola32482082014-08-18 16:23:45 +00001018
Daniel Dunbar764c0822009-12-01 09:51:01 +00001019 // Create the compiler instance to use for building the AST.
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001020 std::unique_ptr<CompilerInstance> Clang(
Benjamin Kramerd6da1a02016-06-12 20:05:23 +00001021 new CompilerInstance(std::move(PCHContainerOps)));
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001022 if (FileMgr && VFS) {
1023 assert(VFS == FileMgr->getVirtualFileSystem() &&
1024 "VFS passed to Parse and VFS in FileMgr are different");
1025 } else if (VFS) {
1026 Clang->setVirtualFileSystem(VFS);
1027 }
Ted Kremenek84de4a12011-03-21 18:40:07 +00001028
1029 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00001030 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1031 CICleanup(Clang.get());
Ted Kremenek84de4a12011-03-21 18:40:07 +00001032
David Blaikieea4395e2017-01-06 19:49:01 +00001033 Clang->setInvocation(std::make_shared<CompilerInvocation>(*Invocation));
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001034 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001035
Douglas Gregor8e984da2010-08-04 16:47:14 +00001036 // Set up diagnostics, capturing any diagnostics that would
1037 // otherwise be dropped.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001038 Clang->setDiagnostics(&getDiagnostics());
Douglas Gregord03e8232010-04-05 21:10:19 +00001039
Daniel Dunbar764c0822009-12-01 09:51:01 +00001040 // Create the target instance.
Alp Toker80758082014-07-06 05:26:44 +00001041 Clang->setTarget(TargetInfo::CreateTargetInfo(
Saleem Abdulrasool10a49722016-04-08 16:52:00 +00001042 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
Rafael Espindola32482082014-08-18 16:23:45 +00001043 if (!Clang->hasTarget())
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001044 return true;
Douglas Gregora0734c52010-08-19 01:33:06 +00001045
Daniel Dunbar764c0822009-12-01 09:51:01 +00001046 // Inform the target of the language options.
1047 //
1048 // FIXME: We shouldn't need to do this, the target should be immutable once
1049 // created. This complexity should be lifted elsewhere.
Alp Toker74437972014-07-06 05:14:24 +00001050 Clang->getTarget().adjust(Clang->getLangOpts());
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001051
Ted Kremenek84de4a12011-03-21 18:40:07 +00001052 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Daniel Dunbar764c0822009-12-01 09:51:01 +00001053 "Invocation must have exactly one source file!");
Richard Smith40c0efa2017-04-26 18:57:40 +00001054 assert(Clang->getFrontendOpts().Inputs[0].getKind().getFormat() ==
1055 InputKind::Source &&
Daniel Dunbar764c0822009-12-01 09:51:01 +00001056 "FIXME: AST inputs not yet supported here!");
Richard Smith40c0efa2017-04-26 18:57:40 +00001057 assert(Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() !=
1058 InputKind::LLVM_IR &&
Daniel Dunbar9507f9c2010-06-07 23:26:47 +00001059 "IR inputs not support here!");
Daniel Dunbar764c0822009-12-01 09:51:01 +00001060
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001061 // Configure the various subsystems.
Alp Toker269d8402014-07-06 05:26:07 +00001062 LangOpts = Clang->getInvocation().LangOpts;
Ted Kremenek84de4a12011-03-21 18:40:07 +00001063 FileSystemOpts = Clang->getFileSystemOpts();
Benjamin Kramerbc632902015-10-06 14:45:20 +00001064 if (!FileMgr) {
1065 Clang->createFileManager();
1066 FileMgr = &Clang->getFileManager();
1067 }
Erik Verbruggen346066b2017-05-30 14:25:54 +00001068
1069 ResetForParse();
1070
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +00001071 SourceMgr = new SourceManager(getDiagnostics(), *FileMgr,
1072 UserFilesAreVolatile);
Douglas Gregor7b02b582010-08-20 00:02:33 +00001073 if (!OverrideMainBuffer) {
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +00001074 checkAndRemoveNonDriverDiags(StoredDiagnostics);
Douglas Gregor7b02b582010-08-20 00:02:33 +00001075 TopLevelDeclsInPreamble.clear();
1076 }
1077
Daniel Dunbar764c0822009-12-01 09:51:01 +00001078 // Create a file manager object to provide access to and cache the filesystem.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001079 Clang->setFileManager(&getFileManager());
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001080
Daniel Dunbar764c0822009-12-01 09:51:01 +00001081 // Create the source manager.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001082 Clang->setSourceManager(&getSourceManager());
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001083
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001084 // If the main file has been overridden due to the use of a preamble,
1085 // make that override happen and introduce the preamble.
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001086 if (OverrideMainBuffer) {
Ilya Biryukov200b3282017-06-21 10:24:58 +00001087 assert(Preamble && "No preamble was built, but OverrideMainBuffer is not null");
1088 Preamble->AddImplicitPreamble(Clang->getInvocation(), OverrideMainBuffer.get());
Douglas Gregor96c04262010-07-27 14:52:07 +00001089
Douglas Gregord9a30af2010-08-02 20:51:39 +00001090 // The stored diagnostic has the old source manager in it; update
1091 // the locations to refer into the new source manager. Since we've
1092 // been careful to make sure that the source manager's state
1093 // before and after are identical, so that we can reuse the source
1094 // location itself.
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +00001095 checkAndSanitizeDiags(StoredDiagnostics, getSourceManager());
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001096
1097 // Keep track of the override buffer;
Rafael Espindola32482082014-08-18 16:23:45 +00001098 SavedMainFileBuffer = std::move(OverrideMainBuffer);
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001099 }
Ahmed Charlesb8984322014-03-07 20:03:18 +00001100
1101 std::unique_ptr<TopLevelDeclTrackerAction> Act(
1102 new TopLevelDeclTrackerAction(*this));
1103
Ted Kremenek022a4902011-03-22 01:15:24 +00001104 // Recover resources if we crash before exiting this method.
1105 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1106 ActCleanup(Act.get());
1107
Douglas Gregor32fbe312012-01-20 16:28:04 +00001108 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0]))
Daniel Dunbar764c0822009-12-01 09:51:01 +00001109 goto error;
Douglas Gregor925296b2011-07-19 16:10:42 +00001110
Richard Smith26b8f782016-03-25 21:46:44 +00001111 if (SavedMainFileBuffer)
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001112 TranslateStoredDiagnostics(getFileManager(), getSourceManager(),
1113 PreambleDiagnostics, StoredDiagnostics);
Erik Verbruggenefe6fa52017-06-09 08:29:58 +00001114 else
1115 PreambleSrcLocCache.clear();
Douglas Gregor925296b2011-07-19 16:10:42 +00001116
Argyrios Kyrtzidis1416e172012-06-08 05:48:06 +00001117 if (!Act->Execute())
1118 goto error;
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001119
1120 transferASTDataFromCompilerInstance(*Clang);
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001121
Daniel Dunbar644dca02009-12-04 08:17:33 +00001122 Act->EndSourceFile();
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001123
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001124 FailedParseDiagnostics.clear();
1125
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001126 return false;
Ted Kremenek5e14d392011-03-21 18:40:17 +00001127
Daniel Dunbar764c0822009-12-01 09:51:01 +00001128error:
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001129 // Remove the overridden buffer we used for the preamble.
Rafael Espindola32482082014-08-18 16:23:45 +00001130 SavedMainFileBuffer = nullptr;
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001131
1132 // Keep the ownership of the data in the ASTUnit because the client may
1133 // want to see the diagnostics.
1134 transferASTDataFromCompilerInstance(*Clang);
1135 FailedParseDiagnostics.swap(StoredDiagnostics);
Douglas Gregorefc46952010-10-12 16:25:54 +00001136 StoredDiagnostics.clear();
Argyrios Kyrtzidis067cbfa2011-10-24 17:25:20 +00001137 NumStoredDiagnosticsFromDriver = 0;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001138 return true;
1139}
1140
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001141static std::pair<unsigned, unsigned>
1142makeStandaloneRange(CharSourceRange Range, const SourceManager &SM,
1143 const LangOptions &LangOpts) {
1144 CharSourceRange FileRange = Lexer::makeFileCharRange(Range, SM, LangOpts);
1145 unsigned Offset = SM.getFileOffset(FileRange.getBegin());
1146 unsigned EndOffset = SM.getFileOffset(FileRange.getEnd());
1147 return std::make_pair(Offset, EndOffset);
1148}
1149
Benjamin Kramer1a6e0a92014-10-03 18:52:54 +00001150static ASTUnit::StandaloneFixIt makeStandaloneFixIt(const SourceManager &SM,
1151 const LangOptions &LangOpts,
1152 const FixItHint &InFix) {
1153 ASTUnit::StandaloneFixIt OutFix;
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001154 OutFix.RemoveRange = makeStandaloneRange(InFix.RemoveRange, SM, LangOpts);
1155 OutFix.InsertFromRange = makeStandaloneRange(InFix.InsertFromRange, SM,
1156 LangOpts);
1157 OutFix.CodeToInsert = InFix.CodeToInsert;
1158 OutFix.BeforePreviousInsertions = InFix.BeforePreviousInsertions;
Benjamin Kramer1a6e0a92014-10-03 18:52:54 +00001159 return OutFix;
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001160}
1161
Benjamin Kramer1a6e0a92014-10-03 18:52:54 +00001162static ASTUnit::StandaloneDiagnostic
1163makeStandaloneDiagnostic(const LangOptions &LangOpts,
1164 const StoredDiagnostic &InDiag) {
1165 ASTUnit::StandaloneDiagnostic OutDiag;
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001166 OutDiag.ID = InDiag.getID();
1167 OutDiag.Level = InDiag.getLevel();
1168 OutDiag.Message = InDiag.getMessage();
1169 OutDiag.LocOffset = 0;
1170 if (InDiag.getLocation().isInvalid())
Benjamin Kramer1a6e0a92014-10-03 18:52:54 +00001171 return OutDiag;
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001172 const SourceManager &SM = InDiag.getLocation().getManager();
1173 SourceLocation FileLoc = SM.getFileLoc(InDiag.getLocation());
1174 OutDiag.Filename = SM.getFilename(FileLoc);
1175 if (OutDiag.Filename.empty())
Benjamin Kramer1a6e0a92014-10-03 18:52:54 +00001176 return OutDiag;
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001177 OutDiag.LocOffset = SM.getFileOffset(FileLoc);
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00001178 for (const CharSourceRange &Range : InDiag.getRanges())
1179 OutDiag.Ranges.push_back(makeStandaloneRange(Range, SM, LangOpts));
1180 for (const FixItHint &FixIt : InDiag.getFixIts())
1181 OutDiag.FixIts.push_back(makeStandaloneFixIt(SM, LangOpts, FixIt));
Benjamin Kramer1a6e0a92014-10-03 18:52:54 +00001182
1183 return OutDiag;
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001184}
1185
Douglas Gregor4dde7492010-07-23 23:58:40 +00001186/// \brief Attempt to build or re-use a precompiled preamble when (re-)parsing
1187/// the source file.
1188///
1189/// This routine will compute the preamble of the main source file. If a
1190/// non-trivial preamble is found, it will precompile that preamble into a
1191/// precompiled header so that the precompiled preamble can be used to reduce
1192/// reparsing time. If a precompiled preamble has already been constructed,
1193/// this routine will determine if it is still valid and, if so, avoid
1194/// rebuilding the precompiled preamble.
1195///
Douglas Gregor028d3e42010-08-09 20:45:32 +00001196/// \param AllowRebuild When true (the default), this routine is
1197/// allowed to rebuild the precompiled preamble if it is found to be
1198/// out-of-date.
1199///
1200/// \param MaxLines When non-zero, the maximum number of lines that
1201/// can occur within the preamble.
1202///
Douglas Gregor6481ef12010-07-24 00:38:13 +00001203/// \returns If the precompiled preamble can be used, returns a newly-allocated
1204/// buffer that should be used in place of the main file when doing so.
1205/// Otherwise, returns a NULL pointer.
Rafael Espindola2346a372014-08-18 18:47:08 +00001206std::unique_ptr<llvm::MemoryBuffer>
1207ASTUnit::getMainBufferWithPrecompiledPreamble(
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001208 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001209 const CompilerInvocation &PreambleInvocationIn,
1210 IntrusiveRefCntPtr<vfs::FileSystem> VFS, bool AllowRebuild,
Rafael Espindola2346a372014-08-18 18:47:08 +00001211 unsigned MaxLines) {
1212
Ilya Biryukov200b3282017-06-21 10:24:58 +00001213 auto MainFilePath =
1214 PreambleInvocationIn.getFrontendOpts().Inputs[0].getFile();
1215 std::unique_ptr<llvm::MemoryBuffer> MainFileBuffer =
1216 getBufferForFileHandlingRemapping(PreambleInvocationIn, VFS.get(),
1217 MainFilePath);
1218 if (!MainFileBuffer)
Craig Topper49a27902014-05-22 04:46:25 +00001219 return nullptr;
Douglas Gregord9a30af2010-08-02 20:51:39 +00001220
Ilya Biryukov200b3282017-06-21 10:24:58 +00001221 PreambleBounds Bounds =
1222 ComputePreambleBounds(*PreambleInvocationIn.getLangOpts(),
1223 MainFileBuffer.get(), MaxLines);
1224 if (!Bounds.Size)
1225 return nullptr;
Alp Toker1b070d22014-07-07 07:47:20 +00001226
Ilya Biryukov200b3282017-06-21 10:24:58 +00001227 if (Preamble) {
1228 if (Preamble->CanReuse(PreambleInvocationIn, MainFileBuffer.get(), Bounds,
1229 VFS.get())) {
1230 // Okay! We can re-use the precompiled preamble.
Rafael Espindolae4777f42013-07-29 18:22:23 +00001231
Ilya Biryukov200b3282017-06-21 10:24:58 +00001232 // Set the state of the diagnostic object to mimic its state
1233 // after parsing the preamble.
1234 getDiagnostics().Reset();
1235 ProcessWarningOptions(getDiagnostics(),
1236 PreambleInvocationIn.getDiagnosticOpts());
1237 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
Alp Toker1b070d22014-07-07 07:47:20 +00001238
Ilya Biryukov200b3282017-06-21 10:24:58 +00001239 PreambleRebuildCounter = 1;
1240 return MainFileBuffer;
1241 } else {
1242 Preamble.reset();
1243 PreambleDiagnostics.clear();
1244 TopLevelDeclsInPreamble.clear();
1245 PreambleRebuildCounter = 1;
Douglas Gregor4dde7492010-07-23 23:58:40 +00001246 }
Douglas Gregor028d3e42010-08-09 20:45:32 +00001247 }
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001248
1249 // If the preamble rebuild counter > 1, it's because we previously
1250 // failed to build a preamble and we're not yet ready to try
1251 // again. Decrement the counter and return a failure.
1252 if (PreambleRebuildCounter > 1) {
1253 --PreambleRebuildCounter;
Craig Topper49a27902014-05-22 04:46:25 +00001254 return nullptr;
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001255 }
1256
Ilya Biryukov200b3282017-06-21 10:24:58 +00001257 assert(!Preamble && "No Preamble should be stored at that point");
1258 // If we aren't allowed to rebuild the precompiled preamble, just
1259 // return now.
1260 if (!AllowRebuild)
Ben Langmuir8832c062014-04-15 18:16:25 +00001261 return nullptr;
1262
Ilya Biryukov200b3282017-06-21 10:24:58 +00001263 SmallVector<StandaloneDiagnostic, 4> NewPreambleDiagsStandalone;
1264 SmallVector<StoredDiagnostic, 4> NewPreambleDiags;
Ilya Biryukovf81d46f2017-06-21 12:34:27 +00001265 ASTUnitPreambleCallbacks Callbacks;
Ilya Biryukov200b3282017-06-21 10:24:58 +00001266 {
1267 llvm::Optional<CaptureDroppedDiagnostics> Capture;
1268 if (CaptureDiagnostics)
1269 Capture.emplace(/*RequestCapture=*/true, *Diagnostics, &NewPreambleDiags,
1270 &NewPreambleDiagsStandalone);
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001271
Ilya Biryukov200b3282017-06-21 10:24:58 +00001272 // We did not previously compute a preamble, or it can't be reused anyway.
1273 SimpleTimer PreambleTimer(WantTiming);
1274 PreambleTimer.setOutput("Precompiling preamble");
Ahmed Charlesb8984322014-03-07 20:03:18 +00001275
Ilya Biryukov200b3282017-06-21 10:24:58 +00001276 llvm::ErrorOr<PrecompiledPreamble> NewPreamble = PrecompiledPreamble::Build(
1277 PreambleInvocationIn, MainFileBuffer.get(), Bounds, *Diagnostics, VFS,
1278 PCHContainerOps, Callbacks);
1279 if (NewPreamble) {
1280 Preamble = std::move(*NewPreamble);
1281 PreambleRebuildCounter = 1;
Dmitri Gribenko47652522013-12-20 00:16:25 +00001282 } else {
Ilya Biryukov200b3282017-06-21 10:24:58 +00001283 switch (static_cast<BuildPreambleError>(NewPreamble.getError().value())) {
1284 case BuildPreambleError::CouldntCreateTempFile:
1285 case BuildPreambleError::PreambleIsEmpty:
1286 // Try again next time.
1287 PreambleRebuildCounter = 1;
Ilya Biryukovf81d46f2017-06-21 12:34:27 +00001288 return nullptr;
Ilya Biryukov200b3282017-06-21 10:24:58 +00001289 case BuildPreambleError::CouldntCreateTargetInfo:
1290 case BuildPreambleError::BeginSourceFileFailed:
1291 case BuildPreambleError::CouldntEmitPCH:
1292 case BuildPreambleError::CouldntCreateVFSOverlay:
1293 // These erros are more likely to repeat, retry after some period.
1294 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Ilya Biryukovf81d46f2017-06-21 12:34:27 +00001295 return nullptr;
Ilya Biryukov200b3282017-06-21 10:24:58 +00001296 }
Ilya Biryukovf81d46f2017-06-21 12:34:27 +00001297 llvm_unreachable("unexpected BuildPreambleError");
Dmitri Gribenko47652522013-12-20 00:16:25 +00001298 }
Douglas Gregor0e119552010-07-31 00:40:00 +00001299 }
Ben Langmuir33c80902014-06-30 20:04:14 +00001300
Ilya Biryukov200b3282017-06-21 10:24:58 +00001301 assert(Preamble && "Preamble wasn't built");
1302
1303 TopLevelDecls.clear();
1304 TopLevelDeclsInPreamble = Callbacks.takeTopLevelDeclIDs();
1305 PreambleTopLevelHashValue = Callbacks.getHash();
1306
1307 NumWarningsInPreamble = getDiagnostics().getNumWarnings();
1308
1309 checkAndRemoveNonDriverDiags(NewPreambleDiags);
1310 StoredDiagnostics = std::move(NewPreambleDiags);
1311 PreambleDiagnostics = std::move(NewPreambleDiagsStandalone);
Alp Toker1b070d22014-07-07 07:47:20 +00001312
Douglas Gregordf7a79a2011-02-16 18:16:54 +00001313 // If the hash of top-level entities differs from the hash of the top-level
1314 // entities the last time we rebuilt the preamble, clear out the completion
1315 // cache.
1316 if (CurrentTopLevelHashValue != PreambleTopLevelHashValue) {
1317 CompletionCacheTopLevelHashValue = 0;
1318 PreambleTopLevelHashValue = CurrentTopLevelHashValue;
1319 }
Rafael Espindola2346a372014-08-18 18:47:08 +00001320
Ilya Biryukov200b3282017-06-21 10:24:58 +00001321 return MainFileBuffer;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001322}
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001323
Douglas Gregore9db88f2010-08-03 19:06:41 +00001324void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
Ilya Biryukov200b3282017-06-21 10:24:58 +00001325 assert(Preamble && "Should only be called when preamble was built");
1326
Douglas Gregore9db88f2010-08-03 19:06:41 +00001327 std::vector<Decl *> Resolved;
1328 Resolved.reserve(TopLevelDeclsInPreamble.size());
1329 ExternalASTSource &Source = *getASTContext().getExternalSource();
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00001330 for (serialization::DeclID TopLevelDecl : TopLevelDeclsInPreamble) {
Douglas Gregore9db88f2010-08-03 19:06:41 +00001331 // Resolve the declaration ID to an actual declaration, possibly
1332 // deserializing the declaration in the process.
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00001333 if (Decl *D = Source.GetExternalDecl(TopLevelDecl))
Douglas Gregore9db88f2010-08-03 19:06:41 +00001334 Resolved.push_back(D);
1335 }
1336 TopLevelDeclsInPreamble.clear();
1337 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1338}
1339
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001340void ASTUnit::transferASTDataFromCompilerInstance(CompilerInstance &CI) {
Ben Langmuir749323f2014-04-22 17:40:12 +00001341 // Steal the created target, context, and preprocessor if they have been
1342 // created.
1343 assert(CI.hasInvocation() && "missing invocation");
Alp Toker269d8402014-07-06 05:26:07 +00001344 LangOpts = CI.getInvocation().LangOpts;
David Blaikieec99b5e2014-08-10 19:14:48 +00001345 TheSema = CI.takeSema();
David Blaikie6beb6aa2014-08-10 19:56:51 +00001346 Consumer = CI.takeASTConsumer();
Ben Langmuir532fdc02014-04-18 20:39:48 +00001347 if (CI.hasASTContext())
1348 Ctx = &CI.getASTContext();
1349 if (CI.hasPreprocessor())
David Blaikie41565462017-01-05 19:48:07 +00001350 PP = CI.getPreprocessorPtr();
Craig Topper49a27902014-05-22 04:46:25 +00001351 CI.setSourceManager(nullptr);
1352 CI.setFileManager(nullptr);
Ben Langmuir532fdc02014-04-18 20:39:48 +00001353 if (CI.hasTarget())
1354 Target = &CI.getTarget();
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001355 Reader = CI.getModuleManager();
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00001356 HadModuleLoaderFatalFailure = CI.hadModuleLoaderFatalFailure();
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001357}
1358
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001359StringRef ASTUnit::getMainFileName() const {
Argyrios Kyrtzidis928e1fd2013-01-11 22:11:14 +00001360 if (Invocation && !Invocation->getFrontendOpts().Inputs.empty()) {
1361 const FrontendInputFile &Input = Invocation->getFrontendOpts().Inputs[0];
1362 if (Input.isFile())
1363 return Input.getFile();
1364 else
1365 return Input.getBuffer()->getBufferIdentifier();
1366 }
1367
1368 if (SourceMgr) {
1369 if (const FileEntry *
1370 FE = SourceMgr->getFileEntryForID(SourceMgr->getMainFileID()))
1371 return FE->getName();
1372 }
1373
1374 return StringRef();
Douglas Gregor16896c42010-10-28 15:44:59 +00001375}
1376
Argyrios Kyrtzidis37f2ab42013-03-05 20:21:14 +00001377StringRef ASTUnit::getASTFileName() const {
1378 if (!isMainFileAST())
1379 return StringRef();
1380
1381 serialization::ModuleFile &
1382 Mod = Reader->getModuleManager().getPrimaryModule();
1383 return Mod.FileName;
1384}
1385
David Blaikieea4395e2017-01-06 19:49:01 +00001386std::unique_ptr<ASTUnit>
1387ASTUnit::create(std::shared_ptr<CompilerInvocation> CI,
1388 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
1389 bool CaptureDiagnostics, bool UserFilesAreVolatile) {
1390 std::unique_ptr<ASTUnit> AST(new ASTUnit(false));
Justin Bognerdbbcb112014-10-14 23:36:06 +00001391 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
Ben Langmuir8832c062014-04-15 18:16:25 +00001392 IntrusiveRefCntPtr<vfs::FileSystem> VFS =
1393 createVFSFromCompilerInvocation(*CI, *Diags);
1394 if (!VFS)
1395 return nullptr;
David Blaikieea4395e2017-01-06 19:49:01 +00001396 AST->Diagnostics = Diags;
1397 AST->FileSystemOpts = CI->getFileSystemOpts();
1398 AST->Invocation = std::move(CI);
Ben Langmuir8832c062014-04-15 18:16:25 +00001399 AST->FileMgr = new FileManager(AST->FileSystemOpts, VFS);
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +00001400 AST->UserFilesAreVolatile = UserFilesAreVolatile;
1401 AST->SourceMgr = new SourceManager(AST->getDiagnostics(), *AST->FileMgr,
1402 UserFilesAreVolatile);
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00001403 AST->PCMCache = new MemoryBufferCache;
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00001404
David Blaikieea4395e2017-01-06 19:49:01 +00001405 return AST;
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00001406}
1407
Ahmed Charlesb8984322014-03-07 20:03:18 +00001408ASTUnit *ASTUnit::LoadFromCompilerInvocationAction(
David Blaikieea4395e2017-01-06 19:49:01 +00001409 std::shared_ptr<CompilerInvocation> CI,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001410 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
Argyrios Kyrtzidisc382abf2016-02-09 19:07:13 +00001411 IntrusiveRefCntPtr<DiagnosticsEngine> Diags, FrontendAction *Action,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001412 ASTUnit *Unit, bool Persistent, StringRef ResourceFilesPath,
Benjamin Kramer5c248d82015-12-15 09:30:31 +00001413 bool OnlyLocalDecls, bool CaptureDiagnostics,
1414 unsigned PrecompilePreambleAfterNParses, bool CacheCodeCompletionResults,
1415 bool IncludeBriefCommentsInCodeCompletion, bool UserFilesAreVolatile,
1416 std::unique_ptr<ASTUnit> *ErrAST) {
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001417 assert(CI && "A CompilerInvocation is required");
1418
Ahmed Charlesb8984322014-03-07 20:03:18 +00001419 std::unique_ptr<ASTUnit> OwnAST;
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001420 ASTUnit *AST = Unit;
1421 if (!AST) {
1422 // Create the AST unit.
David Blaikieea4395e2017-01-06 19:49:01 +00001423 OwnAST = create(CI, Diags, CaptureDiagnostics, UserFilesAreVolatile);
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001424 AST = OwnAST.get();
Ben Langmuir8832c062014-04-15 18:16:25 +00001425 if (!AST)
1426 return nullptr;
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001427 }
1428
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00001429 if (!ResourceFilesPath.empty()) {
1430 // Override the resources path.
1431 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
1432 }
1433 AST->OnlyLocalDecls = OnlyLocalDecls;
1434 AST->CaptureDiagnostics = CaptureDiagnostics;
Benjamin Kramer5c248d82015-12-15 09:30:31 +00001435 if (PrecompilePreambleAfterNParses > 0)
1436 AST->PreambleRebuildCounter = PrecompilePreambleAfterNParses;
Douglas Gregor69f74f82011-08-25 22:30:56 +00001437 AST->TUKind = Action ? Action->getTranslationUnitKind() : TU_Complete;
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00001438 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenko3292d062012-07-02 17:35:10 +00001439 AST->IncludeBriefCommentsInCodeCompletion
1440 = IncludeBriefCommentsInCodeCompletion;
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001441
1442 // Recover resources if we crash before exiting this method.
1443 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001444 ASTUnitCleanup(OwnAST.get());
David Blaikie9c902b52011-09-25 23:23:43 +00001445 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1446 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Alp Tokerf994cef2014-07-05 03:08:06 +00001447 DiagCleanup(Diags.get());
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001448
1449 // We'll manage file buffers ourselves.
1450 CI->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1451 CI->getFrontendOpts().DisableFree = false;
1452 ProcessWarningOptions(AST->getDiagnostics(), CI->getDiagnosticOpts());
1453
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001454 // Create the compiler instance to use for building the AST.
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001455 std::unique_ptr<CompilerInstance> Clang(
Benjamin Kramerd6da1a02016-06-12 20:05:23 +00001456 new CompilerInstance(std::move(PCHContainerOps)));
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001457
1458 // Recover resources if we crash before exiting this method.
1459 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1460 CICleanup(Clang.get());
1461
David Blaikieea4395e2017-01-06 19:49:01 +00001462 Clang->setInvocation(std::move(CI));
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001463 AST->OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001464
1465 // Set up diagnostics, capturing any diagnostics that would
1466 // otherwise be dropped.
1467 Clang->setDiagnostics(&AST->getDiagnostics());
1468
1469 // Create the target instance.
Alp Toker80758082014-07-06 05:26:44 +00001470 Clang->setTarget(TargetInfo::CreateTargetInfo(
Saleem Abdulrasool10a49722016-04-08 16:52:00 +00001471 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001472 if (!Clang->hasTarget())
Craig Topper49a27902014-05-22 04:46:25 +00001473 return nullptr;
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001474
1475 // Inform the target of the language options.
1476 //
1477 // FIXME: We shouldn't need to do this, the target should be immutable once
1478 // created. This complexity should be lifted elsewhere.
Alp Toker74437972014-07-06 05:14:24 +00001479 Clang->getTarget().adjust(Clang->getLangOpts());
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001480
1481 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1482 "Invocation must have exactly one source file!");
Richard Smith40c0efa2017-04-26 18:57:40 +00001483 assert(Clang->getFrontendOpts().Inputs[0].getKind().getFormat() ==
1484 InputKind::Source &&
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001485 "FIXME: AST inputs not yet supported here!");
Richard Smith40c0efa2017-04-26 18:57:40 +00001486 assert(Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() !=
1487 InputKind::LLVM_IR &&
1488 "IR inputs not support here!");
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001489
1490 // Configure the various subsystems.
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001491 AST->TheSema.reset();
Craig Topper49a27902014-05-22 04:46:25 +00001492 AST->Ctx = nullptr;
1493 AST->PP = nullptr;
1494 AST->Reader = nullptr;
1495
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001496 // Create a file manager object to provide access to and cache the filesystem.
1497 Clang->setFileManager(&AST->getFileManager());
1498
1499 // Create the source manager.
1500 Clang->setSourceManager(&AST->getSourceManager());
1501
Argyrios Kyrtzidisc382abf2016-02-09 19:07:13 +00001502 FrontendAction *Act = Action;
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001503
Ahmed Charlesb8984322014-03-07 20:03:18 +00001504 std::unique_ptr<TopLevelDeclTrackerAction> TrackerAct;
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001505 if (!Act) {
1506 TrackerAct.reset(new TopLevelDeclTrackerAction(*AST));
1507 Act = TrackerAct.get();
1508 }
1509
1510 // Recover resources if we crash before exiting this method.
1511 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1512 ActCleanup(TrackerAct.get());
1513
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001514 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
1515 AST->transferASTDataFromCompilerInstance(*Clang);
1516 if (OwnAST && ErrAST)
1517 ErrAST->swap(OwnAST);
1518
Craig Topper49a27902014-05-22 04:46:25 +00001519 return nullptr;
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001520 }
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00001521
1522 if (Persistent && !TrackerAct) {
1523 Clang->getPreprocessor().addPPCallbacks(
Craig Topperb8a70532014-09-10 04:53:53 +00001524 llvm::make_unique<MacroDefinitionTrackerPPCallbacks>(
1525 AST->getCurrentTopLevelHashValue()));
David Blaikie6beb6aa2014-08-10 19:56:51 +00001526 std::vector<std::unique_ptr<ASTConsumer>> Consumers;
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00001527 if (Clang->hasASTConsumer())
1528 Consumers.push_back(Clang->takeASTConsumer());
David Blaikie6beb6aa2014-08-10 19:56:51 +00001529 Consumers.push_back(llvm::make_unique<TopLevelDeclTrackerConsumer>(
1530 *AST, AST->getCurrentTopLevelHashValue()));
1531 Clang->setASTConsumer(
1532 llvm::make_unique<MultiplexConsumer>(std::move(Consumers)));
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00001533 }
Argyrios Kyrtzidis1416e172012-06-08 05:48:06 +00001534 if (!Act->Execute()) {
1535 AST->transferASTDataFromCompilerInstance(*Clang);
1536 if (OwnAST && ErrAST)
1537 ErrAST->swap(OwnAST);
1538
Craig Topper49a27902014-05-22 04:46:25 +00001539 return nullptr;
Argyrios Kyrtzidis1416e172012-06-08 05:48:06 +00001540 }
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001541
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001542 // Steal the created target, context, and preprocessor.
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001543 AST->transferASTDataFromCompilerInstance(*Clang);
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001544
1545 Act->EndSourceFile();
1546
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001547 if (OwnAST)
Ahmed Charles9a16beb2014-03-07 19:33:25 +00001548 return OwnAST.release();
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001549 else
1550 return AST;
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001551}
1552
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001553bool ASTUnit::LoadFromCompilerInvocation(
1554 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001555 unsigned PrecompilePreambleAfterNParses,
1556 IntrusiveRefCntPtr<vfs::FileSystem> VFS) {
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001557 if (!Invocation)
1558 return true;
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001559
1560 assert(VFS && "VFS is null");
1561
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001562 // We'll manage file buffers ourselves.
1563 Invocation->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1564 Invocation->getFrontendOpts().DisableFree = false;
Benjamin Kramer8de9c9b2017-01-18 16:25:48 +00001565 getDiagnostics().Reset();
Douglas Gregor345c1bc2011-01-19 01:02:47 +00001566 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001567
Rafael Espindola32482082014-08-18 16:23:45 +00001568 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
Benjamin Kramer5c248d82015-12-15 09:30:31 +00001569 if (PrecompilePreambleAfterNParses > 0) {
1570 PreambleRebuildCounter = PrecompilePreambleAfterNParses;
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001571 OverrideMainBuffer =
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001572 getMainBufferWithPrecompiledPreamble(PCHContainerOps, *Invocation, VFS);
Benjamin Kramer8484a322017-02-13 16:16:43 +00001573 getDiagnostics().Reset();
1574 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001575 }
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001576
Douglas Gregor16896c42010-10-28 15:44:59 +00001577 SimpleTimer ParsingTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00001578 ParsingTimer.setOutput("Parsing " + getMainFileName());
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001579
Ted Kremenek022a4902011-03-22 01:15:24 +00001580 // Recover resources if we crash before exiting this method.
1581 llvm::CrashRecoveryContextCleanupRegistrar<llvm::MemoryBuffer>
Rafael Espindola32482082014-08-18 16:23:45 +00001582 MemBufferCleanup(OverrideMainBuffer.get());
1583
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001584 return Parse(std::move(PCHContainerOps), std::move(OverrideMainBuffer), VFS);
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001585}
1586
David Blaikie103a2de2014-04-25 17:01:33 +00001587std::unique_ptr<ASTUnit> ASTUnit::LoadFromCompilerInvocation(
David Blaikieea4395e2017-01-06 19:49:01 +00001588 std::shared_ptr<CompilerInvocation> CI,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001589 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
Benjamin Kramerbc632902015-10-06 14:45:20 +00001590 IntrusiveRefCntPtr<DiagnosticsEngine> Diags, FileManager *FileMgr,
Benjamin Kramer5c248d82015-12-15 09:30:31 +00001591 bool OnlyLocalDecls, bool CaptureDiagnostics,
1592 unsigned PrecompilePreambleAfterNParses, TranslationUnitKind TUKind,
1593 bool CacheCodeCompletionResults, bool IncludeBriefCommentsInCodeCompletion,
1594 bool UserFilesAreVolatile) {
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001595 // Create the AST unit.
David Blaikie103a2de2014-04-25 17:01:33 +00001596 std::unique_ptr<ASTUnit> AST(new ASTUnit(false));
Justin Bognerdbbcb112014-10-14 23:36:06 +00001597 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001598 AST->Diagnostics = Diags;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001599 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001600 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor69f74f82011-08-25 22:30:56 +00001601 AST->TUKind = TUKind;
Douglas Gregorb14904c2010-08-13 22:48:40 +00001602 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenko3292d062012-07-02 17:35:10 +00001603 AST->IncludeBriefCommentsInCodeCompletion
1604 = IncludeBriefCommentsInCodeCompletion;
David Blaikieea4395e2017-01-06 19:49:01 +00001605 AST->Invocation = std::move(CI);
Benjamin Kramerbc632902015-10-06 14:45:20 +00001606 AST->FileSystemOpts = FileMgr->getFileSystemOpts();
1607 AST->FileMgr = FileMgr;
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +00001608 AST->UserFilesAreVolatile = UserFilesAreVolatile;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001609
Ted Kremenek4422bfe2011-03-18 02:06:56 +00001610 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00001611 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1612 ASTUnitCleanup(AST.get());
David Blaikie9c902b52011-09-25 23:23:43 +00001613 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1614 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Alp Tokerf994cef2014-07-05 03:08:06 +00001615 DiagCleanup(Diags.get());
Ted Kremenek4422bfe2011-03-18 02:06:56 +00001616
Benjamin Kramerd6da1a02016-06-12 20:05:23 +00001617 if (AST->LoadFromCompilerInvocation(std::move(PCHContainerOps),
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001618 PrecompilePreambleAfterNParses,
1619 AST->FileMgr->getVirtualFileSystem()))
David Blaikie103a2de2014-04-25 17:01:33 +00001620 return nullptr;
1621 return AST;
Daniel Dunbar764c0822009-12-01 09:51:01 +00001622}
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001623
Ahmed Charlesb8984322014-03-07 20:03:18 +00001624ASTUnit *ASTUnit::LoadFromCommandLine(
1625 const char **ArgBegin, const char **ArgEnd,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001626 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
Ahmed Charlesb8984322014-03-07 20:03:18 +00001627 IntrusiveRefCntPtr<DiagnosticsEngine> Diags, StringRef ResourceFilesPath,
1628 bool OnlyLocalDecls, bool CaptureDiagnostics,
1629 ArrayRef<RemappedFile> RemappedFiles, bool RemappedFilesKeepOriginalName,
Benjamin Kramer5c248d82015-12-15 09:30:31 +00001630 unsigned PrecompilePreambleAfterNParses, TranslationUnitKind TUKind,
Ahmed Charlesb8984322014-03-07 20:03:18 +00001631 bool CacheCodeCompletionResults, bool IncludeBriefCommentsInCodeCompletion,
1632 bool AllowPCHWithCompilerErrors, bool SkipFunctionBodies,
Argyrios Kyrtzidis735e92c2017-06-09 01:20:48 +00001633 bool SingleFileParse, bool UserFilesAreVolatile, bool ForSerialization,
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001634 llvm::Optional<StringRef> ModuleFormat, std::unique_ptr<ASTUnit> *ErrAST,
1635 IntrusiveRefCntPtr<vfs::FileSystem> VFS) {
Justin Bognerd512c1e2014-10-15 00:33:06 +00001636 assert(Diags.get() && "no DiagnosticsEngine was provided");
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001637
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001638 SmallVector<StoredDiagnostic, 4> StoredDiagnostics;
David Blaikieea4395e2017-01-06 19:49:01 +00001639
1640 std::shared_ptr<CompilerInvocation> CI;
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001641
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001642 {
Douglas Gregor925296b2011-07-19 16:10:42 +00001643
Ilya Biryukov200b3282017-06-21 10:24:58 +00001644 CaptureDroppedDiagnostics Capture(CaptureDiagnostics, *Diags,
1645 &StoredDiagnostics, nullptr);
Daniel Dunbarfcf2d422010-01-25 00:44:02 +00001646
Argyrios Kyrtzidis5cf423e2011-04-04 23:11:45 +00001647 CI = clang::createInvocationFromCommandLine(
Ilya Biryukovafdadf52017-06-28 15:06:34 +00001648 llvm::makeArrayRef(ArgBegin, ArgEnd), Diags, VFS);
Argyrios Kyrtzidisf606b822011-04-04 21:38:51 +00001649 if (!CI)
Craig Topper49a27902014-05-22 04:46:25 +00001650 return nullptr;
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001651 }
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001652
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001653 // Override any files that need remapping
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00001654 for (const auto &RemappedFile : RemappedFiles) {
1655 CI->getPreprocessorOpts().addRemappedFile(RemappedFile.first,
1656 RemappedFile.second);
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00001657 }
Argyrios Kyrtzidis4a280ff2012-03-07 01:51:17 +00001658 PreprocessorOptions &PPOpts = CI->getPreprocessorOpts();
1659 PPOpts.RemappedFilesKeepOriginalName = RemappedFilesKeepOriginalName;
1660 PPOpts.AllowPCHWithCompilerErrors = AllowPCHWithCompilerErrors;
Erik Verbruggenb34c79f2017-05-30 11:54:55 +00001661 PPOpts.GeneratePreamble = PrecompilePreambleAfterNParses != 0;
Argyrios Kyrtzidis735e92c2017-06-09 01:20:48 +00001662 PPOpts.SingleFileParseMode = SingleFileParse;
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001663
Daniel Dunbara5a166d2009-12-15 00:06:45 +00001664 // Override the resources path.
Daniel Dunbar6b03ece2010-01-30 21:47:16 +00001665 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001666
Erik Verbruggen6e922512012-04-12 10:11:59 +00001667 CI->getFrontendOpts().SkipFunctionBodies = SkipFunctionBodies;
1668
Argyrios Kyrtzidisa3e2ff12015-11-20 03:36:21 +00001669 if (ModuleFormat)
1670 CI->getHeaderSearchOpts().ModuleFormat = ModuleFormat.getValue();
1671
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001672 // Create the AST unit.
Ahmed Charlesb8984322014-03-07 20:03:18 +00001673 std::unique_ptr<ASTUnit> AST;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001674 AST.reset(new ASTUnit(false));
Justin Bognerdbbcb112014-10-14 23:36:06 +00001675 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001676 AST->Diagnostics = Diags;
Anders Carlssonc30dcec2011-03-18 18:22:40 +00001677 AST->FileSystemOpts = CI->getFileSystemOpts();
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001678 if (!VFS)
1679 VFS = vfs::getRealFileSystem();
1680 VFS = createVFSFromCompilerInvocation(*CI, *Diags, VFS);
Ben Langmuir8832c062014-04-15 18:16:25 +00001681 if (!VFS)
1682 return nullptr;
1683 AST->FileMgr = new FileManager(AST->FileSystemOpts, VFS);
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00001684 AST->PCMCache = new MemoryBufferCache;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001685 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001686 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor69f74f82011-08-25 22:30:56 +00001687 AST->TUKind = TUKind;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001688 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenko3292d062012-07-02 17:35:10 +00001689 AST->IncludeBriefCommentsInCodeCompletion
1690 = IncludeBriefCommentsInCodeCompletion;
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +00001691 AST->UserFilesAreVolatile = UserFilesAreVolatile;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001692 AST->NumStoredDiagnosticsFromDriver = StoredDiagnostics.size();
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001693 AST->StoredDiagnostics.swap(StoredDiagnostics);
Ted Kremenek5e14d392011-03-21 18:40:17 +00001694 AST->Invocation = CI;
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00001695 if (ForSerialization)
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00001696 AST->WriterData.reset(new ASTWriterData(*AST->PCMCache));
Alexey Samsonovb4f99dd2014-08-28 23:51:01 +00001697 // Zero out now to ease cleanup during crash recovery.
1698 CI = nullptr;
1699 Diags = nullptr;
Craig Topper49a27902014-05-22 04:46:25 +00001700
Ted Kremenek4422bfe2011-03-18 02:06:56 +00001701 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00001702 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1703 ASTUnitCleanup(AST.get());
Ted Kremenek4422bfe2011-03-18 02:06:56 +00001704
Benjamin Kramerd6da1a02016-06-12 20:05:23 +00001705 if (AST->LoadFromCompilerInvocation(std::move(PCHContainerOps),
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001706 PrecompilePreambleAfterNParses,
1707 VFS)) {
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001708 // Some error occurred, if caller wants to examine diagnostics, pass it the
1709 // ASTUnit.
1710 if (ErrAST) {
1711 AST->StoredDiagnostics.swap(AST->FailedParseDiagnostics);
1712 ErrAST->swap(AST);
1713 }
Craig Topper49a27902014-05-22 04:46:25 +00001714 return nullptr;
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001715 }
1716
Ahmed Charles9a16beb2014-03-07 19:33:25 +00001717 return AST.release();
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001718}
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001719
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001720bool ASTUnit::Reparse(std::shared_ptr<PCHContainerOperations> PCHContainerOps,
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001721 ArrayRef<RemappedFile> RemappedFiles,
1722 IntrusiveRefCntPtr<vfs::FileSystem> VFS) {
Ted Kremenek5e14d392011-03-21 18:40:17 +00001723 if (!Invocation)
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001724 return true;
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00001725
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001726 if (!VFS) {
1727 assert(FileMgr && "FileMgr is null on Reparse call");
1728 VFS = FileMgr->getVirtualFileSystem();
1729 }
1730
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00001731 clearFileLevelDecls();
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001732
Douglas Gregor16896c42010-10-28 15:44:59 +00001733 SimpleTimer ParsingTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00001734 ParsingTimer.setOutput("Reparsing " + getMainFileName());
Douglas Gregor16896c42010-10-28 15:44:59 +00001735
Douglas Gregor0e119552010-07-31 00:40:00 +00001736 // Remap files.
Douglas Gregor7b02b582010-08-20 00:02:33 +00001737 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
Alp Toker1b070d22014-07-07 07:47:20 +00001738 for (const auto &RB : PPOpts.RemappedFileBuffers)
1739 delete RB.second;
1740
Douglas Gregor0e119552010-07-31 00:40:00 +00001741 Invocation->getPreprocessorOpts().clearRemappedFiles();
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00001742 for (const auto &RemappedFile : RemappedFiles) {
1743 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFile.first,
1744 RemappedFile.second);
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00001745 }
Dmitri Gribenkoc444b572014-02-08 00:38:15 +00001746
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001747 // If we have a preamble file lying around, or if we might try to
1748 // build a precompiled preamble, do so now.
Rafael Espindola32482082014-08-18 16:23:45 +00001749 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
Ilya Biryukov200b3282017-06-21 10:24:58 +00001750 if (Preamble || PreambleRebuildCounter > 0)
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001751 OverrideMainBuffer =
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001752 getMainBufferWithPrecompiledPreamble(PCHContainerOps, *Invocation, VFS);
1753
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001754
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001755 // Clear out the diagnostics state.
Benjamin Kramerbc632902015-10-06 14:45:20 +00001756 FileMgr.reset();
Argyrios Kyrtzidisf50f7b22011-11-03 20:28:19 +00001757 getDiagnostics().Reset();
1758 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Argyrios Kyrtzidis462ff352011-11-03 20:57:33 +00001759 if (OverrideMainBuffer)
1760 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
Argyrios Kyrtzidisf50f7b22011-11-03 20:28:19 +00001761
Douglas Gregor4dde7492010-07-23 23:58:40 +00001762 // Parse the sources
Benjamin Kramerd6da1a02016-06-12 20:05:23 +00001763 bool Result =
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001764 Parse(std::move(PCHContainerOps), std::move(OverrideMainBuffer), VFS);
Rafael Espindola32482082014-08-18 16:23:45 +00001765
Argyrios Kyrtzidis36893372011-10-31 21:25:31 +00001766 // If we're caching global code-completion results, and the top-level
1767 // declarations have changed, clear out the code-completion cache.
1768 if (!Result && ShouldCacheCodeCompletionResults &&
1769 CurrentTopLevelHashValue != CompletionCacheTopLevelHashValue)
1770 CacheCodeCompletionResults();
Douglas Gregordf7a79a2011-02-16 18:16:54 +00001771
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00001772 // We now need to clear out the completion info related to this translation
1773 // unit; it'll be recreated if necessary.
1774 CCTUInfo.reset();
Douglas Gregor3f35bb22011-08-04 20:04:59 +00001775
Douglas Gregor4dde7492010-07-23 23:58:40 +00001776 return Result;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001777}
Douglas Gregor8e984da2010-08-04 16:47:14 +00001778
Erik Verbruggen346066b2017-05-30 14:25:54 +00001779void ASTUnit::ResetForParse() {
1780 SavedMainFileBuffer.reset();
1781
1782 SourceMgr.reset();
1783 TheSema.reset();
1784 Ctx.reset();
1785 PP.reset();
1786 Reader.reset();
1787
1788 TopLevelDecls.clear();
1789 clearFileLevelDecls();
1790}
1791
Douglas Gregorb14904c2010-08-13 22:48:40 +00001792//----------------------------------------------------------------------------//
1793// Code completion
1794//----------------------------------------------------------------------------//
1795
1796namespace {
1797 /// \brief Code completion consumer that combines the cached code-completion
1798 /// results from an ASTUnit with the code-completion results provided to it,
1799 /// then passes the result on to
1800 class AugmentedCodeCompleteConsumer : public CodeCompleteConsumer {
Richard Smith697cc9e2012-08-14 03:13:00 +00001801 uint64_t NormalContexts;
Douglas Gregorb14904c2010-08-13 22:48:40 +00001802 ASTUnit &AST;
1803 CodeCompleteConsumer &Next;
1804
1805 public:
1806 AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next,
Dmitri Gribenko3292d062012-07-02 17:35:10 +00001807 const CodeCompleteOptions &CodeCompleteOpts)
1808 : CodeCompleteConsumer(CodeCompleteOpts, Next.isOutputBinary()),
1809 AST(AST), Next(Next)
Douglas Gregorb14904c2010-08-13 22:48:40 +00001810 {
1811 // Compute the set of contexts in which we will look when we don't have
1812 // any information about the specific context.
1813 NormalContexts
Richard Smith697cc9e2012-08-14 03:13:00 +00001814 = (1LL << CodeCompletionContext::CCC_TopLevel)
1815 | (1LL << CodeCompletionContext::CCC_ObjCInterface)
1816 | (1LL << CodeCompletionContext::CCC_ObjCImplementation)
1817 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
1818 | (1LL << CodeCompletionContext::CCC_Statement)
1819 | (1LL << CodeCompletionContext::CCC_Expression)
1820 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
1821 | (1LL << CodeCompletionContext::CCC_DotMemberAccess)
1822 | (1LL << CodeCompletionContext::CCC_ArrowMemberAccess)
1823 | (1LL << CodeCompletionContext::CCC_ObjCPropertyAccess)
1824 | (1LL << CodeCompletionContext::CCC_ObjCProtocolName)
1825 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
1826 | (1LL << CodeCompletionContext::CCC_Recovery);
Douglas Gregor5e35d592010-09-14 23:59:36 +00001827
David Blaikiebbafb8a2012-03-11 07:00:24 +00001828 if (AST.getASTContext().getLangOpts().CPlusPlus)
Richard Smith697cc9e2012-08-14 03:13:00 +00001829 NormalContexts |= (1LL << CodeCompletionContext::CCC_EnumTag)
1830 | (1LL << CodeCompletionContext::CCC_UnionTag)
1831 | (1LL << CodeCompletionContext::CCC_ClassOrStructTag);
Douglas Gregorb14904c2010-08-13 22:48:40 +00001832 }
Craig Topperafa7cb32014-03-13 06:07:04 +00001833
1834 void ProcessCodeCompleteResults(Sema &S, CodeCompletionContext Context,
1835 CodeCompletionResult *Results,
1836 unsigned NumResults) override;
1837
1838 void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
1839 OverloadCandidate *Candidates,
1840 unsigned NumCandidates) override {
Douglas Gregorb14904c2010-08-13 22:48:40 +00001841 Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates);
1842 }
Craig Topperafa7cb32014-03-13 06:07:04 +00001843
1844 CodeCompletionAllocator &getAllocator() override {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001845 return Next.getAllocator();
1846 }
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00001847
Craig Topperafa7cb32014-03-13 06:07:04 +00001848 CodeCompletionTUInfo &getCodeCompletionTUInfo() override {
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00001849 return Next.getCodeCompletionTUInfo();
1850 }
Douglas Gregorb14904c2010-08-13 22:48:40 +00001851 };
Hans Wennborgdcfba332015-10-06 23:40:43 +00001852} // anonymous namespace
Douglas Gregord46cf182010-08-16 20:01:48 +00001853
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001854/// \brief Helper function that computes which global names are hidden by the
1855/// local code-completion results.
Ted Kremenek6a153372010-11-07 06:11:36 +00001856static void CalculateHiddenNames(const CodeCompletionContext &Context,
1857 CodeCompletionResult *Results,
1858 unsigned NumResults,
1859 ASTContext &Ctx,
1860 llvm::StringSet<llvm::BumpPtrAllocator> &HiddenNames){
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001861 bool OnlyTagNames = false;
1862 switch (Context.getKind()) {
Douglas Gregor0ac41382010-09-23 23:01:17 +00001863 case CodeCompletionContext::CCC_Recovery:
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001864 case CodeCompletionContext::CCC_TopLevel:
1865 case CodeCompletionContext::CCC_ObjCInterface:
1866 case CodeCompletionContext::CCC_ObjCImplementation:
1867 case CodeCompletionContext::CCC_ObjCIvarList:
1868 case CodeCompletionContext::CCC_ClassStructUnion:
1869 case CodeCompletionContext::CCC_Statement:
1870 case CodeCompletionContext::CCC_Expression:
1871 case CodeCompletionContext::CCC_ObjCMessageReceiver:
Douglas Gregor21325842011-07-07 16:03:39 +00001872 case CodeCompletionContext::CCC_DotMemberAccess:
1873 case CodeCompletionContext::CCC_ArrowMemberAccess:
1874 case CodeCompletionContext::CCC_ObjCPropertyAccess:
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001875 case CodeCompletionContext::CCC_Namespace:
1876 case CodeCompletionContext::CCC_Type:
Douglas Gregorc49f5b22010-08-23 18:23:48 +00001877 case CodeCompletionContext::CCC_Name:
1878 case CodeCompletionContext::CCC_PotentiallyQualifiedName:
Douglas Gregor5e35d592010-09-14 23:59:36 +00001879 case CodeCompletionContext::CCC_ParenthesizedExpression:
Douglas Gregor2c595ad2011-07-30 06:55:39 +00001880 case CodeCompletionContext::CCC_ObjCInterfaceName:
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001881 break;
1882
1883 case CodeCompletionContext::CCC_EnumTag:
1884 case CodeCompletionContext::CCC_UnionTag:
1885 case CodeCompletionContext::CCC_ClassOrStructTag:
1886 OnlyTagNames = true;
1887 break;
1888
1889 case CodeCompletionContext::CCC_ObjCProtocolName:
Douglas Gregor12785102010-08-24 20:21:13 +00001890 case CodeCompletionContext::CCC_MacroName:
1891 case CodeCompletionContext::CCC_MacroNameUse:
Douglas Gregorec00a262010-08-24 22:20:20 +00001892 case CodeCompletionContext::CCC_PreprocessorExpression:
Douglas Gregor0de55ce2010-08-25 18:41:16 +00001893 case CodeCompletionContext::CCC_PreprocessorDirective:
Douglas Gregorea147052010-08-25 18:04:30 +00001894 case CodeCompletionContext::CCC_NaturalLanguage:
Douglas Gregor67c692c2010-08-26 15:07:07 +00001895 case CodeCompletionContext::CCC_SelectorName:
Douglas Gregor28c78432010-08-27 17:35:51 +00001896 case CodeCompletionContext::CCC_TypeQualifiers:
Douglas Gregor0ac41382010-09-23 23:01:17 +00001897 case CodeCompletionContext::CCC_Other:
Douglas Gregor3a69eaf2011-02-18 23:30:37 +00001898 case CodeCompletionContext::CCC_OtherWithMacros:
Douglas Gregor21325842011-07-07 16:03:39 +00001899 case CodeCompletionContext::CCC_ObjCInstanceMessage:
1900 case CodeCompletionContext::CCC_ObjCClassMessage:
1901 case CodeCompletionContext::CCC_ObjCCategoryName:
Douglas Gregor0de55ce2010-08-25 18:41:16 +00001902 // We're looking for nothing, or we're looking for names that cannot
1903 // be hidden.
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001904 return;
1905 }
1906
John McCall276321a2010-08-25 06:19:51 +00001907 typedef CodeCompletionResult Result;
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001908 for (unsigned I = 0; I != NumResults; ++I) {
1909 if (Results[I].Kind != Result::RK_Declaration)
1910 continue;
1911
1912 unsigned IDNS
1913 = Results[I].Declaration->getUnderlyingDecl()->getIdentifierNamespace();
1914
1915 bool Hiding = false;
1916 if (OnlyTagNames)
1917 Hiding = (IDNS & Decl::IDNS_Tag);
1918 else {
1919 unsigned HiddenIDNS = (Decl::IDNS_Type | Decl::IDNS_Member |
Douglas Gregor59cab552010-08-16 23:05:20 +00001920 Decl::IDNS_Namespace | Decl::IDNS_Ordinary |
1921 Decl::IDNS_NonMemberOperator);
David Blaikiebbafb8a2012-03-11 07:00:24 +00001922 if (Ctx.getLangOpts().CPlusPlus)
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001923 HiddenIDNS |= Decl::IDNS_Tag;
1924 Hiding = (IDNS & HiddenIDNS);
1925 }
1926
1927 if (!Hiding)
1928 continue;
1929
1930 DeclarationName Name = Results[I].Declaration->getDeclName();
1931 if (IdentifierInfo *Identifier = Name.getAsIdentifierInfo())
1932 HiddenNames.insert(Identifier->getName());
1933 else
1934 HiddenNames.insert(Name.getAsString());
1935 }
1936}
1937
Douglas Gregord46cf182010-08-16 20:01:48 +00001938void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &S,
1939 CodeCompletionContext Context,
John McCall276321a2010-08-25 06:19:51 +00001940 CodeCompletionResult *Results,
Douglas Gregord46cf182010-08-16 20:01:48 +00001941 unsigned NumResults) {
1942 // Merge the results we were given with the results we cached.
1943 bool AddedResult = false;
Richard Smith697cc9e2012-08-14 03:13:00 +00001944 uint64_t InContexts =
1945 Context.getKind() == CodeCompletionContext::CCC_Recovery
1946 ? NormalContexts : (1LL << Context.getKind());
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001947 // Contains the set of names that are hidden by "local" completion results.
Ted Kremenek6a153372010-11-07 06:11:36 +00001948 llvm::StringSet<llvm::BumpPtrAllocator> HiddenNames;
John McCall276321a2010-08-25 06:19:51 +00001949 typedef CodeCompletionResult Result;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001950 SmallVector<Result, 8> AllResults;
Douglas Gregord46cf182010-08-16 20:01:48 +00001951 for (ASTUnit::cached_completion_iterator
Douglas Gregordf239672010-08-16 21:23:13 +00001952 C = AST.cached_completion_begin(),
1953 CEnd = AST.cached_completion_end();
Douglas Gregord46cf182010-08-16 20:01:48 +00001954 C != CEnd; ++C) {
1955 // If the context we are in matches any of the contexts we are
1956 // interested in, we'll add this result.
1957 if ((C->ShowInContexts & InContexts) == 0)
1958 continue;
1959
1960 // If we haven't added any results previously, do so now.
1961 if (!AddedResult) {
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001962 CalculateHiddenNames(Context, Results, NumResults, S.Context,
1963 HiddenNames);
Douglas Gregord46cf182010-08-16 20:01:48 +00001964 AllResults.insert(AllResults.end(), Results, Results + NumResults);
1965 AddedResult = true;
1966 }
1967
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001968 // Determine whether this global completion result is hidden by a local
1969 // completion result. If so, skip it.
1970 if (C->Kind != CXCursor_MacroDefinition &&
1971 HiddenNames.count(C->Completion->getTypedText()))
1972 continue;
1973
Douglas Gregord46cf182010-08-16 20:01:48 +00001974 // Adjust priority based on similar type classes.
1975 unsigned Priority = C->Priority;
Douglas Gregor12785102010-08-24 20:21:13 +00001976 CodeCompletionString *Completion = C->Completion;
Douglas Gregord46cf182010-08-16 20:01:48 +00001977 if (!Context.getPreferredType().isNull()) {
1978 if (C->Kind == CXCursor_MacroDefinition) {
1979 Priority = getMacroUsagePriority(C->Completion->getTypedText(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00001980 S.getLangOpts(),
Douglas Gregor12785102010-08-24 20:21:13 +00001981 Context.getPreferredType()->isAnyPointerType());
Douglas Gregord46cf182010-08-16 20:01:48 +00001982 } else if (C->Type) {
1983 CanQualType Expected
Douglas Gregordf239672010-08-16 21:23:13 +00001984 = S.Context.getCanonicalType(
Douglas Gregord46cf182010-08-16 20:01:48 +00001985 Context.getPreferredType().getUnqualifiedType());
1986 SimplifiedTypeClass ExpectedSTC = getSimplifiedTypeClass(Expected);
1987 if (ExpectedSTC == C->TypeClass) {
1988 // We know this type is similar; check for an exact match.
1989 llvm::StringMap<unsigned> &CachedCompletionTypes
Douglas Gregordf239672010-08-16 21:23:13 +00001990 = AST.getCachedCompletionTypes();
Douglas Gregord46cf182010-08-16 20:01:48 +00001991 llvm::StringMap<unsigned>::iterator Pos
Douglas Gregordf239672010-08-16 21:23:13 +00001992 = CachedCompletionTypes.find(QualType(Expected).getAsString());
Douglas Gregord46cf182010-08-16 20:01:48 +00001993 if (Pos != CachedCompletionTypes.end() && Pos->second == C->Type)
1994 Priority /= CCF_ExactTypeMatch;
1995 else
1996 Priority /= CCF_SimilarTypeMatch;
1997 }
1998 }
1999 }
2000
Douglas Gregor12785102010-08-24 20:21:13 +00002001 // Adjust the completion string, if required.
2002 if (C->Kind == CXCursor_MacroDefinition &&
2003 Context.getKind() == CodeCompletionContext::CCC_MacroNameUse) {
2004 // Create a new code-completion string that just contains the
2005 // macro name, without its arguments.
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00002006 CodeCompletionBuilder Builder(getAllocator(), getCodeCompletionTUInfo(),
2007 CCP_CodePattern, C->Availability);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002008 Builder.AddTypedTextChunk(C->Completion->getTypedText());
Douglas Gregor8850aa32010-08-25 18:03:13 +00002009 Priority = CCP_CodePattern;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002010 Completion = Builder.TakeString();
Douglas Gregor12785102010-08-24 20:21:13 +00002011 }
2012
Argyrios Kyrtzidis5c8b1cd2012-09-27 00:24:09 +00002013 AllResults.push_back(Result(Completion, Priority, C->Kind,
Douglas Gregorf757a122010-08-23 23:00:57 +00002014 C->Availability));
Douglas Gregord46cf182010-08-16 20:01:48 +00002015 }
2016
2017 // If we did not add any cached completion results, just forward the
2018 // results we were given to the next consumer.
2019 if (!AddedResult) {
2020 Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
2021 return;
2022 }
Douglas Gregor49f67ce2010-08-26 13:48:20 +00002023
Douglas Gregord46cf182010-08-16 20:01:48 +00002024 Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
2025 AllResults.size());
2026}
2027
Adrian Prantlbb165fb2015-06-20 18:53:08 +00002028void ASTUnit::CodeComplete(
2029 StringRef File, unsigned Line, unsigned Column,
2030 ArrayRef<RemappedFile> RemappedFiles, bool IncludeMacros,
2031 bool IncludeCodePatterns, bool IncludeBriefComments,
2032 CodeCompleteConsumer &Consumer,
2033 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
2034 DiagnosticsEngine &Diag, LangOptions &LangOpts, SourceManager &SourceMgr,
2035 FileManager &FileMgr, SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
2036 SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers) {
Ted Kremenek5e14d392011-03-21 18:40:17 +00002037 if (!Invocation)
Douglas Gregor8e984da2010-08-04 16:47:14 +00002038 return;
2039
Douglas Gregor16896c42010-10-28 15:44:59 +00002040 SimpleTimer CompletionTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00002041 CompletionTimer.setOutput("Code completion @ " + File + ":" +
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002042 Twine(Line) + ":" + Twine(Column));
Douglas Gregor028d3e42010-08-09 20:45:32 +00002043
David Blaikieea4395e2017-01-06 19:49:01 +00002044 auto CCInvocation = std::make_shared<CompilerInvocation>(*Invocation);
Ted Kremenek5e14d392011-03-21 18:40:17 +00002045
2046 FrontendOptions &FrontendOpts = CCInvocation->getFrontendOpts();
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002047 CodeCompleteOptions &CodeCompleteOpts = FrontendOpts.CodeCompleteOpts;
Ted Kremenek5e14d392011-03-21 18:40:17 +00002048 PreprocessorOptions &PreprocessorOpts = CCInvocation->getPreprocessorOpts();
Douglas Gregorb68bc592010-08-05 09:09:23 +00002049
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002050 CodeCompleteOpts.IncludeMacros = IncludeMacros &&
2051 CachedCompletionResults.empty();
2052 CodeCompleteOpts.IncludeCodePatterns = IncludeCodePatterns;
2053 CodeCompleteOpts.IncludeGlobals = CachedCompletionResults.empty();
2054 CodeCompleteOpts.IncludeBriefComments = IncludeBriefComments;
2055
2056 assert(IncludeBriefComments == this->IncludeBriefCommentsInCodeCompletion);
2057
Douglas Gregor8e984da2010-08-04 16:47:14 +00002058 FrontendOpts.CodeCompletionAt.FileName = File;
2059 FrontendOpts.CodeCompletionAt.Line = Line;
2060 FrontendOpts.CodeCompletionAt.Column = Column;
2061
2062 // Set the language options appropriately.
Ted Kremenek8cf47df2011-11-17 23:01:24 +00002063 LangOpts = *CCInvocation->getLangOpts();
Douglas Gregor8e984da2010-08-04 16:47:14 +00002064
Argyrios Kyrtzidis06e8d692014-10-31 16:44:32 +00002065 // Spell-checking and warnings are wasteful during code-completion.
2066 LangOpts.SpellChecking = false;
2067 CCInvocation->getDiagnosticOpts().IgnoreWarnings = true;
2068
Adrian Prantlbb165fb2015-06-20 18:53:08 +00002069 std::unique_ptr<CompilerInstance> Clang(
2070 new CompilerInstance(PCHContainerOps));
Ted Kremenek84de4a12011-03-21 18:40:07 +00002071
2072 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00002073 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
2074 CICleanup(Clang.get());
Ted Kremenek84de4a12011-03-21 18:40:07 +00002075
David Blaikieea4395e2017-01-06 19:49:01 +00002076 auto &Inv = *CCInvocation;
2077 Clang->setInvocation(std::move(CCInvocation));
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00002078 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
Douglas Gregor8e984da2010-08-04 16:47:14 +00002079
2080 // Set up diagnostics, capturing any diagnostics produced.
Ted Kremenek84de4a12011-03-21 18:40:07 +00002081 Clang->setDiagnostics(&Diag);
Douglas Gregor8e984da2010-08-04 16:47:14 +00002082 CaptureDroppedDiagnostics Capture(true,
Ted Kremenek84de4a12011-03-21 18:40:07 +00002083 Clang->getDiagnostics(),
Ilya Biryukov200b3282017-06-21 10:24:58 +00002084 &StoredDiagnostics, nullptr);
David Blaikieea4395e2017-01-06 19:49:01 +00002085 ProcessWarningOptions(Diag, Inv.getDiagnosticOpts());
2086
Douglas Gregor8e984da2010-08-04 16:47:14 +00002087 // Create the target instance.
Alp Toker80758082014-07-06 05:26:44 +00002088 Clang->setTarget(TargetInfo::CreateTargetInfo(
Saleem Abdulrasool10a49722016-04-08 16:52:00 +00002089 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
Ted Kremenek84de4a12011-03-21 18:40:07 +00002090 if (!Clang->hasTarget()) {
Craig Topper49a27902014-05-22 04:46:25 +00002091 Clang->setInvocation(nullptr);
Douglas Gregor2dd19f12010-08-18 22:29:43 +00002092 return;
Douglas Gregor8e984da2010-08-04 16:47:14 +00002093 }
2094
2095 // Inform the target of the language options.
2096 //
2097 // FIXME: We shouldn't need to do this, the target should be immutable once
2098 // created. This complexity should be lifted elsewhere.
Alp Toker74437972014-07-06 05:14:24 +00002099 Clang->getTarget().adjust(Clang->getLangOpts());
Douglas Gregor8e984da2010-08-04 16:47:14 +00002100
Ted Kremenek84de4a12011-03-21 18:40:07 +00002101 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Douglas Gregor8e984da2010-08-04 16:47:14 +00002102 "Invocation must have exactly one source file!");
Richard Smith40c0efa2017-04-26 18:57:40 +00002103 assert(Clang->getFrontendOpts().Inputs[0].getKind().getFormat() ==
2104 InputKind::Source &&
Douglas Gregor8e984da2010-08-04 16:47:14 +00002105 "FIXME: AST inputs not yet supported here!");
Richard Smith40c0efa2017-04-26 18:57:40 +00002106 assert(Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() !=
2107 InputKind::LLVM_IR &&
Douglas Gregor8e984da2010-08-04 16:47:14 +00002108 "IR inputs not support here!");
Douglas Gregor8e984da2010-08-04 16:47:14 +00002109
2110 // Use the source and file managers that we were given.
Ted Kremenek84de4a12011-03-21 18:40:07 +00002111 Clang->setFileManager(&FileMgr);
2112 Clang->setSourceManager(&SourceMgr);
Douglas Gregor8e984da2010-08-04 16:47:14 +00002113
2114 // Remap files.
2115 PreprocessorOpts.clearRemappedFiles();
Douglas Gregord8a5dba2010-08-04 17:07:00 +00002116 PreprocessorOpts.RetainRemappedFileBuffers = true;
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00002117 for (const auto &RemappedFile : RemappedFiles) {
2118 PreprocessorOpts.addRemappedFile(RemappedFile.first, RemappedFile.second);
2119 OwnedBuffers.push_back(RemappedFile.second);
Douglas Gregorb97b6662010-08-20 00:59:43 +00002120 }
Dmitri Gribenkoc444b572014-02-08 00:38:15 +00002121
Douglas Gregorb14904c2010-08-13 22:48:40 +00002122 // Use the code completion consumer we were given, but adding any cached
2123 // code-completion results.
Douglas Gregore9186e62010-11-29 16:13:56 +00002124 AugmentedCodeCompleteConsumer *AugmentedConsumer
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002125 = new AugmentedCodeCompleteConsumer(*this, Consumer, CodeCompleteOpts);
Ted Kremenek84de4a12011-03-21 18:40:07 +00002126 Clang->setCodeCompletionConsumer(AugmentedConsumer);
Douglas Gregor8e984da2010-08-04 16:47:14 +00002127
Douglas Gregor028d3e42010-08-09 20:45:32 +00002128 // If we have a precompiled preamble, try to use it. We only allow
2129 // the use of the precompiled preamble if we're if the completion
2130 // point is within the main file, after the end of the precompiled
2131 // preamble.
Rafael Espindola2346a372014-08-18 18:47:08 +00002132 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
Ilya Biryukov200b3282017-06-21 10:24:58 +00002133 if (Preamble) {
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00002134 std::string CompleteFilePath(File);
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00002135
Ilya Biryukovaf69e402017-05-23 11:37:52 +00002136 auto VFS = FileMgr.getVirtualFileSystem();
2137 auto CompleteFileStatus = VFS->status(CompleteFilePath);
2138 if (CompleteFileStatus) {
2139 llvm::sys::fs::UniqueID CompleteFileID = CompleteFileStatus->getUniqueID();
2140
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00002141 std::string MainPath(OriginalSourceFile);
Ilya Biryukovaf69e402017-05-23 11:37:52 +00002142 auto MainStatus = VFS->status(MainPath);
2143 if (MainStatus) {
2144 llvm::sys::fs::UniqueID MainID = MainStatus->getUniqueID();
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00002145 if (CompleteFileID == MainID && Line > 1)
Rafael Espindola2346a372014-08-18 18:47:08 +00002146 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(
Ilya Biryukovaf69e402017-05-23 11:37:52 +00002147 PCHContainerOps, Inv, VFS, false, Line - 1);
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00002148 }
2149 }
Douglas Gregor028d3e42010-08-09 20:45:32 +00002150 }
2151
2152 // If the main file has been overridden due to the use of a preamble,
2153 // make that override happen and introduce the preamble.
2154 if (OverrideMainBuffer) {
Ilya Biryukov200b3282017-06-21 10:24:58 +00002155 assert(Preamble && "No preamble was built, but OverrideMainBuffer is not null");
2156 Preamble->AddImplicitPreamble(Clang->getInvocation(), OverrideMainBuffer.get());
Rafael Espindola2346a372014-08-18 18:47:08 +00002157 OwnedBuffers.push_back(OverrideMainBuffer.release());
Douglas Gregor7b02b582010-08-20 00:02:33 +00002158 } else {
2159 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
2160 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregor028d3e42010-08-09 20:45:32 +00002161 }
2162
Argyrios Kyrtzidis870704f2012-11-02 22:18:44 +00002163 // Disable the preprocessing record if modules are not enabled.
2164 if (!Clang->getLangOpts().Modules)
2165 PreprocessorOpts.DetailedRecord = false;
Ahmed Charlesb8984322014-03-07 20:03:18 +00002166
2167 std::unique_ptr<SyntaxOnlyAction> Act;
Douglas Gregor8e984da2010-08-04 16:47:14 +00002168 Act.reset(new SyntaxOnlyAction);
Douglas Gregor32fbe312012-01-20 16:28:04 +00002169 if (Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
Douglas Gregor8e984da2010-08-04 16:47:14 +00002170 Act->Execute();
2171 Act->EndSourceFile();
2172 }
Douglas Gregor8e984da2010-08-04 16:47:14 +00002173}
Douglas Gregore9386682010-08-13 05:36:37 +00002174
Argyrios Kyrtzidis39a76382012-09-26 16:39:46 +00002175bool ASTUnit::Save(StringRef File) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00002176 if (HadModuleLoaderFatalFailure)
2177 return true;
2178
Argyrios Kyrtzidis55e75572011-07-21 18:44:49 +00002179 // Write to a temporary file and later rename it to the actual file, to avoid
2180 // possible race conditions.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00002181 SmallString<128> TempPath;
Argyrios Kyrtzidis08a2bfd2011-07-28 00:45:10 +00002182 TempPath = File;
2183 TempPath += "-%%%%%%%%";
2184 int fd;
Yaron Keren92e1b622015-03-18 10:17:07 +00002185 if (llvm::sys::fs::createUniqueFile(TempPath, fd, TempPath))
Argyrios Kyrtzidis39a76382012-09-26 16:39:46 +00002186 return true;
Argyrios Kyrtzidis55e75572011-07-21 18:44:49 +00002187
Douglas Gregore9386682010-08-13 05:36:37 +00002188 // FIXME: Can we somehow regenerate the stat cache here, or do we need to
2189 // unconditionally create a stat cache when we parse the file?
Argyrios Kyrtzidis08a2bfd2011-07-28 00:45:10 +00002190 llvm::raw_fd_ostream Out(fd, /*shouldClose=*/true);
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00002191
2192 serialize(Out);
2193 Out.close();
Argyrios Kyrtzidiseeea16a2012-03-13 02:17:06 +00002194 if (Out.has_error()) {
2195 Out.clear_error();
Argyrios Kyrtzidis39a76382012-09-26 16:39:46 +00002196 return true;
Argyrios Kyrtzidiseeea16a2012-03-13 02:17:06 +00002197 }
Argyrios Kyrtzidis55e75572011-07-21 18:44:49 +00002198
Yaron Keren92e1b622015-03-18 10:17:07 +00002199 if (llvm::sys::fs::rename(TempPath, File)) {
2200 llvm::sys::fs::remove(TempPath);
Argyrios Kyrtzidis39a76382012-09-26 16:39:46 +00002201 return true;
Argyrios Kyrtzidis55e75572011-07-21 18:44:49 +00002202 }
2203
Argyrios Kyrtzidis39a76382012-09-26 16:39:46 +00002204 return false;
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00002205}
2206
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00002207static bool serializeUnit(ASTWriter &Writer,
2208 SmallVectorImpl<char> &Buffer,
2209 Sema &S,
2210 bool hasErrors,
2211 raw_ostream &OS) {
Craig Topper49a27902014-05-22 04:46:25 +00002212 Writer.WriteAST(S, std::string(), nullptr, "", hasErrors);
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00002213
2214 // Write the generated bitstream to "Out".
2215 if (!Buffer.empty())
2216 OS.write(Buffer.data(), Buffer.size());
2217
2218 return false;
2219}
2220
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002221bool ASTUnit::serialize(raw_ostream &OS) {
Argyrios Kyrtzidis70ec1c72016-07-13 20:35:26 +00002222 // For serialization we are lenient if the errors were only warn-as-error kind.
2223 bool hasErrors = getDiagnostics().hasUncompilableErrorOccurred();
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00002224
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00002225 if (WriterData)
2226 return serializeUnit(WriterData->Writer, WriterData->Buffer,
2227 getSema(), hasErrors, OS);
2228
Daniel Dunbar9a963862012-02-29 20:31:23 +00002229 SmallString<128> Buffer;
Douglas Gregore9386682010-08-13 05:36:37 +00002230 llvm::BitstreamWriter Stream(Buffer);
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00002231 MemoryBufferCache PCMCache;
2232 ASTWriter Writer(Stream, Buffer, PCMCache, {});
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00002233 return serializeUnit(Writer, Buffer, getSema(), hasErrors, OS);
Douglas Gregore9386682010-08-13 05:36:37 +00002234}
Douglas Gregor925296b2011-07-19 16:10:42 +00002235
2236typedef ContinuousRangeMap<unsigned, int, 2> SLocRemap;
2237
Douglas Gregor925296b2011-07-19 16:10:42 +00002238void ASTUnit::TranslateStoredDiagnostics(
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002239 FileManager &FileMgr,
Douglas Gregor925296b2011-07-19 16:10:42 +00002240 SourceManager &SrcMgr,
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002241 const SmallVectorImpl<StandaloneDiagnostic> &Diags,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002242 SmallVectorImpl<StoredDiagnostic> &Out) {
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002243 // Map the standalone diagnostic into the new source manager. We also need to
2244 // remap all the locations to the new view. This includes the diag location,
2245 // any associated source ranges, and the source ranges of associated fix-its.
Douglas Gregor925296b2011-07-19 16:10:42 +00002246 // FIXME: There should be a cleaner way to do this.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002247 SmallVector<StoredDiagnostic, 4> Result;
Douglas Gregor925296b2011-07-19 16:10:42 +00002248 Result.reserve(Diags.size());
Erik Verbruggenefe6fa52017-06-09 08:29:58 +00002249
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00002250 for (const StandaloneDiagnostic &SD : Diags) {
Douglas Gregor925296b2011-07-19 16:10:42 +00002251 // Rebuild the StoredDiagnostic.
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002252 if (SD.Filename.empty())
2253 continue;
2254 const FileEntry *FE = FileMgr.getFile(SD.Filename);
2255 if (!FE)
2256 continue;
Erik Verbruggenefe6fa52017-06-09 08:29:58 +00002257 SourceLocation FileLoc;
2258 auto ItFileID = PreambleSrcLocCache.find(SD.Filename);
2259 if (ItFileID == PreambleSrcLocCache.end()) {
2260 FileID FID = SrcMgr.translateFile(FE);
2261 FileLoc = SrcMgr.getLocForStartOfFile(FID);
2262 PreambleSrcLocCache[SD.Filename] = FileLoc;
2263 } else {
2264 FileLoc = ItFileID->getValue();
Erik Verbruggen2c7c38d2017-02-16 09:49:30 +00002265 }
Erik Verbruggenefe6fa52017-06-09 08:29:58 +00002266
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002267 if (FileLoc.isInvalid())
2268 continue;
2269 SourceLocation L = FileLoc.getLocWithOffset(SD.LocOffset);
Douglas Gregor925296b2011-07-19 16:10:42 +00002270 FullSourceLoc Loc(L, SrcMgr);
2271
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002272 SmallVector<CharSourceRange, 4> Ranges;
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002273 Ranges.reserve(SD.Ranges.size());
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00002274 for (const auto &Range : SD.Ranges) {
2275 SourceLocation BL = FileLoc.getLocWithOffset(Range.first);
2276 SourceLocation EL = FileLoc.getLocWithOffset(Range.second);
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002277 Ranges.push_back(CharSourceRange::getCharRange(BL, EL));
Douglas Gregor925296b2011-07-19 16:10:42 +00002278 }
2279
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002280 SmallVector<FixItHint, 2> FixIts;
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002281 FixIts.reserve(SD.FixIts.size());
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00002282 for (const StandaloneFixIt &FixIt : SD.FixIts) {
Douglas Gregor925296b2011-07-19 16:10:42 +00002283 FixIts.push_back(FixItHint());
2284 FixItHint &FH = FixIts.back();
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00002285 FH.CodeToInsert = FixIt.CodeToInsert;
2286 SourceLocation BL = FileLoc.getLocWithOffset(FixIt.RemoveRange.first);
2287 SourceLocation EL = FileLoc.getLocWithOffset(FixIt.RemoveRange.second);
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002288 FH.RemoveRange = CharSourceRange::getCharRange(BL, EL);
Douglas Gregor925296b2011-07-19 16:10:42 +00002289 }
2290
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002291 Result.push_back(StoredDiagnostic(SD.Level, SD.ID,
2292 SD.Message, Loc, Ranges, FixIts));
Douglas Gregor925296b2011-07-19 16:10:42 +00002293 }
2294 Result.swap(Out);
2295}
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002296
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00002297void ASTUnit::addFileLevelDecl(Decl *D) {
2298 assert(D);
Douglas Gregor61d63d02011-11-07 18:53:57 +00002299
2300 // We only care about local declarations.
2301 if (D->isFromASTFile())
2302 return;
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00002303
2304 SourceManager &SM = *SourceMgr;
2305 SourceLocation Loc = D->getLocation();
2306 if (Loc.isInvalid() || !SM.isLocalSourceLocation(Loc))
2307 return;
2308
2309 // We only keep track of the file-level declarations of each file.
2310 if (!D->getLexicalDeclContext()->isFileContext())
2311 return;
2312
2313 SourceLocation FileLoc = SM.getFileLoc(Loc);
2314 assert(SM.isLocalSourceLocation(FileLoc));
2315 FileID FID;
2316 unsigned Offset;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002317 std::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc);
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00002318 if (FID.isInvalid())
2319 return;
2320
2321 LocDeclsTy *&Decls = FileDecls[FID];
2322 if (!Decls)
2323 Decls = new LocDeclsTy();
2324
2325 std::pair<unsigned, Decl *> LocDecl(Offset, D);
2326
2327 if (Decls->empty() || Decls->back().first <= Offset) {
2328 Decls->push_back(LocDecl);
2329 return;
2330 }
2331
Benjamin Kramer45025c02013-08-24 13:22:59 +00002332 LocDeclsTy::iterator I = std::upper_bound(Decls->begin(), Decls->end(),
2333 LocDecl, llvm::less_first());
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00002334
2335 Decls->insert(I, LocDecl);
2336}
2337
Argyrios Kyrtzidise9681522011-11-03 02:20:32 +00002338void ASTUnit::findFileRegionDecls(FileID File, unsigned Offset, unsigned Length,
2339 SmallVectorImpl<Decl *> &Decls) {
2340 if (File.isInvalid())
2341 return;
2342
2343 if (SourceMgr->isLoadedFileID(File)) {
2344 assert(Ctx->getExternalSource() && "No external source!");
2345 return Ctx->getExternalSource()->FindFileRegionDecls(File, Offset, Length,
2346 Decls);
2347 }
2348
2349 FileDeclsTy::iterator I = FileDecls.find(File);
2350 if (I == FileDecls.end())
2351 return;
2352
2353 LocDeclsTy &LocDecls = *I->second;
2354 if (LocDecls.empty())
2355 return;
2356
Benjamin Kramere3e855b2013-08-24 13:12:34 +00002357 LocDeclsTy::iterator BeginIt =
2358 std::lower_bound(LocDecls.begin(), LocDecls.end(),
Craig Topper49a27902014-05-22 04:46:25 +00002359 std::make_pair(Offset, (Decl *)nullptr),
2360 llvm::less_first());
Argyrios Kyrtzidise9681522011-11-03 02:20:32 +00002361 if (BeginIt != LocDecls.begin())
2362 --BeginIt;
2363
Argyrios Kyrtzidis8ad3bab2011-11-23 20:27:36 +00002364 // If we are pointing at a top-level decl inside an objc container, we need
2365 // to backtrack until we find it otherwise we will fail to report that the
2366 // region overlaps with an objc container.
2367 while (BeginIt != LocDecls.begin() &&
2368 BeginIt->second->isTopLevelDeclInObjCContainer())
2369 --BeginIt;
2370
Benjamin Kramere3e855b2013-08-24 13:12:34 +00002371 LocDeclsTy::iterator EndIt = std::upper_bound(
2372 LocDecls.begin(), LocDecls.end(),
Craig Topper49a27902014-05-22 04:46:25 +00002373 std::make_pair(Offset + Length, (Decl *)nullptr), llvm::less_first());
Argyrios Kyrtzidise9681522011-11-03 02:20:32 +00002374 if (EndIt != LocDecls.end())
2375 ++EndIt;
2376
2377 for (LocDeclsTy::iterator DIt = BeginIt; DIt != EndIt; ++DIt)
2378 Decls.push_back(DIt->second);
2379}
2380
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002381SourceLocation ASTUnit::getLocation(const FileEntry *File,
2382 unsigned Line, unsigned Col) const {
2383 const SourceManager &SM = getSourceManager();
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00002384 SourceLocation Loc = SM.translateFileLineCol(File, Line, Col);
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002385 return SM.getMacroArgExpandedLocation(Loc);
2386}
2387
2388SourceLocation ASTUnit::getLocation(const FileEntry *File,
2389 unsigned Offset) const {
2390 const SourceManager &SM = getSourceManager();
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00002391 SourceLocation FileLoc = SM.translateFileLineCol(File, 1, 1);
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002392 return SM.getMacroArgExpandedLocation(FileLoc.getLocWithOffset(Offset));
2393}
2394
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00002395/// \brief If \arg Loc is a loaded location from the preamble, returns
2396/// the corresponding local location of the main file, otherwise it returns
2397/// \arg Loc.
2398SourceLocation ASTUnit::mapLocationFromPreamble(SourceLocation Loc) {
2399 FileID PreambleID;
2400 if (SourceMgr)
2401 PreambleID = SourceMgr->getPreambleFileID();
2402
Ilya Biryukov200b3282017-06-21 10:24:58 +00002403 if (Loc.isInvalid() || !Preamble || PreambleID.isInvalid())
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00002404 return Loc;
2405
2406 unsigned Offs;
Ilya Biryukov200b3282017-06-21 10:24:58 +00002407 if (SourceMgr->isInFileID(Loc, PreambleID, &Offs) && Offs < Preamble->getBounds().Size) {
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00002408 SourceLocation FileLoc
2409 = SourceMgr->getLocForStartOfFile(SourceMgr->getMainFileID());
2410 return FileLoc.getLocWithOffset(Offs);
2411 }
2412
2413 return Loc;
2414}
2415
2416/// \brief If \arg Loc is a local location of the main file but inside the
2417/// preamble chunk, returns the corresponding loaded location from the
2418/// preamble, otherwise it returns \arg Loc.
2419SourceLocation ASTUnit::mapLocationToPreamble(SourceLocation Loc) {
2420 FileID PreambleID;
2421 if (SourceMgr)
2422 PreambleID = SourceMgr->getPreambleFileID();
2423
Ilya Biryukov200b3282017-06-21 10:24:58 +00002424 if (Loc.isInvalid() || !Preamble || PreambleID.isInvalid())
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00002425 return Loc;
2426
2427 unsigned Offs;
2428 if (SourceMgr->isInFileID(Loc, SourceMgr->getMainFileID(), &Offs) &&
Ilya Biryukov200b3282017-06-21 10:24:58 +00002429 Offs < Preamble->getBounds().Size) {
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00002430 SourceLocation FileLoc = SourceMgr->getLocForStartOfFile(PreambleID);
2431 return FileLoc.getLocWithOffset(Offs);
2432 }
2433
2434 return Loc;
2435}
2436
Argyrios Kyrtzidis429ec022011-10-25 00:29:50 +00002437bool ASTUnit::isInPreambleFileID(SourceLocation Loc) {
2438 FileID FID;
2439 if (SourceMgr)
2440 FID = SourceMgr->getPreambleFileID();
2441
2442 if (Loc.isInvalid() || FID.isInvalid())
2443 return false;
2444
2445 return SourceMgr->isInFileID(Loc, FID);
2446}
2447
2448bool ASTUnit::isInMainFileID(SourceLocation Loc) {
2449 FileID FID;
2450 if (SourceMgr)
2451 FID = SourceMgr->getMainFileID();
2452
2453 if (Loc.isInvalid() || FID.isInvalid())
2454 return false;
2455
2456 return SourceMgr->isInFileID(Loc, FID);
2457}
2458
2459SourceLocation ASTUnit::getEndOfPreambleFileID() {
2460 FileID FID;
2461 if (SourceMgr)
2462 FID = SourceMgr->getPreambleFileID();
2463
2464 if (FID.isInvalid())
2465 return SourceLocation();
2466
2467 return SourceMgr->getLocForEndOfFile(FID);
2468}
2469
2470SourceLocation ASTUnit::getStartOfMainFileID() {
2471 FileID FID;
2472 if (SourceMgr)
2473 FID = SourceMgr->getMainFileID();
2474
2475 if (FID.isInvalid())
2476 return SourceLocation();
2477
2478 return SourceMgr->getLocForStartOfFile(FID);
2479}
2480
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00002481llvm::iterator_range<PreprocessingRecord::iterator>
Argyrios Kyrtzidisd4fcf5802012-10-02 16:10:51 +00002482ASTUnit::getLocalPreprocessingEntities() const {
2483 if (isMainFileAST()) {
2484 serialization::ModuleFile &
2485 Mod = Reader->getModuleManager().getPrimaryModule();
2486 return Reader->getModulePreprocessedEntities(Mod);
2487 }
2488
2489 if (PreprocessingRecord *PPRec = PP->getPreprocessingRecord())
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00002490 return llvm::make_range(PPRec->local_begin(), PPRec->local_end());
Argyrios Kyrtzidisd4fcf5802012-10-02 16:10:51 +00002491
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00002492 return llvm::make_range(PreprocessingRecord::iterator(),
2493 PreprocessingRecord::iterator());
Argyrios Kyrtzidisd4fcf5802012-10-02 16:10:51 +00002494}
2495
Argyrios Kyrtzidise514b202012-10-03 01:58:28 +00002496bool ASTUnit::visitLocalTopLevelDecls(void *context, DeclVisitorFn Fn) {
Argyrios Kyrtzidis10e78462012-10-02 21:09:13 +00002497 if (isMainFileAST()) {
2498 serialization::ModuleFile &
2499 Mod = Reader->getModuleManager().getPrimaryModule();
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00002500 for (const Decl *D : Reader->getModuleFileLevelDecls(Mod)) {
2501 if (!Fn(context, D))
Argyrios Kyrtzidis10e78462012-10-02 21:09:13 +00002502 return false;
2503 }
2504
2505 return true;
2506 }
2507
2508 for (ASTUnit::top_level_iterator TL = top_level_begin(),
2509 TLEnd = top_level_end();
2510 TL != TLEnd; ++TL) {
2511 if (!Fn(context, *TL))
2512 return false;
2513 }
2514
2515 return true;
2516}
2517
Argyrios Kyrtzidisf484b132012-10-03 21:05:51 +00002518const FileEntry *ASTUnit::getPCHFile() {
2519 if (!Reader)
Craig Topper49a27902014-05-22 04:46:25 +00002520 return nullptr;
Argyrios Kyrtzidisf484b132012-10-03 21:05:51 +00002521
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00002522 serialization::ModuleFile *Mod = nullptr;
2523 Reader->getModuleManager().visit([&Mod](serialization::ModuleFile &M) {
2524 switch (M.Kind) {
2525 case serialization::MK_ImplicitModule:
2526 case serialization::MK_ExplicitModule:
Manman Ren11f2a472016-08-18 17:42:15 +00002527 case serialization::MK_PrebuiltModule:
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00002528 return true; // skip dependencies.
2529 case serialization::MK_PCH:
2530 Mod = &M;
2531 return true; // found it.
2532 case serialization::MK_Preamble:
2533 return false; // look in dependencies.
2534 case serialization::MK_MainFile:
2535 return false; // look in dependencies.
2536 }
2537
2538 return true;
2539 });
2540 if (Mod)
2541 return Mod->File;
Argyrios Kyrtzidisf484b132012-10-03 21:05:51 +00002542
Craig Topper49a27902014-05-22 04:46:25 +00002543 return nullptr;
Argyrios Kyrtzidisf484b132012-10-03 21:05:51 +00002544}
2545
Argyrios Kyrtzidise445c722012-10-10 02:12:47 +00002546bool ASTUnit::isModuleFile() {
Richard Smithab755972017-06-05 18:10:11 +00002547 return isMainFileAST() && getLangOpts().isCompilingModule();
2548}
2549
2550InputKind ASTUnit::getInputKind() const {
2551 auto &LangOpts = getLangOpts();
2552
2553 InputKind::Language Lang;
2554 if (LangOpts.OpenCL)
2555 Lang = InputKind::OpenCL;
2556 else if (LangOpts.CUDA)
2557 Lang = InputKind::CUDA;
2558 else if (LangOpts.RenderScript)
2559 Lang = InputKind::RenderScript;
2560 else if (LangOpts.CPlusPlus)
2561 Lang = LangOpts.ObjC1 ? InputKind::ObjCXX : InputKind::CXX;
2562 else
2563 Lang = LangOpts.ObjC1 ? InputKind::ObjC : InputKind::C;
2564
2565 InputKind::Format Fmt = InputKind::Source;
2566 if (LangOpts.getCompilingModule() == LangOptions::CMK_ModuleMap)
2567 Fmt = InputKind::ModuleMap;
2568
2569 // We don't know if input was preprocessed. Assume not.
2570 bool PP = false;
2571
2572 return InputKind(Lang, Fmt, PP);
Argyrios Kyrtzidise445c722012-10-10 02:12:47 +00002573}
2574
Argyrios Kyrtzidisebf01362011-10-10 21:57:12 +00002575#ifndef NDEBUG
2576ASTUnit::ConcurrencyState::ConcurrencyState() {
2577 Mutex = new llvm::sys::MutexImpl(/*recursive=*/true);
2578}
2579
2580ASTUnit::ConcurrencyState::~ConcurrencyState() {
2581 delete static_cast<llvm::sys::MutexImpl *>(Mutex);
2582}
2583
2584void ASTUnit::ConcurrencyState::start() {
2585 bool acquired = static_cast<llvm::sys::MutexImpl *>(Mutex)->tryacquire();
2586 assert(acquired && "Concurrent access to ASTUnit!");
2587}
2588
2589void ASTUnit::ConcurrencyState::finish() {
2590 static_cast<llvm::sys::MutexImpl *>(Mutex)->release();
2591}
2592
2593#else // NDEBUG
2594
Hans Wennborgdcfba332015-10-06 23:40:43 +00002595ASTUnit::ConcurrencyState::ConcurrencyState() { Mutex = nullptr; }
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +00002596ASTUnit::ConcurrencyState::~ConcurrencyState() {}
Argyrios Kyrtzidisebf01362011-10-10 21:57:12 +00002597void ASTUnit::ConcurrencyState::start() {}
2598void ASTUnit::ConcurrencyState::finish() {}
2599
Hans Wennborgdcfba332015-10-06 23:40:43 +00002600#endif // NDEBUG