blob: 90161af26cafe57147c14400bf214a25e7f8db2d [file] [log] [blame]
Argyrios Kyrtzidis3a08ec12009-06-20 08:27:14 +00001//===--- ASTUnit.cpp - ASTUnit utility ------------------------------------===//
2//
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>
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000050using namespace clang;
51
Douglas Gregor16896c42010-10-28 15:44:59 +000052using llvm::TimeRecord;
53
54namespace {
55 class SimpleTimer {
56 bool WantTiming;
57 TimeRecord Start;
58 std::string Output;
59
Benjamin Kramerf2e5a912010-11-09 20:00:56 +000060 public:
Douglas Gregor1cbdd952010-11-01 13:48:43 +000061 explicit SimpleTimer(bool WantTiming) : WantTiming(WantTiming) {
Douglas Gregor16896c42010-10-28 15:44:59 +000062 if (WantTiming)
Benjamin Kramerf2e5a912010-11-09 20:00:56 +000063 Start = TimeRecord::getCurrentTime();
Douglas Gregor16896c42010-10-28 15:44:59 +000064 }
65
Chris Lattner0e62c1c2011-07-23 10:55:15 +000066 void setOutput(const Twine &Output) {
Douglas Gregor16896c42010-10-28 15:44:59 +000067 if (WantTiming)
Benjamin Kramerf2e5a912010-11-09 20:00:56 +000068 this->Output = Output.str();
Douglas Gregor16896c42010-10-28 15:44:59 +000069 }
70
Douglas Gregor16896c42010-10-28 15:44:59 +000071 ~SimpleTimer() {
72 if (WantTiming) {
73 TimeRecord Elapsed = TimeRecord::getCurrentTime();
74 Elapsed -= Start;
75 llvm::errs() << Output << ':';
76 Elapsed.print(Elapsed, llvm::errs());
77 llvm::errs() << '\n';
78 }
79 }
80 };
Ted Kremenek06b4f912011-10-27 17:55:18 +000081
82 struct OnDiskData {
83 /// \brief The file in which the precompiled preamble is stored.
84 std::string PreambleFile;
85
Rafael Espindolabc7d9492013-06-26 03:52:38 +000086 /// \brief Temporary files that should be removed when the ASTUnit is
Ted Kremenek06b4f912011-10-27 17:55:18 +000087 /// destroyed.
Rafael Espindolabc7d9492013-06-26 03:52:38 +000088 SmallVector<std::string, 4> TemporaryFiles;
89
Ted Kremenek06b4f912011-10-27 17:55:18 +000090 /// \brief Erase temporary files.
91 void CleanTemporaryFiles();
92
93 /// \brief Erase the preamble file.
94 void CleanPreambleFile();
95
96 /// \brief Erase temporary files and the preamble file.
97 void Cleanup();
98 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +000099}
Ted Kremenek06b4f912011-10-27 17:55:18 +0000100
Ted Kremenekbd307a52011-10-27 19:44:25 +0000101static llvm::sys::SmartMutex<false> &getOnDiskMutex() {
102 static llvm::sys::SmartMutex<false> M(/* recursive = */ true);
103 return M;
104}
105
Dmitri Gribenkob2aa9232012-11-15 14:28:07 +0000106static void cleanupOnDiskMapAtExit();
Ted Kremenek06b4f912011-10-27 17:55:18 +0000107
Dylan Noblesmithcdd31512014-08-24 18:59:52 +0000108typedef llvm::DenseMap<const ASTUnit *,
109 std::unique_ptr<OnDiskData>> OnDiskDataMap;
Ted Kremenek06b4f912011-10-27 17:55:18 +0000110static OnDiskDataMap &getOnDiskDataMap() {
111 static OnDiskDataMap M;
112 static bool hasRegisteredAtExit = false;
113 if (!hasRegisteredAtExit) {
114 hasRegisteredAtExit = true;
115 atexit(cleanupOnDiskMapAtExit);
116 }
117 return M;
118}
119
Dmitri Gribenkob2aa9232012-11-15 14:28:07 +0000120static void cleanupOnDiskMapAtExit() {
Argyrios Kyrtzidis4cf2ffe2012-07-03 16:30:52 +0000121 // Use the mutex because there can be an alive thread destroying an ASTUnit.
122 llvm::MutexGuard Guard(getOnDiskMutex());
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000123 for (const auto &I : getOnDiskDataMap()) {
Ted Kremenek06b4f912011-10-27 17:55:18 +0000124 // We don't worry about freeing the memory associated with OnDiskDataMap.
125 // All we care about is erasing stale files.
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000126 I.second->Cleanup();
Ted Kremenek06b4f912011-10-27 17:55:18 +0000127 }
128}
129
130static OnDiskData &getOnDiskData(const ASTUnit *AU) {
Ted Kremenekbd307a52011-10-27 19:44:25 +0000131 // We require the mutex since we are modifying the structure of the
132 // DenseMap.
133 llvm::MutexGuard Guard(getOnDiskMutex());
Ted Kremenek06b4f912011-10-27 17:55:18 +0000134 OnDiskDataMap &M = getOnDiskDataMap();
Dylan Noblesmithcdd31512014-08-24 18:59:52 +0000135 auto &D = M[AU];
Ted Kremenek06b4f912011-10-27 17:55:18 +0000136 if (!D)
Dylan Noblesmithcdd31512014-08-24 18:59:52 +0000137 D = llvm::make_unique<OnDiskData>();
Ted Kremenek06b4f912011-10-27 17:55:18 +0000138 return *D;
139}
140
141static void erasePreambleFile(const ASTUnit *AU) {
142 getOnDiskData(AU).CleanPreambleFile();
143}
144
145static void removeOnDiskEntry(const ASTUnit *AU) {
Ted Kremenekbd307a52011-10-27 19:44:25 +0000146 // We require the mutex since we are modifying the structure of the
147 // DenseMap.
148 llvm::MutexGuard Guard(getOnDiskMutex());
Ted Kremenek06b4f912011-10-27 17:55:18 +0000149 OnDiskDataMap &M = getOnDiskDataMap();
150 OnDiskDataMap::iterator I = M.find(AU);
151 if (I != M.end()) {
152 I->second->Cleanup();
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000153 M.erase(I);
Ted Kremenek06b4f912011-10-27 17:55:18 +0000154 }
155}
156
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000157static void setPreambleFile(const ASTUnit *AU, StringRef preambleFile) {
Ted Kremenek06b4f912011-10-27 17:55:18 +0000158 getOnDiskData(AU).PreambleFile = preambleFile;
159}
160
161static const std::string &getPreambleFile(const ASTUnit *AU) {
162 return getOnDiskData(AU).PreambleFile;
163}
164
165void OnDiskData::CleanTemporaryFiles() {
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000166 for (StringRef File : TemporaryFiles)
167 llvm::sys::fs::remove(File);
Rafael Espindolabc7d9492013-06-26 03:52:38 +0000168 TemporaryFiles.clear();
Ted Kremenek06b4f912011-10-27 17:55:18 +0000169}
170
171void OnDiskData::CleanPreambleFile() {
172 if (!PreambleFile.empty()) {
Rafael Espindolabc4aa552013-06-26 04:02:37 +0000173 llvm::sys::fs::remove(PreambleFile);
Ted Kremenek06b4f912011-10-27 17:55:18 +0000174 PreambleFile.clear();
175 }
176}
177
178void OnDiskData::Cleanup() {
179 CleanTemporaryFiles();
180 CleanPreambleFile();
181}
182
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000183struct ASTUnit::ASTWriterData {
184 SmallString<128> Buffer;
185 llvm::BitstreamWriter Stream;
186 ASTWriter Writer;
187
188 ASTWriterData() : Stream(Buffer), Writer(Stream) { }
189};
190
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000191void ASTUnit::clearFileLevelDecls() {
Reid Kleckner588c9372014-02-19 23:44:52 +0000192 llvm::DeleteContainerSeconds(FileDecls);
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000193}
194
Ted Kremenek06b4f912011-10-27 17:55:18 +0000195void ASTUnit::CleanTemporaryFiles() {
196 getOnDiskData(this).CleanTemporaryFiles();
197}
198
Rafael Espindolabc7d9492013-06-26 03:52:38 +0000199void ASTUnit::addTemporaryFile(StringRef TempFile) {
Ted Kremenek06b4f912011-10-27 17:55:18 +0000200 getOnDiskData(this).TemporaryFiles.push_back(TempFile);
Douglas Gregor16896c42010-10-28 15:44:59 +0000201}
202
Douglas Gregorbb420ab2010-08-04 05:53:38 +0000203/// \brief After failing to build a precompiled preamble (due to
204/// errors in the source that occurs in the preamble), the number of
205/// reparses during which we'll skip even trying to precompile the
206/// preamble.
207const unsigned DefaultPreambleRebuildInterval = 5;
208
Douglas Gregor68dbaea2010-11-17 00:13:31 +0000209/// \brief Tracks the number of ASTUnit objects that are currently active.
210///
211/// Used for debugging purposes only.
Benjamin Kramer4527fb22014-03-02 17:08:31 +0000212static std::atomic<unsigned> ActiveASTUnitObjects;
Douglas Gregor68dbaea2010-11-17 00:13:31 +0000213
Douglas Gregord03e8232010-04-05 21:10:19 +0000214ASTUnit::ASTUnit(bool _MainFileIsAST)
Craig Topper49a27902014-05-22 04:46:25 +0000215 : Reader(nullptr), HadModuleLoaderFatalFailure(false),
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +0000216 OnlyLocalDecls(false), CaptureDiagnostics(false),
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +0000217 MainFileIsAST(_MainFileIsAST),
Douglas Gregor69f74f82011-08-25 22:30:56 +0000218 TUKind(TU_Complete), WantTiming(getenv("LIBCLANG_TIMING")),
Argyrios Kyrtzidis4954bc12011-03-05 01:03:48 +0000219 OwnsRemappedFileBuffers(true),
Douglas Gregor16896c42010-10-28 15:44:59 +0000220 NumStoredDiagnosticsFromDriver(0),
Rafael Espindola4674a872014-08-13 17:08:22 +0000221 PreambleRebuildCounter(0),
Rafael Espindolafa49c0b2014-08-13 16:47:00 +0000222 NumWarningsInPreamble(0),
Douglas Gregor2c8bd472010-08-17 00:40:40 +0000223 ShouldCacheCodeCompletionResults(false),
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +0000224 IncludeBriefCommentsInCodeCompletion(false), UserFilesAreVolatile(false),
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000225 CompletionCacheTopLevelHashValue(0),
226 PreambleTopLevelHashValue(0),
227 CurrentTopLevelHashValue(0),
Douglas Gregor4740c452010-08-19 00:45:44 +0000228 UnsafeToFree(false) {
Benjamin Kramer4527fb22014-03-02 17:08:31 +0000229 if (getenv("LIBCLANG_OBJTRACKING"))
230 fprintf(stderr, "+++ %u translation units\n", ++ActiveASTUnitObjects);
Douglas Gregor15ba0b32010-07-30 20:58:08 +0000231}
Douglas Gregord03e8232010-04-05 21:10:19 +0000232
Daniel Dunbar764c0822009-12-01 09:51:01 +0000233ASTUnit::~ASTUnit() {
Douglas Gregor6b930962013-05-03 22:58:43 +0000234 // If we loaded from an AST file, balance out the BeginSourceFile call.
235 if (MainFileIsAST && getDiagnostics().getClient()) {
236 getDiagnostics().getClient()->EndSourceFile();
237 }
238
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000239 clearFileLevelDecls();
240
Ted Kremenek06b4f912011-10-27 17:55:18 +0000241 // Clean up the temporary files and the preamble file.
242 removeOnDiskEntry(this);
243
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000244 // Free the buffers associated with remapped files. We are required to
245 // perform this operation here because we explicitly request that the
246 // compiler instance *not* free these buffers for each invocation of the
247 // parser.
Alp Tokerf994cef2014-07-05 03:08:06 +0000248 if (Invocation.get() && OwnsRemappedFileBuffers) {
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000249 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
Alp Toker1b070d22014-07-07 07:47:20 +0000250 for (const auto &RB : PPOpts.RemappedFileBuffers)
251 delete RB.second;
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000252 }
Douglas Gregora0734c52010-08-19 01:33:06 +0000253
Douglas Gregor16896c42010-10-28 15:44:59 +0000254 ClearCachedCompletionResults();
Douglas Gregor68dbaea2010-11-17 00:13:31 +0000255
Benjamin Kramer4527fb22014-03-02 17:08:31 +0000256 if (getenv("LIBCLANG_OBJTRACKING"))
257 fprintf(stderr, "--- %u translation units\n", --ActiveASTUnitObjects);
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000258}
259
Argyrios Kyrtzidisda6e0542012-01-17 18:48:07 +0000260void ASTUnit::setPreprocessor(Preprocessor *pp) { PP = pp; }
261
Douglas Gregor39982192010-08-15 06:18:01 +0000262/// \brief Determine the set of code-completion contexts in which this
263/// declaration should be shown.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000264static unsigned getDeclShowContexts(const NamedDecl *ND,
Douglas Gregor59cab552010-08-16 23:05:20 +0000265 const LangOptions &LangOpts,
266 bool &IsNestedNameSpecifier) {
267 IsNestedNameSpecifier = false;
268
Douglas Gregor39982192010-08-15 06:18:01 +0000269 if (isa<UsingShadowDecl>(ND))
270 ND = dyn_cast<NamedDecl>(ND->getUnderlyingDecl());
271 if (!ND)
272 return 0;
273
Richard Smith697cc9e2012-08-14 03:13:00 +0000274 uint64_t Contexts = 0;
Douglas Gregor39982192010-08-15 06:18:01 +0000275 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND) ||
276 isa<ClassTemplateDecl>(ND) || isa<TemplateTemplateParmDecl>(ND)) {
277 // Types can appear in these contexts.
278 if (LangOpts.CPlusPlus || !isa<TagDecl>(ND))
Richard Smith697cc9e2012-08-14 03:13:00 +0000279 Contexts |= (1LL << CodeCompletionContext::CCC_TopLevel)
280 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
281 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
282 | (1LL << CodeCompletionContext::CCC_Statement)
283 | (1LL << CodeCompletionContext::CCC_Type)
284 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression);
Douglas Gregor39982192010-08-15 06:18:01 +0000285
286 // In C++, types can appear in expressions contexts (for functional casts).
287 if (LangOpts.CPlusPlus)
Richard Smith697cc9e2012-08-14 03:13:00 +0000288 Contexts |= (1LL << CodeCompletionContext::CCC_Expression);
Douglas Gregor39982192010-08-15 06:18:01 +0000289
290 // In Objective-C, message sends can send interfaces. In Objective-C++,
291 // all types are available due to functional casts.
292 if (LangOpts.CPlusPlus || isa<ObjCInterfaceDecl>(ND))
Richard Smith697cc9e2012-08-14 03:13:00 +0000293 Contexts |= (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver);
Douglas Gregor21325842011-07-07 16:03:39 +0000294
295 // In Objective-C, you can only be a subclass of another Objective-C class
296 if (isa<ObjCInterfaceDecl>(ND))
Richard Smith697cc9e2012-08-14 03:13:00 +0000297 Contexts |= (1LL << CodeCompletionContext::CCC_ObjCInterfaceName);
Douglas Gregor39982192010-08-15 06:18:01 +0000298
299 // Deal with tag names.
300 if (isa<EnumDecl>(ND)) {
Richard Smith697cc9e2012-08-14 03:13:00 +0000301 Contexts |= (1LL << CodeCompletionContext::CCC_EnumTag);
Douglas Gregor39982192010-08-15 06:18:01 +0000302
Douglas Gregor59cab552010-08-16 23:05:20 +0000303 // Part of the nested-name-specifier in C++0x.
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000304 if (LangOpts.CPlusPlus11)
Douglas Gregor59cab552010-08-16 23:05:20 +0000305 IsNestedNameSpecifier = true;
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000306 } else if (const RecordDecl *Record = dyn_cast<RecordDecl>(ND)) {
Douglas Gregor39982192010-08-15 06:18:01 +0000307 if (Record->isUnion())
Richard Smith697cc9e2012-08-14 03:13:00 +0000308 Contexts |= (1LL << CodeCompletionContext::CCC_UnionTag);
Douglas Gregor39982192010-08-15 06:18:01 +0000309 else
Richard Smith697cc9e2012-08-14 03:13:00 +0000310 Contexts |= (1LL << CodeCompletionContext::CCC_ClassOrStructTag);
Douglas Gregor39982192010-08-15 06:18:01 +0000311
Douglas Gregor39982192010-08-15 06:18:01 +0000312 if (LangOpts.CPlusPlus)
Douglas Gregor59cab552010-08-16 23:05:20 +0000313 IsNestedNameSpecifier = true;
Douglas Gregor0ac41382010-09-23 23:01:17 +0000314 } else if (isa<ClassTemplateDecl>(ND))
Douglas Gregor59cab552010-08-16 23:05:20 +0000315 IsNestedNameSpecifier = true;
Douglas Gregor39982192010-08-15 06:18:01 +0000316 } else if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
317 // Values can appear in these contexts.
Richard Smith697cc9e2012-08-14 03:13:00 +0000318 Contexts = (1LL << CodeCompletionContext::CCC_Statement)
319 | (1LL << CodeCompletionContext::CCC_Expression)
320 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
321 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver);
Douglas Gregor39982192010-08-15 06:18:01 +0000322 } else if (isa<ObjCProtocolDecl>(ND)) {
Richard Smith697cc9e2012-08-14 03:13:00 +0000323 Contexts = (1LL << CodeCompletionContext::CCC_ObjCProtocolName);
Douglas Gregor21325842011-07-07 16:03:39 +0000324 } else if (isa<ObjCCategoryDecl>(ND)) {
Richard Smith697cc9e2012-08-14 03:13:00 +0000325 Contexts = (1LL << CodeCompletionContext::CCC_ObjCCategoryName);
Douglas Gregor39982192010-08-15 06:18:01 +0000326 } else if (isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) {
Richard Smith697cc9e2012-08-14 03:13:00 +0000327 Contexts = (1LL << CodeCompletionContext::CCC_Namespace);
Douglas Gregor39982192010-08-15 06:18:01 +0000328
329 // Part of the nested-name-specifier.
Douglas Gregor59cab552010-08-16 23:05:20 +0000330 IsNestedNameSpecifier = true;
Douglas Gregor39982192010-08-15 06:18:01 +0000331 }
332
333 return Contexts;
334}
335
Douglas Gregorb14904c2010-08-13 22:48:40 +0000336void ASTUnit::CacheCodeCompletionResults() {
337 if (!TheSema)
338 return;
339
Douglas Gregor16896c42010-10-28 15:44:59 +0000340 SimpleTimer Timer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +0000341 Timer.setOutput("Cache global code completions for " + getMainFileName());
Douglas Gregorb14904c2010-08-13 22:48:40 +0000342
343 // Clear out the previous results.
344 ClearCachedCompletionResults();
345
346 // Gather the set of global code completions.
John McCall276321a2010-08-25 06:19:51 +0000347 typedef CodeCompletionResult Result;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000348 SmallVector<Result, 8> Results;
Douglas Gregor162b7122011-02-16 19:08:06 +0000349 CachedCompletionAllocator = new GlobalCodeCompletionAllocator;
Argyrios Kyrtzidis2bafa002012-11-16 03:34:57 +0000350 CodeCompletionTUInfo CCTUInfo(CachedCompletionAllocator);
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +0000351 TheSema->GatherGlobalCodeCompletions(*CachedCompletionAllocator,
Argyrios Kyrtzidis2bafa002012-11-16 03:34:57 +0000352 CCTUInfo, Results);
Douglas Gregorb14904c2010-08-13 22:48:40 +0000353
354 // Translate global code completions into cached completions.
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000355 llvm::DenseMap<CanQualType, unsigned> CompletionTypes;
Douglas Gregorc3425b12015-07-07 06:20:19 +0000356 CodeCompletionContext CCContext(CodeCompletionContext::CCC_TopLevel);
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000357
358 for (Result &R : Results) {
359 switch (R.Kind) {
Douglas Gregor39982192010-08-15 06:18:01 +0000360 case Result::RK_Declaration: {
Douglas Gregor59cab552010-08-16 23:05:20 +0000361 bool IsNestedNameSpecifier = false;
Douglas Gregor39982192010-08-15 06:18:01 +0000362 CachedCodeCompletionResult CachedResult;
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000363 CachedResult.Completion = R.CreateCodeCompletionString(
Douglas Gregorc3425b12015-07-07 06:20:19 +0000364 *TheSema, CCContext, *CachedCompletionAllocator, CCTUInfo,
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000365 IncludeBriefCommentsInCodeCompletion);
366 CachedResult.ShowInContexts = getDeclShowContexts(
367 R.Declaration, Ctx->getLangOpts(), IsNestedNameSpecifier);
368 CachedResult.Priority = R.Priority;
369 CachedResult.Kind = R.CursorKind;
370 CachedResult.Availability = R.Availability;
Douglas Gregor24747402010-08-16 16:46:30 +0000371
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000372 // Keep track of the type of this completion in an ASTContext-agnostic
373 // way.
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000374 QualType UsageType = getDeclUsageType(*Ctx, R.Declaration);
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000375 if (UsageType.isNull()) {
Douglas Gregor24747402010-08-16 16:46:30 +0000376 CachedResult.TypeClass = STC_Void;
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000377 CachedResult.Type = 0;
378 } else {
379 CanQualType CanUsageType
380 = Ctx->getCanonicalType(UsageType.getUnqualifiedType());
381 CachedResult.TypeClass = getSimplifiedTypeClass(CanUsageType);
382
383 // Determine whether we have already seen this type. If so, we save
384 // ourselves the work of formatting the type string by using the
385 // temporary, CanQualType-based hash table to find the associated value.
386 unsigned &TypeValue = CompletionTypes[CanUsageType];
387 if (TypeValue == 0) {
388 TypeValue = CompletionTypes.size();
389 CachedCompletionTypes[QualType(CanUsageType).getAsString()]
390 = TypeValue;
391 }
392
393 CachedResult.Type = TypeValue;
Douglas Gregor24747402010-08-16 16:46:30 +0000394 }
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000395
Douglas Gregor39982192010-08-15 06:18:01 +0000396 CachedCompletionResults.push_back(CachedResult);
Douglas Gregor59cab552010-08-16 23:05:20 +0000397
398 /// Handle nested-name-specifiers in C++.
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000399 if (TheSema->Context.getLangOpts().CPlusPlus && IsNestedNameSpecifier &&
400 !R.StartsNestedNameSpecifier) {
Douglas Gregor59cab552010-08-16 23:05:20 +0000401 // The contexts in which a nested-name-specifier can appear in C++.
Richard Smith697cc9e2012-08-14 03:13:00 +0000402 uint64_t NNSContexts
403 = (1LL << CodeCompletionContext::CCC_TopLevel)
404 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
405 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
406 | (1LL << CodeCompletionContext::CCC_Statement)
407 | (1LL << CodeCompletionContext::CCC_Expression)
408 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
409 | (1LL << CodeCompletionContext::CCC_EnumTag)
410 | (1LL << CodeCompletionContext::CCC_UnionTag)
411 | (1LL << CodeCompletionContext::CCC_ClassOrStructTag)
412 | (1LL << CodeCompletionContext::CCC_Type)
413 | (1LL << CodeCompletionContext::CCC_PotentiallyQualifiedName)
414 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression);
Douglas Gregor59cab552010-08-16 23:05:20 +0000415
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000416 if (isa<NamespaceDecl>(R.Declaration) ||
417 isa<NamespaceAliasDecl>(R.Declaration))
Richard Smith697cc9e2012-08-14 03:13:00 +0000418 NNSContexts |= (1LL << CodeCompletionContext::CCC_Namespace);
Douglas Gregor59cab552010-08-16 23:05:20 +0000419
420 if (unsigned RemainingContexts
421 = NNSContexts & ~CachedResult.ShowInContexts) {
422 // If there any contexts where this completion can be a
423 // nested-name-specifier but isn't already an option, create a
424 // nested-name-specifier completion.
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000425 R.StartsNestedNameSpecifier = true;
426 CachedResult.Completion = R.CreateCodeCompletionString(
Douglas Gregorc3425b12015-07-07 06:20:19 +0000427 *TheSema, CCContext, *CachedCompletionAllocator, CCTUInfo,
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000428 IncludeBriefCommentsInCodeCompletion);
Douglas Gregor59cab552010-08-16 23:05:20 +0000429 CachedResult.ShowInContexts = RemainingContexts;
430 CachedResult.Priority = CCP_NestedNameSpecifier;
431 CachedResult.TypeClass = STC_Void;
432 CachedResult.Type = 0;
433 CachedCompletionResults.push_back(CachedResult);
434 }
435 }
Douglas Gregorb14904c2010-08-13 22:48:40 +0000436 break;
Douglas Gregor39982192010-08-15 06:18:01 +0000437 }
438
Douglas Gregorb14904c2010-08-13 22:48:40 +0000439 case Result::RK_Keyword:
440 case Result::RK_Pattern:
441 // Ignore keywords and patterns; we don't care, since they are so
442 // easily regenerated.
443 break;
444
445 case Result::RK_Macro: {
446 CachedCodeCompletionResult CachedResult;
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000447 CachedResult.Completion = R.CreateCodeCompletionString(
Douglas Gregorc3425b12015-07-07 06:20:19 +0000448 *TheSema, CCContext, *CachedCompletionAllocator, CCTUInfo,
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000449 IncludeBriefCommentsInCodeCompletion);
Douglas Gregorb14904c2010-08-13 22:48:40 +0000450 CachedResult.ShowInContexts
Richard Smith697cc9e2012-08-14 03:13:00 +0000451 = (1LL << CodeCompletionContext::CCC_TopLevel)
452 | (1LL << CodeCompletionContext::CCC_ObjCInterface)
453 | (1LL << CodeCompletionContext::CCC_ObjCImplementation)
454 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
455 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
456 | (1LL << CodeCompletionContext::CCC_Statement)
457 | (1LL << CodeCompletionContext::CCC_Expression)
458 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
459 | (1LL << CodeCompletionContext::CCC_MacroNameUse)
460 | (1LL << CodeCompletionContext::CCC_PreprocessorExpression)
461 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
462 | (1LL << CodeCompletionContext::CCC_OtherWithMacros);
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000463
464 CachedResult.Priority = R.Priority;
465 CachedResult.Kind = R.CursorKind;
466 CachedResult.Availability = R.Availability;
Douglas Gregor6e240332010-08-16 16:18:59 +0000467 CachedResult.TypeClass = STC_Void;
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000468 CachedResult.Type = 0;
Douglas Gregorb14904c2010-08-13 22:48:40 +0000469 CachedCompletionResults.push_back(CachedResult);
470 break;
471 }
472 }
Douglas Gregorb14904c2010-08-13 22:48:40 +0000473 }
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000474
475 // Save the current top-level hash value.
476 CompletionCacheTopLevelHashValue = CurrentTopLevelHashValue;
Douglas Gregorb14904c2010-08-13 22:48:40 +0000477}
478
479void ASTUnit::ClearCachedCompletionResults() {
Douglas Gregorb14904c2010-08-13 22:48:40 +0000480 CachedCompletionResults.clear();
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000481 CachedCompletionTypes.clear();
Craig Topper49a27902014-05-22 04:46:25 +0000482 CachedCompletionAllocator = nullptr;
Douglas Gregorb14904c2010-08-13 22:48:40 +0000483}
484
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000485namespace {
486
Sebastian Redl2c499f62010-08-18 23:56:43 +0000487/// \brief Gathers information from ASTReader that will be used to initialize
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000488/// a Preprocessor.
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000489class ASTInfoCollector : public ASTReaderListener {
Douglas Gregor83297df2011-09-01 23:39:15 +0000490 Preprocessor &PP;
Douglas Gregore8bbc122011-09-02 00:18:52 +0000491 ASTContext &Context;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000492 LangOptions &LangOpt;
Alp Toker80758082014-07-06 05:26:44 +0000493 std::shared_ptr<TargetOptions> &TargetOpts;
Dylan Noblesmithc95d8192012-02-20 14:00:23 +0000494 IntrusiveRefCntPtr<TargetInfo> &Target;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000495 unsigned &Counter;
Mike Stump11289f42009-09-09 15:08:12 +0000496
Douglas Gregore8bbc122011-09-02 00:18:52 +0000497 bool InitializedLanguage;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000498public:
Alp Toker80758082014-07-06 05:26:44 +0000499 ASTInfoCollector(Preprocessor &PP, ASTContext &Context, LangOptions &LangOpt,
500 std::shared_ptr<TargetOptions> &TargetOpts,
501 IntrusiveRefCntPtr<TargetInfo> &Target, unsigned &Counter)
502 : PP(PP), Context(Context), LangOpt(LangOpt), TargetOpts(TargetOpts),
503 Target(Target), Counter(Counter), InitializedLanguage(false) {}
Mike Stump11289f42009-09-09 15:08:12 +0000504
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000505 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
506 bool AllowCompatibleDifferences) override {
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000507 if (InitializedLanguage)
Douglas Gregor83297df2011-09-01 23:39:15 +0000508 return false;
509
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000510 LangOpt = LangOpts;
511 InitializedLanguage = true;
512
513 updated();
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000514 return false;
515 }
Mike Stump11289f42009-09-09 15:08:12 +0000516
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000517 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
518 bool AllowCompatibleDifferences) override {
Douglas Gregor83297df2011-09-01 23:39:15 +0000519 // If we've already initialized the target, don't do it again.
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000520 if (Target)
Douglas Gregor83297df2011-09-01 23:39:15 +0000521 return false;
Alp Toker80758082014-07-06 05:26:44 +0000522
523 this->TargetOpts = std::make_shared<TargetOptions>(TargetOpts);
524 Target =
525 TargetInfo::CreateTargetInfo(PP.getDiagnostics(), this->TargetOpts);
Argyrios Kyrtzidis9e1fb562012-09-14 20:24:53 +0000526
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000527 updated();
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000528 return false;
529 }
Mike Stump11289f42009-09-09 15:08:12 +0000530
Craig Topperafa7cb32014-03-13 06:07:04 +0000531 void ReadCounter(const serialization::ModuleFile &M,
532 unsigned Value) override {
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000533 Counter = Value;
534 }
Argyrios Kyrtzidis9e1fb562012-09-14 20:24:53 +0000535
536private:
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000537 void updated() {
538 if (!Target || !InitializedLanguage)
539 return;
540
541 // Inform the target of the language options.
542 //
543 // FIXME: We shouldn't need to do this, the target should be immutable once
544 // created. This complexity should be lifted elsewhere.
Alp Toker74437972014-07-06 05:14:24 +0000545 Target->adjust(LangOpt);
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000546
547 // Initialize the preprocessor.
548 PP.Initialize(*Target);
549
550 // Initialize the ASTContext
551 Context.InitBuiltinTypes(*Target);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +0000552
553 // We didn't have access to the comment options when the ASTContext was
554 // constructed, so register them now.
555 Context.getCommentCommandTraits().registerCommentOptions(
556 LangOpt.CommentOpts);
Argyrios Kyrtzidis9e1fb562012-09-14 20:24:53 +0000557 }
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000558};
559
Douglas Gregor6b930962013-05-03 22:58:43 +0000560 /// \brief Diagnostic consumer that saves each diagnostic it is given.
David Blaikief18d91a2011-09-26 00:01:39 +0000561class StoredDiagnosticConsumer : public DiagnosticConsumer {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000562 SmallVectorImpl<StoredDiagnostic> &StoredDiags;
Douglas Gregor6b930962013-05-03 22:58:43 +0000563 SourceManager *SourceMgr;
564
Douglas Gregor33cdd812010-02-18 18:08:43 +0000565public:
David Blaikief18d91a2011-09-26 00:01:39 +0000566 explicit StoredDiagnosticConsumer(
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000567 SmallVectorImpl<StoredDiagnostic> &StoredDiags)
Craig Topper49a27902014-05-22 04:46:25 +0000568 : StoredDiags(StoredDiags), SourceMgr(nullptr) {}
Douglas Gregor6b930962013-05-03 22:58:43 +0000569
Craig Topperafa7cb32014-03-13 06:07:04 +0000570 void BeginSourceFile(const LangOptions &LangOpts,
Craig Topper49a27902014-05-22 04:46:25 +0000571 const Preprocessor *PP = nullptr) override {
Douglas Gregor6b930962013-05-03 22:58:43 +0000572 if (PP)
573 SourceMgr = &PP->getSourceManager();
574 }
575
Craig Topperafa7cb32014-03-13 06:07:04 +0000576 void HandleDiagnostic(DiagnosticsEngine::Level Level,
577 const Diagnostic &Info) override;
Douglas Gregor33cdd812010-02-18 18:08:43 +0000578};
579
580/// \brief RAII object that optionally captures diagnostics, if
581/// there is no diagnostic client to capture them already.
582class CaptureDroppedDiagnostics {
David Blaikie9c902b52011-09-25 23:23:43 +0000583 DiagnosticsEngine &Diags;
David Blaikief18d91a2011-09-26 00:01:39 +0000584 StoredDiagnosticConsumer Client;
David Blaikiee2eefae2011-09-25 23:39:51 +0000585 DiagnosticConsumer *PreviousClient;
Alexander Kornienko41c247a2014-11-17 23:46:02 +0000586 std::unique_ptr<DiagnosticConsumer> OwningPreviousClient;
Douglas Gregor33cdd812010-02-18 18:08:43 +0000587
588public:
David Blaikie9c902b52011-09-25 23:23:43 +0000589 CaptureDroppedDiagnostics(bool RequestCapture, DiagnosticsEngine &Diags,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000590 SmallVectorImpl<StoredDiagnostic> &StoredDiags)
Craig Topper49a27902014-05-22 04:46:25 +0000591 : Diags(Diags), Client(StoredDiags), PreviousClient(nullptr)
Douglas Gregor33cdd812010-02-18 18:08:43 +0000592 {
Craig Topper49a27902014-05-22 04:46:25 +0000593 if (RequestCapture || Diags.getClient() == nullptr) {
Alexander Kornienko41c247a2014-11-17 23:46:02 +0000594 OwningPreviousClient = Diags.takeClient();
595 PreviousClient = Diags.getClient();
596 Diags.setClient(&Client, false);
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000597 }
Douglas Gregor33cdd812010-02-18 18:08:43 +0000598 }
599
600 ~CaptureDroppedDiagnostics() {
Alexander Kornienko41c247a2014-11-17 23:46:02 +0000601 if (Diags.getClient() == &Client)
602 Diags.setClient(PreviousClient, !!OwningPreviousClient.release());
Douglas Gregor33cdd812010-02-18 18:08:43 +0000603 }
604};
605
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000606} // anonymous namespace
607
David Blaikief18d91a2011-09-26 00:01:39 +0000608void StoredDiagnosticConsumer::HandleDiagnostic(DiagnosticsEngine::Level Level,
David Blaikieb5784322011-09-26 01:18:08 +0000609 const Diagnostic &Info) {
Argyrios Kyrtzidisc79346a2010-11-18 20:06:46 +0000610 // Default implementation (Warnings/errors count).
David Blaikiee2eefae2011-09-25 23:39:51 +0000611 DiagnosticConsumer::HandleDiagnostic(Level, Info);
Argyrios Kyrtzidisc79346a2010-11-18 20:06:46 +0000612
Douglas Gregor6b930962013-05-03 22:58:43 +0000613 // Only record the diagnostic if it's part of the source manager we know
614 // about. This effectively drops diagnostics from modules we're building.
615 // FIXME: In the long run, ee don't want to drop source managers from modules.
616 if (!Info.hasSourceManager() || &Info.getSourceManager() == SourceMgr)
Benjamin Kramer3204b152015-05-29 19:42:19 +0000617 StoredDiags.emplace_back(Level, Info);
Douglas Gregor33cdd812010-02-18 18:08:43 +0000618}
619
Argyrios Kyrtzidis1c7455f2013-05-10 01:28:51 +0000620ASTMutationListener *ASTUnit::getASTMutationListener() {
621 if (WriterData)
622 return &WriterData->Writer;
Craig Topper49a27902014-05-22 04:46:25 +0000623 return nullptr;
Argyrios Kyrtzidis1c7455f2013-05-10 01:28:51 +0000624}
625
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000626ASTDeserializationListener *ASTUnit::getDeserializationListener() {
627 if (WriterData)
628 return &WriterData->Writer;
Craig Topper49a27902014-05-22 04:46:25 +0000629 return nullptr;
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000630}
631
Rafael Espindola16e1ba12014-08-26 20:17:44 +0000632std::unique_ptr<llvm::MemoryBuffer>
633ASTUnit::getBufferForFile(StringRef Filename, std::string *ErrorStr) {
Chris Lattner5159f612010-11-23 08:35:12 +0000634 assert(FileMgr);
Benjamin Kramera8857962014-10-26 22:44:13 +0000635 auto Buffer = FileMgr->getBufferForFile(Filename);
636 if (Buffer)
637 return std::move(*Buffer);
638 if (ErrorStr)
639 *ErrorStr = Buffer.getError().message();
640 return nullptr;
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000641}
642
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000643/// \brief Configure the diagnostics object for use with ASTUnit.
Justin Bognerd512c1e2014-10-15 00:33:06 +0000644void ASTUnit::ConfigureDiags(IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000645 ASTUnit &AST, bool CaptureDiagnostics) {
Justin Bognerd512c1e2014-10-15 00:33:06 +0000646 assert(Diags.get() && "no DiagnosticsEngine was provided");
647 if (CaptureDiagnostics)
David Blaikief18d91a2011-09-26 00:01:39 +0000648 Diags->setClient(new StoredDiagnosticConsumer(AST.StoredDiagnostics));
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000649}
650
David Blaikie6f7382d2014-08-10 19:08:04 +0000651std::unique_ptr<ASTUnit> ASTUnit::LoadFromASTFile(
Adrian Prantl6b21ab22015-08-27 19:46:20 +0000652 const std::string &Filename, const PCHContainerReader &PCHContainerRdr,
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000653 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Adrian Prantl6b21ab22015-08-27 19:46:20 +0000654 const FileSystemOptions &FileSystemOpts, bool UseDebugInfo,
655 bool OnlyLocalDecls, ArrayRef<RemappedFile> RemappedFiles,
656 bool CaptureDiagnostics, bool AllowPCHWithCompilerErrors,
657 bool UserFilesAreVolatile) {
Ahmed Charlesb8984322014-03-07 20:03:18 +0000658 std::unique_ptr<ASTUnit> AST(new ASTUnit(true));
Ted Kremenek4422bfe2011-03-18 02:06:56 +0000659
660 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +0000661 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
662 ASTUnitCleanup(AST.get());
David Blaikie9c902b52011-09-25 23:23:43 +0000663 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
664 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Alp Tokerf994cef2014-07-05 03:08:06 +0000665 DiagCleanup(Diags.get());
Ted Kremenek4422bfe2011-03-18 02:06:56 +0000666
Justin Bognerdbbcb112014-10-14 23:36:06 +0000667 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000668
Douglas Gregor16bef852009-10-16 20:01:17 +0000669 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000670 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor7f95d262010-04-05 23:52:57 +0000671 AST->Diagnostics = Diags;
Ben Langmuir8832c062014-04-15 18:16:25 +0000672 IntrusiveRefCntPtr<vfs::FileSystem> VFS = vfs::getRealFileSystem();
673 AST->FileMgr = new FileManager(FileSystemOpts, VFS);
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +0000674 AST->UserFilesAreVolatile = UserFilesAreVolatile;
Ted Kremenek5e14d392011-03-21 18:40:17 +0000675 AST->SourceMgr = new SourceManager(AST->getDiagnostics(),
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +0000676 AST->getFileManager(),
677 UserFilesAreVolatile);
Douglas Gregorb85b9cc2012-10-24 16:19:39 +0000678 AST->HSOpts = new HeaderSearchOptions();
Adrian Prantlfb2398d2015-07-17 01:19:54 +0000679 AST->HSOpts->ModuleFormat = PCHContainerRdr.getFormat();
Douglas Gregorb85b9cc2012-10-24 16:19:39 +0000680 AST->HeaderInfo.reset(new HeaderSearch(AST->HSOpts,
Manuel Klimek1f76c4e2013-10-24 07:51:24 +0000681 AST->getSourceManager(),
Douglas Gregor1fb5c3a2011-12-31 04:05:44 +0000682 AST->getDiagnostics(),
Douglas Gregor89929282012-01-30 06:01:29 +0000683 AST->ASTFileLangOpts,
Craig Topper49a27902014-05-22 04:46:25 +0000684 /*Target=*/nullptr));
Dmitri Gribenkoc444b572014-02-08 00:38:15 +0000685
Dmitri Gribenkob41e7e22014-02-10 12:31:34 +0000686 PreprocessorOptions *PPOpts = new PreprocessorOptions();
Dmitri Gribenkoc444b572014-02-08 00:38:15 +0000687
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000688 for (const auto &RemappedFile : RemappedFiles)
689 PPOpts->addRemappedFile(RemappedFile.first, RemappedFile.second);
Dmitri Gribenkoc444b572014-02-08 00:38:15 +0000690
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000691 // Gather Info for preprocessor construction later on.
Mike Stump11289f42009-09-09 15:08:12 +0000692
David Blaikie6f7382d2014-08-10 19:08:04 +0000693 HeaderSearch &HeaderInfo = *AST->HeaderInfo;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000694 unsigned Counter;
695
Alp Toker96637802014-05-02 03:43:38 +0000696 AST->PP =
697 new Preprocessor(PPOpts, AST->getDiagnostics(), AST->ASTFileLangOpts,
698 AST->getSourceManager(), HeaderInfo, *AST,
Craig Topper49a27902014-05-22 04:46:25 +0000699 /*IILookup=*/nullptr,
Alp Toker96637802014-05-02 03:43:38 +0000700 /*OwnsHeaderSearch=*/false);
Douglas Gregore8bbc122011-09-02 00:18:52 +0000701 Preprocessor &PP = *AST->PP;
702
Alp Toker08043432014-05-03 03:46:04 +0000703 AST->Ctx = new ASTContext(AST->ASTFileLangOpts, AST->getSourceManager(),
704 PP.getIdentifierTable(), PP.getSelectorTable(),
705 PP.getBuiltinInfo());
Douglas Gregore8bbc122011-09-02 00:18:52 +0000706 ASTContext &Context = *AST->Ctx;
Douglas Gregor83297df2011-09-01 23:39:15 +0000707
Argyrios Kyrtzidis945a8192012-09-15 01:10:20 +0000708 bool disableValid = false;
709 if (::getenv("LIBCLANG_DISABLE_PCH_VALIDATION"))
710 disableValid = true;
Adrian Prantlfb2398d2015-07-17 01:19:54 +0000711 AST->Reader = new ASTReader(PP, Context, PCHContainerRdr,
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000712 /*isysroot=*/"",
713 /*DisableValidation=*/disableValid,
714 AllowPCHWithCompilerErrors);
Ted Kremenek2159b8d2011-05-04 23:27:12 +0000715
David Blaikie2721c322014-08-10 16:54:39 +0000716 AST->Reader->setListener(llvm::make_unique<ASTInfoCollector>(
717 *AST->PP, Context, AST->ASTFileLangOpts, AST->TargetOpts, AST->Target,
718 Counter));
Daniel Dunbar2d9c7402009-09-03 05:59:35 +0000719
Argyrios Kyrtzidisf0b4cd12015-03-03 08:04:19 +0000720 // Attach the AST reader to the AST context as an external AST
721 // source, so that declarations will be deserialized from the
722 // AST file as needed.
723 // We need the external source to be set up before we read the AST, because
724 // eagerly-deserialized declarations may use it.
725 Context.setExternalSource(AST->Reader);
726
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000727 switch (AST->Reader->ReadAST(Filename, serialization::MK_MainFile,
Argyrios Kyrtzidis2ec29362012-11-15 18:57:22 +0000728 SourceLocation(), ASTReader::ARR_None)) {
Sebastian Redl2c499f62010-08-18 23:56:43 +0000729 case ASTReader::Success:
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000730 break;
Mike Stump11289f42009-09-09 15:08:12 +0000731
Sebastian Redl2c499f62010-08-18 23:56:43 +0000732 case ASTReader::Failure:
Douglas Gregor7029ce12013-03-19 00:28:20 +0000733 case ASTReader::Missing:
Douglas Gregorc9ad5fb2012-10-22 22:50:17 +0000734 case ASTReader::OutOfDate:
735 case ASTReader::VersionMismatch:
736 case ASTReader::ConfigurationMismatch:
737 case ASTReader::HadErrors:
Douglas Gregord03e8232010-04-05 21:10:19 +0000738 AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
Craig Topper49a27902014-05-22 04:46:25 +0000739 return nullptr;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000740 }
Mike Stump11289f42009-09-09 15:08:12 +0000741
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000742 AST->OriginalSourceFile = AST->Reader->getOriginalSourceFile();
Daniel Dunbara8a50932009-12-02 08:44:16 +0000743
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000744 PP.setCounterValue(Counter);
Mike Stump11289f42009-09-09 15:08:12 +0000745
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000746 // Create an AST consumer, even though it isn't used.
747 AST->Consumer.reset(new ASTConsumer);
748
Sebastian Redl2c499f62010-08-18 23:56:43 +0000749 // Create a semantic analysis object and tell the AST reader about it.
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000750 AST->TheSema.reset(new Sema(PP, Context, *AST->Consumer));
751 AST->TheSema->Initialize();
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000752 AST->Reader->InitializeSema(*AST->TheSema);
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000753
Douglas Gregor6b930962013-05-03 22:58:43 +0000754 // Tell the diagnostic client that we have started a source file.
755 AST->getDiagnostics().getClient()->BeginSourceFile(Context.getLangOpts(),&PP);
756
David Blaikie6f7382d2014-08-10 19:08:04 +0000757 return AST;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000758}
Daniel Dunbar764c0822009-12-01 09:51:01 +0000759
760namespace {
761
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000762/// \brief Preprocessor callback class that updates a hash value with the names
763/// of all macros that have been defined by the translation unit.
764class MacroDefinitionTrackerPPCallbacks : public PPCallbacks {
765 unsigned &Hash;
766
767public:
768 explicit MacroDefinitionTrackerPPCallbacks(unsigned &Hash) : Hash(Hash) { }
Craig Topperafa7cb32014-03-13 06:07:04 +0000769
770 void MacroDefined(const Token &MacroNameTok,
771 const MacroDirective *MD) override {
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000772 Hash = llvm::HashString(MacroNameTok.getIdentifierInfo()->getName(), Hash);
773 }
774};
775
776/// \brief Add the given declaration to the hash of all top-level entities.
777void AddTopLevelDeclarationToHash(Decl *D, unsigned &Hash) {
778 if (!D)
779 return;
780
781 DeclContext *DC = D->getDeclContext();
782 if (!DC)
783 return;
784
785 if (!(DC->isTranslationUnit() || DC->getLookupParent()->isTranslationUnit()))
786 return;
787
788 if (NamedDecl *ND = dyn_cast<NamedDecl>(D)) {
Argyrios Kyrtzidisca5c7be2013-10-15 17:37:55 +0000789 if (EnumDecl *EnumD = dyn_cast<EnumDecl>(D)) {
790 // For an unscoped enum include the enumerators in the hash since they
791 // enter the top-level namespace.
792 if (!EnumD->isScoped()) {
Aaron Ballman23a6dcb2014-03-08 18:45:14 +0000793 for (const auto *EI : EnumD->enumerators()) {
794 if (EI->getIdentifier())
795 Hash = llvm::HashString(EI->getIdentifier()->getName(), Hash);
Argyrios Kyrtzidisca5c7be2013-10-15 17:37:55 +0000796 }
797 }
798 }
799
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000800 if (ND->getIdentifier())
801 Hash = llvm::HashString(ND->getIdentifier()->getName(), Hash);
802 else if (DeclarationName Name = ND->getDeclName()) {
803 std::string NameStr = Name.getAsString();
804 Hash = llvm::HashString(NameStr, Hash);
805 }
806 return;
Argyrios Kyrtzidis48d88de2013-06-24 21:19:12 +0000807 }
808
809 if (ImportDecl *ImportD = dyn_cast<ImportDecl>(D)) {
810 if (Module *Mod = ImportD->getImportedModule()) {
811 std::string ModName = Mod->getFullModuleName();
812 Hash = llvm::HashString(ModName, Hash);
813 }
814 return;
815 }
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000816}
817
Daniel Dunbar644dca02009-12-04 08:17:33 +0000818class TopLevelDeclTrackerConsumer : public ASTConsumer {
819 ASTUnit &Unit;
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000820 unsigned &Hash;
821
Daniel Dunbar644dca02009-12-04 08:17:33 +0000822public:
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000823 TopLevelDeclTrackerConsumer(ASTUnit &_Unit, unsigned &Hash)
824 : Unit(_Unit), Hash(Hash) {
825 Hash = 0;
826 }
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000827
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000828 void handleTopLevelDecl(Decl *D) {
Argyrios Kyrtzidis516eec22011-11-16 02:35:10 +0000829 if (!D)
830 return;
831
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000832 // FIXME: Currently ObjC method declarations are incorrectly being
833 // reported as top-level declarations, even though their DeclContext
834 // is the containing ObjC @interface/@implementation. This is a
835 // fundamental problem in the parser right now.
836 if (isa<ObjCMethodDecl>(D))
837 return;
838
839 AddTopLevelDeclarationToHash(D, Hash);
840 Unit.addTopLevelDecl(D);
841
842 handleFileLevelDecl(D);
843 }
844
845 void handleFileLevelDecl(Decl *D) {
846 Unit.addFileLevelDecl(D);
847 if (NamespaceDecl *NSD = dyn_cast<NamespaceDecl>(D)) {
Aaron Ballman629afae2014-03-07 19:56:05 +0000848 for (auto *I : NSD->decls())
849 handleFileLevelDecl(I);
Ted Kremenekacc59c32010-05-03 20:16:35 +0000850 }
Daniel Dunbar644dca02009-12-04 08:17:33 +0000851 }
Sebastian Redleaa4ade2010-08-11 18:52:41 +0000852
Craig Topperafa7cb32014-03-13 06:07:04 +0000853 bool HandleTopLevelDecl(DeclGroupRef D) override {
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000854 for (Decl *TopLevelDecl : D)
855 handleTopLevelDecl(TopLevelDecl);
Argyrios Kyrtzidis841dd882011-11-18 00:26:59 +0000856 return true;
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000857 }
858
Sebastian Redleaa4ade2010-08-11 18:52:41 +0000859 // We're not interested in "interesting" decls.
Craig Topperafa7cb32014-03-13 06:07:04 +0000860 void HandleInterestingDecl(DeclGroupRef) override {}
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000861
Craig Topperafa7cb32014-03-13 06:07:04 +0000862 void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) override {
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000863 for (Decl *TopLevelDecl : D)
864 handleTopLevelDecl(TopLevelDecl);
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000865 }
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000866
Craig Topperafa7cb32014-03-13 06:07:04 +0000867 ASTMutationListener *GetASTMutationListener() override {
Argyrios Kyrtzidis1c7455f2013-05-10 01:28:51 +0000868 return Unit.getASTMutationListener();
869 }
870
Craig Topperafa7cb32014-03-13 06:07:04 +0000871 ASTDeserializationListener *GetASTDeserializationListener() override {
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000872 return Unit.getDeserializationListener();
873 }
Daniel Dunbar644dca02009-12-04 08:17:33 +0000874};
875
876class TopLevelDeclTrackerAction : public ASTFrontendAction {
877public:
878 ASTUnit &Unit;
879
David Blaikie6beb6aa2014-08-10 19:56:51 +0000880 std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
881 StringRef InFile) override {
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000882 CI.getPreprocessor().addPPCallbacks(
Craig Topperb8a70532014-09-10 04:53:53 +0000883 llvm::make_unique<MacroDefinitionTrackerPPCallbacks>(
884 Unit.getCurrentTopLevelHashValue()));
David Blaikie6beb6aa2014-08-10 19:56:51 +0000885 return llvm::make_unique<TopLevelDeclTrackerConsumer>(
886 Unit, Unit.getCurrentTopLevelHashValue());
Daniel Dunbar764c0822009-12-01 09:51:01 +0000887 }
888
889public:
Daniel Dunbar644dca02009-12-04 08:17:33 +0000890 TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {}
891
Craig Topperafa7cb32014-03-13 06:07:04 +0000892 bool hasCodeCompletionSupport() const override { return false; }
893 TranslationUnitKind getTranslationUnitKind() override {
Douglas Gregor69f74f82011-08-25 22:30:56 +0000894 return Unit.getTranslationUnitKind();
Douglas Gregor028d3e42010-08-09 20:45:32 +0000895 }
Daniel Dunbar764c0822009-12-01 09:51:01 +0000896};
897
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000898class PrecompilePreambleAction : public ASTFrontendAction {
899 ASTUnit &Unit;
900 bool HasEmittedPreamblePCH;
901
902public:
903 explicit PrecompilePreambleAction(ASTUnit &Unit)
904 : Unit(Unit), HasEmittedPreamblePCH(false) {}
905
David Blaikie6beb6aa2014-08-10 19:56:51 +0000906 std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
907 StringRef InFile) override;
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000908 bool hasEmittedPreamblePCH() const { return HasEmittedPreamblePCH; }
909 void setHasEmittedPreamblePCH() { HasEmittedPreamblePCH = true; }
Craig Topperafa7cb32014-03-13 06:07:04 +0000910 bool shouldEraseOutputFiles() override { return !hasEmittedPreamblePCH(); }
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000911
Craig Topperafa7cb32014-03-13 06:07:04 +0000912 bool hasCodeCompletionSupport() const override { return false; }
913 bool hasASTFileSupport() const override { return false; }
914 TranslationUnitKind getTranslationUnitKind() override { return TU_Prefix; }
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000915};
916
Argyrios Kyrtzidis57332712011-09-19 20:40:48 +0000917class PrecompilePreambleConsumer : public PCHGenerator {
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000918 ASTUnit &Unit;
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000919 unsigned &Hash;
Douglas Gregore9db88f2010-08-03 19:06:41 +0000920 std::vector<Decl *> TopLevelDecls;
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000921 PrecompilePreambleAction *Action;
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000922 raw_ostream *Out;
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000923
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000924public:
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000925 PrecompilePreambleConsumer(ASTUnit &Unit, PrecompilePreambleAction *Action,
926 const Preprocessor &PP, StringRef isysroot,
927 raw_ostream *Out)
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000928 : PCHGenerator(PP, "", nullptr, isysroot, std::make_shared<PCHBuffer>(),
929 /*AllowASTWithErrors=*/true),
930 Unit(Unit), Hash(Unit.getCurrentTopLevelHashValue()), Action(Action),
931 Out(Out) {
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000932 Hash = 0;
933 }
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000934
Benjamin Kramera401b9b2015-02-06 18:58:04 +0000935 bool HandleTopLevelDecl(DeclGroupRef DG) override {
936 for (Decl *D : DG) {
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000937 // FIXME: Currently ObjC method declarations are incorrectly being
938 // reported as top-level declarations, even though their DeclContext
939 // is the containing ObjC @interface/@implementation. This is a
940 // fundamental problem in the parser right now.
941 if (isa<ObjCMethodDecl>(D))
942 continue;
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000943 AddTopLevelDeclarationToHash(D, Hash);
Douglas Gregore9db88f2010-08-03 19:06:41 +0000944 TopLevelDecls.push_back(D);
945 }
Argyrios Kyrtzidis841dd882011-11-18 00:26:59 +0000946 return true;
Douglas Gregore9db88f2010-08-03 19:06:41 +0000947 }
948
Craig Topperafa7cb32014-03-13 06:07:04 +0000949 void HandleTranslationUnit(ASTContext &Ctx) override {
Douglas Gregore9db88f2010-08-03 19:06:41 +0000950 PCHGenerator::HandleTranslationUnit(Ctx);
Argyrios Kyrtzidisf0168de2013-06-11 00:36:55 +0000951 if (hasEmittedPCH()) {
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000952 // Write the generated bitstream to "Out".
953 *Out << getPCH();
954 // Make sure it hits disk now.
955 Out->flush();
956 // Free the buffer.
957 llvm::SmallVector<char, 0> Empty;
958 getPCH() = std::move(Empty);
959
Douglas Gregore9db88f2010-08-03 19:06:41 +0000960 // Translate the top-level declarations we captured during
961 // parsing into declaration IDs in the precompiled
962 // preamble. This will allow us to deserialize those top-level
963 // declarations when requested.
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000964 for (Decl *D : TopLevelDecls) {
Argyrios Kyrtzidisacfbbd72013-08-07 21:17:33 +0000965 // Invalid top-level decls may not have been serialized.
966 if (D->isInvalidDecl())
967 continue;
968 Unit.addTopLevelDeclFromPreamble(getWriter().getDeclID(D));
969 }
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000970
971 Action->setHasEmittedPreamblePCH();
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000972 }
973 }
974};
975
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000976}
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000977
David Blaikie6beb6aa2014-08-10 19:56:51 +0000978std::unique_ptr<ASTConsumer>
979PrecompilePreambleAction::CreateASTConsumer(CompilerInstance &CI,
980 StringRef InFile) {
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000981 std::string Sysroot;
982 std::string OutputFile;
Rafael Espindola47de1492015-04-10 12:54:53 +0000983 raw_ostream *OS = GeneratePCHAction::ComputeASTConsumerArguments(
984 CI, InFile, Sysroot, OutputFile);
985 if (!OS)
Craig Topper49a27902014-05-22 04:46:25 +0000986 return nullptr;
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000987
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000988 if (!CI.getFrontendOpts().RelocatablePCH)
989 Sysroot.clear();
Douglas Gregorc567ba22011-07-22 16:35:34 +0000990
Craig Topperb8a70532014-09-10 04:53:53 +0000991 CI.getPreprocessor().addPPCallbacks(
992 llvm::make_unique<MacroDefinitionTrackerPPCallbacks>(
993 Unit.getCurrentTopLevelHashValue()));
David Blaikie6beb6aa2014-08-10 19:56:51 +0000994 return llvm::make_unique<PrecompilePreambleConsumer>(
995 Unit, this, CI.getPreprocessor(), Sysroot, OS);
Daniel Dunbar764c0822009-12-01 09:51:01 +0000996}
997
Benjamin Kramer1ce5d802013-05-05 12:39:28 +0000998static bool isNonDriverDiag(const StoredDiagnostic &StoredDiag) {
999 return StoredDiag.getLocation().isValid();
1000}
1001
1002static void
1003checkAndRemoveNonDriverDiags(SmallVectorImpl<StoredDiagnostic> &StoredDiags) {
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +00001004 // Get rid of stored diagnostics except the ones from the driver which do not
1005 // have a source location.
Benjamin Kramer1ce5d802013-05-05 12:39:28 +00001006 StoredDiags.erase(
1007 std::remove_if(StoredDiags.begin(), StoredDiags.end(), isNonDriverDiag),
1008 StoredDiags.end());
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +00001009}
1010
1011static void checkAndSanitizeDiags(SmallVectorImpl<StoredDiagnostic> &
1012 StoredDiagnostics,
1013 SourceManager &SM) {
1014 // The stored diagnostic has the old source manager in it; update
1015 // the locations to refer into the new source manager. Since we've
1016 // been careful to make sure that the source manager's state
1017 // before and after are identical, so that we can reuse the source
1018 // location itself.
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00001019 for (StoredDiagnostic &SD : StoredDiagnostics) {
1020 if (SD.getLocation().isValid()) {
1021 FullSourceLoc Loc(SD.getLocation(), SM);
1022 SD.setLocation(Loc);
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +00001023 }
1024 }
1025}
1026
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001027/// Parse the source file into a translation unit using the given compiler
1028/// invocation, replacing the current translation unit.
1029///
1030/// \returns True if a failure occurred that causes the ASTUnit not to
1031/// contain any translation-unit information, false otherwise.
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001032bool ASTUnit::Parse(std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1033 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer) {
Rafael Espindola4674a872014-08-13 17:08:22 +00001034 SavedMainFileBuffer.reset();
Craig Topper49a27902014-05-22 04:46:25 +00001035
Rafael Espindola32482082014-08-18 16:23:45 +00001036 if (!Invocation)
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001037 return true;
Rafael Espindola32482082014-08-18 16:23:45 +00001038
Daniel Dunbar764c0822009-12-01 09:51:01 +00001039 // Create the compiler instance to use for building the AST.
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001040 std::unique_ptr<CompilerInstance> Clang(
1041 new CompilerInstance(PCHContainerOps));
Ted Kremenek84de4a12011-03-21 18:40:07 +00001042
1043 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00001044 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1045 CICleanup(Clang.get());
Ted Kremenek84de4a12011-03-21 18:40:07 +00001046
Dylan Noblesmithc95d8192012-02-20 14:00:23 +00001047 IntrusiveRefCntPtr<CompilerInvocation>
Argyrios Kyrtzidis14c32e82011-09-12 18:09:38 +00001048 CCInvocation(new CompilerInvocation(*Invocation));
1049
Alp Tokerf994cef2014-07-05 03:08:06 +00001050 Clang->setInvocation(CCInvocation.get());
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001051 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001052
Douglas Gregor8e984da2010-08-04 16:47:14 +00001053 // Set up diagnostics, capturing any diagnostics that would
1054 // otherwise be dropped.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001055 Clang->setDiagnostics(&getDiagnostics());
Douglas Gregord03e8232010-04-05 21:10:19 +00001056
Daniel Dunbar764c0822009-12-01 09:51:01 +00001057 // Create the target instance.
Alp Toker80758082014-07-06 05:26:44 +00001058 Clang->setTarget(TargetInfo::CreateTargetInfo(
1059 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
Rafael Espindola32482082014-08-18 16:23:45 +00001060 if (!Clang->hasTarget())
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001061 return true;
Douglas Gregora0734c52010-08-19 01:33:06 +00001062
Daniel Dunbar764c0822009-12-01 09:51:01 +00001063 // Inform the target of the language options.
1064 //
1065 // FIXME: We shouldn't need to do this, the target should be immutable once
1066 // created. This complexity should be lifted elsewhere.
Alp Toker74437972014-07-06 05:14:24 +00001067 Clang->getTarget().adjust(Clang->getLangOpts());
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001068
Ted Kremenek84de4a12011-03-21 18:40:07 +00001069 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Daniel Dunbar764c0822009-12-01 09:51:01 +00001070 "Invocation must have exactly one source file!");
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001071 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
Daniel Dunbar764c0822009-12-01 09:51:01 +00001072 "FIXME: AST inputs not yet supported here!");
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001073 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
Daniel Dunbar9507f9c2010-06-07 23:26:47 +00001074 "IR inputs not support here!");
Daniel Dunbar764c0822009-12-01 09:51:01 +00001075
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001076 // Configure the various subsystems.
Alp Toker269d8402014-07-06 05:26:07 +00001077 LangOpts = Clang->getInvocation().LangOpts;
Ted Kremenek84de4a12011-03-21 18:40:07 +00001078 FileSystemOpts = Clang->getFileSystemOpts();
Ben Langmuir2cc485b2014-06-23 16:36:40 +00001079 IntrusiveRefCntPtr<vfs::FileSystem> VFS =
1080 createVFSFromCompilerInvocation(Clang->getInvocation(), getDiagnostics());
Rafael Espindola32482082014-08-18 16:23:45 +00001081 if (!VFS)
Ben Langmuir2cc485b2014-06-23 16:36:40 +00001082 return true;
Ben Langmuir2cc485b2014-06-23 16:36:40 +00001083 FileMgr = new FileManager(FileSystemOpts, VFS);
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +00001084 SourceMgr = new SourceManager(getDiagnostics(), *FileMgr,
1085 UserFilesAreVolatile);
Douglas Gregor6fd55e02010-08-13 03:15:25 +00001086 TheSema.reset();
Craig Topper49a27902014-05-22 04:46:25 +00001087 Ctx = nullptr;
1088 PP = nullptr;
1089 Reader = nullptr;
1090
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001091 // Clear out old caches and data.
1092 TopLevelDecls.clear();
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00001093 clearFileLevelDecls();
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001094 CleanTemporaryFiles();
Douglas Gregord9a30af2010-08-02 20:51:39 +00001095
Douglas Gregor7b02b582010-08-20 00:02:33 +00001096 if (!OverrideMainBuffer) {
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +00001097 checkAndRemoveNonDriverDiags(StoredDiagnostics);
Douglas Gregor7b02b582010-08-20 00:02:33 +00001098 TopLevelDeclsInPreamble.clear();
1099 }
1100
Daniel Dunbar764c0822009-12-01 09:51:01 +00001101 // Create a file manager object to provide access to and cache the filesystem.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001102 Clang->setFileManager(&getFileManager());
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001103
Daniel Dunbar764c0822009-12-01 09:51:01 +00001104 // Create the source manager.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001105 Clang->setSourceManager(&getSourceManager());
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001106
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001107 // If the main file has been overridden due to the use of a preamble,
1108 // make that override happen and introduce the preamble.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001109 PreprocessorOptions &PreprocessorOpts = Clang->getPreprocessorOpts();
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001110 if (OverrideMainBuffer) {
Rafael Espindola32482082014-08-18 16:23:45 +00001111 PreprocessorOpts.addRemappedFile(OriginalSourceFile,
1112 OverrideMainBuffer.get());
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001113 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
1114 PreprocessorOpts.PrecompiledPreambleBytes.second
1115 = PreambleEndsAtStartOfLine;
Ted Kremenek06b4f912011-10-27 17:55:18 +00001116 PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
Douglas Gregorce3a8292010-07-27 00:27:13 +00001117 PreprocessorOpts.DisablePCHValidation = true;
Douglas Gregor96c04262010-07-27 14:52:07 +00001118
Douglas Gregord9a30af2010-08-02 20:51:39 +00001119 // The stored diagnostic has the old source manager in it; update
1120 // the locations to refer into the new source manager. Since we've
1121 // been careful to make sure that the source manager's state
1122 // before and after are identical, so that we can reuse the source
1123 // location itself.
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +00001124 checkAndSanitizeDiags(StoredDiagnostics, getSourceManager());
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001125
1126 // Keep track of the override buffer;
Rafael Espindola32482082014-08-18 16:23:45 +00001127 SavedMainFileBuffer = std::move(OverrideMainBuffer);
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001128 }
Ahmed Charlesb8984322014-03-07 20:03:18 +00001129
1130 std::unique_ptr<TopLevelDeclTrackerAction> Act(
1131 new TopLevelDeclTrackerAction(*this));
1132
Ted Kremenek022a4902011-03-22 01:15:24 +00001133 // Recover resources if we crash before exiting this method.
1134 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1135 ActCleanup(Act.get());
1136
Douglas Gregor32fbe312012-01-20 16:28:04 +00001137 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0]))
Daniel Dunbar764c0822009-12-01 09:51:01 +00001138 goto error;
Douglas Gregor925296b2011-07-19 16:10:42 +00001139
Rafael Espindola32482082014-08-18 16:23:45 +00001140 if (SavedMainFileBuffer) {
Ted Kremenek06b4f912011-10-27 17:55:18 +00001141 std::string ModName = getPreambleFile(this);
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001142 TranslateStoredDiagnostics(getFileManager(), getSourceManager(),
1143 PreambleDiagnostics, StoredDiagnostics);
Douglas Gregor925296b2011-07-19 16:10:42 +00001144 }
1145
Argyrios Kyrtzidis1416e172012-06-08 05:48:06 +00001146 if (!Act->Execute())
1147 goto error;
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001148
1149 transferASTDataFromCompilerInstance(*Clang);
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001150
Daniel Dunbar644dca02009-12-04 08:17:33 +00001151 Act->EndSourceFile();
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001152
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001153 FailedParseDiagnostics.clear();
1154
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001155 return false;
Ted Kremenek5e14d392011-03-21 18:40:17 +00001156
Daniel Dunbar764c0822009-12-01 09:51:01 +00001157error:
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001158 // Remove the overridden buffer we used for the preamble.
Rafael Espindola32482082014-08-18 16:23:45 +00001159 SavedMainFileBuffer = nullptr;
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001160
1161 // Keep the ownership of the data in the ASTUnit because the client may
1162 // want to see the diagnostics.
1163 transferASTDataFromCompilerInstance(*Clang);
1164 FailedParseDiagnostics.swap(StoredDiagnostics);
Douglas Gregorefc46952010-10-12 16:25:54 +00001165 StoredDiagnostics.clear();
Argyrios Kyrtzidis067cbfa2011-10-24 17:25:20 +00001166 NumStoredDiagnosticsFromDriver = 0;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001167 return true;
1168}
1169
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001170/// \brief Simple function to retrieve a path for a preamble precompiled header.
1171static std::string GetPreamblePCHPath() {
Douglas Gregor250ab1d2010-09-11 18:05:19 +00001172 // FIXME: This is a hack so that we can override the preamble file during
1173 // crash-recovery testing, which is the only case where the preamble files
Rafael Espindolabc4aa552013-06-26 04:02:37 +00001174 // are not necessarily cleaned up.
Douglas Gregor250ab1d2010-09-11 18:05:19 +00001175 const char *TmpFile = ::getenv("CINDEXTEST_PREAMBLE_FILE");
1176 if (TmpFile)
1177 return TmpFile;
Rafael Espindolabc4aa552013-06-26 04:02:37 +00001178
1179 SmallString<128> Path;
Rafael Espindolaa36e78e2013-07-05 20:00:06 +00001180 llvm::sys::fs::createTemporaryFile("preamble", "pch", Path);
Rafael Espindolabc4aa552013-06-26 04:02:37 +00001181
1182 return Path.str();
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001183}
1184
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001185/// \brief Compute the preamble for the main file, providing the source buffer
1186/// that corresponds to the main file along with a pair (bytes, start-of-line)
1187/// that describes the preamble.
David Blaikied6902a12014-08-29 06:34:53 +00001188ASTUnit::ComputedPreamble
1189ASTUnit::ComputePreamble(CompilerInvocation &Invocation, unsigned MaxLines) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001190 FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
Chris Lattner5159f612010-11-23 08:35:12 +00001191 PreprocessorOptions &PreprocessorOpts = Invocation.getPreprocessorOpts();
Douglas Gregor4dde7492010-07-23 23:58:40 +00001192
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001193 // Try to determine if the main file has been remapped, either from the
1194 // command line (to another file) or directly through the compiler invocation
1195 // (to a memory buffer).
Craig Topper49a27902014-05-22 04:46:25 +00001196 llvm::MemoryBuffer *Buffer = nullptr;
David Blaikied6902a12014-08-29 06:34:53 +00001197 std::unique_ptr<llvm::MemoryBuffer> BufferOwner;
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00001198 std::string MainFilePath(FrontendOpts.Inputs[0].getFile());
Rafael Espindola073ff102013-07-29 21:26:52 +00001199 llvm::sys::fs::UniqueID MainFileID;
Rafael Espindolabe3b12b02013-06-20 15:12:38 +00001200 if (!llvm::sys::fs::getUniqueID(MainFilePath, MainFileID)) {
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001201 // Check whether there is a file-file remapping of the main file
Alp Toker1b070d22014-07-07 07:47:20 +00001202 for (const auto &RF : PreprocessorOpts.RemappedFiles) {
1203 std::string MPath(RF.first);
Rafael Espindola073ff102013-07-29 21:26:52 +00001204 llvm::sys::fs::UniqueID MID;
Rafael Espindolabe3b12b02013-06-20 15:12:38 +00001205 if (!llvm::sys::fs::getUniqueID(MPath, MID)) {
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00001206 if (MainFileID == MID) {
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001207 // We found a remapping. Try to load the resulting, remapped source.
David Blaikied6902a12014-08-29 06:34:53 +00001208 BufferOwner = getBufferForFile(RF.second);
1209 if (!BufferOwner)
1210 return ComputedPreamble(nullptr, nullptr, 0, true);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001211 }
1212 }
1213 }
1214
1215 // Check whether there is a file-buffer remapping. It supercedes the
1216 // file-file remapping.
Alp Toker1b070d22014-07-07 07:47:20 +00001217 for (const auto &RB : PreprocessorOpts.RemappedFileBuffers) {
1218 std::string MPath(RB.first);
Rafael Espindola073ff102013-07-29 21:26:52 +00001219 llvm::sys::fs::UniqueID MID;
Rafael Espindolabe3b12b02013-06-20 15:12:38 +00001220 if (!llvm::sys::fs::getUniqueID(MPath, MID)) {
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00001221 if (MainFileID == MID) {
1222 // We found a remapping.
David Blaikied6902a12014-08-29 06:34:53 +00001223 BufferOwner.reset();
Alp Toker1b070d22014-07-07 07:47:20 +00001224 Buffer = const_cast<llvm::MemoryBuffer *>(RB.second);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001225 }
1226 }
Douglas Gregor4dde7492010-07-23 23:58:40 +00001227 }
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001228 }
1229
1230 // If the main source file was not remapped, load it now.
David Blaikied6902a12014-08-29 06:34:53 +00001231 if (!Buffer && !BufferOwner) {
1232 BufferOwner = getBufferForFile(FrontendOpts.Inputs[0].getFile());
1233 if (!BufferOwner)
1234 return ComputedPreamble(nullptr, nullptr, 0, true);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001235 }
David Blaikie3d95d852014-08-11 22:08:06 +00001236
David Blaikied6902a12014-08-29 06:34:53 +00001237 if (!Buffer)
1238 Buffer = BufferOwner.get();
1239 auto Pre = Lexer::ComputePreamble(Buffer->getBuffer(),
1240 *Invocation.getLangOpts(), MaxLines);
1241 return ComputedPreamble(Buffer, std::move(BufferOwner), Pre.first,
1242 Pre.second);
Douglas Gregor4dde7492010-07-23 23:58:40 +00001243}
1244
Dmitri Gribenko47652522013-12-20 00:16:25 +00001245ASTUnit::PreambleFileHash
1246ASTUnit::PreambleFileHash::createForFile(off_t Size, time_t ModTime) {
1247 PreambleFileHash Result;
1248 Result.Size = Size;
1249 Result.ModTime = ModTime;
Dmitri Gribenko3ec8ee72013-12-20 01:07:30 +00001250 memset(Result.MD5, 0, sizeof(Result.MD5));
Dmitri Gribenko47652522013-12-20 00:16:25 +00001251 return Result;
1252}
1253
1254ASTUnit::PreambleFileHash ASTUnit::PreambleFileHash::createForMemoryBuffer(
1255 const llvm::MemoryBuffer *Buffer) {
1256 PreambleFileHash Result;
1257 Result.Size = Buffer->getBufferSize();
1258 Result.ModTime = 0;
1259
1260 llvm::MD5 MD5Ctx;
1261 MD5Ctx.update(Buffer->getBuffer().data());
1262 MD5Ctx.final(Result.MD5);
1263
1264 return Result;
1265}
1266
1267namespace clang {
1268bool operator==(const ASTUnit::PreambleFileHash &LHS,
1269 const ASTUnit::PreambleFileHash &RHS) {
1270 return LHS.Size == RHS.Size && LHS.ModTime == RHS.ModTime &&
Dmitri Gribenko3ec8ee72013-12-20 01:07:30 +00001271 memcmp(LHS.MD5, RHS.MD5, sizeof(LHS.MD5)) == 0;
Dmitri Gribenko47652522013-12-20 00:16:25 +00001272}
1273} // namespace clang
1274
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001275static std::pair<unsigned, unsigned>
1276makeStandaloneRange(CharSourceRange Range, const SourceManager &SM,
1277 const LangOptions &LangOpts) {
1278 CharSourceRange FileRange = Lexer::makeFileCharRange(Range, SM, LangOpts);
1279 unsigned Offset = SM.getFileOffset(FileRange.getBegin());
1280 unsigned EndOffset = SM.getFileOffset(FileRange.getEnd());
1281 return std::make_pair(Offset, EndOffset);
1282}
1283
Benjamin Kramer1a6e0a92014-10-03 18:52:54 +00001284static ASTUnit::StandaloneFixIt makeStandaloneFixIt(const SourceManager &SM,
1285 const LangOptions &LangOpts,
1286 const FixItHint &InFix) {
1287 ASTUnit::StandaloneFixIt OutFix;
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001288 OutFix.RemoveRange = makeStandaloneRange(InFix.RemoveRange, SM, LangOpts);
1289 OutFix.InsertFromRange = makeStandaloneRange(InFix.InsertFromRange, SM,
1290 LangOpts);
1291 OutFix.CodeToInsert = InFix.CodeToInsert;
1292 OutFix.BeforePreviousInsertions = InFix.BeforePreviousInsertions;
Benjamin Kramer1a6e0a92014-10-03 18:52:54 +00001293 return OutFix;
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001294}
1295
Benjamin Kramer1a6e0a92014-10-03 18:52:54 +00001296static ASTUnit::StandaloneDiagnostic
1297makeStandaloneDiagnostic(const LangOptions &LangOpts,
1298 const StoredDiagnostic &InDiag) {
1299 ASTUnit::StandaloneDiagnostic OutDiag;
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001300 OutDiag.ID = InDiag.getID();
1301 OutDiag.Level = InDiag.getLevel();
1302 OutDiag.Message = InDiag.getMessage();
1303 OutDiag.LocOffset = 0;
1304 if (InDiag.getLocation().isInvalid())
Benjamin Kramer1a6e0a92014-10-03 18:52:54 +00001305 return OutDiag;
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001306 const SourceManager &SM = InDiag.getLocation().getManager();
1307 SourceLocation FileLoc = SM.getFileLoc(InDiag.getLocation());
1308 OutDiag.Filename = SM.getFilename(FileLoc);
1309 if (OutDiag.Filename.empty())
Benjamin Kramer1a6e0a92014-10-03 18:52:54 +00001310 return OutDiag;
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001311 OutDiag.LocOffset = SM.getFileOffset(FileLoc);
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00001312 for (const CharSourceRange &Range : InDiag.getRanges())
1313 OutDiag.Ranges.push_back(makeStandaloneRange(Range, SM, LangOpts));
1314 for (const FixItHint &FixIt : InDiag.getFixIts())
1315 OutDiag.FixIts.push_back(makeStandaloneFixIt(SM, LangOpts, FixIt));
Benjamin Kramer1a6e0a92014-10-03 18:52:54 +00001316
1317 return OutDiag;
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001318}
1319
Douglas Gregor4dde7492010-07-23 23:58:40 +00001320/// \brief Attempt to build or re-use a precompiled preamble when (re-)parsing
1321/// the source file.
1322///
1323/// This routine will compute the preamble of the main source file. If a
1324/// non-trivial preamble is found, it will precompile that preamble into a
1325/// precompiled header so that the precompiled preamble can be used to reduce
1326/// reparsing time. If a precompiled preamble has already been constructed,
1327/// this routine will determine if it is still valid and, if so, avoid
1328/// rebuilding the precompiled preamble.
1329///
Douglas Gregor028d3e42010-08-09 20:45:32 +00001330/// \param AllowRebuild When true (the default), this routine is
1331/// allowed to rebuild the precompiled preamble if it is found to be
1332/// out-of-date.
1333///
1334/// \param MaxLines When non-zero, the maximum number of lines that
1335/// can occur within the preamble.
1336///
Douglas Gregor6481ef12010-07-24 00:38:13 +00001337/// \returns If the precompiled preamble can be used, returns a newly-allocated
1338/// buffer that should be used in place of the main file when doing so.
1339/// Otherwise, returns a NULL pointer.
Rafael Espindola2346a372014-08-18 18:47:08 +00001340std::unique_ptr<llvm::MemoryBuffer>
1341ASTUnit::getMainBufferWithPrecompiledPreamble(
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001342 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
Rafael Espindola2346a372014-08-18 18:47:08 +00001343 const CompilerInvocation &PreambleInvocationIn, bool AllowRebuild,
1344 unsigned MaxLines) {
1345
Dylan Noblesmithc95d8192012-02-20 14:00:23 +00001346 IntrusiveRefCntPtr<CompilerInvocation>
Douglas Gregor3cc15812011-07-01 18:22:13 +00001347 PreambleInvocation(new CompilerInvocation(PreambleInvocationIn));
1348 FrontendOptions &FrontendOpts = PreambleInvocation->getFrontendOpts();
Douglas Gregor4dde7492010-07-23 23:58:40 +00001349 PreprocessorOptions &PreprocessorOpts
Douglas Gregor3cc15812011-07-01 18:22:13 +00001350 = PreambleInvocation->getPreprocessorOpts();
Douglas Gregor4dde7492010-07-23 23:58:40 +00001351
David Blaikied6902a12014-08-29 06:34:53 +00001352 ComputedPreamble NewPreamble = ComputePreamble(*PreambleInvocation, MaxLines);
Douglas Gregor4dde7492010-07-23 23:58:40 +00001353
David Blaikied6902a12014-08-29 06:34:53 +00001354 if (!NewPreamble.Size) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001355 // We couldn't find a preamble in the main source. Clear out the current
1356 // preamble, if we have one. It's obviously no good any more.
1357 Preamble.clear();
Ted Kremenek06b4f912011-10-27 17:55:18 +00001358 erasePreambleFile(this);
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001359
1360 // The next time we actually see a preamble, precompile it.
1361 PreambleRebuildCounter = 1;
Craig Topper49a27902014-05-22 04:46:25 +00001362 return nullptr;
Douglas Gregor4dde7492010-07-23 23:58:40 +00001363 }
1364
1365 if (!Preamble.empty()) {
1366 // We've previously computed a preamble. Check whether we have the same
1367 // preamble now that we did before, and that there's enough space in
1368 // the main-file buffer within the precompiled preamble to fit the
1369 // new main file.
David Blaikied6902a12014-08-29 06:34:53 +00001370 if (Preamble.size() == NewPreamble.Size &&
1371 PreambleEndsAtStartOfLine == NewPreamble.PreambleEndsAtStartOfLine &&
1372 memcmp(Preamble.getBufferStart(), NewPreamble.Buffer->getBufferStart(),
1373 NewPreamble.Size) == 0) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001374 // The preamble has not changed. We may be able to re-use the precompiled
1375 // preamble.
Douglas Gregord9a30af2010-08-02 20:51:39 +00001376
Douglas Gregor0e119552010-07-31 00:40:00 +00001377 // Check that none of the files used by the preamble have changed.
1378 bool AnyFileChanged = false;
1379
1380 // First, make a record of those files that have been overridden via
1381 // remapping or unsaved_files.
Dmitri Gribenko47652522013-12-20 00:16:25 +00001382 llvm::StringMap<PreambleFileHash> OverriddenFiles;
Alp Toker1b070d22014-07-07 07:47:20 +00001383 for (const auto &R : PreprocessorOpts.RemappedFiles) {
1384 if (AnyFileChanged)
1385 break;
1386
Ben Langmuirc8130a72014-02-20 21:59:23 +00001387 vfs::Status Status;
Alp Toker1b070d22014-07-07 07:47:20 +00001388 if (FileMgr->getNoncachedStatValue(R.second, Status)) {
Douglas Gregor0e119552010-07-31 00:40:00 +00001389 // If we can't stat the file we're remapping to, assume that something
1390 // horrible happened.
1391 AnyFileChanged = true;
1392 break;
1393 }
Rafael Espindolae4777f42013-07-29 18:22:23 +00001394
Alp Toker1b070d22014-07-07 07:47:20 +00001395 OverriddenFiles[R.first] = PreambleFileHash::createForFile(
Rafael Espindolae4777f42013-07-29 18:22:23 +00001396 Status.getSize(), Status.getLastModificationTime().toEpochTime());
Douglas Gregor0e119552010-07-31 00:40:00 +00001397 }
Alp Toker1b070d22014-07-07 07:47:20 +00001398
1399 for (const auto &RB : PreprocessorOpts.RemappedFileBuffers) {
1400 if (AnyFileChanged)
1401 break;
1402 OverriddenFiles[RB.first] =
1403 PreambleFileHash::createForMemoryBuffer(RB.second);
Douglas Gregor0e119552010-07-31 00:40:00 +00001404 }
1405
1406 // Check whether anything has changed.
Dmitri Gribenko47652522013-12-20 00:16:25 +00001407 for (llvm::StringMap<PreambleFileHash>::iterator
Douglas Gregor0e119552010-07-31 00:40:00 +00001408 F = FilesInPreamble.begin(), FEnd = FilesInPreamble.end();
1409 !AnyFileChanged && F != FEnd;
1410 ++F) {
Dmitri Gribenko47652522013-12-20 00:16:25 +00001411 llvm::StringMap<PreambleFileHash>::iterator Overridden
Douglas Gregor0e119552010-07-31 00:40:00 +00001412 = OverriddenFiles.find(F->first());
1413 if (Overridden != OverriddenFiles.end()) {
1414 // This file was remapped; check whether the newly-mapped file
1415 // matches up with the previous mapping.
1416 if (Overridden->second != F->second)
1417 AnyFileChanged = true;
1418 continue;
1419 }
1420
1421 // The file was not remapped; check whether it has changed on disk.
Ben Langmuirc8130a72014-02-20 21:59:23 +00001422 vfs::Status Status;
Rafael Espindolae4777f42013-07-29 18:22:23 +00001423 if (FileMgr->getNoncachedStatValue(F->first(), Status)) {
Douglas Gregor0e119552010-07-31 00:40:00 +00001424 // If we can't stat the file, assume that something horrible happened.
1425 AnyFileChanged = true;
Dmitri Gribenko47652522013-12-20 00:16:25 +00001426 } else if (Status.getSize() != uint64_t(F->second.Size) ||
Rafael Espindolae4777f42013-07-29 18:22:23 +00001427 Status.getLastModificationTime().toEpochTime() !=
Dmitri Gribenko47652522013-12-20 00:16:25 +00001428 uint64_t(F->second.ModTime))
Douglas Gregor0e119552010-07-31 00:40:00 +00001429 AnyFileChanged = true;
1430 }
1431
1432 if (!AnyFileChanged) {
Douglas Gregord9a30af2010-08-02 20:51:39 +00001433 // Okay! We can re-use the precompiled preamble.
1434
1435 // Set the state of the diagnostic object to mimic its state
1436 // after parsing the preamble.
1437 getDiagnostics().Reset();
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00001438 ProcessWarningOptions(getDiagnostics(),
Douglas Gregor3cc15812011-07-01 18:22:13 +00001439 PreambleInvocation->getDiagnosticOpts());
Douglas Gregord9a30af2010-08-02 20:51:39 +00001440 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
Douglas Gregord9a30af2010-08-02 20:51:39 +00001441
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001442 return llvm::MemoryBuffer::getMemBufferCopy(
David Blaikied6902a12014-08-29 06:34:53 +00001443 NewPreamble.Buffer->getBuffer(), FrontendOpts.Inputs[0].getFile());
Douglas Gregor0e119552010-07-31 00:40:00 +00001444 }
Douglas Gregor4dde7492010-07-23 23:58:40 +00001445 }
Douglas Gregor028d3e42010-08-09 20:45:32 +00001446
1447 // If we aren't allowed to rebuild the precompiled preamble, just
1448 // return now.
1449 if (!AllowRebuild)
Craig Topper49a27902014-05-22 04:46:25 +00001450 return nullptr;
Douglas Gregorbb6a8812010-10-08 04:03:57 +00001451
Douglas Gregor4dde7492010-07-23 23:58:40 +00001452 // We can't reuse the previously-computed preamble. Build a new one.
1453 Preamble.clear();
Douglas Gregor925296b2011-07-19 16:10:42 +00001454 PreambleDiagnostics.clear();
Ted Kremenek06b4f912011-10-27 17:55:18 +00001455 erasePreambleFile(this);
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001456 PreambleRebuildCounter = 1;
Douglas Gregor028d3e42010-08-09 20:45:32 +00001457 } else if (!AllowRebuild) {
1458 // We aren't allowed to rebuild the precompiled preamble; just
1459 // return now.
Craig Topper49a27902014-05-22 04:46:25 +00001460 return nullptr;
Douglas Gregor028d3e42010-08-09 20:45:32 +00001461 }
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001462
1463 // If the preamble rebuild counter > 1, it's because we previously
1464 // failed to build a preamble and we're not yet ready to try
1465 // again. Decrement the counter and return a failure.
1466 if (PreambleRebuildCounter > 1) {
1467 --PreambleRebuildCounter;
Craig Topper49a27902014-05-22 04:46:25 +00001468 return nullptr;
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001469 }
1470
Douglas Gregore10f0e52010-09-11 17:56:52 +00001471 // Create a temporary file for the precompiled preamble. In rare
1472 // circumstances, this can fail.
1473 std::string PreamblePCHPath = GetPreamblePCHPath();
1474 if (PreamblePCHPath.empty()) {
1475 // Try again next time.
1476 PreambleRebuildCounter = 1;
Craig Topper49a27902014-05-22 04:46:25 +00001477 return nullptr;
Douglas Gregore10f0e52010-09-11 17:56:52 +00001478 }
1479
Douglas Gregor4dde7492010-07-23 23:58:40 +00001480 // We did not previously compute a preamble, or it can't be reused anyway.
Douglas Gregor16896c42010-10-28 15:44:59 +00001481 SimpleTimer PreambleTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00001482 PreambleTimer.setOutput("Precompiling preamble");
Douglas Gregor4dde7492010-07-23 23:58:40 +00001483
Douglas Gregord9a30af2010-08-02 20:51:39 +00001484 // Save the preamble text for later; we'll need to compare against it for
1485 // subsequent reparses.
Dmitri Gribenko40798d32013-12-19 23:25:59 +00001486 StringRef MainFilename = FrontendOpts.Inputs[0].getFile();
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00001487 Preamble.assign(FileMgr->getFile(MainFilename),
David Blaikied6902a12014-08-29 06:34:53 +00001488 NewPreamble.Buffer->getBufferStart(),
1489 NewPreamble.Buffer->getBufferStart() + NewPreamble.Size);
1490 PreambleEndsAtStartOfLine = NewPreamble.PreambleEndsAtStartOfLine;
Douglas Gregord9a30af2010-08-02 20:51:39 +00001491
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001492 PreambleBuffer = llvm::MemoryBuffer::getMemBufferCopy(
David Blaikied6902a12014-08-29 06:34:53 +00001493 NewPreamble.Buffer->getBuffer().slice(0, Preamble.size()), MainFilename);
Rafael Espindolaa96bd562013-06-26 04:12:57 +00001494
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001495 // Remap the main source file to the preamble buffer.
Rafael Espindolaa96bd562013-06-26 04:12:57 +00001496 StringRef MainFilePath = FrontendOpts.Inputs[0].getFile();
Rafael Espindolafa49c0b2014-08-13 16:47:00 +00001497 PreprocessorOpts.addRemappedFile(MainFilePath, PreambleBuffer.get());
Rafael Espindolaa96bd562013-06-26 04:12:57 +00001498
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001499 // Tell the compiler invocation to generate a temporary precompiled header.
1500 FrontendOpts.ProgramAction = frontend::GeneratePCH;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001501 // FIXME: Generate the precompiled header into memory?
Douglas Gregore10f0e52010-09-11 17:56:52 +00001502 FrontendOpts.OutputFile = PreamblePCHPath;
Douglas Gregorbb6a8812010-10-08 04:03:57 +00001503 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
1504 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001505
1506 // Create the compiler instance to use for building the precompiled preamble.
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001507 std::unique_ptr<CompilerInstance> Clang(
1508 new CompilerInstance(PCHContainerOps));
Ted Kremenek84de4a12011-03-21 18:40:07 +00001509
1510 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00001511 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1512 CICleanup(Clang.get());
Ted Kremenek84de4a12011-03-21 18:40:07 +00001513
Douglas Gregor3cc15812011-07-01 18:22:13 +00001514 Clang->setInvocation(&*PreambleInvocation);
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001515 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001516
Douglas Gregor8e984da2010-08-04 16:47:14 +00001517 // Set up diagnostics, capturing all of the diagnostics produced.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001518 Clang->setDiagnostics(&getDiagnostics());
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001519
1520 // Create the target instance.
Alp Toker80758082014-07-06 05:26:44 +00001521 Clang->setTarget(TargetInfo::CreateTargetInfo(
1522 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
Ted Kremenek84de4a12011-03-21 18:40:07 +00001523 if (!Clang->hasTarget()) {
Rafael Espindolaf5e5bc42013-06-26 04:26:38 +00001524 llvm::sys::fs::remove(FrontendOpts.OutputFile);
Douglas Gregor4dde7492010-07-23 23:58:40 +00001525 Preamble.clear();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001526 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Alp Toker1b070d22014-07-07 07:47:20 +00001527 PreprocessorOpts.RemappedFileBuffers.pop_back();
Craig Topper49a27902014-05-22 04:46:25 +00001528 return nullptr;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001529 }
1530
1531 // Inform the target of the language options.
1532 //
1533 // FIXME: We shouldn't need to do this, the target should be immutable once
1534 // created. This complexity should be lifted elsewhere.
Alp Toker74437972014-07-06 05:14:24 +00001535 Clang->getTarget().adjust(Clang->getLangOpts());
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001536
Ted Kremenek84de4a12011-03-21 18:40:07 +00001537 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001538 "Invocation must have exactly one source file!");
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001539 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001540 "FIXME: AST inputs not yet supported here!");
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001541 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001542 "IR inputs not support here!");
1543
1544 // Clear out old caches and data.
Douglas Gregorbb6a8812010-10-08 04:03:57 +00001545 getDiagnostics().Reset();
Ted Kremenek84de4a12011-03-21 18:40:07 +00001546 ProcessWarningOptions(getDiagnostics(), Clang->getDiagnosticOpts());
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +00001547 checkAndRemoveNonDriverDiags(StoredDiagnostics);
Douglas Gregore9db88f2010-08-03 19:06:41 +00001548 TopLevelDecls.clear();
1549 TopLevelDeclsInPreamble.clear();
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001550 PreambleDiagnostics.clear();
Ben Langmuir8832c062014-04-15 18:16:25 +00001551
1552 IntrusiveRefCntPtr<vfs::FileSystem> VFS =
1553 createVFSFromCompilerInvocation(Clang->getInvocation(), getDiagnostics());
1554 if (!VFS)
1555 return nullptr;
1556
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001557 // Create a file manager object to provide access to and cache the filesystem.
Ben Langmuir8832c062014-04-15 18:16:25 +00001558 Clang->setFileManager(new FileManager(Clang->getFileSystemOpts(), VFS));
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001559
1560 // Create the source manager.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001561 Clang->setSourceManager(new SourceManager(getDiagnostics(),
Ted Kremenek5e14d392011-03-21 18:40:17 +00001562 Clang->getFileManager()));
Ahmed Charlesb8984322014-03-07 20:03:18 +00001563
Ben Langmuir33c80902014-06-30 20:04:14 +00001564 auto PreambleDepCollector = std::make_shared<DependencyCollector>();
1565 Clang->addDependencyCollector(PreambleDepCollector);
1566
Ahmed Charlesb8984322014-03-07 20:03:18 +00001567 std::unique_ptr<PrecompilePreambleAction> Act;
Douglas Gregor48c8cd32010-08-03 08:14:03 +00001568 Act.reset(new PrecompilePreambleAction(*this));
Douglas Gregor32fbe312012-01-20 16:28:04 +00001569 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
Rafael Espindolaf5e5bc42013-06-26 04:26:38 +00001570 llvm::sys::fs::remove(FrontendOpts.OutputFile);
Douglas Gregor4dde7492010-07-23 23:58:40 +00001571 Preamble.clear();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001572 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Alp Toker1b070d22014-07-07 07:47:20 +00001573 PreprocessorOpts.RemappedFileBuffers.pop_back();
Craig Topper49a27902014-05-22 04:46:25 +00001574 return nullptr;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001575 }
1576
1577 Act->Execute();
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001578
1579 // Transfer any diagnostics generated when parsing the preamble into the set
1580 // of preamble diagnostics.
Benjamin Kramer1a6e0a92014-10-03 18:52:54 +00001581 for (stored_diag_iterator I = stored_diag_afterDriver_begin(),
1582 E = stored_diag_end();
1583 I != E; ++I)
1584 PreambleDiagnostics.push_back(
1585 makeStandaloneDiagnostic(Clang->getLangOpts(), *I));
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001586
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001587 Act->EndSourceFile();
Ted Kremenek5e14d392011-03-21 18:40:17 +00001588
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001589 checkAndRemoveNonDriverDiags(StoredDiagnostics);
1590
Argyrios Kyrtzidisf0168de2013-06-11 00:36:55 +00001591 if (!Act->hasEmittedPreamblePCH()) {
Argyrios Kyrtzidisd6f57222013-06-11 16:42:34 +00001592 // The preamble PCH failed (e.g. there was a module loading fatal error),
1593 // so no precompiled header was generated. Forget that we even tried.
Douglas Gregora6f74e22010-09-27 16:43:25 +00001594 // FIXME: Should we leave a note for ourselves to try again?
Rafael Espindolaf5e5bc42013-06-26 04:26:38 +00001595 llvm::sys::fs::remove(FrontendOpts.OutputFile);
Douglas Gregor4dde7492010-07-23 23:58:40 +00001596 Preamble.clear();
Douglas Gregore9db88f2010-08-03 19:06:41 +00001597 TopLevelDeclsInPreamble.clear();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001598 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Alp Toker1b070d22014-07-07 07:47:20 +00001599 PreprocessorOpts.RemappedFileBuffers.pop_back();
Craig Topper49a27902014-05-22 04:46:25 +00001600 return nullptr;
Douglas Gregor4dde7492010-07-23 23:58:40 +00001601 }
1602
1603 // Keep track of the preamble we precompiled.
Ted Kremenek06b4f912011-10-27 17:55:18 +00001604 setPreambleFile(this, FrontendOpts.OutputFile);
Douglas Gregord9a30af2010-08-02 20:51:39 +00001605 NumWarningsInPreamble = getDiagnostics().getNumWarnings();
Douglas Gregor0e119552010-07-31 00:40:00 +00001606
1607 // Keep track of all of the files that the source manager knows about,
1608 // so we can verify whether they have changed or not.
1609 FilesInPreamble.clear();
Ted Kremenek84de4a12011-03-21 18:40:07 +00001610 SourceManager &SourceMgr = Clang->getSourceManager();
Ben Langmuir33c80902014-06-30 20:04:14 +00001611 for (auto &Filename : PreambleDepCollector->getDependencies()) {
1612 const FileEntry *File = Clang->getFileManager().getFile(Filename);
1613 if (!File || File == SourceMgr.getFileEntryForID(SourceMgr.getMainFileID()))
Douglas Gregor0e119552010-07-31 00:40:00 +00001614 continue;
Dmitri Gribenko47652522013-12-20 00:16:25 +00001615 if (time_t ModTime = File->getModificationTime()) {
1616 FilesInPreamble[File->getName()] = PreambleFileHash::createForFile(
Ben Langmuir33c80902014-06-30 20:04:14 +00001617 File->getSize(), ModTime);
Dmitri Gribenko47652522013-12-20 00:16:25 +00001618 } else {
Ben Langmuir33c80902014-06-30 20:04:14 +00001619 llvm::MemoryBuffer *Buffer = SourceMgr.getMemoryBufferForFile(File);
Dmitri Gribenko47652522013-12-20 00:16:25 +00001620 FilesInPreamble[File->getName()] =
1621 PreambleFileHash::createForMemoryBuffer(Buffer);
1622 }
Douglas Gregor0e119552010-07-31 00:40:00 +00001623 }
Ben Langmuir33c80902014-06-30 20:04:14 +00001624
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001625 PreambleRebuildCounter = 1;
Alp Toker1b070d22014-07-07 07:47:20 +00001626 PreprocessorOpts.RemappedFileBuffers.pop_back();
1627
Douglas Gregordf7a79a2011-02-16 18:16:54 +00001628 // If the hash of top-level entities differs from the hash of the top-level
1629 // entities the last time we rebuilt the preamble, clear out the completion
1630 // cache.
1631 if (CurrentTopLevelHashValue != PreambleTopLevelHashValue) {
1632 CompletionCacheTopLevelHashValue = 0;
1633 PreambleTopLevelHashValue = CurrentTopLevelHashValue;
1634 }
Rafael Espindola2346a372014-08-18 18:47:08 +00001635
David Blaikied6902a12014-08-29 06:34:53 +00001636 return llvm::MemoryBuffer::getMemBufferCopy(NewPreamble.Buffer->getBuffer(),
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001637 MainFilename);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001638}
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001639
Douglas Gregore9db88f2010-08-03 19:06:41 +00001640void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
1641 std::vector<Decl *> Resolved;
1642 Resolved.reserve(TopLevelDeclsInPreamble.size());
1643 ExternalASTSource &Source = *getASTContext().getExternalSource();
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00001644 for (serialization::DeclID TopLevelDecl : TopLevelDeclsInPreamble) {
Douglas Gregore9db88f2010-08-03 19:06:41 +00001645 // Resolve the declaration ID to an actual declaration, possibly
1646 // deserializing the declaration in the process.
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00001647 if (Decl *D = Source.GetExternalDecl(TopLevelDecl))
Douglas Gregore9db88f2010-08-03 19:06:41 +00001648 Resolved.push_back(D);
1649 }
1650 TopLevelDeclsInPreamble.clear();
1651 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1652}
1653
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001654void ASTUnit::transferASTDataFromCompilerInstance(CompilerInstance &CI) {
Ben Langmuir749323f2014-04-22 17:40:12 +00001655 // Steal the created target, context, and preprocessor if they have been
1656 // created.
1657 assert(CI.hasInvocation() && "missing invocation");
Alp Toker269d8402014-07-06 05:26:07 +00001658 LangOpts = CI.getInvocation().LangOpts;
David Blaikieec99b5e2014-08-10 19:14:48 +00001659 TheSema = CI.takeSema();
David Blaikie6beb6aa2014-08-10 19:56:51 +00001660 Consumer = CI.takeASTConsumer();
Ben Langmuir532fdc02014-04-18 20:39:48 +00001661 if (CI.hasASTContext())
1662 Ctx = &CI.getASTContext();
1663 if (CI.hasPreprocessor())
1664 PP = &CI.getPreprocessor();
Craig Topper49a27902014-05-22 04:46:25 +00001665 CI.setSourceManager(nullptr);
1666 CI.setFileManager(nullptr);
Ben Langmuir532fdc02014-04-18 20:39:48 +00001667 if (CI.hasTarget())
1668 Target = &CI.getTarget();
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001669 Reader = CI.getModuleManager();
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00001670 HadModuleLoaderFatalFailure = CI.hadModuleLoaderFatalFailure();
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001671}
1672
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001673StringRef ASTUnit::getMainFileName() const {
Argyrios Kyrtzidis928e1fd2013-01-11 22:11:14 +00001674 if (Invocation && !Invocation->getFrontendOpts().Inputs.empty()) {
1675 const FrontendInputFile &Input = Invocation->getFrontendOpts().Inputs[0];
1676 if (Input.isFile())
1677 return Input.getFile();
1678 else
1679 return Input.getBuffer()->getBufferIdentifier();
1680 }
1681
1682 if (SourceMgr) {
1683 if (const FileEntry *
1684 FE = SourceMgr->getFileEntryForID(SourceMgr->getMainFileID()))
1685 return FE->getName();
1686 }
1687
1688 return StringRef();
Douglas Gregor16896c42010-10-28 15:44:59 +00001689}
1690
Argyrios Kyrtzidis37f2ab42013-03-05 20:21:14 +00001691StringRef ASTUnit::getASTFileName() const {
1692 if (!isMainFileAST())
1693 return StringRef();
1694
1695 serialization::ModuleFile &
1696 Mod = Reader->getModuleManager().getPrimaryModule();
1697 return Mod.FileName;
1698}
1699
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00001700ASTUnit *ASTUnit::create(CompilerInvocation *CI,
Dylan Noblesmithc95d8192012-02-20 14:00:23 +00001701 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +00001702 bool CaptureDiagnostics,
1703 bool UserFilesAreVolatile) {
Ahmed Charlesb8984322014-03-07 20:03:18 +00001704 std::unique_ptr<ASTUnit> AST;
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00001705 AST.reset(new ASTUnit(false));
Justin Bognerdbbcb112014-10-14 23:36:06 +00001706 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00001707 AST->Diagnostics = Diags;
Ted Kremenek5e14d392011-03-21 18:40:17 +00001708 AST->Invocation = CI;
Anders Carlssonc30dcec2011-03-18 18:22:40 +00001709 AST->FileSystemOpts = CI->getFileSystemOpts();
Ben Langmuir8832c062014-04-15 18:16:25 +00001710 IntrusiveRefCntPtr<vfs::FileSystem> VFS =
1711 createVFSFromCompilerInvocation(*CI, *Diags);
1712 if (!VFS)
1713 return nullptr;
1714 AST->FileMgr = new FileManager(AST->FileSystemOpts, VFS);
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +00001715 AST->UserFilesAreVolatile = UserFilesAreVolatile;
1716 AST->SourceMgr = new SourceManager(AST->getDiagnostics(), *AST->FileMgr,
1717 UserFilesAreVolatile);
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00001718
Ahmed Charles9a16beb2014-03-07 19:33:25 +00001719 return AST.release();
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00001720}
1721
Ahmed Charlesb8984322014-03-07 20:03:18 +00001722ASTUnit *ASTUnit::LoadFromCompilerInvocationAction(
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001723 CompilerInvocation *CI,
1724 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1725 IntrusiveRefCntPtr<DiagnosticsEngine> Diags, ASTFrontendAction *Action,
1726 ASTUnit *Unit, bool Persistent, StringRef ResourceFilesPath,
1727 bool OnlyLocalDecls, bool CaptureDiagnostics, bool PrecompilePreamble,
1728 bool CacheCodeCompletionResults, bool IncludeBriefCommentsInCodeCompletion,
1729 bool UserFilesAreVolatile, std::unique_ptr<ASTUnit> *ErrAST) {
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001730 assert(CI && "A CompilerInvocation is required");
1731
Ahmed Charlesb8984322014-03-07 20:03:18 +00001732 std::unique_ptr<ASTUnit> OwnAST;
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001733 ASTUnit *AST = Unit;
1734 if (!AST) {
1735 // Create the AST unit.
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +00001736 OwnAST.reset(create(CI, Diags, CaptureDiagnostics, UserFilesAreVolatile));
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001737 AST = OwnAST.get();
Ben Langmuir8832c062014-04-15 18:16:25 +00001738 if (!AST)
1739 return nullptr;
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001740 }
1741
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00001742 if (!ResourceFilesPath.empty()) {
1743 // Override the resources path.
1744 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
1745 }
1746 AST->OnlyLocalDecls = OnlyLocalDecls;
1747 AST->CaptureDiagnostics = CaptureDiagnostics;
1748 if (PrecompilePreamble)
1749 AST->PreambleRebuildCounter = 2;
Douglas Gregor69f74f82011-08-25 22:30:56 +00001750 AST->TUKind = Action ? Action->getTranslationUnitKind() : TU_Complete;
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00001751 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenko3292d062012-07-02 17:35:10 +00001752 AST->IncludeBriefCommentsInCodeCompletion
1753 = IncludeBriefCommentsInCodeCompletion;
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001754
1755 // Recover resources if we crash before exiting this method.
1756 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001757 ASTUnitCleanup(OwnAST.get());
David Blaikie9c902b52011-09-25 23:23:43 +00001758 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1759 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Alp Tokerf994cef2014-07-05 03:08:06 +00001760 DiagCleanup(Diags.get());
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001761
1762 // We'll manage file buffers ourselves.
1763 CI->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1764 CI->getFrontendOpts().DisableFree = false;
1765 ProcessWarningOptions(AST->getDiagnostics(), CI->getDiagnosticOpts());
1766
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001767 // Create the compiler instance to use for building the AST.
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001768 std::unique_ptr<CompilerInstance> Clang(
1769 new CompilerInstance(PCHContainerOps));
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001770
1771 // Recover resources if we crash before exiting this method.
1772 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1773 CICleanup(Clang.get());
1774
1775 Clang->setInvocation(CI);
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001776 AST->OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001777
1778 // Set up diagnostics, capturing any diagnostics that would
1779 // otherwise be dropped.
1780 Clang->setDiagnostics(&AST->getDiagnostics());
1781
1782 // Create the target instance.
Alp Toker80758082014-07-06 05:26:44 +00001783 Clang->setTarget(TargetInfo::CreateTargetInfo(
1784 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001785 if (!Clang->hasTarget())
Craig Topper49a27902014-05-22 04:46:25 +00001786 return nullptr;
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001787
1788 // Inform the target of the language options.
1789 //
1790 // FIXME: We shouldn't need to do this, the target should be immutable once
1791 // created. This complexity should be lifted elsewhere.
Alp Toker74437972014-07-06 05:14:24 +00001792 Clang->getTarget().adjust(Clang->getLangOpts());
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001793
1794 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1795 "Invocation must have exactly one source file!");
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001796 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001797 "FIXME: AST inputs not yet supported here!");
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001798 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001799 "IR inputs not supported here!");
1800
1801 // Configure the various subsystems.
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001802 AST->TheSema.reset();
Craig Topper49a27902014-05-22 04:46:25 +00001803 AST->Ctx = nullptr;
1804 AST->PP = nullptr;
1805 AST->Reader = nullptr;
1806
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001807 // Create a file manager object to provide access to and cache the filesystem.
1808 Clang->setFileManager(&AST->getFileManager());
1809
1810 // Create the source manager.
1811 Clang->setSourceManager(&AST->getSourceManager());
1812
1813 ASTFrontendAction *Act = Action;
1814
Ahmed Charlesb8984322014-03-07 20:03:18 +00001815 std::unique_ptr<TopLevelDeclTrackerAction> TrackerAct;
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001816 if (!Act) {
1817 TrackerAct.reset(new TopLevelDeclTrackerAction(*AST));
1818 Act = TrackerAct.get();
1819 }
1820
1821 // Recover resources if we crash before exiting this method.
1822 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1823 ActCleanup(TrackerAct.get());
1824
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001825 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
1826 AST->transferASTDataFromCompilerInstance(*Clang);
1827 if (OwnAST && ErrAST)
1828 ErrAST->swap(OwnAST);
1829
Craig Topper49a27902014-05-22 04:46:25 +00001830 return nullptr;
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001831 }
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00001832
1833 if (Persistent && !TrackerAct) {
1834 Clang->getPreprocessor().addPPCallbacks(
Craig Topperb8a70532014-09-10 04:53:53 +00001835 llvm::make_unique<MacroDefinitionTrackerPPCallbacks>(
1836 AST->getCurrentTopLevelHashValue()));
David Blaikie6beb6aa2014-08-10 19:56:51 +00001837 std::vector<std::unique_ptr<ASTConsumer>> Consumers;
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00001838 if (Clang->hasASTConsumer())
1839 Consumers.push_back(Clang->takeASTConsumer());
David Blaikie6beb6aa2014-08-10 19:56:51 +00001840 Consumers.push_back(llvm::make_unique<TopLevelDeclTrackerConsumer>(
1841 *AST, AST->getCurrentTopLevelHashValue()));
1842 Clang->setASTConsumer(
1843 llvm::make_unique<MultiplexConsumer>(std::move(Consumers)));
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00001844 }
Argyrios Kyrtzidis1416e172012-06-08 05:48:06 +00001845 if (!Act->Execute()) {
1846 AST->transferASTDataFromCompilerInstance(*Clang);
1847 if (OwnAST && ErrAST)
1848 ErrAST->swap(OwnAST);
1849
Craig Topper49a27902014-05-22 04:46:25 +00001850 return nullptr;
Argyrios Kyrtzidis1416e172012-06-08 05:48:06 +00001851 }
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001852
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001853 // Steal the created target, context, and preprocessor.
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001854 AST->transferASTDataFromCompilerInstance(*Clang);
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001855
1856 Act->EndSourceFile();
1857
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001858 if (OwnAST)
Ahmed Charles9a16beb2014-03-07 19:33:25 +00001859 return OwnAST.release();
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001860 else
1861 return AST;
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001862}
1863
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001864bool ASTUnit::LoadFromCompilerInvocation(
1865 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1866 bool PrecompilePreamble) {
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001867 if (!Invocation)
1868 return true;
1869
1870 // We'll manage file buffers ourselves.
1871 Invocation->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1872 Invocation->getFrontendOpts().DisableFree = false;
Douglas Gregor345c1bc2011-01-19 01:02:47 +00001873 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001874
Rafael Espindola32482082014-08-18 16:23:45 +00001875 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
Douglas Gregorf5a18542010-10-27 17:24:53 +00001876 if (PrecompilePreamble) {
Douglas Gregorc6592922010-11-15 23:00:34 +00001877 PreambleRebuildCounter = 2;
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001878 OverrideMainBuffer =
1879 getMainBufferWithPrecompiledPreamble(PCHContainerOps, *Invocation);
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001880 }
1881
Douglas Gregor16896c42010-10-28 15:44:59 +00001882 SimpleTimer ParsingTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00001883 ParsingTimer.setOutput("Parsing " + getMainFileName());
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001884
Ted Kremenek022a4902011-03-22 01:15:24 +00001885 // Recover resources if we crash before exiting this method.
1886 llvm::CrashRecoveryContextCleanupRegistrar<llvm::MemoryBuffer>
Rafael Espindola32482082014-08-18 16:23:45 +00001887 MemBufferCleanup(OverrideMainBuffer.get());
1888
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001889 return Parse(PCHContainerOps, std::move(OverrideMainBuffer));
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001890}
1891
David Blaikie103a2de2014-04-25 17:01:33 +00001892std::unique_ptr<ASTUnit> ASTUnit::LoadFromCompilerInvocation(
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001893 CompilerInvocation *CI,
1894 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1895 IntrusiveRefCntPtr<DiagnosticsEngine> Diags, bool OnlyLocalDecls,
1896 bool CaptureDiagnostics, bool PrecompilePreamble,
David Blaikie103a2de2014-04-25 17:01:33 +00001897 TranslationUnitKind TUKind, bool CacheCodeCompletionResults,
1898 bool IncludeBriefCommentsInCodeCompletion, bool UserFilesAreVolatile) {
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001899 // Create the AST unit.
David Blaikie103a2de2014-04-25 17:01:33 +00001900 std::unique_ptr<ASTUnit> AST(new ASTUnit(false));
Justin Bognerdbbcb112014-10-14 23:36:06 +00001901 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001902 AST->Diagnostics = Diags;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001903 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001904 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor69f74f82011-08-25 22:30:56 +00001905 AST->TUKind = TUKind;
Douglas Gregorb14904c2010-08-13 22:48:40 +00001906 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenko3292d062012-07-02 17:35:10 +00001907 AST->IncludeBriefCommentsInCodeCompletion
1908 = IncludeBriefCommentsInCodeCompletion;
Ted Kremenek5e14d392011-03-21 18:40:17 +00001909 AST->Invocation = CI;
Argyrios Kyrtzidis3ad52ed2013-01-21 18:45:42 +00001910 AST->FileSystemOpts = CI->getFileSystemOpts();
Ben Langmuir8832c062014-04-15 18:16:25 +00001911 IntrusiveRefCntPtr<vfs::FileSystem> VFS =
1912 createVFSFromCompilerInvocation(*CI, *Diags);
1913 if (!VFS)
1914 return nullptr;
1915 AST->FileMgr = new FileManager(AST->FileSystemOpts, VFS);
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +00001916 AST->UserFilesAreVolatile = UserFilesAreVolatile;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001917
Ted Kremenek4422bfe2011-03-18 02:06:56 +00001918 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00001919 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1920 ASTUnitCleanup(AST.get());
David Blaikie9c902b52011-09-25 23:23:43 +00001921 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1922 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Alp Tokerf994cef2014-07-05 03:08:06 +00001923 DiagCleanup(Diags.get());
Ted Kremenek4422bfe2011-03-18 02:06:56 +00001924
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001925 if (AST->LoadFromCompilerInvocation(PCHContainerOps, PrecompilePreamble))
David Blaikie103a2de2014-04-25 17:01:33 +00001926 return nullptr;
1927 return AST;
Daniel Dunbar764c0822009-12-01 09:51:01 +00001928}
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001929
Ahmed Charlesb8984322014-03-07 20:03:18 +00001930ASTUnit *ASTUnit::LoadFromCommandLine(
1931 const char **ArgBegin, const char **ArgEnd,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00001932 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
Ahmed Charlesb8984322014-03-07 20:03:18 +00001933 IntrusiveRefCntPtr<DiagnosticsEngine> Diags, StringRef ResourceFilesPath,
1934 bool OnlyLocalDecls, bool CaptureDiagnostics,
1935 ArrayRef<RemappedFile> RemappedFiles, bool RemappedFilesKeepOriginalName,
1936 bool PrecompilePreamble, TranslationUnitKind TUKind,
1937 bool CacheCodeCompletionResults, bool IncludeBriefCommentsInCodeCompletion,
1938 bool AllowPCHWithCompilerErrors, bool SkipFunctionBodies,
1939 bool UserFilesAreVolatile, bool ForSerialization,
1940 std::unique_ptr<ASTUnit> *ErrAST) {
Justin Bognerd512c1e2014-10-15 00:33:06 +00001941 assert(Diags.get() && "no DiagnosticsEngine was provided");
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001942
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001943 SmallVector<StoredDiagnostic, 4> StoredDiagnostics;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001944
Dylan Noblesmithc95d8192012-02-20 14:00:23 +00001945 IntrusiveRefCntPtr<CompilerInvocation> CI;
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001946
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001947 {
Douglas Gregor925296b2011-07-19 16:10:42 +00001948
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001949 CaptureDroppedDiagnostics Capture(CaptureDiagnostics, *Diags,
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001950 StoredDiagnostics);
Daniel Dunbarfcf2d422010-01-25 00:44:02 +00001951
Argyrios Kyrtzidis5cf423e2011-04-04 23:11:45 +00001952 CI = clang::createInvocationFromCommandLine(
Frits van Bommel717d7ed2011-07-18 12:00:32 +00001953 llvm::makeArrayRef(ArgBegin, ArgEnd),
1954 Diags);
Argyrios Kyrtzidisf606b822011-04-04 21:38:51 +00001955 if (!CI)
Craig Topper49a27902014-05-22 04:46:25 +00001956 return nullptr;
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001957 }
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001958
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001959 // Override any files that need remapping
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00001960 for (const auto &RemappedFile : RemappedFiles) {
1961 CI->getPreprocessorOpts().addRemappedFile(RemappedFile.first,
1962 RemappedFile.second);
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00001963 }
Argyrios Kyrtzidis4a280ff2012-03-07 01:51:17 +00001964 PreprocessorOptions &PPOpts = CI->getPreprocessorOpts();
1965 PPOpts.RemappedFilesKeepOriginalName = RemappedFilesKeepOriginalName;
1966 PPOpts.AllowPCHWithCompilerErrors = AllowPCHWithCompilerErrors;
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001967
Daniel Dunbara5a166d2009-12-15 00:06:45 +00001968 // Override the resources path.
Daniel Dunbar6b03ece2010-01-30 21:47:16 +00001969 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001970
Erik Verbruggen6e922512012-04-12 10:11:59 +00001971 CI->getFrontendOpts().SkipFunctionBodies = SkipFunctionBodies;
1972
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001973 // Create the AST unit.
Ahmed Charlesb8984322014-03-07 20:03:18 +00001974 std::unique_ptr<ASTUnit> AST;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001975 AST.reset(new ASTUnit(false));
Justin Bognerdbbcb112014-10-14 23:36:06 +00001976 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001977 AST->Diagnostics = Diags;
Anders Carlssonc30dcec2011-03-18 18:22:40 +00001978 AST->FileSystemOpts = CI->getFileSystemOpts();
Ben Langmuir8832c062014-04-15 18:16:25 +00001979 IntrusiveRefCntPtr<vfs::FileSystem> VFS =
1980 createVFSFromCompilerInvocation(*CI, *Diags);
1981 if (!VFS)
1982 return nullptr;
1983 AST->FileMgr = new FileManager(AST->FileSystemOpts, VFS);
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001984 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001985 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor69f74f82011-08-25 22:30:56 +00001986 AST->TUKind = TUKind;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001987 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenko3292d062012-07-02 17:35:10 +00001988 AST->IncludeBriefCommentsInCodeCompletion
1989 = IncludeBriefCommentsInCodeCompletion;
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +00001990 AST->UserFilesAreVolatile = UserFilesAreVolatile;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001991 AST->NumStoredDiagnosticsFromDriver = StoredDiagnostics.size();
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001992 AST->StoredDiagnostics.swap(StoredDiagnostics);
Ted Kremenek5e14d392011-03-21 18:40:17 +00001993 AST->Invocation = CI;
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00001994 if (ForSerialization)
1995 AST->WriterData.reset(new ASTWriterData());
Alexey Samsonovb4f99dd2014-08-28 23:51:01 +00001996 // Zero out now to ease cleanup during crash recovery.
1997 CI = nullptr;
1998 Diags = nullptr;
Craig Topper49a27902014-05-22 04:46:25 +00001999
Ted Kremenek4422bfe2011-03-18 02:06:56 +00002000 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00002001 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
2002 ASTUnitCleanup(AST.get());
Ted Kremenek4422bfe2011-03-18 02:06:56 +00002003
Adrian Prantlbb165fb2015-06-20 18:53:08 +00002004 if (AST->LoadFromCompilerInvocation(PCHContainerOps, PrecompilePreamble)) {
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00002005 // Some error occurred, if caller wants to examine diagnostics, pass it the
2006 // ASTUnit.
2007 if (ErrAST) {
2008 AST->StoredDiagnostics.swap(AST->FailedParseDiagnostics);
2009 ErrAST->swap(AST);
2010 }
Craig Topper49a27902014-05-22 04:46:25 +00002011 return nullptr;
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00002012 }
2013
Ahmed Charles9a16beb2014-03-07 19:33:25 +00002014 return AST.release();
Daniel Dunbar55a17b62009-12-02 03:23:45 +00002015}
Douglas Gregoraa21cc42010-07-19 21:46:24 +00002016
Adrian Prantlbb165fb2015-06-20 18:53:08 +00002017bool ASTUnit::Reparse(std::shared_ptr<PCHContainerOperations> PCHContainerOps,
2018 ArrayRef<RemappedFile> RemappedFiles) {
Ted Kremenek5e14d392011-03-21 18:40:17 +00002019 if (!Invocation)
Douglas Gregoraa21cc42010-07-19 21:46:24 +00002020 return true;
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00002021
2022 clearFileLevelDecls();
Douglas Gregoraa21cc42010-07-19 21:46:24 +00002023
Douglas Gregor16896c42010-10-28 15:44:59 +00002024 SimpleTimer ParsingTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00002025 ParsingTimer.setOutput("Reparsing " + getMainFileName());
Douglas Gregor16896c42010-10-28 15:44:59 +00002026
Douglas Gregor0e119552010-07-31 00:40:00 +00002027 // Remap files.
Douglas Gregor7b02b582010-08-20 00:02:33 +00002028 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
Alp Toker1b070d22014-07-07 07:47:20 +00002029 for (const auto &RB : PPOpts.RemappedFileBuffers)
2030 delete RB.second;
2031
Douglas Gregor0e119552010-07-31 00:40:00 +00002032 Invocation->getPreprocessorOpts().clearRemappedFiles();
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00002033 for (const auto &RemappedFile : RemappedFiles) {
2034 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFile.first,
2035 RemappedFile.second);
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00002036 }
Dmitri Gribenkoc444b572014-02-08 00:38:15 +00002037
Douglas Gregorbb420ab2010-08-04 05:53:38 +00002038 // If we have a preamble file lying around, or if we might try to
2039 // build a precompiled preamble, do so now.
Rafael Espindola32482082014-08-18 16:23:45 +00002040 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
Ted Kremenek06b4f912011-10-27 17:55:18 +00002041 if (!getPreambleFile(this).empty() || PreambleRebuildCounter > 0)
Adrian Prantlbb165fb2015-06-20 18:53:08 +00002042 OverrideMainBuffer =
2043 getMainBufferWithPrecompiledPreamble(PCHContainerOps, *Invocation);
2044
Douglas Gregoraa21cc42010-07-19 21:46:24 +00002045 // Clear out the diagnostics state.
Argyrios Kyrtzidisf50f7b22011-11-03 20:28:19 +00002046 getDiagnostics().Reset();
2047 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Argyrios Kyrtzidis462ff352011-11-03 20:57:33 +00002048 if (OverrideMainBuffer)
2049 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
Argyrios Kyrtzidisf50f7b22011-11-03 20:28:19 +00002050
Douglas Gregor4dde7492010-07-23 23:58:40 +00002051 // Parse the sources
Adrian Prantlbb165fb2015-06-20 18:53:08 +00002052 bool Result = Parse(PCHContainerOps, std::move(OverrideMainBuffer));
Rafael Espindola32482082014-08-18 16:23:45 +00002053
Argyrios Kyrtzidis36893372011-10-31 21:25:31 +00002054 // If we're caching global code-completion results, and the top-level
2055 // declarations have changed, clear out the code-completion cache.
2056 if (!Result && ShouldCacheCodeCompletionResults &&
2057 CurrentTopLevelHashValue != CompletionCacheTopLevelHashValue)
2058 CacheCodeCompletionResults();
Douglas Gregordf7a79a2011-02-16 18:16:54 +00002059
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00002060 // We now need to clear out the completion info related to this translation
2061 // unit; it'll be recreated if necessary.
2062 CCTUInfo.reset();
Douglas Gregor3f35bb22011-08-04 20:04:59 +00002063
Douglas Gregor4dde7492010-07-23 23:58:40 +00002064 return Result;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00002065}
Douglas Gregor8e984da2010-08-04 16:47:14 +00002066
Douglas Gregorb14904c2010-08-13 22:48:40 +00002067//----------------------------------------------------------------------------//
2068// Code completion
2069//----------------------------------------------------------------------------//
2070
2071namespace {
2072 /// \brief Code completion consumer that combines the cached code-completion
2073 /// results from an ASTUnit with the code-completion results provided to it,
2074 /// then passes the result on to
2075 class AugmentedCodeCompleteConsumer : public CodeCompleteConsumer {
Richard Smith697cc9e2012-08-14 03:13:00 +00002076 uint64_t NormalContexts;
Douglas Gregorb14904c2010-08-13 22:48:40 +00002077 ASTUnit &AST;
2078 CodeCompleteConsumer &Next;
2079
2080 public:
2081 AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next,
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002082 const CodeCompleteOptions &CodeCompleteOpts)
2083 : CodeCompleteConsumer(CodeCompleteOpts, Next.isOutputBinary()),
2084 AST(AST), Next(Next)
Douglas Gregorb14904c2010-08-13 22:48:40 +00002085 {
2086 // Compute the set of contexts in which we will look when we don't have
2087 // any information about the specific context.
2088 NormalContexts
Richard Smith697cc9e2012-08-14 03:13:00 +00002089 = (1LL << CodeCompletionContext::CCC_TopLevel)
2090 | (1LL << CodeCompletionContext::CCC_ObjCInterface)
2091 | (1LL << CodeCompletionContext::CCC_ObjCImplementation)
2092 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
2093 | (1LL << CodeCompletionContext::CCC_Statement)
2094 | (1LL << CodeCompletionContext::CCC_Expression)
2095 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
2096 | (1LL << CodeCompletionContext::CCC_DotMemberAccess)
2097 | (1LL << CodeCompletionContext::CCC_ArrowMemberAccess)
2098 | (1LL << CodeCompletionContext::CCC_ObjCPropertyAccess)
2099 | (1LL << CodeCompletionContext::CCC_ObjCProtocolName)
2100 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
2101 | (1LL << CodeCompletionContext::CCC_Recovery);
Douglas Gregor5e35d592010-09-14 23:59:36 +00002102
David Blaikiebbafb8a2012-03-11 07:00:24 +00002103 if (AST.getASTContext().getLangOpts().CPlusPlus)
Richard Smith697cc9e2012-08-14 03:13:00 +00002104 NormalContexts |= (1LL << CodeCompletionContext::CCC_EnumTag)
2105 | (1LL << CodeCompletionContext::CCC_UnionTag)
2106 | (1LL << CodeCompletionContext::CCC_ClassOrStructTag);
Douglas Gregorb14904c2010-08-13 22:48:40 +00002107 }
Craig Topperafa7cb32014-03-13 06:07:04 +00002108
2109 void ProcessCodeCompleteResults(Sema &S, CodeCompletionContext Context,
2110 CodeCompletionResult *Results,
2111 unsigned NumResults) override;
2112
2113 void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
2114 OverloadCandidate *Candidates,
2115 unsigned NumCandidates) override {
Douglas Gregorb14904c2010-08-13 22:48:40 +00002116 Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates);
2117 }
Craig Topperafa7cb32014-03-13 06:07:04 +00002118
2119 CodeCompletionAllocator &getAllocator() override {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002120 return Next.getAllocator();
2121 }
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00002122
Craig Topperafa7cb32014-03-13 06:07:04 +00002123 CodeCompletionTUInfo &getCodeCompletionTUInfo() override {
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00002124 return Next.getCodeCompletionTUInfo();
2125 }
Douglas Gregorb14904c2010-08-13 22:48:40 +00002126 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002127}
Douglas Gregord46cf182010-08-16 20:01:48 +00002128
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002129/// \brief Helper function that computes which global names are hidden by the
2130/// local code-completion results.
Ted Kremenek6a153372010-11-07 06:11:36 +00002131static void CalculateHiddenNames(const CodeCompletionContext &Context,
2132 CodeCompletionResult *Results,
2133 unsigned NumResults,
2134 ASTContext &Ctx,
2135 llvm::StringSet<llvm::BumpPtrAllocator> &HiddenNames){
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002136 bool OnlyTagNames = false;
2137 switch (Context.getKind()) {
Douglas Gregor0ac41382010-09-23 23:01:17 +00002138 case CodeCompletionContext::CCC_Recovery:
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002139 case CodeCompletionContext::CCC_TopLevel:
2140 case CodeCompletionContext::CCC_ObjCInterface:
2141 case CodeCompletionContext::CCC_ObjCImplementation:
2142 case CodeCompletionContext::CCC_ObjCIvarList:
2143 case CodeCompletionContext::CCC_ClassStructUnion:
2144 case CodeCompletionContext::CCC_Statement:
2145 case CodeCompletionContext::CCC_Expression:
2146 case CodeCompletionContext::CCC_ObjCMessageReceiver:
Douglas Gregor21325842011-07-07 16:03:39 +00002147 case CodeCompletionContext::CCC_DotMemberAccess:
2148 case CodeCompletionContext::CCC_ArrowMemberAccess:
2149 case CodeCompletionContext::CCC_ObjCPropertyAccess:
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002150 case CodeCompletionContext::CCC_Namespace:
2151 case CodeCompletionContext::CCC_Type:
Douglas Gregorc49f5b22010-08-23 18:23:48 +00002152 case CodeCompletionContext::CCC_Name:
2153 case CodeCompletionContext::CCC_PotentiallyQualifiedName:
Douglas Gregor5e35d592010-09-14 23:59:36 +00002154 case CodeCompletionContext::CCC_ParenthesizedExpression:
Douglas Gregor2c595ad2011-07-30 06:55:39 +00002155 case CodeCompletionContext::CCC_ObjCInterfaceName:
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002156 break;
2157
2158 case CodeCompletionContext::CCC_EnumTag:
2159 case CodeCompletionContext::CCC_UnionTag:
2160 case CodeCompletionContext::CCC_ClassOrStructTag:
2161 OnlyTagNames = true;
2162 break;
2163
2164 case CodeCompletionContext::CCC_ObjCProtocolName:
Douglas Gregor12785102010-08-24 20:21:13 +00002165 case CodeCompletionContext::CCC_MacroName:
2166 case CodeCompletionContext::CCC_MacroNameUse:
Douglas Gregorec00a262010-08-24 22:20:20 +00002167 case CodeCompletionContext::CCC_PreprocessorExpression:
Douglas Gregor0de55ce2010-08-25 18:41:16 +00002168 case CodeCompletionContext::CCC_PreprocessorDirective:
Douglas Gregorea147052010-08-25 18:04:30 +00002169 case CodeCompletionContext::CCC_NaturalLanguage:
Douglas Gregor67c692c2010-08-26 15:07:07 +00002170 case CodeCompletionContext::CCC_SelectorName:
Douglas Gregor28c78432010-08-27 17:35:51 +00002171 case CodeCompletionContext::CCC_TypeQualifiers:
Douglas Gregor0ac41382010-09-23 23:01:17 +00002172 case CodeCompletionContext::CCC_Other:
Douglas Gregor3a69eaf2011-02-18 23:30:37 +00002173 case CodeCompletionContext::CCC_OtherWithMacros:
Douglas Gregor21325842011-07-07 16:03:39 +00002174 case CodeCompletionContext::CCC_ObjCInstanceMessage:
2175 case CodeCompletionContext::CCC_ObjCClassMessage:
2176 case CodeCompletionContext::CCC_ObjCCategoryName:
Douglas Gregor0de55ce2010-08-25 18:41:16 +00002177 // We're looking for nothing, or we're looking for names that cannot
2178 // be hidden.
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002179 return;
2180 }
2181
John McCall276321a2010-08-25 06:19:51 +00002182 typedef CodeCompletionResult Result;
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002183 for (unsigned I = 0; I != NumResults; ++I) {
2184 if (Results[I].Kind != Result::RK_Declaration)
2185 continue;
2186
2187 unsigned IDNS
2188 = Results[I].Declaration->getUnderlyingDecl()->getIdentifierNamespace();
2189
2190 bool Hiding = false;
2191 if (OnlyTagNames)
2192 Hiding = (IDNS & Decl::IDNS_Tag);
2193 else {
2194 unsigned HiddenIDNS = (Decl::IDNS_Type | Decl::IDNS_Member |
Douglas Gregor59cab552010-08-16 23:05:20 +00002195 Decl::IDNS_Namespace | Decl::IDNS_Ordinary |
2196 Decl::IDNS_NonMemberOperator);
David Blaikiebbafb8a2012-03-11 07:00:24 +00002197 if (Ctx.getLangOpts().CPlusPlus)
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002198 HiddenIDNS |= Decl::IDNS_Tag;
2199 Hiding = (IDNS & HiddenIDNS);
2200 }
2201
2202 if (!Hiding)
2203 continue;
2204
2205 DeclarationName Name = Results[I].Declaration->getDeclName();
2206 if (IdentifierInfo *Identifier = Name.getAsIdentifierInfo())
2207 HiddenNames.insert(Identifier->getName());
2208 else
2209 HiddenNames.insert(Name.getAsString());
2210 }
2211}
2212
2213
Douglas Gregord46cf182010-08-16 20:01:48 +00002214void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &S,
2215 CodeCompletionContext Context,
John McCall276321a2010-08-25 06:19:51 +00002216 CodeCompletionResult *Results,
Douglas Gregord46cf182010-08-16 20:01:48 +00002217 unsigned NumResults) {
2218 // Merge the results we were given with the results we cached.
2219 bool AddedResult = false;
Richard Smith697cc9e2012-08-14 03:13:00 +00002220 uint64_t InContexts =
2221 Context.getKind() == CodeCompletionContext::CCC_Recovery
2222 ? NormalContexts : (1LL << Context.getKind());
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002223 // Contains the set of names that are hidden by "local" completion results.
Ted Kremenek6a153372010-11-07 06:11:36 +00002224 llvm::StringSet<llvm::BumpPtrAllocator> HiddenNames;
John McCall276321a2010-08-25 06:19:51 +00002225 typedef CodeCompletionResult Result;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002226 SmallVector<Result, 8> AllResults;
Douglas Gregord46cf182010-08-16 20:01:48 +00002227 for (ASTUnit::cached_completion_iterator
Douglas Gregordf239672010-08-16 21:23:13 +00002228 C = AST.cached_completion_begin(),
2229 CEnd = AST.cached_completion_end();
Douglas Gregord46cf182010-08-16 20:01:48 +00002230 C != CEnd; ++C) {
2231 // If the context we are in matches any of the contexts we are
2232 // interested in, we'll add this result.
2233 if ((C->ShowInContexts & InContexts) == 0)
2234 continue;
2235
2236 // If we haven't added any results previously, do so now.
2237 if (!AddedResult) {
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002238 CalculateHiddenNames(Context, Results, NumResults, S.Context,
2239 HiddenNames);
Douglas Gregord46cf182010-08-16 20:01:48 +00002240 AllResults.insert(AllResults.end(), Results, Results + NumResults);
2241 AddedResult = true;
2242 }
2243
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002244 // Determine whether this global completion result is hidden by a local
2245 // completion result. If so, skip it.
2246 if (C->Kind != CXCursor_MacroDefinition &&
2247 HiddenNames.count(C->Completion->getTypedText()))
2248 continue;
2249
Douglas Gregord46cf182010-08-16 20:01:48 +00002250 // Adjust priority based on similar type classes.
2251 unsigned Priority = C->Priority;
Douglas Gregor12785102010-08-24 20:21:13 +00002252 CodeCompletionString *Completion = C->Completion;
Douglas Gregord46cf182010-08-16 20:01:48 +00002253 if (!Context.getPreferredType().isNull()) {
2254 if (C->Kind == CXCursor_MacroDefinition) {
2255 Priority = getMacroUsagePriority(C->Completion->getTypedText(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00002256 S.getLangOpts(),
Douglas Gregor12785102010-08-24 20:21:13 +00002257 Context.getPreferredType()->isAnyPointerType());
Douglas Gregord46cf182010-08-16 20:01:48 +00002258 } else if (C->Type) {
2259 CanQualType Expected
Douglas Gregordf239672010-08-16 21:23:13 +00002260 = S.Context.getCanonicalType(
Douglas Gregord46cf182010-08-16 20:01:48 +00002261 Context.getPreferredType().getUnqualifiedType());
2262 SimplifiedTypeClass ExpectedSTC = getSimplifiedTypeClass(Expected);
2263 if (ExpectedSTC == C->TypeClass) {
2264 // We know this type is similar; check for an exact match.
2265 llvm::StringMap<unsigned> &CachedCompletionTypes
Douglas Gregordf239672010-08-16 21:23:13 +00002266 = AST.getCachedCompletionTypes();
Douglas Gregord46cf182010-08-16 20:01:48 +00002267 llvm::StringMap<unsigned>::iterator Pos
Douglas Gregordf239672010-08-16 21:23:13 +00002268 = CachedCompletionTypes.find(QualType(Expected).getAsString());
Douglas Gregord46cf182010-08-16 20:01:48 +00002269 if (Pos != CachedCompletionTypes.end() && Pos->second == C->Type)
2270 Priority /= CCF_ExactTypeMatch;
2271 else
2272 Priority /= CCF_SimilarTypeMatch;
2273 }
2274 }
2275 }
2276
Douglas Gregor12785102010-08-24 20:21:13 +00002277 // Adjust the completion string, if required.
2278 if (C->Kind == CXCursor_MacroDefinition &&
2279 Context.getKind() == CodeCompletionContext::CCC_MacroNameUse) {
2280 // Create a new code-completion string that just contains the
2281 // macro name, without its arguments.
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00002282 CodeCompletionBuilder Builder(getAllocator(), getCodeCompletionTUInfo(),
2283 CCP_CodePattern, C->Availability);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002284 Builder.AddTypedTextChunk(C->Completion->getTypedText());
Douglas Gregor8850aa32010-08-25 18:03:13 +00002285 Priority = CCP_CodePattern;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002286 Completion = Builder.TakeString();
Douglas Gregor12785102010-08-24 20:21:13 +00002287 }
2288
Argyrios Kyrtzidis5c8b1cd2012-09-27 00:24:09 +00002289 AllResults.push_back(Result(Completion, Priority, C->Kind,
Douglas Gregorf757a122010-08-23 23:00:57 +00002290 C->Availability));
Douglas Gregord46cf182010-08-16 20:01:48 +00002291 }
2292
2293 // If we did not add any cached completion results, just forward the
2294 // results we were given to the next consumer.
2295 if (!AddedResult) {
2296 Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
2297 return;
2298 }
Douglas Gregor49f67ce2010-08-26 13:48:20 +00002299
Douglas Gregord46cf182010-08-16 20:01:48 +00002300 Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
2301 AllResults.size());
2302}
2303
Adrian Prantlbb165fb2015-06-20 18:53:08 +00002304void ASTUnit::CodeComplete(
2305 StringRef File, unsigned Line, unsigned Column,
2306 ArrayRef<RemappedFile> RemappedFiles, bool IncludeMacros,
2307 bool IncludeCodePatterns, bool IncludeBriefComments,
2308 CodeCompleteConsumer &Consumer,
2309 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
2310 DiagnosticsEngine &Diag, LangOptions &LangOpts, SourceManager &SourceMgr,
2311 FileManager &FileMgr, SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
2312 SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers) {
Ted Kremenek5e14d392011-03-21 18:40:17 +00002313 if (!Invocation)
Douglas Gregor8e984da2010-08-04 16:47:14 +00002314 return;
2315
Douglas Gregor16896c42010-10-28 15:44:59 +00002316 SimpleTimer CompletionTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00002317 CompletionTimer.setOutput("Code completion @ " + File + ":" +
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002318 Twine(Line) + ":" + Twine(Column));
Douglas Gregor028d3e42010-08-09 20:45:32 +00002319
Dylan Noblesmithc95d8192012-02-20 14:00:23 +00002320 IntrusiveRefCntPtr<CompilerInvocation>
Ted Kremenek5e14d392011-03-21 18:40:17 +00002321 CCInvocation(new CompilerInvocation(*Invocation));
2322
2323 FrontendOptions &FrontendOpts = CCInvocation->getFrontendOpts();
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002324 CodeCompleteOptions &CodeCompleteOpts = FrontendOpts.CodeCompleteOpts;
Ted Kremenek5e14d392011-03-21 18:40:17 +00002325 PreprocessorOptions &PreprocessorOpts = CCInvocation->getPreprocessorOpts();
Douglas Gregorb68bc592010-08-05 09:09:23 +00002326
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002327 CodeCompleteOpts.IncludeMacros = IncludeMacros &&
2328 CachedCompletionResults.empty();
2329 CodeCompleteOpts.IncludeCodePatterns = IncludeCodePatterns;
2330 CodeCompleteOpts.IncludeGlobals = CachedCompletionResults.empty();
2331 CodeCompleteOpts.IncludeBriefComments = IncludeBriefComments;
2332
2333 assert(IncludeBriefComments == this->IncludeBriefCommentsInCodeCompletion);
2334
Douglas Gregor8e984da2010-08-04 16:47:14 +00002335 FrontendOpts.CodeCompletionAt.FileName = File;
2336 FrontendOpts.CodeCompletionAt.Line = Line;
2337 FrontendOpts.CodeCompletionAt.Column = Column;
2338
2339 // Set the language options appropriately.
Ted Kremenek8cf47df2011-11-17 23:01:24 +00002340 LangOpts = *CCInvocation->getLangOpts();
Douglas Gregor8e984da2010-08-04 16:47:14 +00002341
Argyrios Kyrtzidis06e8d692014-10-31 16:44:32 +00002342 // Spell-checking and warnings are wasteful during code-completion.
2343 LangOpts.SpellChecking = false;
2344 CCInvocation->getDiagnosticOpts().IgnoreWarnings = true;
2345
Adrian Prantlbb165fb2015-06-20 18:53:08 +00002346 std::unique_ptr<CompilerInstance> Clang(
2347 new CompilerInstance(PCHContainerOps));
Ted Kremenek84de4a12011-03-21 18:40:07 +00002348
2349 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00002350 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
2351 CICleanup(Clang.get());
Ted Kremenek84de4a12011-03-21 18:40:07 +00002352
Ted Kremenek5e14d392011-03-21 18:40:17 +00002353 Clang->setInvocation(&*CCInvocation);
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00002354 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
Douglas Gregor8e984da2010-08-04 16:47:14 +00002355
2356 // Set up diagnostics, capturing any diagnostics produced.
Ted Kremenek84de4a12011-03-21 18:40:07 +00002357 Clang->setDiagnostics(&Diag);
Douglas Gregor8e984da2010-08-04 16:47:14 +00002358 CaptureDroppedDiagnostics Capture(true,
Ted Kremenek84de4a12011-03-21 18:40:07 +00002359 Clang->getDiagnostics(),
Douglas Gregor8e984da2010-08-04 16:47:14 +00002360 StoredDiagnostics);
Manuel Klimekbe0474c2013-07-18 14:23:12 +00002361 ProcessWarningOptions(Diag, CCInvocation->getDiagnosticOpts());
Douglas Gregor8e984da2010-08-04 16:47:14 +00002362
2363 // Create the target instance.
Alp Toker80758082014-07-06 05:26:44 +00002364 Clang->setTarget(TargetInfo::CreateTargetInfo(
2365 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
Ted Kremenek84de4a12011-03-21 18:40:07 +00002366 if (!Clang->hasTarget()) {
Craig Topper49a27902014-05-22 04:46:25 +00002367 Clang->setInvocation(nullptr);
Douglas Gregor2dd19f12010-08-18 22:29:43 +00002368 return;
Douglas Gregor8e984da2010-08-04 16:47:14 +00002369 }
2370
2371 // Inform the target of the language options.
2372 //
2373 // FIXME: We shouldn't need to do this, the target should be immutable once
2374 // created. This complexity should be lifted elsewhere.
Alp Toker74437972014-07-06 05:14:24 +00002375 Clang->getTarget().adjust(Clang->getLangOpts());
Douglas Gregor8e984da2010-08-04 16:47:14 +00002376
Ted Kremenek84de4a12011-03-21 18:40:07 +00002377 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Douglas Gregor8e984da2010-08-04 16:47:14 +00002378 "Invocation must have exactly one source file!");
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00002379 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
Douglas Gregor8e984da2010-08-04 16:47:14 +00002380 "FIXME: AST inputs not yet supported here!");
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00002381 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
Douglas Gregor8e984da2010-08-04 16:47:14 +00002382 "IR inputs not support here!");
2383
2384
2385 // Use the source and file managers that we were given.
Ted Kremenek84de4a12011-03-21 18:40:07 +00002386 Clang->setFileManager(&FileMgr);
2387 Clang->setSourceManager(&SourceMgr);
Douglas Gregor8e984da2010-08-04 16:47:14 +00002388
2389 // Remap files.
2390 PreprocessorOpts.clearRemappedFiles();
Douglas Gregord8a5dba2010-08-04 17:07:00 +00002391 PreprocessorOpts.RetainRemappedFileBuffers = true;
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00002392 for (const auto &RemappedFile : RemappedFiles) {
2393 PreprocessorOpts.addRemappedFile(RemappedFile.first, RemappedFile.second);
2394 OwnedBuffers.push_back(RemappedFile.second);
Douglas Gregorb97b6662010-08-20 00:59:43 +00002395 }
Dmitri Gribenkoc444b572014-02-08 00:38:15 +00002396
Douglas Gregorb14904c2010-08-13 22:48:40 +00002397 // Use the code completion consumer we were given, but adding any cached
2398 // code-completion results.
Douglas Gregore9186e62010-11-29 16:13:56 +00002399 AugmentedCodeCompleteConsumer *AugmentedConsumer
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002400 = new AugmentedCodeCompleteConsumer(*this, Consumer, CodeCompleteOpts);
Ted Kremenek84de4a12011-03-21 18:40:07 +00002401 Clang->setCodeCompletionConsumer(AugmentedConsumer);
Douglas Gregor8e984da2010-08-04 16:47:14 +00002402
Douglas Gregor028d3e42010-08-09 20:45:32 +00002403 // If we have a precompiled preamble, try to use it. We only allow
2404 // the use of the precompiled preamble if we're if the completion
2405 // point is within the main file, after the end of the precompiled
2406 // preamble.
Rafael Espindola2346a372014-08-18 18:47:08 +00002407 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
Ted Kremenek06b4f912011-10-27 17:55:18 +00002408 if (!getPreambleFile(this).empty()) {
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00002409 std::string CompleteFilePath(File);
Rafael Espindola073ff102013-07-29 21:26:52 +00002410 llvm::sys::fs::UniqueID CompleteFileID;
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00002411
Rafael Espindolabe3b12b02013-06-20 15:12:38 +00002412 if (!llvm::sys::fs::getUniqueID(CompleteFilePath, CompleteFileID)) {
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00002413 std::string MainPath(OriginalSourceFile);
Rafael Espindola073ff102013-07-29 21:26:52 +00002414 llvm::sys::fs::UniqueID MainID;
Rafael Espindolabe3b12b02013-06-20 15:12:38 +00002415 if (!llvm::sys::fs::getUniqueID(MainPath, MainID)) {
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00002416 if (CompleteFileID == MainID && Line > 1)
Rafael Espindola2346a372014-08-18 18:47:08 +00002417 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(
Adrian Prantlbb165fb2015-06-20 18:53:08 +00002418 PCHContainerOps, *CCInvocation, false, Line - 1);
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00002419 }
2420 }
Douglas Gregor028d3e42010-08-09 20:45:32 +00002421 }
2422
2423 // If the main file has been overridden due to the use of a preamble,
2424 // make that override happen and introduce the preamble.
2425 if (OverrideMainBuffer) {
Rafael Espindola2346a372014-08-18 18:47:08 +00002426 PreprocessorOpts.addRemappedFile(OriginalSourceFile,
2427 OverrideMainBuffer.get());
Douglas Gregor028d3e42010-08-09 20:45:32 +00002428 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
2429 PreprocessorOpts.PrecompiledPreambleBytes.second
2430 = PreambleEndsAtStartOfLine;
Ted Kremenek06b4f912011-10-27 17:55:18 +00002431 PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
Douglas Gregor028d3e42010-08-09 20:45:32 +00002432 PreprocessorOpts.DisablePCHValidation = true;
Rafael Espindola2346a372014-08-18 18:47:08 +00002433
2434 OwnedBuffers.push_back(OverrideMainBuffer.release());
Douglas Gregor7b02b582010-08-20 00:02:33 +00002435 } else {
2436 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
2437 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregor028d3e42010-08-09 20:45:32 +00002438 }
2439
Argyrios Kyrtzidis870704f2012-11-02 22:18:44 +00002440 // Disable the preprocessing record if modules are not enabled.
2441 if (!Clang->getLangOpts().Modules)
2442 PreprocessorOpts.DetailedRecord = false;
Ahmed Charlesb8984322014-03-07 20:03:18 +00002443
2444 std::unique_ptr<SyntaxOnlyAction> Act;
Douglas Gregor8e984da2010-08-04 16:47:14 +00002445 Act.reset(new SyntaxOnlyAction);
Douglas Gregor32fbe312012-01-20 16:28:04 +00002446 if (Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
Douglas Gregor8e984da2010-08-04 16:47:14 +00002447 Act->Execute();
2448 Act->EndSourceFile();
2449 }
Douglas Gregor8e984da2010-08-04 16:47:14 +00002450}
Douglas Gregore9386682010-08-13 05:36:37 +00002451
Argyrios Kyrtzidis39a76382012-09-26 16:39:46 +00002452bool ASTUnit::Save(StringRef File) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00002453 if (HadModuleLoaderFatalFailure)
2454 return true;
2455
Argyrios Kyrtzidis55e75572011-07-21 18:44:49 +00002456 // Write to a temporary file and later rename it to the actual file, to avoid
2457 // possible race conditions.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00002458 SmallString<128> TempPath;
Argyrios Kyrtzidis08a2bfd2011-07-28 00:45:10 +00002459 TempPath = File;
2460 TempPath += "-%%%%%%%%";
2461 int fd;
Yaron Keren92e1b622015-03-18 10:17:07 +00002462 if (llvm::sys::fs::createUniqueFile(TempPath, fd, TempPath))
Argyrios Kyrtzidis39a76382012-09-26 16:39:46 +00002463 return true;
Argyrios Kyrtzidis55e75572011-07-21 18:44:49 +00002464
Douglas Gregore9386682010-08-13 05:36:37 +00002465 // FIXME: Can we somehow regenerate the stat cache here, or do we need to
2466 // unconditionally create a stat cache when we parse the file?
Argyrios Kyrtzidis08a2bfd2011-07-28 00:45:10 +00002467 llvm::raw_fd_ostream Out(fd, /*shouldClose=*/true);
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00002468
2469 serialize(Out);
2470 Out.close();
Argyrios Kyrtzidiseeea16a2012-03-13 02:17:06 +00002471 if (Out.has_error()) {
2472 Out.clear_error();
Argyrios Kyrtzidis39a76382012-09-26 16:39:46 +00002473 return true;
Argyrios Kyrtzidiseeea16a2012-03-13 02:17:06 +00002474 }
Argyrios Kyrtzidis55e75572011-07-21 18:44:49 +00002475
Yaron Keren92e1b622015-03-18 10:17:07 +00002476 if (llvm::sys::fs::rename(TempPath, File)) {
2477 llvm::sys::fs::remove(TempPath);
Argyrios Kyrtzidis39a76382012-09-26 16:39:46 +00002478 return true;
Argyrios Kyrtzidis55e75572011-07-21 18:44:49 +00002479 }
2480
Argyrios Kyrtzidis39a76382012-09-26 16:39:46 +00002481 return false;
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00002482}
2483
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00002484static bool serializeUnit(ASTWriter &Writer,
2485 SmallVectorImpl<char> &Buffer,
2486 Sema &S,
2487 bool hasErrors,
2488 raw_ostream &OS) {
Craig Topper49a27902014-05-22 04:46:25 +00002489 Writer.WriteAST(S, std::string(), nullptr, "", hasErrors);
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00002490
2491 // Write the generated bitstream to "Out".
2492 if (!Buffer.empty())
2493 OS.write(Buffer.data(), Buffer.size());
2494
2495 return false;
2496}
2497
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002498bool ASTUnit::serialize(raw_ostream &OS) {
Argyrios Kyrtzidis4a280ff2012-03-07 01:51:17 +00002499 bool hasErrors = getDiagnostics().hasErrorOccurred();
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00002500
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00002501 if (WriterData)
2502 return serializeUnit(WriterData->Writer, WriterData->Buffer,
2503 getSema(), hasErrors, OS);
2504
Daniel Dunbar9a963862012-02-29 20:31:23 +00002505 SmallString<128> Buffer;
Douglas Gregore9386682010-08-13 05:36:37 +00002506 llvm::BitstreamWriter Stream(Buffer);
Sebastian Redl55c0ad52010-08-18 23:56:21 +00002507 ASTWriter Writer(Stream);
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00002508 return serializeUnit(Writer, Buffer, getSema(), hasErrors, OS);
Douglas Gregore9386682010-08-13 05:36:37 +00002509}
Douglas Gregor925296b2011-07-19 16:10:42 +00002510
2511typedef ContinuousRangeMap<unsigned, int, 2> SLocRemap;
2512
Douglas Gregor925296b2011-07-19 16:10:42 +00002513void ASTUnit::TranslateStoredDiagnostics(
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002514 FileManager &FileMgr,
Douglas Gregor925296b2011-07-19 16:10:42 +00002515 SourceManager &SrcMgr,
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002516 const SmallVectorImpl<StandaloneDiagnostic> &Diags,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002517 SmallVectorImpl<StoredDiagnostic> &Out) {
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002518 // Map the standalone diagnostic into the new source manager. We also need to
2519 // remap all the locations to the new view. This includes the diag location,
2520 // any associated source ranges, and the source ranges of associated fix-its.
Douglas Gregor925296b2011-07-19 16:10:42 +00002521 // FIXME: There should be a cleaner way to do this.
2522
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002523 SmallVector<StoredDiagnostic, 4> Result;
Douglas Gregor925296b2011-07-19 16:10:42 +00002524 Result.reserve(Diags.size());
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00002525 for (const StandaloneDiagnostic &SD : Diags) {
Douglas Gregor925296b2011-07-19 16:10:42 +00002526 // Rebuild the StoredDiagnostic.
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002527 if (SD.Filename.empty())
2528 continue;
2529 const FileEntry *FE = FileMgr.getFile(SD.Filename);
2530 if (!FE)
2531 continue;
2532 FileID FID = SrcMgr.translateFile(FE);
2533 SourceLocation FileLoc = SrcMgr.getLocForStartOfFile(FID);
2534 if (FileLoc.isInvalid())
2535 continue;
2536 SourceLocation L = FileLoc.getLocWithOffset(SD.LocOffset);
Douglas Gregor925296b2011-07-19 16:10:42 +00002537 FullSourceLoc Loc(L, SrcMgr);
2538
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002539 SmallVector<CharSourceRange, 4> Ranges;
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002540 Ranges.reserve(SD.Ranges.size());
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00002541 for (const auto &Range : SD.Ranges) {
2542 SourceLocation BL = FileLoc.getLocWithOffset(Range.first);
2543 SourceLocation EL = FileLoc.getLocWithOffset(Range.second);
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002544 Ranges.push_back(CharSourceRange::getCharRange(BL, EL));
Douglas Gregor925296b2011-07-19 16:10:42 +00002545 }
2546
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002547 SmallVector<FixItHint, 2> FixIts;
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002548 FixIts.reserve(SD.FixIts.size());
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00002549 for (const StandaloneFixIt &FixIt : SD.FixIts) {
Douglas Gregor925296b2011-07-19 16:10:42 +00002550 FixIts.push_back(FixItHint());
2551 FixItHint &FH = FixIts.back();
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00002552 FH.CodeToInsert = FixIt.CodeToInsert;
2553 SourceLocation BL = FileLoc.getLocWithOffset(FixIt.RemoveRange.first);
2554 SourceLocation EL = FileLoc.getLocWithOffset(FixIt.RemoveRange.second);
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002555 FH.RemoveRange = CharSourceRange::getCharRange(BL, EL);
Douglas Gregor925296b2011-07-19 16:10:42 +00002556 }
2557
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002558 Result.push_back(StoredDiagnostic(SD.Level, SD.ID,
2559 SD.Message, Loc, Ranges, FixIts));
Douglas Gregor925296b2011-07-19 16:10:42 +00002560 }
2561 Result.swap(Out);
2562}
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002563
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00002564void ASTUnit::addFileLevelDecl(Decl *D) {
2565 assert(D);
Douglas Gregor61d63d02011-11-07 18:53:57 +00002566
2567 // We only care about local declarations.
2568 if (D->isFromASTFile())
2569 return;
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00002570
2571 SourceManager &SM = *SourceMgr;
2572 SourceLocation Loc = D->getLocation();
2573 if (Loc.isInvalid() || !SM.isLocalSourceLocation(Loc))
2574 return;
2575
2576 // We only keep track of the file-level declarations of each file.
2577 if (!D->getLexicalDeclContext()->isFileContext())
2578 return;
2579
2580 SourceLocation FileLoc = SM.getFileLoc(Loc);
2581 assert(SM.isLocalSourceLocation(FileLoc));
2582 FileID FID;
2583 unsigned Offset;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002584 std::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc);
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00002585 if (FID.isInvalid())
2586 return;
2587
2588 LocDeclsTy *&Decls = FileDecls[FID];
2589 if (!Decls)
2590 Decls = new LocDeclsTy();
2591
2592 std::pair<unsigned, Decl *> LocDecl(Offset, D);
2593
2594 if (Decls->empty() || Decls->back().first <= Offset) {
2595 Decls->push_back(LocDecl);
2596 return;
2597 }
2598
Benjamin Kramer45025c02013-08-24 13:22:59 +00002599 LocDeclsTy::iterator I = std::upper_bound(Decls->begin(), Decls->end(),
2600 LocDecl, llvm::less_first());
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00002601
2602 Decls->insert(I, LocDecl);
2603}
2604
Argyrios Kyrtzidise9681522011-11-03 02:20:32 +00002605void ASTUnit::findFileRegionDecls(FileID File, unsigned Offset, unsigned Length,
2606 SmallVectorImpl<Decl *> &Decls) {
2607 if (File.isInvalid())
2608 return;
2609
2610 if (SourceMgr->isLoadedFileID(File)) {
2611 assert(Ctx->getExternalSource() && "No external source!");
2612 return Ctx->getExternalSource()->FindFileRegionDecls(File, Offset, Length,
2613 Decls);
2614 }
2615
2616 FileDeclsTy::iterator I = FileDecls.find(File);
2617 if (I == FileDecls.end())
2618 return;
2619
2620 LocDeclsTy &LocDecls = *I->second;
2621 if (LocDecls.empty())
2622 return;
2623
Benjamin Kramere3e855b2013-08-24 13:12:34 +00002624 LocDeclsTy::iterator BeginIt =
2625 std::lower_bound(LocDecls.begin(), LocDecls.end(),
Craig Topper49a27902014-05-22 04:46:25 +00002626 std::make_pair(Offset, (Decl *)nullptr),
2627 llvm::less_first());
Argyrios Kyrtzidise9681522011-11-03 02:20:32 +00002628 if (BeginIt != LocDecls.begin())
2629 --BeginIt;
2630
Argyrios Kyrtzidis8ad3bab2011-11-23 20:27:36 +00002631 // If we are pointing at a top-level decl inside an objc container, we need
2632 // to backtrack until we find it otherwise we will fail to report that the
2633 // region overlaps with an objc container.
2634 while (BeginIt != LocDecls.begin() &&
2635 BeginIt->second->isTopLevelDeclInObjCContainer())
2636 --BeginIt;
2637
Benjamin Kramere3e855b2013-08-24 13:12:34 +00002638 LocDeclsTy::iterator EndIt = std::upper_bound(
2639 LocDecls.begin(), LocDecls.end(),
Craig Topper49a27902014-05-22 04:46:25 +00002640 std::make_pair(Offset + Length, (Decl *)nullptr), llvm::less_first());
Argyrios Kyrtzidise9681522011-11-03 02:20:32 +00002641 if (EndIt != LocDecls.end())
2642 ++EndIt;
2643
2644 for (LocDeclsTy::iterator DIt = BeginIt; DIt != EndIt; ++DIt)
2645 Decls.push_back(DIt->second);
2646}
2647
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002648SourceLocation ASTUnit::getLocation(const FileEntry *File,
2649 unsigned Line, unsigned Col) const {
2650 const SourceManager &SM = getSourceManager();
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00002651 SourceLocation Loc = SM.translateFileLineCol(File, Line, Col);
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002652 return SM.getMacroArgExpandedLocation(Loc);
2653}
2654
2655SourceLocation ASTUnit::getLocation(const FileEntry *File,
2656 unsigned Offset) const {
2657 const SourceManager &SM = getSourceManager();
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00002658 SourceLocation FileLoc = SM.translateFileLineCol(File, 1, 1);
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002659 return SM.getMacroArgExpandedLocation(FileLoc.getLocWithOffset(Offset));
2660}
2661
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00002662/// \brief If \arg Loc is a loaded location from the preamble, returns
2663/// the corresponding local location of the main file, otherwise it returns
2664/// \arg Loc.
2665SourceLocation ASTUnit::mapLocationFromPreamble(SourceLocation Loc) {
2666 FileID PreambleID;
2667 if (SourceMgr)
2668 PreambleID = SourceMgr->getPreambleFileID();
2669
2670 if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2671 return Loc;
2672
2673 unsigned Offs;
2674 if (SourceMgr->isInFileID(Loc, PreambleID, &Offs) && Offs < Preamble.size()) {
2675 SourceLocation FileLoc
2676 = SourceMgr->getLocForStartOfFile(SourceMgr->getMainFileID());
2677 return FileLoc.getLocWithOffset(Offs);
2678 }
2679
2680 return Loc;
2681}
2682
2683/// \brief If \arg Loc is a local location of the main file but inside the
2684/// preamble chunk, returns the corresponding loaded location from the
2685/// preamble, otherwise it returns \arg Loc.
2686SourceLocation ASTUnit::mapLocationToPreamble(SourceLocation Loc) {
2687 FileID PreambleID;
2688 if (SourceMgr)
2689 PreambleID = SourceMgr->getPreambleFileID();
2690
2691 if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2692 return Loc;
2693
2694 unsigned Offs;
2695 if (SourceMgr->isInFileID(Loc, SourceMgr->getMainFileID(), &Offs) &&
2696 Offs < Preamble.size()) {
2697 SourceLocation FileLoc = SourceMgr->getLocForStartOfFile(PreambleID);
2698 return FileLoc.getLocWithOffset(Offs);
2699 }
2700
2701 return Loc;
2702}
2703
Argyrios Kyrtzidis429ec022011-10-25 00:29:50 +00002704bool ASTUnit::isInPreambleFileID(SourceLocation Loc) {
2705 FileID FID;
2706 if (SourceMgr)
2707 FID = SourceMgr->getPreambleFileID();
2708
2709 if (Loc.isInvalid() || FID.isInvalid())
2710 return false;
2711
2712 return SourceMgr->isInFileID(Loc, FID);
2713}
2714
2715bool ASTUnit::isInMainFileID(SourceLocation Loc) {
2716 FileID FID;
2717 if (SourceMgr)
2718 FID = SourceMgr->getMainFileID();
2719
2720 if (Loc.isInvalid() || FID.isInvalid())
2721 return false;
2722
2723 return SourceMgr->isInFileID(Loc, FID);
2724}
2725
2726SourceLocation ASTUnit::getEndOfPreambleFileID() {
2727 FileID FID;
2728 if (SourceMgr)
2729 FID = SourceMgr->getPreambleFileID();
2730
2731 if (FID.isInvalid())
2732 return SourceLocation();
2733
2734 return SourceMgr->getLocForEndOfFile(FID);
2735}
2736
2737SourceLocation ASTUnit::getStartOfMainFileID() {
2738 FileID FID;
2739 if (SourceMgr)
2740 FID = SourceMgr->getMainFileID();
2741
2742 if (FID.isInvalid())
2743 return SourceLocation();
2744
2745 return SourceMgr->getLocForStartOfFile(FID);
2746}
2747
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00002748llvm::iterator_range<PreprocessingRecord::iterator>
Argyrios Kyrtzidisd4fcf5802012-10-02 16:10:51 +00002749ASTUnit::getLocalPreprocessingEntities() const {
2750 if (isMainFileAST()) {
2751 serialization::ModuleFile &
2752 Mod = Reader->getModuleManager().getPrimaryModule();
2753 return Reader->getModulePreprocessedEntities(Mod);
2754 }
2755
2756 if (PreprocessingRecord *PPRec = PP->getPreprocessingRecord())
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00002757 return llvm::make_range(PPRec->local_begin(), PPRec->local_end());
Argyrios Kyrtzidisd4fcf5802012-10-02 16:10:51 +00002758
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00002759 return llvm::make_range(PreprocessingRecord::iterator(),
2760 PreprocessingRecord::iterator());
Argyrios Kyrtzidisd4fcf5802012-10-02 16:10:51 +00002761}
2762
Argyrios Kyrtzidise514b202012-10-03 01:58:28 +00002763bool ASTUnit::visitLocalTopLevelDecls(void *context, DeclVisitorFn Fn) {
Argyrios Kyrtzidis10e78462012-10-02 21:09:13 +00002764 if (isMainFileAST()) {
2765 serialization::ModuleFile &
2766 Mod = Reader->getModuleManager().getPrimaryModule();
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00002767 for (const Decl *D : Reader->getModuleFileLevelDecls(Mod)) {
2768 if (!Fn(context, D))
Argyrios Kyrtzidis10e78462012-10-02 21:09:13 +00002769 return false;
2770 }
2771
2772 return true;
2773 }
2774
2775 for (ASTUnit::top_level_iterator TL = top_level_begin(),
2776 TLEnd = top_level_end();
2777 TL != TLEnd; ++TL) {
2778 if (!Fn(context, *TL))
2779 return false;
2780 }
2781
2782 return true;
2783}
2784
Argyrios Kyrtzidisf484b132012-10-03 21:05:51 +00002785const FileEntry *ASTUnit::getPCHFile() {
2786 if (!Reader)
Craig Topper49a27902014-05-22 04:46:25 +00002787 return nullptr;
Argyrios Kyrtzidisf484b132012-10-03 21:05:51 +00002788
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00002789 serialization::ModuleFile *Mod = nullptr;
2790 Reader->getModuleManager().visit([&Mod](serialization::ModuleFile &M) {
2791 switch (M.Kind) {
2792 case serialization::MK_ImplicitModule:
2793 case serialization::MK_ExplicitModule:
2794 return true; // skip dependencies.
2795 case serialization::MK_PCH:
2796 Mod = &M;
2797 return true; // found it.
2798 case serialization::MK_Preamble:
2799 return false; // look in dependencies.
2800 case serialization::MK_MainFile:
2801 return false; // look in dependencies.
2802 }
2803
2804 return true;
2805 });
2806 if (Mod)
2807 return Mod->File;
Argyrios Kyrtzidisf484b132012-10-03 21:05:51 +00002808
Craig Topper49a27902014-05-22 04:46:25 +00002809 return nullptr;
Argyrios Kyrtzidisf484b132012-10-03 21:05:51 +00002810}
2811
Argyrios Kyrtzidise445c722012-10-10 02:12:47 +00002812bool ASTUnit::isModuleFile() {
2813 return isMainFileAST() && !ASTFileLangOpts.CurrentModule.empty();
2814}
2815
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002816void ASTUnit::PreambleData::countLines() const {
2817 NumLines = 0;
2818 if (empty())
2819 return;
2820
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00002821 NumLines = std::count(Buffer.begin(), Buffer.end(), '\n');
2822
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002823 if (Buffer.back() != '\n')
2824 ++NumLines;
2825}
Argyrios Kyrtzidisebf01362011-10-10 21:57:12 +00002826
2827#ifndef NDEBUG
2828ASTUnit::ConcurrencyState::ConcurrencyState() {
2829 Mutex = new llvm::sys::MutexImpl(/*recursive=*/true);
2830}
2831
2832ASTUnit::ConcurrencyState::~ConcurrencyState() {
2833 delete static_cast<llvm::sys::MutexImpl *>(Mutex);
2834}
2835
2836void ASTUnit::ConcurrencyState::start() {
2837 bool acquired = static_cast<llvm::sys::MutexImpl *>(Mutex)->tryacquire();
2838 assert(acquired && "Concurrent access to ASTUnit!");
2839}
2840
2841void ASTUnit::ConcurrencyState::finish() {
2842 static_cast<llvm::sys::MutexImpl *>(Mutex)->release();
2843}
2844
2845#else // NDEBUG
2846
Alp Tokerb159c132013-11-22 07:49:39 +00002847ASTUnit::ConcurrencyState::ConcurrencyState() { Mutex = 0; }
Argyrios Kyrtzidisebf01362011-10-10 21:57:12 +00002848ASTUnit::ConcurrencyState::~ConcurrencyState() {}
2849void ASTUnit::ConcurrencyState::start() {}
2850void ASTUnit::ConcurrencyState::finish() {}
2851
2852#endif