blob: 8d139f2c0a6d734337241b3b95de8464a4c39fdd [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 };
Ted Kremenek06b4f912011-10-27 17:55:18 +000082
83 struct OnDiskData {
84 /// \brief The file in which the precompiled preamble is stored.
85 std::string PreambleFile;
86
Ted Kremenek06b4f912011-10-27 17:55:18 +000087 /// \brief Erase the preamble file.
88 void CleanPreambleFile();
89
90 /// \brief Erase temporary files and the preamble file.
91 void Cleanup();
92 };
Ilya Biryukovaf69e402017-05-23 11:37:52 +000093
94 template <class T>
95 std::unique_ptr<T> valueOrNull(llvm::ErrorOr<std::unique_ptr<T>> Val) {
96 if (!Val)
97 return nullptr;
98 return std::move(*Val);
99 }
100
101 template <class T>
102 bool moveOnNoError(llvm::ErrorOr<T> Val, T &Output) {
103 if (!Val)
104 return false;
105 Output = std::move(*Val);
106 return true;
107 }
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000108}
Ted Kremenek06b4f912011-10-27 17:55:18 +0000109
Ted Kremenekbd307a52011-10-27 19:44:25 +0000110static llvm::sys::SmartMutex<false> &getOnDiskMutex() {
111 static llvm::sys::SmartMutex<false> M(/* recursive = */ true);
112 return M;
113}
114
Dmitri Gribenkob2aa9232012-11-15 14:28:07 +0000115static void cleanupOnDiskMapAtExit();
Ted Kremenek06b4f912011-10-27 17:55:18 +0000116
Dylan Noblesmithcdd31512014-08-24 18:59:52 +0000117typedef llvm::DenseMap<const ASTUnit *,
118 std::unique_ptr<OnDiskData>> OnDiskDataMap;
Ted Kremenek06b4f912011-10-27 17:55:18 +0000119static OnDiskDataMap &getOnDiskDataMap() {
120 static OnDiskDataMap M;
121 static bool hasRegisteredAtExit = false;
122 if (!hasRegisteredAtExit) {
123 hasRegisteredAtExit = true;
124 atexit(cleanupOnDiskMapAtExit);
125 }
126 return M;
127}
128
Dmitri Gribenkob2aa9232012-11-15 14:28:07 +0000129static void cleanupOnDiskMapAtExit() {
Argyrios Kyrtzidis4cf2ffe2012-07-03 16:30:52 +0000130 // Use the mutex because there can be an alive thread destroying an ASTUnit.
131 llvm::MutexGuard Guard(getOnDiskMutex());
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000132 for (const auto &I : getOnDiskDataMap()) {
Ted Kremenek06b4f912011-10-27 17:55:18 +0000133 // We don't worry about freeing the memory associated with OnDiskDataMap.
134 // All we care about is erasing stale files.
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000135 I.second->Cleanup();
Ted Kremenek06b4f912011-10-27 17:55:18 +0000136 }
137}
138
139static OnDiskData &getOnDiskData(const ASTUnit *AU) {
Ted Kremenekbd307a52011-10-27 19:44:25 +0000140 // We require the mutex since we are modifying the structure of the
141 // DenseMap.
142 llvm::MutexGuard Guard(getOnDiskMutex());
Ted Kremenek06b4f912011-10-27 17:55:18 +0000143 OnDiskDataMap &M = getOnDiskDataMap();
Dylan Noblesmithcdd31512014-08-24 18:59:52 +0000144 auto &D = M[AU];
Ted Kremenek06b4f912011-10-27 17:55:18 +0000145 if (!D)
Dylan Noblesmithcdd31512014-08-24 18:59:52 +0000146 D = llvm::make_unique<OnDiskData>();
Ted Kremenek06b4f912011-10-27 17:55:18 +0000147 return *D;
148}
149
150static void erasePreambleFile(const ASTUnit *AU) {
151 getOnDiskData(AU).CleanPreambleFile();
152}
153
154static void removeOnDiskEntry(const ASTUnit *AU) {
Ted Kremenekbd307a52011-10-27 19:44:25 +0000155 // We require the mutex since we are modifying the structure of the
156 // DenseMap.
157 llvm::MutexGuard Guard(getOnDiskMutex());
Ted Kremenek06b4f912011-10-27 17:55:18 +0000158 OnDiskDataMap &M = getOnDiskDataMap();
159 OnDiskDataMap::iterator I = M.find(AU);
160 if (I != M.end()) {
161 I->second->Cleanup();
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000162 M.erase(I);
Ted Kremenek06b4f912011-10-27 17:55:18 +0000163 }
164}
165
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000166static void setPreambleFile(const ASTUnit *AU, StringRef preambleFile) {
Ted Kremenek06b4f912011-10-27 17:55:18 +0000167 getOnDiskData(AU).PreambleFile = preambleFile;
168}
169
170static const std::string &getPreambleFile(const ASTUnit *AU) {
171 return getOnDiskData(AU).PreambleFile;
172}
173
Ted Kremenek06b4f912011-10-27 17:55:18 +0000174void OnDiskData::CleanPreambleFile() {
175 if (!PreambleFile.empty()) {
Rafael Espindolabc4aa552013-06-26 04:02:37 +0000176 llvm::sys::fs::remove(PreambleFile);
Ted Kremenek06b4f912011-10-27 17:55:18 +0000177 PreambleFile.clear();
178 }
179}
180
181void OnDiskData::Cleanup() {
Ted Kremenek06b4f912011-10-27 17:55:18 +0000182 CleanPreambleFile();
183}
184
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000185struct ASTUnit::ASTWriterData {
186 SmallString<128> Buffer;
187 llvm::BitstreamWriter Stream;
188 ASTWriter Writer;
189
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +0000190 ASTWriterData(MemoryBufferCache &PCMCache)
191 : Stream(Buffer), Writer(Stream, Buffer, PCMCache, {}) {}
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000192};
193
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000194void ASTUnit::clearFileLevelDecls() {
Reid Kleckner588c9372014-02-19 23:44:52 +0000195 llvm::DeleteContainerSeconds(FileDecls);
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000196}
197
Douglas Gregorbb420ab2010-08-04 05:53:38 +0000198/// \brief After failing to build a precompiled preamble (due to
199/// errors in the source that occurs in the preamble), the number of
200/// reparses during which we'll skip even trying to precompile the
201/// preamble.
202const unsigned DefaultPreambleRebuildInterval = 5;
203
Douglas Gregor68dbaea2010-11-17 00:13:31 +0000204/// \brief Tracks the number of ASTUnit objects that are currently active.
205///
206/// Used for debugging purposes only.
Benjamin Kramer4527fb22014-03-02 17:08:31 +0000207static std::atomic<unsigned> ActiveASTUnitObjects;
Douglas Gregor68dbaea2010-11-17 00:13:31 +0000208
Douglas Gregord03e8232010-04-05 21:10:19 +0000209ASTUnit::ASTUnit(bool _MainFileIsAST)
Craig Topper49a27902014-05-22 04:46:25 +0000210 : Reader(nullptr), HadModuleLoaderFatalFailure(false),
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +0000211 OnlyLocalDecls(false), CaptureDiagnostics(false),
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +0000212 MainFileIsAST(_MainFileIsAST),
Douglas Gregor69f74f82011-08-25 22:30:56 +0000213 TUKind(TU_Complete), WantTiming(getenv("LIBCLANG_TIMING")),
Argyrios Kyrtzidis4954bc12011-03-05 01:03:48 +0000214 OwnsRemappedFileBuffers(true),
Douglas Gregor16896c42010-10-28 15:44:59 +0000215 NumStoredDiagnosticsFromDriver(0),
Rafael Espindola4674a872014-08-13 17:08:22 +0000216 PreambleRebuildCounter(0),
Rafael Espindolafa49c0b2014-08-13 16:47:00 +0000217 NumWarningsInPreamble(0),
Douglas Gregor2c8bd472010-08-17 00:40:40 +0000218 ShouldCacheCodeCompletionResults(false),
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +0000219 IncludeBriefCommentsInCodeCompletion(false), UserFilesAreVolatile(false),
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000220 CompletionCacheTopLevelHashValue(0),
221 PreambleTopLevelHashValue(0),
222 CurrentTopLevelHashValue(0),
Douglas Gregor4740c452010-08-19 00:45:44 +0000223 UnsafeToFree(false) {
Benjamin Kramer4527fb22014-03-02 17:08:31 +0000224 if (getenv("LIBCLANG_OBJTRACKING"))
225 fprintf(stderr, "+++ %u translation units\n", ++ActiveASTUnitObjects);
Douglas Gregor15ba0b32010-07-30 20:58:08 +0000226}
Douglas Gregord03e8232010-04-05 21:10:19 +0000227
Daniel Dunbar764c0822009-12-01 09:51:01 +0000228ASTUnit::~ASTUnit() {
Douglas Gregor6b930962013-05-03 22:58:43 +0000229 // If we loaded from an AST file, balance out the BeginSourceFile call.
230 if (MainFileIsAST && getDiagnostics().getClient()) {
231 getDiagnostics().getClient()->EndSourceFile();
232 }
233
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000234 clearFileLevelDecls();
235
Ted Kremenek06b4f912011-10-27 17:55:18 +0000236 // Clean up the temporary files and the preamble file.
237 removeOnDiskEntry(this);
238
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000239 // Free the buffers associated with remapped files. We are required to
240 // perform this operation here because we explicitly request that the
241 // compiler instance *not* free these buffers for each invocation of the
242 // parser.
David Blaikieea4395e2017-01-06 19:49:01 +0000243 if (Invocation && OwnsRemappedFileBuffers) {
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000244 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
Alp Toker1b070d22014-07-07 07:47:20 +0000245 for (const auto &RB : PPOpts.RemappedFileBuffers)
246 delete RB.second;
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000247 }
Douglas Gregora0734c52010-08-19 01:33:06 +0000248
Douglas Gregor16896c42010-10-28 15:44:59 +0000249 ClearCachedCompletionResults();
Douglas Gregor68dbaea2010-11-17 00:13:31 +0000250
Benjamin Kramer4527fb22014-03-02 17:08:31 +0000251 if (getenv("LIBCLANG_OBJTRACKING"))
252 fprintf(stderr, "--- %u translation units\n", --ActiveASTUnitObjects);
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000253}
254
David Blaikie41565462017-01-05 19:48:07 +0000255void ASTUnit::setPreprocessor(std::shared_ptr<Preprocessor> PP) {
256 this->PP = std::move(PP);
257}
Argyrios Kyrtzidisda6e0542012-01-17 18:48:07 +0000258
Douglas Gregor39982192010-08-15 06:18:01 +0000259/// \brief Determine the set of code-completion contexts in which this
260/// declaration should be shown.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000261static unsigned getDeclShowContexts(const NamedDecl *ND,
Douglas Gregor59cab552010-08-16 23:05:20 +0000262 const LangOptions &LangOpts,
263 bool &IsNestedNameSpecifier) {
264 IsNestedNameSpecifier = false;
265
Douglas Gregor39982192010-08-15 06:18:01 +0000266 if (isa<UsingShadowDecl>(ND))
267 ND = dyn_cast<NamedDecl>(ND->getUnderlyingDecl());
268 if (!ND)
269 return 0;
270
Richard Smith697cc9e2012-08-14 03:13:00 +0000271 uint64_t Contexts = 0;
Douglas Gregor39982192010-08-15 06:18:01 +0000272 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND) ||
273 isa<ClassTemplateDecl>(ND) || isa<TemplateTemplateParmDecl>(ND)) {
274 // Types can appear in these contexts.
275 if (LangOpts.CPlusPlus || !isa<TagDecl>(ND))
Richard Smith697cc9e2012-08-14 03:13:00 +0000276 Contexts |= (1LL << CodeCompletionContext::CCC_TopLevel)
277 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
278 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
279 | (1LL << CodeCompletionContext::CCC_Statement)
280 | (1LL << CodeCompletionContext::CCC_Type)
281 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression);
Douglas Gregor39982192010-08-15 06:18:01 +0000282
283 // In C++, types can appear in expressions contexts (for functional casts).
284 if (LangOpts.CPlusPlus)
Richard Smith697cc9e2012-08-14 03:13:00 +0000285 Contexts |= (1LL << CodeCompletionContext::CCC_Expression);
Douglas Gregor39982192010-08-15 06:18:01 +0000286
287 // In Objective-C, message sends can send interfaces. In Objective-C++,
288 // all types are available due to functional casts.
289 if (LangOpts.CPlusPlus || isa<ObjCInterfaceDecl>(ND))
Richard Smith697cc9e2012-08-14 03:13:00 +0000290 Contexts |= (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver);
Douglas Gregor21325842011-07-07 16:03:39 +0000291
292 // In Objective-C, you can only be a subclass of another Objective-C class
293 if (isa<ObjCInterfaceDecl>(ND))
Richard Smith697cc9e2012-08-14 03:13:00 +0000294 Contexts |= (1LL << CodeCompletionContext::CCC_ObjCInterfaceName);
Douglas Gregor39982192010-08-15 06:18:01 +0000295
296 // Deal with tag names.
297 if (isa<EnumDecl>(ND)) {
Richard Smith697cc9e2012-08-14 03:13:00 +0000298 Contexts |= (1LL << CodeCompletionContext::CCC_EnumTag);
Douglas Gregor39982192010-08-15 06:18:01 +0000299
Douglas Gregor59cab552010-08-16 23:05:20 +0000300 // Part of the nested-name-specifier in C++0x.
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000301 if (LangOpts.CPlusPlus11)
Douglas Gregor59cab552010-08-16 23:05:20 +0000302 IsNestedNameSpecifier = true;
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000303 } else if (const RecordDecl *Record = dyn_cast<RecordDecl>(ND)) {
Douglas Gregor39982192010-08-15 06:18:01 +0000304 if (Record->isUnion())
Richard Smith697cc9e2012-08-14 03:13:00 +0000305 Contexts |= (1LL << CodeCompletionContext::CCC_UnionTag);
Douglas Gregor39982192010-08-15 06:18:01 +0000306 else
Richard Smith697cc9e2012-08-14 03:13:00 +0000307 Contexts |= (1LL << CodeCompletionContext::CCC_ClassOrStructTag);
Douglas Gregor39982192010-08-15 06:18:01 +0000308
Douglas Gregor39982192010-08-15 06:18:01 +0000309 if (LangOpts.CPlusPlus)
Douglas Gregor59cab552010-08-16 23:05:20 +0000310 IsNestedNameSpecifier = true;
Douglas Gregor0ac41382010-09-23 23:01:17 +0000311 } else if (isa<ClassTemplateDecl>(ND))
Douglas Gregor59cab552010-08-16 23:05:20 +0000312 IsNestedNameSpecifier = true;
Douglas Gregor39982192010-08-15 06:18:01 +0000313 } else if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
314 // Values can appear in these contexts.
Richard Smith697cc9e2012-08-14 03:13:00 +0000315 Contexts = (1LL << CodeCompletionContext::CCC_Statement)
316 | (1LL << CodeCompletionContext::CCC_Expression)
317 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
318 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver);
Douglas Gregor39982192010-08-15 06:18:01 +0000319 } else if (isa<ObjCProtocolDecl>(ND)) {
Richard Smith697cc9e2012-08-14 03:13:00 +0000320 Contexts = (1LL << CodeCompletionContext::CCC_ObjCProtocolName);
Douglas Gregor21325842011-07-07 16:03:39 +0000321 } else if (isa<ObjCCategoryDecl>(ND)) {
Richard Smith697cc9e2012-08-14 03:13:00 +0000322 Contexts = (1LL << CodeCompletionContext::CCC_ObjCCategoryName);
Douglas Gregor39982192010-08-15 06:18:01 +0000323 } else if (isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) {
Richard Smith697cc9e2012-08-14 03:13:00 +0000324 Contexts = (1LL << CodeCompletionContext::CCC_Namespace);
Douglas Gregor39982192010-08-15 06:18:01 +0000325
326 // Part of the nested-name-specifier.
Douglas Gregor59cab552010-08-16 23:05:20 +0000327 IsNestedNameSpecifier = true;
Douglas Gregor39982192010-08-15 06:18:01 +0000328 }
329
330 return Contexts;
331}
332
Douglas Gregorb14904c2010-08-13 22:48:40 +0000333void ASTUnit::CacheCodeCompletionResults() {
334 if (!TheSema)
335 return;
336
Douglas Gregor16896c42010-10-28 15:44:59 +0000337 SimpleTimer Timer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +0000338 Timer.setOutput("Cache global code completions for " + getMainFileName());
Douglas Gregorb14904c2010-08-13 22:48:40 +0000339
340 // Clear out the previous results.
341 ClearCachedCompletionResults();
342
343 // Gather the set of global code completions.
John McCall276321a2010-08-25 06:19:51 +0000344 typedef CodeCompletionResult Result;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000345 SmallVector<Result, 8> Results;
David Blaikieea4395e2017-01-06 19:49:01 +0000346 CachedCompletionAllocator = std::make_shared<GlobalCodeCompletionAllocator>();
Argyrios Kyrtzidis2bafa002012-11-16 03:34:57 +0000347 CodeCompletionTUInfo CCTUInfo(CachedCompletionAllocator);
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +0000348 TheSema->GatherGlobalCodeCompletions(*CachedCompletionAllocator,
Argyrios Kyrtzidis2bafa002012-11-16 03:34:57 +0000349 CCTUInfo, Results);
Douglas Gregorb14904c2010-08-13 22:48:40 +0000350
351 // Translate global code completions into cached completions.
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000352 llvm::DenseMap<CanQualType, unsigned> CompletionTypes;
Douglas Gregorc3425b12015-07-07 06:20:19 +0000353 CodeCompletionContext CCContext(CodeCompletionContext::CCC_TopLevel);
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000354
355 for (Result &R : Results) {
356 switch (R.Kind) {
Douglas Gregor39982192010-08-15 06:18:01 +0000357 case Result::RK_Declaration: {
Douglas Gregor59cab552010-08-16 23:05:20 +0000358 bool IsNestedNameSpecifier = false;
Douglas Gregor39982192010-08-15 06:18:01 +0000359 CachedCodeCompletionResult CachedResult;
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000360 CachedResult.Completion = R.CreateCodeCompletionString(
Douglas Gregorc3425b12015-07-07 06:20:19 +0000361 *TheSema, CCContext, *CachedCompletionAllocator, CCTUInfo,
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000362 IncludeBriefCommentsInCodeCompletion);
363 CachedResult.ShowInContexts = getDeclShowContexts(
364 R.Declaration, Ctx->getLangOpts(), IsNestedNameSpecifier);
365 CachedResult.Priority = R.Priority;
366 CachedResult.Kind = R.CursorKind;
367 CachedResult.Availability = R.Availability;
Douglas Gregor24747402010-08-16 16:46:30 +0000368
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000369 // Keep track of the type of this completion in an ASTContext-agnostic
370 // way.
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000371 QualType UsageType = getDeclUsageType(*Ctx, R.Declaration);
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000372 if (UsageType.isNull()) {
Douglas Gregor24747402010-08-16 16:46:30 +0000373 CachedResult.TypeClass = STC_Void;
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000374 CachedResult.Type = 0;
375 } else {
376 CanQualType CanUsageType
377 = Ctx->getCanonicalType(UsageType.getUnqualifiedType());
378 CachedResult.TypeClass = getSimplifiedTypeClass(CanUsageType);
379
380 // Determine whether we have already seen this type. If so, we save
381 // ourselves the work of formatting the type string by using the
382 // temporary, CanQualType-based hash table to find the associated value.
383 unsigned &TypeValue = CompletionTypes[CanUsageType];
384 if (TypeValue == 0) {
385 TypeValue = CompletionTypes.size();
386 CachedCompletionTypes[QualType(CanUsageType).getAsString()]
387 = TypeValue;
388 }
389
390 CachedResult.Type = TypeValue;
Douglas Gregor24747402010-08-16 16:46:30 +0000391 }
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000392
Douglas Gregor39982192010-08-15 06:18:01 +0000393 CachedCompletionResults.push_back(CachedResult);
Douglas Gregor59cab552010-08-16 23:05:20 +0000394
395 /// Handle nested-name-specifiers in C++.
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000396 if (TheSema->Context.getLangOpts().CPlusPlus && IsNestedNameSpecifier &&
397 !R.StartsNestedNameSpecifier) {
Douglas Gregor59cab552010-08-16 23:05:20 +0000398 // The contexts in which a nested-name-specifier can appear in C++.
Richard Smith697cc9e2012-08-14 03:13:00 +0000399 uint64_t NNSContexts
400 = (1LL << CodeCompletionContext::CCC_TopLevel)
401 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
402 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
403 | (1LL << CodeCompletionContext::CCC_Statement)
404 | (1LL << CodeCompletionContext::CCC_Expression)
405 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
406 | (1LL << CodeCompletionContext::CCC_EnumTag)
407 | (1LL << CodeCompletionContext::CCC_UnionTag)
408 | (1LL << CodeCompletionContext::CCC_ClassOrStructTag)
409 | (1LL << CodeCompletionContext::CCC_Type)
410 | (1LL << CodeCompletionContext::CCC_PotentiallyQualifiedName)
411 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression);
Douglas Gregor59cab552010-08-16 23:05:20 +0000412
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000413 if (isa<NamespaceDecl>(R.Declaration) ||
414 isa<NamespaceAliasDecl>(R.Declaration))
Richard Smith697cc9e2012-08-14 03:13:00 +0000415 NNSContexts |= (1LL << CodeCompletionContext::CCC_Namespace);
Douglas Gregor59cab552010-08-16 23:05:20 +0000416
417 if (unsigned RemainingContexts
418 = NNSContexts & ~CachedResult.ShowInContexts) {
419 // If there any contexts where this completion can be a
420 // nested-name-specifier but isn't already an option, create a
421 // nested-name-specifier completion.
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000422 R.StartsNestedNameSpecifier = true;
423 CachedResult.Completion = R.CreateCodeCompletionString(
Douglas Gregorc3425b12015-07-07 06:20:19 +0000424 *TheSema, CCContext, *CachedCompletionAllocator, CCTUInfo,
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000425 IncludeBriefCommentsInCodeCompletion);
Douglas Gregor59cab552010-08-16 23:05:20 +0000426 CachedResult.ShowInContexts = RemainingContexts;
427 CachedResult.Priority = CCP_NestedNameSpecifier;
428 CachedResult.TypeClass = STC_Void;
429 CachedResult.Type = 0;
430 CachedCompletionResults.push_back(CachedResult);
431 }
432 }
Douglas Gregorb14904c2010-08-13 22:48:40 +0000433 break;
Douglas Gregor39982192010-08-15 06:18:01 +0000434 }
435
Douglas Gregorb14904c2010-08-13 22:48:40 +0000436 case Result::RK_Keyword:
437 case Result::RK_Pattern:
438 // Ignore keywords and patterns; we don't care, since they are so
439 // easily regenerated.
440 break;
441
442 case Result::RK_Macro: {
443 CachedCodeCompletionResult CachedResult;
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000444 CachedResult.Completion = R.CreateCodeCompletionString(
Douglas Gregorc3425b12015-07-07 06:20:19 +0000445 *TheSema, CCContext, *CachedCompletionAllocator, CCTUInfo,
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000446 IncludeBriefCommentsInCodeCompletion);
Douglas Gregorb14904c2010-08-13 22:48:40 +0000447 CachedResult.ShowInContexts
Richard Smith697cc9e2012-08-14 03:13:00 +0000448 = (1LL << CodeCompletionContext::CCC_TopLevel)
449 | (1LL << CodeCompletionContext::CCC_ObjCInterface)
450 | (1LL << CodeCompletionContext::CCC_ObjCImplementation)
451 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
452 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
453 | (1LL << CodeCompletionContext::CCC_Statement)
454 | (1LL << CodeCompletionContext::CCC_Expression)
455 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
456 | (1LL << CodeCompletionContext::CCC_MacroNameUse)
457 | (1LL << CodeCompletionContext::CCC_PreprocessorExpression)
458 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
459 | (1LL << CodeCompletionContext::CCC_OtherWithMacros);
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000460
461 CachedResult.Priority = R.Priority;
462 CachedResult.Kind = R.CursorKind;
463 CachedResult.Availability = R.Availability;
Douglas Gregor6e240332010-08-16 16:18:59 +0000464 CachedResult.TypeClass = STC_Void;
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000465 CachedResult.Type = 0;
Douglas Gregorb14904c2010-08-13 22:48:40 +0000466 CachedCompletionResults.push_back(CachedResult);
467 break;
468 }
469 }
Douglas Gregorb14904c2010-08-13 22:48:40 +0000470 }
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000471
472 // Save the current top-level hash value.
473 CompletionCacheTopLevelHashValue = CurrentTopLevelHashValue;
Douglas Gregorb14904c2010-08-13 22:48:40 +0000474}
475
476void ASTUnit::ClearCachedCompletionResults() {
Douglas Gregorb14904c2010-08-13 22:48:40 +0000477 CachedCompletionResults.clear();
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000478 CachedCompletionTypes.clear();
Craig Topper49a27902014-05-22 04:46:25 +0000479 CachedCompletionAllocator = nullptr;
Douglas Gregorb14904c2010-08-13 22:48:40 +0000480}
481
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000482namespace {
483
Sebastian Redl2c499f62010-08-18 23:56:43 +0000484/// \brief Gathers information from ASTReader that will be used to initialize
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000485/// a Preprocessor.
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000486class ASTInfoCollector : public ASTReaderListener {
Douglas Gregor83297df2011-09-01 23:39:15 +0000487 Preprocessor &PP;
Douglas Gregore8bbc122011-09-02 00:18:52 +0000488 ASTContext &Context;
Richard Smith18934752017-06-06 00:32:01 +0000489 HeaderSearchOptions &HSOpts;
490 PreprocessorOptions &PPOpts;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000491 LangOptions &LangOpt;
Alp Toker80758082014-07-06 05:26:44 +0000492 std::shared_ptr<TargetOptions> &TargetOpts;
Dylan Noblesmithc95d8192012-02-20 14:00:23 +0000493 IntrusiveRefCntPtr<TargetInfo> &Target;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000494 unsigned &Counter;
Mike Stump11289f42009-09-09 15:08:12 +0000495
Douglas Gregore8bbc122011-09-02 00:18:52 +0000496 bool InitializedLanguage;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000497public:
Richard Smith18934752017-06-06 00:32:01 +0000498 ASTInfoCollector(Preprocessor &PP, ASTContext &Context,
499 HeaderSearchOptions &HSOpts, PreprocessorOptions &PPOpts,
500 LangOptions &LangOpt,
Alp Toker80758082014-07-06 05:26:44 +0000501 std::shared_ptr<TargetOptions> &TargetOpts,
502 IntrusiveRefCntPtr<TargetInfo> &Target, unsigned &Counter)
Richard Smith18934752017-06-06 00:32:01 +0000503 : PP(PP), Context(Context), HSOpts(HSOpts), PPOpts(PPOpts),
504 LangOpt(LangOpt), TargetOpts(TargetOpts), Target(Target),
505 Counter(Counter), InitializedLanguage(false) {}
Mike Stump11289f42009-09-09 15:08:12 +0000506
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000507 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
508 bool AllowCompatibleDifferences) override {
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000509 if (InitializedLanguage)
Douglas Gregor83297df2011-09-01 23:39:15 +0000510 return false;
511
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000512 LangOpt = LangOpts;
513 InitializedLanguage = true;
514
515 updated();
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000516 return false;
517 }
Mike Stump11289f42009-09-09 15:08:12 +0000518
Richard Smith18934752017-06-06 00:32:01 +0000519 virtual bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
520 StringRef SpecificModuleCachePath,
521 bool Complain) override {
522 this->HSOpts = HSOpts;
523 return false;
524 }
525
526 virtual bool
527 ReadPreprocessorOptions(const PreprocessorOptions &PPOpts, bool Complain,
528 std::string &SuggestedPredefines) override {
529 this->PPOpts = PPOpts;
530 return false;
531 }
532
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000533 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
534 bool AllowCompatibleDifferences) override {
Douglas Gregor83297df2011-09-01 23:39:15 +0000535 // If we've already initialized the target, don't do it again.
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000536 if (Target)
Douglas Gregor83297df2011-09-01 23:39:15 +0000537 return false;
Alp Toker80758082014-07-06 05:26:44 +0000538
539 this->TargetOpts = std::make_shared<TargetOptions>(TargetOpts);
540 Target =
541 TargetInfo::CreateTargetInfo(PP.getDiagnostics(), this->TargetOpts);
Argyrios Kyrtzidis9e1fb562012-09-14 20:24:53 +0000542
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000543 updated();
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000544 return false;
545 }
Mike Stump11289f42009-09-09 15:08:12 +0000546
Craig Topperafa7cb32014-03-13 06:07:04 +0000547 void ReadCounter(const serialization::ModuleFile &M,
548 unsigned Value) override {
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000549 Counter = Value;
550 }
Argyrios Kyrtzidis9e1fb562012-09-14 20:24:53 +0000551
552private:
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000553 void updated() {
554 if (!Target || !InitializedLanguage)
555 return;
556
557 // Inform the target of the language options.
558 //
559 // FIXME: We shouldn't need to do this, the target should be immutable once
560 // created. This complexity should be lifted elsewhere.
Alp Toker74437972014-07-06 05:14:24 +0000561 Target->adjust(LangOpt);
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000562
563 // Initialize the preprocessor.
564 PP.Initialize(*Target);
565
566 // Initialize the ASTContext
567 Context.InitBuiltinTypes(*Target);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +0000568
569 // We didn't have access to the comment options when the ASTContext was
570 // constructed, so register them now.
571 Context.getCommentCommandTraits().registerCommentOptions(
572 LangOpt.CommentOpts);
Argyrios Kyrtzidis9e1fb562012-09-14 20:24:53 +0000573 }
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000574};
575
Douglas Gregor6b930962013-05-03 22:58:43 +0000576 /// \brief Diagnostic consumer that saves each diagnostic it is given.
David Blaikief18d91a2011-09-26 00:01:39 +0000577class StoredDiagnosticConsumer : public DiagnosticConsumer {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000578 SmallVectorImpl<StoredDiagnostic> &StoredDiags;
Douglas Gregor6b930962013-05-03 22:58:43 +0000579 SourceManager *SourceMgr;
580
Douglas Gregor33cdd812010-02-18 18:08:43 +0000581public:
David Blaikief18d91a2011-09-26 00:01:39 +0000582 explicit StoredDiagnosticConsumer(
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000583 SmallVectorImpl<StoredDiagnostic> &StoredDiags)
Craig Topper49a27902014-05-22 04:46:25 +0000584 : StoredDiags(StoredDiags), SourceMgr(nullptr) {}
Douglas Gregor6b930962013-05-03 22:58:43 +0000585
Craig Topperafa7cb32014-03-13 06:07:04 +0000586 void BeginSourceFile(const LangOptions &LangOpts,
Craig Topper49a27902014-05-22 04:46:25 +0000587 const Preprocessor *PP = nullptr) override {
Douglas Gregor6b930962013-05-03 22:58:43 +0000588 if (PP)
589 SourceMgr = &PP->getSourceManager();
590 }
591
Craig Topperafa7cb32014-03-13 06:07:04 +0000592 void HandleDiagnostic(DiagnosticsEngine::Level Level,
593 const Diagnostic &Info) override;
Douglas Gregor33cdd812010-02-18 18:08:43 +0000594};
595
596/// \brief RAII object that optionally captures diagnostics, if
597/// there is no diagnostic client to capture them already.
598class CaptureDroppedDiagnostics {
David Blaikie9c902b52011-09-25 23:23:43 +0000599 DiagnosticsEngine &Diags;
David Blaikief18d91a2011-09-26 00:01:39 +0000600 StoredDiagnosticConsumer Client;
David Blaikiee2eefae2011-09-25 23:39:51 +0000601 DiagnosticConsumer *PreviousClient;
Alexander Kornienko41c247a2014-11-17 23:46:02 +0000602 std::unique_ptr<DiagnosticConsumer> OwningPreviousClient;
Douglas Gregor33cdd812010-02-18 18:08:43 +0000603
604public:
David Blaikie9c902b52011-09-25 23:23:43 +0000605 CaptureDroppedDiagnostics(bool RequestCapture, DiagnosticsEngine &Diags,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000606 SmallVectorImpl<StoredDiagnostic> &StoredDiags)
Craig Topper49a27902014-05-22 04:46:25 +0000607 : Diags(Diags), Client(StoredDiags), PreviousClient(nullptr)
Douglas Gregor33cdd812010-02-18 18:08:43 +0000608 {
Craig Topper49a27902014-05-22 04:46:25 +0000609 if (RequestCapture || Diags.getClient() == nullptr) {
Alexander Kornienko41c247a2014-11-17 23:46:02 +0000610 OwningPreviousClient = Diags.takeClient();
611 PreviousClient = Diags.getClient();
612 Diags.setClient(&Client, false);
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000613 }
Douglas Gregor33cdd812010-02-18 18:08:43 +0000614 }
615
616 ~CaptureDroppedDiagnostics() {
Alexander Kornienko41c247a2014-11-17 23:46:02 +0000617 if (Diags.getClient() == &Client)
618 Diags.setClient(PreviousClient, !!OwningPreviousClient.release());
Douglas Gregor33cdd812010-02-18 18:08:43 +0000619 }
620};
621
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000622} // anonymous namespace
623
David Blaikief18d91a2011-09-26 00:01:39 +0000624void StoredDiagnosticConsumer::HandleDiagnostic(DiagnosticsEngine::Level Level,
David Blaikieb5784322011-09-26 01:18:08 +0000625 const Diagnostic &Info) {
Argyrios Kyrtzidisc79346a2010-11-18 20:06:46 +0000626 // Default implementation (Warnings/errors count).
David Blaikiee2eefae2011-09-25 23:39:51 +0000627 DiagnosticConsumer::HandleDiagnostic(Level, Info);
Argyrios Kyrtzidisc79346a2010-11-18 20:06:46 +0000628
Douglas Gregor6b930962013-05-03 22:58:43 +0000629 // Only record the diagnostic if it's part of the source manager we know
630 // about. This effectively drops diagnostics from modules we're building.
631 // FIXME: In the long run, ee don't want to drop source managers from modules.
632 if (!Info.hasSourceManager() || &Info.getSourceManager() == SourceMgr)
Benjamin Kramer3204b152015-05-29 19:42:19 +0000633 StoredDiags.emplace_back(Level, Info);
Douglas Gregor33cdd812010-02-18 18:08:43 +0000634}
635
Argyrios Kyrtzidisa38cb202017-01-30 06:05:58 +0000636IntrusiveRefCntPtr<ASTReader> ASTUnit::getASTReader() const {
637 return Reader;
638}
639
Argyrios Kyrtzidis1c7455f2013-05-10 01:28:51 +0000640ASTMutationListener *ASTUnit::getASTMutationListener() {
641 if (WriterData)
642 return &WriterData->Writer;
Craig Topper49a27902014-05-22 04:46:25 +0000643 return nullptr;
Argyrios Kyrtzidis1c7455f2013-05-10 01:28:51 +0000644}
645
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000646ASTDeserializationListener *ASTUnit::getDeserializationListener() {
647 if (WriterData)
648 return &WriterData->Writer;
Craig Topper49a27902014-05-22 04:46:25 +0000649 return nullptr;
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000650}
651
Rafael Espindola16e1ba12014-08-26 20:17:44 +0000652std::unique_ptr<llvm::MemoryBuffer>
653ASTUnit::getBufferForFile(StringRef Filename, std::string *ErrorStr) {
Chris Lattner5159f612010-11-23 08:35:12 +0000654 assert(FileMgr);
Benjamin Kramera8857962014-10-26 22:44:13 +0000655 auto Buffer = FileMgr->getBufferForFile(Filename);
656 if (Buffer)
657 return std::move(*Buffer);
658 if (ErrorStr)
659 *ErrorStr = Buffer.getError().message();
660 return nullptr;
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000661}
662
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000663/// \brief Configure the diagnostics object for use with ASTUnit.
Justin Bognerd512c1e2014-10-15 00:33:06 +0000664void ASTUnit::ConfigureDiags(IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000665 ASTUnit &AST, bool CaptureDiagnostics) {
Justin Bognerd512c1e2014-10-15 00:33:06 +0000666 assert(Diags.get() && "no DiagnosticsEngine was provided");
667 if (CaptureDiagnostics)
David Blaikief18d91a2011-09-26 00:01:39 +0000668 Diags->setClient(new StoredDiagnosticConsumer(AST.StoredDiagnostics));
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000669}
670
David Blaikie6f7382d2014-08-10 19:08:04 +0000671std::unique_ptr<ASTUnit> ASTUnit::LoadFromASTFile(
Adrian Prantl6b21ab22015-08-27 19:46:20 +0000672 const std::string &Filename, const PCHContainerReader &PCHContainerRdr,
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000673 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Adrian Prantl6b21ab22015-08-27 19:46:20 +0000674 const FileSystemOptions &FileSystemOpts, bool UseDebugInfo,
675 bool OnlyLocalDecls, ArrayRef<RemappedFile> RemappedFiles,
676 bool CaptureDiagnostics, bool AllowPCHWithCompilerErrors,
677 bool UserFilesAreVolatile) {
Ahmed Charlesb8984322014-03-07 20:03:18 +0000678 std::unique_ptr<ASTUnit> AST(new ASTUnit(true));
Ted Kremenek4422bfe2011-03-18 02:06:56 +0000679
680 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +0000681 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
682 ASTUnitCleanup(AST.get());
David Blaikie9c902b52011-09-25 23:23:43 +0000683 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
684 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Alp Tokerf994cef2014-07-05 03:08:06 +0000685 DiagCleanup(Diags.get());
Ted Kremenek4422bfe2011-03-18 02:06:56 +0000686
Justin Bognerdbbcb112014-10-14 23:36:06 +0000687 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000688
Richard Smithab755972017-06-05 18:10:11 +0000689 AST->LangOpts = std::make_shared<LangOptions>();
Douglas Gregor16bef852009-10-16 20:01:17 +0000690 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000691 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor7f95d262010-04-05 23:52:57 +0000692 AST->Diagnostics = Diags;
Ben Langmuir8832c062014-04-15 18:16:25 +0000693 IntrusiveRefCntPtr<vfs::FileSystem> VFS = vfs::getRealFileSystem();
694 AST->FileMgr = new FileManager(FileSystemOpts, VFS);
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +0000695 AST->UserFilesAreVolatile = UserFilesAreVolatile;
Ted Kremenek5e14d392011-03-21 18:40:17 +0000696 AST->SourceMgr = new SourceManager(AST->getDiagnostics(),
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +0000697 AST->getFileManager(),
698 UserFilesAreVolatile);
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +0000699 AST->PCMCache = new MemoryBufferCache;
David Blaikie9c28cb32017-01-06 01:04:46 +0000700 AST->HSOpts = std::make_shared<HeaderSearchOptions>();
Adrian Prantlfb2398d2015-07-17 01:19:54 +0000701 AST->HSOpts->ModuleFormat = PCHContainerRdr.getFormat();
Douglas Gregorb85b9cc2012-10-24 16:19:39 +0000702 AST->HeaderInfo.reset(new HeaderSearch(AST->HSOpts,
Manuel Klimek1f76c4e2013-10-24 07:51:24 +0000703 AST->getSourceManager(),
Douglas Gregor1fb5c3a2011-12-31 04:05:44 +0000704 AST->getDiagnostics(),
Richard Smithab755972017-06-05 18:10:11 +0000705 AST->getLangOpts(),
Craig Topper49a27902014-05-22 04:46:25 +0000706 /*Target=*/nullptr));
Richard Smith18934752017-06-06 00:32:01 +0000707 AST->PPOpts = std::make_shared<PreprocessorOptions>();
Dmitri Gribenkoc444b572014-02-08 00:38:15 +0000708
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000709 for (const auto &RemappedFile : RemappedFiles)
Richard Smith18934752017-06-06 00:32:01 +0000710 AST->PPOpts->addRemappedFile(RemappedFile.first, RemappedFile.second);
Dmitri Gribenkoc444b572014-02-08 00:38:15 +0000711
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000712 // Gather Info for preprocessor construction later on.
Mike Stump11289f42009-09-09 15:08:12 +0000713
David Blaikie6f7382d2014-08-10 19:08:04 +0000714 HeaderSearch &HeaderInfo = *AST->HeaderInfo;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000715 unsigned Counter;
716
David Blaikie41565462017-01-05 19:48:07 +0000717 AST->PP = std::make_shared<Preprocessor>(
Richard Smith18934752017-06-06 00:32:01 +0000718 AST->PPOpts, AST->getDiagnostics(), *AST->LangOpts,
Richard Smith5d2ed482017-06-09 19:22:32 +0000719 AST->getSourceManager(), *AST->PCMCache, HeaderInfo, AST->ModuleLoader,
David Blaikie41565462017-01-05 19:48:07 +0000720 /*IILookup=*/nullptr,
721 /*OwnsHeaderSearch=*/false);
Douglas Gregore8bbc122011-09-02 00:18:52 +0000722 Preprocessor &PP = *AST->PP;
723
Richard Smithab755972017-06-05 18:10:11 +0000724 AST->Ctx = new ASTContext(*AST->LangOpts, AST->getSourceManager(),
Alp Toker08043432014-05-03 03:46:04 +0000725 PP.getIdentifierTable(), PP.getSelectorTable(),
726 PP.getBuiltinInfo());
Douglas Gregore8bbc122011-09-02 00:18:52 +0000727 ASTContext &Context = *AST->Ctx;
Douglas Gregor83297df2011-09-01 23:39:15 +0000728
Argyrios Kyrtzidis945a8192012-09-15 01:10:20 +0000729 bool disableValid = false;
730 if (::getenv("LIBCLANG_DISABLE_PCH_VALIDATION"))
731 disableValid = true;
Douglas Gregor6623e1f2015-11-03 18:33:07 +0000732 AST->Reader = new ASTReader(PP, Context, PCHContainerRdr, { },
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000733 /*isysroot=*/"",
734 /*DisableValidation=*/disableValid,
735 AllowPCHWithCompilerErrors);
Ted Kremenek2159b8d2011-05-04 23:27:12 +0000736
David Blaikie2721c322014-08-10 16:54:39 +0000737 AST->Reader->setListener(llvm::make_unique<ASTInfoCollector>(
Richard Smith18934752017-06-06 00:32:01 +0000738 *AST->PP, Context, *AST->HSOpts, *AST->PPOpts, *AST->LangOpts,
739 AST->TargetOpts, AST->Target, Counter));
Daniel Dunbar2d9c7402009-09-03 05:59:35 +0000740
Argyrios Kyrtzidisf0b4cd12015-03-03 08:04:19 +0000741 // Attach the AST reader to the AST context as an external AST
742 // source, so that declarations will be deserialized from the
743 // AST file as needed.
744 // We need the external source to be set up before we read the AST, because
745 // eagerly-deserialized declarations may use it.
746 Context.setExternalSource(AST->Reader);
747
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000748 switch (AST->Reader->ReadAST(Filename, serialization::MK_MainFile,
Argyrios Kyrtzidis2ec29362012-11-15 18:57:22 +0000749 SourceLocation(), ASTReader::ARR_None)) {
Sebastian Redl2c499f62010-08-18 23:56:43 +0000750 case ASTReader::Success:
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000751 break;
Mike Stump11289f42009-09-09 15:08:12 +0000752
Sebastian Redl2c499f62010-08-18 23:56:43 +0000753 case ASTReader::Failure:
Douglas Gregor7029ce12013-03-19 00:28:20 +0000754 case ASTReader::Missing:
Douglas Gregorc9ad5fb2012-10-22 22:50:17 +0000755 case ASTReader::OutOfDate:
756 case ASTReader::VersionMismatch:
757 case ASTReader::ConfigurationMismatch:
758 case ASTReader::HadErrors:
Douglas Gregord03e8232010-04-05 21:10:19 +0000759 AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
Craig Topper49a27902014-05-22 04:46:25 +0000760 return nullptr;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000761 }
Mike Stump11289f42009-09-09 15:08:12 +0000762
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000763 AST->OriginalSourceFile = AST->Reader->getOriginalSourceFile();
Daniel Dunbara8a50932009-12-02 08:44:16 +0000764
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000765 PP.setCounterValue(Counter);
Mike Stump11289f42009-09-09 15:08:12 +0000766
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000767 // Create an AST consumer, even though it isn't used.
768 AST->Consumer.reset(new ASTConsumer);
769
Sebastian Redl2c499f62010-08-18 23:56:43 +0000770 // Create a semantic analysis object and tell the AST reader about it.
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000771 AST->TheSema.reset(new Sema(PP, Context, *AST->Consumer));
772 AST->TheSema->Initialize();
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000773 AST->Reader->InitializeSema(*AST->TheSema);
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000774
Douglas Gregor6b930962013-05-03 22:58:43 +0000775 // Tell the diagnostic client that we have started a source file.
776 AST->getDiagnostics().getClient()->BeginSourceFile(Context.getLangOpts(),&PP);
777
David Blaikie6f7382d2014-08-10 19:08:04 +0000778 return AST;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000779}
Daniel Dunbar764c0822009-12-01 09:51:01 +0000780
781namespace {
782
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000783/// \brief Preprocessor callback class that updates a hash value with the names
784/// of all macros that have been defined by the translation unit.
785class MacroDefinitionTrackerPPCallbacks : public PPCallbacks {
786 unsigned &Hash;
787
788public:
789 explicit MacroDefinitionTrackerPPCallbacks(unsigned &Hash) : Hash(Hash) { }
Craig Topperafa7cb32014-03-13 06:07:04 +0000790
791 void MacroDefined(const Token &MacroNameTok,
792 const MacroDirective *MD) override {
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000793 Hash = llvm::HashString(MacroNameTok.getIdentifierInfo()->getName(), Hash);
794 }
795};
796
797/// \brief Add the given declaration to the hash of all top-level entities.
798void AddTopLevelDeclarationToHash(Decl *D, unsigned &Hash) {
799 if (!D)
800 return;
801
802 DeclContext *DC = D->getDeclContext();
803 if (!DC)
804 return;
805
806 if (!(DC->isTranslationUnit() || DC->getLookupParent()->isTranslationUnit()))
807 return;
808
809 if (NamedDecl *ND = dyn_cast<NamedDecl>(D)) {
Argyrios Kyrtzidisca5c7be2013-10-15 17:37:55 +0000810 if (EnumDecl *EnumD = dyn_cast<EnumDecl>(D)) {
811 // For an unscoped enum include the enumerators in the hash since they
812 // enter the top-level namespace.
813 if (!EnumD->isScoped()) {
Aaron Ballman23a6dcb2014-03-08 18:45:14 +0000814 for (const auto *EI : EnumD->enumerators()) {
815 if (EI->getIdentifier())
816 Hash = llvm::HashString(EI->getIdentifier()->getName(), Hash);
Argyrios Kyrtzidisca5c7be2013-10-15 17:37:55 +0000817 }
818 }
819 }
820
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000821 if (ND->getIdentifier())
822 Hash = llvm::HashString(ND->getIdentifier()->getName(), Hash);
823 else if (DeclarationName Name = ND->getDeclName()) {
824 std::string NameStr = Name.getAsString();
825 Hash = llvm::HashString(NameStr, Hash);
826 }
827 return;
Argyrios Kyrtzidis48d88de2013-06-24 21:19:12 +0000828 }
829
830 if (ImportDecl *ImportD = dyn_cast<ImportDecl>(D)) {
831 if (Module *Mod = ImportD->getImportedModule()) {
832 std::string ModName = Mod->getFullModuleName();
833 Hash = llvm::HashString(ModName, Hash);
834 }
835 return;
836 }
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000837}
838
Daniel Dunbar644dca02009-12-04 08:17:33 +0000839class TopLevelDeclTrackerConsumer : public ASTConsumer {
840 ASTUnit &Unit;
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000841 unsigned &Hash;
842
Daniel Dunbar644dca02009-12-04 08:17:33 +0000843public:
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000844 TopLevelDeclTrackerConsumer(ASTUnit &_Unit, unsigned &Hash)
845 : Unit(_Unit), Hash(Hash) {
846 Hash = 0;
847 }
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000848
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000849 void handleTopLevelDecl(Decl *D) {
Argyrios Kyrtzidis516eec22011-11-16 02:35:10 +0000850 if (!D)
851 return;
852
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000853 // FIXME: Currently ObjC method declarations are incorrectly being
854 // reported as top-level declarations, even though their DeclContext
855 // is the containing ObjC @interface/@implementation. This is a
856 // fundamental problem in the parser right now.
857 if (isa<ObjCMethodDecl>(D))
858 return;
859
860 AddTopLevelDeclarationToHash(D, Hash);
861 Unit.addTopLevelDecl(D);
862
863 handleFileLevelDecl(D);
864 }
865
866 void handleFileLevelDecl(Decl *D) {
867 Unit.addFileLevelDecl(D);
868 if (NamespaceDecl *NSD = dyn_cast<NamespaceDecl>(D)) {
Aaron Ballman629afae2014-03-07 19:56:05 +0000869 for (auto *I : NSD->decls())
870 handleFileLevelDecl(I);
Ted Kremenekacc59c32010-05-03 20:16:35 +0000871 }
Daniel Dunbar644dca02009-12-04 08:17:33 +0000872 }
Sebastian Redleaa4ade2010-08-11 18:52:41 +0000873
Craig Topperafa7cb32014-03-13 06:07:04 +0000874 bool HandleTopLevelDecl(DeclGroupRef D) override {
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000875 for (Decl *TopLevelDecl : D)
876 handleTopLevelDecl(TopLevelDecl);
Argyrios Kyrtzidis841dd882011-11-18 00:26:59 +0000877 return true;
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000878 }
879
Sebastian Redleaa4ade2010-08-11 18:52:41 +0000880 // We're not interested in "interesting" decls.
Craig Topperafa7cb32014-03-13 06:07:04 +0000881 void HandleInterestingDecl(DeclGroupRef) override {}
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000882
Craig Topperafa7cb32014-03-13 06:07:04 +0000883 void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) override {
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000884 for (Decl *TopLevelDecl : D)
885 handleTopLevelDecl(TopLevelDecl);
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000886 }
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000887
Craig Topperafa7cb32014-03-13 06:07:04 +0000888 ASTMutationListener *GetASTMutationListener() override {
Argyrios Kyrtzidis1c7455f2013-05-10 01:28:51 +0000889 return Unit.getASTMutationListener();
890 }
891
Craig Topperafa7cb32014-03-13 06:07:04 +0000892 ASTDeserializationListener *GetASTDeserializationListener() override {
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000893 return Unit.getDeserializationListener();
894 }
Daniel Dunbar644dca02009-12-04 08:17:33 +0000895};
896
897class TopLevelDeclTrackerAction : public ASTFrontendAction {
898public:
899 ASTUnit &Unit;
900
David Blaikie6beb6aa2014-08-10 19:56:51 +0000901 std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
902 StringRef InFile) override {
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000903 CI.getPreprocessor().addPPCallbacks(
Craig Topperb8a70532014-09-10 04:53:53 +0000904 llvm::make_unique<MacroDefinitionTrackerPPCallbacks>(
905 Unit.getCurrentTopLevelHashValue()));
David Blaikie6beb6aa2014-08-10 19:56:51 +0000906 return llvm::make_unique<TopLevelDeclTrackerConsumer>(
907 Unit, Unit.getCurrentTopLevelHashValue());
Daniel Dunbar764c0822009-12-01 09:51:01 +0000908 }
909
910public:
Daniel Dunbar644dca02009-12-04 08:17:33 +0000911 TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {}
912
Craig Topperafa7cb32014-03-13 06:07:04 +0000913 bool hasCodeCompletionSupport() const override { return false; }
914 TranslationUnitKind getTranslationUnitKind() override {
Douglas Gregor69f74f82011-08-25 22:30:56 +0000915 return Unit.getTranslationUnitKind();
Douglas Gregor028d3e42010-08-09 20:45:32 +0000916 }
Daniel Dunbar764c0822009-12-01 09:51:01 +0000917};
918
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000919class PrecompilePreambleAction : public ASTFrontendAction {
920 ASTUnit &Unit;
921 bool HasEmittedPreamblePCH;
922
923public:
924 explicit PrecompilePreambleAction(ASTUnit &Unit)
925 : Unit(Unit), HasEmittedPreamblePCH(false) {}
926
David Blaikie6beb6aa2014-08-10 19:56:51 +0000927 std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
928 StringRef InFile) override;
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000929 bool hasEmittedPreamblePCH() const { return HasEmittedPreamblePCH; }
930 void setHasEmittedPreamblePCH() { HasEmittedPreamblePCH = true; }
Craig Topperafa7cb32014-03-13 06:07:04 +0000931 bool shouldEraseOutputFiles() override { return !hasEmittedPreamblePCH(); }
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000932
Craig Topperafa7cb32014-03-13 06:07:04 +0000933 bool hasCodeCompletionSupport() const override { return false; }
934 bool hasASTFileSupport() const override { return false; }
935 TranslationUnitKind getTranslationUnitKind() override { return TU_Prefix; }
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000936};
937
Argyrios Kyrtzidis57332712011-09-19 20:40:48 +0000938class PrecompilePreambleConsumer : public PCHGenerator {
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000939 ASTUnit &Unit;
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000940 unsigned &Hash;
Douglas Gregore9db88f2010-08-03 19:06:41 +0000941 std::vector<Decl *> TopLevelDecls;
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000942 PrecompilePreambleAction *Action;
Peter Collingbourne03f89072016-07-15 00:55:40 +0000943 std::unique_ptr<raw_ostream> Out;
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000944
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000945public:
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000946 PrecompilePreambleConsumer(ASTUnit &Unit, PrecompilePreambleAction *Action,
947 const Preprocessor &PP, StringRef isysroot,
Peter Collingbourne03f89072016-07-15 00:55:40 +0000948 std::unique_ptr<raw_ostream> Out)
Richard Smithbd97f352016-08-25 18:26:30 +0000949 : PCHGenerator(PP, "", isysroot, std::make_shared<PCHBuffer>(),
David Blaikie61137e12017-01-05 18:23:18 +0000950 ArrayRef<std::shared_ptr<ModuleFileExtension>>(),
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000951 /*AllowASTWithErrors=*/true),
952 Unit(Unit), Hash(Unit.getCurrentTopLevelHashValue()), Action(Action),
Peter Collingbourne03f89072016-07-15 00:55:40 +0000953 Out(std::move(Out)) {
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000954 Hash = 0;
955 }
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000956
Benjamin Kramera401b9b2015-02-06 18:58:04 +0000957 bool HandleTopLevelDecl(DeclGroupRef DG) override {
958 for (Decl *D : DG) {
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000959 // FIXME: Currently ObjC method declarations are incorrectly being
960 // reported as top-level declarations, even though their DeclContext
961 // is the containing ObjC @interface/@implementation. This is a
962 // fundamental problem in the parser right now.
963 if (isa<ObjCMethodDecl>(D))
964 continue;
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000965 AddTopLevelDeclarationToHash(D, Hash);
Douglas Gregore9db88f2010-08-03 19:06:41 +0000966 TopLevelDecls.push_back(D);
967 }
Argyrios Kyrtzidis841dd882011-11-18 00:26:59 +0000968 return true;
Douglas Gregore9db88f2010-08-03 19:06:41 +0000969 }
970
Craig Topperafa7cb32014-03-13 06:07:04 +0000971 void HandleTranslationUnit(ASTContext &Ctx) override {
Douglas Gregore9db88f2010-08-03 19:06:41 +0000972 PCHGenerator::HandleTranslationUnit(Ctx);
Argyrios Kyrtzidisf0168de2013-06-11 00:36:55 +0000973 if (hasEmittedPCH()) {
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000974 // Write the generated bitstream to "Out".
975 *Out << getPCH();
976 // Make sure it hits disk now.
977 Out->flush();
978 // Free the buffer.
979 llvm::SmallVector<char, 0> Empty;
980 getPCH() = std::move(Empty);
981
Douglas Gregore9db88f2010-08-03 19:06:41 +0000982 // Translate the top-level declarations we captured during
983 // parsing into declaration IDs in the precompiled
984 // preamble. This will allow us to deserialize those top-level
985 // declarations when requested.
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000986 for (Decl *D : TopLevelDecls) {
Argyrios Kyrtzidisacfbbd72013-08-07 21:17:33 +0000987 // Invalid top-level decls may not have been serialized.
988 if (D->isInvalidDecl())
989 continue;
990 Unit.addTopLevelDeclFromPreamble(getWriter().getDeclID(D));
991 }
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000992
993 Action->setHasEmittedPreamblePCH();
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000994 }
995 }
996};
997
Hans Wennborgdcfba332015-10-06 23:40:43 +0000998} // anonymous namespace
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000999
David Blaikie6beb6aa2014-08-10 19:56:51 +00001000std::unique_ptr<ASTConsumer>
1001PrecompilePreambleAction::CreateASTConsumer(CompilerInstance &CI,
1002 StringRef InFile) {
Benjamin Kramer65745dc2013-06-11 13:07:19 +00001003 std::string Sysroot;
1004 std::string OutputFile;
Peter Collingbourne03f89072016-07-15 00:55:40 +00001005 std::unique_ptr<raw_ostream> OS =
1006 GeneratePCHAction::ComputeASTConsumerArguments(CI, InFile, Sysroot,
1007 OutputFile);
Rafael Espindola47de1492015-04-10 12:54:53 +00001008 if (!OS)
Craig Topper49a27902014-05-22 04:46:25 +00001009 return nullptr;
Douglas Gregor48c8cd32010-08-03 08:14:03 +00001010
Benjamin Kramer65745dc2013-06-11 13:07:19 +00001011 if (!CI.getFrontendOpts().RelocatablePCH)
1012 Sysroot.clear();
Douglas Gregorc567ba22011-07-22 16:35:34 +00001013
Craig Topperb8a70532014-09-10 04:53:53 +00001014 CI.getPreprocessor().addPPCallbacks(
1015 llvm::make_unique<MacroDefinitionTrackerPPCallbacks>(
1016 Unit.getCurrentTopLevelHashValue()));
David Blaikie6beb6aa2014-08-10 19:56:51 +00001017 return llvm::make_unique<PrecompilePreambleConsumer>(
Peter Collingbourne03f89072016-07-15 00:55:40 +00001018 Unit, this, CI.getPreprocessor(), Sysroot, std::move(OS));
Daniel Dunbar764c0822009-12-01 09:51:01 +00001019}
1020
Benjamin Kramer1ce5d802013-05-05 12:39:28 +00001021static bool isNonDriverDiag(const StoredDiagnostic &StoredDiag) {
1022 return StoredDiag.getLocation().isValid();
1023}
1024
1025static void
1026checkAndRemoveNonDriverDiags(SmallVectorImpl<StoredDiagnostic> &StoredDiags) {
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +00001027 // Get rid of stored diagnostics except the ones from the driver which do not
1028 // have a source location.
Benjamin Kramer1ce5d802013-05-05 12:39:28 +00001029 StoredDiags.erase(
1030 std::remove_if(StoredDiags.begin(), StoredDiags.end(), isNonDriverDiag),
1031 StoredDiags.end());
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +00001032}
1033
1034static void checkAndSanitizeDiags(SmallVectorImpl<StoredDiagnostic> &
1035 StoredDiagnostics,
1036 SourceManager &SM) {
1037 // The stored diagnostic has the old source manager in it; update
1038 // the locations to refer into the new source manager. Since we've
1039 // been careful to make sure that the source manager's state
1040 // before and after are identical, so that we can reuse the source
1041 // location itself.
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00001042 for (StoredDiagnostic &SD : StoredDiagnostics) {
1043 if (SD.getLocation().isValid()) {
1044 FullSourceLoc Loc(SD.getLocation(), SM);
1045 SD.setLocation(Loc);
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +00001046 }
1047 }
1048}
1049
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001050/// Parse the source file into a translation unit using the given compiler
1051/// invocation, replacing the current translation unit.
1052///
1053/// \returns True if a failure occurred that causes the ASTUnit not to
1054/// contain any translation-unit information, false otherwise.
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001055bool ASTUnit::Parse(std::shared_ptr<PCHContainerOperations> PCHContainerOps,
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001056 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer,
1057 IntrusiveRefCntPtr<vfs::FileSystem> VFS) {
Rafael Espindola32482082014-08-18 16:23:45 +00001058 if (!Invocation)
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001059 return true;
Rafael Espindola32482082014-08-18 16:23:45 +00001060
Daniel Dunbar764c0822009-12-01 09:51:01 +00001061 // Create the compiler instance to use for building the AST.
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001062 std::unique_ptr<CompilerInstance> Clang(
Benjamin Kramerd6da1a02016-06-12 20:05:23 +00001063 new CompilerInstance(std::move(PCHContainerOps)));
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001064 if (FileMgr && VFS) {
1065 assert(VFS == FileMgr->getVirtualFileSystem() &&
1066 "VFS passed to Parse and VFS in FileMgr are different");
1067 } else if (VFS) {
1068 Clang->setVirtualFileSystem(VFS);
1069 }
Ted Kremenek84de4a12011-03-21 18:40:07 +00001070
1071 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00001072 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1073 CICleanup(Clang.get());
Ted Kremenek84de4a12011-03-21 18:40:07 +00001074
David Blaikieea4395e2017-01-06 19:49:01 +00001075 Clang->setInvocation(std::make_shared<CompilerInvocation>(*Invocation));
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001076 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001077
Douglas Gregor8e984da2010-08-04 16:47:14 +00001078 // Set up diagnostics, capturing any diagnostics that would
1079 // otherwise be dropped.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001080 Clang->setDiagnostics(&getDiagnostics());
Douglas Gregord03e8232010-04-05 21:10:19 +00001081
Daniel Dunbar764c0822009-12-01 09:51:01 +00001082 // Create the target instance.
Alp Toker80758082014-07-06 05:26:44 +00001083 Clang->setTarget(TargetInfo::CreateTargetInfo(
Saleem Abdulrasool10a49722016-04-08 16:52:00 +00001084 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
Rafael Espindola32482082014-08-18 16:23:45 +00001085 if (!Clang->hasTarget())
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001086 return true;
Douglas Gregora0734c52010-08-19 01:33:06 +00001087
Daniel Dunbar764c0822009-12-01 09:51:01 +00001088 // Inform the target of the language options.
1089 //
1090 // FIXME: We shouldn't need to do this, the target should be immutable once
1091 // created. This complexity should be lifted elsewhere.
Alp Toker74437972014-07-06 05:14:24 +00001092 Clang->getTarget().adjust(Clang->getLangOpts());
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001093
Ted Kremenek84de4a12011-03-21 18:40:07 +00001094 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Daniel Dunbar764c0822009-12-01 09:51:01 +00001095 "Invocation must have exactly one source file!");
Richard Smith40c0efa2017-04-26 18:57:40 +00001096 assert(Clang->getFrontendOpts().Inputs[0].getKind().getFormat() ==
1097 InputKind::Source &&
Daniel Dunbar764c0822009-12-01 09:51:01 +00001098 "FIXME: AST inputs not yet supported here!");
Richard Smith40c0efa2017-04-26 18:57:40 +00001099 assert(Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() !=
1100 InputKind::LLVM_IR &&
Daniel Dunbar9507f9c2010-06-07 23:26:47 +00001101 "IR inputs not support here!");
Daniel Dunbar764c0822009-12-01 09:51:01 +00001102
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001103 // Configure the various subsystems.
Alp Toker269d8402014-07-06 05:26:07 +00001104 LangOpts = Clang->getInvocation().LangOpts;
Ted Kremenek84de4a12011-03-21 18:40:07 +00001105 FileSystemOpts = Clang->getFileSystemOpts();
Benjamin Kramerbc632902015-10-06 14:45:20 +00001106 if (!FileMgr) {
1107 Clang->createFileManager();
1108 FileMgr = &Clang->getFileManager();
1109 }
Erik Verbruggen346066b2017-05-30 14:25:54 +00001110
1111 ResetForParse();
1112
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +00001113 SourceMgr = new SourceManager(getDiagnostics(), *FileMgr,
1114 UserFilesAreVolatile);
Douglas Gregor7b02b582010-08-20 00:02:33 +00001115 if (!OverrideMainBuffer) {
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +00001116 checkAndRemoveNonDriverDiags(StoredDiagnostics);
Douglas Gregor7b02b582010-08-20 00:02:33 +00001117 TopLevelDeclsInPreamble.clear();
1118 }
1119
Daniel Dunbar764c0822009-12-01 09:51:01 +00001120 // Create a file manager object to provide access to and cache the filesystem.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001121 Clang->setFileManager(&getFileManager());
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001122
Daniel Dunbar764c0822009-12-01 09:51:01 +00001123 // Create the source manager.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001124 Clang->setSourceManager(&getSourceManager());
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001125
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001126 // If the main file has been overridden due to the use of a preamble,
1127 // make that override happen and introduce the preamble.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001128 PreprocessorOptions &PreprocessorOpts = Clang->getPreprocessorOpts();
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001129 if (OverrideMainBuffer) {
Rafael Espindola32482082014-08-18 16:23:45 +00001130 PreprocessorOpts.addRemappedFile(OriginalSourceFile,
1131 OverrideMainBuffer.get());
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001132 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
1133 PreprocessorOpts.PrecompiledPreambleBytes.second
1134 = PreambleEndsAtStartOfLine;
Ted Kremenek06b4f912011-10-27 17:55:18 +00001135 PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
Douglas Gregorce3a8292010-07-27 00:27:13 +00001136 PreprocessorOpts.DisablePCHValidation = true;
Douglas Gregor96c04262010-07-27 14:52:07 +00001137
Douglas Gregord9a30af2010-08-02 20:51:39 +00001138 // The stored diagnostic has the old source manager in it; update
1139 // the locations to refer into the new source manager. Since we've
1140 // been careful to make sure that the source manager's state
1141 // before and after are identical, so that we can reuse the source
1142 // location itself.
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +00001143 checkAndSanitizeDiags(StoredDiagnostics, getSourceManager());
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001144
1145 // Keep track of the override buffer;
Rafael Espindola32482082014-08-18 16:23:45 +00001146 SavedMainFileBuffer = std::move(OverrideMainBuffer);
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001147 }
Ahmed Charlesb8984322014-03-07 20:03:18 +00001148
1149 std::unique_ptr<TopLevelDeclTrackerAction> Act(
1150 new TopLevelDeclTrackerAction(*this));
1151
Ted Kremenek022a4902011-03-22 01:15:24 +00001152 // Recover resources if we crash before exiting this method.
1153 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1154 ActCleanup(Act.get());
1155
Douglas Gregor32fbe312012-01-20 16:28:04 +00001156 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0]))
Daniel Dunbar764c0822009-12-01 09:51:01 +00001157 goto error;
Douglas Gregor925296b2011-07-19 16:10:42 +00001158
Richard Smith26b8f782016-03-25 21:46:44 +00001159 if (SavedMainFileBuffer)
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001160 TranslateStoredDiagnostics(getFileManager(), getSourceManager(),
1161 PreambleDiagnostics, StoredDiagnostics);
Erik Verbruggenefe6fa52017-06-09 08:29:58 +00001162 else
1163 PreambleSrcLocCache.clear();
Douglas Gregor925296b2011-07-19 16:10:42 +00001164
Argyrios Kyrtzidis1416e172012-06-08 05:48:06 +00001165 if (!Act->Execute())
1166 goto error;
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001167
1168 transferASTDataFromCompilerInstance(*Clang);
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001169
Daniel Dunbar644dca02009-12-04 08:17:33 +00001170 Act->EndSourceFile();
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001171
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001172 FailedParseDiagnostics.clear();
1173
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001174 return false;
Ted Kremenek5e14d392011-03-21 18:40:17 +00001175
Daniel Dunbar764c0822009-12-01 09:51:01 +00001176error:
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001177 // Remove the overridden buffer we used for the preamble.
Rafael Espindola32482082014-08-18 16:23:45 +00001178 SavedMainFileBuffer = nullptr;
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001179
1180 // Keep the ownership of the data in the ASTUnit because the client may
1181 // want to see the diagnostics.
1182 transferASTDataFromCompilerInstance(*Clang);
1183 FailedParseDiagnostics.swap(StoredDiagnostics);
Douglas Gregorefc46952010-10-12 16:25:54 +00001184 StoredDiagnostics.clear();
Argyrios Kyrtzidis067cbfa2011-10-24 17:25:20 +00001185 NumStoredDiagnosticsFromDriver = 0;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001186 return true;
1187}
1188
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001189/// \brief Simple function to retrieve a path for a preamble precompiled header.
1190static std::string GetPreamblePCHPath() {
Douglas Gregor250ab1d2010-09-11 18:05:19 +00001191 // FIXME: This is a hack so that we can override the preamble file during
1192 // crash-recovery testing, which is the only case where the preamble files
Rafael Espindolabc4aa552013-06-26 04:02:37 +00001193 // are not necessarily cleaned up.
Douglas Gregor250ab1d2010-09-11 18:05:19 +00001194 const char *TmpFile = ::getenv("CINDEXTEST_PREAMBLE_FILE");
1195 if (TmpFile)
1196 return TmpFile;
Rafael Espindolabc4aa552013-06-26 04:02:37 +00001197
1198 SmallString<128> Path;
Rafael Espindolaa36e78e2013-07-05 20:00:06 +00001199 llvm::sys::fs::createTemporaryFile("preamble", "pch", Path);
Rafael Espindolabc4aa552013-06-26 04:02:37 +00001200
1201 return Path.str();
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001202}
1203
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001204/// \brief Compute the preamble for the main file, providing the source buffer
1205/// that corresponds to the main file along with a pair (bytes, start-of-line)
1206/// that describes the preamble.
David Blaikied6902a12014-08-29 06:34:53 +00001207ASTUnit::ComputedPreamble
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001208ASTUnit::ComputePreamble(CompilerInvocation &Invocation, unsigned MaxLines,
1209 IntrusiveRefCntPtr<vfs::FileSystem> VFS) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001210 FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
Chris Lattner5159f612010-11-23 08:35:12 +00001211 PreprocessorOptions &PreprocessorOpts = Invocation.getPreprocessorOpts();
Douglas Gregor4dde7492010-07-23 23:58:40 +00001212
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001213 // Try to determine if the main file has been remapped, either from the
1214 // command line (to another file) or directly through the compiler invocation
1215 // (to a memory buffer).
Craig Topper49a27902014-05-22 04:46:25 +00001216 llvm::MemoryBuffer *Buffer = nullptr;
David Blaikied6902a12014-08-29 06:34:53 +00001217 std::unique_ptr<llvm::MemoryBuffer> BufferOwner;
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00001218 std::string MainFilePath(FrontendOpts.Inputs[0].getFile());
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001219 auto MainFileStatus = VFS->status(MainFilePath);
1220 if (MainFileStatus) {
1221 llvm::sys::fs::UniqueID MainFileID = MainFileStatus->getUniqueID();
1222
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001223 // Check whether there is a file-file remapping of the main file
Alp Toker1b070d22014-07-07 07:47:20 +00001224 for (const auto &RF : PreprocessorOpts.RemappedFiles) {
1225 std::string MPath(RF.first);
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001226 auto MPathStatus = VFS->status(MPath);
1227 if (MPathStatus) {
1228 llvm::sys::fs::UniqueID MID = MPathStatus->getUniqueID();
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00001229 if (MainFileID == MID) {
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001230 // We found a remapping. Try to load the resulting, remapped source.
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001231 BufferOwner = valueOrNull(VFS->getBufferForFile(RF.second));
David Blaikied6902a12014-08-29 06:34:53 +00001232 if (!BufferOwner)
1233 return ComputedPreamble(nullptr, nullptr, 0, true);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001234 }
1235 }
1236 }
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001237
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001238 // Check whether there is a file-buffer remapping. It supercedes the
1239 // file-file remapping.
Alp Toker1b070d22014-07-07 07:47:20 +00001240 for (const auto &RB : PreprocessorOpts.RemappedFileBuffers) {
1241 std::string MPath(RB.first);
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001242 auto MPathStatus = VFS->status(MPath);
1243 if (MPathStatus) {
1244 llvm::sys::fs::UniqueID MID = MPathStatus->getUniqueID();
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00001245 if (MainFileID == MID) {
1246 // We found a remapping.
David Blaikied6902a12014-08-29 06:34:53 +00001247 BufferOwner.reset();
Alp Toker1b070d22014-07-07 07:47:20 +00001248 Buffer = const_cast<llvm::MemoryBuffer *>(RB.second);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001249 }
1250 }
Douglas Gregor4dde7492010-07-23 23:58:40 +00001251 }
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001252 }
1253
1254 // If the main source file was not remapped, load it now.
David Blaikied6902a12014-08-29 06:34:53 +00001255 if (!Buffer && !BufferOwner) {
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001256 BufferOwner = valueOrNull(VFS->getBufferForFile(FrontendOpts.Inputs[0].getFile()));
David Blaikied6902a12014-08-29 06:34:53 +00001257 if (!BufferOwner)
1258 return ComputedPreamble(nullptr, nullptr, 0, true);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001259 }
David Blaikie3d95d852014-08-11 22:08:06 +00001260
David Blaikied6902a12014-08-29 06:34:53 +00001261 if (!Buffer)
1262 Buffer = BufferOwner.get();
1263 auto Pre = Lexer::ComputePreamble(Buffer->getBuffer(),
1264 *Invocation.getLangOpts(), MaxLines);
1265 return ComputedPreamble(Buffer, std::move(BufferOwner), Pre.first,
1266 Pre.second);
Douglas Gregor4dde7492010-07-23 23:58:40 +00001267}
1268
Dmitri Gribenko47652522013-12-20 00:16:25 +00001269ASTUnit::PreambleFileHash
1270ASTUnit::PreambleFileHash::createForFile(off_t Size, time_t ModTime) {
1271 PreambleFileHash Result;
1272 Result.Size = Size;
1273 Result.ModTime = ModTime;
Zachary Turner82a0c972017-03-20 23:33:18 +00001274 Result.MD5 = {};
Dmitri Gribenko47652522013-12-20 00:16:25 +00001275 return Result;
1276}
1277
1278ASTUnit::PreambleFileHash ASTUnit::PreambleFileHash::createForMemoryBuffer(
1279 const llvm::MemoryBuffer *Buffer) {
1280 PreambleFileHash Result;
1281 Result.Size = Buffer->getBufferSize();
1282 Result.ModTime = 0;
1283
1284 llvm::MD5 MD5Ctx;
1285 MD5Ctx.update(Buffer->getBuffer().data());
1286 MD5Ctx.final(Result.MD5);
1287
1288 return Result;
1289}
1290
1291namespace clang {
1292bool operator==(const ASTUnit::PreambleFileHash &LHS,
1293 const ASTUnit::PreambleFileHash &RHS) {
1294 return LHS.Size == RHS.Size && LHS.ModTime == RHS.ModTime &&
Zachary Turner82a0c972017-03-20 23:33:18 +00001295 LHS.MD5 == RHS.MD5;
Dmitri Gribenko47652522013-12-20 00:16:25 +00001296}
1297} // namespace clang
1298
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001299static std::pair<unsigned, unsigned>
1300makeStandaloneRange(CharSourceRange Range, const SourceManager &SM,
1301 const LangOptions &LangOpts) {
1302 CharSourceRange FileRange = Lexer::makeFileCharRange(Range, SM, LangOpts);
1303 unsigned Offset = SM.getFileOffset(FileRange.getBegin());
1304 unsigned EndOffset = SM.getFileOffset(FileRange.getEnd());
1305 return std::make_pair(Offset, EndOffset);
1306}
1307
Benjamin Kramer1a6e0a92014-10-03 18:52:54 +00001308static ASTUnit::StandaloneFixIt makeStandaloneFixIt(const SourceManager &SM,
1309 const LangOptions &LangOpts,
1310 const FixItHint &InFix) {
1311 ASTUnit::StandaloneFixIt OutFix;
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001312 OutFix.RemoveRange = makeStandaloneRange(InFix.RemoveRange, SM, LangOpts);
1313 OutFix.InsertFromRange = makeStandaloneRange(InFix.InsertFromRange, SM,
1314 LangOpts);
1315 OutFix.CodeToInsert = InFix.CodeToInsert;
1316 OutFix.BeforePreviousInsertions = InFix.BeforePreviousInsertions;
Benjamin Kramer1a6e0a92014-10-03 18:52:54 +00001317 return OutFix;
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001318}
1319
Benjamin Kramer1a6e0a92014-10-03 18:52:54 +00001320static ASTUnit::StandaloneDiagnostic
1321makeStandaloneDiagnostic(const LangOptions &LangOpts,
1322 const StoredDiagnostic &InDiag) {
1323 ASTUnit::StandaloneDiagnostic OutDiag;
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001324 OutDiag.ID = InDiag.getID();
1325 OutDiag.Level = InDiag.getLevel();
1326 OutDiag.Message = InDiag.getMessage();
1327 OutDiag.LocOffset = 0;
1328 if (InDiag.getLocation().isInvalid())
Benjamin Kramer1a6e0a92014-10-03 18:52:54 +00001329 return OutDiag;
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001330 const SourceManager &SM = InDiag.getLocation().getManager();
1331 SourceLocation FileLoc = SM.getFileLoc(InDiag.getLocation());
1332 OutDiag.Filename = SM.getFilename(FileLoc);
1333 if (OutDiag.Filename.empty())
Benjamin Kramer1a6e0a92014-10-03 18:52:54 +00001334 return OutDiag;
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001335 OutDiag.LocOffset = SM.getFileOffset(FileLoc);
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00001336 for (const CharSourceRange &Range : InDiag.getRanges())
1337 OutDiag.Ranges.push_back(makeStandaloneRange(Range, SM, LangOpts));
1338 for (const FixItHint &FixIt : InDiag.getFixIts())
1339 OutDiag.FixIts.push_back(makeStandaloneFixIt(SM, LangOpts, FixIt));
Benjamin Kramer1a6e0a92014-10-03 18:52:54 +00001340
1341 return OutDiag;
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001342}
1343
Douglas Gregor4dde7492010-07-23 23:58:40 +00001344/// \brief Attempt to build or re-use a precompiled preamble when (re-)parsing
1345/// the source file.
1346///
1347/// This routine will compute the preamble of the main source file. If a
1348/// non-trivial preamble is found, it will precompile that preamble into a
1349/// precompiled header so that the precompiled preamble can be used to reduce
1350/// reparsing time. If a precompiled preamble has already been constructed,
1351/// this routine will determine if it is still valid and, if so, avoid
1352/// rebuilding the precompiled preamble.
1353///
Douglas Gregor028d3e42010-08-09 20:45:32 +00001354/// \param AllowRebuild When true (the default), this routine is
1355/// allowed to rebuild the precompiled preamble if it is found to be
1356/// out-of-date.
1357///
1358/// \param MaxLines When non-zero, the maximum number of lines that
1359/// can occur within the preamble.
1360///
Douglas Gregor6481ef12010-07-24 00:38:13 +00001361/// \returns If the precompiled preamble can be used, returns a newly-allocated
1362/// buffer that should be used in place of the main file when doing so.
1363/// Otherwise, returns a NULL pointer.
Rafael Espindola2346a372014-08-18 18:47:08 +00001364std::unique_ptr<llvm::MemoryBuffer>
1365ASTUnit::getMainBufferWithPrecompiledPreamble(
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001366 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001367 const CompilerInvocation &PreambleInvocationIn,
1368 IntrusiveRefCntPtr<vfs::FileSystem> VFS, bool AllowRebuild,
Rafael Espindola2346a372014-08-18 18:47:08 +00001369 unsigned MaxLines) {
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001370 assert(VFS && "VFS is null");
Rafael Espindola2346a372014-08-18 18:47:08 +00001371
David Blaikieea4395e2017-01-06 19:49:01 +00001372 auto PreambleInvocation =
1373 std::make_shared<CompilerInvocation>(PreambleInvocationIn);
Douglas Gregor3cc15812011-07-01 18:22:13 +00001374 FrontendOptions &FrontendOpts = PreambleInvocation->getFrontendOpts();
Douglas Gregor4dde7492010-07-23 23:58:40 +00001375 PreprocessorOptions &PreprocessorOpts
Douglas Gregor3cc15812011-07-01 18:22:13 +00001376 = PreambleInvocation->getPreprocessorOpts();
Douglas Gregor4dde7492010-07-23 23:58:40 +00001377
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001378 ComputedPreamble NewPreamble =
1379 ComputePreamble(*PreambleInvocation, MaxLines, VFS);
Douglas Gregor4dde7492010-07-23 23:58:40 +00001380
David Blaikied6902a12014-08-29 06:34:53 +00001381 if (!NewPreamble.Size) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001382 // We couldn't find a preamble in the main source. Clear out the current
1383 // preamble, if we have one. It's obviously no good any more.
1384 Preamble.clear();
Ted Kremenek06b4f912011-10-27 17:55:18 +00001385 erasePreambleFile(this);
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001386
1387 // The next time we actually see a preamble, precompile it.
1388 PreambleRebuildCounter = 1;
Craig Topper49a27902014-05-22 04:46:25 +00001389 return nullptr;
Douglas Gregor4dde7492010-07-23 23:58:40 +00001390 }
1391
1392 if (!Preamble.empty()) {
1393 // We've previously computed a preamble. Check whether we have the same
1394 // preamble now that we did before, and that there's enough space in
1395 // the main-file buffer within the precompiled preamble to fit the
1396 // new main file.
David Blaikied6902a12014-08-29 06:34:53 +00001397 if (Preamble.size() == NewPreamble.Size &&
1398 PreambleEndsAtStartOfLine == NewPreamble.PreambleEndsAtStartOfLine &&
1399 memcmp(Preamble.getBufferStart(), NewPreamble.Buffer->getBufferStart(),
1400 NewPreamble.Size) == 0) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001401 // The preamble has not changed. We may be able to re-use the precompiled
1402 // preamble.
Douglas Gregord9a30af2010-08-02 20:51:39 +00001403
Douglas Gregor0e119552010-07-31 00:40:00 +00001404 // Check that none of the files used by the preamble have changed.
1405 bool AnyFileChanged = false;
1406
1407 // First, make a record of those files that have been overridden via
1408 // remapping or unsaved_files.
Cameron Desrochers6fffec32016-05-17 14:34:53 +00001409 std::map<llvm::sys::fs::UniqueID, PreambleFileHash> OverriddenFiles;
Alp Toker1b070d22014-07-07 07:47:20 +00001410 for (const auto &R : PreprocessorOpts.RemappedFiles) {
1411 if (AnyFileChanged)
1412 break;
1413
Ben Langmuirc8130a72014-02-20 21:59:23 +00001414 vfs::Status Status;
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001415 if (!moveOnNoError(VFS->status(R.second), Status)) {
Douglas Gregor0e119552010-07-31 00:40:00 +00001416 // If we can't stat the file we're remapping to, assume that something
1417 // horrible happened.
1418 AnyFileChanged = true;
1419 break;
1420 }
Rafael Espindolae4777f42013-07-29 18:22:23 +00001421
Cameron Desrochers6fffec32016-05-17 14:34:53 +00001422 OverriddenFiles[Status.getUniqueID()] = PreambleFileHash::createForFile(
Pavel Labathac71c8e2016-11-09 10:52:22 +00001423 Status.getSize(),
1424 llvm::sys::toTimeT(Status.getLastModificationTime()));
Douglas Gregor0e119552010-07-31 00:40:00 +00001425 }
Alp Toker1b070d22014-07-07 07:47:20 +00001426
1427 for (const auto &RB : PreprocessorOpts.RemappedFileBuffers) {
1428 if (AnyFileChanged)
1429 break;
Cameron Desrochers6fffec32016-05-17 14:34:53 +00001430
1431 vfs::Status Status;
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001432 if (!moveOnNoError(VFS->status(RB.first), Status)) {
Cameron Desrochers6fffec32016-05-17 14:34:53 +00001433 AnyFileChanged = true;
1434 break;
1435 }
1436
1437 OverriddenFiles[Status.getUniqueID()] =
Alp Toker1b070d22014-07-07 07:47:20 +00001438 PreambleFileHash::createForMemoryBuffer(RB.second);
Douglas Gregor0e119552010-07-31 00:40:00 +00001439 }
1440
1441 // Check whether anything has changed.
Cameron Desrochers6fffec32016-05-17 14:34:53 +00001442 for (llvm::StringMap<PreambleFileHash>::iterator
Douglas Gregor0e119552010-07-31 00:40:00 +00001443 F = FilesInPreamble.begin(), FEnd = FilesInPreamble.end();
1444 !AnyFileChanged && F != FEnd;
1445 ++F) {
Cameron Desrochers6fffec32016-05-17 14:34:53 +00001446 vfs::Status Status;
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001447 if (!moveOnNoError(VFS->status(F->first()), Status)) {
Cameron Desrochers6fffec32016-05-17 14:34:53 +00001448 // If we can't stat the file, assume that something horrible happened.
1449 AnyFileChanged = true;
1450 break;
1451 }
1452
1453 std::map<llvm::sys::fs::UniqueID, PreambleFileHash>::iterator Overridden
1454 = OverriddenFiles.find(Status.getUniqueID());
Douglas Gregor0e119552010-07-31 00:40:00 +00001455 if (Overridden != OverriddenFiles.end()) {
1456 // This file was remapped; check whether the newly-mapped file
1457 // matches up with the previous mapping.
1458 if (Overridden->second != F->second)
1459 AnyFileChanged = true;
1460 continue;
1461 }
1462
1463 // The file was not remapped; check whether it has changed on disk.
Cameron Desrochers6fffec32016-05-17 14:34:53 +00001464 if (Status.getSize() != uint64_t(F->second.Size) ||
Pavel Labathac71c8e2016-11-09 10:52:22 +00001465 llvm::sys::toTimeT(Status.getLastModificationTime()) !=
1466 F->second.ModTime)
Douglas Gregor0e119552010-07-31 00:40:00 +00001467 AnyFileChanged = true;
1468 }
1469
1470 if (!AnyFileChanged) {
Douglas Gregord9a30af2010-08-02 20:51:39 +00001471 // Okay! We can re-use the precompiled preamble.
1472
1473 // Set the state of the diagnostic object to mimic its state
1474 // after parsing the preamble.
1475 getDiagnostics().Reset();
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00001476 ProcessWarningOptions(getDiagnostics(),
Douglas Gregor3cc15812011-07-01 18:22:13 +00001477 PreambleInvocation->getDiagnosticOpts());
Douglas Gregord9a30af2010-08-02 20:51:39 +00001478 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
Douglas Gregord9a30af2010-08-02 20:51:39 +00001479
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001480 return llvm::MemoryBuffer::getMemBufferCopy(
David Blaikied6902a12014-08-29 06:34:53 +00001481 NewPreamble.Buffer->getBuffer(), FrontendOpts.Inputs[0].getFile());
Douglas Gregor0e119552010-07-31 00:40:00 +00001482 }
Douglas Gregor4dde7492010-07-23 23:58:40 +00001483 }
Douglas Gregor028d3e42010-08-09 20:45:32 +00001484
1485 // If we aren't allowed to rebuild the precompiled preamble, just
1486 // return now.
1487 if (!AllowRebuild)
Craig Topper49a27902014-05-22 04:46:25 +00001488 return nullptr;
Douglas Gregorbb6a8812010-10-08 04:03:57 +00001489
Douglas Gregor4dde7492010-07-23 23:58:40 +00001490 // We can't reuse the previously-computed preamble. Build a new one.
1491 Preamble.clear();
Douglas Gregor925296b2011-07-19 16:10:42 +00001492 PreambleDiagnostics.clear();
Ted Kremenek06b4f912011-10-27 17:55:18 +00001493 erasePreambleFile(this);
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001494 PreambleRebuildCounter = 1;
Douglas Gregor028d3e42010-08-09 20:45:32 +00001495 } else if (!AllowRebuild) {
1496 // We aren't allowed to rebuild the precompiled preamble; just
1497 // return now.
Craig Topper49a27902014-05-22 04:46:25 +00001498 return nullptr;
Douglas Gregor028d3e42010-08-09 20:45:32 +00001499 }
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001500
1501 // If the preamble rebuild counter > 1, it's because we previously
1502 // failed to build a preamble and we're not yet ready to try
1503 // again. Decrement the counter and return a failure.
1504 if (PreambleRebuildCounter > 1) {
1505 --PreambleRebuildCounter;
Craig Topper49a27902014-05-22 04:46:25 +00001506 return nullptr;
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001507 }
1508
Douglas Gregore10f0e52010-09-11 17:56:52 +00001509 // Create a temporary file for the precompiled preamble. In rare
1510 // circumstances, this can fail.
1511 std::string PreamblePCHPath = GetPreamblePCHPath();
1512 if (PreamblePCHPath.empty()) {
1513 // Try again next time.
1514 PreambleRebuildCounter = 1;
Craig Topper49a27902014-05-22 04:46:25 +00001515 return nullptr;
Douglas Gregore10f0e52010-09-11 17:56:52 +00001516 }
1517
Douglas Gregor4dde7492010-07-23 23:58:40 +00001518 // We did not previously compute a preamble, or it can't be reused anyway.
Douglas Gregor16896c42010-10-28 15:44:59 +00001519 SimpleTimer PreambleTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00001520 PreambleTimer.setOutput("Precompiling preamble");
Douglas Gregor4dde7492010-07-23 23:58:40 +00001521
Douglas Gregord9a30af2010-08-02 20:51:39 +00001522 // Save the preamble text for later; we'll need to compare against it for
1523 // subsequent reparses.
Dmitri Gribenko40798d32013-12-19 23:25:59 +00001524 StringRef MainFilename = FrontendOpts.Inputs[0].getFile();
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00001525 Preamble.assign(FileMgr->getFile(MainFilename),
David Blaikied6902a12014-08-29 06:34:53 +00001526 NewPreamble.Buffer->getBufferStart(),
1527 NewPreamble.Buffer->getBufferStart() + NewPreamble.Size);
1528 PreambleEndsAtStartOfLine = NewPreamble.PreambleEndsAtStartOfLine;
Douglas Gregord9a30af2010-08-02 20:51:39 +00001529
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001530 PreambleBuffer = llvm::MemoryBuffer::getMemBufferCopy(
David Blaikied6902a12014-08-29 06:34:53 +00001531 NewPreamble.Buffer->getBuffer().slice(0, Preamble.size()), MainFilename);
Rafael Espindolaa96bd562013-06-26 04:12:57 +00001532
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001533 // Remap the main source file to the preamble buffer.
Rafael Espindolaa96bd562013-06-26 04:12:57 +00001534 StringRef MainFilePath = FrontendOpts.Inputs[0].getFile();
Rafael Espindolafa49c0b2014-08-13 16:47:00 +00001535 PreprocessorOpts.addRemappedFile(MainFilePath, PreambleBuffer.get());
Rafael Espindolaa96bd562013-06-26 04:12:57 +00001536
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001537 // Tell the compiler invocation to generate a temporary precompiled header.
1538 FrontendOpts.ProgramAction = frontend::GeneratePCH;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001539 // FIXME: Generate the precompiled header into memory?
Douglas Gregore10f0e52010-09-11 17:56:52 +00001540 FrontendOpts.OutputFile = PreamblePCHPath;
Douglas Gregorbb6a8812010-10-08 04:03:57 +00001541 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
1542 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001543
1544 // Create the compiler instance to use for building the precompiled preamble.
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001545 std::unique_ptr<CompilerInstance> Clang(
Benjamin Kramerd6da1a02016-06-12 20:05:23 +00001546 new CompilerInstance(std::move(PCHContainerOps)));
Ted Kremenek84de4a12011-03-21 18:40:07 +00001547
1548 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00001549 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1550 CICleanup(Clang.get());
Ted Kremenek84de4a12011-03-21 18:40:07 +00001551
David Blaikieea4395e2017-01-06 19:49:01 +00001552 Clang->setInvocation(std::move(PreambleInvocation));
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001553 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001554
Douglas Gregor8e984da2010-08-04 16:47:14 +00001555 // Set up diagnostics, capturing all of the diagnostics produced.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001556 Clang->setDiagnostics(&getDiagnostics());
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001557
1558 // Create the target instance.
Alp Toker80758082014-07-06 05:26:44 +00001559 Clang->setTarget(TargetInfo::CreateTargetInfo(
Saleem Abdulrasool10a49722016-04-08 16:52:00 +00001560 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
Ted Kremenek84de4a12011-03-21 18:40:07 +00001561 if (!Clang->hasTarget()) {
Rafael Espindolaf5e5bc42013-06-26 04:26:38 +00001562 llvm::sys::fs::remove(FrontendOpts.OutputFile);
Douglas Gregor4dde7492010-07-23 23:58:40 +00001563 Preamble.clear();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001564 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Alp Toker1b070d22014-07-07 07:47:20 +00001565 PreprocessorOpts.RemappedFileBuffers.pop_back();
Craig Topper49a27902014-05-22 04:46:25 +00001566 return nullptr;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001567 }
1568
1569 // Inform the target of the language options.
1570 //
1571 // FIXME: We shouldn't need to do this, the target should be immutable once
1572 // created. This complexity should be lifted elsewhere.
Alp Toker74437972014-07-06 05:14:24 +00001573 Clang->getTarget().adjust(Clang->getLangOpts());
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001574
Ted Kremenek84de4a12011-03-21 18:40:07 +00001575 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001576 "Invocation must have exactly one source file!");
Richard Smith40c0efa2017-04-26 18:57:40 +00001577 assert(Clang->getFrontendOpts().Inputs[0].getKind().getFormat() ==
1578 InputKind::Source &&
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001579 "FIXME: AST inputs not yet supported here!");
Richard Smith40c0efa2017-04-26 18:57:40 +00001580 assert(Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() !=
1581 InputKind::LLVM_IR &&
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001582 "IR inputs not support here!");
1583
1584 // Clear out old caches and data.
Douglas Gregorbb6a8812010-10-08 04:03:57 +00001585 getDiagnostics().Reset();
Ted Kremenek84de4a12011-03-21 18:40:07 +00001586 ProcessWarningOptions(getDiagnostics(), Clang->getDiagnosticOpts());
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +00001587 checkAndRemoveNonDriverDiags(StoredDiagnostics);
Douglas Gregore9db88f2010-08-03 19:06:41 +00001588 TopLevelDecls.clear();
1589 TopLevelDeclsInPreamble.clear();
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001590 PreambleDiagnostics.clear();
Ben Langmuir8832c062014-04-15 18:16:25 +00001591
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001592 VFS = createVFSFromCompilerInvocation(Clang->getInvocation(),
1593 getDiagnostics(), VFS);
Ben Langmuir8832c062014-04-15 18:16:25 +00001594 if (!VFS)
1595 return nullptr;
1596
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001597 // Create a file manager object to provide access to and cache the filesystem.
Ben Langmuir8832c062014-04-15 18:16:25 +00001598 Clang->setFileManager(new FileManager(Clang->getFileSystemOpts(), VFS));
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001599
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001600 // Create the source manager.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001601 Clang->setSourceManager(new SourceManager(getDiagnostics(),
Ted Kremenek5e14d392011-03-21 18:40:17 +00001602 Clang->getFileManager()));
Ahmed Charlesb8984322014-03-07 20:03:18 +00001603
Ben Langmuir33c80902014-06-30 20:04:14 +00001604 auto PreambleDepCollector = std::make_shared<DependencyCollector>();
1605 Clang->addDependencyCollector(PreambleDepCollector);
1606
Ahmed Charlesb8984322014-03-07 20:03:18 +00001607 std::unique_ptr<PrecompilePreambleAction> Act;
Douglas Gregor48c8cd32010-08-03 08:14:03 +00001608 Act.reset(new PrecompilePreambleAction(*this));
Douglas Gregor32fbe312012-01-20 16:28:04 +00001609 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
Rafael Espindolaf5e5bc42013-06-26 04:26:38 +00001610 llvm::sys::fs::remove(FrontendOpts.OutputFile);
Douglas Gregor4dde7492010-07-23 23:58:40 +00001611 Preamble.clear();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001612 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Alp Toker1b070d22014-07-07 07:47:20 +00001613 PreprocessorOpts.RemappedFileBuffers.pop_back();
Craig Topper49a27902014-05-22 04:46:25 +00001614 return nullptr;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001615 }
1616
1617 Act->Execute();
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001618
1619 // Transfer any diagnostics generated when parsing the preamble into the set
1620 // of preamble diagnostics.
Benjamin Kramer1a6e0a92014-10-03 18:52:54 +00001621 for (stored_diag_iterator I = stored_diag_afterDriver_begin(),
1622 E = stored_diag_end();
1623 I != E; ++I)
1624 PreambleDiagnostics.push_back(
1625 makeStandaloneDiagnostic(Clang->getLangOpts(), *I));
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001626
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001627 Act->EndSourceFile();
Ted Kremenek5e14d392011-03-21 18:40:17 +00001628
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001629 checkAndRemoveNonDriverDiags(StoredDiagnostics);
1630
Argyrios Kyrtzidisf0168de2013-06-11 00:36:55 +00001631 if (!Act->hasEmittedPreamblePCH()) {
Argyrios Kyrtzidisd6f57222013-06-11 16:42:34 +00001632 // The preamble PCH failed (e.g. there was a module loading fatal error),
1633 // so no precompiled header was generated. Forget that we even tried.
Douglas Gregora6f74e22010-09-27 16:43:25 +00001634 // FIXME: Should we leave a note for ourselves to try again?
Rafael Espindolaf5e5bc42013-06-26 04:26:38 +00001635 llvm::sys::fs::remove(FrontendOpts.OutputFile);
Douglas Gregor4dde7492010-07-23 23:58:40 +00001636 Preamble.clear();
Douglas Gregore9db88f2010-08-03 19:06:41 +00001637 TopLevelDeclsInPreamble.clear();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001638 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Alp Toker1b070d22014-07-07 07:47:20 +00001639 PreprocessorOpts.RemappedFileBuffers.pop_back();
Craig Topper49a27902014-05-22 04:46:25 +00001640 return nullptr;
Douglas Gregor4dde7492010-07-23 23:58:40 +00001641 }
1642
1643 // Keep track of the preamble we precompiled.
Ted Kremenek06b4f912011-10-27 17:55:18 +00001644 setPreambleFile(this, FrontendOpts.OutputFile);
Douglas Gregord9a30af2010-08-02 20:51:39 +00001645 NumWarningsInPreamble = getDiagnostics().getNumWarnings();
Douglas Gregor0e119552010-07-31 00:40:00 +00001646
1647 // Keep track of all of the files that the source manager knows about,
1648 // so we can verify whether they have changed or not.
1649 FilesInPreamble.clear();
Ted Kremenek84de4a12011-03-21 18:40:07 +00001650 SourceManager &SourceMgr = Clang->getSourceManager();
Ben Langmuir33c80902014-06-30 20:04:14 +00001651 for (auto &Filename : PreambleDepCollector->getDependencies()) {
1652 const FileEntry *File = Clang->getFileManager().getFile(Filename);
1653 if (!File || File == SourceMgr.getFileEntryForID(SourceMgr.getMainFileID()))
Douglas Gregor0e119552010-07-31 00:40:00 +00001654 continue;
Dmitri Gribenko47652522013-12-20 00:16:25 +00001655 if (time_t ModTime = File->getModificationTime()) {
1656 FilesInPreamble[File->getName()] = PreambleFileHash::createForFile(
Ben Langmuir33c80902014-06-30 20:04:14 +00001657 File->getSize(), ModTime);
Dmitri Gribenko47652522013-12-20 00:16:25 +00001658 } else {
Ben Langmuir33c80902014-06-30 20:04:14 +00001659 llvm::MemoryBuffer *Buffer = SourceMgr.getMemoryBufferForFile(File);
Dmitri Gribenko47652522013-12-20 00:16:25 +00001660 FilesInPreamble[File->getName()] =
1661 PreambleFileHash::createForMemoryBuffer(Buffer);
1662 }
Douglas Gregor0e119552010-07-31 00:40:00 +00001663 }
Ben Langmuir33c80902014-06-30 20:04:14 +00001664
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001665 PreambleRebuildCounter = 1;
Alp Toker1b070d22014-07-07 07:47:20 +00001666 PreprocessorOpts.RemappedFileBuffers.pop_back();
1667
Douglas Gregordf7a79a2011-02-16 18:16:54 +00001668 // If the hash of top-level entities differs from the hash of the top-level
1669 // entities the last time we rebuilt the preamble, clear out the completion
1670 // cache.
1671 if (CurrentTopLevelHashValue != PreambleTopLevelHashValue) {
1672 CompletionCacheTopLevelHashValue = 0;
1673 PreambleTopLevelHashValue = CurrentTopLevelHashValue;
1674 }
Rafael Espindola2346a372014-08-18 18:47:08 +00001675
David Blaikied6902a12014-08-29 06:34:53 +00001676 return llvm::MemoryBuffer::getMemBufferCopy(NewPreamble.Buffer->getBuffer(),
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001677 MainFilename);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001678}
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001679
Douglas Gregore9db88f2010-08-03 19:06:41 +00001680void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
1681 std::vector<Decl *> Resolved;
1682 Resolved.reserve(TopLevelDeclsInPreamble.size());
1683 ExternalASTSource &Source = *getASTContext().getExternalSource();
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00001684 for (serialization::DeclID TopLevelDecl : TopLevelDeclsInPreamble) {
Douglas Gregore9db88f2010-08-03 19:06:41 +00001685 // Resolve the declaration ID to an actual declaration, possibly
1686 // deserializing the declaration in the process.
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00001687 if (Decl *D = Source.GetExternalDecl(TopLevelDecl))
Douglas Gregore9db88f2010-08-03 19:06:41 +00001688 Resolved.push_back(D);
1689 }
1690 TopLevelDeclsInPreamble.clear();
1691 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1692}
1693
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001694void ASTUnit::transferASTDataFromCompilerInstance(CompilerInstance &CI) {
Ben Langmuir749323f2014-04-22 17:40:12 +00001695 // Steal the created target, context, and preprocessor if they have been
1696 // created.
1697 assert(CI.hasInvocation() && "missing invocation");
Alp Toker269d8402014-07-06 05:26:07 +00001698 LangOpts = CI.getInvocation().LangOpts;
David Blaikieec99b5e2014-08-10 19:14:48 +00001699 TheSema = CI.takeSema();
David Blaikie6beb6aa2014-08-10 19:56:51 +00001700 Consumer = CI.takeASTConsumer();
Ben Langmuir532fdc02014-04-18 20:39:48 +00001701 if (CI.hasASTContext())
1702 Ctx = &CI.getASTContext();
1703 if (CI.hasPreprocessor())
David Blaikie41565462017-01-05 19:48:07 +00001704 PP = CI.getPreprocessorPtr();
Craig Topper49a27902014-05-22 04:46:25 +00001705 CI.setSourceManager(nullptr);
1706 CI.setFileManager(nullptr);
Ben Langmuir532fdc02014-04-18 20:39:48 +00001707 if (CI.hasTarget())
1708 Target = &CI.getTarget();
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001709 Reader = CI.getModuleManager();
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00001710 HadModuleLoaderFatalFailure = CI.hadModuleLoaderFatalFailure();
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001711}
1712
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001713StringRef ASTUnit::getMainFileName() const {
Argyrios Kyrtzidis928e1fd2013-01-11 22:11:14 +00001714 if (Invocation && !Invocation->getFrontendOpts().Inputs.empty()) {
1715 const FrontendInputFile &Input = Invocation->getFrontendOpts().Inputs[0];
1716 if (Input.isFile())
1717 return Input.getFile();
1718 else
1719 return Input.getBuffer()->getBufferIdentifier();
1720 }
1721
1722 if (SourceMgr) {
1723 if (const FileEntry *
1724 FE = SourceMgr->getFileEntryForID(SourceMgr->getMainFileID()))
1725 return FE->getName();
1726 }
1727
1728 return StringRef();
Douglas Gregor16896c42010-10-28 15:44:59 +00001729}
1730
Argyrios Kyrtzidis37f2ab42013-03-05 20:21:14 +00001731StringRef ASTUnit::getASTFileName() const {
1732 if (!isMainFileAST())
1733 return StringRef();
1734
1735 serialization::ModuleFile &
1736 Mod = Reader->getModuleManager().getPrimaryModule();
1737 return Mod.FileName;
1738}
1739
David Blaikieea4395e2017-01-06 19:49:01 +00001740std::unique_ptr<ASTUnit>
1741ASTUnit::create(std::shared_ptr<CompilerInvocation> CI,
1742 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
1743 bool CaptureDiagnostics, bool UserFilesAreVolatile) {
1744 std::unique_ptr<ASTUnit> AST(new ASTUnit(false));
Justin Bognerdbbcb112014-10-14 23:36:06 +00001745 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
Ben Langmuir8832c062014-04-15 18:16:25 +00001746 IntrusiveRefCntPtr<vfs::FileSystem> VFS =
1747 createVFSFromCompilerInvocation(*CI, *Diags);
1748 if (!VFS)
1749 return nullptr;
David Blaikieea4395e2017-01-06 19:49:01 +00001750 AST->Diagnostics = Diags;
1751 AST->FileSystemOpts = CI->getFileSystemOpts();
1752 AST->Invocation = std::move(CI);
Ben Langmuir8832c062014-04-15 18:16:25 +00001753 AST->FileMgr = new FileManager(AST->FileSystemOpts, VFS);
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +00001754 AST->UserFilesAreVolatile = UserFilesAreVolatile;
1755 AST->SourceMgr = new SourceManager(AST->getDiagnostics(), *AST->FileMgr,
1756 UserFilesAreVolatile);
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00001757 AST->PCMCache = new MemoryBufferCache;
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00001758
David Blaikieea4395e2017-01-06 19:49:01 +00001759 return AST;
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00001760}
1761
Ahmed Charlesb8984322014-03-07 20:03:18 +00001762ASTUnit *ASTUnit::LoadFromCompilerInvocationAction(
David Blaikieea4395e2017-01-06 19:49:01 +00001763 std::shared_ptr<CompilerInvocation> CI,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001764 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
Argyrios Kyrtzidisc382abf2016-02-09 19:07:13 +00001765 IntrusiveRefCntPtr<DiagnosticsEngine> Diags, FrontendAction *Action,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001766 ASTUnit *Unit, bool Persistent, StringRef ResourceFilesPath,
Benjamin Kramer5c248d82015-12-15 09:30:31 +00001767 bool OnlyLocalDecls, bool CaptureDiagnostics,
1768 unsigned PrecompilePreambleAfterNParses, bool CacheCodeCompletionResults,
1769 bool IncludeBriefCommentsInCodeCompletion, bool UserFilesAreVolatile,
1770 std::unique_ptr<ASTUnit> *ErrAST) {
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001771 assert(CI && "A CompilerInvocation is required");
1772
Ahmed Charlesb8984322014-03-07 20:03:18 +00001773 std::unique_ptr<ASTUnit> OwnAST;
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001774 ASTUnit *AST = Unit;
1775 if (!AST) {
1776 // Create the AST unit.
David Blaikieea4395e2017-01-06 19:49:01 +00001777 OwnAST = create(CI, Diags, CaptureDiagnostics, UserFilesAreVolatile);
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001778 AST = OwnAST.get();
Ben Langmuir8832c062014-04-15 18:16:25 +00001779 if (!AST)
1780 return nullptr;
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001781 }
1782
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00001783 if (!ResourceFilesPath.empty()) {
1784 // Override the resources path.
1785 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
1786 }
1787 AST->OnlyLocalDecls = OnlyLocalDecls;
1788 AST->CaptureDiagnostics = CaptureDiagnostics;
Benjamin Kramer5c248d82015-12-15 09:30:31 +00001789 if (PrecompilePreambleAfterNParses > 0)
1790 AST->PreambleRebuildCounter = PrecompilePreambleAfterNParses;
Douglas Gregor69f74f82011-08-25 22:30:56 +00001791 AST->TUKind = Action ? Action->getTranslationUnitKind() : TU_Complete;
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00001792 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenko3292d062012-07-02 17:35:10 +00001793 AST->IncludeBriefCommentsInCodeCompletion
1794 = IncludeBriefCommentsInCodeCompletion;
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001795
1796 // Recover resources if we crash before exiting this method.
1797 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001798 ASTUnitCleanup(OwnAST.get());
David Blaikie9c902b52011-09-25 23:23:43 +00001799 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1800 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Alp Tokerf994cef2014-07-05 03:08:06 +00001801 DiagCleanup(Diags.get());
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001802
1803 // We'll manage file buffers ourselves.
1804 CI->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1805 CI->getFrontendOpts().DisableFree = false;
1806 ProcessWarningOptions(AST->getDiagnostics(), CI->getDiagnosticOpts());
1807
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001808 // Create the compiler instance to use for building the AST.
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001809 std::unique_ptr<CompilerInstance> Clang(
Benjamin Kramerd6da1a02016-06-12 20:05:23 +00001810 new CompilerInstance(std::move(PCHContainerOps)));
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001811
1812 // Recover resources if we crash before exiting this method.
1813 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1814 CICleanup(Clang.get());
1815
David Blaikieea4395e2017-01-06 19:49:01 +00001816 Clang->setInvocation(std::move(CI));
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001817 AST->OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001818
1819 // Set up diagnostics, capturing any diagnostics that would
1820 // otherwise be dropped.
1821 Clang->setDiagnostics(&AST->getDiagnostics());
1822
1823 // Create the target instance.
Alp Toker80758082014-07-06 05:26:44 +00001824 Clang->setTarget(TargetInfo::CreateTargetInfo(
Saleem Abdulrasool10a49722016-04-08 16:52:00 +00001825 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001826 if (!Clang->hasTarget())
Craig Topper49a27902014-05-22 04:46:25 +00001827 return nullptr;
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001828
1829 // Inform the target of the language options.
1830 //
1831 // FIXME: We shouldn't need to do this, the target should be immutable once
1832 // created. This complexity should be lifted elsewhere.
Alp Toker74437972014-07-06 05:14:24 +00001833 Clang->getTarget().adjust(Clang->getLangOpts());
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001834
1835 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1836 "Invocation must have exactly one source file!");
Richard Smith40c0efa2017-04-26 18:57:40 +00001837 assert(Clang->getFrontendOpts().Inputs[0].getKind().getFormat() ==
1838 InputKind::Source &&
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001839 "FIXME: AST inputs not yet supported here!");
Richard Smith40c0efa2017-04-26 18:57:40 +00001840 assert(Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() !=
1841 InputKind::LLVM_IR &&
1842 "IR inputs not support here!");
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001843
1844 // Configure the various subsystems.
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001845 AST->TheSema.reset();
Craig Topper49a27902014-05-22 04:46:25 +00001846 AST->Ctx = nullptr;
1847 AST->PP = nullptr;
1848 AST->Reader = nullptr;
1849
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001850 // Create a file manager object to provide access to and cache the filesystem.
1851 Clang->setFileManager(&AST->getFileManager());
1852
1853 // Create the source manager.
1854 Clang->setSourceManager(&AST->getSourceManager());
1855
Argyrios Kyrtzidisc382abf2016-02-09 19:07:13 +00001856 FrontendAction *Act = Action;
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001857
Ahmed Charlesb8984322014-03-07 20:03:18 +00001858 std::unique_ptr<TopLevelDeclTrackerAction> TrackerAct;
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001859 if (!Act) {
1860 TrackerAct.reset(new TopLevelDeclTrackerAction(*AST));
1861 Act = TrackerAct.get();
1862 }
1863
1864 // Recover resources if we crash before exiting this method.
1865 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1866 ActCleanup(TrackerAct.get());
1867
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001868 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
1869 AST->transferASTDataFromCompilerInstance(*Clang);
1870 if (OwnAST && ErrAST)
1871 ErrAST->swap(OwnAST);
1872
Craig Topper49a27902014-05-22 04:46:25 +00001873 return nullptr;
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001874 }
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00001875
1876 if (Persistent && !TrackerAct) {
1877 Clang->getPreprocessor().addPPCallbacks(
Craig Topperb8a70532014-09-10 04:53:53 +00001878 llvm::make_unique<MacroDefinitionTrackerPPCallbacks>(
1879 AST->getCurrentTopLevelHashValue()));
David Blaikie6beb6aa2014-08-10 19:56:51 +00001880 std::vector<std::unique_ptr<ASTConsumer>> Consumers;
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00001881 if (Clang->hasASTConsumer())
1882 Consumers.push_back(Clang->takeASTConsumer());
David Blaikie6beb6aa2014-08-10 19:56:51 +00001883 Consumers.push_back(llvm::make_unique<TopLevelDeclTrackerConsumer>(
1884 *AST, AST->getCurrentTopLevelHashValue()));
1885 Clang->setASTConsumer(
1886 llvm::make_unique<MultiplexConsumer>(std::move(Consumers)));
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00001887 }
Argyrios Kyrtzidis1416e172012-06-08 05:48:06 +00001888 if (!Act->Execute()) {
1889 AST->transferASTDataFromCompilerInstance(*Clang);
1890 if (OwnAST && ErrAST)
1891 ErrAST->swap(OwnAST);
1892
Craig Topper49a27902014-05-22 04:46:25 +00001893 return nullptr;
Argyrios Kyrtzidis1416e172012-06-08 05:48:06 +00001894 }
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001895
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001896 // Steal the created target, context, and preprocessor.
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001897 AST->transferASTDataFromCompilerInstance(*Clang);
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001898
1899 Act->EndSourceFile();
1900
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001901 if (OwnAST)
Ahmed Charles9a16beb2014-03-07 19:33:25 +00001902 return OwnAST.release();
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001903 else
1904 return AST;
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001905}
1906
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001907bool ASTUnit::LoadFromCompilerInvocation(
1908 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001909 unsigned PrecompilePreambleAfterNParses,
1910 IntrusiveRefCntPtr<vfs::FileSystem> VFS) {
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001911 if (!Invocation)
1912 return true;
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001913
1914 assert(VFS && "VFS is null");
1915
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001916 // We'll manage file buffers ourselves.
1917 Invocation->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1918 Invocation->getFrontendOpts().DisableFree = false;
Benjamin Kramer8de9c9b2017-01-18 16:25:48 +00001919 getDiagnostics().Reset();
Douglas Gregor345c1bc2011-01-19 01:02:47 +00001920 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001921
Rafael Espindola32482082014-08-18 16:23:45 +00001922 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
Benjamin Kramer5c248d82015-12-15 09:30:31 +00001923 if (PrecompilePreambleAfterNParses > 0) {
1924 PreambleRebuildCounter = PrecompilePreambleAfterNParses;
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001925 OverrideMainBuffer =
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001926 getMainBufferWithPrecompiledPreamble(PCHContainerOps, *Invocation, VFS);
Benjamin Kramer8484a322017-02-13 16:16:43 +00001927 getDiagnostics().Reset();
1928 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001929 }
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001930
Douglas Gregor16896c42010-10-28 15:44:59 +00001931 SimpleTimer ParsingTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00001932 ParsingTimer.setOutput("Parsing " + getMainFileName());
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001933
Ted Kremenek022a4902011-03-22 01:15:24 +00001934 // Recover resources if we crash before exiting this method.
1935 llvm::CrashRecoveryContextCleanupRegistrar<llvm::MemoryBuffer>
Rafael Espindola32482082014-08-18 16:23:45 +00001936 MemBufferCleanup(OverrideMainBuffer.get());
1937
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001938 return Parse(std::move(PCHContainerOps), std::move(OverrideMainBuffer), VFS);
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001939}
1940
David Blaikie103a2de2014-04-25 17:01:33 +00001941std::unique_ptr<ASTUnit> ASTUnit::LoadFromCompilerInvocation(
David Blaikieea4395e2017-01-06 19:49:01 +00001942 std::shared_ptr<CompilerInvocation> CI,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001943 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
Benjamin Kramerbc632902015-10-06 14:45:20 +00001944 IntrusiveRefCntPtr<DiagnosticsEngine> Diags, FileManager *FileMgr,
Benjamin Kramer5c248d82015-12-15 09:30:31 +00001945 bool OnlyLocalDecls, bool CaptureDiagnostics,
1946 unsigned PrecompilePreambleAfterNParses, TranslationUnitKind TUKind,
1947 bool CacheCodeCompletionResults, bool IncludeBriefCommentsInCodeCompletion,
1948 bool UserFilesAreVolatile) {
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001949 // Create the AST unit.
David Blaikie103a2de2014-04-25 17:01:33 +00001950 std::unique_ptr<ASTUnit> AST(new ASTUnit(false));
Justin Bognerdbbcb112014-10-14 23:36:06 +00001951 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001952 AST->Diagnostics = Diags;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001953 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001954 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor69f74f82011-08-25 22:30:56 +00001955 AST->TUKind = TUKind;
Douglas Gregorb14904c2010-08-13 22:48:40 +00001956 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenko3292d062012-07-02 17:35:10 +00001957 AST->IncludeBriefCommentsInCodeCompletion
1958 = IncludeBriefCommentsInCodeCompletion;
David Blaikieea4395e2017-01-06 19:49:01 +00001959 AST->Invocation = std::move(CI);
Benjamin Kramerbc632902015-10-06 14:45:20 +00001960 AST->FileSystemOpts = FileMgr->getFileSystemOpts();
1961 AST->FileMgr = FileMgr;
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +00001962 AST->UserFilesAreVolatile = UserFilesAreVolatile;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001963
Ted Kremenek4422bfe2011-03-18 02:06:56 +00001964 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00001965 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1966 ASTUnitCleanup(AST.get());
David Blaikie9c902b52011-09-25 23:23:43 +00001967 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1968 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Alp Tokerf994cef2014-07-05 03:08:06 +00001969 DiagCleanup(Diags.get());
Ted Kremenek4422bfe2011-03-18 02:06:56 +00001970
Benjamin Kramerd6da1a02016-06-12 20:05:23 +00001971 if (AST->LoadFromCompilerInvocation(std::move(PCHContainerOps),
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001972 PrecompilePreambleAfterNParses,
1973 AST->FileMgr->getVirtualFileSystem()))
David Blaikie103a2de2014-04-25 17:01:33 +00001974 return nullptr;
1975 return AST;
Daniel Dunbar764c0822009-12-01 09:51:01 +00001976}
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001977
Ahmed Charlesb8984322014-03-07 20:03:18 +00001978ASTUnit *ASTUnit::LoadFromCommandLine(
1979 const char **ArgBegin, const char **ArgEnd,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001980 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
Ahmed Charlesb8984322014-03-07 20:03:18 +00001981 IntrusiveRefCntPtr<DiagnosticsEngine> Diags, StringRef ResourceFilesPath,
1982 bool OnlyLocalDecls, bool CaptureDiagnostics,
1983 ArrayRef<RemappedFile> RemappedFiles, bool RemappedFilesKeepOriginalName,
Benjamin Kramer5c248d82015-12-15 09:30:31 +00001984 unsigned PrecompilePreambleAfterNParses, TranslationUnitKind TUKind,
Ahmed Charlesb8984322014-03-07 20:03:18 +00001985 bool CacheCodeCompletionResults, bool IncludeBriefCommentsInCodeCompletion,
1986 bool AllowPCHWithCompilerErrors, bool SkipFunctionBodies,
Argyrios Kyrtzidis735e92c2017-06-09 01:20:48 +00001987 bool SingleFileParse, bool UserFilesAreVolatile, bool ForSerialization,
Ilya Biryukovaf69e402017-05-23 11:37:52 +00001988 llvm::Optional<StringRef> ModuleFormat, std::unique_ptr<ASTUnit> *ErrAST,
1989 IntrusiveRefCntPtr<vfs::FileSystem> VFS) {
Justin Bognerd512c1e2014-10-15 00:33:06 +00001990 assert(Diags.get() && "no DiagnosticsEngine was provided");
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001991
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001992 SmallVector<StoredDiagnostic, 4> StoredDiagnostics;
David Blaikieea4395e2017-01-06 19:49:01 +00001993
1994 std::shared_ptr<CompilerInvocation> CI;
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001995
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001996 {
Douglas Gregor925296b2011-07-19 16:10:42 +00001997
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001998 CaptureDroppedDiagnostics Capture(CaptureDiagnostics, *Diags,
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001999 StoredDiagnostics);
Daniel Dunbarfcf2d422010-01-25 00:44:02 +00002000
Argyrios Kyrtzidis5cf423e2011-04-04 23:11:45 +00002001 CI = clang::createInvocationFromCommandLine(
David Blaikieea4395e2017-01-06 19:49:01 +00002002 llvm::makeArrayRef(ArgBegin, ArgEnd), Diags);
Argyrios Kyrtzidisf606b822011-04-04 21:38:51 +00002003 if (!CI)
Craig Topper49a27902014-05-22 04:46:25 +00002004 return nullptr;
Daniel Dunbar55a17b62009-12-02 03:23:45 +00002005 }
Douglas Gregor44c6ee72010-11-11 00:39:14 +00002006
Douglas Gregoraa98ed92010-01-23 00:14:00 +00002007 // Override any files that need remapping
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00002008 for (const auto &RemappedFile : RemappedFiles) {
2009 CI->getPreprocessorOpts().addRemappedFile(RemappedFile.first,
2010 RemappedFile.second);
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00002011 }
Argyrios Kyrtzidis4a280ff2012-03-07 01:51:17 +00002012 PreprocessorOptions &PPOpts = CI->getPreprocessorOpts();
2013 PPOpts.RemappedFilesKeepOriginalName = RemappedFilesKeepOriginalName;
2014 PPOpts.AllowPCHWithCompilerErrors = AllowPCHWithCompilerErrors;
Erik Verbruggenb34c79f2017-05-30 11:54:55 +00002015 PPOpts.GeneratePreamble = PrecompilePreambleAfterNParses != 0;
Argyrios Kyrtzidis735e92c2017-06-09 01:20:48 +00002016 PPOpts.SingleFileParseMode = SingleFileParse;
Douglas Gregoraa98ed92010-01-23 00:14:00 +00002017
Daniel Dunbara5a166d2009-12-15 00:06:45 +00002018 // Override the resources path.
Daniel Dunbar6b03ece2010-01-30 21:47:16 +00002019 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
Daniel Dunbar55a17b62009-12-02 03:23:45 +00002020
Erik Verbruggen6e922512012-04-12 10:11:59 +00002021 CI->getFrontendOpts().SkipFunctionBodies = SkipFunctionBodies;
2022
Argyrios Kyrtzidisa3e2ff12015-11-20 03:36:21 +00002023 if (ModuleFormat)
2024 CI->getHeaderSearchOpts().ModuleFormat = ModuleFormat.getValue();
2025
Douglas Gregor7bb8af62010-10-12 00:50:20 +00002026 // Create the AST unit.
Ahmed Charlesb8984322014-03-07 20:03:18 +00002027 std::unique_ptr<ASTUnit> AST;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00002028 AST.reset(new ASTUnit(false));
Justin Bognerdbbcb112014-10-14 23:36:06 +00002029 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
Douglas Gregor7bb8af62010-10-12 00:50:20 +00002030 AST->Diagnostics = Diags;
Anders Carlssonc30dcec2011-03-18 18:22:40 +00002031 AST->FileSystemOpts = CI->getFileSystemOpts();
Ilya Biryukovaf69e402017-05-23 11:37:52 +00002032 if (!VFS)
2033 VFS = vfs::getRealFileSystem();
2034 VFS = createVFSFromCompilerInvocation(*CI, *Diags, VFS);
Ben Langmuir8832c062014-04-15 18:16:25 +00002035 if (!VFS)
2036 return nullptr;
2037 AST->FileMgr = new FileManager(AST->FileSystemOpts, VFS);
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00002038 AST->PCMCache = new MemoryBufferCache;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00002039 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor44c6ee72010-11-11 00:39:14 +00002040 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor69f74f82011-08-25 22:30:56 +00002041 AST->TUKind = TUKind;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00002042 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002043 AST->IncludeBriefCommentsInCodeCompletion
2044 = IncludeBriefCommentsInCodeCompletion;
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +00002045 AST->UserFilesAreVolatile = UserFilesAreVolatile;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00002046 AST->NumStoredDiagnosticsFromDriver = StoredDiagnostics.size();
Douglas Gregor7bb8af62010-10-12 00:50:20 +00002047 AST->StoredDiagnostics.swap(StoredDiagnostics);
Ted Kremenek5e14d392011-03-21 18:40:17 +00002048 AST->Invocation = CI;
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00002049 if (ForSerialization)
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00002050 AST->WriterData.reset(new ASTWriterData(*AST->PCMCache));
Alexey Samsonovb4f99dd2014-08-28 23:51:01 +00002051 // Zero out now to ease cleanup during crash recovery.
2052 CI = nullptr;
2053 Diags = nullptr;
Craig Topper49a27902014-05-22 04:46:25 +00002054
Ted Kremenek4422bfe2011-03-18 02:06:56 +00002055 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00002056 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
2057 ASTUnitCleanup(AST.get());
Ted Kremenek4422bfe2011-03-18 02:06:56 +00002058
Benjamin Kramerd6da1a02016-06-12 20:05:23 +00002059 if (AST->LoadFromCompilerInvocation(std::move(PCHContainerOps),
Ilya Biryukovaf69e402017-05-23 11:37:52 +00002060 PrecompilePreambleAfterNParses,
2061 VFS)) {
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00002062 // Some error occurred, if caller wants to examine diagnostics, pass it the
2063 // ASTUnit.
2064 if (ErrAST) {
2065 AST->StoredDiagnostics.swap(AST->FailedParseDiagnostics);
2066 ErrAST->swap(AST);
2067 }
Craig Topper49a27902014-05-22 04:46:25 +00002068 return nullptr;
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00002069 }
2070
Ahmed Charles9a16beb2014-03-07 19:33:25 +00002071 return AST.release();
Daniel Dunbar55a17b62009-12-02 03:23:45 +00002072}
Douglas Gregoraa21cc42010-07-19 21:46:24 +00002073
Adrian Prantlbb165fb2015-06-20 18:53:08 +00002074bool ASTUnit::Reparse(std::shared_ptr<PCHContainerOperations> PCHContainerOps,
Ilya Biryukovaf69e402017-05-23 11:37:52 +00002075 ArrayRef<RemappedFile> RemappedFiles,
2076 IntrusiveRefCntPtr<vfs::FileSystem> VFS) {
Ted Kremenek5e14d392011-03-21 18:40:17 +00002077 if (!Invocation)
Douglas Gregoraa21cc42010-07-19 21:46:24 +00002078 return true;
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00002079
Ilya Biryukovaf69e402017-05-23 11:37:52 +00002080 if (!VFS) {
2081 assert(FileMgr && "FileMgr is null on Reparse call");
2082 VFS = FileMgr->getVirtualFileSystem();
2083 }
2084
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00002085 clearFileLevelDecls();
Douglas Gregoraa21cc42010-07-19 21:46:24 +00002086
Douglas Gregor16896c42010-10-28 15:44:59 +00002087 SimpleTimer ParsingTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00002088 ParsingTimer.setOutput("Reparsing " + getMainFileName());
Douglas Gregor16896c42010-10-28 15:44:59 +00002089
Douglas Gregor0e119552010-07-31 00:40:00 +00002090 // Remap files.
Douglas Gregor7b02b582010-08-20 00:02:33 +00002091 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
Alp Toker1b070d22014-07-07 07:47:20 +00002092 for (const auto &RB : PPOpts.RemappedFileBuffers)
2093 delete RB.second;
2094
Douglas Gregor0e119552010-07-31 00:40:00 +00002095 Invocation->getPreprocessorOpts().clearRemappedFiles();
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00002096 for (const auto &RemappedFile : RemappedFiles) {
2097 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFile.first,
2098 RemappedFile.second);
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00002099 }
Dmitri Gribenkoc444b572014-02-08 00:38:15 +00002100
Douglas Gregorbb420ab2010-08-04 05:53:38 +00002101 // If we have a preamble file lying around, or if we might try to
2102 // build a precompiled preamble, do so now.
Rafael Espindola32482082014-08-18 16:23:45 +00002103 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
Ted Kremenek06b4f912011-10-27 17:55:18 +00002104 if (!getPreambleFile(this).empty() || PreambleRebuildCounter > 0)
Adrian Prantlbb165fb2015-06-20 18:53:08 +00002105 OverrideMainBuffer =
Ilya Biryukovaf69e402017-05-23 11:37:52 +00002106 getMainBufferWithPrecompiledPreamble(PCHContainerOps, *Invocation, VFS);
2107
Adrian Prantlbb165fb2015-06-20 18:53:08 +00002108
Douglas Gregoraa21cc42010-07-19 21:46:24 +00002109 // Clear out the diagnostics state.
Benjamin Kramerbc632902015-10-06 14:45:20 +00002110 FileMgr.reset();
Argyrios Kyrtzidisf50f7b22011-11-03 20:28:19 +00002111 getDiagnostics().Reset();
2112 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Argyrios Kyrtzidis462ff352011-11-03 20:57:33 +00002113 if (OverrideMainBuffer)
2114 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
Argyrios Kyrtzidisf50f7b22011-11-03 20:28:19 +00002115
Douglas Gregor4dde7492010-07-23 23:58:40 +00002116 // Parse the sources
Benjamin Kramerd6da1a02016-06-12 20:05:23 +00002117 bool Result =
Ilya Biryukovaf69e402017-05-23 11:37:52 +00002118 Parse(std::move(PCHContainerOps), std::move(OverrideMainBuffer), VFS);
Rafael Espindola32482082014-08-18 16:23:45 +00002119
Argyrios Kyrtzidis36893372011-10-31 21:25:31 +00002120 // If we're caching global code-completion results, and the top-level
2121 // declarations have changed, clear out the code-completion cache.
2122 if (!Result && ShouldCacheCodeCompletionResults &&
2123 CurrentTopLevelHashValue != CompletionCacheTopLevelHashValue)
2124 CacheCodeCompletionResults();
Douglas Gregordf7a79a2011-02-16 18:16:54 +00002125
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00002126 // We now need to clear out the completion info related to this translation
2127 // unit; it'll be recreated if necessary.
2128 CCTUInfo.reset();
Douglas Gregor3f35bb22011-08-04 20:04:59 +00002129
Douglas Gregor4dde7492010-07-23 23:58:40 +00002130 return Result;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00002131}
Douglas Gregor8e984da2010-08-04 16:47:14 +00002132
Erik Verbruggen346066b2017-05-30 14:25:54 +00002133void ASTUnit::ResetForParse() {
2134 SavedMainFileBuffer.reset();
2135
2136 SourceMgr.reset();
2137 TheSema.reset();
2138 Ctx.reset();
2139 PP.reset();
2140 Reader.reset();
2141
2142 TopLevelDecls.clear();
2143 clearFileLevelDecls();
2144}
2145
Douglas Gregorb14904c2010-08-13 22:48:40 +00002146//----------------------------------------------------------------------------//
2147// Code completion
2148//----------------------------------------------------------------------------//
2149
2150namespace {
2151 /// \brief Code completion consumer that combines the cached code-completion
2152 /// results from an ASTUnit with the code-completion results provided to it,
2153 /// then passes the result on to
2154 class AugmentedCodeCompleteConsumer : public CodeCompleteConsumer {
Richard Smith697cc9e2012-08-14 03:13:00 +00002155 uint64_t NormalContexts;
Douglas Gregorb14904c2010-08-13 22:48:40 +00002156 ASTUnit &AST;
2157 CodeCompleteConsumer &Next;
2158
2159 public:
2160 AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next,
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002161 const CodeCompleteOptions &CodeCompleteOpts)
2162 : CodeCompleteConsumer(CodeCompleteOpts, Next.isOutputBinary()),
2163 AST(AST), Next(Next)
Douglas Gregorb14904c2010-08-13 22:48:40 +00002164 {
2165 // Compute the set of contexts in which we will look when we don't have
2166 // any information about the specific context.
2167 NormalContexts
Richard Smith697cc9e2012-08-14 03:13:00 +00002168 = (1LL << CodeCompletionContext::CCC_TopLevel)
2169 | (1LL << CodeCompletionContext::CCC_ObjCInterface)
2170 | (1LL << CodeCompletionContext::CCC_ObjCImplementation)
2171 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
2172 | (1LL << CodeCompletionContext::CCC_Statement)
2173 | (1LL << CodeCompletionContext::CCC_Expression)
2174 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
2175 | (1LL << CodeCompletionContext::CCC_DotMemberAccess)
2176 | (1LL << CodeCompletionContext::CCC_ArrowMemberAccess)
2177 | (1LL << CodeCompletionContext::CCC_ObjCPropertyAccess)
2178 | (1LL << CodeCompletionContext::CCC_ObjCProtocolName)
2179 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
2180 | (1LL << CodeCompletionContext::CCC_Recovery);
Douglas Gregor5e35d592010-09-14 23:59:36 +00002181
David Blaikiebbafb8a2012-03-11 07:00:24 +00002182 if (AST.getASTContext().getLangOpts().CPlusPlus)
Richard Smith697cc9e2012-08-14 03:13:00 +00002183 NormalContexts |= (1LL << CodeCompletionContext::CCC_EnumTag)
2184 | (1LL << CodeCompletionContext::CCC_UnionTag)
2185 | (1LL << CodeCompletionContext::CCC_ClassOrStructTag);
Douglas Gregorb14904c2010-08-13 22:48:40 +00002186 }
Craig Topperafa7cb32014-03-13 06:07:04 +00002187
2188 void ProcessCodeCompleteResults(Sema &S, CodeCompletionContext Context,
2189 CodeCompletionResult *Results,
2190 unsigned NumResults) override;
2191
2192 void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
2193 OverloadCandidate *Candidates,
2194 unsigned NumCandidates) override {
Douglas Gregorb14904c2010-08-13 22:48:40 +00002195 Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates);
2196 }
Craig Topperafa7cb32014-03-13 06:07:04 +00002197
2198 CodeCompletionAllocator &getAllocator() override {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002199 return Next.getAllocator();
2200 }
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00002201
Craig Topperafa7cb32014-03-13 06:07:04 +00002202 CodeCompletionTUInfo &getCodeCompletionTUInfo() override {
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00002203 return Next.getCodeCompletionTUInfo();
2204 }
Douglas Gregorb14904c2010-08-13 22:48:40 +00002205 };
Hans Wennborgdcfba332015-10-06 23:40:43 +00002206} // anonymous namespace
Douglas Gregord46cf182010-08-16 20:01:48 +00002207
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002208/// \brief Helper function that computes which global names are hidden by the
2209/// local code-completion results.
Ted Kremenek6a153372010-11-07 06:11:36 +00002210static void CalculateHiddenNames(const CodeCompletionContext &Context,
2211 CodeCompletionResult *Results,
2212 unsigned NumResults,
2213 ASTContext &Ctx,
2214 llvm::StringSet<llvm::BumpPtrAllocator> &HiddenNames){
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002215 bool OnlyTagNames = false;
2216 switch (Context.getKind()) {
Douglas Gregor0ac41382010-09-23 23:01:17 +00002217 case CodeCompletionContext::CCC_Recovery:
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002218 case CodeCompletionContext::CCC_TopLevel:
2219 case CodeCompletionContext::CCC_ObjCInterface:
2220 case CodeCompletionContext::CCC_ObjCImplementation:
2221 case CodeCompletionContext::CCC_ObjCIvarList:
2222 case CodeCompletionContext::CCC_ClassStructUnion:
2223 case CodeCompletionContext::CCC_Statement:
2224 case CodeCompletionContext::CCC_Expression:
2225 case CodeCompletionContext::CCC_ObjCMessageReceiver:
Douglas Gregor21325842011-07-07 16:03:39 +00002226 case CodeCompletionContext::CCC_DotMemberAccess:
2227 case CodeCompletionContext::CCC_ArrowMemberAccess:
2228 case CodeCompletionContext::CCC_ObjCPropertyAccess:
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002229 case CodeCompletionContext::CCC_Namespace:
2230 case CodeCompletionContext::CCC_Type:
Douglas Gregorc49f5b22010-08-23 18:23:48 +00002231 case CodeCompletionContext::CCC_Name:
2232 case CodeCompletionContext::CCC_PotentiallyQualifiedName:
Douglas Gregor5e35d592010-09-14 23:59:36 +00002233 case CodeCompletionContext::CCC_ParenthesizedExpression:
Douglas Gregor2c595ad2011-07-30 06:55:39 +00002234 case CodeCompletionContext::CCC_ObjCInterfaceName:
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002235 break;
2236
2237 case CodeCompletionContext::CCC_EnumTag:
2238 case CodeCompletionContext::CCC_UnionTag:
2239 case CodeCompletionContext::CCC_ClassOrStructTag:
2240 OnlyTagNames = true;
2241 break;
2242
2243 case CodeCompletionContext::CCC_ObjCProtocolName:
Douglas Gregor12785102010-08-24 20:21:13 +00002244 case CodeCompletionContext::CCC_MacroName:
2245 case CodeCompletionContext::CCC_MacroNameUse:
Douglas Gregorec00a262010-08-24 22:20:20 +00002246 case CodeCompletionContext::CCC_PreprocessorExpression:
Douglas Gregor0de55ce2010-08-25 18:41:16 +00002247 case CodeCompletionContext::CCC_PreprocessorDirective:
Douglas Gregorea147052010-08-25 18:04:30 +00002248 case CodeCompletionContext::CCC_NaturalLanguage:
Douglas Gregor67c692c2010-08-26 15:07:07 +00002249 case CodeCompletionContext::CCC_SelectorName:
Douglas Gregor28c78432010-08-27 17:35:51 +00002250 case CodeCompletionContext::CCC_TypeQualifiers:
Douglas Gregor0ac41382010-09-23 23:01:17 +00002251 case CodeCompletionContext::CCC_Other:
Douglas Gregor3a69eaf2011-02-18 23:30:37 +00002252 case CodeCompletionContext::CCC_OtherWithMacros:
Douglas Gregor21325842011-07-07 16:03:39 +00002253 case CodeCompletionContext::CCC_ObjCInstanceMessage:
2254 case CodeCompletionContext::CCC_ObjCClassMessage:
2255 case CodeCompletionContext::CCC_ObjCCategoryName:
Douglas Gregor0de55ce2010-08-25 18:41:16 +00002256 // We're looking for nothing, or we're looking for names that cannot
2257 // be hidden.
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002258 return;
2259 }
2260
John McCall276321a2010-08-25 06:19:51 +00002261 typedef CodeCompletionResult Result;
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002262 for (unsigned I = 0; I != NumResults; ++I) {
2263 if (Results[I].Kind != Result::RK_Declaration)
2264 continue;
2265
2266 unsigned IDNS
2267 = Results[I].Declaration->getUnderlyingDecl()->getIdentifierNamespace();
2268
2269 bool Hiding = false;
2270 if (OnlyTagNames)
2271 Hiding = (IDNS & Decl::IDNS_Tag);
2272 else {
2273 unsigned HiddenIDNS = (Decl::IDNS_Type | Decl::IDNS_Member |
Douglas Gregor59cab552010-08-16 23:05:20 +00002274 Decl::IDNS_Namespace | Decl::IDNS_Ordinary |
2275 Decl::IDNS_NonMemberOperator);
David Blaikiebbafb8a2012-03-11 07:00:24 +00002276 if (Ctx.getLangOpts().CPlusPlus)
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002277 HiddenIDNS |= Decl::IDNS_Tag;
2278 Hiding = (IDNS & HiddenIDNS);
2279 }
2280
2281 if (!Hiding)
2282 continue;
2283
2284 DeclarationName Name = Results[I].Declaration->getDeclName();
2285 if (IdentifierInfo *Identifier = Name.getAsIdentifierInfo())
2286 HiddenNames.insert(Identifier->getName());
2287 else
2288 HiddenNames.insert(Name.getAsString());
2289 }
2290}
2291
Douglas Gregord46cf182010-08-16 20:01:48 +00002292void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &S,
2293 CodeCompletionContext Context,
John McCall276321a2010-08-25 06:19:51 +00002294 CodeCompletionResult *Results,
Douglas Gregord46cf182010-08-16 20:01:48 +00002295 unsigned NumResults) {
2296 // Merge the results we were given with the results we cached.
2297 bool AddedResult = false;
Richard Smith697cc9e2012-08-14 03:13:00 +00002298 uint64_t InContexts =
2299 Context.getKind() == CodeCompletionContext::CCC_Recovery
2300 ? NormalContexts : (1LL << Context.getKind());
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002301 // Contains the set of names that are hidden by "local" completion results.
Ted Kremenek6a153372010-11-07 06:11:36 +00002302 llvm::StringSet<llvm::BumpPtrAllocator> HiddenNames;
John McCall276321a2010-08-25 06:19:51 +00002303 typedef CodeCompletionResult Result;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002304 SmallVector<Result, 8> AllResults;
Douglas Gregord46cf182010-08-16 20:01:48 +00002305 for (ASTUnit::cached_completion_iterator
Douglas Gregordf239672010-08-16 21:23:13 +00002306 C = AST.cached_completion_begin(),
2307 CEnd = AST.cached_completion_end();
Douglas Gregord46cf182010-08-16 20:01:48 +00002308 C != CEnd; ++C) {
2309 // If the context we are in matches any of the contexts we are
2310 // interested in, we'll add this result.
2311 if ((C->ShowInContexts & InContexts) == 0)
2312 continue;
2313
2314 // If we haven't added any results previously, do so now.
2315 if (!AddedResult) {
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002316 CalculateHiddenNames(Context, Results, NumResults, S.Context,
2317 HiddenNames);
Douglas Gregord46cf182010-08-16 20:01:48 +00002318 AllResults.insert(AllResults.end(), Results, Results + NumResults);
2319 AddedResult = true;
2320 }
2321
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002322 // Determine whether this global completion result is hidden by a local
2323 // completion result. If so, skip it.
2324 if (C->Kind != CXCursor_MacroDefinition &&
2325 HiddenNames.count(C->Completion->getTypedText()))
2326 continue;
2327
Douglas Gregord46cf182010-08-16 20:01:48 +00002328 // Adjust priority based on similar type classes.
2329 unsigned Priority = C->Priority;
Douglas Gregor12785102010-08-24 20:21:13 +00002330 CodeCompletionString *Completion = C->Completion;
Douglas Gregord46cf182010-08-16 20:01:48 +00002331 if (!Context.getPreferredType().isNull()) {
2332 if (C->Kind == CXCursor_MacroDefinition) {
2333 Priority = getMacroUsagePriority(C->Completion->getTypedText(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00002334 S.getLangOpts(),
Douglas Gregor12785102010-08-24 20:21:13 +00002335 Context.getPreferredType()->isAnyPointerType());
Douglas Gregord46cf182010-08-16 20:01:48 +00002336 } else if (C->Type) {
2337 CanQualType Expected
Douglas Gregordf239672010-08-16 21:23:13 +00002338 = S.Context.getCanonicalType(
Douglas Gregord46cf182010-08-16 20:01:48 +00002339 Context.getPreferredType().getUnqualifiedType());
2340 SimplifiedTypeClass ExpectedSTC = getSimplifiedTypeClass(Expected);
2341 if (ExpectedSTC == C->TypeClass) {
2342 // We know this type is similar; check for an exact match.
2343 llvm::StringMap<unsigned> &CachedCompletionTypes
Douglas Gregordf239672010-08-16 21:23:13 +00002344 = AST.getCachedCompletionTypes();
Douglas Gregord46cf182010-08-16 20:01:48 +00002345 llvm::StringMap<unsigned>::iterator Pos
Douglas Gregordf239672010-08-16 21:23:13 +00002346 = CachedCompletionTypes.find(QualType(Expected).getAsString());
Douglas Gregord46cf182010-08-16 20:01:48 +00002347 if (Pos != CachedCompletionTypes.end() && Pos->second == C->Type)
2348 Priority /= CCF_ExactTypeMatch;
2349 else
2350 Priority /= CCF_SimilarTypeMatch;
2351 }
2352 }
2353 }
2354
Douglas Gregor12785102010-08-24 20:21:13 +00002355 // Adjust the completion string, if required.
2356 if (C->Kind == CXCursor_MacroDefinition &&
2357 Context.getKind() == CodeCompletionContext::CCC_MacroNameUse) {
2358 // Create a new code-completion string that just contains the
2359 // macro name, without its arguments.
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00002360 CodeCompletionBuilder Builder(getAllocator(), getCodeCompletionTUInfo(),
2361 CCP_CodePattern, C->Availability);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002362 Builder.AddTypedTextChunk(C->Completion->getTypedText());
Douglas Gregor8850aa32010-08-25 18:03:13 +00002363 Priority = CCP_CodePattern;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002364 Completion = Builder.TakeString();
Douglas Gregor12785102010-08-24 20:21:13 +00002365 }
2366
Argyrios Kyrtzidis5c8b1cd2012-09-27 00:24:09 +00002367 AllResults.push_back(Result(Completion, Priority, C->Kind,
Douglas Gregorf757a122010-08-23 23:00:57 +00002368 C->Availability));
Douglas Gregord46cf182010-08-16 20:01:48 +00002369 }
2370
2371 // If we did not add any cached completion results, just forward the
2372 // results we were given to the next consumer.
2373 if (!AddedResult) {
2374 Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
2375 return;
2376 }
Douglas Gregor49f67ce2010-08-26 13:48:20 +00002377
Douglas Gregord46cf182010-08-16 20:01:48 +00002378 Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
2379 AllResults.size());
2380}
2381
Adrian Prantlbb165fb2015-06-20 18:53:08 +00002382void ASTUnit::CodeComplete(
2383 StringRef File, unsigned Line, unsigned Column,
2384 ArrayRef<RemappedFile> RemappedFiles, bool IncludeMacros,
2385 bool IncludeCodePatterns, bool IncludeBriefComments,
2386 CodeCompleteConsumer &Consumer,
2387 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
2388 DiagnosticsEngine &Diag, LangOptions &LangOpts, SourceManager &SourceMgr,
2389 FileManager &FileMgr, SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
2390 SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers) {
Ted Kremenek5e14d392011-03-21 18:40:17 +00002391 if (!Invocation)
Douglas Gregor8e984da2010-08-04 16:47:14 +00002392 return;
2393
Douglas Gregor16896c42010-10-28 15:44:59 +00002394 SimpleTimer CompletionTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00002395 CompletionTimer.setOutput("Code completion @ " + File + ":" +
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002396 Twine(Line) + ":" + Twine(Column));
Douglas Gregor028d3e42010-08-09 20:45:32 +00002397
David Blaikieea4395e2017-01-06 19:49:01 +00002398 auto CCInvocation = std::make_shared<CompilerInvocation>(*Invocation);
Ted Kremenek5e14d392011-03-21 18:40:17 +00002399
2400 FrontendOptions &FrontendOpts = CCInvocation->getFrontendOpts();
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002401 CodeCompleteOptions &CodeCompleteOpts = FrontendOpts.CodeCompleteOpts;
Ted Kremenek5e14d392011-03-21 18:40:17 +00002402 PreprocessorOptions &PreprocessorOpts = CCInvocation->getPreprocessorOpts();
Douglas Gregorb68bc592010-08-05 09:09:23 +00002403
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002404 CodeCompleteOpts.IncludeMacros = IncludeMacros &&
2405 CachedCompletionResults.empty();
2406 CodeCompleteOpts.IncludeCodePatterns = IncludeCodePatterns;
2407 CodeCompleteOpts.IncludeGlobals = CachedCompletionResults.empty();
2408 CodeCompleteOpts.IncludeBriefComments = IncludeBriefComments;
2409
2410 assert(IncludeBriefComments == this->IncludeBriefCommentsInCodeCompletion);
2411
Douglas Gregor8e984da2010-08-04 16:47:14 +00002412 FrontendOpts.CodeCompletionAt.FileName = File;
2413 FrontendOpts.CodeCompletionAt.Line = Line;
2414 FrontendOpts.CodeCompletionAt.Column = Column;
2415
2416 // Set the language options appropriately.
Ted Kremenek8cf47df2011-11-17 23:01:24 +00002417 LangOpts = *CCInvocation->getLangOpts();
Douglas Gregor8e984da2010-08-04 16:47:14 +00002418
Argyrios Kyrtzidis06e8d692014-10-31 16:44:32 +00002419 // Spell-checking and warnings are wasteful during code-completion.
2420 LangOpts.SpellChecking = false;
2421 CCInvocation->getDiagnosticOpts().IgnoreWarnings = true;
2422
Adrian Prantlbb165fb2015-06-20 18:53:08 +00002423 std::unique_ptr<CompilerInstance> Clang(
2424 new CompilerInstance(PCHContainerOps));
Ted Kremenek84de4a12011-03-21 18:40:07 +00002425
2426 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00002427 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
2428 CICleanup(Clang.get());
Ted Kremenek84de4a12011-03-21 18:40:07 +00002429
David Blaikieea4395e2017-01-06 19:49:01 +00002430 auto &Inv = *CCInvocation;
2431 Clang->setInvocation(std::move(CCInvocation));
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00002432 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
Douglas Gregor8e984da2010-08-04 16:47:14 +00002433
2434 // Set up diagnostics, capturing any diagnostics produced.
Ted Kremenek84de4a12011-03-21 18:40:07 +00002435 Clang->setDiagnostics(&Diag);
Douglas Gregor8e984da2010-08-04 16:47:14 +00002436 CaptureDroppedDiagnostics Capture(true,
Ted Kremenek84de4a12011-03-21 18:40:07 +00002437 Clang->getDiagnostics(),
Douglas Gregor8e984da2010-08-04 16:47:14 +00002438 StoredDiagnostics);
David Blaikieea4395e2017-01-06 19:49:01 +00002439 ProcessWarningOptions(Diag, Inv.getDiagnosticOpts());
2440
Douglas Gregor8e984da2010-08-04 16:47:14 +00002441 // Create the target instance.
Alp Toker80758082014-07-06 05:26:44 +00002442 Clang->setTarget(TargetInfo::CreateTargetInfo(
Saleem Abdulrasool10a49722016-04-08 16:52:00 +00002443 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
Ted Kremenek84de4a12011-03-21 18:40:07 +00002444 if (!Clang->hasTarget()) {
Craig Topper49a27902014-05-22 04:46:25 +00002445 Clang->setInvocation(nullptr);
Douglas Gregor2dd19f12010-08-18 22:29:43 +00002446 return;
Douglas Gregor8e984da2010-08-04 16:47:14 +00002447 }
2448
2449 // Inform the target of the language options.
2450 //
2451 // FIXME: We shouldn't need to do this, the target should be immutable once
2452 // created. This complexity should be lifted elsewhere.
Alp Toker74437972014-07-06 05:14:24 +00002453 Clang->getTarget().adjust(Clang->getLangOpts());
Douglas Gregor8e984da2010-08-04 16:47:14 +00002454
Ted Kremenek84de4a12011-03-21 18:40:07 +00002455 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Douglas Gregor8e984da2010-08-04 16:47:14 +00002456 "Invocation must have exactly one source file!");
Richard Smith40c0efa2017-04-26 18:57:40 +00002457 assert(Clang->getFrontendOpts().Inputs[0].getKind().getFormat() ==
2458 InputKind::Source &&
Douglas Gregor8e984da2010-08-04 16:47:14 +00002459 "FIXME: AST inputs not yet supported here!");
Richard Smith40c0efa2017-04-26 18:57:40 +00002460 assert(Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() !=
2461 InputKind::LLVM_IR &&
Douglas Gregor8e984da2010-08-04 16:47:14 +00002462 "IR inputs not support here!");
Douglas Gregor8e984da2010-08-04 16:47:14 +00002463
2464 // Use the source and file managers that we were given.
Ted Kremenek84de4a12011-03-21 18:40:07 +00002465 Clang->setFileManager(&FileMgr);
2466 Clang->setSourceManager(&SourceMgr);
Douglas Gregor8e984da2010-08-04 16:47:14 +00002467
2468 // Remap files.
2469 PreprocessorOpts.clearRemappedFiles();
Douglas Gregord8a5dba2010-08-04 17:07:00 +00002470 PreprocessorOpts.RetainRemappedFileBuffers = true;
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00002471 for (const auto &RemappedFile : RemappedFiles) {
2472 PreprocessorOpts.addRemappedFile(RemappedFile.first, RemappedFile.second);
2473 OwnedBuffers.push_back(RemappedFile.second);
Douglas Gregorb97b6662010-08-20 00:59:43 +00002474 }
Dmitri Gribenkoc444b572014-02-08 00:38:15 +00002475
Douglas Gregorb14904c2010-08-13 22:48:40 +00002476 // Use the code completion consumer we were given, but adding any cached
2477 // code-completion results.
Douglas Gregore9186e62010-11-29 16:13:56 +00002478 AugmentedCodeCompleteConsumer *AugmentedConsumer
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002479 = new AugmentedCodeCompleteConsumer(*this, Consumer, CodeCompleteOpts);
Ted Kremenek84de4a12011-03-21 18:40:07 +00002480 Clang->setCodeCompletionConsumer(AugmentedConsumer);
Douglas Gregor8e984da2010-08-04 16:47:14 +00002481
Douglas Gregor028d3e42010-08-09 20:45:32 +00002482 // If we have a precompiled preamble, try to use it. We only allow
2483 // the use of the precompiled preamble if we're if the completion
2484 // point is within the main file, after the end of the precompiled
2485 // preamble.
Rafael Espindola2346a372014-08-18 18:47:08 +00002486 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
Ted Kremenek06b4f912011-10-27 17:55:18 +00002487 if (!getPreambleFile(this).empty()) {
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00002488 std::string CompleteFilePath(File);
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00002489
Ilya Biryukovaf69e402017-05-23 11:37:52 +00002490 auto VFS = FileMgr.getVirtualFileSystem();
2491 auto CompleteFileStatus = VFS->status(CompleteFilePath);
2492 if (CompleteFileStatus) {
2493 llvm::sys::fs::UniqueID CompleteFileID = CompleteFileStatus->getUniqueID();
2494
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00002495 std::string MainPath(OriginalSourceFile);
Ilya Biryukovaf69e402017-05-23 11:37:52 +00002496 auto MainStatus = VFS->status(MainPath);
2497 if (MainStatus) {
2498 llvm::sys::fs::UniqueID MainID = MainStatus->getUniqueID();
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00002499 if (CompleteFileID == MainID && Line > 1)
Rafael Espindola2346a372014-08-18 18:47:08 +00002500 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(
Ilya Biryukovaf69e402017-05-23 11:37:52 +00002501 PCHContainerOps, Inv, VFS, false, Line - 1);
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00002502 }
2503 }
Douglas Gregor028d3e42010-08-09 20:45:32 +00002504 }
2505
2506 // If the main file has been overridden due to the use of a preamble,
2507 // make that override happen and introduce the preamble.
2508 if (OverrideMainBuffer) {
Rafael Espindola2346a372014-08-18 18:47:08 +00002509 PreprocessorOpts.addRemappedFile(OriginalSourceFile,
2510 OverrideMainBuffer.get());
Douglas Gregor028d3e42010-08-09 20:45:32 +00002511 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
2512 PreprocessorOpts.PrecompiledPreambleBytes.second
2513 = PreambleEndsAtStartOfLine;
Ted Kremenek06b4f912011-10-27 17:55:18 +00002514 PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
Douglas Gregor028d3e42010-08-09 20:45:32 +00002515 PreprocessorOpts.DisablePCHValidation = true;
Rafael Espindola2346a372014-08-18 18:47:08 +00002516
2517 OwnedBuffers.push_back(OverrideMainBuffer.release());
Douglas Gregor7b02b582010-08-20 00:02:33 +00002518 } else {
2519 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
2520 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregor028d3e42010-08-09 20:45:32 +00002521 }
2522
Argyrios Kyrtzidis870704f2012-11-02 22:18:44 +00002523 // Disable the preprocessing record if modules are not enabled.
2524 if (!Clang->getLangOpts().Modules)
2525 PreprocessorOpts.DetailedRecord = false;
Ahmed Charlesb8984322014-03-07 20:03:18 +00002526
2527 std::unique_ptr<SyntaxOnlyAction> Act;
Douglas Gregor8e984da2010-08-04 16:47:14 +00002528 Act.reset(new SyntaxOnlyAction);
Douglas Gregor32fbe312012-01-20 16:28:04 +00002529 if (Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
Douglas Gregor8e984da2010-08-04 16:47:14 +00002530 Act->Execute();
2531 Act->EndSourceFile();
2532 }
Douglas Gregor8e984da2010-08-04 16:47:14 +00002533}
Douglas Gregore9386682010-08-13 05:36:37 +00002534
Argyrios Kyrtzidis39a76382012-09-26 16:39:46 +00002535bool ASTUnit::Save(StringRef File) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00002536 if (HadModuleLoaderFatalFailure)
2537 return true;
2538
Argyrios Kyrtzidis55e75572011-07-21 18:44:49 +00002539 // Write to a temporary file and later rename it to the actual file, to avoid
2540 // possible race conditions.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00002541 SmallString<128> TempPath;
Argyrios Kyrtzidis08a2bfd2011-07-28 00:45:10 +00002542 TempPath = File;
2543 TempPath += "-%%%%%%%%";
2544 int fd;
Yaron Keren92e1b622015-03-18 10:17:07 +00002545 if (llvm::sys::fs::createUniqueFile(TempPath, fd, TempPath))
Argyrios Kyrtzidis39a76382012-09-26 16:39:46 +00002546 return true;
Argyrios Kyrtzidis55e75572011-07-21 18:44:49 +00002547
Douglas Gregore9386682010-08-13 05:36:37 +00002548 // FIXME: Can we somehow regenerate the stat cache here, or do we need to
2549 // unconditionally create a stat cache when we parse the file?
Argyrios Kyrtzidis08a2bfd2011-07-28 00:45:10 +00002550 llvm::raw_fd_ostream Out(fd, /*shouldClose=*/true);
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00002551
2552 serialize(Out);
2553 Out.close();
Argyrios Kyrtzidiseeea16a2012-03-13 02:17:06 +00002554 if (Out.has_error()) {
2555 Out.clear_error();
Argyrios Kyrtzidis39a76382012-09-26 16:39:46 +00002556 return true;
Argyrios Kyrtzidiseeea16a2012-03-13 02:17:06 +00002557 }
Argyrios Kyrtzidis55e75572011-07-21 18:44:49 +00002558
Yaron Keren92e1b622015-03-18 10:17:07 +00002559 if (llvm::sys::fs::rename(TempPath, File)) {
2560 llvm::sys::fs::remove(TempPath);
Argyrios Kyrtzidis39a76382012-09-26 16:39:46 +00002561 return true;
Argyrios Kyrtzidis55e75572011-07-21 18:44:49 +00002562 }
2563
Argyrios Kyrtzidis39a76382012-09-26 16:39:46 +00002564 return false;
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00002565}
2566
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00002567static bool serializeUnit(ASTWriter &Writer,
2568 SmallVectorImpl<char> &Buffer,
2569 Sema &S,
2570 bool hasErrors,
2571 raw_ostream &OS) {
Craig Topper49a27902014-05-22 04:46:25 +00002572 Writer.WriteAST(S, std::string(), nullptr, "", hasErrors);
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00002573
2574 // Write the generated bitstream to "Out".
2575 if (!Buffer.empty())
2576 OS.write(Buffer.data(), Buffer.size());
2577
2578 return false;
2579}
2580
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002581bool ASTUnit::serialize(raw_ostream &OS) {
Argyrios Kyrtzidis70ec1c72016-07-13 20:35:26 +00002582 // For serialization we are lenient if the errors were only warn-as-error kind.
2583 bool hasErrors = getDiagnostics().hasUncompilableErrorOccurred();
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00002584
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00002585 if (WriterData)
2586 return serializeUnit(WriterData->Writer, WriterData->Buffer,
2587 getSema(), hasErrors, OS);
2588
Daniel Dunbar9a963862012-02-29 20:31:23 +00002589 SmallString<128> Buffer;
Douglas Gregore9386682010-08-13 05:36:37 +00002590 llvm::BitstreamWriter Stream(Buffer);
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00002591 MemoryBufferCache PCMCache;
2592 ASTWriter Writer(Stream, Buffer, PCMCache, {});
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00002593 return serializeUnit(Writer, Buffer, getSema(), hasErrors, OS);
Douglas Gregore9386682010-08-13 05:36:37 +00002594}
Douglas Gregor925296b2011-07-19 16:10:42 +00002595
2596typedef ContinuousRangeMap<unsigned, int, 2> SLocRemap;
2597
Douglas Gregor925296b2011-07-19 16:10:42 +00002598void ASTUnit::TranslateStoredDiagnostics(
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002599 FileManager &FileMgr,
Douglas Gregor925296b2011-07-19 16:10:42 +00002600 SourceManager &SrcMgr,
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002601 const SmallVectorImpl<StandaloneDiagnostic> &Diags,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002602 SmallVectorImpl<StoredDiagnostic> &Out) {
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002603 // Map the standalone diagnostic into the new source manager. We also need to
2604 // remap all the locations to the new view. This includes the diag location,
2605 // any associated source ranges, and the source ranges of associated fix-its.
Douglas Gregor925296b2011-07-19 16:10:42 +00002606 // FIXME: There should be a cleaner way to do this.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002607 SmallVector<StoredDiagnostic, 4> Result;
Douglas Gregor925296b2011-07-19 16:10:42 +00002608 Result.reserve(Diags.size());
Erik Verbruggenefe6fa52017-06-09 08:29:58 +00002609
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00002610 for (const StandaloneDiagnostic &SD : Diags) {
Douglas Gregor925296b2011-07-19 16:10:42 +00002611 // Rebuild the StoredDiagnostic.
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002612 if (SD.Filename.empty())
2613 continue;
2614 const FileEntry *FE = FileMgr.getFile(SD.Filename);
2615 if (!FE)
2616 continue;
Erik Verbruggenefe6fa52017-06-09 08:29:58 +00002617 SourceLocation FileLoc;
2618 auto ItFileID = PreambleSrcLocCache.find(SD.Filename);
2619 if (ItFileID == PreambleSrcLocCache.end()) {
2620 FileID FID = SrcMgr.translateFile(FE);
2621 FileLoc = SrcMgr.getLocForStartOfFile(FID);
2622 PreambleSrcLocCache[SD.Filename] = FileLoc;
2623 } else {
2624 FileLoc = ItFileID->getValue();
Erik Verbruggen2c7c38d2017-02-16 09:49:30 +00002625 }
Erik Verbruggenefe6fa52017-06-09 08:29:58 +00002626
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002627 if (FileLoc.isInvalid())
2628 continue;
2629 SourceLocation L = FileLoc.getLocWithOffset(SD.LocOffset);
Douglas Gregor925296b2011-07-19 16:10:42 +00002630 FullSourceLoc Loc(L, SrcMgr);
2631
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002632 SmallVector<CharSourceRange, 4> Ranges;
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002633 Ranges.reserve(SD.Ranges.size());
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00002634 for (const auto &Range : SD.Ranges) {
2635 SourceLocation BL = FileLoc.getLocWithOffset(Range.first);
2636 SourceLocation EL = FileLoc.getLocWithOffset(Range.second);
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002637 Ranges.push_back(CharSourceRange::getCharRange(BL, EL));
Douglas Gregor925296b2011-07-19 16:10:42 +00002638 }
2639
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002640 SmallVector<FixItHint, 2> FixIts;
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002641 FixIts.reserve(SD.FixIts.size());
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00002642 for (const StandaloneFixIt &FixIt : SD.FixIts) {
Douglas Gregor925296b2011-07-19 16:10:42 +00002643 FixIts.push_back(FixItHint());
2644 FixItHint &FH = FixIts.back();
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00002645 FH.CodeToInsert = FixIt.CodeToInsert;
2646 SourceLocation BL = FileLoc.getLocWithOffset(FixIt.RemoveRange.first);
2647 SourceLocation EL = FileLoc.getLocWithOffset(FixIt.RemoveRange.second);
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002648 FH.RemoveRange = CharSourceRange::getCharRange(BL, EL);
Douglas Gregor925296b2011-07-19 16:10:42 +00002649 }
2650
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002651 Result.push_back(StoredDiagnostic(SD.Level, SD.ID,
2652 SD.Message, Loc, Ranges, FixIts));
Douglas Gregor925296b2011-07-19 16:10:42 +00002653 }
2654 Result.swap(Out);
2655}
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002656
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00002657void ASTUnit::addFileLevelDecl(Decl *D) {
2658 assert(D);
Douglas Gregor61d63d02011-11-07 18:53:57 +00002659
2660 // We only care about local declarations.
2661 if (D->isFromASTFile())
2662 return;
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00002663
2664 SourceManager &SM = *SourceMgr;
2665 SourceLocation Loc = D->getLocation();
2666 if (Loc.isInvalid() || !SM.isLocalSourceLocation(Loc))
2667 return;
2668
2669 // We only keep track of the file-level declarations of each file.
2670 if (!D->getLexicalDeclContext()->isFileContext())
2671 return;
2672
2673 SourceLocation FileLoc = SM.getFileLoc(Loc);
2674 assert(SM.isLocalSourceLocation(FileLoc));
2675 FileID FID;
2676 unsigned Offset;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002677 std::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc);
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00002678 if (FID.isInvalid())
2679 return;
2680
2681 LocDeclsTy *&Decls = FileDecls[FID];
2682 if (!Decls)
2683 Decls = new LocDeclsTy();
2684
2685 std::pair<unsigned, Decl *> LocDecl(Offset, D);
2686
2687 if (Decls->empty() || Decls->back().first <= Offset) {
2688 Decls->push_back(LocDecl);
2689 return;
2690 }
2691
Benjamin Kramer45025c02013-08-24 13:22:59 +00002692 LocDeclsTy::iterator I = std::upper_bound(Decls->begin(), Decls->end(),
2693 LocDecl, llvm::less_first());
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00002694
2695 Decls->insert(I, LocDecl);
2696}
2697
Argyrios Kyrtzidise9681522011-11-03 02:20:32 +00002698void ASTUnit::findFileRegionDecls(FileID File, unsigned Offset, unsigned Length,
2699 SmallVectorImpl<Decl *> &Decls) {
2700 if (File.isInvalid())
2701 return;
2702
2703 if (SourceMgr->isLoadedFileID(File)) {
2704 assert(Ctx->getExternalSource() && "No external source!");
2705 return Ctx->getExternalSource()->FindFileRegionDecls(File, Offset, Length,
2706 Decls);
2707 }
2708
2709 FileDeclsTy::iterator I = FileDecls.find(File);
2710 if (I == FileDecls.end())
2711 return;
2712
2713 LocDeclsTy &LocDecls = *I->second;
2714 if (LocDecls.empty())
2715 return;
2716
Benjamin Kramere3e855b2013-08-24 13:12:34 +00002717 LocDeclsTy::iterator BeginIt =
2718 std::lower_bound(LocDecls.begin(), LocDecls.end(),
Craig Topper49a27902014-05-22 04:46:25 +00002719 std::make_pair(Offset, (Decl *)nullptr),
2720 llvm::less_first());
Argyrios Kyrtzidise9681522011-11-03 02:20:32 +00002721 if (BeginIt != LocDecls.begin())
2722 --BeginIt;
2723
Argyrios Kyrtzidis8ad3bab2011-11-23 20:27:36 +00002724 // If we are pointing at a top-level decl inside an objc container, we need
2725 // to backtrack until we find it otherwise we will fail to report that the
2726 // region overlaps with an objc container.
2727 while (BeginIt != LocDecls.begin() &&
2728 BeginIt->second->isTopLevelDeclInObjCContainer())
2729 --BeginIt;
2730
Benjamin Kramere3e855b2013-08-24 13:12:34 +00002731 LocDeclsTy::iterator EndIt = std::upper_bound(
2732 LocDecls.begin(), LocDecls.end(),
Craig Topper49a27902014-05-22 04:46:25 +00002733 std::make_pair(Offset + Length, (Decl *)nullptr), llvm::less_first());
Argyrios Kyrtzidise9681522011-11-03 02:20:32 +00002734 if (EndIt != LocDecls.end())
2735 ++EndIt;
2736
2737 for (LocDeclsTy::iterator DIt = BeginIt; DIt != EndIt; ++DIt)
2738 Decls.push_back(DIt->second);
2739}
2740
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002741SourceLocation ASTUnit::getLocation(const FileEntry *File,
2742 unsigned Line, unsigned Col) const {
2743 const SourceManager &SM = getSourceManager();
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00002744 SourceLocation Loc = SM.translateFileLineCol(File, Line, Col);
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002745 return SM.getMacroArgExpandedLocation(Loc);
2746}
2747
2748SourceLocation ASTUnit::getLocation(const FileEntry *File,
2749 unsigned Offset) const {
2750 const SourceManager &SM = getSourceManager();
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00002751 SourceLocation FileLoc = SM.translateFileLineCol(File, 1, 1);
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002752 return SM.getMacroArgExpandedLocation(FileLoc.getLocWithOffset(Offset));
2753}
2754
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00002755/// \brief If \arg Loc is a loaded location from the preamble, returns
2756/// the corresponding local location of the main file, otherwise it returns
2757/// \arg Loc.
2758SourceLocation ASTUnit::mapLocationFromPreamble(SourceLocation Loc) {
2759 FileID PreambleID;
2760 if (SourceMgr)
2761 PreambleID = SourceMgr->getPreambleFileID();
2762
2763 if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2764 return Loc;
2765
2766 unsigned Offs;
2767 if (SourceMgr->isInFileID(Loc, PreambleID, &Offs) && Offs < Preamble.size()) {
2768 SourceLocation FileLoc
2769 = SourceMgr->getLocForStartOfFile(SourceMgr->getMainFileID());
2770 return FileLoc.getLocWithOffset(Offs);
2771 }
2772
2773 return Loc;
2774}
2775
2776/// \brief If \arg Loc is a local location of the main file but inside the
2777/// preamble chunk, returns the corresponding loaded location from the
2778/// preamble, otherwise it returns \arg Loc.
2779SourceLocation ASTUnit::mapLocationToPreamble(SourceLocation Loc) {
2780 FileID PreambleID;
2781 if (SourceMgr)
2782 PreambleID = SourceMgr->getPreambleFileID();
2783
2784 if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2785 return Loc;
2786
2787 unsigned Offs;
2788 if (SourceMgr->isInFileID(Loc, SourceMgr->getMainFileID(), &Offs) &&
2789 Offs < Preamble.size()) {
2790 SourceLocation FileLoc = SourceMgr->getLocForStartOfFile(PreambleID);
2791 return FileLoc.getLocWithOffset(Offs);
2792 }
2793
2794 return Loc;
2795}
2796
Argyrios Kyrtzidis429ec022011-10-25 00:29:50 +00002797bool ASTUnit::isInPreambleFileID(SourceLocation Loc) {
2798 FileID FID;
2799 if (SourceMgr)
2800 FID = SourceMgr->getPreambleFileID();
2801
2802 if (Loc.isInvalid() || FID.isInvalid())
2803 return false;
2804
2805 return SourceMgr->isInFileID(Loc, FID);
2806}
2807
2808bool ASTUnit::isInMainFileID(SourceLocation Loc) {
2809 FileID FID;
2810 if (SourceMgr)
2811 FID = SourceMgr->getMainFileID();
2812
2813 if (Loc.isInvalid() || FID.isInvalid())
2814 return false;
2815
2816 return SourceMgr->isInFileID(Loc, FID);
2817}
2818
2819SourceLocation ASTUnit::getEndOfPreambleFileID() {
2820 FileID FID;
2821 if (SourceMgr)
2822 FID = SourceMgr->getPreambleFileID();
2823
2824 if (FID.isInvalid())
2825 return SourceLocation();
2826
2827 return SourceMgr->getLocForEndOfFile(FID);
2828}
2829
2830SourceLocation ASTUnit::getStartOfMainFileID() {
2831 FileID FID;
2832 if (SourceMgr)
2833 FID = SourceMgr->getMainFileID();
2834
2835 if (FID.isInvalid())
2836 return SourceLocation();
2837
2838 return SourceMgr->getLocForStartOfFile(FID);
2839}
2840
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00002841llvm::iterator_range<PreprocessingRecord::iterator>
Argyrios Kyrtzidisd4fcf5802012-10-02 16:10:51 +00002842ASTUnit::getLocalPreprocessingEntities() const {
2843 if (isMainFileAST()) {
2844 serialization::ModuleFile &
2845 Mod = Reader->getModuleManager().getPrimaryModule();
2846 return Reader->getModulePreprocessedEntities(Mod);
2847 }
2848
2849 if (PreprocessingRecord *PPRec = PP->getPreprocessingRecord())
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00002850 return llvm::make_range(PPRec->local_begin(), PPRec->local_end());
Argyrios Kyrtzidisd4fcf5802012-10-02 16:10:51 +00002851
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00002852 return llvm::make_range(PreprocessingRecord::iterator(),
2853 PreprocessingRecord::iterator());
Argyrios Kyrtzidisd4fcf5802012-10-02 16:10:51 +00002854}
2855
Argyrios Kyrtzidise514b202012-10-03 01:58:28 +00002856bool ASTUnit::visitLocalTopLevelDecls(void *context, DeclVisitorFn Fn) {
Argyrios Kyrtzidis10e78462012-10-02 21:09:13 +00002857 if (isMainFileAST()) {
2858 serialization::ModuleFile &
2859 Mod = Reader->getModuleManager().getPrimaryModule();
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00002860 for (const Decl *D : Reader->getModuleFileLevelDecls(Mod)) {
2861 if (!Fn(context, D))
Argyrios Kyrtzidis10e78462012-10-02 21:09:13 +00002862 return false;
2863 }
2864
2865 return true;
2866 }
2867
2868 for (ASTUnit::top_level_iterator TL = top_level_begin(),
2869 TLEnd = top_level_end();
2870 TL != TLEnd; ++TL) {
2871 if (!Fn(context, *TL))
2872 return false;
2873 }
2874
2875 return true;
2876}
2877
Argyrios Kyrtzidisf484b132012-10-03 21:05:51 +00002878const FileEntry *ASTUnit::getPCHFile() {
2879 if (!Reader)
Craig Topper49a27902014-05-22 04:46:25 +00002880 return nullptr;
Argyrios Kyrtzidisf484b132012-10-03 21:05:51 +00002881
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00002882 serialization::ModuleFile *Mod = nullptr;
2883 Reader->getModuleManager().visit([&Mod](serialization::ModuleFile &M) {
2884 switch (M.Kind) {
2885 case serialization::MK_ImplicitModule:
2886 case serialization::MK_ExplicitModule:
Manman Ren11f2a472016-08-18 17:42:15 +00002887 case serialization::MK_PrebuiltModule:
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00002888 return true; // skip dependencies.
2889 case serialization::MK_PCH:
2890 Mod = &M;
2891 return true; // found it.
2892 case serialization::MK_Preamble:
2893 return false; // look in dependencies.
2894 case serialization::MK_MainFile:
2895 return false; // look in dependencies.
2896 }
2897
2898 return true;
2899 });
2900 if (Mod)
2901 return Mod->File;
Argyrios Kyrtzidisf484b132012-10-03 21:05:51 +00002902
Craig Topper49a27902014-05-22 04:46:25 +00002903 return nullptr;
Argyrios Kyrtzidisf484b132012-10-03 21:05:51 +00002904}
2905
Argyrios Kyrtzidise445c722012-10-10 02:12:47 +00002906bool ASTUnit::isModuleFile() {
Richard Smithab755972017-06-05 18:10:11 +00002907 return isMainFileAST() && getLangOpts().isCompilingModule();
2908}
2909
2910InputKind ASTUnit::getInputKind() const {
2911 auto &LangOpts = getLangOpts();
2912
2913 InputKind::Language Lang;
2914 if (LangOpts.OpenCL)
2915 Lang = InputKind::OpenCL;
2916 else if (LangOpts.CUDA)
2917 Lang = InputKind::CUDA;
2918 else if (LangOpts.RenderScript)
2919 Lang = InputKind::RenderScript;
2920 else if (LangOpts.CPlusPlus)
2921 Lang = LangOpts.ObjC1 ? InputKind::ObjCXX : InputKind::CXX;
2922 else
2923 Lang = LangOpts.ObjC1 ? InputKind::ObjC : InputKind::C;
2924
2925 InputKind::Format Fmt = InputKind::Source;
2926 if (LangOpts.getCompilingModule() == LangOptions::CMK_ModuleMap)
2927 Fmt = InputKind::ModuleMap;
2928
2929 // We don't know if input was preprocessed. Assume not.
2930 bool PP = false;
2931
2932 return InputKind(Lang, Fmt, PP);
Argyrios Kyrtzidise445c722012-10-10 02:12:47 +00002933}
2934
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002935void ASTUnit::PreambleData::countLines() const {
2936 NumLines = 0;
2937 if (empty())
2938 return;
2939
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00002940 NumLines = std::count(Buffer.begin(), Buffer.end(), '\n');
2941
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002942 if (Buffer.back() != '\n')
2943 ++NumLines;
2944}
Argyrios Kyrtzidisebf01362011-10-10 21:57:12 +00002945
2946#ifndef NDEBUG
2947ASTUnit::ConcurrencyState::ConcurrencyState() {
2948 Mutex = new llvm::sys::MutexImpl(/*recursive=*/true);
2949}
2950
2951ASTUnit::ConcurrencyState::~ConcurrencyState() {
2952 delete static_cast<llvm::sys::MutexImpl *>(Mutex);
2953}
2954
2955void ASTUnit::ConcurrencyState::start() {
2956 bool acquired = static_cast<llvm::sys::MutexImpl *>(Mutex)->tryacquire();
2957 assert(acquired && "Concurrent access to ASTUnit!");
2958}
2959
2960void ASTUnit::ConcurrencyState::finish() {
2961 static_cast<llvm::sys::MutexImpl *>(Mutex)->release();
2962}
2963
2964#else // NDEBUG
2965
Hans Wennborgdcfba332015-10-06 23:40:43 +00002966ASTUnit::ConcurrencyState::ConcurrencyState() { Mutex = nullptr; }
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +00002967ASTUnit::ConcurrencyState::~ConcurrencyState() {}
Argyrios Kyrtzidisebf01362011-10-10 21:57:12 +00002968void ASTUnit::ConcurrencyState::start() {}
2969void ASTUnit::ConcurrencyState::finish() {}
2970
Hans Wennborgdcfba332015-10-06 23:40:43 +00002971#endif // NDEBUG