blob: 635d566159bdf04b2179b39a9f330a0842b3f1d1 [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"
21#include "clang/Basic/TargetInfo.h"
22#include "clang/Basic/TargetOptions.h"
Ben Langmuirc8130a72014-02-20 21:59:23 +000023#include "clang/Basic/VirtualFileSystem.h"
Daniel Dunbar764c0822009-12-01 09:51:01 +000024#include "clang/Frontend/CompilerInstance.h"
25#include "clang/Frontend/FrontendActions.h"
Daniel Dunbar55a17b62009-12-02 03:23:45 +000026#include "clang/Frontend/FrontendDiagnostic.h"
Daniel Dunbar764c0822009-12-01 09:51:01 +000027#include "clang/Frontend/FrontendOptions.h"
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +000028#include "clang/Frontend/MultiplexConsumer.h"
Douglas Gregor36e3b5c2010-10-11 21:37:58 +000029#include "clang/Frontend/Utils.h"
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000030#include "clang/Lex/HeaderSearch.h"
31#include "clang/Lex/Preprocessor.h"
Douglas Gregor1452ff12012-10-24 17:46:57 +000032#include "clang/Lex/PreprocessorOptions.h"
David Blaikie0a4e61f2013-09-13 18:32:52 +000033#include "clang/Sema/Sema.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000034#include "clang/Serialization/ASTReader.h"
35#include "clang/Serialization/ASTWriter.h"
Chris Lattnerce6c42f2011-03-23 04:04:01 +000036#include "llvm/ADT/ArrayRef.h"
Douglas Gregordf7a79a2011-02-16 18:16:54 +000037#include "llvm/ADT/StringExtras.h"
Douglas Gregor40a5a7d2010-08-16 23:08:34 +000038#include "llvm/ADT/StringSet.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000039#include "llvm/Support/CrashRecoveryContext.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000040#include "llvm/Support/Host.h"
41#include "llvm/Support/MemoryBuffer.h"
Argyrios Kyrtzidisebf01362011-10-10 21:57:12 +000042#include "llvm/Support/Mutex.h"
Ted Kremenekbd307a52011-10-27 19:44:25 +000043#include "llvm/Support/MutexGuard.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000044#include "llvm/Support/Path.h"
45#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
Rafael Espindolabc7d9492013-06-26 03:52:38 +000087 /// \brief Temporary files that should be removed when the ASTUnit is
Ted Kremenek06b4f912011-10-27 17:55:18 +000088 /// destroyed.
Rafael Espindolabc7d9492013-06-26 03:52:38 +000089 SmallVector<std::string, 4> TemporaryFiles;
90
Ted Kremenek06b4f912011-10-27 17:55:18 +000091 /// \brief Erase temporary files.
92 void CleanTemporaryFiles();
93
94 /// \brief Erase the preamble file.
95 void CleanPreambleFile();
96
97 /// \brief Erase temporary files and the preamble file.
98 void Cleanup();
99 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000100}
Ted Kremenek06b4f912011-10-27 17:55:18 +0000101
Ted Kremenekbd307a52011-10-27 19:44:25 +0000102static llvm::sys::SmartMutex<false> &getOnDiskMutex() {
103 static llvm::sys::SmartMutex<false> M(/* recursive = */ true);
104 return M;
105}
106
Dmitri Gribenkob2aa9232012-11-15 14:28:07 +0000107static void cleanupOnDiskMapAtExit();
Ted Kremenek06b4f912011-10-27 17:55:18 +0000108
Dylan Noblesmithcdd31512014-08-24 18:59:52 +0000109typedef llvm::DenseMap<const ASTUnit *,
110 std::unique_ptr<OnDiskData>> OnDiskDataMap;
Ted Kremenek06b4f912011-10-27 17:55:18 +0000111static OnDiskDataMap &getOnDiskDataMap() {
112 static OnDiskDataMap M;
113 static bool hasRegisteredAtExit = false;
114 if (!hasRegisteredAtExit) {
115 hasRegisteredAtExit = true;
116 atexit(cleanupOnDiskMapAtExit);
117 }
118 return M;
119}
120
Dmitri Gribenkob2aa9232012-11-15 14:28:07 +0000121static void cleanupOnDiskMapAtExit() {
Argyrios Kyrtzidis4cf2ffe2012-07-03 16:30:52 +0000122 // Use the mutex because there can be an alive thread destroying an ASTUnit.
123 llvm::MutexGuard Guard(getOnDiskMutex());
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000124 for (const auto &I : getOnDiskDataMap()) {
Ted Kremenek06b4f912011-10-27 17:55:18 +0000125 // We don't worry about freeing the memory associated with OnDiskDataMap.
126 // All we care about is erasing stale files.
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000127 I.second->Cleanup();
Ted Kremenek06b4f912011-10-27 17:55:18 +0000128 }
129}
130
131static OnDiskData &getOnDiskData(const ASTUnit *AU) {
Ted Kremenekbd307a52011-10-27 19:44:25 +0000132 // We require the mutex since we are modifying the structure of the
133 // DenseMap.
134 llvm::MutexGuard Guard(getOnDiskMutex());
Ted Kremenek06b4f912011-10-27 17:55:18 +0000135 OnDiskDataMap &M = getOnDiskDataMap();
Dylan Noblesmithcdd31512014-08-24 18:59:52 +0000136 auto &D = M[AU];
Ted Kremenek06b4f912011-10-27 17:55:18 +0000137 if (!D)
Dylan Noblesmithcdd31512014-08-24 18:59:52 +0000138 D = llvm::make_unique<OnDiskData>();
Ted Kremenek06b4f912011-10-27 17:55:18 +0000139 return *D;
140}
141
142static void erasePreambleFile(const ASTUnit *AU) {
143 getOnDiskData(AU).CleanPreambleFile();
144}
145
146static void removeOnDiskEntry(const ASTUnit *AU) {
Ted Kremenekbd307a52011-10-27 19:44:25 +0000147 // We require the mutex since we are modifying the structure of the
148 // DenseMap.
149 llvm::MutexGuard Guard(getOnDiskMutex());
Ted Kremenek06b4f912011-10-27 17:55:18 +0000150 OnDiskDataMap &M = getOnDiskDataMap();
151 OnDiskDataMap::iterator I = M.find(AU);
152 if (I != M.end()) {
153 I->second->Cleanup();
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000154 M.erase(I);
Ted Kremenek06b4f912011-10-27 17:55:18 +0000155 }
156}
157
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000158static void setPreambleFile(const ASTUnit *AU, StringRef preambleFile) {
Ted Kremenek06b4f912011-10-27 17:55:18 +0000159 getOnDiskData(AU).PreambleFile = preambleFile;
160}
161
162static const std::string &getPreambleFile(const ASTUnit *AU) {
163 return getOnDiskData(AU).PreambleFile;
164}
165
166void OnDiskData::CleanTemporaryFiles() {
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000167 for (StringRef File : TemporaryFiles)
168 llvm::sys::fs::remove(File);
Rafael Espindolabc7d9492013-06-26 03:52:38 +0000169 TemporaryFiles.clear();
Ted Kremenek06b4f912011-10-27 17:55:18 +0000170}
171
172void OnDiskData::CleanPreambleFile() {
173 if (!PreambleFile.empty()) {
Rafael Espindolabc4aa552013-06-26 04:02:37 +0000174 llvm::sys::fs::remove(PreambleFile);
Ted Kremenek06b4f912011-10-27 17:55:18 +0000175 PreambleFile.clear();
176 }
177}
178
179void OnDiskData::Cleanup() {
180 CleanTemporaryFiles();
181 CleanPreambleFile();
182}
183
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000184struct ASTUnit::ASTWriterData {
185 SmallString<128> Buffer;
186 llvm::BitstreamWriter Stream;
187 ASTWriter Writer;
188
Douglas Gregor6623e1f2015-11-03 18:33:07 +0000189 ASTWriterData() : Stream(Buffer), Writer(Stream, { }) { }
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000190};
191
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000192void ASTUnit::clearFileLevelDecls() {
Reid Kleckner588c9372014-02-19 23:44:52 +0000193 llvm::DeleteContainerSeconds(FileDecls);
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000194}
195
Ted Kremenek06b4f912011-10-27 17:55:18 +0000196void ASTUnit::CleanTemporaryFiles() {
197 getOnDiskData(this).CleanTemporaryFiles();
198}
199
Rafael Espindolabc7d9492013-06-26 03:52:38 +0000200void ASTUnit::addTemporaryFile(StringRef TempFile) {
Ted Kremenek06b4f912011-10-27 17:55:18 +0000201 getOnDiskData(this).TemporaryFiles.push_back(TempFile);
Douglas Gregor16896c42010-10-28 15:44:59 +0000202}
203
Douglas Gregorbb420ab2010-08-04 05:53:38 +0000204/// \brief After failing to build a precompiled preamble (due to
205/// errors in the source that occurs in the preamble), the number of
206/// reparses during which we'll skip even trying to precompile the
207/// preamble.
208const unsigned DefaultPreambleRebuildInterval = 5;
209
Douglas Gregor68dbaea2010-11-17 00:13:31 +0000210/// \brief Tracks the number of ASTUnit objects that are currently active.
211///
212/// Used for debugging purposes only.
Benjamin Kramer4527fb22014-03-02 17:08:31 +0000213static std::atomic<unsigned> ActiveASTUnitObjects;
Douglas Gregor68dbaea2010-11-17 00:13:31 +0000214
Douglas Gregord03e8232010-04-05 21:10:19 +0000215ASTUnit::ASTUnit(bool _MainFileIsAST)
Craig Topper49a27902014-05-22 04:46:25 +0000216 : Reader(nullptr), HadModuleLoaderFatalFailure(false),
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +0000217 OnlyLocalDecls(false), CaptureDiagnostics(false),
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +0000218 MainFileIsAST(_MainFileIsAST),
Douglas Gregor69f74f82011-08-25 22:30:56 +0000219 TUKind(TU_Complete), WantTiming(getenv("LIBCLANG_TIMING")),
Argyrios Kyrtzidis4954bc12011-03-05 01:03:48 +0000220 OwnsRemappedFileBuffers(true),
Douglas Gregor16896c42010-10-28 15:44:59 +0000221 NumStoredDiagnosticsFromDriver(0),
Rafael Espindola4674a872014-08-13 17:08:22 +0000222 PreambleRebuildCounter(0),
Rafael Espindolafa49c0b2014-08-13 16:47:00 +0000223 NumWarningsInPreamble(0),
Douglas Gregor2c8bd472010-08-17 00:40:40 +0000224 ShouldCacheCodeCompletionResults(false),
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +0000225 IncludeBriefCommentsInCodeCompletion(false), UserFilesAreVolatile(false),
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000226 CompletionCacheTopLevelHashValue(0),
227 PreambleTopLevelHashValue(0),
228 CurrentTopLevelHashValue(0),
Douglas Gregor4740c452010-08-19 00:45:44 +0000229 UnsafeToFree(false) {
Benjamin Kramer4527fb22014-03-02 17:08:31 +0000230 if (getenv("LIBCLANG_OBJTRACKING"))
231 fprintf(stderr, "+++ %u translation units\n", ++ActiveASTUnitObjects);
Douglas Gregor15ba0b32010-07-30 20:58:08 +0000232}
Douglas Gregord03e8232010-04-05 21:10:19 +0000233
Daniel Dunbar764c0822009-12-01 09:51:01 +0000234ASTUnit::~ASTUnit() {
Douglas Gregor6b930962013-05-03 22:58:43 +0000235 // If we loaded from an AST file, balance out the BeginSourceFile call.
236 if (MainFileIsAST && getDiagnostics().getClient()) {
237 getDiagnostics().getClient()->EndSourceFile();
238 }
239
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000240 clearFileLevelDecls();
241
Ted Kremenek06b4f912011-10-27 17:55:18 +0000242 // Clean up the temporary files and the preamble file.
243 removeOnDiskEntry(this);
244
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000245 // Free the buffers associated with remapped files. We are required to
246 // perform this operation here because we explicitly request that the
247 // compiler instance *not* free these buffers for each invocation of the
248 // parser.
Alp Tokerf994cef2014-07-05 03:08:06 +0000249 if (Invocation.get() && OwnsRemappedFileBuffers) {
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000250 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
Alp Toker1b070d22014-07-07 07:47:20 +0000251 for (const auto &RB : PPOpts.RemappedFileBuffers)
252 delete RB.second;
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000253 }
Douglas Gregora0734c52010-08-19 01:33:06 +0000254
Douglas Gregor16896c42010-10-28 15:44:59 +0000255 ClearCachedCompletionResults();
Douglas Gregor68dbaea2010-11-17 00:13:31 +0000256
Benjamin Kramer4527fb22014-03-02 17:08:31 +0000257 if (getenv("LIBCLANG_OBJTRACKING"))
258 fprintf(stderr, "--- %u translation units\n", --ActiveASTUnitObjects);
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000259}
260
Argyrios Kyrtzidisda6e0542012-01-17 18:48:07 +0000261void ASTUnit::setPreprocessor(Preprocessor *pp) { PP = pp; }
262
Douglas Gregor39982192010-08-15 06:18:01 +0000263/// \brief Determine the set of code-completion contexts in which this
264/// declaration should be shown.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000265static unsigned getDeclShowContexts(const NamedDecl *ND,
Douglas Gregor59cab552010-08-16 23:05:20 +0000266 const LangOptions &LangOpts,
267 bool &IsNestedNameSpecifier) {
268 IsNestedNameSpecifier = false;
269
Douglas Gregor39982192010-08-15 06:18:01 +0000270 if (isa<UsingShadowDecl>(ND))
271 ND = dyn_cast<NamedDecl>(ND->getUnderlyingDecl());
272 if (!ND)
273 return 0;
274
Richard Smith697cc9e2012-08-14 03:13:00 +0000275 uint64_t Contexts = 0;
Douglas Gregor39982192010-08-15 06:18:01 +0000276 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND) ||
277 isa<ClassTemplateDecl>(ND) || isa<TemplateTemplateParmDecl>(ND)) {
278 // Types can appear in these contexts.
279 if (LangOpts.CPlusPlus || !isa<TagDecl>(ND))
Richard Smith697cc9e2012-08-14 03:13:00 +0000280 Contexts |= (1LL << CodeCompletionContext::CCC_TopLevel)
281 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
282 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
283 | (1LL << CodeCompletionContext::CCC_Statement)
284 | (1LL << CodeCompletionContext::CCC_Type)
285 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression);
Douglas Gregor39982192010-08-15 06:18:01 +0000286
287 // In C++, types can appear in expressions contexts (for functional casts).
288 if (LangOpts.CPlusPlus)
Richard Smith697cc9e2012-08-14 03:13:00 +0000289 Contexts |= (1LL << CodeCompletionContext::CCC_Expression);
Douglas Gregor39982192010-08-15 06:18:01 +0000290
291 // In Objective-C, message sends can send interfaces. In Objective-C++,
292 // all types are available due to functional casts.
293 if (LangOpts.CPlusPlus || isa<ObjCInterfaceDecl>(ND))
Richard Smith697cc9e2012-08-14 03:13:00 +0000294 Contexts |= (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver);
Douglas Gregor21325842011-07-07 16:03:39 +0000295
296 // In Objective-C, you can only be a subclass of another Objective-C class
297 if (isa<ObjCInterfaceDecl>(ND))
Richard Smith697cc9e2012-08-14 03:13:00 +0000298 Contexts |= (1LL << CodeCompletionContext::CCC_ObjCInterfaceName);
Douglas Gregor39982192010-08-15 06:18:01 +0000299
300 // Deal with tag names.
301 if (isa<EnumDecl>(ND)) {
Richard Smith697cc9e2012-08-14 03:13:00 +0000302 Contexts |= (1LL << CodeCompletionContext::CCC_EnumTag);
Douglas Gregor39982192010-08-15 06:18:01 +0000303
Douglas Gregor59cab552010-08-16 23:05:20 +0000304 // Part of the nested-name-specifier in C++0x.
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000305 if (LangOpts.CPlusPlus11)
Douglas Gregor59cab552010-08-16 23:05:20 +0000306 IsNestedNameSpecifier = true;
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000307 } else if (const RecordDecl *Record = dyn_cast<RecordDecl>(ND)) {
Douglas Gregor39982192010-08-15 06:18:01 +0000308 if (Record->isUnion())
Richard Smith697cc9e2012-08-14 03:13:00 +0000309 Contexts |= (1LL << CodeCompletionContext::CCC_UnionTag);
Douglas Gregor39982192010-08-15 06:18:01 +0000310 else
Richard Smith697cc9e2012-08-14 03:13:00 +0000311 Contexts |= (1LL << CodeCompletionContext::CCC_ClassOrStructTag);
Douglas Gregor39982192010-08-15 06:18:01 +0000312
Douglas Gregor39982192010-08-15 06:18:01 +0000313 if (LangOpts.CPlusPlus)
Douglas Gregor59cab552010-08-16 23:05:20 +0000314 IsNestedNameSpecifier = true;
Douglas Gregor0ac41382010-09-23 23:01:17 +0000315 } else if (isa<ClassTemplateDecl>(ND))
Douglas Gregor59cab552010-08-16 23:05:20 +0000316 IsNestedNameSpecifier = true;
Douglas Gregor39982192010-08-15 06:18:01 +0000317 } else if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
318 // Values can appear in these contexts.
Richard Smith697cc9e2012-08-14 03:13:00 +0000319 Contexts = (1LL << CodeCompletionContext::CCC_Statement)
320 | (1LL << CodeCompletionContext::CCC_Expression)
321 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
322 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver);
Douglas Gregor39982192010-08-15 06:18:01 +0000323 } else if (isa<ObjCProtocolDecl>(ND)) {
Richard Smith697cc9e2012-08-14 03:13:00 +0000324 Contexts = (1LL << CodeCompletionContext::CCC_ObjCProtocolName);
Douglas Gregor21325842011-07-07 16:03:39 +0000325 } else if (isa<ObjCCategoryDecl>(ND)) {
Richard Smith697cc9e2012-08-14 03:13:00 +0000326 Contexts = (1LL << CodeCompletionContext::CCC_ObjCCategoryName);
Douglas Gregor39982192010-08-15 06:18:01 +0000327 } else if (isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) {
Richard Smith697cc9e2012-08-14 03:13:00 +0000328 Contexts = (1LL << CodeCompletionContext::CCC_Namespace);
Douglas Gregor39982192010-08-15 06:18:01 +0000329
330 // Part of the nested-name-specifier.
Douglas Gregor59cab552010-08-16 23:05:20 +0000331 IsNestedNameSpecifier = true;
Douglas Gregor39982192010-08-15 06:18:01 +0000332 }
333
334 return Contexts;
335}
336
Douglas Gregorb14904c2010-08-13 22:48:40 +0000337void ASTUnit::CacheCodeCompletionResults() {
338 if (!TheSema)
339 return;
340
Douglas Gregor16896c42010-10-28 15:44:59 +0000341 SimpleTimer Timer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +0000342 Timer.setOutput("Cache global code completions for " + getMainFileName());
Douglas Gregorb14904c2010-08-13 22:48:40 +0000343
344 // Clear out the previous results.
345 ClearCachedCompletionResults();
346
347 // Gather the set of global code completions.
John McCall276321a2010-08-25 06:19:51 +0000348 typedef CodeCompletionResult Result;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000349 SmallVector<Result, 8> Results;
Douglas Gregor162b7122011-02-16 19:08:06 +0000350 CachedCompletionAllocator = new GlobalCodeCompletionAllocator;
Argyrios Kyrtzidis2bafa002012-11-16 03:34:57 +0000351 CodeCompletionTUInfo CCTUInfo(CachedCompletionAllocator);
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +0000352 TheSema->GatherGlobalCodeCompletions(*CachedCompletionAllocator,
Argyrios Kyrtzidis2bafa002012-11-16 03:34:57 +0000353 CCTUInfo, Results);
Douglas Gregorb14904c2010-08-13 22:48:40 +0000354
355 // Translate global code completions into cached completions.
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000356 llvm::DenseMap<CanQualType, unsigned> CompletionTypes;
Douglas Gregorc3425b12015-07-07 06:20:19 +0000357 CodeCompletionContext CCContext(CodeCompletionContext::CCC_TopLevel);
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000358
359 for (Result &R : Results) {
360 switch (R.Kind) {
Douglas Gregor39982192010-08-15 06:18:01 +0000361 case Result::RK_Declaration: {
Douglas Gregor59cab552010-08-16 23:05:20 +0000362 bool IsNestedNameSpecifier = false;
Douglas Gregor39982192010-08-15 06:18:01 +0000363 CachedCodeCompletionResult CachedResult;
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000364 CachedResult.Completion = R.CreateCodeCompletionString(
Douglas Gregorc3425b12015-07-07 06:20:19 +0000365 *TheSema, CCContext, *CachedCompletionAllocator, CCTUInfo,
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000366 IncludeBriefCommentsInCodeCompletion);
367 CachedResult.ShowInContexts = getDeclShowContexts(
368 R.Declaration, Ctx->getLangOpts(), IsNestedNameSpecifier);
369 CachedResult.Priority = R.Priority;
370 CachedResult.Kind = R.CursorKind;
371 CachedResult.Availability = R.Availability;
Douglas Gregor24747402010-08-16 16:46:30 +0000372
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000373 // Keep track of the type of this completion in an ASTContext-agnostic
374 // way.
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000375 QualType UsageType = getDeclUsageType(*Ctx, R.Declaration);
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000376 if (UsageType.isNull()) {
Douglas Gregor24747402010-08-16 16:46:30 +0000377 CachedResult.TypeClass = STC_Void;
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000378 CachedResult.Type = 0;
379 } else {
380 CanQualType CanUsageType
381 = Ctx->getCanonicalType(UsageType.getUnqualifiedType());
382 CachedResult.TypeClass = getSimplifiedTypeClass(CanUsageType);
383
384 // Determine whether we have already seen this type. If so, we save
385 // ourselves the work of formatting the type string by using the
386 // temporary, CanQualType-based hash table to find the associated value.
387 unsigned &TypeValue = CompletionTypes[CanUsageType];
388 if (TypeValue == 0) {
389 TypeValue = CompletionTypes.size();
390 CachedCompletionTypes[QualType(CanUsageType).getAsString()]
391 = TypeValue;
392 }
393
394 CachedResult.Type = TypeValue;
Douglas Gregor24747402010-08-16 16:46:30 +0000395 }
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000396
Douglas Gregor39982192010-08-15 06:18:01 +0000397 CachedCompletionResults.push_back(CachedResult);
Douglas Gregor59cab552010-08-16 23:05:20 +0000398
399 /// Handle nested-name-specifiers in C++.
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000400 if (TheSema->Context.getLangOpts().CPlusPlus && IsNestedNameSpecifier &&
401 !R.StartsNestedNameSpecifier) {
Douglas Gregor59cab552010-08-16 23:05:20 +0000402 // The contexts in which a nested-name-specifier can appear in C++.
Richard Smith697cc9e2012-08-14 03:13:00 +0000403 uint64_t NNSContexts
404 = (1LL << CodeCompletionContext::CCC_TopLevel)
405 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
406 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
407 | (1LL << CodeCompletionContext::CCC_Statement)
408 | (1LL << CodeCompletionContext::CCC_Expression)
409 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
410 | (1LL << CodeCompletionContext::CCC_EnumTag)
411 | (1LL << CodeCompletionContext::CCC_UnionTag)
412 | (1LL << CodeCompletionContext::CCC_ClassOrStructTag)
413 | (1LL << CodeCompletionContext::CCC_Type)
414 | (1LL << CodeCompletionContext::CCC_PotentiallyQualifiedName)
415 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression);
Douglas Gregor59cab552010-08-16 23:05:20 +0000416
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000417 if (isa<NamespaceDecl>(R.Declaration) ||
418 isa<NamespaceAliasDecl>(R.Declaration))
Richard Smith697cc9e2012-08-14 03:13:00 +0000419 NNSContexts |= (1LL << CodeCompletionContext::CCC_Namespace);
Douglas Gregor59cab552010-08-16 23:05:20 +0000420
421 if (unsigned RemainingContexts
422 = NNSContexts & ~CachedResult.ShowInContexts) {
423 // If there any contexts where this completion can be a
424 // nested-name-specifier but isn't already an option, create a
425 // nested-name-specifier completion.
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000426 R.StartsNestedNameSpecifier = true;
427 CachedResult.Completion = R.CreateCodeCompletionString(
Douglas Gregorc3425b12015-07-07 06:20:19 +0000428 *TheSema, CCContext, *CachedCompletionAllocator, CCTUInfo,
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000429 IncludeBriefCommentsInCodeCompletion);
Douglas Gregor59cab552010-08-16 23:05:20 +0000430 CachedResult.ShowInContexts = RemainingContexts;
431 CachedResult.Priority = CCP_NestedNameSpecifier;
432 CachedResult.TypeClass = STC_Void;
433 CachedResult.Type = 0;
434 CachedCompletionResults.push_back(CachedResult);
435 }
436 }
Douglas Gregorb14904c2010-08-13 22:48:40 +0000437 break;
Douglas Gregor39982192010-08-15 06:18:01 +0000438 }
439
Douglas Gregorb14904c2010-08-13 22:48:40 +0000440 case Result::RK_Keyword:
441 case Result::RK_Pattern:
442 // Ignore keywords and patterns; we don't care, since they are so
443 // easily regenerated.
444 break;
445
446 case Result::RK_Macro: {
447 CachedCodeCompletionResult CachedResult;
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000448 CachedResult.Completion = R.CreateCodeCompletionString(
Douglas Gregorc3425b12015-07-07 06:20:19 +0000449 *TheSema, CCContext, *CachedCompletionAllocator, CCTUInfo,
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000450 IncludeBriefCommentsInCodeCompletion);
Douglas Gregorb14904c2010-08-13 22:48:40 +0000451 CachedResult.ShowInContexts
Richard Smith697cc9e2012-08-14 03:13:00 +0000452 = (1LL << CodeCompletionContext::CCC_TopLevel)
453 | (1LL << CodeCompletionContext::CCC_ObjCInterface)
454 | (1LL << CodeCompletionContext::CCC_ObjCImplementation)
455 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
456 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
457 | (1LL << CodeCompletionContext::CCC_Statement)
458 | (1LL << CodeCompletionContext::CCC_Expression)
459 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
460 | (1LL << CodeCompletionContext::CCC_MacroNameUse)
461 | (1LL << CodeCompletionContext::CCC_PreprocessorExpression)
462 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
463 | (1LL << CodeCompletionContext::CCC_OtherWithMacros);
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000464
465 CachedResult.Priority = R.Priority;
466 CachedResult.Kind = R.CursorKind;
467 CachedResult.Availability = R.Availability;
Douglas Gregor6e240332010-08-16 16:18:59 +0000468 CachedResult.TypeClass = STC_Void;
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000469 CachedResult.Type = 0;
Douglas Gregorb14904c2010-08-13 22:48:40 +0000470 CachedCompletionResults.push_back(CachedResult);
471 break;
472 }
473 }
Douglas Gregorb14904c2010-08-13 22:48:40 +0000474 }
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000475
476 // Save the current top-level hash value.
477 CompletionCacheTopLevelHashValue = CurrentTopLevelHashValue;
Douglas Gregorb14904c2010-08-13 22:48:40 +0000478}
479
480void ASTUnit::ClearCachedCompletionResults() {
Douglas Gregorb14904c2010-08-13 22:48:40 +0000481 CachedCompletionResults.clear();
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000482 CachedCompletionTypes.clear();
Craig Topper49a27902014-05-22 04:46:25 +0000483 CachedCompletionAllocator = nullptr;
Douglas Gregorb14904c2010-08-13 22:48:40 +0000484}
485
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000486namespace {
487
Sebastian Redl2c499f62010-08-18 23:56:43 +0000488/// \brief Gathers information from ASTReader that will be used to initialize
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000489/// a Preprocessor.
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000490class ASTInfoCollector : public ASTReaderListener {
Douglas Gregor83297df2011-09-01 23:39:15 +0000491 Preprocessor &PP;
Douglas Gregore8bbc122011-09-02 00:18:52 +0000492 ASTContext &Context;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000493 LangOptions &LangOpt;
Alp Toker80758082014-07-06 05:26:44 +0000494 std::shared_ptr<TargetOptions> &TargetOpts;
Dylan Noblesmithc95d8192012-02-20 14:00:23 +0000495 IntrusiveRefCntPtr<TargetInfo> &Target;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000496 unsigned &Counter;
Mike Stump11289f42009-09-09 15:08:12 +0000497
Douglas Gregore8bbc122011-09-02 00:18:52 +0000498 bool InitializedLanguage;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000499public:
Alp Toker80758082014-07-06 05:26:44 +0000500 ASTInfoCollector(Preprocessor &PP, ASTContext &Context, LangOptions &LangOpt,
501 std::shared_ptr<TargetOptions> &TargetOpts,
502 IntrusiveRefCntPtr<TargetInfo> &Target, unsigned &Counter)
503 : PP(PP), Context(Context), LangOpt(LangOpt), TargetOpts(TargetOpts),
504 Target(Target), Counter(Counter), InitializedLanguage(false) {}
Mike Stump11289f42009-09-09 15:08:12 +0000505
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000506 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
507 bool AllowCompatibleDifferences) override {
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000508 if (InitializedLanguage)
Douglas Gregor83297df2011-09-01 23:39:15 +0000509 return false;
510
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000511 LangOpt = LangOpts;
512 InitializedLanguage = true;
513
514 updated();
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000515 return false;
516 }
Mike Stump11289f42009-09-09 15:08:12 +0000517
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000518 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
519 bool AllowCompatibleDifferences) override {
Douglas Gregor83297df2011-09-01 23:39:15 +0000520 // If we've already initialized the target, don't do it again.
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000521 if (Target)
Douglas Gregor83297df2011-09-01 23:39:15 +0000522 return false;
Alp Toker80758082014-07-06 05:26:44 +0000523
524 this->TargetOpts = std::make_shared<TargetOptions>(TargetOpts);
525 Target =
526 TargetInfo::CreateTargetInfo(PP.getDiagnostics(), this->TargetOpts);
Argyrios Kyrtzidis9e1fb562012-09-14 20:24:53 +0000527
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000528 updated();
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000529 return false;
530 }
Mike Stump11289f42009-09-09 15:08:12 +0000531
Craig Topperafa7cb32014-03-13 06:07:04 +0000532 void ReadCounter(const serialization::ModuleFile &M,
533 unsigned Value) override {
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000534 Counter = Value;
535 }
Argyrios Kyrtzidis9e1fb562012-09-14 20:24:53 +0000536
537private:
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000538 void updated() {
539 if (!Target || !InitializedLanguage)
540 return;
541
542 // Inform the target of the language options.
543 //
544 // FIXME: We shouldn't need to do this, the target should be immutable once
545 // created. This complexity should be lifted elsewhere.
Alp Toker74437972014-07-06 05:14:24 +0000546 Target->adjust(LangOpt);
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000547
548 // Initialize the preprocessor.
549 PP.Initialize(*Target);
550
551 // Initialize the ASTContext
552 Context.InitBuiltinTypes(*Target);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +0000553
554 // We didn't have access to the comment options when the ASTContext was
555 // constructed, so register them now.
556 Context.getCommentCommandTraits().registerCommentOptions(
557 LangOpt.CommentOpts);
Argyrios Kyrtzidis9e1fb562012-09-14 20:24:53 +0000558 }
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000559};
560
Douglas Gregor6b930962013-05-03 22:58:43 +0000561 /// \brief Diagnostic consumer that saves each diagnostic it is given.
David Blaikief18d91a2011-09-26 00:01:39 +0000562class StoredDiagnosticConsumer : public DiagnosticConsumer {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000563 SmallVectorImpl<StoredDiagnostic> &StoredDiags;
Douglas Gregor6b930962013-05-03 22:58:43 +0000564 SourceManager *SourceMgr;
565
Douglas Gregor33cdd812010-02-18 18:08:43 +0000566public:
David Blaikief18d91a2011-09-26 00:01:39 +0000567 explicit StoredDiagnosticConsumer(
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000568 SmallVectorImpl<StoredDiagnostic> &StoredDiags)
Craig Topper49a27902014-05-22 04:46:25 +0000569 : StoredDiags(StoredDiags), SourceMgr(nullptr) {}
Douglas Gregor6b930962013-05-03 22:58:43 +0000570
Craig Topperafa7cb32014-03-13 06:07:04 +0000571 void BeginSourceFile(const LangOptions &LangOpts,
Craig Topper49a27902014-05-22 04:46:25 +0000572 const Preprocessor *PP = nullptr) override {
Douglas Gregor6b930962013-05-03 22:58:43 +0000573 if (PP)
574 SourceMgr = &PP->getSourceManager();
575 }
576
Craig Topperafa7cb32014-03-13 06:07:04 +0000577 void HandleDiagnostic(DiagnosticsEngine::Level Level,
578 const Diagnostic &Info) override;
Douglas Gregor33cdd812010-02-18 18:08:43 +0000579};
580
581/// \brief RAII object that optionally captures diagnostics, if
582/// there is no diagnostic client to capture them already.
583class CaptureDroppedDiagnostics {
David Blaikie9c902b52011-09-25 23:23:43 +0000584 DiagnosticsEngine &Diags;
David Blaikief18d91a2011-09-26 00:01:39 +0000585 StoredDiagnosticConsumer Client;
David Blaikiee2eefae2011-09-25 23:39:51 +0000586 DiagnosticConsumer *PreviousClient;
Alexander Kornienko41c247a2014-11-17 23:46:02 +0000587 std::unique_ptr<DiagnosticConsumer> OwningPreviousClient;
Douglas Gregor33cdd812010-02-18 18:08:43 +0000588
589public:
David Blaikie9c902b52011-09-25 23:23:43 +0000590 CaptureDroppedDiagnostics(bool RequestCapture, DiagnosticsEngine &Diags,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000591 SmallVectorImpl<StoredDiagnostic> &StoredDiags)
Craig Topper49a27902014-05-22 04:46:25 +0000592 : Diags(Diags), Client(StoredDiags), PreviousClient(nullptr)
Douglas Gregor33cdd812010-02-18 18:08:43 +0000593 {
Craig Topper49a27902014-05-22 04:46:25 +0000594 if (RequestCapture || Diags.getClient() == nullptr) {
Alexander Kornienko41c247a2014-11-17 23:46:02 +0000595 OwningPreviousClient = Diags.takeClient();
596 PreviousClient = Diags.getClient();
597 Diags.setClient(&Client, false);
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000598 }
Douglas Gregor33cdd812010-02-18 18:08:43 +0000599 }
600
601 ~CaptureDroppedDiagnostics() {
Alexander Kornienko41c247a2014-11-17 23:46:02 +0000602 if (Diags.getClient() == &Client)
603 Diags.setClient(PreviousClient, !!OwningPreviousClient.release());
Douglas Gregor33cdd812010-02-18 18:08:43 +0000604 }
605};
606
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000607} // anonymous namespace
608
David Blaikief18d91a2011-09-26 00:01:39 +0000609void StoredDiagnosticConsumer::HandleDiagnostic(DiagnosticsEngine::Level Level,
David Blaikieb5784322011-09-26 01:18:08 +0000610 const Diagnostic &Info) {
Argyrios Kyrtzidisc79346a2010-11-18 20:06:46 +0000611 // Default implementation (Warnings/errors count).
David Blaikiee2eefae2011-09-25 23:39:51 +0000612 DiagnosticConsumer::HandleDiagnostic(Level, Info);
Argyrios Kyrtzidisc79346a2010-11-18 20:06:46 +0000613
Douglas Gregor6b930962013-05-03 22:58:43 +0000614 // Only record the diagnostic if it's part of the source manager we know
615 // about. This effectively drops diagnostics from modules we're building.
616 // FIXME: In the long run, ee don't want to drop source managers from modules.
617 if (!Info.hasSourceManager() || &Info.getSourceManager() == SourceMgr)
Benjamin Kramer3204b152015-05-29 19:42:19 +0000618 StoredDiags.emplace_back(Level, Info);
Douglas Gregor33cdd812010-02-18 18:08:43 +0000619}
620
Argyrios Kyrtzidis1c7455f2013-05-10 01:28:51 +0000621ASTMutationListener *ASTUnit::getASTMutationListener() {
622 if (WriterData)
623 return &WriterData->Writer;
Craig Topper49a27902014-05-22 04:46:25 +0000624 return nullptr;
Argyrios Kyrtzidis1c7455f2013-05-10 01:28:51 +0000625}
626
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000627ASTDeserializationListener *ASTUnit::getDeserializationListener() {
628 if (WriterData)
629 return &WriterData->Writer;
Craig Topper49a27902014-05-22 04:46:25 +0000630 return nullptr;
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000631}
632
Rafael Espindola16e1ba12014-08-26 20:17:44 +0000633std::unique_ptr<llvm::MemoryBuffer>
634ASTUnit::getBufferForFile(StringRef Filename, std::string *ErrorStr) {
Chris Lattner5159f612010-11-23 08:35:12 +0000635 assert(FileMgr);
Benjamin Kramera8857962014-10-26 22:44:13 +0000636 auto Buffer = FileMgr->getBufferForFile(Filename);
637 if (Buffer)
638 return std::move(*Buffer);
639 if (ErrorStr)
640 *ErrorStr = Buffer.getError().message();
641 return nullptr;
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000642}
643
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000644/// \brief Configure the diagnostics object for use with ASTUnit.
Justin Bognerd512c1e2014-10-15 00:33:06 +0000645void ASTUnit::ConfigureDiags(IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000646 ASTUnit &AST, bool CaptureDiagnostics) {
Justin Bognerd512c1e2014-10-15 00:33:06 +0000647 assert(Diags.get() && "no DiagnosticsEngine was provided");
648 if (CaptureDiagnostics)
David Blaikief18d91a2011-09-26 00:01:39 +0000649 Diags->setClient(new StoredDiagnosticConsumer(AST.StoredDiagnostics));
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000650}
651
David Blaikie6f7382d2014-08-10 19:08:04 +0000652std::unique_ptr<ASTUnit> ASTUnit::LoadFromASTFile(
Adrian Prantl6b21ab22015-08-27 19:46:20 +0000653 const std::string &Filename, const PCHContainerReader &PCHContainerRdr,
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000654 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Adrian Prantl6b21ab22015-08-27 19:46:20 +0000655 const FileSystemOptions &FileSystemOpts, bool UseDebugInfo,
656 bool OnlyLocalDecls, ArrayRef<RemappedFile> RemappedFiles,
657 bool CaptureDiagnostics, bool AllowPCHWithCompilerErrors,
658 bool UserFilesAreVolatile) {
Ahmed Charlesb8984322014-03-07 20:03:18 +0000659 std::unique_ptr<ASTUnit> AST(new ASTUnit(true));
Ted Kremenek4422bfe2011-03-18 02:06:56 +0000660
661 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +0000662 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
663 ASTUnitCleanup(AST.get());
David Blaikie9c902b52011-09-25 23:23:43 +0000664 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
665 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Alp Tokerf994cef2014-07-05 03:08:06 +0000666 DiagCleanup(Diags.get());
Ted Kremenek4422bfe2011-03-18 02:06:56 +0000667
Justin Bognerdbbcb112014-10-14 23:36:06 +0000668 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000669
Douglas Gregor16bef852009-10-16 20:01:17 +0000670 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000671 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor7f95d262010-04-05 23:52:57 +0000672 AST->Diagnostics = Diags;
Ben Langmuir8832c062014-04-15 18:16:25 +0000673 IntrusiveRefCntPtr<vfs::FileSystem> VFS = vfs::getRealFileSystem();
674 AST->FileMgr = new FileManager(FileSystemOpts, VFS);
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +0000675 AST->UserFilesAreVolatile = UserFilesAreVolatile;
Ted Kremenek5e14d392011-03-21 18:40:17 +0000676 AST->SourceMgr = new SourceManager(AST->getDiagnostics(),
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +0000677 AST->getFileManager(),
678 UserFilesAreVolatile);
Douglas Gregorb85b9cc2012-10-24 16:19:39 +0000679 AST->HSOpts = new HeaderSearchOptions();
Adrian Prantlfb2398d2015-07-17 01:19:54 +0000680 AST->HSOpts->ModuleFormat = PCHContainerRdr.getFormat();
Douglas Gregorb85b9cc2012-10-24 16:19:39 +0000681 AST->HeaderInfo.reset(new HeaderSearch(AST->HSOpts,
Manuel Klimek1f76c4e2013-10-24 07:51:24 +0000682 AST->getSourceManager(),
Douglas Gregor1fb5c3a2011-12-31 04:05:44 +0000683 AST->getDiagnostics(),
Douglas Gregor89929282012-01-30 06:01:29 +0000684 AST->ASTFileLangOpts,
Craig Topper49a27902014-05-22 04:46:25 +0000685 /*Target=*/nullptr));
Dmitri Gribenkoc444b572014-02-08 00:38:15 +0000686
Dmitri Gribenkob41e7e22014-02-10 12:31:34 +0000687 PreprocessorOptions *PPOpts = new PreprocessorOptions();
Dmitri Gribenkoc444b572014-02-08 00:38:15 +0000688
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000689 for (const auto &RemappedFile : RemappedFiles)
690 PPOpts->addRemappedFile(RemappedFile.first, RemappedFile.second);
Dmitri Gribenkoc444b572014-02-08 00:38:15 +0000691
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000692 // Gather Info for preprocessor construction later on.
Mike Stump11289f42009-09-09 15:08:12 +0000693
David Blaikie6f7382d2014-08-10 19:08:04 +0000694 HeaderSearch &HeaderInfo = *AST->HeaderInfo;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000695 unsigned Counter;
696
Alp Toker96637802014-05-02 03:43:38 +0000697 AST->PP =
698 new Preprocessor(PPOpts, AST->getDiagnostics(), AST->ASTFileLangOpts,
699 AST->getSourceManager(), HeaderInfo, *AST,
Craig Topper49a27902014-05-22 04:46:25 +0000700 /*IILookup=*/nullptr,
Alp Toker96637802014-05-02 03:43:38 +0000701 /*OwnsHeaderSearch=*/false);
Douglas Gregore8bbc122011-09-02 00:18:52 +0000702 Preprocessor &PP = *AST->PP;
703
Alp Toker08043432014-05-03 03:46:04 +0000704 AST->Ctx = new ASTContext(AST->ASTFileLangOpts, AST->getSourceManager(),
705 PP.getIdentifierTable(), PP.getSelectorTable(),
706 PP.getBuiltinInfo());
Douglas Gregore8bbc122011-09-02 00:18:52 +0000707 ASTContext &Context = *AST->Ctx;
Douglas Gregor83297df2011-09-01 23:39:15 +0000708
Argyrios Kyrtzidis945a8192012-09-15 01:10:20 +0000709 bool disableValid = false;
710 if (::getenv("LIBCLANG_DISABLE_PCH_VALIDATION"))
711 disableValid = true;
Douglas Gregor6623e1f2015-11-03 18:33:07 +0000712 AST->Reader = new ASTReader(PP, Context, PCHContainerRdr, { },
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000713 /*isysroot=*/"",
714 /*DisableValidation=*/disableValid,
715 AllowPCHWithCompilerErrors);
Ted Kremenek2159b8d2011-05-04 23:27:12 +0000716
David Blaikie2721c322014-08-10 16:54:39 +0000717 AST->Reader->setListener(llvm::make_unique<ASTInfoCollector>(
718 *AST->PP, Context, AST->ASTFileLangOpts, AST->TargetOpts, AST->Target,
719 Counter));
Daniel Dunbar2d9c7402009-09-03 05:59:35 +0000720
Argyrios Kyrtzidisf0b4cd12015-03-03 08:04:19 +0000721 // Attach the AST reader to the AST context as an external AST
722 // source, so that declarations will be deserialized from the
723 // AST file as needed.
724 // We need the external source to be set up before we read the AST, because
725 // eagerly-deserialized declarations may use it.
726 Context.setExternalSource(AST->Reader);
727
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000728 switch (AST->Reader->ReadAST(Filename, serialization::MK_MainFile,
Argyrios Kyrtzidis2ec29362012-11-15 18:57:22 +0000729 SourceLocation(), ASTReader::ARR_None)) {
Sebastian Redl2c499f62010-08-18 23:56:43 +0000730 case ASTReader::Success:
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000731 break;
Mike Stump11289f42009-09-09 15:08:12 +0000732
Sebastian Redl2c499f62010-08-18 23:56:43 +0000733 case ASTReader::Failure:
Douglas Gregor7029ce12013-03-19 00:28:20 +0000734 case ASTReader::Missing:
Douglas Gregorc9ad5fb2012-10-22 22:50:17 +0000735 case ASTReader::OutOfDate:
736 case ASTReader::VersionMismatch:
737 case ASTReader::ConfigurationMismatch:
738 case ASTReader::HadErrors:
Douglas Gregord03e8232010-04-05 21:10:19 +0000739 AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
Craig Topper49a27902014-05-22 04:46:25 +0000740 return nullptr;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000741 }
Mike Stump11289f42009-09-09 15:08:12 +0000742
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000743 AST->OriginalSourceFile = AST->Reader->getOriginalSourceFile();
Daniel Dunbara8a50932009-12-02 08:44:16 +0000744
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000745 PP.setCounterValue(Counter);
Mike Stump11289f42009-09-09 15:08:12 +0000746
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000747 // Create an AST consumer, even though it isn't used.
748 AST->Consumer.reset(new ASTConsumer);
749
Sebastian Redl2c499f62010-08-18 23:56:43 +0000750 // Create a semantic analysis object and tell the AST reader about it.
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000751 AST->TheSema.reset(new Sema(PP, Context, *AST->Consumer));
752 AST->TheSema->Initialize();
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000753 AST->Reader->InitializeSema(*AST->TheSema);
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000754
Douglas Gregor6b930962013-05-03 22:58:43 +0000755 // Tell the diagnostic client that we have started a source file.
756 AST->getDiagnostics().getClient()->BeginSourceFile(Context.getLangOpts(),&PP);
757
David Blaikie6f7382d2014-08-10 19:08:04 +0000758 return AST;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000759}
Daniel Dunbar764c0822009-12-01 09:51:01 +0000760
761namespace {
762
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000763/// \brief Preprocessor callback class that updates a hash value with the names
764/// of all macros that have been defined by the translation unit.
765class MacroDefinitionTrackerPPCallbacks : public PPCallbacks {
766 unsigned &Hash;
767
768public:
769 explicit MacroDefinitionTrackerPPCallbacks(unsigned &Hash) : Hash(Hash) { }
Craig Topperafa7cb32014-03-13 06:07:04 +0000770
771 void MacroDefined(const Token &MacroNameTok,
772 const MacroDirective *MD) override {
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000773 Hash = llvm::HashString(MacroNameTok.getIdentifierInfo()->getName(), Hash);
774 }
775};
776
777/// \brief Add the given declaration to the hash of all top-level entities.
778void AddTopLevelDeclarationToHash(Decl *D, unsigned &Hash) {
779 if (!D)
780 return;
781
782 DeclContext *DC = D->getDeclContext();
783 if (!DC)
784 return;
785
786 if (!(DC->isTranslationUnit() || DC->getLookupParent()->isTranslationUnit()))
787 return;
788
789 if (NamedDecl *ND = dyn_cast<NamedDecl>(D)) {
Argyrios Kyrtzidisca5c7be2013-10-15 17:37:55 +0000790 if (EnumDecl *EnumD = dyn_cast<EnumDecl>(D)) {
791 // For an unscoped enum include the enumerators in the hash since they
792 // enter the top-level namespace.
793 if (!EnumD->isScoped()) {
Aaron Ballman23a6dcb2014-03-08 18:45:14 +0000794 for (const auto *EI : EnumD->enumerators()) {
795 if (EI->getIdentifier())
796 Hash = llvm::HashString(EI->getIdentifier()->getName(), Hash);
Argyrios Kyrtzidisca5c7be2013-10-15 17:37:55 +0000797 }
798 }
799 }
800
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000801 if (ND->getIdentifier())
802 Hash = llvm::HashString(ND->getIdentifier()->getName(), Hash);
803 else if (DeclarationName Name = ND->getDeclName()) {
804 std::string NameStr = Name.getAsString();
805 Hash = llvm::HashString(NameStr, Hash);
806 }
807 return;
Argyrios Kyrtzidis48d88de2013-06-24 21:19:12 +0000808 }
809
810 if (ImportDecl *ImportD = dyn_cast<ImportDecl>(D)) {
811 if (Module *Mod = ImportD->getImportedModule()) {
812 std::string ModName = Mod->getFullModuleName();
813 Hash = llvm::HashString(ModName, Hash);
814 }
815 return;
816 }
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000817}
818
Daniel Dunbar644dca02009-12-04 08:17:33 +0000819class TopLevelDeclTrackerConsumer : public ASTConsumer {
820 ASTUnit &Unit;
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000821 unsigned &Hash;
822
Daniel Dunbar644dca02009-12-04 08:17:33 +0000823public:
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000824 TopLevelDeclTrackerConsumer(ASTUnit &_Unit, unsigned &Hash)
825 : Unit(_Unit), Hash(Hash) {
826 Hash = 0;
827 }
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000828
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000829 void handleTopLevelDecl(Decl *D) {
Argyrios Kyrtzidis516eec22011-11-16 02:35:10 +0000830 if (!D)
831 return;
832
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000833 // FIXME: Currently ObjC method declarations are incorrectly being
834 // reported as top-level declarations, even though their DeclContext
835 // is the containing ObjC @interface/@implementation. This is a
836 // fundamental problem in the parser right now.
837 if (isa<ObjCMethodDecl>(D))
838 return;
839
840 AddTopLevelDeclarationToHash(D, Hash);
841 Unit.addTopLevelDecl(D);
842
843 handleFileLevelDecl(D);
844 }
845
846 void handleFileLevelDecl(Decl *D) {
847 Unit.addFileLevelDecl(D);
848 if (NamespaceDecl *NSD = dyn_cast<NamespaceDecl>(D)) {
Aaron Ballman629afae2014-03-07 19:56:05 +0000849 for (auto *I : NSD->decls())
850 handleFileLevelDecl(I);
Ted Kremenekacc59c32010-05-03 20:16:35 +0000851 }
Daniel Dunbar644dca02009-12-04 08:17:33 +0000852 }
Sebastian Redleaa4ade2010-08-11 18:52:41 +0000853
Craig Topperafa7cb32014-03-13 06:07:04 +0000854 bool HandleTopLevelDecl(DeclGroupRef D) override {
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000855 for (Decl *TopLevelDecl : D)
856 handleTopLevelDecl(TopLevelDecl);
Argyrios Kyrtzidis841dd882011-11-18 00:26:59 +0000857 return true;
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000858 }
859
Sebastian Redleaa4ade2010-08-11 18:52:41 +0000860 // We're not interested in "interesting" decls.
Craig Topperafa7cb32014-03-13 06:07:04 +0000861 void HandleInterestingDecl(DeclGroupRef) override {}
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000862
Craig Topperafa7cb32014-03-13 06:07:04 +0000863 void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) override {
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000864 for (Decl *TopLevelDecl : D)
865 handleTopLevelDecl(TopLevelDecl);
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000866 }
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000867
Craig Topperafa7cb32014-03-13 06:07:04 +0000868 ASTMutationListener *GetASTMutationListener() override {
Argyrios Kyrtzidis1c7455f2013-05-10 01:28:51 +0000869 return Unit.getASTMutationListener();
870 }
871
Craig Topperafa7cb32014-03-13 06:07:04 +0000872 ASTDeserializationListener *GetASTDeserializationListener() override {
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000873 return Unit.getDeserializationListener();
874 }
Daniel Dunbar644dca02009-12-04 08:17:33 +0000875};
876
877class TopLevelDeclTrackerAction : public ASTFrontendAction {
878public:
879 ASTUnit &Unit;
880
David Blaikie6beb6aa2014-08-10 19:56:51 +0000881 std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
882 StringRef InFile) override {
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000883 CI.getPreprocessor().addPPCallbacks(
Craig Topperb8a70532014-09-10 04:53:53 +0000884 llvm::make_unique<MacroDefinitionTrackerPPCallbacks>(
885 Unit.getCurrentTopLevelHashValue()));
David Blaikie6beb6aa2014-08-10 19:56:51 +0000886 return llvm::make_unique<TopLevelDeclTrackerConsumer>(
887 Unit, Unit.getCurrentTopLevelHashValue());
Daniel Dunbar764c0822009-12-01 09:51:01 +0000888 }
889
890public:
Daniel Dunbar644dca02009-12-04 08:17:33 +0000891 TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {}
892
Craig Topperafa7cb32014-03-13 06:07:04 +0000893 bool hasCodeCompletionSupport() const override { return false; }
894 TranslationUnitKind getTranslationUnitKind() override {
Douglas Gregor69f74f82011-08-25 22:30:56 +0000895 return Unit.getTranslationUnitKind();
Douglas Gregor028d3e42010-08-09 20:45:32 +0000896 }
Daniel Dunbar764c0822009-12-01 09:51:01 +0000897};
898
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000899class PrecompilePreambleAction : public ASTFrontendAction {
900 ASTUnit &Unit;
901 bool HasEmittedPreamblePCH;
902
903public:
904 explicit PrecompilePreambleAction(ASTUnit &Unit)
905 : Unit(Unit), HasEmittedPreamblePCH(false) {}
906
David Blaikie6beb6aa2014-08-10 19:56:51 +0000907 std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
908 StringRef InFile) override;
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000909 bool hasEmittedPreamblePCH() const { return HasEmittedPreamblePCH; }
910 void setHasEmittedPreamblePCH() { HasEmittedPreamblePCH = true; }
Craig Topperafa7cb32014-03-13 06:07:04 +0000911 bool shouldEraseOutputFiles() override { return !hasEmittedPreamblePCH(); }
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000912
Craig Topperafa7cb32014-03-13 06:07:04 +0000913 bool hasCodeCompletionSupport() const override { return false; }
914 bool hasASTFileSupport() const override { return false; }
915 TranslationUnitKind getTranslationUnitKind() override { return TU_Prefix; }
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000916};
917
Argyrios Kyrtzidis57332712011-09-19 20:40:48 +0000918class PrecompilePreambleConsumer : public PCHGenerator {
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000919 ASTUnit &Unit;
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000920 unsigned &Hash;
Douglas Gregore9db88f2010-08-03 19:06:41 +0000921 std::vector<Decl *> TopLevelDecls;
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000922 PrecompilePreambleAction *Action;
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000923 raw_ostream *Out;
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000924
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000925public:
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000926 PrecompilePreambleConsumer(ASTUnit &Unit, PrecompilePreambleAction *Action,
927 const Preprocessor &PP, StringRef isysroot,
928 raw_ostream *Out)
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000929 : PCHGenerator(PP, "", nullptr, isysroot, std::make_shared<PCHBuffer>(),
Douglas Gregor6623e1f2015-11-03 18:33:07 +0000930 ArrayRef<llvm::IntrusiveRefCntPtr<ModuleFileExtension>>(),
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000931 /*AllowASTWithErrors=*/true),
932 Unit(Unit), Hash(Unit.getCurrentTopLevelHashValue()), Action(Action),
933 Out(Out) {
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000934 Hash = 0;
935 }
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000936
Benjamin Kramera401b9b2015-02-06 18:58:04 +0000937 bool HandleTopLevelDecl(DeclGroupRef DG) override {
938 for (Decl *D : DG) {
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000939 // FIXME: Currently ObjC method declarations are incorrectly being
940 // reported as top-level declarations, even though their DeclContext
941 // is the containing ObjC @interface/@implementation. This is a
942 // fundamental problem in the parser right now.
943 if (isa<ObjCMethodDecl>(D))
944 continue;
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000945 AddTopLevelDeclarationToHash(D, Hash);
Douglas Gregore9db88f2010-08-03 19:06:41 +0000946 TopLevelDecls.push_back(D);
947 }
Argyrios Kyrtzidis841dd882011-11-18 00:26:59 +0000948 return true;
Douglas Gregore9db88f2010-08-03 19:06:41 +0000949 }
950
Craig Topperafa7cb32014-03-13 06:07:04 +0000951 void HandleTranslationUnit(ASTContext &Ctx) override {
Douglas Gregore9db88f2010-08-03 19:06:41 +0000952 PCHGenerator::HandleTranslationUnit(Ctx);
Argyrios Kyrtzidisf0168de2013-06-11 00:36:55 +0000953 if (hasEmittedPCH()) {
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000954 // Write the generated bitstream to "Out".
955 *Out << getPCH();
956 // Make sure it hits disk now.
957 Out->flush();
958 // Free the buffer.
959 llvm::SmallVector<char, 0> Empty;
960 getPCH() = std::move(Empty);
961
Douglas Gregore9db88f2010-08-03 19:06:41 +0000962 // Translate the top-level declarations we captured during
963 // parsing into declaration IDs in the precompiled
964 // preamble. This will allow us to deserialize those top-level
965 // declarations when requested.
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000966 for (Decl *D : TopLevelDecls) {
Argyrios Kyrtzidisacfbbd72013-08-07 21:17:33 +0000967 // Invalid top-level decls may not have been serialized.
968 if (D->isInvalidDecl())
969 continue;
970 Unit.addTopLevelDeclFromPreamble(getWriter().getDeclID(D));
971 }
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000972
973 Action->setHasEmittedPreamblePCH();
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000974 }
975 }
976};
977
Hans Wennborgdcfba332015-10-06 23:40:43 +0000978} // anonymous namespace
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000979
David Blaikie6beb6aa2014-08-10 19:56:51 +0000980std::unique_ptr<ASTConsumer>
981PrecompilePreambleAction::CreateASTConsumer(CompilerInstance &CI,
982 StringRef InFile) {
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000983 std::string Sysroot;
984 std::string OutputFile;
Rafael Espindola47de1492015-04-10 12:54:53 +0000985 raw_ostream *OS = GeneratePCHAction::ComputeASTConsumerArguments(
986 CI, InFile, Sysroot, OutputFile);
987 if (!OS)
Craig Topper49a27902014-05-22 04:46:25 +0000988 return nullptr;
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000989
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000990 if (!CI.getFrontendOpts().RelocatablePCH)
991 Sysroot.clear();
Douglas Gregorc567ba22011-07-22 16:35:34 +0000992
Craig Topperb8a70532014-09-10 04:53:53 +0000993 CI.getPreprocessor().addPPCallbacks(
994 llvm::make_unique<MacroDefinitionTrackerPPCallbacks>(
995 Unit.getCurrentTopLevelHashValue()));
David Blaikie6beb6aa2014-08-10 19:56:51 +0000996 return llvm::make_unique<PrecompilePreambleConsumer>(
997 Unit, this, CI.getPreprocessor(), Sysroot, OS);
Daniel Dunbar764c0822009-12-01 09:51:01 +0000998}
999
Benjamin Kramer1ce5d802013-05-05 12:39:28 +00001000static bool isNonDriverDiag(const StoredDiagnostic &StoredDiag) {
1001 return StoredDiag.getLocation().isValid();
1002}
1003
1004static void
1005checkAndRemoveNonDriverDiags(SmallVectorImpl<StoredDiagnostic> &StoredDiags) {
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +00001006 // Get rid of stored diagnostics except the ones from the driver which do not
1007 // have a source location.
Benjamin Kramer1ce5d802013-05-05 12:39:28 +00001008 StoredDiags.erase(
1009 std::remove_if(StoredDiags.begin(), StoredDiags.end(), isNonDriverDiag),
1010 StoredDiags.end());
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +00001011}
1012
1013static void checkAndSanitizeDiags(SmallVectorImpl<StoredDiagnostic> &
1014 StoredDiagnostics,
1015 SourceManager &SM) {
1016 // The stored diagnostic has the old source manager in it; update
1017 // the locations to refer into the new source manager. Since we've
1018 // been careful to make sure that the source manager's state
1019 // before and after are identical, so that we can reuse the source
1020 // location itself.
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00001021 for (StoredDiagnostic &SD : StoredDiagnostics) {
1022 if (SD.getLocation().isValid()) {
1023 FullSourceLoc Loc(SD.getLocation(), SM);
1024 SD.setLocation(Loc);
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +00001025 }
1026 }
1027}
1028
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001029/// Parse the source file into a translation unit using the given compiler
1030/// invocation, replacing the current translation unit.
1031///
1032/// \returns True if a failure occurred that causes the ASTUnit not to
1033/// contain any translation-unit information, false otherwise.
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001034bool ASTUnit::Parse(std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1035 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer) {
Rafael Espindola4674a872014-08-13 17:08:22 +00001036 SavedMainFileBuffer.reset();
Craig Topper49a27902014-05-22 04:46:25 +00001037
Rafael Espindola32482082014-08-18 16:23:45 +00001038 if (!Invocation)
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001039 return true;
Rafael Espindola32482082014-08-18 16:23:45 +00001040
Daniel Dunbar764c0822009-12-01 09:51:01 +00001041 // Create the compiler instance to use for building the AST.
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001042 std::unique_ptr<CompilerInstance> Clang(
Benjamin Kramerd6da1a02016-06-12 20:05:23 +00001043 new CompilerInstance(std::move(PCHContainerOps)));
Ted Kremenek84de4a12011-03-21 18:40:07 +00001044
1045 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00001046 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1047 CICleanup(Clang.get());
Ted Kremenek84de4a12011-03-21 18:40:07 +00001048
Dylan Noblesmithc95d8192012-02-20 14:00:23 +00001049 IntrusiveRefCntPtr<CompilerInvocation>
Argyrios Kyrtzidis14c32e82011-09-12 18:09:38 +00001050 CCInvocation(new CompilerInvocation(*Invocation));
1051
Alp Tokerf994cef2014-07-05 03:08:06 +00001052 Clang->setInvocation(CCInvocation.get());
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001053 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001054
Douglas Gregor8e984da2010-08-04 16:47:14 +00001055 // Set up diagnostics, capturing any diagnostics that would
1056 // otherwise be dropped.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001057 Clang->setDiagnostics(&getDiagnostics());
Douglas Gregord03e8232010-04-05 21:10:19 +00001058
Daniel Dunbar764c0822009-12-01 09:51:01 +00001059 // Create the target instance.
Alp Toker80758082014-07-06 05:26:44 +00001060 Clang->setTarget(TargetInfo::CreateTargetInfo(
Saleem Abdulrasool10a49722016-04-08 16:52:00 +00001061 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
Rafael Espindola32482082014-08-18 16:23:45 +00001062 if (!Clang->hasTarget())
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001063 return true;
Douglas Gregora0734c52010-08-19 01:33:06 +00001064
Daniel Dunbar764c0822009-12-01 09:51:01 +00001065 // Inform the target of the language options.
1066 //
1067 // FIXME: We shouldn't need to do this, the target should be immutable once
1068 // created. This complexity should be lifted elsewhere.
Alp Toker74437972014-07-06 05:14:24 +00001069 Clang->getTarget().adjust(Clang->getLangOpts());
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001070
Ted Kremenek84de4a12011-03-21 18:40:07 +00001071 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Daniel Dunbar764c0822009-12-01 09:51:01 +00001072 "Invocation must have exactly one source file!");
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001073 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
Daniel Dunbar764c0822009-12-01 09:51:01 +00001074 "FIXME: AST inputs not yet supported here!");
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001075 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
Daniel Dunbar9507f9c2010-06-07 23:26:47 +00001076 "IR inputs not support here!");
Daniel Dunbar764c0822009-12-01 09:51:01 +00001077
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001078 // Configure the various subsystems.
Alp Toker269d8402014-07-06 05:26:07 +00001079 LangOpts = Clang->getInvocation().LangOpts;
Ted Kremenek84de4a12011-03-21 18:40:07 +00001080 FileSystemOpts = Clang->getFileSystemOpts();
Benjamin Kramerbc632902015-10-06 14:45:20 +00001081 if (!FileMgr) {
1082 Clang->createFileManager();
1083 FileMgr = &Clang->getFileManager();
1084 }
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +00001085 SourceMgr = new SourceManager(getDiagnostics(), *FileMgr,
1086 UserFilesAreVolatile);
Douglas Gregor6fd55e02010-08-13 03:15:25 +00001087 TheSema.reset();
Craig Topper49a27902014-05-22 04:46:25 +00001088 Ctx = nullptr;
1089 PP = nullptr;
1090 Reader = nullptr;
1091
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001092 // Clear out old caches and data.
1093 TopLevelDecls.clear();
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00001094 clearFileLevelDecls();
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001095 CleanTemporaryFiles();
Douglas Gregord9a30af2010-08-02 20:51:39 +00001096
Douglas Gregor7b02b582010-08-20 00:02:33 +00001097 if (!OverrideMainBuffer) {
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +00001098 checkAndRemoveNonDriverDiags(StoredDiagnostics);
Douglas Gregor7b02b582010-08-20 00:02:33 +00001099 TopLevelDeclsInPreamble.clear();
1100 }
1101
Daniel Dunbar764c0822009-12-01 09:51:01 +00001102 // Create a file manager object to provide access to and cache the filesystem.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001103 Clang->setFileManager(&getFileManager());
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001104
Daniel Dunbar764c0822009-12-01 09:51:01 +00001105 // Create the source manager.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001106 Clang->setSourceManager(&getSourceManager());
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001107
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001108 // If the main file has been overridden due to the use of a preamble,
1109 // make that override happen and introduce the preamble.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001110 PreprocessorOptions &PreprocessorOpts = Clang->getPreprocessorOpts();
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001111 if (OverrideMainBuffer) {
Rafael Espindola32482082014-08-18 16:23:45 +00001112 PreprocessorOpts.addRemappedFile(OriginalSourceFile,
1113 OverrideMainBuffer.get());
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001114 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
1115 PreprocessorOpts.PrecompiledPreambleBytes.second
1116 = PreambleEndsAtStartOfLine;
Ted Kremenek06b4f912011-10-27 17:55:18 +00001117 PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
Douglas Gregorce3a8292010-07-27 00:27:13 +00001118 PreprocessorOpts.DisablePCHValidation = true;
Douglas Gregor96c04262010-07-27 14:52:07 +00001119
Douglas Gregord9a30af2010-08-02 20:51:39 +00001120 // The stored diagnostic has the old source manager in it; update
1121 // the locations to refer into the new source manager. Since we've
1122 // been careful to make sure that the source manager's state
1123 // before and after are identical, so that we can reuse the source
1124 // location itself.
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +00001125 checkAndSanitizeDiags(StoredDiagnostics, getSourceManager());
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001126
1127 // Keep track of the override buffer;
Rafael Espindola32482082014-08-18 16:23:45 +00001128 SavedMainFileBuffer = std::move(OverrideMainBuffer);
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001129 }
Ahmed Charlesb8984322014-03-07 20:03:18 +00001130
1131 std::unique_ptr<TopLevelDeclTrackerAction> Act(
1132 new TopLevelDeclTrackerAction(*this));
1133
Ted Kremenek022a4902011-03-22 01:15:24 +00001134 // Recover resources if we crash before exiting this method.
1135 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1136 ActCleanup(Act.get());
1137
Douglas Gregor32fbe312012-01-20 16:28:04 +00001138 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0]))
Daniel Dunbar764c0822009-12-01 09:51:01 +00001139 goto error;
Douglas Gregor925296b2011-07-19 16:10:42 +00001140
Richard Smith26b8f782016-03-25 21:46:44 +00001141 if (SavedMainFileBuffer)
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001142 TranslateStoredDiagnostics(getFileManager(), getSourceManager(),
1143 PreambleDiagnostics, StoredDiagnostics);
Douglas Gregor925296b2011-07-19 16:10:42 +00001144
Argyrios Kyrtzidis1416e172012-06-08 05:48:06 +00001145 if (!Act->Execute())
1146 goto error;
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001147
1148 transferASTDataFromCompilerInstance(*Clang);
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001149
Daniel Dunbar644dca02009-12-04 08:17:33 +00001150 Act->EndSourceFile();
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001151
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001152 FailedParseDiagnostics.clear();
1153
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001154 return false;
Ted Kremenek5e14d392011-03-21 18:40:17 +00001155
Daniel Dunbar764c0822009-12-01 09:51:01 +00001156error:
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001157 // Remove the overridden buffer we used for the preamble.
Rafael Espindola32482082014-08-18 16:23:45 +00001158 SavedMainFileBuffer = nullptr;
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001159
1160 // Keep the ownership of the data in the ASTUnit because the client may
1161 // want to see the diagnostics.
1162 transferASTDataFromCompilerInstance(*Clang);
1163 FailedParseDiagnostics.swap(StoredDiagnostics);
Douglas Gregorefc46952010-10-12 16:25:54 +00001164 StoredDiagnostics.clear();
Argyrios Kyrtzidis067cbfa2011-10-24 17:25:20 +00001165 NumStoredDiagnosticsFromDriver = 0;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001166 return true;
1167}
1168
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001169/// \brief Simple function to retrieve a path for a preamble precompiled header.
1170static std::string GetPreamblePCHPath() {
Douglas Gregor250ab1d2010-09-11 18:05:19 +00001171 // FIXME: This is a hack so that we can override the preamble file during
1172 // crash-recovery testing, which is the only case where the preamble files
Rafael Espindolabc4aa552013-06-26 04:02:37 +00001173 // are not necessarily cleaned up.
Douglas Gregor250ab1d2010-09-11 18:05:19 +00001174 const char *TmpFile = ::getenv("CINDEXTEST_PREAMBLE_FILE");
1175 if (TmpFile)
1176 return TmpFile;
Rafael Espindolabc4aa552013-06-26 04:02:37 +00001177
1178 SmallString<128> Path;
Rafael Espindolaa36e78e2013-07-05 20:00:06 +00001179 llvm::sys::fs::createTemporaryFile("preamble", "pch", Path);
Rafael Espindolabc4aa552013-06-26 04:02:37 +00001180
1181 return Path.str();
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001182}
1183
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001184/// \brief Compute the preamble for the main file, providing the source buffer
1185/// that corresponds to the main file along with a pair (bytes, start-of-line)
1186/// that describes the preamble.
David Blaikied6902a12014-08-29 06:34:53 +00001187ASTUnit::ComputedPreamble
1188ASTUnit::ComputePreamble(CompilerInvocation &Invocation, unsigned MaxLines) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001189 FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
Chris Lattner5159f612010-11-23 08:35:12 +00001190 PreprocessorOptions &PreprocessorOpts = Invocation.getPreprocessorOpts();
Douglas Gregor4dde7492010-07-23 23:58:40 +00001191
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001192 // Try to determine if the main file has been remapped, either from the
1193 // command line (to another file) or directly through the compiler invocation
1194 // (to a memory buffer).
Craig Topper49a27902014-05-22 04:46:25 +00001195 llvm::MemoryBuffer *Buffer = nullptr;
David Blaikied6902a12014-08-29 06:34:53 +00001196 std::unique_ptr<llvm::MemoryBuffer> BufferOwner;
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00001197 std::string MainFilePath(FrontendOpts.Inputs[0].getFile());
Rafael Espindola073ff102013-07-29 21:26:52 +00001198 llvm::sys::fs::UniqueID MainFileID;
Rafael Espindolabe3b12b02013-06-20 15:12:38 +00001199 if (!llvm::sys::fs::getUniqueID(MainFilePath, MainFileID)) {
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001200 // Check whether there is a file-file remapping of the main file
Alp Toker1b070d22014-07-07 07:47:20 +00001201 for (const auto &RF : PreprocessorOpts.RemappedFiles) {
1202 std::string MPath(RF.first);
Rafael Espindola073ff102013-07-29 21:26:52 +00001203 llvm::sys::fs::UniqueID MID;
Rafael Espindolabe3b12b02013-06-20 15:12:38 +00001204 if (!llvm::sys::fs::getUniqueID(MPath, MID)) {
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00001205 if (MainFileID == MID) {
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001206 // We found a remapping. Try to load the resulting, remapped source.
David Blaikied6902a12014-08-29 06:34:53 +00001207 BufferOwner = getBufferForFile(RF.second);
1208 if (!BufferOwner)
1209 return ComputedPreamble(nullptr, nullptr, 0, true);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001210 }
1211 }
1212 }
1213
1214 // Check whether there is a file-buffer remapping. It supercedes the
1215 // file-file remapping.
Alp Toker1b070d22014-07-07 07:47:20 +00001216 for (const auto &RB : PreprocessorOpts.RemappedFileBuffers) {
1217 std::string MPath(RB.first);
Rafael Espindola073ff102013-07-29 21:26:52 +00001218 llvm::sys::fs::UniqueID MID;
Rafael Espindolabe3b12b02013-06-20 15:12:38 +00001219 if (!llvm::sys::fs::getUniqueID(MPath, MID)) {
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00001220 if (MainFileID == MID) {
1221 // We found a remapping.
David Blaikied6902a12014-08-29 06:34:53 +00001222 BufferOwner.reset();
Alp Toker1b070d22014-07-07 07:47:20 +00001223 Buffer = const_cast<llvm::MemoryBuffer *>(RB.second);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001224 }
1225 }
Douglas Gregor4dde7492010-07-23 23:58:40 +00001226 }
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001227 }
1228
1229 // If the main source file was not remapped, load it now.
David Blaikied6902a12014-08-29 06:34:53 +00001230 if (!Buffer && !BufferOwner) {
1231 BufferOwner = getBufferForFile(FrontendOpts.Inputs[0].getFile());
1232 if (!BufferOwner)
1233 return ComputedPreamble(nullptr, nullptr, 0, true);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001234 }
David Blaikie3d95d852014-08-11 22:08:06 +00001235
David Blaikied6902a12014-08-29 06:34:53 +00001236 if (!Buffer)
1237 Buffer = BufferOwner.get();
1238 auto Pre = Lexer::ComputePreamble(Buffer->getBuffer(),
1239 *Invocation.getLangOpts(), MaxLines);
1240 return ComputedPreamble(Buffer, std::move(BufferOwner), Pre.first,
1241 Pre.second);
Douglas Gregor4dde7492010-07-23 23:58:40 +00001242}
1243
Dmitri Gribenko47652522013-12-20 00:16:25 +00001244ASTUnit::PreambleFileHash
1245ASTUnit::PreambleFileHash::createForFile(off_t Size, time_t ModTime) {
1246 PreambleFileHash Result;
1247 Result.Size = Size;
1248 Result.ModTime = ModTime;
Dmitri Gribenko3ec8ee72013-12-20 01:07:30 +00001249 memset(Result.MD5, 0, sizeof(Result.MD5));
Dmitri Gribenko47652522013-12-20 00:16:25 +00001250 return Result;
1251}
1252
1253ASTUnit::PreambleFileHash ASTUnit::PreambleFileHash::createForMemoryBuffer(
1254 const llvm::MemoryBuffer *Buffer) {
1255 PreambleFileHash Result;
1256 Result.Size = Buffer->getBufferSize();
1257 Result.ModTime = 0;
1258
1259 llvm::MD5 MD5Ctx;
1260 MD5Ctx.update(Buffer->getBuffer().data());
1261 MD5Ctx.final(Result.MD5);
1262
1263 return Result;
1264}
1265
1266namespace clang {
1267bool operator==(const ASTUnit::PreambleFileHash &LHS,
1268 const ASTUnit::PreambleFileHash &RHS) {
1269 return LHS.Size == RHS.Size && LHS.ModTime == RHS.ModTime &&
Dmitri Gribenko3ec8ee72013-12-20 01:07:30 +00001270 memcmp(LHS.MD5, RHS.MD5, sizeof(LHS.MD5)) == 0;
Dmitri Gribenko47652522013-12-20 00:16:25 +00001271}
1272} // namespace clang
1273
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001274static std::pair<unsigned, unsigned>
1275makeStandaloneRange(CharSourceRange Range, const SourceManager &SM,
1276 const LangOptions &LangOpts) {
1277 CharSourceRange FileRange = Lexer::makeFileCharRange(Range, SM, LangOpts);
1278 unsigned Offset = SM.getFileOffset(FileRange.getBegin());
1279 unsigned EndOffset = SM.getFileOffset(FileRange.getEnd());
1280 return std::make_pair(Offset, EndOffset);
1281}
1282
Benjamin Kramer1a6e0a92014-10-03 18:52:54 +00001283static ASTUnit::StandaloneFixIt makeStandaloneFixIt(const SourceManager &SM,
1284 const LangOptions &LangOpts,
1285 const FixItHint &InFix) {
1286 ASTUnit::StandaloneFixIt OutFix;
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001287 OutFix.RemoveRange = makeStandaloneRange(InFix.RemoveRange, SM, LangOpts);
1288 OutFix.InsertFromRange = makeStandaloneRange(InFix.InsertFromRange, SM,
1289 LangOpts);
1290 OutFix.CodeToInsert = InFix.CodeToInsert;
1291 OutFix.BeforePreviousInsertions = InFix.BeforePreviousInsertions;
Benjamin Kramer1a6e0a92014-10-03 18:52:54 +00001292 return OutFix;
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001293}
1294
Benjamin Kramer1a6e0a92014-10-03 18:52:54 +00001295static ASTUnit::StandaloneDiagnostic
1296makeStandaloneDiagnostic(const LangOptions &LangOpts,
1297 const StoredDiagnostic &InDiag) {
1298 ASTUnit::StandaloneDiagnostic OutDiag;
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001299 OutDiag.ID = InDiag.getID();
1300 OutDiag.Level = InDiag.getLevel();
1301 OutDiag.Message = InDiag.getMessage();
1302 OutDiag.LocOffset = 0;
1303 if (InDiag.getLocation().isInvalid())
Benjamin Kramer1a6e0a92014-10-03 18:52:54 +00001304 return OutDiag;
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001305 const SourceManager &SM = InDiag.getLocation().getManager();
1306 SourceLocation FileLoc = SM.getFileLoc(InDiag.getLocation());
1307 OutDiag.Filename = SM.getFilename(FileLoc);
1308 if (OutDiag.Filename.empty())
Benjamin Kramer1a6e0a92014-10-03 18:52:54 +00001309 return OutDiag;
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001310 OutDiag.LocOffset = SM.getFileOffset(FileLoc);
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00001311 for (const CharSourceRange &Range : InDiag.getRanges())
1312 OutDiag.Ranges.push_back(makeStandaloneRange(Range, SM, LangOpts));
1313 for (const FixItHint &FixIt : InDiag.getFixIts())
1314 OutDiag.FixIts.push_back(makeStandaloneFixIt(SM, LangOpts, FixIt));
Benjamin Kramer1a6e0a92014-10-03 18:52:54 +00001315
1316 return OutDiag;
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001317}
1318
Douglas Gregor4dde7492010-07-23 23:58:40 +00001319/// \brief Attempt to build or re-use a precompiled preamble when (re-)parsing
1320/// the source file.
1321///
1322/// This routine will compute the preamble of the main source file. If a
1323/// non-trivial preamble is found, it will precompile that preamble into a
1324/// precompiled header so that the precompiled preamble can be used to reduce
1325/// reparsing time. If a precompiled preamble has already been constructed,
1326/// this routine will determine if it is still valid and, if so, avoid
1327/// rebuilding the precompiled preamble.
1328///
Douglas Gregor028d3e42010-08-09 20:45:32 +00001329/// \param AllowRebuild When true (the default), this routine is
1330/// allowed to rebuild the precompiled preamble if it is found to be
1331/// out-of-date.
1332///
1333/// \param MaxLines When non-zero, the maximum number of lines that
1334/// can occur within the preamble.
1335///
Douglas Gregor6481ef12010-07-24 00:38:13 +00001336/// \returns If the precompiled preamble can be used, returns a newly-allocated
1337/// buffer that should be used in place of the main file when doing so.
1338/// Otherwise, returns a NULL pointer.
Rafael Espindola2346a372014-08-18 18:47:08 +00001339std::unique_ptr<llvm::MemoryBuffer>
1340ASTUnit::getMainBufferWithPrecompiledPreamble(
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001341 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
Rafael Espindola2346a372014-08-18 18:47:08 +00001342 const CompilerInvocation &PreambleInvocationIn, bool AllowRebuild,
1343 unsigned MaxLines) {
1344
Dylan Noblesmithc95d8192012-02-20 14:00:23 +00001345 IntrusiveRefCntPtr<CompilerInvocation>
Douglas Gregor3cc15812011-07-01 18:22:13 +00001346 PreambleInvocation(new CompilerInvocation(PreambleInvocationIn));
1347 FrontendOptions &FrontendOpts = PreambleInvocation->getFrontendOpts();
Douglas Gregor4dde7492010-07-23 23:58:40 +00001348 PreprocessorOptions &PreprocessorOpts
Douglas Gregor3cc15812011-07-01 18:22:13 +00001349 = PreambleInvocation->getPreprocessorOpts();
Douglas Gregor4dde7492010-07-23 23:58:40 +00001350
David Blaikied6902a12014-08-29 06:34:53 +00001351 ComputedPreamble NewPreamble = ComputePreamble(*PreambleInvocation, MaxLines);
Douglas Gregor4dde7492010-07-23 23:58:40 +00001352
David Blaikied6902a12014-08-29 06:34:53 +00001353 if (!NewPreamble.Size) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001354 // We couldn't find a preamble in the main source. Clear out the current
1355 // preamble, if we have one. It's obviously no good any more.
1356 Preamble.clear();
Ted Kremenek06b4f912011-10-27 17:55:18 +00001357 erasePreambleFile(this);
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001358
1359 // The next time we actually see a preamble, precompile it.
1360 PreambleRebuildCounter = 1;
Craig Topper49a27902014-05-22 04:46:25 +00001361 return nullptr;
Douglas Gregor4dde7492010-07-23 23:58:40 +00001362 }
1363
1364 if (!Preamble.empty()) {
1365 // We've previously computed a preamble. Check whether we have the same
1366 // preamble now that we did before, and that there's enough space in
1367 // the main-file buffer within the precompiled preamble to fit the
1368 // new main file.
David Blaikied6902a12014-08-29 06:34:53 +00001369 if (Preamble.size() == NewPreamble.Size &&
1370 PreambleEndsAtStartOfLine == NewPreamble.PreambleEndsAtStartOfLine &&
1371 memcmp(Preamble.getBufferStart(), NewPreamble.Buffer->getBufferStart(),
1372 NewPreamble.Size) == 0) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001373 // The preamble has not changed. We may be able to re-use the precompiled
1374 // preamble.
Douglas Gregord9a30af2010-08-02 20:51:39 +00001375
Douglas Gregor0e119552010-07-31 00:40:00 +00001376 // Check that none of the files used by the preamble have changed.
1377 bool AnyFileChanged = false;
1378
1379 // First, make a record of those files that have been overridden via
1380 // remapping or unsaved_files.
Cameron Desrochers6fffec32016-05-17 14:34:53 +00001381 std::map<llvm::sys::fs::UniqueID, PreambleFileHash> OverriddenFiles;
Alp Toker1b070d22014-07-07 07:47:20 +00001382 for (const auto &R : PreprocessorOpts.RemappedFiles) {
1383 if (AnyFileChanged)
1384 break;
1385
Ben Langmuirc8130a72014-02-20 21:59:23 +00001386 vfs::Status Status;
Alp Toker1b070d22014-07-07 07:47:20 +00001387 if (FileMgr->getNoncachedStatValue(R.second, Status)) {
Douglas Gregor0e119552010-07-31 00:40:00 +00001388 // If we can't stat the file we're remapping to, assume that something
1389 // horrible happened.
1390 AnyFileChanged = true;
1391 break;
1392 }
Rafael Espindolae4777f42013-07-29 18:22:23 +00001393
Cameron Desrochers6fffec32016-05-17 14:34:53 +00001394 OverriddenFiles[Status.getUniqueID()] = PreambleFileHash::createForFile(
Rafael Espindolae4777f42013-07-29 18:22:23 +00001395 Status.getSize(), Status.getLastModificationTime().toEpochTime());
Douglas Gregor0e119552010-07-31 00:40:00 +00001396 }
Alp Toker1b070d22014-07-07 07:47:20 +00001397
1398 for (const auto &RB : PreprocessorOpts.RemappedFileBuffers) {
1399 if (AnyFileChanged)
1400 break;
Cameron Desrochers6fffec32016-05-17 14:34:53 +00001401
1402 vfs::Status Status;
1403 if (FileMgr->getNoncachedStatValue(RB.first, Status)) {
1404 AnyFileChanged = true;
1405 break;
1406 }
1407
1408 OverriddenFiles[Status.getUniqueID()] =
Alp Toker1b070d22014-07-07 07:47:20 +00001409 PreambleFileHash::createForMemoryBuffer(RB.second);
Douglas Gregor0e119552010-07-31 00:40:00 +00001410 }
1411
1412 // Check whether anything has changed.
Cameron Desrochers6fffec32016-05-17 14:34:53 +00001413 for (llvm::StringMap<PreambleFileHash>::iterator
Douglas Gregor0e119552010-07-31 00:40:00 +00001414 F = FilesInPreamble.begin(), FEnd = FilesInPreamble.end();
1415 !AnyFileChanged && F != FEnd;
1416 ++F) {
Cameron Desrochers6fffec32016-05-17 14:34:53 +00001417 vfs::Status Status;
1418 if (FileMgr->getNoncachedStatValue(F->first(), Status)) {
1419 // If we can't stat the file, assume that something horrible happened.
1420 AnyFileChanged = true;
1421 break;
1422 }
1423
1424 std::map<llvm::sys::fs::UniqueID, PreambleFileHash>::iterator Overridden
1425 = OverriddenFiles.find(Status.getUniqueID());
Douglas Gregor0e119552010-07-31 00:40:00 +00001426 if (Overridden != OverriddenFiles.end()) {
1427 // This file was remapped; check whether the newly-mapped file
1428 // matches up with the previous mapping.
1429 if (Overridden->second != F->second)
1430 AnyFileChanged = true;
1431 continue;
1432 }
1433
1434 // The file was not remapped; check whether it has changed on disk.
Cameron Desrochers6fffec32016-05-17 14:34:53 +00001435 if (Status.getSize() != uint64_t(F->second.Size) ||
1436 Status.getLastModificationTime().toEpochTime() !=
1437 uint64_t(F->second.ModTime))
Douglas Gregor0e119552010-07-31 00:40:00 +00001438 AnyFileChanged = true;
1439 }
1440
1441 if (!AnyFileChanged) {
Douglas Gregord9a30af2010-08-02 20:51:39 +00001442 // Okay! We can re-use the precompiled preamble.
1443
1444 // Set the state of the diagnostic object to mimic its state
1445 // after parsing the preamble.
1446 getDiagnostics().Reset();
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00001447 ProcessWarningOptions(getDiagnostics(),
Douglas Gregor3cc15812011-07-01 18:22:13 +00001448 PreambleInvocation->getDiagnosticOpts());
Douglas Gregord9a30af2010-08-02 20:51:39 +00001449 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
Douglas Gregord9a30af2010-08-02 20:51:39 +00001450
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001451 return llvm::MemoryBuffer::getMemBufferCopy(
David Blaikied6902a12014-08-29 06:34:53 +00001452 NewPreamble.Buffer->getBuffer(), FrontendOpts.Inputs[0].getFile());
Douglas Gregor0e119552010-07-31 00:40:00 +00001453 }
Douglas Gregor4dde7492010-07-23 23:58:40 +00001454 }
Douglas Gregor028d3e42010-08-09 20:45:32 +00001455
1456 // If we aren't allowed to rebuild the precompiled preamble, just
1457 // return now.
1458 if (!AllowRebuild)
Craig Topper49a27902014-05-22 04:46:25 +00001459 return nullptr;
Douglas Gregorbb6a8812010-10-08 04:03:57 +00001460
Douglas Gregor4dde7492010-07-23 23:58:40 +00001461 // We can't reuse the previously-computed preamble. Build a new one.
1462 Preamble.clear();
Douglas Gregor925296b2011-07-19 16:10:42 +00001463 PreambleDiagnostics.clear();
Ted Kremenek06b4f912011-10-27 17:55:18 +00001464 erasePreambleFile(this);
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001465 PreambleRebuildCounter = 1;
Douglas Gregor028d3e42010-08-09 20:45:32 +00001466 } else if (!AllowRebuild) {
1467 // We aren't allowed to rebuild the precompiled preamble; just
1468 // return now.
Craig Topper49a27902014-05-22 04:46:25 +00001469 return nullptr;
Douglas Gregor028d3e42010-08-09 20:45:32 +00001470 }
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001471
1472 // If the preamble rebuild counter > 1, it's because we previously
1473 // failed to build a preamble and we're not yet ready to try
1474 // again. Decrement the counter and return a failure.
1475 if (PreambleRebuildCounter > 1) {
1476 --PreambleRebuildCounter;
Craig Topper49a27902014-05-22 04:46:25 +00001477 return nullptr;
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001478 }
1479
Douglas Gregore10f0e52010-09-11 17:56:52 +00001480 // Create a temporary file for the precompiled preamble. In rare
1481 // circumstances, this can fail.
1482 std::string PreamblePCHPath = GetPreamblePCHPath();
1483 if (PreamblePCHPath.empty()) {
1484 // Try again next time.
1485 PreambleRebuildCounter = 1;
Craig Topper49a27902014-05-22 04:46:25 +00001486 return nullptr;
Douglas Gregore10f0e52010-09-11 17:56:52 +00001487 }
1488
Douglas Gregor4dde7492010-07-23 23:58:40 +00001489 // We did not previously compute a preamble, or it can't be reused anyway.
Douglas Gregor16896c42010-10-28 15:44:59 +00001490 SimpleTimer PreambleTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00001491 PreambleTimer.setOutput("Precompiling preamble");
Douglas Gregor4dde7492010-07-23 23:58:40 +00001492
Douglas Gregord9a30af2010-08-02 20:51:39 +00001493 // Save the preamble text for later; we'll need to compare against it for
1494 // subsequent reparses.
Dmitri Gribenko40798d32013-12-19 23:25:59 +00001495 StringRef MainFilename = FrontendOpts.Inputs[0].getFile();
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00001496 Preamble.assign(FileMgr->getFile(MainFilename),
David Blaikied6902a12014-08-29 06:34:53 +00001497 NewPreamble.Buffer->getBufferStart(),
1498 NewPreamble.Buffer->getBufferStart() + NewPreamble.Size);
1499 PreambleEndsAtStartOfLine = NewPreamble.PreambleEndsAtStartOfLine;
Douglas Gregord9a30af2010-08-02 20:51:39 +00001500
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001501 PreambleBuffer = llvm::MemoryBuffer::getMemBufferCopy(
David Blaikied6902a12014-08-29 06:34:53 +00001502 NewPreamble.Buffer->getBuffer().slice(0, Preamble.size()), MainFilename);
Rafael Espindolaa96bd562013-06-26 04:12:57 +00001503
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001504 // Remap the main source file to the preamble buffer.
Rafael Espindolaa96bd562013-06-26 04:12:57 +00001505 StringRef MainFilePath = FrontendOpts.Inputs[0].getFile();
Rafael Espindolafa49c0b2014-08-13 16:47:00 +00001506 PreprocessorOpts.addRemappedFile(MainFilePath, PreambleBuffer.get());
Rafael Espindolaa96bd562013-06-26 04:12:57 +00001507
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001508 // Tell the compiler invocation to generate a temporary precompiled header.
1509 FrontendOpts.ProgramAction = frontend::GeneratePCH;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001510 // FIXME: Generate the precompiled header into memory?
Douglas Gregore10f0e52010-09-11 17:56:52 +00001511 FrontendOpts.OutputFile = PreamblePCHPath;
Douglas Gregorbb6a8812010-10-08 04:03:57 +00001512 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
1513 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001514
1515 // Create the compiler instance to use for building the precompiled preamble.
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001516 std::unique_ptr<CompilerInstance> Clang(
Benjamin Kramerd6da1a02016-06-12 20:05:23 +00001517 new CompilerInstance(std::move(PCHContainerOps)));
Ted Kremenek84de4a12011-03-21 18:40:07 +00001518
1519 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00001520 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1521 CICleanup(Clang.get());
Ted Kremenek84de4a12011-03-21 18:40:07 +00001522
Douglas Gregor3cc15812011-07-01 18:22:13 +00001523 Clang->setInvocation(&*PreambleInvocation);
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001524 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001525
Douglas Gregor8e984da2010-08-04 16:47:14 +00001526 // Set up diagnostics, capturing all of the diagnostics produced.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001527 Clang->setDiagnostics(&getDiagnostics());
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001528
1529 // Create the target instance.
Alp Toker80758082014-07-06 05:26:44 +00001530 Clang->setTarget(TargetInfo::CreateTargetInfo(
Saleem Abdulrasool10a49722016-04-08 16:52:00 +00001531 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
Ted Kremenek84de4a12011-03-21 18:40:07 +00001532 if (!Clang->hasTarget()) {
Rafael Espindolaf5e5bc42013-06-26 04:26:38 +00001533 llvm::sys::fs::remove(FrontendOpts.OutputFile);
Douglas Gregor4dde7492010-07-23 23:58:40 +00001534 Preamble.clear();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001535 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Alp Toker1b070d22014-07-07 07:47:20 +00001536 PreprocessorOpts.RemappedFileBuffers.pop_back();
Craig Topper49a27902014-05-22 04:46:25 +00001537 return nullptr;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001538 }
1539
1540 // Inform the target of the language options.
1541 //
1542 // FIXME: We shouldn't need to do this, the target should be immutable once
1543 // created. This complexity should be lifted elsewhere.
Alp Toker74437972014-07-06 05:14:24 +00001544 Clang->getTarget().adjust(Clang->getLangOpts());
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001545
Ted Kremenek84de4a12011-03-21 18:40:07 +00001546 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001547 "Invocation must have exactly one source file!");
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001548 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001549 "FIXME: AST inputs not yet supported here!");
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001550 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001551 "IR inputs not support here!");
1552
1553 // Clear out old caches and data.
Douglas Gregorbb6a8812010-10-08 04:03:57 +00001554 getDiagnostics().Reset();
Ted Kremenek84de4a12011-03-21 18:40:07 +00001555 ProcessWarningOptions(getDiagnostics(), Clang->getDiagnosticOpts());
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +00001556 checkAndRemoveNonDriverDiags(StoredDiagnostics);
Douglas Gregore9db88f2010-08-03 19:06:41 +00001557 TopLevelDecls.clear();
1558 TopLevelDeclsInPreamble.clear();
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001559 PreambleDiagnostics.clear();
Ben Langmuir8832c062014-04-15 18:16:25 +00001560
1561 IntrusiveRefCntPtr<vfs::FileSystem> VFS =
1562 createVFSFromCompilerInvocation(Clang->getInvocation(), getDiagnostics());
1563 if (!VFS)
1564 return nullptr;
1565
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001566 // Create a file manager object to provide access to and cache the filesystem.
Ben Langmuir8832c062014-04-15 18:16:25 +00001567 Clang->setFileManager(new FileManager(Clang->getFileSystemOpts(), VFS));
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001568
1569 // Create the source manager.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001570 Clang->setSourceManager(new SourceManager(getDiagnostics(),
Ted Kremenek5e14d392011-03-21 18:40:17 +00001571 Clang->getFileManager()));
Ahmed Charlesb8984322014-03-07 20:03:18 +00001572
Ben Langmuir33c80902014-06-30 20:04:14 +00001573 auto PreambleDepCollector = std::make_shared<DependencyCollector>();
1574 Clang->addDependencyCollector(PreambleDepCollector);
1575
Ahmed Charlesb8984322014-03-07 20:03:18 +00001576 std::unique_ptr<PrecompilePreambleAction> Act;
Douglas Gregor48c8cd32010-08-03 08:14:03 +00001577 Act.reset(new PrecompilePreambleAction(*this));
Douglas Gregor32fbe312012-01-20 16:28:04 +00001578 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
Rafael Espindolaf5e5bc42013-06-26 04:26:38 +00001579 llvm::sys::fs::remove(FrontendOpts.OutputFile);
Douglas Gregor4dde7492010-07-23 23:58:40 +00001580 Preamble.clear();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001581 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Alp Toker1b070d22014-07-07 07:47:20 +00001582 PreprocessorOpts.RemappedFileBuffers.pop_back();
Craig Topper49a27902014-05-22 04:46:25 +00001583 return nullptr;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001584 }
1585
1586 Act->Execute();
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001587
1588 // Transfer any diagnostics generated when parsing the preamble into the set
1589 // of preamble diagnostics.
Benjamin Kramer1a6e0a92014-10-03 18:52:54 +00001590 for (stored_diag_iterator I = stored_diag_afterDriver_begin(),
1591 E = stored_diag_end();
1592 I != E; ++I)
1593 PreambleDiagnostics.push_back(
1594 makeStandaloneDiagnostic(Clang->getLangOpts(), *I));
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001595
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001596 Act->EndSourceFile();
Ted Kremenek5e14d392011-03-21 18:40:17 +00001597
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001598 checkAndRemoveNonDriverDiags(StoredDiagnostics);
1599
Argyrios Kyrtzidisf0168de2013-06-11 00:36:55 +00001600 if (!Act->hasEmittedPreamblePCH()) {
Argyrios Kyrtzidisd6f57222013-06-11 16:42:34 +00001601 // The preamble PCH failed (e.g. there was a module loading fatal error),
1602 // so no precompiled header was generated. Forget that we even tried.
Douglas Gregora6f74e22010-09-27 16:43:25 +00001603 // FIXME: Should we leave a note for ourselves to try again?
Rafael Espindolaf5e5bc42013-06-26 04:26:38 +00001604 llvm::sys::fs::remove(FrontendOpts.OutputFile);
Douglas Gregor4dde7492010-07-23 23:58:40 +00001605 Preamble.clear();
Douglas Gregore9db88f2010-08-03 19:06:41 +00001606 TopLevelDeclsInPreamble.clear();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001607 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Alp Toker1b070d22014-07-07 07:47:20 +00001608 PreprocessorOpts.RemappedFileBuffers.pop_back();
Craig Topper49a27902014-05-22 04:46:25 +00001609 return nullptr;
Douglas Gregor4dde7492010-07-23 23:58:40 +00001610 }
1611
1612 // Keep track of the preamble we precompiled.
Ted Kremenek06b4f912011-10-27 17:55:18 +00001613 setPreambleFile(this, FrontendOpts.OutputFile);
Douglas Gregord9a30af2010-08-02 20:51:39 +00001614 NumWarningsInPreamble = getDiagnostics().getNumWarnings();
Douglas Gregor0e119552010-07-31 00:40:00 +00001615
1616 // Keep track of all of the files that the source manager knows about,
1617 // so we can verify whether they have changed or not.
1618 FilesInPreamble.clear();
Ted Kremenek84de4a12011-03-21 18:40:07 +00001619 SourceManager &SourceMgr = Clang->getSourceManager();
Ben Langmuir33c80902014-06-30 20:04:14 +00001620 for (auto &Filename : PreambleDepCollector->getDependencies()) {
1621 const FileEntry *File = Clang->getFileManager().getFile(Filename);
1622 if (!File || File == SourceMgr.getFileEntryForID(SourceMgr.getMainFileID()))
Douglas Gregor0e119552010-07-31 00:40:00 +00001623 continue;
Dmitri Gribenko47652522013-12-20 00:16:25 +00001624 if (time_t ModTime = File->getModificationTime()) {
1625 FilesInPreamble[File->getName()] = PreambleFileHash::createForFile(
Ben Langmuir33c80902014-06-30 20:04:14 +00001626 File->getSize(), ModTime);
Dmitri Gribenko47652522013-12-20 00:16:25 +00001627 } else {
Ben Langmuir33c80902014-06-30 20:04:14 +00001628 llvm::MemoryBuffer *Buffer = SourceMgr.getMemoryBufferForFile(File);
Dmitri Gribenko47652522013-12-20 00:16:25 +00001629 FilesInPreamble[File->getName()] =
1630 PreambleFileHash::createForMemoryBuffer(Buffer);
1631 }
Douglas Gregor0e119552010-07-31 00:40:00 +00001632 }
Ben Langmuir33c80902014-06-30 20:04:14 +00001633
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001634 PreambleRebuildCounter = 1;
Alp Toker1b070d22014-07-07 07:47:20 +00001635 PreprocessorOpts.RemappedFileBuffers.pop_back();
1636
Douglas Gregordf7a79a2011-02-16 18:16:54 +00001637 // If the hash of top-level entities differs from the hash of the top-level
1638 // entities the last time we rebuilt the preamble, clear out the completion
1639 // cache.
1640 if (CurrentTopLevelHashValue != PreambleTopLevelHashValue) {
1641 CompletionCacheTopLevelHashValue = 0;
1642 PreambleTopLevelHashValue = CurrentTopLevelHashValue;
1643 }
Rafael Espindola2346a372014-08-18 18:47:08 +00001644
David Blaikied6902a12014-08-29 06:34:53 +00001645 return llvm::MemoryBuffer::getMemBufferCopy(NewPreamble.Buffer->getBuffer(),
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001646 MainFilename);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001647}
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001648
Douglas Gregore9db88f2010-08-03 19:06:41 +00001649void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
1650 std::vector<Decl *> Resolved;
1651 Resolved.reserve(TopLevelDeclsInPreamble.size());
1652 ExternalASTSource &Source = *getASTContext().getExternalSource();
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00001653 for (serialization::DeclID TopLevelDecl : TopLevelDeclsInPreamble) {
Douglas Gregore9db88f2010-08-03 19:06:41 +00001654 // Resolve the declaration ID to an actual declaration, possibly
1655 // deserializing the declaration in the process.
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00001656 if (Decl *D = Source.GetExternalDecl(TopLevelDecl))
Douglas Gregore9db88f2010-08-03 19:06:41 +00001657 Resolved.push_back(D);
1658 }
1659 TopLevelDeclsInPreamble.clear();
1660 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1661}
1662
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001663void ASTUnit::transferASTDataFromCompilerInstance(CompilerInstance &CI) {
Ben Langmuir749323f2014-04-22 17:40:12 +00001664 // Steal the created target, context, and preprocessor if they have been
1665 // created.
1666 assert(CI.hasInvocation() && "missing invocation");
Alp Toker269d8402014-07-06 05:26:07 +00001667 LangOpts = CI.getInvocation().LangOpts;
David Blaikieec99b5e2014-08-10 19:14:48 +00001668 TheSema = CI.takeSema();
David Blaikie6beb6aa2014-08-10 19:56:51 +00001669 Consumer = CI.takeASTConsumer();
Ben Langmuir532fdc02014-04-18 20:39:48 +00001670 if (CI.hasASTContext())
1671 Ctx = &CI.getASTContext();
1672 if (CI.hasPreprocessor())
1673 PP = &CI.getPreprocessor();
Craig Topper49a27902014-05-22 04:46:25 +00001674 CI.setSourceManager(nullptr);
1675 CI.setFileManager(nullptr);
Ben Langmuir532fdc02014-04-18 20:39:48 +00001676 if (CI.hasTarget())
1677 Target = &CI.getTarget();
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001678 Reader = CI.getModuleManager();
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00001679 HadModuleLoaderFatalFailure = CI.hadModuleLoaderFatalFailure();
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001680}
1681
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001682StringRef ASTUnit::getMainFileName() const {
Argyrios Kyrtzidis928e1fd2013-01-11 22:11:14 +00001683 if (Invocation && !Invocation->getFrontendOpts().Inputs.empty()) {
1684 const FrontendInputFile &Input = Invocation->getFrontendOpts().Inputs[0];
1685 if (Input.isFile())
1686 return Input.getFile();
1687 else
1688 return Input.getBuffer()->getBufferIdentifier();
1689 }
1690
1691 if (SourceMgr) {
1692 if (const FileEntry *
1693 FE = SourceMgr->getFileEntryForID(SourceMgr->getMainFileID()))
1694 return FE->getName();
1695 }
1696
1697 return StringRef();
Douglas Gregor16896c42010-10-28 15:44:59 +00001698}
1699
Argyrios Kyrtzidis37f2ab42013-03-05 20:21:14 +00001700StringRef ASTUnit::getASTFileName() const {
1701 if (!isMainFileAST())
1702 return StringRef();
1703
1704 serialization::ModuleFile &
1705 Mod = Reader->getModuleManager().getPrimaryModule();
1706 return Mod.FileName;
1707}
1708
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00001709ASTUnit *ASTUnit::create(CompilerInvocation *CI,
Dylan Noblesmithc95d8192012-02-20 14:00:23 +00001710 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +00001711 bool CaptureDiagnostics,
1712 bool UserFilesAreVolatile) {
Ahmed Charlesb8984322014-03-07 20:03:18 +00001713 std::unique_ptr<ASTUnit> AST;
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00001714 AST.reset(new ASTUnit(false));
Justin Bognerdbbcb112014-10-14 23:36:06 +00001715 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00001716 AST->Diagnostics = Diags;
Ted Kremenek5e14d392011-03-21 18:40:17 +00001717 AST->Invocation = CI;
Anders Carlssonc30dcec2011-03-18 18:22:40 +00001718 AST->FileSystemOpts = CI->getFileSystemOpts();
Ben Langmuir8832c062014-04-15 18:16:25 +00001719 IntrusiveRefCntPtr<vfs::FileSystem> VFS =
1720 createVFSFromCompilerInvocation(*CI, *Diags);
1721 if (!VFS)
1722 return nullptr;
1723 AST->FileMgr = new FileManager(AST->FileSystemOpts, VFS);
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +00001724 AST->UserFilesAreVolatile = UserFilesAreVolatile;
1725 AST->SourceMgr = new SourceManager(AST->getDiagnostics(), *AST->FileMgr,
1726 UserFilesAreVolatile);
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00001727
Ahmed Charles9a16beb2014-03-07 19:33:25 +00001728 return AST.release();
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00001729}
1730
Ahmed Charlesb8984322014-03-07 20:03:18 +00001731ASTUnit *ASTUnit::LoadFromCompilerInvocationAction(
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001732 CompilerInvocation *CI,
1733 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
Argyrios Kyrtzidisc382abf2016-02-09 19:07:13 +00001734 IntrusiveRefCntPtr<DiagnosticsEngine> Diags, FrontendAction *Action,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001735 ASTUnit *Unit, bool Persistent, StringRef ResourceFilesPath,
Benjamin Kramer5c248d82015-12-15 09:30:31 +00001736 bool OnlyLocalDecls, bool CaptureDiagnostics,
1737 unsigned PrecompilePreambleAfterNParses, bool CacheCodeCompletionResults,
1738 bool IncludeBriefCommentsInCodeCompletion, bool UserFilesAreVolatile,
1739 std::unique_ptr<ASTUnit> *ErrAST) {
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001740 assert(CI && "A CompilerInvocation is required");
1741
Ahmed Charlesb8984322014-03-07 20:03:18 +00001742 std::unique_ptr<ASTUnit> OwnAST;
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001743 ASTUnit *AST = Unit;
1744 if (!AST) {
1745 // Create the AST unit.
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +00001746 OwnAST.reset(create(CI, Diags, CaptureDiagnostics, UserFilesAreVolatile));
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001747 AST = OwnAST.get();
Ben Langmuir8832c062014-04-15 18:16:25 +00001748 if (!AST)
1749 return nullptr;
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001750 }
1751
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00001752 if (!ResourceFilesPath.empty()) {
1753 // Override the resources path.
1754 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
1755 }
1756 AST->OnlyLocalDecls = OnlyLocalDecls;
1757 AST->CaptureDiagnostics = CaptureDiagnostics;
Benjamin Kramer5c248d82015-12-15 09:30:31 +00001758 if (PrecompilePreambleAfterNParses > 0)
1759 AST->PreambleRebuildCounter = PrecompilePreambleAfterNParses;
Douglas Gregor69f74f82011-08-25 22:30:56 +00001760 AST->TUKind = Action ? Action->getTranslationUnitKind() : TU_Complete;
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00001761 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenko3292d062012-07-02 17:35:10 +00001762 AST->IncludeBriefCommentsInCodeCompletion
1763 = IncludeBriefCommentsInCodeCompletion;
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001764
1765 // Recover resources if we crash before exiting this method.
1766 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001767 ASTUnitCleanup(OwnAST.get());
David Blaikie9c902b52011-09-25 23:23:43 +00001768 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1769 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Alp Tokerf994cef2014-07-05 03:08:06 +00001770 DiagCleanup(Diags.get());
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001771
1772 // We'll manage file buffers ourselves.
1773 CI->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1774 CI->getFrontendOpts().DisableFree = false;
1775 ProcessWarningOptions(AST->getDiagnostics(), CI->getDiagnosticOpts());
1776
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001777 // Create the compiler instance to use for building the AST.
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001778 std::unique_ptr<CompilerInstance> Clang(
Benjamin Kramerd6da1a02016-06-12 20:05:23 +00001779 new CompilerInstance(std::move(PCHContainerOps)));
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001780
1781 // Recover resources if we crash before exiting this method.
1782 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1783 CICleanup(Clang.get());
1784
1785 Clang->setInvocation(CI);
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001786 AST->OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001787
1788 // Set up diagnostics, capturing any diagnostics that would
1789 // otherwise be dropped.
1790 Clang->setDiagnostics(&AST->getDiagnostics());
1791
1792 // Create the target instance.
Alp Toker80758082014-07-06 05:26:44 +00001793 Clang->setTarget(TargetInfo::CreateTargetInfo(
Saleem Abdulrasool10a49722016-04-08 16:52:00 +00001794 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001795 if (!Clang->hasTarget())
Craig Topper49a27902014-05-22 04:46:25 +00001796 return nullptr;
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001797
1798 // Inform the target of the language options.
1799 //
1800 // FIXME: We shouldn't need to do this, the target should be immutable once
1801 // created. This complexity should be lifted elsewhere.
Alp Toker74437972014-07-06 05:14:24 +00001802 Clang->getTarget().adjust(Clang->getLangOpts());
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001803
1804 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1805 "Invocation must have exactly one source file!");
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001806 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001807 "FIXME: AST inputs not yet supported here!");
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001808 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001809 "IR inputs not supported here!");
1810
1811 // Configure the various subsystems.
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001812 AST->TheSema.reset();
Craig Topper49a27902014-05-22 04:46:25 +00001813 AST->Ctx = nullptr;
1814 AST->PP = nullptr;
1815 AST->Reader = nullptr;
1816
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001817 // Create a file manager object to provide access to and cache the filesystem.
1818 Clang->setFileManager(&AST->getFileManager());
1819
1820 // Create the source manager.
1821 Clang->setSourceManager(&AST->getSourceManager());
1822
Argyrios Kyrtzidisc382abf2016-02-09 19:07:13 +00001823 FrontendAction *Act = Action;
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001824
Ahmed Charlesb8984322014-03-07 20:03:18 +00001825 std::unique_ptr<TopLevelDeclTrackerAction> TrackerAct;
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001826 if (!Act) {
1827 TrackerAct.reset(new TopLevelDeclTrackerAction(*AST));
1828 Act = TrackerAct.get();
1829 }
1830
1831 // Recover resources if we crash before exiting this method.
1832 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1833 ActCleanup(TrackerAct.get());
1834
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001835 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
1836 AST->transferASTDataFromCompilerInstance(*Clang);
1837 if (OwnAST && ErrAST)
1838 ErrAST->swap(OwnAST);
1839
Craig Topper49a27902014-05-22 04:46:25 +00001840 return nullptr;
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001841 }
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00001842
1843 if (Persistent && !TrackerAct) {
1844 Clang->getPreprocessor().addPPCallbacks(
Craig Topperb8a70532014-09-10 04:53:53 +00001845 llvm::make_unique<MacroDefinitionTrackerPPCallbacks>(
1846 AST->getCurrentTopLevelHashValue()));
David Blaikie6beb6aa2014-08-10 19:56:51 +00001847 std::vector<std::unique_ptr<ASTConsumer>> Consumers;
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00001848 if (Clang->hasASTConsumer())
1849 Consumers.push_back(Clang->takeASTConsumer());
David Blaikie6beb6aa2014-08-10 19:56:51 +00001850 Consumers.push_back(llvm::make_unique<TopLevelDeclTrackerConsumer>(
1851 *AST, AST->getCurrentTopLevelHashValue()));
1852 Clang->setASTConsumer(
1853 llvm::make_unique<MultiplexConsumer>(std::move(Consumers)));
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00001854 }
Argyrios Kyrtzidis1416e172012-06-08 05:48:06 +00001855 if (!Act->Execute()) {
1856 AST->transferASTDataFromCompilerInstance(*Clang);
1857 if (OwnAST && ErrAST)
1858 ErrAST->swap(OwnAST);
1859
Craig Topper49a27902014-05-22 04:46:25 +00001860 return nullptr;
Argyrios Kyrtzidis1416e172012-06-08 05:48:06 +00001861 }
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001862
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001863 // Steal the created target, context, and preprocessor.
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001864 AST->transferASTDataFromCompilerInstance(*Clang);
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001865
1866 Act->EndSourceFile();
1867
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001868 if (OwnAST)
Ahmed Charles9a16beb2014-03-07 19:33:25 +00001869 return OwnAST.release();
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001870 else
1871 return AST;
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001872}
1873
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001874bool ASTUnit::LoadFromCompilerInvocation(
1875 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
Benjamin Kramer5c248d82015-12-15 09:30:31 +00001876 unsigned PrecompilePreambleAfterNParses) {
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001877 if (!Invocation)
1878 return true;
1879
1880 // We'll manage file buffers ourselves.
1881 Invocation->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1882 Invocation->getFrontendOpts().DisableFree = false;
Douglas Gregor345c1bc2011-01-19 01:02:47 +00001883 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001884
Rafael Espindola32482082014-08-18 16:23:45 +00001885 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
Benjamin Kramer5c248d82015-12-15 09:30:31 +00001886 if (PrecompilePreambleAfterNParses > 0) {
1887 PreambleRebuildCounter = PrecompilePreambleAfterNParses;
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001888 OverrideMainBuffer =
1889 getMainBufferWithPrecompiledPreamble(PCHContainerOps, *Invocation);
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001890 }
1891
Douglas Gregor16896c42010-10-28 15:44:59 +00001892 SimpleTimer ParsingTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00001893 ParsingTimer.setOutput("Parsing " + getMainFileName());
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001894
Ted Kremenek022a4902011-03-22 01:15:24 +00001895 // Recover resources if we crash before exiting this method.
1896 llvm::CrashRecoveryContextCleanupRegistrar<llvm::MemoryBuffer>
Rafael Espindola32482082014-08-18 16:23:45 +00001897 MemBufferCleanup(OverrideMainBuffer.get());
1898
Benjamin Kramerd6da1a02016-06-12 20:05:23 +00001899 return Parse(std::move(PCHContainerOps), std::move(OverrideMainBuffer));
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001900}
1901
David Blaikie103a2de2014-04-25 17:01:33 +00001902std::unique_ptr<ASTUnit> ASTUnit::LoadFromCompilerInvocation(
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001903 CompilerInvocation *CI,
1904 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
Benjamin Kramerbc632902015-10-06 14:45:20 +00001905 IntrusiveRefCntPtr<DiagnosticsEngine> Diags, FileManager *FileMgr,
Benjamin Kramer5c248d82015-12-15 09:30:31 +00001906 bool OnlyLocalDecls, bool CaptureDiagnostics,
1907 unsigned PrecompilePreambleAfterNParses, TranslationUnitKind TUKind,
1908 bool CacheCodeCompletionResults, bool IncludeBriefCommentsInCodeCompletion,
1909 bool UserFilesAreVolatile) {
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001910 // Create the AST unit.
David Blaikie103a2de2014-04-25 17:01:33 +00001911 std::unique_ptr<ASTUnit> AST(new ASTUnit(false));
Justin Bognerdbbcb112014-10-14 23:36:06 +00001912 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001913 AST->Diagnostics = Diags;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001914 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001915 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor69f74f82011-08-25 22:30:56 +00001916 AST->TUKind = TUKind;
Douglas Gregorb14904c2010-08-13 22:48:40 +00001917 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenko3292d062012-07-02 17:35:10 +00001918 AST->IncludeBriefCommentsInCodeCompletion
1919 = IncludeBriefCommentsInCodeCompletion;
Ted Kremenek5e14d392011-03-21 18:40:17 +00001920 AST->Invocation = CI;
Benjamin Kramerbc632902015-10-06 14:45:20 +00001921 AST->FileSystemOpts = FileMgr->getFileSystemOpts();
1922 AST->FileMgr = FileMgr;
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +00001923 AST->UserFilesAreVolatile = UserFilesAreVolatile;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001924
Ted Kremenek4422bfe2011-03-18 02:06:56 +00001925 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00001926 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1927 ASTUnitCleanup(AST.get());
David Blaikie9c902b52011-09-25 23:23:43 +00001928 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1929 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Alp Tokerf994cef2014-07-05 03:08:06 +00001930 DiagCleanup(Diags.get());
Ted Kremenek4422bfe2011-03-18 02:06:56 +00001931
Benjamin Kramerd6da1a02016-06-12 20:05:23 +00001932 if (AST->LoadFromCompilerInvocation(std::move(PCHContainerOps),
Benjamin Kramer5c248d82015-12-15 09:30:31 +00001933 PrecompilePreambleAfterNParses))
David Blaikie103a2de2014-04-25 17:01:33 +00001934 return nullptr;
1935 return AST;
Daniel Dunbar764c0822009-12-01 09:51:01 +00001936}
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001937
Ahmed Charlesb8984322014-03-07 20:03:18 +00001938ASTUnit *ASTUnit::LoadFromCommandLine(
1939 const char **ArgBegin, const char **ArgEnd,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001940 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
Ahmed Charlesb8984322014-03-07 20:03:18 +00001941 IntrusiveRefCntPtr<DiagnosticsEngine> Diags, StringRef ResourceFilesPath,
1942 bool OnlyLocalDecls, bool CaptureDiagnostics,
1943 ArrayRef<RemappedFile> RemappedFiles, bool RemappedFilesKeepOriginalName,
Benjamin Kramer5c248d82015-12-15 09:30:31 +00001944 unsigned PrecompilePreambleAfterNParses, TranslationUnitKind TUKind,
Ahmed Charlesb8984322014-03-07 20:03:18 +00001945 bool CacheCodeCompletionResults, bool IncludeBriefCommentsInCodeCompletion,
1946 bool AllowPCHWithCompilerErrors, bool SkipFunctionBodies,
1947 bool UserFilesAreVolatile, bool ForSerialization,
Benjamin Kramer5c248d82015-12-15 09:30:31 +00001948 llvm::Optional<StringRef> ModuleFormat, std::unique_ptr<ASTUnit> *ErrAST) {
Justin Bognerd512c1e2014-10-15 00:33:06 +00001949 assert(Diags.get() && "no DiagnosticsEngine was provided");
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001950
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001951 SmallVector<StoredDiagnostic, 4> StoredDiagnostics;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001952
Dylan Noblesmithc95d8192012-02-20 14:00:23 +00001953 IntrusiveRefCntPtr<CompilerInvocation> CI;
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001954
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001955 {
Douglas Gregor925296b2011-07-19 16:10:42 +00001956
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001957 CaptureDroppedDiagnostics Capture(CaptureDiagnostics, *Diags,
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001958 StoredDiagnostics);
Daniel Dunbarfcf2d422010-01-25 00:44:02 +00001959
Argyrios Kyrtzidis5cf423e2011-04-04 23:11:45 +00001960 CI = clang::createInvocationFromCommandLine(
Frits van Bommel717d7ed2011-07-18 12:00:32 +00001961 llvm::makeArrayRef(ArgBegin, ArgEnd),
1962 Diags);
Argyrios Kyrtzidisf606b822011-04-04 21:38:51 +00001963 if (!CI)
Craig Topper49a27902014-05-22 04:46:25 +00001964 return nullptr;
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001965 }
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001966
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001967 // Override any files that need remapping
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00001968 for (const auto &RemappedFile : RemappedFiles) {
1969 CI->getPreprocessorOpts().addRemappedFile(RemappedFile.first,
1970 RemappedFile.second);
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00001971 }
Argyrios Kyrtzidis4a280ff2012-03-07 01:51:17 +00001972 PreprocessorOptions &PPOpts = CI->getPreprocessorOpts();
1973 PPOpts.RemappedFilesKeepOriginalName = RemappedFilesKeepOriginalName;
1974 PPOpts.AllowPCHWithCompilerErrors = AllowPCHWithCompilerErrors;
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001975
Daniel Dunbara5a166d2009-12-15 00:06:45 +00001976 // Override the resources path.
Daniel Dunbar6b03ece2010-01-30 21:47:16 +00001977 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001978
Erik Verbruggen6e922512012-04-12 10:11:59 +00001979 CI->getFrontendOpts().SkipFunctionBodies = SkipFunctionBodies;
1980
Argyrios Kyrtzidisa3e2ff12015-11-20 03:36:21 +00001981 if (ModuleFormat)
1982 CI->getHeaderSearchOpts().ModuleFormat = ModuleFormat.getValue();
1983
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001984 // Create the AST unit.
Ahmed Charlesb8984322014-03-07 20:03:18 +00001985 std::unique_ptr<ASTUnit> AST;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001986 AST.reset(new ASTUnit(false));
Justin Bognerdbbcb112014-10-14 23:36:06 +00001987 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001988 AST->Diagnostics = Diags;
Anders Carlssonc30dcec2011-03-18 18:22:40 +00001989 AST->FileSystemOpts = CI->getFileSystemOpts();
Ben Langmuir8832c062014-04-15 18:16:25 +00001990 IntrusiveRefCntPtr<vfs::FileSystem> VFS =
1991 createVFSFromCompilerInvocation(*CI, *Diags);
1992 if (!VFS)
1993 return nullptr;
1994 AST->FileMgr = new FileManager(AST->FileSystemOpts, VFS);
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001995 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001996 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor69f74f82011-08-25 22:30:56 +00001997 AST->TUKind = TUKind;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001998 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenko3292d062012-07-02 17:35:10 +00001999 AST->IncludeBriefCommentsInCodeCompletion
2000 = IncludeBriefCommentsInCodeCompletion;
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +00002001 AST->UserFilesAreVolatile = UserFilesAreVolatile;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00002002 AST->NumStoredDiagnosticsFromDriver = StoredDiagnostics.size();
Douglas Gregor7bb8af62010-10-12 00:50:20 +00002003 AST->StoredDiagnostics.swap(StoredDiagnostics);
Ted Kremenek5e14d392011-03-21 18:40:17 +00002004 AST->Invocation = CI;
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00002005 if (ForSerialization)
2006 AST->WriterData.reset(new ASTWriterData());
Alexey Samsonovb4f99dd2014-08-28 23:51:01 +00002007 // Zero out now to ease cleanup during crash recovery.
2008 CI = nullptr;
2009 Diags = nullptr;
Craig Topper49a27902014-05-22 04:46:25 +00002010
Ted Kremenek4422bfe2011-03-18 02:06:56 +00002011 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00002012 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
2013 ASTUnitCleanup(AST.get());
Ted Kremenek4422bfe2011-03-18 02:06:56 +00002014
Benjamin Kramerd6da1a02016-06-12 20:05:23 +00002015 if (AST->LoadFromCompilerInvocation(std::move(PCHContainerOps),
Benjamin Kramer5c248d82015-12-15 09:30:31 +00002016 PrecompilePreambleAfterNParses)) {
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00002017 // Some error occurred, if caller wants to examine diagnostics, pass it the
2018 // ASTUnit.
2019 if (ErrAST) {
2020 AST->StoredDiagnostics.swap(AST->FailedParseDiagnostics);
2021 ErrAST->swap(AST);
2022 }
Craig Topper49a27902014-05-22 04:46:25 +00002023 return nullptr;
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00002024 }
2025
Ahmed Charles9a16beb2014-03-07 19:33:25 +00002026 return AST.release();
Daniel Dunbar55a17b62009-12-02 03:23:45 +00002027}
Douglas Gregoraa21cc42010-07-19 21:46:24 +00002028
Adrian Prantlbb165fb2015-06-20 18:53:08 +00002029bool ASTUnit::Reparse(std::shared_ptr<PCHContainerOperations> PCHContainerOps,
2030 ArrayRef<RemappedFile> RemappedFiles) {
Ted Kremenek5e14d392011-03-21 18:40:17 +00002031 if (!Invocation)
Douglas Gregoraa21cc42010-07-19 21:46:24 +00002032 return true;
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00002033
2034 clearFileLevelDecls();
Douglas Gregoraa21cc42010-07-19 21:46:24 +00002035
Douglas Gregor16896c42010-10-28 15:44:59 +00002036 SimpleTimer ParsingTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00002037 ParsingTimer.setOutput("Reparsing " + getMainFileName());
Douglas Gregor16896c42010-10-28 15:44:59 +00002038
Douglas Gregor0e119552010-07-31 00:40:00 +00002039 // Remap files.
Douglas Gregor7b02b582010-08-20 00:02:33 +00002040 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
Alp Toker1b070d22014-07-07 07:47:20 +00002041 for (const auto &RB : PPOpts.RemappedFileBuffers)
2042 delete RB.second;
2043
Douglas Gregor0e119552010-07-31 00:40:00 +00002044 Invocation->getPreprocessorOpts().clearRemappedFiles();
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00002045 for (const auto &RemappedFile : RemappedFiles) {
2046 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFile.first,
2047 RemappedFile.second);
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00002048 }
Dmitri Gribenkoc444b572014-02-08 00:38:15 +00002049
Douglas Gregorbb420ab2010-08-04 05:53:38 +00002050 // If we have a preamble file lying around, or if we might try to
2051 // build a precompiled preamble, do so now.
Rafael Espindola32482082014-08-18 16:23:45 +00002052 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
Ted Kremenek06b4f912011-10-27 17:55:18 +00002053 if (!getPreambleFile(this).empty() || PreambleRebuildCounter > 0)
Adrian Prantlbb165fb2015-06-20 18:53:08 +00002054 OverrideMainBuffer =
2055 getMainBufferWithPrecompiledPreamble(PCHContainerOps, *Invocation);
2056
Douglas Gregoraa21cc42010-07-19 21:46:24 +00002057 // Clear out the diagnostics state.
Benjamin Kramerbc632902015-10-06 14:45:20 +00002058 FileMgr.reset();
Argyrios Kyrtzidisf50f7b22011-11-03 20:28:19 +00002059 getDiagnostics().Reset();
2060 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Argyrios Kyrtzidis462ff352011-11-03 20:57:33 +00002061 if (OverrideMainBuffer)
2062 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
Argyrios Kyrtzidisf50f7b22011-11-03 20:28:19 +00002063
Douglas Gregor4dde7492010-07-23 23:58:40 +00002064 // Parse the sources
Benjamin Kramerd6da1a02016-06-12 20:05:23 +00002065 bool Result =
2066 Parse(std::move(PCHContainerOps), std::move(OverrideMainBuffer));
Rafael Espindola32482082014-08-18 16:23:45 +00002067
Argyrios Kyrtzidis36893372011-10-31 21:25:31 +00002068 // If we're caching global code-completion results, and the top-level
2069 // declarations have changed, clear out the code-completion cache.
2070 if (!Result && ShouldCacheCodeCompletionResults &&
2071 CurrentTopLevelHashValue != CompletionCacheTopLevelHashValue)
2072 CacheCodeCompletionResults();
Douglas Gregordf7a79a2011-02-16 18:16:54 +00002073
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00002074 // We now need to clear out the completion info related to this translation
2075 // unit; it'll be recreated if necessary.
2076 CCTUInfo.reset();
Douglas Gregor3f35bb22011-08-04 20:04:59 +00002077
Douglas Gregor4dde7492010-07-23 23:58:40 +00002078 return Result;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00002079}
Douglas Gregor8e984da2010-08-04 16:47:14 +00002080
Douglas Gregorb14904c2010-08-13 22:48:40 +00002081//----------------------------------------------------------------------------//
2082// Code completion
2083//----------------------------------------------------------------------------//
2084
2085namespace {
2086 /// \brief Code completion consumer that combines the cached code-completion
2087 /// results from an ASTUnit with the code-completion results provided to it,
2088 /// then passes the result on to
2089 class AugmentedCodeCompleteConsumer : public CodeCompleteConsumer {
Richard Smith697cc9e2012-08-14 03:13:00 +00002090 uint64_t NormalContexts;
Douglas Gregorb14904c2010-08-13 22:48:40 +00002091 ASTUnit &AST;
2092 CodeCompleteConsumer &Next;
2093
2094 public:
2095 AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next,
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002096 const CodeCompleteOptions &CodeCompleteOpts)
2097 : CodeCompleteConsumer(CodeCompleteOpts, Next.isOutputBinary()),
2098 AST(AST), Next(Next)
Douglas Gregorb14904c2010-08-13 22:48:40 +00002099 {
2100 // Compute the set of contexts in which we will look when we don't have
2101 // any information about the specific context.
2102 NormalContexts
Richard Smith697cc9e2012-08-14 03:13:00 +00002103 = (1LL << CodeCompletionContext::CCC_TopLevel)
2104 | (1LL << CodeCompletionContext::CCC_ObjCInterface)
2105 | (1LL << CodeCompletionContext::CCC_ObjCImplementation)
2106 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
2107 | (1LL << CodeCompletionContext::CCC_Statement)
2108 | (1LL << CodeCompletionContext::CCC_Expression)
2109 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
2110 | (1LL << CodeCompletionContext::CCC_DotMemberAccess)
2111 | (1LL << CodeCompletionContext::CCC_ArrowMemberAccess)
2112 | (1LL << CodeCompletionContext::CCC_ObjCPropertyAccess)
2113 | (1LL << CodeCompletionContext::CCC_ObjCProtocolName)
2114 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
2115 | (1LL << CodeCompletionContext::CCC_Recovery);
Douglas Gregor5e35d592010-09-14 23:59:36 +00002116
David Blaikiebbafb8a2012-03-11 07:00:24 +00002117 if (AST.getASTContext().getLangOpts().CPlusPlus)
Richard Smith697cc9e2012-08-14 03:13:00 +00002118 NormalContexts |= (1LL << CodeCompletionContext::CCC_EnumTag)
2119 | (1LL << CodeCompletionContext::CCC_UnionTag)
2120 | (1LL << CodeCompletionContext::CCC_ClassOrStructTag);
Douglas Gregorb14904c2010-08-13 22:48:40 +00002121 }
Craig Topperafa7cb32014-03-13 06:07:04 +00002122
2123 void ProcessCodeCompleteResults(Sema &S, CodeCompletionContext Context,
2124 CodeCompletionResult *Results,
2125 unsigned NumResults) override;
2126
2127 void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
2128 OverloadCandidate *Candidates,
2129 unsigned NumCandidates) override {
Douglas Gregorb14904c2010-08-13 22:48:40 +00002130 Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates);
2131 }
Craig Topperafa7cb32014-03-13 06:07:04 +00002132
2133 CodeCompletionAllocator &getAllocator() override {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002134 return Next.getAllocator();
2135 }
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00002136
Craig Topperafa7cb32014-03-13 06:07:04 +00002137 CodeCompletionTUInfo &getCodeCompletionTUInfo() override {
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00002138 return Next.getCodeCompletionTUInfo();
2139 }
Douglas Gregorb14904c2010-08-13 22:48:40 +00002140 };
Hans Wennborgdcfba332015-10-06 23:40:43 +00002141} // anonymous namespace
Douglas Gregord46cf182010-08-16 20:01:48 +00002142
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002143/// \brief Helper function that computes which global names are hidden by the
2144/// local code-completion results.
Ted Kremenek6a153372010-11-07 06:11:36 +00002145static void CalculateHiddenNames(const CodeCompletionContext &Context,
2146 CodeCompletionResult *Results,
2147 unsigned NumResults,
2148 ASTContext &Ctx,
2149 llvm::StringSet<llvm::BumpPtrAllocator> &HiddenNames){
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002150 bool OnlyTagNames = false;
2151 switch (Context.getKind()) {
Douglas Gregor0ac41382010-09-23 23:01:17 +00002152 case CodeCompletionContext::CCC_Recovery:
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002153 case CodeCompletionContext::CCC_TopLevel:
2154 case CodeCompletionContext::CCC_ObjCInterface:
2155 case CodeCompletionContext::CCC_ObjCImplementation:
2156 case CodeCompletionContext::CCC_ObjCIvarList:
2157 case CodeCompletionContext::CCC_ClassStructUnion:
2158 case CodeCompletionContext::CCC_Statement:
2159 case CodeCompletionContext::CCC_Expression:
2160 case CodeCompletionContext::CCC_ObjCMessageReceiver:
Douglas Gregor21325842011-07-07 16:03:39 +00002161 case CodeCompletionContext::CCC_DotMemberAccess:
2162 case CodeCompletionContext::CCC_ArrowMemberAccess:
2163 case CodeCompletionContext::CCC_ObjCPropertyAccess:
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002164 case CodeCompletionContext::CCC_Namespace:
2165 case CodeCompletionContext::CCC_Type:
Douglas Gregorc49f5b22010-08-23 18:23:48 +00002166 case CodeCompletionContext::CCC_Name:
2167 case CodeCompletionContext::CCC_PotentiallyQualifiedName:
Douglas Gregor5e35d592010-09-14 23:59:36 +00002168 case CodeCompletionContext::CCC_ParenthesizedExpression:
Douglas Gregor2c595ad2011-07-30 06:55:39 +00002169 case CodeCompletionContext::CCC_ObjCInterfaceName:
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002170 break;
2171
2172 case CodeCompletionContext::CCC_EnumTag:
2173 case CodeCompletionContext::CCC_UnionTag:
2174 case CodeCompletionContext::CCC_ClassOrStructTag:
2175 OnlyTagNames = true;
2176 break;
2177
2178 case CodeCompletionContext::CCC_ObjCProtocolName:
Douglas Gregor12785102010-08-24 20:21:13 +00002179 case CodeCompletionContext::CCC_MacroName:
2180 case CodeCompletionContext::CCC_MacroNameUse:
Douglas Gregorec00a262010-08-24 22:20:20 +00002181 case CodeCompletionContext::CCC_PreprocessorExpression:
Douglas Gregor0de55ce2010-08-25 18:41:16 +00002182 case CodeCompletionContext::CCC_PreprocessorDirective:
Douglas Gregorea147052010-08-25 18:04:30 +00002183 case CodeCompletionContext::CCC_NaturalLanguage:
Douglas Gregor67c692c2010-08-26 15:07:07 +00002184 case CodeCompletionContext::CCC_SelectorName:
Douglas Gregor28c78432010-08-27 17:35:51 +00002185 case CodeCompletionContext::CCC_TypeQualifiers:
Douglas Gregor0ac41382010-09-23 23:01:17 +00002186 case CodeCompletionContext::CCC_Other:
Douglas Gregor3a69eaf2011-02-18 23:30:37 +00002187 case CodeCompletionContext::CCC_OtherWithMacros:
Douglas Gregor21325842011-07-07 16:03:39 +00002188 case CodeCompletionContext::CCC_ObjCInstanceMessage:
2189 case CodeCompletionContext::CCC_ObjCClassMessage:
2190 case CodeCompletionContext::CCC_ObjCCategoryName:
Douglas Gregor0de55ce2010-08-25 18:41:16 +00002191 // We're looking for nothing, or we're looking for names that cannot
2192 // be hidden.
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002193 return;
2194 }
2195
John McCall276321a2010-08-25 06:19:51 +00002196 typedef CodeCompletionResult Result;
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002197 for (unsigned I = 0; I != NumResults; ++I) {
2198 if (Results[I].Kind != Result::RK_Declaration)
2199 continue;
2200
2201 unsigned IDNS
2202 = Results[I].Declaration->getUnderlyingDecl()->getIdentifierNamespace();
2203
2204 bool Hiding = false;
2205 if (OnlyTagNames)
2206 Hiding = (IDNS & Decl::IDNS_Tag);
2207 else {
2208 unsigned HiddenIDNS = (Decl::IDNS_Type | Decl::IDNS_Member |
Douglas Gregor59cab552010-08-16 23:05:20 +00002209 Decl::IDNS_Namespace | Decl::IDNS_Ordinary |
2210 Decl::IDNS_NonMemberOperator);
David Blaikiebbafb8a2012-03-11 07:00:24 +00002211 if (Ctx.getLangOpts().CPlusPlus)
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002212 HiddenIDNS |= Decl::IDNS_Tag;
2213 Hiding = (IDNS & HiddenIDNS);
2214 }
2215
2216 if (!Hiding)
2217 continue;
2218
2219 DeclarationName Name = Results[I].Declaration->getDeclName();
2220 if (IdentifierInfo *Identifier = Name.getAsIdentifierInfo())
2221 HiddenNames.insert(Identifier->getName());
2222 else
2223 HiddenNames.insert(Name.getAsString());
2224 }
2225}
2226
Douglas Gregord46cf182010-08-16 20:01:48 +00002227void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &S,
2228 CodeCompletionContext Context,
John McCall276321a2010-08-25 06:19:51 +00002229 CodeCompletionResult *Results,
Douglas Gregord46cf182010-08-16 20:01:48 +00002230 unsigned NumResults) {
2231 // Merge the results we were given with the results we cached.
2232 bool AddedResult = false;
Richard Smith697cc9e2012-08-14 03:13:00 +00002233 uint64_t InContexts =
2234 Context.getKind() == CodeCompletionContext::CCC_Recovery
2235 ? NormalContexts : (1LL << Context.getKind());
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002236 // Contains the set of names that are hidden by "local" completion results.
Ted Kremenek6a153372010-11-07 06:11:36 +00002237 llvm::StringSet<llvm::BumpPtrAllocator> HiddenNames;
John McCall276321a2010-08-25 06:19:51 +00002238 typedef CodeCompletionResult Result;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002239 SmallVector<Result, 8> AllResults;
Douglas Gregord46cf182010-08-16 20:01:48 +00002240 for (ASTUnit::cached_completion_iterator
Douglas Gregordf239672010-08-16 21:23:13 +00002241 C = AST.cached_completion_begin(),
2242 CEnd = AST.cached_completion_end();
Douglas Gregord46cf182010-08-16 20:01:48 +00002243 C != CEnd; ++C) {
2244 // If the context we are in matches any of the contexts we are
2245 // interested in, we'll add this result.
2246 if ((C->ShowInContexts & InContexts) == 0)
2247 continue;
2248
2249 // If we haven't added any results previously, do so now.
2250 if (!AddedResult) {
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002251 CalculateHiddenNames(Context, Results, NumResults, S.Context,
2252 HiddenNames);
Douglas Gregord46cf182010-08-16 20:01:48 +00002253 AllResults.insert(AllResults.end(), Results, Results + NumResults);
2254 AddedResult = true;
2255 }
2256
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002257 // Determine whether this global completion result is hidden by a local
2258 // completion result. If so, skip it.
2259 if (C->Kind != CXCursor_MacroDefinition &&
2260 HiddenNames.count(C->Completion->getTypedText()))
2261 continue;
2262
Douglas Gregord46cf182010-08-16 20:01:48 +00002263 // Adjust priority based on similar type classes.
2264 unsigned Priority = C->Priority;
Douglas Gregor12785102010-08-24 20:21:13 +00002265 CodeCompletionString *Completion = C->Completion;
Douglas Gregord46cf182010-08-16 20:01:48 +00002266 if (!Context.getPreferredType().isNull()) {
2267 if (C->Kind == CXCursor_MacroDefinition) {
2268 Priority = getMacroUsagePriority(C->Completion->getTypedText(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00002269 S.getLangOpts(),
Douglas Gregor12785102010-08-24 20:21:13 +00002270 Context.getPreferredType()->isAnyPointerType());
Douglas Gregord46cf182010-08-16 20:01:48 +00002271 } else if (C->Type) {
2272 CanQualType Expected
Douglas Gregordf239672010-08-16 21:23:13 +00002273 = S.Context.getCanonicalType(
Douglas Gregord46cf182010-08-16 20:01:48 +00002274 Context.getPreferredType().getUnqualifiedType());
2275 SimplifiedTypeClass ExpectedSTC = getSimplifiedTypeClass(Expected);
2276 if (ExpectedSTC == C->TypeClass) {
2277 // We know this type is similar; check for an exact match.
2278 llvm::StringMap<unsigned> &CachedCompletionTypes
Douglas Gregordf239672010-08-16 21:23:13 +00002279 = AST.getCachedCompletionTypes();
Douglas Gregord46cf182010-08-16 20:01:48 +00002280 llvm::StringMap<unsigned>::iterator Pos
Douglas Gregordf239672010-08-16 21:23:13 +00002281 = CachedCompletionTypes.find(QualType(Expected).getAsString());
Douglas Gregord46cf182010-08-16 20:01:48 +00002282 if (Pos != CachedCompletionTypes.end() && Pos->second == C->Type)
2283 Priority /= CCF_ExactTypeMatch;
2284 else
2285 Priority /= CCF_SimilarTypeMatch;
2286 }
2287 }
2288 }
2289
Douglas Gregor12785102010-08-24 20:21:13 +00002290 // Adjust the completion string, if required.
2291 if (C->Kind == CXCursor_MacroDefinition &&
2292 Context.getKind() == CodeCompletionContext::CCC_MacroNameUse) {
2293 // Create a new code-completion string that just contains the
2294 // macro name, without its arguments.
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00002295 CodeCompletionBuilder Builder(getAllocator(), getCodeCompletionTUInfo(),
2296 CCP_CodePattern, C->Availability);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002297 Builder.AddTypedTextChunk(C->Completion->getTypedText());
Douglas Gregor8850aa32010-08-25 18:03:13 +00002298 Priority = CCP_CodePattern;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002299 Completion = Builder.TakeString();
Douglas Gregor12785102010-08-24 20:21:13 +00002300 }
2301
Argyrios Kyrtzidis5c8b1cd2012-09-27 00:24:09 +00002302 AllResults.push_back(Result(Completion, Priority, C->Kind,
Douglas Gregorf757a122010-08-23 23:00:57 +00002303 C->Availability));
Douglas Gregord46cf182010-08-16 20:01:48 +00002304 }
2305
2306 // If we did not add any cached completion results, just forward the
2307 // results we were given to the next consumer.
2308 if (!AddedResult) {
2309 Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
2310 return;
2311 }
Douglas Gregor49f67ce2010-08-26 13:48:20 +00002312
Douglas Gregord46cf182010-08-16 20:01:48 +00002313 Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
2314 AllResults.size());
2315}
2316
Adrian Prantlbb165fb2015-06-20 18:53:08 +00002317void ASTUnit::CodeComplete(
2318 StringRef File, unsigned Line, unsigned Column,
2319 ArrayRef<RemappedFile> RemappedFiles, bool IncludeMacros,
2320 bool IncludeCodePatterns, bool IncludeBriefComments,
2321 CodeCompleteConsumer &Consumer,
2322 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
2323 DiagnosticsEngine &Diag, LangOptions &LangOpts, SourceManager &SourceMgr,
2324 FileManager &FileMgr, SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
2325 SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers) {
Ted Kremenek5e14d392011-03-21 18:40:17 +00002326 if (!Invocation)
Douglas Gregor8e984da2010-08-04 16:47:14 +00002327 return;
2328
Douglas Gregor16896c42010-10-28 15:44:59 +00002329 SimpleTimer CompletionTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00002330 CompletionTimer.setOutput("Code completion @ " + File + ":" +
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002331 Twine(Line) + ":" + Twine(Column));
Douglas Gregor028d3e42010-08-09 20:45:32 +00002332
Dylan Noblesmithc95d8192012-02-20 14:00:23 +00002333 IntrusiveRefCntPtr<CompilerInvocation>
Ted Kremenek5e14d392011-03-21 18:40:17 +00002334 CCInvocation(new CompilerInvocation(*Invocation));
2335
2336 FrontendOptions &FrontendOpts = CCInvocation->getFrontendOpts();
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002337 CodeCompleteOptions &CodeCompleteOpts = FrontendOpts.CodeCompleteOpts;
Ted Kremenek5e14d392011-03-21 18:40:17 +00002338 PreprocessorOptions &PreprocessorOpts = CCInvocation->getPreprocessorOpts();
Douglas Gregorb68bc592010-08-05 09:09:23 +00002339
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002340 CodeCompleteOpts.IncludeMacros = IncludeMacros &&
2341 CachedCompletionResults.empty();
2342 CodeCompleteOpts.IncludeCodePatterns = IncludeCodePatterns;
2343 CodeCompleteOpts.IncludeGlobals = CachedCompletionResults.empty();
2344 CodeCompleteOpts.IncludeBriefComments = IncludeBriefComments;
2345
2346 assert(IncludeBriefComments == this->IncludeBriefCommentsInCodeCompletion);
2347
Douglas Gregor8e984da2010-08-04 16:47:14 +00002348 FrontendOpts.CodeCompletionAt.FileName = File;
2349 FrontendOpts.CodeCompletionAt.Line = Line;
2350 FrontendOpts.CodeCompletionAt.Column = Column;
2351
2352 // Set the language options appropriately.
Ted Kremenek8cf47df2011-11-17 23:01:24 +00002353 LangOpts = *CCInvocation->getLangOpts();
Douglas Gregor8e984da2010-08-04 16:47:14 +00002354
Argyrios Kyrtzidis06e8d692014-10-31 16:44:32 +00002355 // Spell-checking and warnings are wasteful during code-completion.
2356 LangOpts.SpellChecking = false;
2357 CCInvocation->getDiagnosticOpts().IgnoreWarnings = true;
2358
Adrian Prantlbb165fb2015-06-20 18:53:08 +00002359 std::unique_ptr<CompilerInstance> Clang(
2360 new CompilerInstance(PCHContainerOps));
Ted Kremenek84de4a12011-03-21 18:40:07 +00002361
2362 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00002363 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
2364 CICleanup(Clang.get());
Ted Kremenek84de4a12011-03-21 18:40:07 +00002365
Ted Kremenek5e14d392011-03-21 18:40:17 +00002366 Clang->setInvocation(&*CCInvocation);
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00002367 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
Douglas Gregor8e984da2010-08-04 16:47:14 +00002368
2369 // Set up diagnostics, capturing any diagnostics produced.
Ted Kremenek84de4a12011-03-21 18:40:07 +00002370 Clang->setDiagnostics(&Diag);
Douglas Gregor8e984da2010-08-04 16:47:14 +00002371 CaptureDroppedDiagnostics Capture(true,
Ted Kremenek84de4a12011-03-21 18:40:07 +00002372 Clang->getDiagnostics(),
Douglas Gregor8e984da2010-08-04 16:47:14 +00002373 StoredDiagnostics);
Manuel Klimekbe0474c2013-07-18 14:23:12 +00002374 ProcessWarningOptions(Diag, CCInvocation->getDiagnosticOpts());
Douglas Gregor8e984da2010-08-04 16:47:14 +00002375
2376 // Create the target instance.
Alp Toker80758082014-07-06 05:26:44 +00002377 Clang->setTarget(TargetInfo::CreateTargetInfo(
Saleem Abdulrasool10a49722016-04-08 16:52:00 +00002378 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
Ted Kremenek84de4a12011-03-21 18:40:07 +00002379 if (!Clang->hasTarget()) {
Craig Topper49a27902014-05-22 04:46:25 +00002380 Clang->setInvocation(nullptr);
Douglas Gregor2dd19f12010-08-18 22:29:43 +00002381 return;
Douglas Gregor8e984da2010-08-04 16:47:14 +00002382 }
2383
2384 // Inform the target of the language options.
2385 //
2386 // FIXME: We shouldn't need to do this, the target should be immutable once
2387 // created. This complexity should be lifted elsewhere.
Alp Toker74437972014-07-06 05:14:24 +00002388 Clang->getTarget().adjust(Clang->getLangOpts());
Douglas Gregor8e984da2010-08-04 16:47:14 +00002389
Ted Kremenek84de4a12011-03-21 18:40:07 +00002390 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Douglas Gregor8e984da2010-08-04 16:47:14 +00002391 "Invocation must have exactly one source file!");
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00002392 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
Douglas Gregor8e984da2010-08-04 16:47:14 +00002393 "FIXME: AST inputs not yet supported here!");
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00002394 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
Douglas Gregor8e984da2010-08-04 16:47:14 +00002395 "IR inputs not support here!");
2396
2397
2398 // Use the source and file managers that we were given.
Ted Kremenek84de4a12011-03-21 18:40:07 +00002399 Clang->setFileManager(&FileMgr);
2400 Clang->setSourceManager(&SourceMgr);
Douglas Gregor8e984da2010-08-04 16:47:14 +00002401
2402 // Remap files.
2403 PreprocessorOpts.clearRemappedFiles();
Douglas Gregord8a5dba2010-08-04 17:07:00 +00002404 PreprocessorOpts.RetainRemappedFileBuffers = true;
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00002405 for (const auto &RemappedFile : RemappedFiles) {
2406 PreprocessorOpts.addRemappedFile(RemappedFile.first, RemappedFile.second);
2407 OwnedBuffers.push_back(RemappedFile.second);
Douglas Gregorb97b6662010-08-20 00:59:43 +00002408 }
Dmitri Gribenkoc444b572014-02-08 00:38:15 +00002409
Douglas Gregorb14904c2010-08-13 22:48:40 +00002410 // Use the code completion consumer we were given, but adding any cached
2411 // code-completion results.
Douglas Gregore9186e62010-11-29 16:13:56 +00002412 AugmentedCodeCompleteConsumer *AugmentedConsumer
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002413 = new AugmentedCodeCompleteConsumer(*this, Consumer, CodeCompleteOpts);
Ted Kremenek84de4a12011-03-21 18:40:07 +00002414 Clang->setCodeCompletionConsumer(AugmentedConsumer);
Douglas Gregor8e984da2010-08-04 16:47:14 +00002415
Douglas Gregor028d3e42010-08-09 20:45:32 +00002416 // If we have a precompiled preamble, try to use it. We only allow
2417 // the use of the precompiled preamble if we're if the completion
2418 // point is within the main file, after the end of the precompiled
2419 // preamble.
Rafael Espindola2346a372014-08-18 18:47:08 +00002420 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
Ted Kremenek06b4f912011-10-27 17:55:18 +00002421 if (!getPreambleFile(this).empty()) {
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00002422 std::string CompleteFilePath(File);
Rafael Espindola073ff102013-07-29 21:26:52 +00002423 llvm::sys::fs::UniqueID CompleteFileID;
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00002424
Rafael Espindolabe3b12b02013-06-20 15:12:38 +00002425 if (!llvm::sys::fs::getUniqueID(CompleteFilePath, CompleteFileID)) {
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00002426 std::string MainPath(OriginalSourceFile);
Rafael Espindola073ff102013-07-29 21:26:52 +00002427 llvm::sys::fs::UniqueID MainID;
Rafael Espindolabe3b12b02013-06-20 15:12:38 +00002428 if (!llvm::sys::fs::getUniqueID(MainPath, MainID)) {
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00002429 if (CompleteFileID == MainID && Line > 1)
Rafael Espindola2346a372014-08-18 18:47:08 +00002430 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(
Adrian Prantlbb165fb2015-06-20 18:53:08 +00002431 PCHContainerOps, *CCInvocation, false, Line - 1);
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00002432 }
2433 }
Douglas Gregor028d3e42010-08-09 20:45:32 +00002434 }
2435
2436 // If the main file has been overridden due to the use of a preamble,
2437 // make that override happen and introduce the preamble.
2438 if (OverrideMainBuffer) {
Rafael Espindola2346a372014-08-18 18:47:08 +00002439 PreprocessorOpts.addRemappedFile(OriginalSourceFile,
2440 OverrideMainBuffer.get());
Douglas Gregor028d3e42010-08-09 20:45:32 +00002441 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
2442 PreprocessorOpts.PrecompiledPreambleBytes.second
2443 = PreambleEndsAtStartOfLine;
Ted Kremenek06b4f912011-10-27 17:55:18 +00002444 PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
Douglas Gregor028d3e42010-08-09 20:45:32 +00002445 PreprocessorOpts.DisablePCHValidation = true;
Rafael Espindola2346a372014-08-18 18:47:08 +00002446
2447 OwnedBuffers.push_back(OverrideMainBuffer.release());
Douglas Gregor7b02b582010-08-20 00:02:33 +00002448 } else {
2449 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
2450 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregor028d3e42010-08-09 20:45:32 +00002451 }
2452
Argyrios Kyrtzidis870704f2012-11-02 22:18:44 +00002453 // Disable the preprocessing record if modules are not enabled.
2454 if (!Clang->getLangOpts().Modules)
2455 PreprocessorOpts.DetailedRecord = false;
Ahmed Charlesb8984322014-03-07 20:03:18 +00002456
2457 std::unique_ptr<SyntaxOnlyAction> Act;
Douglas Gregor8e984da2010-08-04 16:47:14 +00002458 Act.reset(new SyntaxOnlyAction);
Douglas Gregor32fbe312012-01-20 16:28:04 +00002459 if (Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
Douglas Gregor8e984da2010-08-04 16:47:14 +00002460 Act->Execute();
2461 Act->EndSourceFile();
2462 }
Douglas Gregor8e984da2010-08-04 16:47:14 +00002463}
Douglas Gregore9386682010-08-13 05:36:37 +00002464
Argyrios Kyrtzidis39a76382012-09-26 16:39:46 +00002465bool ASTUnit::Save(StringRef File) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00002466 if (HadModuleLoaderFatalFailure)
2467 return true;
2468
Argyrios Kyrtzidis55e75572011-07-21 18:44:49 +00002469 // Write to a temporary file and later rename it to the actual file, to avoid
2470 // possible race conditions.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00002471 SmallString<128> TempPath;
Argyrios Kyrtzidis08a2bfd2011-07-28 00:45:10 +00002472 TempPath = File;
2473 TempPath += "-%%%%%%%%";
2474 int fd;
Yaron Keren92e1b622015-03-18 10:17:07 +00002475 if (llvm::sys::fs::createUniqueFile(TempPath, fd, TempPath))
Argyrios Kyrtzidis39a76382012-09-26 16:39:46 +00002476 return true;
Argyrios Kyrtzidis55e75572011-07-21 18:44:49 +00002477
Douglas Gregore9386682010-08-13 05:36:37 +00002478 // FIXME: Can we somehow regenerate the stat cache here, or do we need to
2479 // unconditionally create a stat cache when we parse the file?
Argyrios Kyrtzidis08a2bfd2011-07-28 00:45:10 +00002480 llvm::raw_fd_ostream Out(fd, /*shouldClose=*/true);
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00002481
2482 serialize(Out);
2483 Out.close();
Argyrios Kyrtzidiseeea16a2012-03-13 02:17:06 +00002484 if (Out.has_error()) {
2485 Out.clear_error();
Argyrios Kyrtzidis39a76382012-09-26 16:39:46 +00002486 return true;
Argyrios Kyrtzidiseeea16a2012-03-13 02:17:06 +00002487 }
Argyrios Kyrtzidis55e75572011-07-21 18:44:49 +00002488
Yaron Keren92e1b622015-03-18 10:17:07 +00002489 if (llvm::sys::fs::rename(TempPath, File)) {
2490 llvm::sys::fs::remove(TempPath);
Argyrios Kyrtzidis39a76382012-09-26 16:39:46 +00002491 return true;
Argyrios Kyrtzidis55e75572011-07-21 18:44:49 +00002492 }
2493
Argyrios Kyrtzidis39a76382012-09-26 16:39:46 +00002494 return false;
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00002495}
2496
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00002497static bool serializeUnit(ASTWriter &Writer,
2498 SmallVectorImpl<char> &Buffer,
2499 Sema &S,
2500 bool hasErrors,
2501 raw_ostream &OS) {
Craig Topper49a27902014-05-22 04:46:25 +00002502 Writer.WriteAST(S, std::string(), nullptr, "", hasErrors);
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00002503
2504 // Write the generated bitstream to "Out".
2505 if (!Buffer.empty())
2506 OS.write(Buffer.data(), Buffer.size());
2507
2508 return false;
2509}
2510
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002511bool ASTUnit::serialize(raw_ostream &OS) {
Argyrios Kyrtzidis4a280ff2012-03-07 01:51:17 +00002512 bool hasErrors = getDiagnostics().hasErrorOccurred();
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00002513
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00002514 if (WriterData)
2515 return serializeUnit(WriterData->Writer, WriterData->Buffer,
2516 getSema(), hasErrors, OS);
2517
Daniel Dunbar9a963862012-02-29 20:31:23 +00002518 SmallString<128> Buffer;
Douglas Gregore9386682010-08-13 05:36:37 +00002519 llvm::BitstreamWriter Stream(Buffer);
Douglas Gregor6623e1f2015-11-03 18:33:07 +00002520 ASTWriter Writer(Stream, { });
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00002521 return serializeUnit(Writer, Buffer, getSema(), hasErrors, OS);
Douglas Gregore9386682010-08-13 05:36:37 +00002522}
Douglas Gregor925296b2011-07-19 16:10:42 +00002523
2524typedef ContinuousRangeMap<unsigned, int, 2> SLocRemap;
2525
Douglas Gregor925296b2011-07-19 16:10:42 +00002526void ASTUnit::TranslateStoredDiagnostics(
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002527 FileManager &FileMgr,
Douglas Gregor925296b2011-07-19 16:10:42 +00002528 SourceManager &SrcMgr,
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002529 const SmallVectorImpl<StandaloneDiagnostic> &Diags,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002530 SmallVectorImpl<StoredDiagnostic> &Out) {
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002531 // Map the standalone diagnostic into the new source manager. We also need to
2532 // remap all the locations to the new view. This includes the diag location,
2533 // any associated source ranges, and the source ranges of associated fix-its.
Douglas Gregor925296b2011-07-19 16:10:42 +00002534 // FIXME: There should be a cleaner way to do this.
2535
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002536 SmallVector<StoredDiagnostic, 4> Result;
Douglas Gregor925296b2011-07-19 16:10:42 +00002537 Result.reserve(Diags.size());
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00002538 for (const StandaloneDiagnostic &SD : Diags) {
Douglas Gregor925296b2011-07-19 16:10:42 +00002539 // Rebuild the StoredDiagnostic.
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002540 if (SD.Filename.empty())
2541 continue;
2542 const FileEntry *FE = FileMgr.getFile(SD.Filename);
2543 if (!FE)
2544 continue;
2545 FileID FID = SrcMgr.translateFile(FE);
2546 SourceLocation FileLoc = SrcMgr.getLocForStartOfFile(FID);
2547 if (FileLoc.isInvalid())
2548 continue;
2549 SourceLocation L = FileLoc.getLocWithOffset(SD.LocOffset);
Douglas Gregor925296b2011-07-19 16:10:42 +00002550 FullSourceLoc Loc(L, SrcMgr);
2551
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002552 SmallVector<CharSourceRange, 4> Ranges;
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002553 Ranges.reserve(SD.Ranges.size());
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00002554 for (const auto &Range : SD.Ranges) {
2555 SourceLocation BL = FileLoc.getLocWithOffset(Range.first);
2556 SourceLocation EL = FileLoc.getLocWithOffset(Range.second);
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002557 Ranges.push_back(CharSourceRange::getCharRange(BL, EL));
Douglas Gregor925296b2011-07-19 16:10:42 +00002558 }
2559
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002560 SmallVector<FixItHint, 2> FixIts;
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002561 FixIts.reserve(SD.FixIts.size());
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00002562 for (const StandaloneFixIt &FixIt : SD.FixIts) {
Douglas Gregor925296b2011-07-19 16:10:42 +00002563 FixIts.push_back(FixItHint());
2564 FixItHint &FH = FixIts.back();
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00002565 FH.CodeToInsert = FixIt.CodeToInsert;
2566 SourceLocation BL = FileLoc.getLocWithOffset(FixIt.RemoveRange.first);
2567 SourceLocation EL = FileLoc.getLocWithOffset(FixIt.RemoveRange.second);
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002568 FH.RemoveRange = CharSourceRange::getCharRange(BL, EL);
Douglas Gregor925296b2011-07-19 16:10:42 +00002569 }
2570
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002571 Result.push_back(StoredDiagnostic(SD.Level, SD.ID,
2572 SD.Message, Loc, Ranges, FixIts));
Douglas Gregor925296b2011-07-19 16:10:42 +00002573 }
2574 Result.swap(Out);
2575}
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002576
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00002577void ASTUnit::addFileLevelDecl(Decl *D) {
2578 assert(D);
Douglas Gregor61d63d02011-11-07 18:53:57 +00002579
2580 // We only care about local declarations.
2581 if (D->isFromASTFile())
2582 return;
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00002583
2584 SourceManager &SM = *SourceMgr;
2585 SourceLocation Loc = D->getLocation();
2586 if (Loc.isInvalid() || !SM.isLocalSourceLocation(Loc))
2587 return;
2588
2589 // We only keep track of the file-level declarations of each file.
2590 if (!D->getLexicalDeclContext()->isFileContext())
2591 return;
2592
2593 SourceLocation FileLoc = SM.getFileLoc(Loc);
2594 assert(SM.isLocalSourceLocation(FileLoc));
2595 FileID FID;
2596 unsigned Offset;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002597 std::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc);
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00002598 if (FID.isInvalid())
2599 return;
2600
2601 LocDeclsTy *&Decls = FileDecls[FID];
2602 if (!Decls)
2603 Decls = new LocDeclsTy();
2604
2605 std::pair<unsigned, Decl *> LocDecl(Offset, D);
2606
2607 if (Decls->empty() || Decls->back().first <= Offset) {
2608 Decls->push_back(LocDecl);
2609 return;
2610 }
2611
Benjamin Kramer45025c02013-08-24 13:22:59 +00002612 LocDeclsTy::iterator I = std::upper_bound(Decls->begin(), Decls->end(),
2613 LocDecl, llvm::less_first());
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00002614
2615 Decls->insert(I, LocDecl);
2616}
2617
Argyrios Kyrtzidise9681522011-11-03 02:20:32 +00002618void ASTUnit::findFileRegionDecls(FileID File, unsigned Offset, unsigned Length,
2619 SmallVectorImpl<Decl *> &Decls) {
2620 if (File.isInvalid())
2621 return;
2622
2623 if (SourceMgr->isLoadedFileID(File)) {
2624 assert(Ctx->getExternalSource() && "No external source!");
2625 return Ctx->getExternalSource()->FindFileRegionDecls(File, Offset, Length,
2626 Decls);
2627 }
2628
2629 FileDeclsTy::iterator I = FileDecls.find(File);
2630 if (I == FileDecls.end())
2631 return;
2632
2633 LocDeclsTy &LocDecls = *I->second;
2634 if (LocDecls.empty())
2635 return;
2636
Benjamin Kramere3e855b2013-08-24 13:12:34 +00002637 LocDeclsTy::iterator BeginIt =
2638 std::lower_bound(LocDecls.begin(), LocDecls.end(),
Craig Topper49a27902014-05-22 04:46:25 +00002639 std::make_pair(Offset, (Decl *)nullptr),
2640 llvm::less_first());
Argyrios Kyrtzidise9681522011-11-03 02:20:32 +00002641 if (BeginIt != LocDecls.begin())
2642 --BeginIt;
2643
Argyrios Kyrtzidis8ad3bab2011-11-23 20:27:36 +00002644 // If we are pointing at a top-level decl inside an objc container, we need
2645 // to backtrack until we find it otherwise we will fail to report that the
2646 // region overlaps with an objc container.
2647 while (BeginIt != LocDecls.begin() &&
2648 BeginIt->second->isTopLevelDeclInObjCContainer())
2649 --BeginIt;
2650
Benjamin Kramere3e855b2013-08-24 13:12:34 +00002651 LocDeclsTy::iterator EndIt = std::upper_bound(
2652 LocDecls.begin(), LocDecls.end(),
Craig Topper49a27902014-05-22 04:46:25 +00002653 std::make_pair(Offset + Length, (Decl *)nullptr), llvm::less_first());
Argyrios Kyrtzidise9681522011-11-03 02:20:32 +00002654 if (EndIt != LocDecls.end())
2655 ++EndIt;
2656
2657 for (LocDeclsTy::iterator DIt = BeginIt; DIt != EndIt; ++DIt)
2658 Decls.push_back(DIt->second);
2659}
2660
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002661SourceLocation ASTUnit::getLocation(const FileEntry *File,
2662 unsigned Line, unsigned Col) const {
2663 const SourceManager &SM = getSourceManager();
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00002664 SourceLocation Loc = SM.translateFileLineCol(File, Line, Col);
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002665 return SM.getMacroArgExpandedLocation(Loc);
2666}
2667
2668SourceLocation ASTUnit::getLocation(const FileEntry *File,
2669 unsigned Offset) const {
2670 const SourceManager &SM = getSourceManager();
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00002671 SourceLocation FileLoc = SM.translateFileLineCol(File, 1, 1);
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002672 return SM.getMacroArgExpandedLocation(FileLoc.getLocWithOffset(Offset));
2673}
2674
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00002675/// \brief If \arg Loc is a loaded location from the preamble, returns
2676/// the corresponding local location of the main file, otherwise it returns
2677/// \arg Loc.
2678SourceLocation ASTUnit::mapLocationFromPreamble(SourceLocation Loc) {
2679 FileID PreambleID;
2680 if (SourceMgr)
2681 PreambleID = SourceMgr->getPreambleFileID();
2682
2683 if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2684 return Loc;
2685
2686 unsigned Offs;
2687 if (SourceMgr->isInFileID(Loc, PreambleID, &Offs) && Offs < Preamble.size()) {
2688 SourceLocation FileLoc
2689 = SourceMgr->getLocForStartOfFile(SourceMgr->getMainFileID());
2690 return FileLoc.getLocWithOffset(Offs);
2691 }
2692
2693 return Loc;
2694}
2695
2696/// \brief If \arg Loc is a local location of the main file but inside the
2697/// preamble chunk, returns the corresponding loaded location from the
2698/// preamble, otherwise it returns \arg Loc.
2699SourceLocation ASTUnit::mapLocationToPreamble(SourceLocation Loc) {
2700 FileID PreambleID;
2701 if (SourceMgr)
2702 PreambleID = SourceMgr->getPreambleFileID();
2703
2704 if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2705 return Loc;
2706
2707 unsigned Offs;
2708 if (SourceMgr->isInFileID(Loc, SourceMgr->getMainFileID(), &Offs) &&
2709 Offs < Preamble.size()) {
2710 SourceLocation FileLoc = SourceMgr->getLocForStartOfFile(PreambleID);
2711 return FileLoc.getLocWithOffset(Offs);
2712 }
2713
2714 return Loc;
2715}
2716
Argyrios Kyrtzidis429ec022011-10-25 00:29:50 +00002717bool ASTUnit::isInPreambleFileID(SourceLocation Loc) {
2718 FileID FID;
2719 if (SourceMgr)
2720 FID = SourceMgr->getPreambleFileID();
2721
2722 if (Loc.isInvalid() || FID.isInvalid())
2723 return false;
2724
2725 return SourceMgr->isInFileID(Loc, FID);
2726}
2727
2728bool ASTUnit::isInMainFileID(SourceLocation Loc) {
2729 FileID FID;
2730 if (SourceMgr)
2731 FID = SourceMgr->getMainFileID();
2732
2733 if (Loc.isInvalid() || FID.isInvalid())
2734 return false;
2735
2736 return SourceMgr->isInFileID(Loc, FID);
2737}
2738
2739SourceLocation ASTUnit::getEndOfPreambleFileID() {
2740 FileID FID;
2741 if (SourceMgr)
2742 FID = SourceMgr->getPreambleFileID();
2743
2744 if (FID.isInvalid())
2745 return SourceLocation();
2746
2747 return SourceMgr->getLocForEndOfFile(FID);
2748}
2749
2750SourceLocation ASTUnit::getStartOfMainFileID() {
2751 FileID FID;
2752 if (SourceMgr)
2753 FID = SourceMgr->getMainFileID();
2754
2755 if (FID.isInvalid())
2756 return SourceLocation();
2757
2758 return SourceMgr->getLocForStartOfFile(FID);
2759}
2760
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00002761llvm::iterator_range<PreprocessingRecord::iterator>
Argyrios Kyrtzidisd4fcf5802012-10-02 16:10:51 +00002762ASTUnit::getLocalPreprocessingEntities() const {
2763 if (isMainFileAST()) {
2764 serialization::ModuleFile &
2765 Mod = Reader->getModuleManager().getPrimaryModule();
2766 return Reader->getModulePreprocessedEntities(Mod);
2767 }
2768
2769 if (PreprocessingRecord *PPRec = PP->getPreprocessingRecord())
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00002770 return llvm::make_range(PPRec->local_begin(), PPRec->local_end());
Argyrios Kyrtzidisd4fcf5802012-10-02 16:10:51 +00002771
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00002772 return llvm::make_range(PreprocessingRecord::iterator(),
2773 PreprocessingRecord::iterator());
Argyrios Kyrtzidisd4fcf5802012-10-02 16:10:51 +00002774}
2775
Argyrios Kyrtzidise514b202012-10-03 01:58:28 +00002776bool ASTUnit::visitLocalTopLevelDecls(void *context, DeclVisitorFn Fn) {
Argyrios Kyrtzidis10e78462012-10-02 21:09:13 +00002777 if (isMainFileAST()) {
2778 serialization::ModuleFile &
2779 Mod = Reader->getModuleManager().getPrimaryModule();
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00002780 for (const Decl *D : Reader->getModuleFileLevelDecls(Mod)) {
2781 if (!Fn(context, D))
Argyrios Kyrtzidis10e78462012-10-02 21:09:13 +00002782 return false;
2783 }
2784
2785 return true;
2786 }
2787
2788 for (ASTUnit::top_level_iterator TL = top_level_begin(),
2789 TLEnd = top_level_end();
2790 TL != TLEnd; ++TL) {
2791 if (!Fn(context, *TL))
2792 return false;
2793 }
2794
2795 return true;
2796}
2797
Argyrios Kyrtzidisf484b132012-10-03 21:05:51 +00002798const FileEntry *ASTUnit::getPCHFile() {
2799 if (!Reader)
Craig Topper49a27902014-05-22 04:46:25 +00002800 return nullptr;
Argyrios Kyrtzidisf484b132012-10-03 21:05:51 +00002801
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00002802 serialization::ModuleFile *Mod = nullptr;
2803 Reader->getModuleManager().visit([&Mod](serialization::ModuleFile &M) {
2804 switch (M.Kind) {
2805 case serialization::MK_ImplicitModule:
2806 case serialization::MK_ExplicitModule:
2807 return true; // skip dependencies.
2808 case serialization::MK_PCH:
2809 Mod = &M;
2810 return true; // found it.
2811 case serialization::MK_Preamble:
2812 return false; // look in dependencies.
2813 case serialization::MK_MainFile:
2814 return false; // look in dependencies.
2815 }
2816
2817 return true;
2818 });
2819 if (Mod)
2820 return Mod->File;
Argyrios Kyrtzidisf484b132012-10-03 21:05:51 +00002821
Craig Topper49a27902014-05-22 04:46:25 +00002822 return nullptr;
Argyrios Kyrtzidisf484b132012-10-03 21:05:51 +00002823}
2824
Argyrios Kyrtzidise445c722012-10-10 02:12:47 +00002825bool ASTUnit::isModuleFile() {
Richard Smith7e82e012016-02-19 22:25:36 +00002826 return isMainFileAST() && ASTFileLangOpts.CompilingModule;
Argyrios Kyrtzidise445c722012-10-10 02:12:47 +00002827}
2828
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002829void ASTUnit::PreambleData::countLines() const {
2830 NumLines = 0;
2831 if (empty())
2832 return;
2833
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00002834 NumLines = std::count(Buffer.begin(), Buffer.end(), '\n');
2835
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002836 if (Buffer.back() != '\n')
2837 ++NumLines;
2838}
Argyrios Kyrtzidisebf01362011-10-10 21:57:12 +00002839
2840#ifndef NDEBUG
2841ASTUnit::ConcurrencyState::ConcurrencyState() {
2842 Mutex = new llvm::sys::MutexImpl(/*recursive=*/true);
2843}
2844
2845ASTUnit::ConcurrencyState::~ConcurrencyState() {
2846 delete static_cast<llvm::sys::MutexImpl *>(Mutex);
2847}
2848
2849void ASTUnit::ConcurrencyState::start() {
2850 bool acquired = static_cast<llvm::sys::MutexImpl *>(Mutex)->tryacquire();
2851 assert(acquired && "Concurrent access to ASTUnit!");
2852}
2853
2854void ASTUnit::ConcurrencyState::finish() {
2855 static_cast<llvm::sys::MutexImpl *>(Mutex)->release();
2856}
2857
2858#else // NDEBUG
2859
Hans Wennborgdcfba332015-10-06 23:40:43 +00002860ASTUnit::ConcurrencyState::ConcurrencyState() { Mutex = nullptr; }
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +00002861ASTUnit::ConcurrencyState::~ConcurrencyState() {}
Argyrios Kyrtzidisebf01362011-10-10 21:57:12 +00002862void ASTUnit::ConcurrencyState::start() {}
2863void ASTUnit::ConcurrencyState::finish() {}
2864
Hans Wennborgdcfba332015-10-06 23:40:43 +00002865#endif // NDEBUG