blob: a3998fa351de7bd8b10120b803e50891c1b82019 [file] [log] [blame]
Argyrios Kyrtzidis4b562cf2009-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 Kyrtzidis0853a022009-06-20 08:08:23 +000014#include "clang/Frontend/ASTUnit.h"
Daniel Dunbar521bf9c2009-12-01 09:51:01 +000015#include "clang/AST/ASTConsumer.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000016#include "clang/AST/ASTContext.h"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000017#include "clang/AST/DeclVisitor.h"
18#include "clang/AST/StmtVisitor.h"
Chandler Carruth55fc8732012-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"
Stephen Hines651f13c2014-04-23 16:59:28 -070023#include "clang/Basic/VirtualFileSystem.h"
Daniel Dunbar521bf9c2009-12-01 09:51:01 +000024#include "clang/Frontend/CompilerInstance.h"
25#include "clang/Frontend/FrontendActions.h"
Daniel Dunbar7b556682009-12-02 03:23:45 +000026#include "clang/Frontend/FrontendDiagnostic.h"
Daniel Dunbar521bf9c2009-12-01 09:51:01 +000027#include "clang/Frontend/FrontendOptions.h"
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +000028#include "clang/Frontend/MultiplexConsumer.h"
Douglas Gregor32be4a52010-10-11 21:37:58 +000029#include "clang/Frontend/Utils.h"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000030#include "clang/Lex/HeaderSearch.h"
31#include "clang/Lex/Preprocessor.h"
Douglas Gregor36a16492012-10-24 17:46:57 +000032#include "clang/Lex/PreprocessorOptions.h"
David Blaikie0b5ca512013-09-13 18:32:52 +000033#include "clang/Sema/Sema.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000034#include "clang/Serialization/ASTReader.h"
35#include "clang/Serialization/ASTWriter.h"
Chris Lattner7f9fc3f2011-03-23 04:04:01 +000036#include "llvm/ADT/ArrayRef.h"
Douglas Gregor9b7db622011-02-16 18:16:54 +000037#include "llvm/ADT/StringExtras.h"
Douglas Gregor349d38c2010-08-16 23:08:34 +000038#include "llvm/ADT/StringSet.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000039#include "llvm/Support/CrashRecoveryContext.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000040#include "llvm/Support/Host.h"
41#include "llvm/Support/MemoryBuffer.h"
Argyrios Kyrtzidisa696ece2011-10-10 21:57:12 +000042#include "llvm/Support/Mutex.h"
Ted Kremeneke055f8a2011-10-27 19:44:25 +000043#include "llvm/Support/MutexGuard.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000044#include "llvm/Support/Path.h"
45#include "llvm/Support/Timer.h"
46#include "llvm/Support/raw_ostream.h"
Stephen Hines651f13c2014-04-23 16:59:28 -070047#include <atomic>
Zhongxing Xuad23ebe2010-07-23 02:15:08 +000048#include <cstdio>
Chandler Carruth55fc8732012-12-04 09:13:33 +000049#include <cstdlib>
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000050using namespace clang;
51
Douglas Gregor213f18b2010-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 Krameredfb7ec2010-11-09 20:00:56 +000060 public:
Douglas Gregor9dba61a2010-11-01 13:48:43 +000061 explicit SimpleTimer(bool WantTiming) : WantTiming(WantTiming) {
Douglas Gregor213f18b2010-10-28 15:44:59 +000062 if (WantTiming)
Benjamin Krameredfb7ec2010-11-09 20:00:56 +000063 Start = TimeRecord::getCurrentTime();
Douglas Gregor213f18b2010-10-28 15:44:59 +000064 }
65
Chris Lattner5f9e2722011-07-23 10:55:15 +000066 void setOutput(const Twine &Output) {
Douglas Gregor213f18b2010-10-28 15:44:59 +000067 if (WantTiming)
Benjamin Krameredfb7ec2010-11-09 20:00:56 +000068 this->Output = Output.str();
Douglas Gregor213f18b2010-10-28 15:44:59 +000069 }
70
Douglas Gregor213f18b2010-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 Kremenek1872b312011-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 Espindolab804cb32013-06-26 03:52:38 +000086 /// \brief Temporary files that should be removed when the ASTUnit is
Ted Kremenek1872b312011-10-27 17:55:18 +000087 /// destroyed.
Rafael Espindolab804cb32013-06-26 03:52:38 +000088 SmallVector<std::string, 4> TemporaryFiles;
89
Ted Kremenek1872b312011-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 };
99}
100
Ted Kremeneke055f8a2011-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 Gribenkoc4a77902012-11-15 14:28:07 +0000106static void cleanupOnDiskMapAtExit();
Ted Kremenek1872b312011-10-27 17:55:18 +0000107
Stephen Hines176edba2014-12-01 14:53:08 -0800108typedef llvm::DenseMap<const ASTUnit *,
109 std::unique_ptr<OnDiskData>> OnDiskDataMap;
Ted Kremenek1872b312011-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 Gribenkoc4a77902012-11-15 14:28:07 +0000120static void cleanupOnDiskMapAtExit() {
Argyrios Kyrtzidis81788132012-07-03 16:30:52 +0000121 // Use the mutex because there can be an alive thread destroying an ASTUnit.
122 llvm::MutexGuard Guard(getOnDiskMutex());
Ted Kremenek1872b312011-10-27 17:55:18 +0000123 OnDiskDataMap &M = getOnDiskDataMap();
124 for (OnDiskDataMap::iterator I = M.begin(), E = M.end(); I != E; ++I) {
125 // We don't worry about freeing the memory associated with OnDiskDataMap.
126 // All we care about is erasing stale files.
127 I->second->Cleanup();
128 }
129}
130
131static OnDiskData &getOnDiskData(const ASTUnit *AU) {
Ted Kremeneke055f8a2011-10-27 19:44:25 +0000132 // We require the mutex since we are modifying the structure of the
133 // DenseMap.
134 llvm::MutexGuard Guard(getOnDiskMutex());
Ted Kremenek1872b312011-10-27 17:55:18 +0000135 OnDiskDataMap &M = getOnDiskDataMap();
Stephen Hines176edba2014-12-01 14:53:08 -0800136 auto &D = M[AU];
Ted Kremenek1872b312011-10-27 17:55:18 +0000137 if (!D)
Stephen Hines176edba2014-12-01 14:53:08 -0800138 D = llvm::make_unique<OnDiskData>();
Ted Kremenek1872b312011-10-27 17:55:18 +0000139 return *D;
140}
141
142static void erasePreambleFile(const ASTUnit *AU) {
143 getOnDiskData(AU).CleanPreambleFile();
144}
145
146static void removeOnDiskEntry(const ASTUnit *AU) {
Ted Kremeneke055f8a2011-10-27 19:44:25 +0000147 // We require the mutex since we are modifying the structure of the
148 // DenseMap.
149 llvm::MutexGuard Guard(getOnDiskMutex());
Ted Kremenek1872b312011-10-27 17:55:18 +0000150 OnDiskDataMap &M = getOnDiskDataMap();
151 OnDiskDataMap::iterator I = M.find(AU);
152 if (I != M.end()) {
153 I->second->Cleanup();
Ted Kremenek1872b312011-10-27 17:55:18 +0000154 M.erase(AU);
155 }
156}
157
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000158static void setPreambleFile(const ASTUnit *AU, StringRef preambleFile) {
Ted Kremenek1872b312011-10-27 17:55:18 +0000159 getOnDiskData(AU).PreambleFile = preambleFile;
160}
161
162static const std::string &getPreambleFile(const ASTUnit *AU) {
163 return getOnDiskData(AU).PreambleFile;
164}
165
166void OnDiskData::CleanTemporaryFiles() {
167 for (unsigned I = 0, N = TemporaryFiles.size(); I != N; ++I)
Rafael Espindolab804cb32013-06-26 03:52:38 +0000168 llvm::sys::fs::remove(TemporaryFiles[I]);
169 TemporaryFiles.clear();
Ted Kremenek1872b312011-10-27 17:55:18 +0000170}
171
172void OnDiskData::CleanPreambleFile() {
173 if (!PreambleFile.empty()) {
Rafael Espindola85d28482013-06-26 04:02:37 +0000174 llvm::sys::fs::remove(PreambleFile);
Ted Kremenek1872b312011-10-27 17:55:18 +0000175 PreambleFile.clear();
176 }
177}
178
179void OnDiskData::Cleanup() {
180 CleanTemporaryFiles();
181 CleanPreambleFile();
182}
183
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000184struct ASTUnit::ASTWriterData {
185 SmallString<128> Buffer;
186 llvm::BitstreamWriter Stream;
187 ASTWriter Writer;
188
189 ASTWriterData() : Stream(Buffer), Writer(Stream) { }
190};
191
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000192void ASTUnit::clearFileLevelDecls() {
Stephen Hines651f13c2014-04-23 16:59:28 -0700193 llvm::DeleteContainerSeconds(FileDecls);
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000194}
195
Ted Kremenek1872b312011-10-27 17:55:18 +0000196void ASTUnit::CleanTemporaryFiles() {
197 getOnDiskData(this).CleanTemporaryFiles();
198}
199
Rafael Espindolab804cb32013-06-26 03:52:38 +0000200void ASTUnit::addTemporaryFile(StringRef TempFile) {
Ted Kremenek1872b312011-10-27 17:55:18 +0000201 getOnDiskData(this).TemporaryFiles.push_back(TempFile);
Douglas Gregor213f18b2010-10-28 15:44:59 +0000202}
203
Douglas Gregoreababfb2010-08-04 05:53:38 +0000204/// \brief After failing to build a precompiled preamble (due to
205/// errors in the source that occurs in the preamble), the number of
206/// reparses during which we'll skip even trying to precompile the
207/// preamble.
208const unsigned DefaultPreambleRebuildInterval = 5;
209
Douglas Gregore3c60a72010-11-17 00:13:31 +0000210/// \brief Tracks the number of ASTUnit objects that are currently active.
211///
212/// Used for debugging purposes only.
Stephen Hines651f13c2014-04-23 16:59:28 -0700213static std::atomic<unsigned> ActiveASTUnitObjects;
Douglas Gregore3c60a72010-11-17 00:13:31 +0000214
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000215ASTUnit::ASTUnit(bool _MainFileIsAST)
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700216 : Reader(nullptr), HadModuleLoaderFatalFailure(false),
Argyrios Kyrtzidis3b7deda2013-05-24 05:44:08 +0000217 OnlyLocalDecls(false), CaptureDiagnostics(false),
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +0000218 MainFileIsAST(_MainFileIsAST),
Douglas Gregor467dc882011-08-25 22:30:56 +0000219 TUKind(TU_Complete), WantTiming(getenv("LIBCLANG_TIMING")),
Argyrios Kyrtzidis15727dd2011-03-05 01:03:48 +0000220 OwnsRemappedFileBuffers(true),
Douglas Gregor213f18b2010-10-28 15:44:59 +0000221 NumStoredDiagnosticsFromDriver(0),
Stephen Hines176edba2014-12-01 14:53:08 -0800222 PreambleRebuildCounter(0),
223 NumWarningsInPreamble(0),
Douglas Gregor727d93e2010-08-17 00:40:40 +0000224 ShouldCacheCodeCompletionResults(false),
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +0000225 IncludeBriefCommentsInCodeCompletion(false), UserFilesAreVolatile(false),
Douglas Gregor9b7db622011-02-16 18:16:54 +0000226 CompletionCacheTopLevelHashValue(0),
227 PreambleTopLevelHashValue(0),
228 CurrentTopLevelHashValue(0),
Douglas Gregor8b1540c2010-08-19 00:45:44 +0000229 UnsafeToFree(false) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700230 if (getenv("LIBCLANG_OBJTRACKING"))
231 fprintf(stderr, "+++ %u translation units\n", ++ActiveASTUnitObjects);
Douglas Gregor385103b2010-07-30 20:58:08 +0000232}
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000233
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000234ASTUnit::~ASTUnit() {
Douglas Gregora4a90ca2013-05-03 22:58:43 +0000235 // If we loaded from an AST file, balance out the BeginSourceFile call.
236 if (MainFileIsAST && getDiagnostics().getClient()) {
237 getDiagnostics().getClient()->EndSourceFile();
238 }
239
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000240 clearFileLevelDecls();
241
Ted Kremenek1872b312011-10-27 17:55:18 +0000242 // Clean up the temporary files and the preamble file.
243 removeOnDiskEntry(this);
244
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000245 // Free the buffers associated with remapped files. We are required to
246 // perform this operation here because we explicitly request that the
247 // compiler instance *not* free these buffers for each invocation of the
248 // parser.
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700249 if (Invocation.get() && OwnsRemappedFileBuffers) {
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000250 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700251 for (const auto &RB : PPOpts.RemappedFileBuffers)
252 delete RB.second;
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000253 }
Douglas Gregor671947b2010-08-19 01:33:06 +0000254
Douglas Gregor213f18b2010-10-28 15:44:59 +0000255 ClearCachedCompletionResults();
Douglas Gregore3c60a72010-11-17 00:13:31 +0000256
Stephen Hines651f13c2014-04-23 16:59:28 -0700257 if (getenv("LIBCLANG_OBJTRACKING"))
258 fprintf(stderr, "--- %u translation units\n", --ActiveASTUnitObjects);
Douglas Gregorabc563f2010-07-19 21:46:24 +0000259}
260
Argyrios Kyrtzidis7fe90f32012-01-17 18:48:07 +0000261void ASTUnit::setPreprocessor(Preprocessor *pp) { PP = pp; }
262
Douglas Gregor8071e422010-08-15 06:18:01 +0000263/// \brief Determine the set of code-completion contexts in which this
264/// declaration should be shown.
Dmitri Gribenko89cf4252013-01-23 17:21:11 +0000265static unsigned getDeclShowContexts(const NamedDecl *ND,
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000266 const LangOptions &LangOpts,
267 bool &IsNestedNameSpecifier) {
268 IsNestedNameSpecifier = false;
269
Douglas Gregor8071e422010-08-15 06:18:01 +0000270 if (isa<UsingShadowDecl>(ND))
271 ND = dyn_cast<NamedDecl>(ND->getUnderlyingDecl());
272 if (!ND)
273 return 0;
274
Richard Smith026b3582012-08-14 03:13:00 +0000275 uint64_t Contexts = 0;
Douglas Gregor8071e422010-08-15 06:18:01 +0000276 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND) ||
277 isa<ClassTemplateDecl>(ND) || isa<TemplateTemplateParmDecl>(ND)) {
278 // Types can appear in these contexts.
279 if (LangOpts.CPlusPlus || !isa<TagDecl>(ND))
Richard Smith026b3582012-08-14 03:13:00 +0000280 Contexts |= (1LL << CodeCompletionContext::CCC_TopLevel)
281 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
282 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
283 | (1LL << CodeCompletionContext::CCC_Statement)
284 | (1LL << CodeCompletionContext::CCC_Type)
285 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression);
Douglas Gregor8071e422010-08-15 06:18:01 +0000286
287 // In C++, types can appear in expressions contexts (for functional casts).
288 if (LangOpts.CPlusPlus)
Richard Smith026b3582012-08-14 03:13:00 +0000289 Contexts |= (1LL << CodeCompletionContext::CCC_Expression);
Douglas Gregor8071e422010-08-15 06:18:01 +0000290
291 // In Objective-C, message sends can send interfaces. In Objective-C++,
292 // all types are available due to functional casts.
293 if (LangOpts.CPlusPlus || isa<ObjCInterfaceDecl>(ND))
Richard Smith026b3582012-08-14 03:13:00 +0000294 Contexts |= (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver);
Douglas Gregor3da626b2011-07-07 16:03:39 +0000295
296 // In Objective-C, you can only be a subclass of another Objective-C class
297 if (isa<ObjCInterfaceDecl>(ND))
Richard Smith026b3582012-08-14 03:13:00 +0000298 Contexts |= (1LL << CodeCompletionContext::CCC_ObjCInterfaceName);
Douglas Gregor8071e422010-08-15 06:18:01 +0000299
300 // Deal with tag names.
301 if (isa<EnumDecl>(ND)) {
Richard Smith026b3582012-08-14 03:13:00 +0000302 Contexts |= (1LL << CodeCompletionContext::CCC_EnumTag);
Douglas Gregor8071e422010-08-15 06:18:01 +0000303
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000304 // Part of the nested-name-specifier in C++0x.
Richard Smith80ad52f2013-01-02 11:42:31 +0000305 if (LangOpts.CPlusPlus11)
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000306 IsNestedNameSpecifier = true;
Dmitri Gribenko89cf4252013-01-23 17:21:11 +0000307 } else if (const RecordDecl *Record = dyn_cast<RecordDecl>(ND)) {
Douglas Gregor8071e422010-08-15 06:18:01 +0000308 if (Record->isUnion())
Richard Smith026b3582012-08-14 03:13:00 +0000309 Contexts |= (1LL << CodeCompletionContext::CCC_UnionTag);
Douglas Gregor8071e422010-08-15 06:18:01 +0000310 else
Richard Smith026b3582012-08-14 03:13:00 +0000311 Contexts |= (1LL << CodeCompletionContext::CCC_ClassOrStructTag);
Douglas Gregor8071e422010-08-15 06:18:01 +0000312
Douglas Gregor8071e422010-08-15 06:18:01 +0000313 if (LangOpts.CPlusPlus)
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000314 IsNestedNameSpecifier = true;
Douglas Gregor52779fb2010-09-23 23:01:17 +0000315 } else if (isa<ClassTemplateDecl>(ND))
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000316 IsNestedNameSpecifier = true;
Douglas Gregor8071e422010-08-15 06:18:01 +0000317 } else if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
318 // Values can appear in these contexts.
Richard Smith026b3582012-08-14 03:13:00 +0000319 Contexts = (1LL << CodeCompletionContext::CCC_Statement)
320 | (1LL << CodeCompletionContext::CCC_Expression)
321 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
322 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver);
Douglas Gregor8071e422010-08-15 06:18:01 +0000323 } else if (isa<ObjCProtocolDecl>(ND)) {
Richard Smith026b3582012-08-14 03:13:00 +0000324 Contexts = (1LL << CodeCompletionContext::CCC_ObjCProtocolName);
Douglas Gregor3da626b2011-07-07 16:03:39 +0000325 } else if (isa<ObjCCategoryDecl>(ND)) {
Richard Smith026b3582012-08-14 03:13:00 +0000326 Contexts = (1LL << CodeCompletionContext::CCC_ObjCCategoryName);
Douglas Gregor8071e422010-08-15 06:18:01 +0000327 } else if (isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) {
Richard Smith026b3582012-08-14 03:13:00 +0000328 Contexts = (1LL << CodeCompletionContext::CCC_Namespace);
Douglas Gregor8071e422010-08-15 06:18:01 +0000329
330 // Part of the nested-name-specifier.
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000331 IsNestedNameSpecifier = true;
Douglas Gregor8071e422010-08-15 06:18:01 +0000332 }
333
334 return Contexts;
335}
336
Douglas Gregor87c08a52010-08-13 22:48:40 +0000337void ASTUnit::CacheCodeCompletionResults() {
338 if (!TheSema)
339 return;
340
Douglas Gregor213f18b2010-10-28 15:44:59 +0000341 SimpleTimer Timer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +0000342 Timer.setOutput("Cache global code completions for " + getMainFileName());
Douglas Gregor87c08a52010-08-13 22:48:40 +0000343
344 // Clear out the previous results.
345 ClearCachedCompletionResults();
346
347 // Gather the set of global code completions.
John McCall0a2c5e22010-08-25 06:19:51 +0000348 typedef CodeCompletionResult Result;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000349 SmallVector<Result, 8> Results;
Douglas Gregor48601b32011-02-16 19:08:06 +0000350 CachedCompletionAllocator = new GlobalCodeCompletionAllocator;
Argyrios Kyrtzidis7fdc8fd2012-11-16 03:34:57 +0000351 CodeCompletionTUInfo CCTUInfo(CachedCompletionAllocator);
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +0000352 TheSema->GatherGlobalCodeCompletions(*CachedCompletionAllocator,
Argyrios Kyrtzidis7fdc8fd2012-11-16 03:34:57 +0000353 CCTUInfo, Results);
Douglas Gregor87c08a52010-08-13 22:48:40 +0000354
355 // Translate global code completions into cached completions.
Douglas Gregorf5586f62010-08-16 18:08:11 +0000356 llvm::DenseMap<CanQualType, unsigned> CompletionTypes;
357
Douglas Gregor87c08a52010-08-13 22:48:40 +0000358 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
359 switch (Results[I].Kind) {
Douglas Gregor8071e422010-08-15 06:18:01 +0000360 case Result::RK_Declaration: {
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000361 bool IsNestedNameSpecifier = false;
Douglas Gregor8071e422010-08-15 06:18:01 +0000362 CachedCodeCompletionResult CachedResult;
Douglas Gregor218937c2011-02-01 19:23:04 +0000363 CachedResult.Completion = Results[I].CreateCodeCompletionString(*TheSema,
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +0000364 *CachedCompletionAllocator,
Argyrios Kyrtzidis7fdc8fd2012-11-16 03:34:57 +0000365 CCTUInfo,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +0000366 IncludeBriefCommentsInCodeCompletion);
Douglas Gregor8071e422010-08-15 06:18:01 +0000367 CachedResult.ShowInContexts = getDeclShowContexts(Results[I].Declaration,
David Blaikie4e4d0842012-03-11 07:00:24 +0000368 Ctx->getLangOpts(),
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000369 IsNestedNameSpecifier);
Douglas Gregor8071e422010-08-15 06:18:01 +0000370 CachedResult.Priority = Results[I].Priority;
371 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregor58ddb602010-08-23 23:00:57 +0000372 CachedResult.Availability = Results[I].Availability;
Douglas Gregorc4421e92010-08-16 16:46:30 +0000373
Douglas Gregorf5586f62010-08-16 18:08:11 +0000374 // Keep track of the type of this completion in an ASTContext-agnostic
375 // way.
Douglas Gregorc4421e92010-08-16 16:46:30 +0000376 QualType UsageType = getDeclUsageType(*Ctx, Results[I].Declaration);
Douglas Gregorf5586f62010-08-16 18:08:11 +0000377 if (UsageType.isNull()) {
Douglas Gregorc4421e92010-08-16 16:46:30 +0000378 CachedResult.TypeClass = STC_Void;
Douglas Gregorf5586f62010-08-16 18:08:11 +0000379 CachedResult.Type = 0;
380 } else {
381 CanQualType CanUsageType
382 = Ctx->getCanonicalType(UsageType.getUnqualifiedType());
383 CachedResult.TypeClass = getSimplifiedTypeClass(CanUsageType);
384
385 // Determine whether we have already seen this type. If so, we save
386 // ourselves the work of formatting the type string by using the
387 // temporary, CanQualType-based hash table to find the associated value.
388 unsigned &TypeValue = CompletionTypes[CanUsageType];
389 if (TypeValue == 0) {
390 TypeValue = CompletionTypes.size();
391 CachedCompletionTypes[QualType(CanUsageType).getAsString()]
392 = TypeValue;
393 }
394
395 CachedResult.Type = TypeValue;
Douglas Gregorc4421e92010-08-16 16:46:30 +0000396 }
Douglas Gregorf5586f62010-08-16 18:08:11 +0000397
Douglas Gregor8071e422010-08-15 06:18:01 +0000398 CachedCompletionResults.push_back(CachedResult);
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000399
400 /// Handle nested-name-specifiers in C++.
David Blaikie4e4d0842012-03-11 07:00:24 +0000401 if (TheSema->Context.getLangOpts().CPlusPlus &&
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000402 IsNestedNameSpecifier && !Results[I].StartsNestedNameSpecifier) {
403 // The contexts in which a nested-name-specifier can appear in C++.
Richard Smith026b3582012-08-14 03:13:00 +0000404 uint64_t NNSContexts
405 = (1LL << CodeCompletionContext::CCC_TopLevel)
406 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
407 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
408 | (1LL << CodeCompletionContext::CCC_Statement)
409 | (1LL << CodeCompletionContext::CCC_Expression)
410 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
411 | (1LL << CodeCompletionContext::CCC_EnumTag)
412 | (1LL << CodeCompletionContext::CCC_UnionTag)
413 | (1LL << CodeCompletionContext::CCC_ClassOrStructTag)
414 | (1LL << CodeCompletionContext::CCC_Type)
415 | (1LL << CodeCompletionContext::CCC_PotentiallyQualifiedName)
416 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression);
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000417
418 if (isa<NamespaceDecl>(Results[I].Declaration) ||
419 isa<NamespaceAliasDecl>(Results[I].Declaration))
Richard Smith026b3582012-08-14 03:13:00 +0000420 NNSContexts |= (1LL << CodeCompletionContext::CCC_Namespace);
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000421
422 if (unsigned RemainingContexts
423 = NNSContexts & ~CachedResult.ShowInContexts) {
424 // If there any contexts where this completion can be a
425 // nested-name-specifier but isn't already an option, create a
426 // nested-name-specifier completion.
427 Results[I].StartsNestedNameSpecifier = true;
Douglas Gregor218937c2011-02-01 19:23:04 +0000428 CachedResult.Completion
429 = Results[I].CreateCodeCompletionString(*TheSema,
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +0000430 *CachedCompletionAllocator,
Argyrios Kyrtzidis7fdc8fd2012-11-16 03:34:57 +0000431 CCTUInfo,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +0000432 IncludeBriefCommentsInCodeCompletion);
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000433 CachedResult.ShowInContexts = RemainingContexts;
434 CachedResult.Priority = CCP_NestedNameSpecifier;
435 CachedResult.TypeClass = STC_Void;
436 CachedResult.Type = 0;
437 CachedCompletionResults.push_back(CachedResult);
438 }
439 }
Douglas Gregor87c08a52010-08-13 22:48:40 +0000440 break;
Douglas Gregor8071e422010-08-15 06:18:01 +0000441 }
442
Douglas Gregor87c08a52010-08-13 22:48:40 +0000443 case Result::RK_Keyword:
444 case Result::RK_Pattern:
445 // Ignore keywords and patterns; we don't care, since they are so
446 // easily regenerated.
447 break;
448
449 case Result::RK_Macro: {
450 CachedCodeCompletionResult CachedResult;
Douglas Gregor218937c2011-02-01 19:23:04 +0000451 CachedResult.Completion
452 = Results[I].CreateCodeCompletionString(*TheSema,
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +0000453 *CachedCompletionAllocator,
Argyrios Kyrtzidis7fdc8fd2012-11-16 03:34:57 +0000454 CCTUInfo,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +0000455 IncludeBriefCommentsInCodeCompletion);
Douglas Gregor87c08a52010-08-13 22:48:40 +0000456 CachedResult.ShowInContexts
Richard Smith026b3582012-08-14 03:13:00 +0000457 = (1LL << CodeCompletionContext::CCC_TopLevel)
458 | (1LL << CodeCompletionContext::CCC_ObjCInterface)
459 | (1LL << CodeCompletionContext::CCC_ObjCImplementation)
460 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
461 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
462 | (1LL << CodeCompletionContext::CCC_Statement)
463 | (1LL << CodeCompletionContext::CCC_Expression)
464 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
465 | (1LL << CodeCompletionContext::CCC_MacroNameUse)
466 | (1LL << CodeCompletionContext::CCC_PreprocessorExpression)
467 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
468 | (1LL << CodeCompletionContext::CCC_OtherWithMacros);
Douglas Gregor2ccccb32010-08-23 18:23:48 +0000469
Douglas Gregor87c08a52010-08-13 22:48:40 +0000470 CachedResult.Priority = Results[I].Priority;
471 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregor58ddb602010-08-23 23:00:57 +0000472 CachedResult.Availability = Results[I].Availability;
Douglas Gregor1827e102010-08-16 16:18:59 +0000473 CachedResult.TypeClass = STC_Void;
Douglas Gregorf5586f62010-08-16 18:08:11 +0000474 CachedResult.Type = 0;
Douglas Gregor87c08a52010-08-13 22:48:40 +0000475 CachedCompletionResults.push_back(CachedResult);
476 break;
477 }
478 }
Douglas Gregor87c08a52010-08-13 22:48:40 +0000479 }
Douglas Gregor9b7db622011-02-16 18:16:54 +0000480
481 // Save the current top-level hash value.
482 CompletionCacheTopLevelHashValue = CurrentTopLevelHashValue;
Douglas Gregor87c08a52010-08-13 22:48:40 +0000483}
484
485void ASTUnit::ClearCachedCompletionResults() {
Douglas Gregor87c08a52010-08-13 22:48:40 +0000486 CachedCompletionResults.clear();
Douglas Gregorf5586f62010-08-16 18:08:11 +0000487 CachedCompletionTypes.clear();
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700488 CachedCompletionAllocator = nullptr;
Douglas Gregor87c08a52010-08-13 22:48:40 +0000489}
490
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000491namespace {
492
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000493/// \brief Gathers information from ASTReader that will be used to initialize
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000494/// a Preprocessor.
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000495class ASTInfoCollector : public ASTReaderListener {
Douglas Gregor998b3d32011-09-01 23:39:15 +0000496 Preprocessor &PP;
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000497 ASTContext &Context;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000498 LangOptions &LangOpt;
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700499 std::shared_ptr<TargetOptions> &TargetOpts;
Dylan Noblesmithc93dc782012-02-20 14:00:23 +0000500 IntrusiveRefCntPtr<TargetInfo> &Target;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000501 unsigned &Counter;
Mike Stump1eb44332009-09-09 15:08:12 +0000502
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000503 bool InitializedLanguage;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000504public:
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700505 ASTInfoCollector(Preprocessor &PP, ASTContext &Context, LangOptions &LangOpt,
506 std::shared_ptr<TargetOptions> &TargetOpts,
507 IntrusiveRefCntPtr<TargetInfo> &Target, unsigned &Counter)
508 : PP(PP), Context(Context), LangOpt(LangOpt), TargetOpts(TargetOpts),
509 Target(Target), Counter(Counter), InitializedLanguage(false) {}
Mike Stump1eb44332009-09-09 15:08:12 +0000510
Stephen Hines176edba2014-12-01 14:53:08 -0800511 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
512 bool AllowCompatibleDifferences) override {
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000513 if (InitializedLanguage)
Douglas Gregor998b3d32011-09-01 23:39:15 +0000514 return false;
515
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000516 LangOpt = LangOpts;
517 InitializedLanguage = true;
518
519 updated();
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000520 return false;
521 }
Mike Stump1eb44332009-09-09 15:08:12 +0000522
Stephen Hines651f13c2014-04-23 16:59:28 -0700523 bool ReadTargetOptions(const TargetOptions &TargetOpts,
524 bool Complain) override {
Douglas Gregor998b3d32011-09-01 23:39:15 +0000525 // If we've already initialized the target, don't do it again.
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000526 if (Target)
Douglas Gregor998b3d32011-09-01 23:39:15 +0000527 return false;
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700528
529 this->TargetOpts = std::make_shared<TargetOptions>(TargetOpts);
530 Target =
531 TargetInfo::CreateTargetInfo(PP.getDiagnostics(), this->TargetOpts);
Argyrios Kyrtzidis7f186332012-09-14 20:24:53 +0000532
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000533 updated();
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000534 return false;
535 }
Mike Stump1eb44332009-09-09 15:08:12 +0000536
Stephen Hines651f13c2014-04-23 16:59:28 -0700537 void ReadCounter(const serialization::ModuleFile &M,
538 unsigned Value) override {
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000539 Counter = Value;
540 }
Argyrios Kyrtzidis7f186332012-09-14 20:24:53 +0000541
542private:
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000543 void updated() {
544 if (!Target || !InitializedLanguage)
545 return;
546
547 // Inform the target of the language options.
548 //
549 // FIXME: We shouldn't need to do this, the target should be immutable once
550 // created. This complexity should be lifted elsewhere.
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700551 Target->adjust(LangOpt);
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000552
553 // Initialize the preprocessor.
554 PP.Initialize(*Target);
555
556 // Initialize the ASTContext
557 Context.InitBuiltinTypes(*Target);
Dmitri Gribenko6ebf0912013-02-22 14:21:27 +0000558
559 // We didn't have access to the comment options when the ASTContext was
560 // constructed, so register them now.
561 Context.getCommentCommandTraits().registerCommentOptions(
562 LangOpt.CommentOpts);
Argyrios Kyrtzidis7f186332012-09-14 20:24:53 +0000563 }
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000564};
565
Douglas Gregora4a90ca2013-05-03 22:58:43 +0000566 /// \brief Diagnostic consumer that saves each diagnostic it is given.
David Blaikie26e7a902011-09-26 00:01:39 +0000567class StoredDiagnosticConsumer : public DiagnosticConsumer {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000568 SmallVectorImpl<StoredDiagnostic> &StoredDiags;
Douglas Gregora4a90ca2013-05-03 22:58:43 +0000569 SourceManager *SourceMgr;
570
Douglas Gregora88084b2010-02-18 18:08:43 +0000571public:
David Blaikie26e7a902011-09-26 00:01:39 +0000572 explicit StoredDiagnosticConsumer(
Chris Lattner5f9e2722011-07-23 10:55:15 +0000573 SmallVectorImpl<StoredDiagnostic> &StoredDiags)
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700574 : StoredDiags(StoredDiags), SourceMgr(nullptr) {}
Douglas Gregora4a90ca2013-05-03 22:58:43 +0000575
Stephen Hines651f13c2014-04-23 16:59:28 -0700576 void BeginSourceFile(const LangOptions &LangOpts,
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700577 const Preprocessor *PP = nullptr) override {
Douglas Gregora4a90ca2013-05-03 22:58:43 +0000578 if (PP)
579 SourceMgr = &PP->getSourceManager();
580 }
581
Stephen Hines651f13c2014-04-23 16:59:28 -0700582 void HandleDiagnostic(DiagnosticsEngine::Level Level,
583 const Diagnostic &Info) override;
Douglas Gregora88084b2010-02-18 18:08:43 +0000584};
585
586/// \brief RAII object that optionally captures diagnostics, if
587/// there is no diagnostic client to capture them already.
588class CaptureDroppedDiagnostics {
David Blaikied6471f72011-09-25 23:23:43 +0000589 DiagnosticsEngine &Diags;
David Blaikie26e7a902011-09-26 00:01:39 +0000590 StoredDiagnosticConsumer Client;
David Blaikie78ad0b92011-09-25 23:39:51 +0000591 DiagnosticConsumer *PreviousClient;
Stephen Hines176edba2014-12-01 14:53:08 -0800592 std::unique_ptr<DiagnosticConsumer> OwningPreviousClient;
Douglas Gregora88084b2010-02-18 18:08:43 +0000593
594public:
David Blaikied6471f72011-09-25 23:23:43 +0000595 CaptureDroppedDiagnostics(bool RequestCapture, DiagnosticsEngine &Diags,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000596 SmallVectorImpl<StoredDiagnostic> &StoredDiags)
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700597 : Diags(Diags), Client(StoredDiags), PreviousClient(nullptr)
Douglas Gregora88084b2010-02-18 18:08:43 +0000598 {
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700599 if (RequestCapture || Diags.getClient() == nullptr) {
Stephen Hines176edba2014-12-01 14:53:08 -0800600 OwningPreviousClient = Diags.takeClient();
601 PreviousClient = Diags.getClient();
602 Diags.setClient(&Client, false);
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000603 }
Douglas Gregora88084b2010-02-18 18:08:43 +0000604 }
605
606 ~CaptureDroppedDiagnostics() {
Stephen Hines176edba2014-12-01 14:53:08 -0800607 if (Diags.getClient() == &Client)
608 Diags.setClient(PreviousClient, !!OwningPreviousClient.release());
Douglas Gregora88084b2010-02-18 18:08:43 +0000609 }
610};
611
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000612} // anonymous namespace
613
David Blaikie26e7a902011-09-26 00:01:39 +0000614void StoredDiagnosticConsumer::HandleDiagnostic(DiagnosticsEngine::Level Level,
David Blaikie40847cf2011-09-26 01:18:08 +0000615 const Diagnostic &Info) {
Argyrios Kyrtzidisf2224d82010-11-18 20:06:46 +0000616 // Default implementation (Warnings/errors count).
David Blaikie78ad0b92011-09-25 23:39:51 +0000617 DiagnosticConsumer::HandleDiagnostic(Level, Info);
Argyrios Kyrtzidisf2224d82010-11-18 20:06:46 +0000618
Douglas Gregora4a90ca2013-05-03 22:58:43 +0000619 // Only record the diagnostic if it's part of the source manager we know
620 // about. This effectively drops diagnostics from modules we're building.
621 // FIXME: In the long run, ee don't want to drop source managers from modules.
622 if (!Info.hasSourceManager() || &Info.getSourceManager() == SourceMgr)
623 StoredDiags.push_back(StoredDiagnostic(Level, Info));
Douglas Gregora88084b2010-02-18 18:08:43 +0000624}
625
Argyrios Kyrtzidis7eca8d22013-05-10 01:28:51 +0000626ASTMutationListener *ASTUnit::getASTMutationListener() {
627 if (WriterData)
628 return &WriterData->Writer;
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700629 return nullptr;
Argyrios Kyrtzidis7eca8d22013-05-10 01:28:51 +0000630}
631
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000632ASTDeserializationListener *ASTUnit::getDeserializationListener() {
633 if (WriterData)
634 return &WriterData->Writer;
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700635 return nullptr;
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000636}
637
Stephen Hines176edba2014-12-01 14:53:08 -0800638std::unique_ptr<llvm::MemoryBuffer>
639ASTUnit::getBufferForFile(StringRef Filename, std::string *ErrorStr) {
Chris Lattner39b49bc2010-11-23 08:35:12 +0000640 assert(FileMgr);
Stephen Hines176edba2014-12-01 14:53:08 -0800641 auto Buffer = FileMgr->getBufferForFile(Filename);
642 if (Buffer)
643 return std::move(*Buffer);
644 if (ErrorStr)
645 *ErrorStr = Buffer.getError().message();
646 return nullptr;
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +0000647}
648
Douglas Gregore47be3e2010-11-11 00:39:14 +0000649/// \brief Configure the diagnostics object for use with ASTUnit.
Stephen Hines176edba2014-12-01 14:53:08 -0800650void ASTUnit::ConfigureDiags(IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Douglas Gregore47be3e2010-11-11 00:39:14 +0000651 ASTUnit &AST, bool CaptureDiagnostics) {
Stephen Hines176edba2014-12-01 14:53:08 -0800652 assert(Diags.get() && "no DiagnosticsEngine was provided");
653 if (CaptureDiagnostics)
David Blaikie26e7a902011-09-26 00:01:39 +0000654 Diags->setClient(new StoredDiagnosticConsumer(AST.StoredDiagnostics));
Douglas Gregore47be3e2010-11-11 00:39:14 +0000655}
656
Stephen Hines176edba2014-12-01 14:53:08 -0800657std::unique_ptr<ASTUnit> ASTUnit::LoadFromASTFile(
658 const std::string &Filename, IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
659 const FileSystemOptions &FileSystemOpts, bool OnlyLocalDecls,
660 ArrayRef<RemappedFile> RemappedFiles, bool CaptureDiagnostics,
661 bool AllowPCHWithCompilerErrors, bool UserFilesAreVolatile) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700662 std::unique_ptr<ASTUnit> AST(new ASTUnit(true));
Ted Kremenekb547eeb2011-03-18 02:06:56 +0000663
664 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +0000665 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
666 ASTUnitCleanup(AST.get());
David Blaikied6471f72011-09-25 23:23:43 +0000667 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
668 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700669 DiagCleanup(Diags.get());
Ted Kremenekb547eeb2011-03-18 02:06:56 +0000670
Stephen Hines176edba2014-12-01 14:53:08 -0800671 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
Douglas Gregorabc563f2010-07-19 21:46:24 +0000672
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000673 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregore47be3e2010-11-11 00:39:14 +0000674 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor28019772010-04-05 23:52:57 +0000675 AST->Diagnostics = Diags;
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700676 IntrusiveRefCntPtr<vfs::FileSystem> VFS = vfs::getRealFileSystem();
677 AST->FileMgr = new FileManager(FileSystemOpts, VFS);
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +0000678 AST->UserFilesAreVolatile = UserFilesAreVolatile;
Ted Kremenek4f327862011-03-21 18:40:17 +0000679 AST->SourceMgr = new SourceManager(AST->getDiagnostics(),
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +0000680 AST->getFileManager(),
681 UserFilesAreVolatile);
Douglas Gregorc042edd2012-10-24 16:19:39 +0000682 AST->HSOpts = new HeaderSearchOptions();
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700683
Douglas Gregorc042edd2012-10-24 16:19:39 +0000684 AST->HeaderInfo.reset(new HeaderSearch(AST->HSOpts,
Manuel Klimekee0cd372013-10-24 07:51:24 +0000685 AST->getSourceManager(),
Douglas Gregor51f564f2011-12-31 04:05:44 +0000686 AST->getDiagnostics(),
Douglas Gregordc58aa72012-01-30 06:01:29 +0000687 AST->ASTFileLangOpts,
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700688 /*Target=*/nullptr));
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000689
Stephen Hines651f13c2014-04-23 16:59:28 -0700690 PreprocessorOptions *PPOpts = new PreprocessorOptions();
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000691
Stephen Hines651f13c2014-04-23 16:59:28 -0700692 for (unsigned I = 0, N = RemappedFiles.size(); I != N; ++I)
693 PPOpts->addRemappedFile(RemappedFiles[I].first, RemappedFiles[I].second);
694
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000695 // Gather Info for preprocessor construction later on.
Mike Stump1eb44332009-09-09 15:08:12 +0000696
Stephen Hines176edba2014-12-01 14:53:08 -0800697 HeaderSearch &HeaderInfo = *AST->HeaderInfo;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000698 unsigned Counter;
699
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700700 AST->PP =
701 new Preprocessor(PPOpts, AST->getDiagnostics(), AST->ASTFileLangOpts,
702 AST->getSourceManager(), HeaderInfo, *AST,
703 /*IILookup=*/nullptr,
704 /*OwnsHeaderSearch=*/false);
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000705 Preprocessor &PP = *AST->PP;
706
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700707 AST->Ctx = new ASTContext(AST->ASTFileLangOpts, AST->getSourceManager(),
708 PP.getIdentifierTable(), PP.getSelectorTable(),
709 PP.getBuiltinInfo());
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000710 ASTContext &Context = *AST->Ctx;
Douglas Gregor998b3d32011-09-01 23:39:15 +0000711
Argyrios Kyrtzidis98e95bf2012-09-15 01:10:20 +0000712 bool disableValid = false;
713 if (::getenv("LIBCLANG_DISABLE_PCH_VALIDATION"))
714 disableValid = true;
Stephen Hines651f13c2014-04-23 16:59:28 -0700715 AST->Reader = new ASTReader(PP, Context,
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +0000716 /*isysroot=*/"",
Argyrios Kyrtzidis98e95bf2012-09-15 01:10:20 +0000717 /*DisableValidation=*/disableValid,
Stephen Hines651f13c2014-04-23 16:59:28 -0700718 AllowPCHWithCompilerErrors);
Ted Kremenek8c647de2011-05-04 23:27:12 +0000719
Stephen Hines176edba2014-12-01 14:53:08 -0800720 AST->Reader->setListener(llvm::make_unique<ASTInfoCollector>(
721 *AST->PP, Context, AST->ASTFileLangOpts, AST->TargetOpts, AST->Target,
722 Counter));
Daniel Dunbarcc318932009-09-03 05:59:35 +0000723
Stephen Hines651f13c2014-04-23 16:59:28 -0700724 switch (AST->Reader->ReadAST(Filename, serialization::MK_MainFile,
Argyrios Kyrtzidis958bcaf2012-11-15 18:57:22 +0000725 SourceLocation(), ASTReader::ARR_None)) {
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000726 case ASTReader::Success:
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000727 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000728
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000729 case ASTReader::Failure:
Douglas Gregor677e15f2013-03-19 00:28:20 +0000730 case ASTReader::Missing:
Douglas Gregor4825fd72012-10-22 22:50:17 +0000731 case ASTReader::OutOfDate:
732 case ASTReader::VersionMismatch:
733 case ASTReader::ConfigurationMismatch:
734 case ASTReader::HadErrors:
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000735 AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700736 return nullptr;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000737 }
Mike Stump1eb44332009-09-09 15:08:12 +0000738
Stephen Hines651f13c2014-04-23 16:59:28 -0700739 AST->OriginalSourceFile = AST->Reader->getOriginalSourceFile();
Daniel Dunbar68d40e22009-12-02 08:44:16 +0000740
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000741 PP.setCounterValue(Counter);
Mike Stump1eb44332009-09-09 15:08:12 +0000742
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000743 // Attach the AST reader to the AST context as an external AST
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000744 // source, so that declarations will be deserialized from the
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000745 // AST file as needed.
Stephen Hines651f13c2014-04-23 16:59:28 -0700746 Context.setExternalSource(AST->Reader);
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000747
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000748 // Create an AST consumer, even though it isn't used.
749 AST->Consumer.reset(new ASTConsumer);
750
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000751 // Create a semantic analysis object and tell the AST reader about it.
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000752 AST->TheSema.reset(new Sema(PP, Context, *AST->Consumer));
753 AST->TheSema->Initialize();
Stephen Hines651f13c2014-04-23 16:59:28 -0700754 AST->Reader->InitializeSema(*AST->TheSema);
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000755
Douglas Gregora4a90ca2013-05-03 22:58:43 +0000756 // Tell the diagnostic client that we have started a source file.
757 AST->getDiagnostics().getClient()->BeginSourceFile(Context.getLangOpts(),&PP);
758
Stephen Hines176edba2014-12-01 14:53:08 -0800759 return AST;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000760}
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000761
762namespace {
763
Douglas Gregor9b7db622011-02-16 18:16:54 +0000764/// \brief Preprocessor callback class that updates a hash value with the names
765/// of all macros that have been defined by the translation unit.
766class MacroDefinitionTrackerPPCallbacks : public PPCallbacks {
767 unsigned &Hash;
768
769public:
770 explicit MacroDefinitionTrackerPPCallbacks(unsigned &Hash) : Hash(Hash) { }
Stephen Hines651f13c2014-04-23 16:59:28 -0700771
772 void MacroDefined(const Token &MacroNameTok,
773 const MacroDirective *MD) override {
Douglas Gregor9b7db622011-02-16 18:16:54 +0000774 Hash = llvm::HashString(MacroNameTok.getIdentifierInfo()->getName(), Hash);
775 }
776};
777
778/// \brief Add the given declaration to the hash of all top-level entities.
779void AddTopLevelDeclarationToHash(Decl *D, unsigned &Hash) {
780 if (!D)
781 return;
782
783 DeclContext *DC = D->getDeclContext();
784 if (!DC)
785 return;
786
787 if (!(DC->isTranslationUnit() || DC->getLookupParent()->isTranslationUnit()))
788 return;
789
790 if (NamedDecl *ND = dyn_cast<NamedDecl>(D)) {
Argyrios Kyrtzidise96a7b42013-10-15 17:37:55 +0000791 if (EnumDecl *EnumD = dyn_cast<EnumDecl>(D)) {
792 // For an unscoped enum include the enumerators in the hash since they
793 // enter the top-level namespace.
794 if (!EnumD->isScoped()) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700795 for (const auto *EI : EnumD->enumerators()) {
796 if (EI->getIdentifier())
797 Hash = llvm::HashString(EI->getIdentifier()->getName(), Hash);
Argyrios Kyrtzidise96a7b42013-10-15 17:37:55 +0000798 }
799 }
800 }
801
Douglas Gregor9b7db622011-02-16 18:16:54 +0000802 if (ND->getIdentifier())
803 Hash = llvm::HashString(ND->getIdentifier()->getName(), Hash);
804 else if (DeclarationName Name = ND->getDeclName()) {
805 std::string NameStr = Name.getAsString();
806 Hash = llvm::HashString(NameStr, Hash);
807 }
808 return;
Argyrios Kyrtzidis1f3ff6a2013-06-24 21:19:12 +0000809 }
810
811 if (ImportDecl *ImportD = dyn_cast<ImportDecl>(D)) {
812 if (Module *Mod = ImportD->getImportedModule()) {
813 std::string ModName = Mod->getFullModuleName();
814 Hash = llvm::HashString(ModName, Hash);
815 }
816 return;
817 }
Douglas Gregor9b7db622011-02-16 18:16:54 +0000818}
819
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000820class TopLevelDeclTrackerConsumer : public ASTConsumer {
821 ASTUnit &Unit;
Douglas Gregor9b7db622011-02-16 18:16:54 +0000822 unsigned &Hash;
823
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000824public:
Douglas Gregor9b7db622011-02-16 18:16:54 +0000825 TopLevelDeclTrackerConsumer(ASTUnit &_Unit, unsigned &Hash)
826 : Unit(_Unit), Hash(Hash) {
827 Hash = 0;
828 }
Douglas Gregor9b7db622011-02-16 18:16:54 +0000829
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000830 void handleTopLevelDecl(Decl *D) {
Argyrios Kyrtzidis35593a92011-11-16 02:35:10 +0000831 if (!D)
832 return;
833
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000834 // FIXME: Currently ObjC method declarations are incorrectly being
835 // reported as top-level declarations, even though their DeclContext
836 // is the containing ObjC @interface/@implementation. This is a
837 // fundamental problem in the parser right now.
838 if (isa<ObjCMethodDecl>(D))
839 return;
840
841 AddTopLevelDeclarationToHash(D, Hash);
842 Unit.addTopLevelDecl(D);
843
844 handleFileLevelDecl(D);
845 }
846
847 void handleFileLevelDecl(Decl *D) {
848 Unit.addFileLevelDecl(D);
849 if (NamespaceDecl *NSD = dyn_cast<NamespaceDecl>(D)) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700850 for (auto *I : NSD->decls())
851 handleFileLevelDecl(I);
Ted Kremenekda5a4282010-05-03 20:16:35 +0000852 }
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000853 }
Sebastian Redl27372b42010-08-11 18:52:41 +0000854
Stephen Hines651f13c2014-04-23 16:59:28 -0700855 bool HandleTopLevelDecl(DeclGroupRef D) override {
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000856 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it)
857 handleTopLevelDecl(*it);
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000858 return true;
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000859 }
860
Sebastian Redl27372b42010-08-11 18:52:41 +0000861 // We're not interested in "interesting" decls.
Stephen Hines651f13c2014-04-23 16:59:28 -0700862 void HandleInterestingDecl(DeclGroupRef) override {}
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000863
Stephen Hines651f13c2014-04-23 16:59:28 -0700864 void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) override {
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000865 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it)
866 handleTopLevelDecl(*it);
867 }
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000868
Stephen Hines651f13c2014-04-23 16:59:28 -0700869 ASTMutationListener *GetASTMutationListener() override {
Argyrios Kyrtzidis7eca8d22013-05-10 01:28:51 +0000870 return Unit.getASTMutationListener();
871 }
872
Stephen Hines651f13c2014-04-23 16:59:28 -0700873 ASTDeserializationListener *GetASTDeserializationListener() override {
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000874 return Unit.getDeserializationListener();
875 }
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000876};
877
878class TopLevelDeclTrackerAction : public ASTFrontendAction {
879public:
880 ASTUnit &Unit;
881
Stephen Hines176edba2014-12-01 14:53:08 -0800882 std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
883 StringRef InFile) override {
Douglas Gregor9b7db622011-02-16 18:16:54 +0000884 CI.getPreprocessor().addPPCallbacks(
Stephen Hines176edba2014-12-01 14:53:08 -0800885 llvm::make_unique<MacroDefinitionTrackerPPCallbacks>(
886 Unit.getCurrentTopLevelHashValue()));
887 return llvm::make_unique<TopLevelDeclTrackerConsumer>(
888 Unit, Unit.getCurrentTopLevelHashValue());
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000889 }
890
891public:
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000892 TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {}
893
Stephen Hines651f13c2014-04-23 16:59:28 -0700894 bool hasCodeCompletionSupport() const override { return false; }
895 TranslationUnitKind getTranslationUnitKind() override {
Douglas Gregor467dc882011-08-25 22:30:56 +0000896 return Unit.getTranslationUnitKind();
Douglas Gregordf95a132010-08-09 20:45:32 +0000897 }
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000898};
899
Benjamin Kramerb62b8b92013-06-11 13:07:19 +0000900class PrecompilePreambleAction : public ASTFrontendAction {
901 ASTUnit &Unit;
902 bool HasEmittedPreamblePCH;
903
904public:
905 explicit PrecompilePreambleAction(ASTUnit &Unit)
906 : Unit(Unit), HasEmittedPreamblePCH(false) {}
907
Stephen Hines176edba2014-12-01 14:53:08 -0800908 std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
909 StringRef InFile) override;
Benjamin Kramerb62b8b92013-06-11 13:07:19 +0000910 bool hasEmittedPreamblePCH() const { return HasEmittedPreamblePCH; }
911 void setHasEmittedPreamblePCH() { HasEmittedPreamblePCH = true; }
Stephen Hines651f13c2014-04-23 16:59:28 -0700912 bool shouldEraseOutputFiles() override { return !hasEmittedPreamblePCH(); }
Benjamin Kramerb62b8b92013-06-11 13:07:19 +0000913
Stephen Hines651f13c2014-04-23 16:59:28 -0700914 bool hasCodeCompletionSupport() const override { return false; }
915 bool hasASTFileSupport() const override { return false; }
916 TranslationUnitKind getTranslationUnitKind() override { return TU_Prefix; }
Benjamin Kramerb62b8b92013-06-11 13:07:19 +0000917};
918
Argyrios Kyrtzidis92ddef12011-09-19 20:40:48 +0000919class PrecompilePreambleConsumer : public PCHGenerator {
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000920 ASTUnit &Unit;
Benjamin Kramerb62b8b92013-06-11 13:07:19 +0000921 unsigned &Hash;
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000922 std::vector<Decl *> TopLevelDecls;
Benjamin Kramerb62b8b92013-06-11 13:07:19 +0000923 PrecompilePreambleAction *Action;
924
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000925public:
Benjamin Kramerb62b8b92013-06-11 13:07:19 +0000926 PrecompilePreambleConsumer(ASTUnit &Unit, PrecompilePreambleAction *Action,
927 const Preprocessor &PP, StringRef isysroot,
928 raw_ostream *Out)
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700929 : PCHGenerator(PP, "", nullptr, isysroot, Out, /*AllowASTWithErrors=*/true),
Benjamin Kramerb62b8b92013-06-11 13:07:19 +0000930 Unit(Unit), Hash(Unit.getCurrentTopLevelHashValue()), Action(Action) {
Douglas Gregor9b7db622011-02-16 18:16:54 +0000931 Hash = 0;
932 }
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000933
Stephen Hines651f13c2014-04-23 16:59:28 -0700934 bool HandleTopLevelDecl(DeclGroupRef D) override {
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000935 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
936 Decl *D = *it;
937 // 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 Gregor9b7db622011-02-16 18:16:54 +0000943 AddTopLevelDeclarationToHash(D, Hash);
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000944 TopLevelDecls.push_back(D);
945 }
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000946 return true;
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000947 }
948
Stephen Hines651f13c2014-04-23 16:59:28 -0700949 void HandleTranslationUnit(ASTContext &Ctx) override {
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000950 PCHGenerator::HandleTranslationUnit(Ctx);
Argyrios Kyrtzidis1f01f7c2013-06-11 00:36:55 +0000951 if (hasEmittedPCH()) {
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000952 // Translate the top-level declarations we captured during
953 // parsing into declaration IDs in the precompiled
954 // preamble. This will allow us to deserialize those top-level
955 // declarations when requested.
Argyrios Kyrtzidis51e75ae2013-08-07 21:17:33 +0000956 for (unsigned I = 0, N = TopLevelDecls.size(); I != N; ++I) {
957 Decl *D = TopLevelDecls[I];
958 // Invalid top-level decls may not have been serialized.
959 if (D->isInvalidDecl())
960 continue;
961 Unit.addTopLevelDeclFromPreamble(getWriter().getDeclID(D));
962 }
Benjamin Kramerb62b8b92013-06-11 13:07:19 +0000963
964 Action->setHasEmittedPreamblePCH();
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000965 }
966 }
967};
968
Benjamin Kramerb62b8b92013-06-11 13:07:19 +0000969}
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000970
Stephen Hines176edba2014-12-01 14:53:08 -0800971std::unique_ptr<ASTConsumer>
972PrecompilePreambleAction::CreateASTConsumer(CompilerInstance &CI,
973 StringRef InFile) {
Benjamin Kramerb62b8b92013-06-11 13:07:19 +0000974 std::string Sysroot;
975 std::string OutputFile;
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700976 raw_ostream *OS = nullptr;
Benjamin Kramerb62b8b92013-06-11 13:07:19 +0000977 if (GeneratePCHAction::ComputeASTConsumerArguments(CI, InFile, Sysroot,
978 OutputFile, OS))
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700979 return nullptr;
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000980
Benjamin Kramerb62b8b92013-06-11 13:07:19 +0000981 if (!CI.getFrontendOpts().RelocatablePCH)
982 Sysroot.clear();
Douglas Gregor832d6202011-07-22 16:35:34 +0000983
Stephen Hines176edba2014-12-01 14:53:08 -0800984 CI.getPreprocessor().addPPCallbacks(
985 llvm::make_unique<MacroDefinitionTrackerPPCallbacks>(
986 Unit.getCurrentTopLevelHashValue()));
987 return llvm::make_unique<PrecompilePreambleConsumer>(
988 Unit, this, CI.getPreprocessor(), Sysroot, OS);
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000989}
990
Benjamin Kramerfe57db22013-05-05 12:39:28 +0000991static bool isNonDriverDiag(const StoredDiagnostic &StoredDiag) {
992 return StoredDiag.getLocation().isValid();
993}
994
995static void
996checkAndRemoveNonDriverDiags(SmallVectorImpl<StoredDiagnostic> &StoredDiags) {
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +0000997 // Get rid of stored diagnostics except the ones from the driver which do not
998 // have a source location.
Benjamin Kramerfe57db22013-05-05 12:39:28 +0000999 StoredDiags.erase(
1000 std::remove_if(StoredDiags.begin(), StoredDiags.end(), isNonDriverDiag),
1001 StoredDiags.end());
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00001002}
1003
1004static void checkAndSanitizeDiags(SmallVectorImpl<StoredDiagnostic> &
1005 StoredDiagnostics,
1006 SourceManager &SM) {
1007 // The stored diagnostic has the old source manager in it; update
1008 // the locations to refer into the new source manager. Since we've
1009 // been careful to make sure that the source manager's state
1010 // before and after are identical, so that we can reuse the source
1011 // location itself.
1012 for (unsigned I = 0, N = StoredDiagnostics.size(); I < N; ++I) {
1013 if (StoredDiagnostics[I].getLocation().isValid()) {
1014 FullSourceLoc Loc(StoredDiagnostics[I].getLocation(), SM);
1015 StoredDiagnostics[I].setLocation(Loc);
1016 }
1017 }
1018}
1019
Douglas Gregorabc563f2010-07-19 21:46:24 +00001020/// Parse the source file into a translation unit using the given compiler
1021/// invocation, replacing the current translation unit.
1022///
1023/// \returns True if a failure occurred that causes the ASTUnit not to
1024/// contain any translation-unit information, false otherwise.
Stephen Hines176edba2014-12-01 14:53:08 -08001025bool ASTUnit::Parse(std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer) {
1026 SavedMainFileBuffer.reset();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001027
Stephen Hines176edba2014-12-01 14:53:08 -08001028 if (!Invocation)
Douglas Gregorabc563f2010-07-19 21:46:24 +00001029 return true;
Stephen Hines176edba2014-12-01 14:53:08 -08001030
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001031 // Create the compiler instance to use for building the AST.
Stephen Hines651f13c2014-04-23 16:59:28 -07001032 std::unique_ptr<CompilerInstance> Clang(new CompilerInstance());
Ted Kremenek03201fb2011-03-21 18:40:07 +00001033
1034 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00001035 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1036 CICleanup(Clang.get());
Ted Kremenek03201fb2011-03-21 18:40:07 +00001037
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001038 IntrusiveRefCntPtr<CompilerInvocation>
Argyrios Kyrtzidis26d43cd2011-09-12 18:09:38 +00001039 CCInvocation(new CompilerInvocation(*Invocation));
1040
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001041 Clang->setInvocation(CCInvocation.get());
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001042 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
Douglas Gregorabc563f2010-07-19 21:46:24 +00001043
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001044 // Set up diagnostics, capturing any diagnostics that would
1045 // otherwise be dropped.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001046 Clang->setDiagnostics(&getDiagnostics());
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001047
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001048 // Create the target instance.
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001049 Clang->setTarget(TargetInfo::CreateTargetInfo(
1050 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
Stephen Hines176edba2014-12-01 14:53:08 -08001051 if (!Clang->hasTarget())
Douglas Gregorabc563f2010-07-19 21:46:24 +00001052 return true;
Douglas Gregor671947b2010-08-19 01:33:06 +00001053
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001054 // Inform the target of the language options.
1055 //
1056 // FIXME: We shouldn't need to do this, the target should be immutable once
1057 // created. This complexity should be lifted elsewhere.
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001058 Clang->getTarget().adjust(Clang->getLangOpts());
Douglas Gregorabc563f2010-07-19 21:46:24 +00001059
Ted Kremenek03201fb2011-03-21 18:40:07 +00001060 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001061 "Invocation must have exactly one source file!");
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001062 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001063 "FIXME: AST inputs not yet supported here!");
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001064 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
Daniel Dunbarfaddc3e2010-06-07 23:26:47 +00001065 "IR inputs not support here!");
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001066
Douglas Gregorabc563f2010-07-19 21:46:24 +00001067 // Configure the various subsystems.
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001068 LangOpts = Clang->getInvocation().LangOpts;
Ted Kremenek03201fb2011-03-21 18:40:07 +00001069 FileSystemOpts = Clang->getFileSystemOpts();
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001070 IntrusiveRefCntPtr<vfs::FileSystem> VFS =
1071 createVFSFromCompilerInvocation(Clang->getInvocation(), getDiagnostics());
Stephen Hines176edba2014-12-01 14:53:08 -08001072 if (!VFS)
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001073 return true;
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001074 FileMgr = new FileManager(FileSystemOpts, VFS);
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001075 SourceMgr = new SourceManager(getDiagnostics(), *FileMgr,
1076 UserFilesAreVolatile);
Douglas Gregor914ed9d2010-08-13 03:15:25 +00001077 TheSema.reset();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001078 Ctx = nullptr;
1079 PP = nullptr;
1080 Reader = nullptr;
1081
Douglas Gregorabc563f2010-07-19 21:46:24 +00001082 // Clear out old caches and data.
1083 TopLevelDecls.clear();
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +00001084 clearFileLevelDecls();
Douglas Gregorabc563f2010-07-19 21:46:24 +00001085 CleanTemporaryFiles();
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001086
Douglas Gregorf128fed2010-08-20 00:02:33 +00001087 if (!OverrideMainBuffer) {
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00001088 checkAndRemoveNonDriverDiags(StoredDiagnostics);
Douglas Gregorf128fed2010-08-20 00:02:33 +00001089 TopLevelDeclsInPreamble.clear();
1090 }
1091
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001092 // Create a file manager object to provide access to and cache the filesystem.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001093 Clang->setFileManager(&getFileManager());
Douglas Gregorabc563f2010-07-19 21:46:24 +00001094
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001095 // Create the source manager.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001096 Clang->setSourceManager(&getSourceManager());
Douglas Gregorabc563f2010-07-19 21:46:24 +00001097
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001098 // If the main file has been overridden due to the use of a preamble,
1099 // make that override happen and introduce the preamble.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001100 PreprocessorOptions &PreprocessorOpts = Clang->getPreprocessorOpts();
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001101 if (OverrideMainBuffer) {
Stephen Hines176edba2014-12-01 14:53:08 -08001102 PreprocessorOpts.addRemappedFile(OriginalSourceFile,
1103 OverrideMainBuffer.get());
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001104 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
1105 PreprocessorOpts.PrecompiledPreambleBytes.second
1106 = PreambleEndsAtStartOfLine;
Ted Kremenek1872b312011-10-27 17:55:18 +00001107 PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001108 PreprocessorOpts.DisablePCHValidation = true;
Douglas Gregor28233422010-07-27 14:52:07 +00001109
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001110 // The stored diagnostic has the old source manager in it; update
1111 // the locations to refer into the new source manager. Since we've
1112 // been careful to make sure that the source manager's state
1113 // before and after are identical, so that we can reuse the source
1114 // location itself.
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00001115 checkAndSanitizeDiags(StoredDiagnostics, getSourceManager());
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001116
1117 // Keep track of the override buffer;
Stephen Hines176edba2014-12-01 14:53:08 -08001118 SavedMainFileBuffer = std::move(OverrideMainBuffer);
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001119 }
Stephen Hines651f13c2014-04-23 16:59:28 -07001120
1121 std::unique_ptr<TopLevelDeclTrackerAction> Act(
1122 new TopLevelDeclTrackerAction(*this));
1123
Ted Kremenek25a11e12011-03-22 01:15:24 +00001124 // Recover resources if we crash before exiting this method.
1125 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1126 ActCleanup(Act.get());
1127
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001128 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0]))
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001129 goto error;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001130
Stephen Hines176edba2014-12-01 14:53:08 -08001131 if (SavedMainFileBuffer) {
Ted Kremenek1872b312011-10-27 17:55:18 +00001132 std::string ModName = getPreambleFile(this);
Stephen Hines651f13c2014-04-23 16:59:28 -07001133 TranslateStoredDiagnostics(getFileManager(), getSourceManager(),
1134 PreambleDiagnostics, StoredDiagnostics);
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001135 }
1136
Argyrios Kyrtzidis374a00b2012-06-08 05:48:06 +00001137 if (!Act->Execute())
1138 goto error;
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001139
1140 transferASTDataFromCompilerInstance(*Clang);
Douglas Gregorabc563f2010-07-19 21:46:24 +00001141
Daniel Dunbarf772d1e2009-12-04 08:17:33 +00001142 Act->EndSourceFile();
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001143
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001144 FailedParseDiagnostics.clear();
1145
Douglas Gregorabc563f2010-07-19 21:46:24 +00001146 return false;
Ted Kremenek4f327862011-03-21 18:40:17 +00001147
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001148error:
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001149 // Remove the overridden buffer we used for the preamble.
Stephen Hines176edba2014-12-01 14:53:08 -08001150 SavedMainFileBuffer = nullptr;
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001151
1152 // Keep the ownership of the data in the ASTUnit because the client may
1153 // want to see the diagnostics.
1154 transferASTDataFromCompilerInstance(*Clang);
1155 FailedParseDiagnostics.swap(StoredDiagnostics);
Douglas Gregord54eb442010-10-12 16:25:54 +00001156 StoredDiagnostics.clear();
Argyrios Kyrtzidis3e9d3262011-10-24 17:25:20 +00001157 NumStoredDiagnosticsFromDriver = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001158 return true;
1159}
1160
Douglas Gregor44c181a2010-07-23 00:33:23 +00001161/// \brief Simple function to retrieve a path for a preamble precompiled header.
1162static std::string GetPreamblePCHPath() {
Douglas Gregor424668c2010-09-11 18:05:19 +00001163 // FIXME: This is a hack so that we can override the preamble file during
1164 // crash-recovery testing, which is the only case where the preamble files
Rafael Espindola85d28482013-06-26 04:02:37 +00001165 // are not necessarily cleaned up.
Douglas Gregor424668c2010-09-11 18:05:19 +00001166 const char *TmpFile = ::getenv("CINDEXTEST_PREAMBLE_FILE");
1167 if (TmpFile)
1168 return TmpFile;
Rafael Espindola85d28482013-06-26 04:02:37 +00001169
1170 SmallString<128> Path;
Rafael Espindola1ec4a862013-07-05 20:00:06 +00001171 llvm::sys::fs::createTemporaryFile("preamble", "pch", Path);
Rafael Espindola85d28482013-06-26 04:02:37 +00001172
1173 return Path.str();
Douglas Gregor44c181a2010-07-23 00:33:23 +00001174}
1175
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001176/// \brief Compute the preamble for the main file, providing the source buffer
1177/// that corresponds to the main file along with a pair (bytes, start-of-line)
1178/// that describes the preamble.
Stephen Hines176edba2014-12-01 14:53:08 -08001179ASTUnit::ComputedPreamble
1180ASTUnit::ComputePreamble(CompilerInvocation &Invocation, unsigned MaxLines) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001181 FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
Chris Lattner39b49bc2010-11-23 08:35:12 +00001182 PreprocessorOptions &PreprocessorOpts = Invocation.getPreprocessorOpts();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001183
Douglas Gregor44c181a2010-07-23 00:33:23 +00001184 // Try to determine if the main file has been remapped, either from the
1185 // command line (to another file) or directly through the compiler invocation
1186 // (to a memory buffer).
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001187 llvm::MemoryBuffer *Buffer = nullptr;
Stephen Hines176edba2014-12-01 14:53:08 -08001188 std::unique_ptr<llvm::MemoryBuffer> BufferOwner;
Rafael Espindola105b2072013-06-18 19:40:07 +00001189 std::string MainFilePath(FrontendOpts.Inputs[0].getFile());
Rafael Espindola44888352013-07-29 21:26:52 +00001190 llvm::sys::fs::UniqueID MainFileID;
Rafael Espindolada4cb0c2013-06-20 15:12:38 +00001191 if (!llvm::sys::fs::getUniqueID(MainFilePath, MainFileID)) {
Douglas Gregor44c181a2010-07-23 00:33:23 +00001192 // Check whether there is a file-file remapping of the main file
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001193 for (const auto &RF : PreprocessorOpts.RemappedFiles) {
1194 std::string MPath(RF.first);
Rafael Espindola44888352013-07-29 21:26:52 +00001195 llvm::sys::fs::UniqueID MID;
Rafael Espindolada4cb0c2013-06-20 15:12:38 +00001196 if (!llvm::sys::fs::getUniqueID(MPath, MID)) {
Rafael Espindola105b2072013-06-18 19:40:07 +00001197 if (MainFileID == MID) {
Douglas Gregor44c181a2010-07-23 00:33:23 +00001198 // We found a remapping. Try to load the resulting, remapped source.
Stephen Hines176edba2014-12-01 14:53:08 -08001199 BufferOwner = getBufferForFile(RF.second);
1200 if (!BufferOwner)
1201 return ComputedPreamble(nullptr, nullptr, 0, true);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001202 }
1203 }
1204 }
1205
1206 // Check whether there is a file-buffer remapping. It supercedes the
1207 // file-file remapping.
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001208 for (const auto &RB : PreprocessorOpts.RemappedFileBuffers) {
1209 std::string MPath(RB.first);
Rafael Espindola44888352013-07-29 21:26:52 +00001210 llvm::sys::fs::UniqueID MID;
Rafael Espindolada4cb0c2013-06-20 15:12:38 +00001211 if (!llvm::sys::fs::getUniqueID(MPath, MID)) {
Rafael Espindola105b2072013-06-18 19:40:07 +00001212 if (MainFileID == MID) {
1213 // We found a remapping.
Stephen Hines176edba2014-12-01 14:53:08 -08001214 BufferOwner.reset();
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001215 Buffer = const_cast<llvm::MemoryBuffer *>(RB.second);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001216 }
1217 }
Douglas Gregor175c4a92010-07-23 23:58:40 +00001218 }
Douglas Gregor44c181a2010-07-23 00:33:23 +00001219 }
1220
1221 // If the main source file was not remapped, load it now.
Stephen Hines176edba2014-12-01 14:53:08 -08001222 if (!Buffer && !BufferOwner) {
1223 BufferOwner = getBufferForFile(FrontendOpts.Inputs[0].getFile());
1224 if (!BufferOwner)
1225 return ComputedPreamble(nullptr, nullptr, 0, true);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001226 }
Stephen Hines176edba2014-12-01 14:53:08 -08001227
1228 if (!Buffer)
1229 Buffer = BufferOwner.get();
1230 auto Pre = Lexer::ComputePreamble(Buffer->getBuffer(),
1231 *Invocation.getLangOpts(), MaxLines);
1232 return ComputedPreamble(Buffer, std::move(BufferOwner), Pre.first,
1233 Pre.second);
Douglas Gregor175c4a92010-07-23 23:58:40 +00001234}
1235
Stephen Hines651f13c2014-04-23 16:59:28 -07001236ASTUnit::PreambleFileHash
1237ASTUnit::PreambleFileHash::createForFile(off_t Size, time_t ModTime) {
1238 PreambleFileHash Result;
1239 Result.Size = Size;
1240 Result.ModTime = ModTime;
1241 memset(Result.MD5, 0, sizeof(Result.MD5));
Douglas Gregor754f3492010-07-24 00:38:13 +00001242 return Result;
1243}
1244
Stephen Hines651f13c2014-04-23 16:59:28 -07001245ASTUnit::PreambleFileHash ASTUnit::PreambleFileHash::createForMemoryBuffer(
1246 const llvm::MemoryBuffer *Buffer) {
1247 PreambleFileHash Result;
1248 Result.Size = Buffer->getBufferSize();
1249 Result.ModTime = 0;
1250
1251 llvm::MD5 MD5Ctx;
1252 MD5Ctx.update(Buffer->getBuffer().data());
1253 MD5Ctx.final(Result.MD5);
1254
1255 return Result;
1256}
1257
1258namespace clang {
1259bool operator==(const ASTUnit::PreambleFileHash &LHS,
1260 const ASTUnit::PreambleFileHash &RHS) {
1261 return LHS.Size == RHS.Size && LHS.ModTime == RHS.ModTime &&
1262 memcmp(LHS.MD5, RHS.MD5, sizeof(LHS.MD5)) == 0;
1263}
1264} // namespace clang
1265
1266static std::pair<unsigned, unsigned>
1267makeStandaloneRange(CharSourceRange Range, const SourceManager &SM,
1268 const LangOptions &LangOpts) {
1269 CharSourceRange FileRange = Lexer::makeFileCharRange(Range, SM, LangOpts);
1270 unsigned Offset = SM.getFileOffset(FileRange.getBegin());
1271 unsigned EndOffset = SM.getFileOffset(FileRange.getEnd());
1272 return std::make_pair(Offset, EndOffset);
1273}
1274
Stephen Hines176edba2014-12-01 14:53:08 -08001275static ASTUnit::StandaloneFixIt makeStandaloneFixIt(const SourceManager &SM,
1276 const LangOptions &LangOpts,
1277 const FixItHint &InFix) {
1278 ASTUnit::StandaloneFixIt OutFix;
Stephen Hines651f13c2014-04-23 16:59:28 -07001279 OutFix.RemoveRange = makeStandaloneRange(InFix.RemoveRange, SM, LangOpts);
1280 OutFix.InsertFromRange = makeStandaloneRange(InFix.InsertFromRange, SM,
1281 LangOpts);
1282 OutFix.CodeToInsert = InFix.CodeToInsert;
1283 OutFix.BeforePreviousInsertions = InFix.BeforePreviousInsertions;
Stephen Hines176edba2014-12-01 14:53:08 -08001284 return OutFix;
Stephen Hines651f13c2014-04-23 16:59:28 -07001285}
1286
Stephen Hines176edba2014-12-01 14:53:08 -08001287static ASTUnit::StandaloneDiagnostic
1288makeStandaloneDiagnostic(const LangOptions &LangOpts,
1289 const StoredDiagnostic &InDiag) {
1290 ASTUnit::StandaloneDiagnostic OutDiag;
Stephen Hines651f13c2014-04-23 16:59:28 -07001291 OutDiag.ID = InDiag.getID();
1292 OutDiag.Level = InDiag.getLevel();
1293 OutDiag.Message = InDiag.getMessage();
1294 OutDiag.LocOffset = 0;
1295 if (InDiag.getLocation().isInvalid())
Stephen Hines176edba2014-12-01 14:53:08 -08001296 return OutDiag;
Stephen Hines651f13c2014-04-23 16:59:28 -07001297 const SourceManager &SM = InDiag.getLocation().getManager();
1298 SourceLocation FileLoc = SM.getFileLoc(InDiag.getLocation());
1299 OutDiag.Filename = SM.getFilename(FileLoc);
1300 if (OutDiag.Filename.empty())
Stephen Hines176edba2014-12-01 14:53:08 -08001301 return OutDiag;
Stephen Hines651f13c2014-04-23 16:59:28 -07001302 OutDiag.LocOffset = SM.getFileOffset(FileLoc);
1303 for (StoredDiagnostic::range_iterator
1304 I = InDiag.range_begin(), E = InDiag.range_end(); I != E; ++I) {
1305 OutDiag.Ranges.push_back(makeStandaloneRange(*I, SM, LangOpts));
1306 }
Stephen Hines176edba2014-12-01 14:53:08 -08001307 for (StoredDiagnostic::fixit_iterator I = InDiag.fixit_begin(),
1308 E = InDiag.fixit_end();
1309 I != E; ++I)
1310 OutDiag.FixIts.push_back(makeStandaloneFixIt(SM, LangOpts, *I));
1311
1312 return OutDiag;
Stephen Hines651f13c2014-04-23 16:59:28 -07001313}
1314
Douglas Gregor175c4a92010-07-23 23:58:40 +00001315/// \brief Attempt to build or re-use a precompiled preamble when (re-)parsing
1316/// the source file.
1317///
1318/// This routine will compute the preamble of the main source file. If a
1319/// non-trivial preamble is found, it will precompile that preamble into a
1320/// precompiled header so that the precompiled preamble can be used to reduce
1321/// reparsing time. If a precompiled preamble has already been constructed,
1322/// this routine will determine if it is still valid and, if so, avoid
1323/// rebuilding the precompiled preamble.
1324///
Douglas Gregordf95a132010-08-09 20:45:32 +00001325/// \param AllowRebuild When true (the default), this routine is
1326/// allowed to rebuild the precompiled preamble if it is found to be
1327/// out-of-date.
1328///
1329/// \param MaxLines When non-zero, the maximum number of lines that
1330/// can occur within the preamble.
1331///
Douglas Gregor754f3492010-07-24 00:38:13 +00001332/// \returns If the precompiled preamble can be used, returns a newly-allocated
1333/// buffer that should be used in place of the main file when doing so.
1334/// Otherwise, returns a NULL pointer.
Stephen Hines176edba2014-12-01 14:53:08 -08001335std::unique_ptr<llvm::MemoryBuffer>
1336ASTUnit::getMainBufferWithPrecompiledPreamble(
1337 const CompilerInvocation &PreambleInvocationIn, bool AllowRebuild,
1338 unsigned MaxLines) {
1339
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001340 IntrusiveRefCntPtr<CompilerInvocation>
Douglas Gregor01b6e312011-07-01 18:22:13 +00001341 PreambleInvocation(new CompilerInvocation(PreambleInvocationIn));
1342 FrontendOptions &FrontendOpts = PreambleInvocation->getFrontendOpts();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001343 PreprocessorOptions &PreprocessorOpts
Douglas Gregor01b6e312011-07-01 18:22:13 +00001344 = PreambleInvocation->getPreprocessorOpts();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001345
Stephen Hines176edba2014-12-01 14:53:08 -08001346 ComputedPreamble NewPreamble = ComputePreamble(*PreambleInvocation, MaxLines);
Douglas Gregor175c4a92010-07-23 23:58:40 +00001347
Stephen Hines176edba2014-12-01 14:53:08 -08001348 if (!NewPreamble.Size) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001349 // We couldn't find a preamble in the main source. Clear out the current
1350 // preamble, if we have one. It's obviously no good any more.
1351 Preamble.clear();
Ted Kremenek1872b312011-10-27 17:55:18 +00001352 erasePreambleFile(this);
Douglas Gregoreababfb2010-08-04 05:53:38 +00001353
1354 // The next time we actually see a preamble, precompile it.
1355 PreambleRebuildCounter = 1;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001356 return nullptr;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001357 }
1358
1359 if (!Preamble.empty()) {
1360 // We've previously computed a preamble. Check whether we have the same
1361 // preamble now that we did before, and that there's enough space in
1362 // the main-file buffer within the precompiled preamble to fit the
1363 // new main file.
Stephen Hines176edba2014-12-01 14:53:08 -08001364 if (Preamble.size() == NewPreamble.Size &&
1365 PreambleEndsAtStartOfLine == NewPreamble.PreambleEndsAtStartOfLine &&
1366 memcmp(Preamble.getBufferStart(), NewPreamble.Buffer->getBufferStart(),
1367 NewPreamble.Size) == 0) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001368 // The preamble has not changed. We may be able to re-use the precompiled
1369 // preamble.
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001370
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001371 // Check that none of the files used by the preamble have changed.
1372 bool AnyFileChanged = false;
1373
1374 // First, make a record of those files that have been overridden via
1375 // remapping or unsaved_files.
Stephen Hines651f13c2014-04-23 16:59:28 -07001376 llvm::StringMap<PreambleFileHash> OverriddenFiles;
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001377 for (const auto &R : PreprocessorOpts.RemappedFiles) {
1378 if (AnyFileChanged)
1379 break;
1380
Stephen Hines651f13c2014-04-23 16:59:28 -07001381 vfs::Status Status;
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001382 if (FileMgr->getNoncachedStatValue(R.second, Status)) {
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001383 // If we can't stat the file we're remapping to, assume that something
1384 // horrible happened.
1385 AnyFileChanged = true;
1386 break;
1387 }
Rafael Espindolaaefb1d32013-07-29 18:22:23 +00001388
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001389 OverriddenFiles[R.first] = PreambleFileHash::createForFile(
Rafael Espindolaaefb1d32013-07-29 18:22:23 +00001390 Status.getSize(), Status.getLastModificationTime().toEpochTime());
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001391 }
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001392
1393 for (const auto &RB : PreprocessorOpts.RemappedFileBuffers) {
1394 if (AnyFileChanged)
1395 break;
1396 OverriddenFiles[RB.first] =
1397 PreambleFileHash::createForMemoryBuffer(RB.second);
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001398 }
1399
1400 // Check whether anything has changed.
Stephen Hines651f13c2014-04-23 16:59:28 -07001401 for (llvm::StringMap<PreambleFileHash>::iterator
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001402 F = FilesInPreamble.begin(), FEnd = FilesInPreamble.end();
1403 !AnyFileChanged && F != FEnd;
1404 ++F) {
Stephen Hines651f13c2014-04-23 16:59:28 -07001405 llvm::StringMap<PreambleFileHash>::iterator Overridden
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001406 = OverriddenFiles.find(F->first());
1407 if (Overridden != OverriddenFiles.end()) {
1408 // This file was remapped; check whether the newly-mapped file
1409 // matches up with the previous mapping.
1410 if (Overridden->second != F->second)
1411 AnyFileChanged = true;
1412 continue;
1413 }
1414
1415 // The file was not remapped; check whether it has changed on disk.
Stephen Hines651f13c2014-04-23 16:59:28 -07001416 vfs::Status Status;
Rafael Espindolaaefb1d32013-07-29 18:22:23 +00001417 if (FileMgr->getNoncachedStatValue(F->first(), Status)) {
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001418 // If we can't stat the file, assume that something horrible happened.
1419 AnyFileChanged = true;
Stephen Hines651f13c2014-04-23 16:59:28 -07001420 } else if (Status.getSize() != uint64_t(F->second.Size) ||
Rafael Espindolaaefb1d32013-07-29 18:22:23 +00001421 Status.getLastModificationTime().toEpochTime() !=
Stephen Hines651f13c2014-04-23 16:59:28 -07001422 uint64_t(F->second.ModTime))
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001423 AnyFileChanged = true;
1424 }
1425
1426 if (!AnyFileChanged) {
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001427 // Okay! We can re-use the precompiled preamble.
1428
1429 // Set the state of the diagnostic object to mimic its state
1430 // after parsing the preamble.
1431 getDiagnostics().Reset();
Douglas Gregor32be4a52010-10-11 21:37:58 +00001432 ProcessWarningOptions(getDiagnostics(),
Douglas Gregor01b6e312011-07-01 18:22:13 +00001433 PreambleInvocation->getDiagnosticOpts());
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001434 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001435
Stephen Hines651f13c2014-04-23 16:59:28 -07001436 return llvm::MemoryBuffer::getMemBufferCopy(
Stephen Hines176edba2014-12-01 14:53:08 -08001437 NewPreamble.Buffer->getBuffer(), FrontendOpts.Inputs[0].getFile());
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001438 }
Douglas Gregor175c4a92010-07-23 23:58:40 +00001439 }
Douglas Gregordf95a132010-08-09 20:45:32 +00001440
1441 // If we aren't allowed to rebuild the precompiled preamble, just
1442 // return now.
1443 if (!AllowRebuild)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001444 return nullptr;
Douglas Gregoraa3e6ba2010-10-08 04:03:57 +00001445
Douglas Gregor175c4a92010-07-23 23:58:40 +00001446 // We can't reuse the previously-computed preamble. Build a new one.
1447 Preamble.clear();
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001448 PreambleDiagnostics.clear();
Ted Kremenek1872b312011-10-27 17:55:18 +00001449 erasePreambleFile(this);
Douglas Gregoreababfb2010-08-04 05:53:38 +00001450 PreambleRebuildCounter = 1;
Douglas Gregordf95a132010-08-09 20:45:32 +00001451 } else if (!AllowRebuild) {
1452 // We aren't allowed to rebuild the precompiled preamble; just
1453 // return now.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001454 return nullptr;
Douglas Gregordf95a132010-08-09 20:45:32 +00001455 }
Douglas Gregoreababfb2010-08-04 05:53:38 +00001456
1457 // If the preamble rebuild counter > 1, it's because we previously
1458 // failed to build a preamble and we're not yet ready to try
1459 // again. Decrement the counter and return a failure.
1460 if (PreambleRebuildCounter > 1) {
1461 --PreambleRebuildCounter;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001462 return nullptr;
Douglas Gregoreababfb2010-08-04 05:53:38 +00001463 }
1464
Douglas Gregor2cd4fd42010-09-11 17:56:52 +00001465 // Create a temporary file for the precompiled preamble. In rare
1466 // circumstances, this can fail.
1467 std::string PreamblePCHPath = GetPreamblePCHPath();
1468 if (PreamblePCHPath.empty()) {
1469 // Try again next time.
1470 PreambleRebuildCounter = 1;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001471 return nullptr;
Douglas Gregor2cd4fd42010-09-11 17:56:52 +00001472 }
1473
Douglas Gregor175c4a92010-07-23 23:58:40 +00001474 // We did not previously compute a preamble, or it can't be reused anyway.
Douglas Gregor213f18b2010-10-28 15:44:59 +00001475 SimpleTimer PreambleTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00001476 PreambleTimer.setOutput("Precompiling preamble");
Douglas Gregor175c4a92010-07-23 23:58:40 +00001477
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001478 // Save the preamble text for later; we'll need to compare against it for
1479 // subsequent reparses.
Stephen Hines651f13c2014-04-23 16:59:28 -07001480 StringRef MainFilename = FrontendOpts.Inputs[0].getFile();
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00001481 Preamble.assign(FileMgr->getFile(MainFilename),
Stephen Hines176edba2014-12-01 14:53:08 -08001482 NewPreamble.Buffer->getBufferStart(),
1483 NewPreamble.Buffer->getBufferStart() + NewPreamble.Size);
1484 PreambleEndsAtStartOfLine = NewPreamble.PreambleEndsAtStartOfLine;
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001485
Stephen Hines176edba2014-12-01 14:53:08 -08001486 PreambleBuffer = llvm::MemoryBuffer::getMemBufferCopy(
1487 NewPreamble.Buffer->getBuffer().slice(0, Preamble.size()), MainFilename);
Rafael Espindola1cd7df42013-06-26 04:12:57 +00001488
Douglas Gregor44c181a2010-07-23 00:33:23 +00001489 // Remap the main source file to the preamble buffer.
Rafael Espindola1cd7df42013-06-26 04:12:57 +00001490 StringRef MainFilePath = FrontendOpts.Inputs[0].getFile();
Stephen Hines176edba2014-12-01 14:53:08 -08001491 PreprocessorOpts.addRemappedFile(MainFilePath, PreambleBuffer.get());
Rafael Espindola1cd7df42013-06-26 04:12:57 +00001492
Douglas Gregor44c181a2010-07-23 00:33:23 +00001493 // Tell the compiler invocation to generate a temporary precompiled header.
1494 FrontendOpts.ProgramAction = frontend::GeneratePCH;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001495 // FIXME: Generate the precompiled header into memory?
Douglas Gregor2cd4fd42010-09-11 17:56:52 +00001496 FrontendOpts.OutputFile = PreamblePCHPath;
Douglas Gregoraa3e6ba2010-10-08 04:03:57 +00001497 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
1498 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001499
1500 // Create the compiler instance to use for building the precompiled preamble.
Stephen Hines651f13c2014-04-23 16:59:28 -07001501 std::unique_ptr<CompilerInstance> Clang(new CompilerInstance());
Ted Kremenek03201fb2011-03-21 18:40:07 +00001502
1503 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00001504 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1505 CICleanup(Clang.get());
Ted Kremenek03201fb2011-03-21 18:40:07 +00001506
Douglas Gregor01b6e312011-07-01 18:22:13 +00001507 Clang->setInvocation(&*PreambleInvocation);
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001508 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
Douglas Gregor44c181a2010-07-23 00:33:23 +00001509
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001510 // Set up diagnostics, capturing all of the diagnostics produced.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001511 Clang->setDiagnostics(&getDiagnostics());
Douglas Gregor44c181a2010-07-23 00:33:23 +00001512
1513 // Create the target instance.
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001514 Clang->setTarget(TargetInfo::CreateTargetInfo(
1515 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
Ted Kremenek03201fb2011-03-21 18:40:07 +00001516 if (!Clang->hasTarget()) {
Rafael Espindola21b18242013-06-26 04:26:38 +00001517 llvm::sys::fs::remove(FrontendOpts.OutputFile);
Douglas Gregor175c4a92010-07-23 23:58:40 +00001518 Preamble.clear();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001519 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001520 PreprocessorOpts.RemappedFileBuffers.pop_back();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001521 return nullptr;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001522 }
1523
1524 // Inform the target of the language options.
1525 //
1526 // FIXME: We shouldn't need to do this, the target should be immutable once
1527 // created. This complexity should be lifted elsewhere.
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001528 Clang->getTarget().adjust(Clang->getLangOpts());
Douglas Gregor44c181a2010-07-23 00:33:23 +00001529
Ted Kremenek03201fb2011-03-21 18:40:07 +00001530 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Douglas Gregor44c181a2010-07-23 00:33:23 +00001531 "Invocation must have exactly one source file!");
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001532 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
Douglas Gregor44c181a2010-07-23 00:33:23 +00001533 "FIXME: AST inputs not yet supported here!");
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001534 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
Douglas Gregor44c181a2010-07-23 00:33:23 +00001535 "IR inputs not support here!");
1536
1537 // Clear out old caches and data.
Douglas Gregoraa3e6ba2010-10-08 04:03:57 +00001538 getDiagnostics().Reset();
Ted Kremenek03201fb2011-03-21 18:40:07 +00001539 ProcessWarningOptions(getDiagnostics(), Clang->getDiagnosticOpts());
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00001540 checkAndRemoveNonDriverDiags(StoredDiagnostics);
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001541 TopLevelDecls.clear();
1542 TopLevelDeclsInPreamble.clear();
Stephen Hines651f13c2014-04-23 16:59:28 -07001543 PreambleDiagnostics.clear();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001544
1545 IntrusiveRefCntPtr<vfs::FileSystem> VFS =
1546 createVFSFromCompilerInvocation(Clang->getInvocation(), getDiagnostics());
1547 if (!VFS)
1548 return nullptr;
1549
Douglas Gregor44c181a2010-07-23 00:33:23 +00001550 // Create a file manager object to provide access to and cache the filesystem.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001551 Clang->setFileManager(new FileManager(Clang->getFileSystemOpts(), VFS));
Douglas Gregor44c181a2010-07-23 00:33:23 +00001552
1553 // Create the source manager.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001554 Clang->setSourceManager(new SourceManager(getDiagnostics(),
Ted Kremenek4f327862011-03-21 18:40:17 +00001555 Clang->getFileManager()));
Stephen Hines651f13c2014-04-23 16:59:28 -07001556
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001557 auto PreambleDepCollector = std::make_shared<DependencyCollector>();
1558 Clang->addDependencyCollector(PreambleDepCollector);
1559
Stephen Hines651f13c2014-04-23 16:59:28 -07001560 std::unique_ptr<PrecompilePreambleAction> Act;
Douglas Gregor1d715ac2010-08-03 08:14:03 +00001561 Act.reset(new PrecompilePreambleAction(*this));
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001562 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
Rafael Espindola21b18242013-06-26 04:26:38 +00001563 llvm::sys::fs::remove(FrontendOpts.OutputFile);
Douglas Gregor175c4a92010-07-23 23:58:40 +00001564 Preamble.clear();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001565 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001566 PreprocessorOpts.RemappedFileBuffers.pop_back();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001567 return nullptr;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001568 }
1569
1570 Act->Execute();
Stephen Hines651f13c2014-04-23 16:59:28 -07001571
1572 // Transfer any diagnostics generated when parsing the preamble into the set
1573 // of preamble diagnostics.
Stephen Hines176edba2014-12-01 14:53:08 -08001574 for (stored_diag_iterator I = stored_diag_afterDriver_begin(),
1575 E = stored_diag_end();
1576 I != E; ++I)
1577 PreambleDiagnostics.push_back(
1578 makeStandaloneDiagnostic(Clang->getLangOpts(), *I));
Stephen Hines651f13c2014-04-23 16:59:28 -07001579
Douglas Gregor44c181a2010-07-23 00:33:23 +00001580 Act->EndSourceFile();
Ted Kremenek4f327862011-03-21 18:40:17 +00001581
Stephen Hines651f13c2014-04-23 16:59:28 -07001582 checkAndRemoveNonDriverDiags(StoredDiagnostics);
1583
Argyrios Kyrtzidis1f01f7c2013-06-11 00:36:55 +00001584 if (!Act->hasEmittedPreamblePCH()) {
Argyrios Kyrtzidis739f9e52013-06-11 16:42:34 +00001585 // The preamble PCH failed (e.g. there was a module loading fatal error),
1586 // so no precompiled header was generated. Forget that we even tried.
Douglas Gregor06e50442010-09-27 16:43:25 +00001587 // FIXME: Should we leave a note for ourselves to try again?
Rafael Espindola21b18242013-06-26 04:26:38 +00001588 llvm::sys::fs::remove(FrontendOpts.OutputFile);
Douglas Gregor175c4a92010-07-23 23:58:40 +00001589 Preamble.clear();
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001590 TopLevelDeclsInPreamble.clear();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001591 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001592 PreprocessorOpts.RemappedFileBuffers.pop_back();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001593 return nullptr;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001594 }
1595
1596 // Keep track of the preamble we precompiled.
Ted Kremenek1872b312011-10-27 17:55:18 +00001597 setPreambleFile(this, FrontendOpts.OutputFile);
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001598 NumWarningsInPreamble = getDiagnostics().getNumWarnings();
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001599
1600 // Keep track of all of the files that the source manager knows about,
1601 // so we can verify whether they have changed or not.
1602 FilesInPreamble.clear();
Ted Kremenek03201fb2011-03-21 18:40:07 +00001603 SourceManager &SourceMgr = Clang->getSourceManager();
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001604 for (auto &Filename : PreambleDepCollector->getDependencies()) {
1605 const FileEntry *File = Clang->getFileManager().getFile(Filename);
1606 if (!File || File == SourceMgr.getFileEntryForID(SourceMgr.getMainFileID()))
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001607 continue;
Stephen Hines651f13c2014-04-23 16:59:28 -07001608 if (time_t ModTime = File->getModificationTime()) {
1609 FilesInPreamble[File->getName()] = PreambleFileHash::createForFile(
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001610 File->getSize(), ModTime);
Stephen Hines651f13c2014-04-23 16:59:28 -07001611 } else {
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001612 llvm::MemoryBuffer *Buffer = SourceMgr.getMemoryBufferForFile(File);
Stephen Hines651f13c2014-04-23 16:59:28 -07001613 FilesInPreamble[File->getName()] =
1614 PreambleFileHash::createForMemoryBuffer(Buffer);
1615 }
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001616 }
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001617
Douglas Gregoreababfb2010-08-04 05:53:38 +00001618 PreambleRebuildCounter = 1;
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001619 PreprocessorOpts.RemappedFileBuffers.pop_back();
1620
Douglas Gregor9b7db622011-02-16 18:16:54 +00001621 // If the hash of top-level entities differs from the hash of the top-level
1622 // entities the last time we rebuilt the preamble, clear out the completion
1623 // cache.
1624 if (CurrentTopLevelHashValue != PreambleTopLevelHashValue) {
1625 CompletionCacheTopLevelHashValue = 0;
1626 PreambleTopLevelHashValue = CurrentTopLevelHashValue;
1627 }
Stephen Hines176edba2014-12-01 14:53:08 -08001628
1629 return llvm::MemoryBuffer::getMemBufferCopy(NewPreamble.Buffer->getBuffer(),
Stephen Hines651f13c2014-04-23 16:59:28 -07001630 MainFilename);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001631}
Douglas Gregorabc563f2010-07-19 21:46:24 +00001632
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001633void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
1634 std::vector<Decl *> Resolved;
1635 Resolved.reserve(TopLevelDeclsInPreamble.size());
1636 ExternalASTSource &Source = *getASTContext().getExternalSource();
1637 for (unsigned I = 0, N = TopLevelDeclsInPreamble.size(); I != N; ++I) {
1638 // Resolve the declaration ID to an actual declaration, possibly
1639 // deserializing the declaration in the process.
1640 Decl *D = Source.GetExternalDecl(TopLevelDeclsInPreamble[I]);
1641 if (D)
1642 Resolved.push_back(D);
1643 }
1644 TopLevelDeclsInPreamble.clear();
1645 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1646}
1647
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001648void ASTUnit::transferASTDataFromCompilerInstance(CompilerInstance &CI) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001649 // Steal the created target, context, and preprocessor if they have been
1650 // created.
1651 assert(CI.hasInvocation() && "missing invocation");
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001652 LangOpts = CI.getInvocation().LangOpts;
Stephen Hines176edba2014-12-01 14:53:08 -08001653 TheSema = CI.takeSema();
1654 Consumer = CI.takeASTConsumer();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001655 if (CI.hasASTContext())
1656 Ctx = &CI.getASTContext();
1657 if (CI.hasPreprocessor())
1658 PP = &CI.getPreprocessor();
1659 CI.setSourceManager(nullptr);
1660 CI.setFileManager(nullptr);
1661 if (CI.hasTarget())
1662 Target = &CI.getTarget();
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001663 Reader = CI.getModuleManager();
Argyrios Kyrtzidis3b7deda2013-05-24 05:44:08 +00001664 HadModuleLoaderFatalFailure = CI.hadModuleLoaderFatalFailure();
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001665}
1666
Chris Lattner5f9e2722011-07-23 10:55:15 +00001667StringRef ASTUnit::getMainFileName() const {
Argyrios Kyrtzidis814b51a2013-01-11 22:11:14 +00001668 if (Invocation && !Invocation->getFrontendOpts().Inputs.empty()) {
1669 const FrontendInputFile &Input = Invocation->getFrontendOpts().Inputs[0];
1670 if (Input.isFile())
1671 return Input.getFile();
1672 else
1673 return Input.getBuffer()->getBufferIdentifier();
1674 }
1675
1676 if (SourceMgr) {
1677 if (const FileEntry *
1678 FE = SourceMgr->getFileEntryForID(SourceMgr->getMainFileID()))
1679 return FE->getName();
1680 }
1681
1682 return StringRef();
Douglas Gregor213f18b2010-10-28 15:44:59 +00001683}
1684
Argyrios Kyrtzidis44f65a52013-03-05 20:21:14 +00001685StringRef ASTUnit::getASTFileName() const {
1686 if (!isMainFileAST())
1687 return StringRef();
1688
1689 serialization::ModuleFile &
1690 Mod = Reader->getModuleManager().getPrimaryModule();
1691 return Mod.FileName;
1692}
1693
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001694ASTUnit *ASTUnit::create(CompilerInvocation *CI,
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001695 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001696 bool CaptureDiagnostics,
1697 bool UserFilesAreVolatile) {
Stephen Hines651f13c2014-04-23 16:59:28 -07001698 std::unique_ptr<ASTUnit> AST;
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001699 AST.reset(new ASTUnit(false));
Stephen Hines176edba2014-12-01 14:53:08 -08001700 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001701 AST->Diagnostics = Diags;
Ted Kremenek4f327862011-03-21 18:40:17 +00001702 AST->Invocation = CI;
Anders Carlsson0d8d7e62011-03-18 18:22:40 +00001703 AST->FileSystemOpts = CI->getFileSystemOpts();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001704 IntrusiveRefCntPtr<vfs::FileSystem> VFS =
1705 createVFSFromCompilerInvocation(*CI, *Diags);
1706 if (!VFS)
1707 return nullptr;
1708 AST->FileMgr = new FileManager(AST->FileSystemOpts, VFS);
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001709 AST->UserFilesAreVolatile = UserFilesAreVolatile;
1710 AST->SourceMgr = new SourceManager(AST->getDiagnostics(), *AST->FileMgr,
1711 UserFilesAreVolatile);
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001712
Stephen Hines651f13c2014-04-23 16:59:28 -07001713 return AST.release();
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001714}
1715
Stephen Hines651f13c2014-04-23 16:59:28 -07001716ASTUnit *ASTUnit::LoadFromCompilerInvocationAction(
1717 CompilerInvocation *CI, IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
1718 ASTFrontendAction *Action, ASTUnit *Unit, bool Persistent,
1719 StringRef ResourceFilesPath, bool OnlyLocalDecls, bool CaptureDiagnostics,
1720 bool PrecompilePreamble, bool CacheCodeCompletionResults,
1721 bool IncludeBriefCommentsInCodeCompletion, bool UserFilesAreVolatile,
1722 std::unique_ptr<ASTUnit> *ErrAST) {
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001723 assert(CI && "A CompilerInvocation is required");
1724
Stephen Hines651f13c2014-04-23 16:59:28 -07001725 std::unique_ptr<ASTUnit> OwnAST;
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001726 ASTUnit *AST = Unit;
1727 if (!AST) {
1728 // Create the AST unit.
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001729 OwnAST.reset(create(CI, Diags, CaptureDiagnostics, UserFilesAreVolatile));
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001730 AST = OwnAST.get();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001731 if (!AST)
1732 return nullptr;
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001733 }
1734
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00001735 if (!ResourceFilesPath.empty()) {
1736 // Override the resources path.
1737 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
1738 }
1739 AST->OnlyLocalDecls = OnlyLocalDecls;
1740 AST->CaptureDiagnostics = CaptureDiagnostics;
1741 if (PrecompilePreamble)
1742 AST->PreambleRebuildCounter = 2;
Douglas Gregor467dc882011-08-25 22:30:56 +00001743 AST->TUKind = Action ? Action->getTranslationUnitKind() : TU_Complete;
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00001744 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00001745 AST->IncludeBriefCommentsInCodeCompletion
1746 = IncludeBriefCommentsInCodeCompletion;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001747
1748 // Recover resources if we crash before exiting this method.
1749 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001750 ASTUnitCleanup(OwnAST.get());
David Blaikied6471f72011-09-25 23:23:43 +00001751 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1752 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001753 DiagCleanup(Diags.get());
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001754
1755 // We'll manage file buffers ourselves.
1756 CI->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1757 CI->getFrontendOpts().DisableFree = false;
1758 ProcessWarningOptions(AST->getDiagnostics(), CI->getDiagnosticOpts());
1759
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001760 // Create the compiler instance to use for building the AST.
Stephen Hines651f13c2014-04-23 16:59:28 -07001761 std::unique_ptr<CompilerInstance> Clang(new CompilerInstance());
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001762
1763 // Recover resources if we crash before exiting this method.
1764 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1765 CICleanup(Clang.get());
1766
1767 Clang->setInvocation(CI);
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001768 AST->OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001769
1770 // Set up diagnostics, capturing any diagnostics that would
1771 // otherwise be dropped.
1772 Clang->setDiagnostics(&AST->getDiagnostics());
1773
1774 // Create the target instance.
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001775 Clang->setTarget(TargetInfo::CreateTargetInfo(
1776 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001777 if (!Clang->hasTarget())
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001778 return nullptr;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001779
1780 // Inform the target of the language options.
1781 //
1782 // FIXME: We shouldn't need to do this, the target should be immutable once
1783 // created. This complexity should be lifted elsewhere.
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001784 Clang->getTarget().adjust(Clang->getLangOpts());
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001785
1786 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1787 "Invocation must have exactly one source file!");
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001788 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001789 "FIXME: AST inputs not yet supported here!");
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001790 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001791 "IR inputs not supported here!");
1792
1793 // Configure the various subsystems.
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001794 AST->TheSema.reset();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001795 AST->Ctx = nullptr;
1796 AST->PP = nullptr;
1797 AST->Reader = nullptr;
1798
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001799 // Create a file manager object to provide access to and cache the filesystem.
1800 Clang->setFileManager(&AST->getFileManager());
1801
1802 // Create the source manager.
1803 Clang->setSourceManager(&AST->getSourceManager());
1804
1805 ASTFrontendAction *Act = Action;
1806
Stephen Hines651f13c2014-04-23 16:59:28 -07001807 std::unique_ptr<TopLevelDeclTrackerAction> TrackerAct;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001808 if (!Act) {
1809 TrackerAct.reset(new TopLevelDeclTrackerAction(*AST));
1810 Act = TrackerAct.get();
1811 }
1812
1813 // Recover resources if we crash before exiting this method.
1814 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1815 ActCleanup(TrackerAct.get());
1816
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001817 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
1818 AST->transferASTDataFromCompilerInstance(*Clang);
1819 if (OwnAST && ErrAST)
1820 ErrAST->swap(OwnAST);
1821
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001822 return nullptr;
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001823 }
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00001824
1825 if (Persistent && !TrackerAct) {
1826 Clang->getPreprocessor().addPPCallbacks(
Stephen Hines176edba2014-12-01 14:53:08 -08001827 llvm::make_unique<MacroDefinitionTrackerPPCallbacks>(
1828 AST->getCurrentTopLevelHashValue()));
1829 std::vector<std::unique_ptr<ASTConsumer>> Consumers;
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00001830 if (Clang->hasASTConsumer())
1831 Consumers.push_back(Clang->takeASTConsumer());
Stephen Hines176edba2014-12-01 14:53:08 -08001832 Consumers.push_back(llvm::make_unique<TopLevelDeclTrackerConsumer>(
1833 *AST, AST->getCurrentTopLevelHashValue()));
1834 Clang->setASTConsumer(
1835 llvm::make_unique<MultiplexConsumer>(std::move(Consumers)));
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00001836 }
Argyrios Kyrtzidis374a00b2012-06-08 05:48:06 +00001837 if (!Act->Execute()) {
1838 AST->transferASTDataFromCompilerInstance(*Clang);
1839 if (OwnAST && ErrAST)
1840 ErrAST->swap(OwnAST);
1841
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001842 return nullptr;
Argyrios Kyrtzidis374a00b2012-06-08 05:48:06 +00001843 }
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001844
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001845 // Steal the created target, context, and preprocessor.
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001846 AST->transferASTDataFromCompilerInstance(*Clang);
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001847
1848 Act->EndSourceFile();
1849
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001850 if (OwnAST)
Stephen Hines651f13c2014-04-23 16:59:28 -07001851 return OwnAST.release();
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001852 else
1853 return AST;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001854}
1855
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001856bool ASTUnit::LoadFromCompilerInvocation(bool PrecompilePreamble) {
1857 if (!Invocation)
1858 return true;
1859
1860 // We'll manage file buffers ourselves.
1861 Invocation->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1862 Invocation->getFrontendOpts().DisableFree = false;
Douglas Gregor0b53cf82011-01-19 01:02:47 +00001863 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001864
Stephen Hines176edba2014-12-01 14:53:08 -08001865 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
Douglas Gregor99ba2022010-10-27 17:24:53 +00001866 if (PrecompilePreamble) {
Douglas Gregor08bb4c62010-11-15 23:00:34 +00001867 PreambleRebuildCounter = 2;
Stephen Hines176edba2014-12-01 14:53:08 -08001868 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(*Invocation);
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001869 }
1870
Douglas Gregor213f18b2010-10-28 15:44:59 +00001871 SimpleTimer ParsingTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00001872 ParsingTimer.setOutput("Parsing " + getMainFileName());
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001873
Ted Kremenek25a11e12011-03-22 01:15:24 +00001874 // Recover resources if we crash before exiting this method.
1875 llvm::CrashRecoveryContextCleanupRegistrar<llvm::MemoryBuffer>
Stephen Hines176edba2014-12-01 14:53:08 -08001876 MemBufferCleanup(OverrideMainBuffer.get());
1877
1878 return Parse(std::move(OverrideMainBuffer));
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001879}
1880
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001881std::unique_ptr<ASTUnit> ASTUnit::LoadFromCompilerInvocation(
1882 CompilerInvocation *CI, IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
1883 bool OnlyLocalDecls, bool CaptureDiagnostics, bool PrecompilePreamble,
1884 TranslationUnitKind TUKind, bool CacheCodeCompletionResults,
1885 bool IncludeBriefCommentsInCodeCompletion, bool UserFilesAreVolatile) {
Douglas Gregorabc563f2010-07-19 21:46:24 +00001886 // Create the AST unit.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001887 std::unique_ptr<ASTUnit> AST(new ASTUnit(false));
Stephen Hines176edba2014-12-01 14:53:08 -08001888 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
Douglas Gregorabc563f2010-07-19 21:46:24 +00001889 AST->Diagnostics = Diags;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001890 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregore47be3e2010-11-11 00:39:14 +00001891 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor467dc882011-08-25 22:30:56 +00001892 AST->TUKind = TUKind;
Douglas Gregor87c08a52010-08-13 22:48:40 +00001893 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00001894 AST->IncludeBriefCommentsInCodeCompletion
1895 = IncludeBriefCommentsInCodeCompletion;
Ted Kremenek4f327862011-03-21 18:40:17 +00001896 AST->Invocation = CI;
Argyrios Kyrtzidiseb8fc582013-01-21 18:45:42 +00001897 AST->FileSystemOpts = CI->getFileSystemOpts();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001898 IntrusiveRefCntPtr<vfs::FileSystem> VFS =
1899 createVFSFromCompilerInvocation(*CI, *Diags);
1900 if (!VFS)
1901 return nullptr;
1902 AST->FileMgr = new FileManager(AST->FileSystemOpts, VFS);
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001903 AST->UserFilesAreVolatile = UserFilesAreVolatile;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001904
Ted Kremenekb547eeb2011-03-18 02:06:56 +00001905 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00001906 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1907 ASTUnitCleanup(AST.get());
David Blaikied6471f72011-09-25 23:23:43 +00001908 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1909 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001910 DiagCleanup(Diags.get());
Ted Kremenekb547eeb2011-03-18 02:06:56 +00001911
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001912 if (AST->LoadFromCompilerInvocation(PrecompilePreamble))
1913 return nullptr;
1914 return AST;
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001915}
Daniel Dunbar7b556682009-12-02 03:23:45 +00001916
Stephen Hines651f13c2014-04-23 16:59:28 -07001917ASTUnit *ASTUnit::LoadFromCommandLine(
1918 const char **ArgBegin, const char **ArgEnd,
1919 IntrusiveRefCntPtr<DiagnosticsEngine> Diags, StringRef ResourceFilesPath,
1920 bool OnlyLocalDecls, bool CaptureDiagnostics,
1921 ArrayRef<RemappedFile> RemappedFiles, bool RemappedFilesKeepOriginalName,
1922 bool PrecompilePreamble, TranslationUnitKind TUKind,
1923 bool CacheCodeCompletionResults, bool IncludeBriefCommentsInCodeCompletion,
1924 bool AllowPCHWithCompilerErrors, bool SkipFunctionBodies,
1925 bool UserFilesAreVolatile, bool ForSerialization,
1926 std::unique_ptr<ASTUnit> *ErrAST) {
Stephen Hines176edba2014-12-01 14:53:08 -08001927 assert(Diags.get() && "no DiagnosticsEngine was provided");
Daniel Dunbar7b556682009-12-02 03:23:45 +00001928
Chris Lattner5f9e2722011-07-23 10:55:15 +00001929 SmallVector<StoredDiagnostic, 4> StoredDiagnostics;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001930
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001931 IntrusiveRefCntPtr<CompilerInvocation> CI;
Douglas Gregore47be3e2010-11-11 00:39:14 +00001932
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001933 {
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001934
Douglas Gregore47be3e2010-11-11 00:39:14 +00001935 CaptureDroppedDiagnostics Capture(CaptureDiagnostics, *Diags,
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001936 StoredDiagnostics);
Daniel Dunbar3bd54cc2010-01-25 00:44:02 +00001937
Argyrios Kyrtzidis832316e2011-04-04 23:11:45 +00001938 CI = clang::createInvocationFromCommandLine(
Frits van Bommele9c02652011-07-18 12:00:32 +00001939 llvm::makeArrayRef(ArgBegin, ArgEnd),
1940 Diags);
Argyrios Kyrtzidis054e4f52011-04-04 21:38:51 +00001941 if (!CI)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001942 return nullptr;
Daniel Dunbar7b556682009-12-02 03:23:45 +00001943 }
Douglas Gregore47be3e2010-11-11 00:39:14 +00001944
Douglas Gregor4db64a42010-01-23 00:14:00 +00001945 // Override any files that need remapping
Stephen Hines651f13c2014-04-23 16:59:28 -07001946 for (unsigned I = 0, N = RemappedFiles.size(); I != N; ++I) {
1947 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
1948 RemappedFiles[I].second);
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001949 }
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +00001950 PreprocessorOptions &PPOpts = CI->getPreprocessorOpts();
1951 PPOpts.RemappedFilesKeepOriginalName = RemappedFilesKeepOriginalName;
1952 PPOpts.AllowPCHWithCompilerErrors = AllowPCHWithCompilerErrors;
Douglas Gregor4db64a42010-01-23 00:14:00 +00001953
Daniel Dunbar8b9adfe2009-12-15 00:06:45 +00001954 // Override the resources path.
Daniel Dunbar807b0612010-01-30 21:47:16 +00001955 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
Daniel Dunbar7b556682009-12-02 03:23:45 +00001956
Erik Verbruggen6a91d382012-04-12 10:11:59 +00001957 CI->getFrontendOpts().SkipFunctionBodies = SkipFunctionBodies;
1958
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001959 // Create the AST unit.
Stephen Hines651f13c2014-04-23 16:59:28 -07001960 std::unique_ptr<ASTUnit> AST;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001961 AST.reset(new ASTUnit(false));
Stephen Hines176edba2014-12-01 14:53:08 -08001962 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001963 AST->Diagnostics = Diags;
Anders Carlsson0d8d7e62011-03-18 18:22:40 +00001964 AST->FileSystemOpts = CI->getFileSystemOpts();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001965 IntrusiveRefCntPtr<vfs::FileSystem> VFS =
1966 createVFSFromCompilerInvocation(*CI, *Diags);
1967 if (!VFS)
1968 return nullptr;
1969 AST->FileMgr = new FileManager(AST->FileSystemOpts, VFS);
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001970 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregore47be3e2010-11-11 00:39:14 +00001971 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor467dc882011-08-25 22:30:56 +00001972 AST->TUKind = TUKind;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001973 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00001974 AST->IncludeBriefCommentsInCodeCompletion
1975 = IncludeBriefCommentsInCodeCompletion;
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001976 AST->UserFilesAreVolatile = UserFilesAreVolatile;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001977 AST->NumStoredDiagnosticsFromDriver = StoredDiagnostics.size();
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001978 AST->StoredDiagnostics.swap(StoredDiagnostics);
Ted Kremenek4f327862011-03-21 18:40:17 +00001979 AST->Invocation = CI;
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +00001980 if (ForSerialization)
1981 AST->WriterData.reset(new ASTWriterData());
Stephen Hines176edba2014-12-01 14:53:08 -08001982 // Zero out now to ease cleanup during crash recovery.
1983 CI = nullptr;
1984 Diags = nullptr;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001985
Ted Kremenekb547eeb2011-03-18 02:06:56 +00001986 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00001987 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1988 ASTUnitCleanup(AST.get());
Ted Kremenekb547eeb2011-03-18 02:06:56 +00001989
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001990 if (AST->LoadFromCompilerInvocation(PrecompilePreamble)) {
1991 // Some error occurred, if caller wants to examine diagnostics, pass it the
1992 // ASTUnit.
1993 if (ErrAST) {
1994 AST->StoredDiagnostics.swap(AST->FailedParseDiagnostics);
1995 ErrAST->swap(AST);
1996 }
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001997 return nullptr;
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001998 }
1999
Stephen Hines651f13c2014-04-23 16:59:28 -07002000 return AST.release();
Daniel Dunbar7b556682009-12-02 03:23:45 +00002001}
Douglas Gregorabc563f2010-07-19 21:46:24 +00002002
Stephen Hines651f13c2014-04-23 16:59:28 -07002003bool ASTUnit::Reparse(ArrayRef<RemappedFile> RemappedFiles) {
Ted Kremenek4f327862011-03-21 18:40:17 +00002004 if (!Invocation)
Douglas Gregorabc563f2010-07-19 21:46:24 +00002005 return true;
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +00002006
2007 clearFileLevelDecls();
Douglas Gregorabc563f2010-07-19 21:46:24 +00002008
Douglas Gregor213f18b2010-10-28 15:44:59 +00002009 SimpleTimer ParsingTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00002010 ParsingTimer.setOutput("Reparsing " + getMainFileName());
Douglas Gregor213f18b2010-10-28 15:44:59 +00002011
Douglas Gregorcc5888d2010-07-31 00:40:00 +00002012 // Remap files.
Douglas Gregorf128fed2010-08-20 00:02:33 +00002013 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002014 for (const auto &RB : PPOpts.RemappedFileBuffers)
2015 delete RB.second;
2016
Douglas Gregorcc5888d2010-07-31 00:40:00 +00002017 Invocation->getPreprocessorOpts().clearRemappedFiles();
Stephen Hines651f13c2014-04-23 16:59:28 -07002018 for (unsigned I = 0, N = RemappedFiles.size(); I != N; ++I) {
2019 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
2020 RemappedFiles[I].second);
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00002021 }
Stephen Hines651f13c2014-04-23 16:59:28 -07002022
Douglas Gregoreababfb2010-08-04 05:53:38 +00002023 // If we have a preamble file lying around, or if we might try to
2024 // build a precompiled preamble, do so now.
Stephen Hines176edba2014-12-01 14:53:08 -08002025 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
Ted Kremenek1872b312011-10-27 17:55:18 +00002026 if (!getPreambleFile(this).empty() || PreambleRebuildCounter > 0)
Douglas Gregor2283d792010-08-20 00:59:43 +00002027 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(*Invocation);
Douglas Gregor175c4a92010-07-23 23:58:40 +00002028
Douglas Gregorabc563f2010-07-19 21:46:24 +00002029 // Clear out the diagnostics state.
Argyrios Kyrtzidise6825d32011-11-03 20:28:19 +00002030 getDiagnostics().Reset();
2031 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Argyrios Kyrtzidis27368f92011-11-03 20:57:33 +00002032 if (OverrideMainBuffer)
2033 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
Argyrios Kyrtzidise6825d32011-11-03 20:28:19 +00002034
Douglas Gregor175c4a92010-07-23 23:58:40 +00002035 // Parse the sources
Stephen Hines176edba2014-12-01 14:53:08 -08002036 bool Result = Parse(std::move(OverrideMainBuffer));
2037
Argyrios Kyrtzidis2fe17fc2011-10-31 21:25:31 +00002038 // If we're caching global code-completion results, and the top-level
2039 // declarations have changed, clear out the code-completion cache.
2040 if (!Result && ShouldCacheCodeCompletionResults &&
2041 CurrentTopLevelHashValue != CompletionCacheTopLevelHashValue)
2042 CacheCodeCompletionResults();
Douglas Gregor9b7db622011-02-16 18:16:54 +00002043
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00002044 // We now need to clear out the completion info related to this translation
2045 // unit; it'll be recreated if necessary.
2046 CCTUInfo.reset();
Douglas Gregor8fa0a802011-08-04 20:04:59 +00002047
Douglas Gregor175c4a92010-07-23 23:58:40 +00002048 return Result;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002049}
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002050
Douglas Gregor87c08a52010-08-13 22:48:40 +00002051//----------------------------------------------------------------------------//
2052// Code completion
2053//----------------------------------------------------------------------------//
2054
2055namespace {
2056 /// \brief Code completion consumer that combines the cached code-completion
2057 /// results from an ASTUnit with the code-completion results provided to it,
2058 /// then passes the result on to
2059 class AugmentedCodeCompleteConsumer : public CodeCompleteConsumer {
Richard Smith026b3582012-08-14 03:13:00 +00002060 uint64_t NormalContexts;
Douglas Gregor87c08a52010-08-13 22:48:40 +00002061 ASTUnit &AST;
2062 CodeCompleteConsumer &Next;
2063
2064 public:
2065 AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002066 const CodeCompleteOptions &CodeCompleteOpts)
2067 : CodeCompleteConsumer(CodeCompleteOpts, Next.isOutputBinary()),
2068 AST(AST), Next(Next)
Douglas Gregor87c08a52010-08-13 22:48:40 +00002069 {
2070 // Compute the set of contexts in which we will look when we don't have
2071 // any information about the specific context.
2072 NormalContexts
Richard Smith026b3582012-08-14 03:13:00 +00002073 = (1LL << CodeCompletionContext::CCC_TopLevel)
2074 | (1LL << CodeCompletionContext::CCC_ObjCInterface)
2075 | (1LL << CodeCompletionContext::CCC_ObjCImplementation)
2076 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
2077 | (1LL << CodeCompletionContext::CCC_Statement)
2078 | (1LL << CodeCompletionContext::CCC_Expression)
2079 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
2080 | (1LL << CodeCompletionContext::CCC_DotMemberAccess)
2081 | (1LL << CodeCompletionContext::CCC_ArrowMemberAccess)
2082 | (1LL << CodeCompletionContext::CCC_ObjCPropertyAccess)
2083 | (1LL << CodeCompletionContext::CCC_ObjCProtocolName)
2084 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
2085 | (1LL << CodeCompletionContext::CCC_Recovery);
Douglas Gregor02688102010-09-14 23:59:36 +00002086
David Blaikie4e4d0842012-03-11 07:00:24 +00002087 if (AST.getASTContext().getLangOpts().CPlusPlus)
Richard Smith026b3582012-08-14 03:13:00 +00002088 NormalContexts |= (1LL << CodeCompletionContext::CCC_EnumTag)
2089 | (1LL << CodeCompletionContext::CCC_UnionTag)
2090 | (1LL << CodeCompletionContext::CCC_ClassOrStructTag);
Douglas Gregor87c08a52010-08-13 22:48:40 +00002091 }
Stephen Hines651f13c2014-04-23 16:59:28 -07002092
2093 void ProcessCodeCompleteResults(Sema &S, CodeCompletionContext Context,
2094 CodeCompletionResult *Results,
2095 unsigned NumResults) override;
2096
2097 void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
2098 OverloadCandidate *Candidates,
2099 unsigned NumCandidates) override {
Douglas Gregor87c08a52010-08-13 22:48:40 +00002100 Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates);
2101 }
Stephen Hines651f13c2014-04-23 16:59:28 -07002102
2103 CodeCompletionAllocator &getAllocator() override {
Douglas Gregor218937c2011-02-01 19:23:04 +00002104 return Next.getAllocator();
2105 }
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00002106
Stephen Hines651f13c2014-04-23 16:59:28 -07002107 CodeCompletionTUInfo &getCodeCompletionTUInfo() override {
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00002108 return Next.getCodeCompletionTUInfo();
2109 }
Douglas Gregor87c08a52010-08-13 22:48:40 +00002110 };
2111}
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002112
Douglas Gregor5f808c22010-08-16 21:18:39 +00002113/// \brief Helper function that computes which global names are hidden by the
2114/// local code-completion results.
Ted Kremenekc198f612010-11-07 06:11:36 +00002115static void CalculateHiddenNames(const CodeCompletionContext &Context,
2116 CodeCompletionResult *Results,
2117 unsigned NumResults,
2118 ASTContext &Ctx,
2119 llvm::StringSet<llvm::BumpPtrAllocator> &HiddenNames){
Douglas Gregor5f808c22010-08-16 21:18:39 +00002120 bool OnlyTagNames = false;
2121 switch (Context.getKind()) {
Douglas Gregor52779fb2010-09-23 23:01:17 +00002122 case CodeCompletionContext::CCC_Recovery:
Douglas Gregor5f808c22010-08-16 21:18:39 +00002123 case CodeCompletionContext::CCC_TopLevel:
2124 case CodeCompletionContext::CCC_ObjCInterface:
2125 case CodeCompletionContext::CCC_ObjCImplementation:
2126 case CodeCompletionContext::CCC_ObjCIvarList:
2127 case CodeCompletionContext::CCC_ClassStructUnion:
2128 case CodeCompletionContext::CCC_Statement:
2129 case CodeCompletionContext::CCC_Expression:
2130 case CodeCompletionContext::CCC_ObjCMessageReceiver:
Douglas Gregor3da626b2011-07-07 16:03:39 +00002131 case CodeCompletionContext::CCC_DotMemberAccess:
2132 case CodeCompletionContext::CCC_ArrowMemberAccess:
2133 case CodeCompletionContext::CCC_ObjCPropertyAccess:
Douglas Gregor5f808c22010-08-16 21:18:39 +00002134 case CodeCompletionContext::CCC_Namespace:
2135 case CodeCompletionContext::CCC_Type:
Douglas Gregor2ccccb32010-08-23 18:23:48 +00002136 case CodeCompletionContext::CCC_Name:
2137 case CodeCompletionContext::CCC_PotentiallyQualifiedName:
Douglas Gregor02688102010-09-14 23:59:36 +00002138 case CodeCompletionContext::CCC_ParenthesizedExpression:
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00002139 case CodeCompletionContext::CCC_ObjCInterfaceName:
Douglas Gregor5f808c22010-08-16 21:18:39 +00002140 break;
2141
2142 case CodeCompletionContext::CCC_EnumTag:
2143 case CodeCompletionContext::CCC_UnionTag:
2144 case CodeCompletionContext::CCC_ClassOrStructTag:
2145 OnlyTagNames = true;
2146 break;
2147
2148 case CodeCompletionContext::CCC_ObjCProtocolName:
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002149 case CodeCompletionContext::CCC_MacroName:
2150 case CodeCompletionContext::CCC_MacroNameUse:
Douglas Gregorf29c5232010-08-24 22:20:20 +00002151 case CodeCompletionContext::CCC_PreprocessorExpression:
Douglas Gregor721f3592010-08-25 18:41:16 +00002152 case CodeCompletionContext::CCC_PreprocessorDirective:
Douglas Gregor59a66942010-08-25 18:04:30 +00002153 case CodeCompletionContext::CCC_NaturalLanguage:
Douglas Gregor458433d2010-08-26 15:07:07 +00002154 case CodeCompletionContext::CCC_SelectorName:
Douglas Gregor1a480c42010-08-27 17:35:51 +00002155 case CodeCompletionContext::CCC_TypeQualifiers:
Douglas Gregor52779fb2010-09-23 23:01:17 +00002156 case CodeCompletionContext::CCC_Other:
Douglas Gregor5c722c702011-02-18 23:30:37 +00002157 case CodeCompletionContext::CCC_OtherWithMacros:
Douglas Gregor3da626b2011-07-07 16:03:39 +00002158 case CodeCompletionContext::CCC_ObjCInstanceMessage:
2159 case CodeCompletionContext::CCC_ObjCClassMessage:
2160 case CodeCompletionContext::CCC_ObjCCategoryName:
Douglas Gregor721f3592010-08-25 18:41:16 +00002161 // We're looking for nothing, or we're looking for names that cannot
2162 // be hidden.
Douglas Gregor5f808c22010-08-16 21:18:39 +00002163 return;
2164 }
2165
John McCall0a2c5e22010-08-25 06:19:51 +00002166 typedef CodeCompletionResult Result;
Douglas Gregor5f808c22010-08-16 21:18:39 +00002167 for (unsigned I = 0; I != NumResults; ++I) {
2168 if (Results[I].Kind != Result::RK_Declaration)
2169 continue;
2170
2171 unsigned IDNS
2172 = Results[I].Declaration->getUnderlyingDecl()->getIdentifierNamespace();
2173
2174 bool Hiding = false;
2175 if (OnlyTagNames)
2176 Hiding = (IDNS & Decl::IDNS_Tag);
2177 else {
2178 unsigned HiddenIDNS = (Decl::IDNS_Type | Decl::IDNS_Member |
Douglas Gregora5fb7c32010-08-16 23:05:20 +00002179 Decl::IDNS_Namespace | Decl::IDNS_Ordinary |
2180 Decl::IDNS_NonMemberOperator);
David Blaikie4e4d0842012-03-11 07:00:24 +00002181 if (Ctx.getLangOpts().CPlusPlus)
Douglas Gregor5f808c22010-08-16 21:18:39 +00002182 HiddenIDNS |= Decl::IDNS_Tag;
2183 Hiding = (IDNS & HiddenIDNS);
2184 }
2185
2186 if (!Hiding)
2187 continue;
2188
2189 DeclarationName Name = Results[I].Declaration->getDeclName();
2190 if (IdentifierInfo *Identifier = Name.getAsIdentifierInfo())
2191 HiddenNames.insert(Identifier->getName());
2192 else
2193 HiddenNames.insert(Name.getAsString());
2194 }
2195}
2196
2197
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002198void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &S,
2199 CodeCompletionContext Context,
John McCall0a2c5e22010-08-25 06:19:51 +00002200 CodeCompletionResult *Results,
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002201 unsigned NumResults) {
2202 // Merge the results we were given with the results we cached.
2203 bool AddedResult = false;
Richard Smith026b3582012-08-14 03:13:00 +00002204 uint64_t InContexts =
2205 Context.getKind() == CodeCompletionContext::CCC_Recovery
2206 ? NormalContexts : (1LL << Context.getKind());
Douglas Gregor5f808c22010-08-16 21:18:39 +00002207 // Contains the set of names that are hidden by "local" completion results.
Ted Kremenekc198f612010-11-07 06:11:36 +00002208 llvm::StringSet<llvm::BumpPtrAllocator> HiddenNames;
John McCall0a2c5e22010-08-25 06:19:51 +00002209 typedef CodeCompletionResult Result;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002210 SmallVector<Result, 8> AllResults;
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002211 for (ASTUnit::cached_completion_iterator
Douglas Gregor5535d572010-08-16 21:23:13 +00002212 C = AST.cached_completion_begin(),
2213 CEnd = AST.cached_completion_end();
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002214 C != CEnd; ++C) {
2215 // If the context we are in matches any of the contexts we are
2216 // interested in, we'll add this result.
2217 if ((C->ShowInContexts & InContexts) == 0)
2218 continue;
2219
2220 // If we haven't added any results previously, do so now.
2221 if (!AddedResult) {
Douglas Gregor5f808c22010-08-16 21:18:39 +00002222 CalculateHiddenNames(Context, Results, NumResults, S.Context,
2223 HiddenNames);
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002224 AllResults.insert(AllResults.end(), Results, Results + NumResults);
2225 AddedResult = true;
2226 }
2227
Douglas Gregor5f808c22010-08-16 21:18:39 +00002228 // Determine whether this global completion result is hidden by a local
2229 // completion result. If so, skip it.
2230 if (C->Kind != CXCursor_MacroDefinition &&
2231 HiddenNames.count(C->Completion->getTypedText()))
2232 continue;
2233
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002234 // Adjust priority based on similar type classes.
2235 unsigned Priority = C->Priority;
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002236 CodeCompletionString *Completion = C->Completion;
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002237 if (!Context.getPreferredType().isNull()) {
2238 if (C->Kind == CXCursor_MacroDefinition) {
2239 Priority = getMacroUsagePriority(C->Completion->getTypedText(),
David Blaikie4e4d0842012-03-11 07:00:24 +00002240 S.getLangOpts(),
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002241 Context.getPreferredType()->isAnyPointerType());
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002242 } else if (C->Type) {
2243 CanQualType Expected
Douglas Gregor5535d572010-08-16 21:23:13 +00002244 = S.Context.getCanonicalType(
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002245 Context.getPreferredType().getUnqualifiedType());
2246 SimplifiedTypeClass ExpectedSTC = getSimplifiedTypeClass(Expected);
2247 if (ExpectedSTC == C->TypeClass) {
2248 // We know this type is similar; check for an exact match.
2249 llvm::StringMap<unsigned> &CachedCompletionTypes
Douglas Gregor5535d572010-08-16 21:23:13 +00002250 = AST.getCachedCompletionTypes();
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002251 llvm::StringMap<unsigned>::iterator Pos
Douglas Gregor5535d572010-08-16 21:23:13 +00002252 = CachedCompletionTypes.find(QualType(Expected).getAsString());
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002253 if (Pos != CachedCompletionTypes.end() && Pos->second == C->Type)
2254 Priority /= CCF_ExactTypeMatch;
2255 else
2256 Priority /= CCF_SimilarTypeMatch;
2257 }
2258 }
2259 }
2260
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002261 // Adjust the completion string, if required.
2262 if (C->Kind == CXCursor_MacroDefinition &&
2263 Context.getKind() == CodeCompletionContext::CCC_MacroNameUse) {
2264 // Create a new code-completion string that just contains the
2265 // macro name, without its arguments.
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00002266 CodeCompletionBuilder Builder(getAllocator(), getCodeCompletionTUInfo(),
2267 CCP_CodePattern, C->Availability);
Douglas Gregor218937c2011-02-01 19:23:04 +00002268 Builder.AddTypedTextChunk(C->Completion->getTypedText());
Douglas Gregor4125c372010-08-25 18:03:13 +00002269 Priority = CCP_CodePattern;
Douglas Gregor218937c2011-02-01 19:23:04 +00002270 Completion = Builder.TakeString();
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002271 }
2272
Argyrios Kyrtzidisc04bb922012-09-27 00:24:09 +00002273 AllResults.push_back(Result(Completion, Priority, C->Kind,
Douglas Gregor58ddb602010-08-23 23:00:57 +00002274 C->Availability));
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002275 }
2276
2277 // If we did not add any cached completion results, just forward the
2278 // results we were given to the next consumer.
2279 if (!AddedResult) {
2280 Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
2281 return;
2282 }
Douglas Gregor1e5e6682010-08-26 13:48:20 +00002283
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002284 Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
2285 AllResults.size());
2286}
2287
2288
2289
Chris Lattner5f9e2722011-07-23 10:55:15 +00002290void ASTUnit::CodeComplete(StringRef File, unsigned Line, unsigned Column,
Stephen Hines651f13c2014-04-23 16:59:28 -07002291 ArrayRef<RemappedFile> RemappedFiles,
Douglas Gregorcee235c2010-08-05 09:09:23 +00002292 bool IncludeMacros,
2293 bool IncludeCodePatterns,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002294 bool IncludeBriefComments,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002295 CodeCompleteConsumer &Consumer,
David Blaikied6471f72011-09-25 23:23:43 +00002296 DiagnosticsEngine &Diag, LangOptions &LangOpts,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002297 SourceManager &SourceMgr, FileManager &FileMgr,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002298 SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
2299 SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers) {
Ted Kremenek4f327862011-03-21 18:40:17 +00002300 if (!Invocation)
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002301 return;
2302
Douglas Gregor213f18b2010-10-28 15:44:59 +00002303 SimpleTimer CompletionTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00002304 CompletionTimer.setOutput("Code completion @ " + File + ":" +
Chris Lattner5f9e2722011-07-23 10:55:15 +00002305 Twine(Line) + ":" + Twine(Column));
Douglas Gregordf95a132010-08-09 20:45:32 +00002306
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00002307 IntrusiveRefCntPtr<CompilerInvocation>
Ted Kremenek4f327862011-03-21 18:40:17 +00002308 CCInvocation(new CompilerInvocation(*Invocation));
2309
2310 FrontendOptions &FrontendOpts = CCInvocation->getFrontendOpts();
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002311 CodeCompleteOptions &CodeCompleteOpts = FrontendOpts.CodeCompleteOpts;
Ted Kremenek4f327862011-03-21 18:40:17 +00002312 PreprocessorOptions &PreprocessorOpts = CCInvocation->getPreprocessorOpts();
Douglas Gregorcee235c2010-08-05 09:09:23 +00002313
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002314 CodeCompleteOpts.IncludeMacros = IncludeMacros &&
2315 CachedCompletionResults.empty();
2316 CodeCompleteOpts.IncludeCodePatterns = IncludeCodePatterns;
2317 CodeCompleteOpts.IncludeGlobals = CachedCompletionResults.empty();
2318 CodeCompleteOpts.IncludeBriefComments = IncludeBriefComments;
2319
2320 assert(IncludeBriefComments == this->IncludeBriefCommentsInCodeCompletion);
2321
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002322 FrontendOpts.CodeCompletionAt.FileName = File;
2323 FrontendOpts.CodeCompletionAt.Line = Line;
2324 FrontendOpts.CodeCompletionAt.Column = Column;
2325
2326 // Set the language options appropriately.
Ted Kremenekd3b74d92011-11-17 23:01:24 +00002327 LangOpts = *CCInvocation->getLangOpts();
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002328
Stephen Hines176edba2014-12-01 14:53:08 -08002329 // Spell-checking and warnings are wasteful during code-completion.
2330 LangOpts.SpellChecking = false;
2331 CCInvocation->getDiagnosticOpts().IgnoreWarnings = true;
2332
Stephen Hines651f13c2014-04-23 16:59:28 -07002333 std::unique_ptr<CompilerInstance> Clang(new CompilerInstance());
Ted Kremenek03201fb2011-03-21 18:40:07 +00002334
2335 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00002336 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
2337 CICleanup(Clang.get());
Ted Kremenek03201fb2011-03-21 18:40:07 +00002338
Ted Kremenek4f327862011-03-21 18:40:17 +00002339 Clang->setInvocation(&*CCInvocation);
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00002340 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002341
2342 // Set up diagnostics, capturing any diagnostics produced.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002343 Clang->setDiagnostics(&Diag);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002344 CaptureDroppedDiagnostics Capture(true,
Ted Kremenek03201fb2011-03-21 18:40:07 +00002345 Clang->getDiagnostics(),
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002346 StoredDiagnostics);
Manuel Klimekf0c06a32013-07-18 14:23:12 +00002347 ProcessWarningOptions(Diag, CCInvocation->getDiagnosticOpts());
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002348
2349 // Create the target instance.
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002350 Clang->setTarget(TargetInfo::CreateTargetInfo(
2351 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
Ted Kremenek03201fb2011-03-21 18:40:07 +00002352 if (!Clang->hasTarget()) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002353 Clang->setInvocation(nullptr);
Douglas Gregorbdbb0042010-08-18 22:29:43 +00002354 return;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002355 }
2356
2357 // Inform the target of the language options.
2358 //
2359 // FIXME: We shouldn't need to do this, the target should be immutable once
2360 // created. This complexity should be lifted elsewhere.
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002361 Clang->getTarget().adjust(Clang->getLangOpts());
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002362
Ted Kremenek03201fb2011-03-21 18:40:07 +00002363 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002364 "Invocation must have exactly one source file!");
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00002365 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002366 "FIXME: AST inputs not yet supported here!");
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00002367 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002368 "IR inputs not support here!");
2369
2370
2371 // Use the source and file managers that we were given.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002372 Clang->setFileManager(&FileMgr);
2373 Clang->setSourceManager(&SourceMgr);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002374
2375 // Remap files.
2376 PreprocessorOpts.clearRemappedFiles();
Douglas Gregorb75d3df2010-08-04 17:07:00 +00002377 PreprocessorOpts.RetainRemappedFileBuffers = true;
Stephen Hines651f13c2014-04-23 16:59:28 -07002378 for (unsigned I = 0, N = RemappedFiles.size(); I != N; ++I) {
2379 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first,
2380 RemappedFiles[I].second);
2381 OwnedBuffers.push_back(RemappedFiles[I].second);
Douglas Gregor2283d792010-08-20 00:59:43 +00002382 }
Stephen Hines651f13c2014-04-23 16:59:28 -07002383
Douglas Gregor87c08a52010-08-13 22:48:40 +00002384 // Use the code completion consumer we were given, but adding any cached
2385 // code-completion results.
Douglas Gregor7f946ad2010-11-29 16:13:56 +00002386 AugmentedCodeCompleteConsumer *AugmentedConsumer
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002387 = new AugmentedCodeCompleteConsumer(*this, Consumer, CodeCompleteOpts);
Ted Kremenek03201fb2011-03-21 18:40:07 +00002388 Clang->setCodeCompletionConsumer(AugmentedConsumer);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002389
Douglas Gregordf95a132010-08-09 20:45:32 +00002390 // If we have a precompiled preamble, try to use it. We only allow
2391 // the use of the precompiled preamble if we're if the completion
2392 // point is within the main file, after the end of the precompiled
2393 // preamble.
Stephen Hines176edba2014-12-01 14:53:08 -08002394 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
Ted Kremenek1872b312011-10-27 17:55:18 +00002395 if (!getPreambleFile(this).empty()) {
Rafael Espindola105b2072013-06-18 19:40:07 +00002396 std::string CompleteFilePath(File);
Rafael Espindola44888352013-07-29 21:26:52 +00002397 llvm::sys::fs::UniqueID CompleteFileID;
Rafael Espindola105b2072013-06-18 19:40:07 +00002398
Rafael Espindolada4cb0c2013-06-20 15:12:38 +00002399 if (!llvm::sys::fs::getUniqueID(CompleteFilePath, CompleteFileID)) {
Rafael Espindola105b2072013-06-18 19:40:07 +00002400 std::string MainPath(OriginalSourceFile);
Rafael Espindola44888352013-07-29 21:26:52 +00002401 llvm::sys::fs::UniqueID MainID;
Rafael Espindolada4cb0c2013-06-20 15:12:38 +00002402 if (!llvm::sys::fs::getUniqueID(MainPath, MainID)) {
Rafael Espindola105b2072013-06-18 19:40:07 +00002403 if (CompleteFileID == MainID && Line > 1)
Stephen Hines176edba2014-12-01 14:53:08 -08002404 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(
2405 *CCInvocation, false, Line - 1);
Rafael Espindola105b2072013-06-18 19:40:07 +00002406 }
2407 }
Douglas Gregordf95a132010-08-09 20:45:32 +00002408 }
2409
2410 // If the main file has been overridden due to the use of a preamble,
2411 // make that override happen and introduce the preamble.
2412 if (OverrideMainBuffer) {
Stephen Hines176edba2014-12-01 14:53:08 -08002413 PreprocessorOpts.addRemappedFile(OriginalSourceFile,
2414 OverrideMainBuffer.get());
Douglas Gregordf95a132010-08-09 20:45:32 +00002415 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
2416 PreprocessorOpts.PrecompiledPreambleBytes.second
2417 = PreambleEndsAtStartOfLine;
Ted Kremenek1872b312011-10-27 17:55:18 +00002418 PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
Douglas Gregordf95a132010-08-09 20:45:32 +00002419 PreprocessorOpts.DisablePCHValidation = true;
Stephen Hines176edba2014-12-01 14:53:08 -08002420
2421 OwnedBuffers.push_back(OverrideMainBuffer.release());
Douglas Gregorf128fed2010-08-20 00:02:33 +00002422 } else {
2423 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
2424 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregordf95a132010-08-09 20:45:32 +00002425 }
2426
Argyrios Kyrtzidise50904f2012-11-02 22:18:44 +00002427 // Disable the preprocessing record if modules are not enabled.
2428 if (!Clang->getLangOpts().Modules)
2429 PreprocessorOpts.DetailedRecord = false;
Stephen Hines651f13c2014-04-23 16:59:28 -07002430
2431 std::unique_ptr<SyntaxOnlyAction> Act;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002432 Act.reset(new SyntaxOnlyAction);
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00002433 if (Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002434 Act->Execute();
2435 Act->EndSourceFile();
2436 }
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002437}
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002438
Argyrios Kyrtzidise6d22022012-09-26 16:39:46 +00002439bool ASTUnit::Save(StringRef File) {
Argyrios Kyrtzidis3b7deda2013-05-24 05:44:08 +00002440 if (HadModuleLoaderFatalFailure)
2441 return true;
2442
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002443 // Write to a temporary file and later rename it to the actual file, to avoid
2444 // possible race conditions.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002445 SmallString<128> TempPath;
Argyrios Kyrtzidis7e909852011-07-28 00:45:10 +00002446 TempPath = File;
2447 TempPath += "-%%%%%%%%";
2448 int fd;
Rafael Espindola70e7aec2013-07-05 21:13:58 +00002449 if (llvm::sys::fs::createUniqueFile(TempPath.str(), fd, TempPath))
Argyrios Kyrtzidise6d22022012-09-26 16:39:46 +00002450 return true;
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002451
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002452 // FIXME: Can we somehow regenerate the stat cache here, or do we need to
2453 // unconditionally create a stat cache when we parse the file?
Argyrios Kyrtzidis7e909852011-07-28 00:45:10 +00002454 llvm::raw_fd_ostream Out(fd, /*shouldClose=*/true);
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00002455
2456 serialize(Out);
2457 Out.close();
Argyrios Kyrtzidis4bd26542012-03-13 02:17:06 +00002458 if (Out.has_error()) {
2459 Out.clear_error();
Argyrios Kyrtzidise6d22022012-09-26 16:39:46 +00002460 return true;
Argyrios Kyrtzidis4bd26542012-03-13 02:17:06 +00002461 }
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002462
Rafael Espindola8d2a7012011-12-25 01:18:52 +00002463 if (llvm::sys::fs::rename(TempPath.str(), File)) {
Stephen Hines651f13c2014-04-23 16:59:28 -07002464 llvm::sys::fs::remove(TempPath.str());
Argyrios Kyrtzidise6d22022012-09-26 16:39:46 +00002465 return true;
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002466 }
2467
Argyrios Kyrtzidise6d22022012-09-26 16:39:46 +00002468 return false;
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00002469}
2470
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +00002471static bool serializeUnit(ASTWriter &Writer,
2472 SmallVectorImpl<char> &Buffer,
2473 Sema &S,
2474 bool hasErrors,
2475 raw_ostream &OS) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002476 Writer.WriteAST(S, std::string(), nullptr, "", hasErrors);
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +00002477
2478 // Write the generated bitstream to "Out".
2479 if (!Buffer.empty())
2480 OS.write(Buffer.data(), Buffer.size());
2481
2482 return false;
2483}
2484
Chris Lattner5f9e2722011-07-23 10:55:15 +00002485bool ASTUnit::serialize(raw_ostream &OS) {
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +00002486 bool hasErrors = getDiagnostics().hasErrorOccurred();
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00002487
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +00002488 if (WriterData)
2489 return serializeUnit(WriterData->Writer, WriterData->Buffer,
2490 getSema(), hasErrors, OS);
2491
Daniel Dunbar8d6ff022012-02-29 20:31:23 +00002492 SmallString<128> Buffer;
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002493 llvm::BitstreamWriter Stream(Buffer);
Sebastian Redla4232eb2010-08-18 23:56:21 +00002494 ASTWriter Writer(Stream);
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +00002495 return serializeUnit(Writer, Buffer, getSema(), hasErrors, OS);
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002496}
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002497
2498typedef ContinuousRangeMap<unsigned, int, 2> SLocRemap;
2499
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002500void ASTUnit::TranslateStoredDiagnostics(
Stephen Hines651f13c2014-04-23 16:59:28 -07002501 FileManager &FileMgr,
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002502 SourceManager &SrcMgr,
Stephen Hines651f13c2014-04-23 16:59:28 -07002503 const SmallVectorImpl<StandaloneDiagnostic> &Diags,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002504 SmallVectorImpl<StoredDiagnostic> &Out) {
Stephen Hines651f13c2014-04-23 16:59:28 -07002505 // Map the standalone diagnostic into the new source manager. We also need to
2506 // remap all the locations to the new view. This includes the diag location,
2507 // any associated source ranges, and the source ranges of associated fix-its.
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002508 // FIXME: There should be a cleaner way to do this.
2509
Chris Lattner5f9e2722011-07-23 10:55:15 +00002510 SmallVector<StoredDiagnostic, 4> Result;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002511 Result.reserve(Diags.size());
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002512 for (unsigned I = 0, N = Diags.size(); I != N; ++I) {
2513 // Rebuild the StoredDiagnostic.
Stephen Hines651f13c2014-04-23 16:59:28 -07002514 const StandaloneDiagnostic &SD = Diags[I];
2515 if (SD.Filename.empty())
2516 continue;
2517 const FileEntry *FE = FileMgr.getFile(SD.Filename);
2518 if (!FE)
2519 continue;
2520 FileID FID = SrcMgr.translateFile(FE);
2521 SourceLocation FileLoc = SrcMgr.getLocForStartOfFile(FID);
2522 if (FileLoc.isInvalid())
2523 continue;
2524 SourceLocation L = FileLoc.getLocWithOffset(SD.LocOffset);
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002525 FullSourceLoc Loc(L, SrcMgr);
2526
Chris Lattner5f9e2722011-07-23 10:55:15 +00002527 SmallVector<CharSourceRange, 4> Ranges;
Stephen Hines651f13c2014-04-23 16:59:28 -07002528 Ranges.reserve(SD.Ranges.size());
2529 for (std::vector<std::pair<unsigned, unsigned> >::const_iterator
2530 I = SD.Ranges.begin(), E = SD.Ranges.end(); I != E; ++I) {
2531 SourceLocation BL = FileLoc.getLocWithOffset((*I).first);
2532 SourceLocation EL = FileLoc.getLocWithOffset((*I).second);
2533 Ranges.push_back(CharSourceRange::getCharRange(BL, EL));
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002534 }
2535
Chris Lattner5f9e2722011-07-23 10:55:15 +00002536 SmallVector<FixItHint, 2> FixIts;
Stephen Hines651f13c2014-04-23 16:59:28 -07002537 FixIts.reserve(SD.FixIts.size());
2538 for (std::vector<StandaloneFixIt>::const_iterator
2539 I = SD.FixIts.begin(), E = SD.FixIts.end();
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002540 I != E; ++I) {
2541 FixIts.push_back(FixItHint());
2542 FixItHint &FH = FixIts.back();
2543 FH.CodeToInsert = I->CodeToInsert;
Stephen Hines651f13c2014-04-23 16:59:28 -07002544 SourceLocation BL = FileLoc.getLocWithOffset(I->RemoveRange.first);
2545 SourceLocation EL = FileLoc.getLocWithOffset(I->RemoveRange.second);
2546 FH.RemoveRange = CharSourceRange::getCharRange(BL, EL);
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002547 }
2548
Stephen Hines651f13c2014-04-23 16:59:28 -07002549 Result.push_back(StoredDiagnostic(SD.Level, SD.ID,
2550 SD.Message, Loc, Ranges, FixIts));
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002551 }
2552 Result.swap(Out);
2553}
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002554
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +00002555void ASTUnit::addFileLevelDecl(Decl *D) {
2556 assert(D);
Douglas Gregor66e87002011-11-07 18:53:57 +00002557
2558 // We only care about local declarations.
2559 if (D->isFromASTFile())
2560 return;
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +00002561
2562 SourceManager &SM = *SourceMgr;
2563 SourceLocation Loc = D->getLocation();
2564 if (Loc.isInvalid() || !SM.isLocalSourceLocation(Loc))
2565 return;
2566
2567 // We only keep track of the file-level declarations of each file.
2568 if (!D->getLexicalDeclContext()->isFileContext())
2569 return;
2570
2571 SourceLocation FileLoc = SM.getFileLoc(Loc);
2572 assert(SM.isLocalSourceLocation(FileLoc));
2573 FileID FID;
2574 unsigned Offset;
Stephen Hines651f13c2014-04-23 16:59:28 -07002575 std::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc);
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +00002576 if (FID.isInvalid())
2577 return;
2578
2579 LocDeclsTy *&Decls = FileDecls[FID];
2580 if (!Decls)
2581 Decls = new LocDeclsTy();
2582
2583 std::pair<unsigned, Decl *> LocDecl(Offset, D);
2584
2585 if (Decls->empty() || Decls->back().first <= Offset) {
2586 Decls->push_back(LocDecl);
2587 return;
2588 }
2589
Benjamin Kramer809d2542013-08-24 13:22:59 +00002590 LocDeclsTy::iterator I = std::upper_bound(Decls->begin(), Decls->end(),
2591 LocDecl, llvm::less_first());
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +00002592
2593 Decls->insert(I, LocDecl);
2594}
2595
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +00002596void ASTUnit::findFileRegionDecls(FileID File, unsigned Offset, unsigned Length,
2597 SmallVectorImpl<Decl *> &Decls) {
2598 if (File.isInvalid())
2599 return;
2600
2601 if (SourceMgr->isLoadedFileID(File)) {
2602 assert(Ctx->getExternalSource() && "No external source!");
2603 return Ctx->getExternalSource()->FindFileRegionDecls(File, Offset, Length,
2604 Decls);
2605 }
2606
2607 FileDeclsTy::iterator I = FileDecls.find(File);
2608 if (I == FileDecls.end())
2609 return;
2610
2611 LocDeclsTy &LocDecls = *I->second;
2612 if (LocDecls.empty())
2613 return;
2614
Benjamin Kramera9bdbce2013-08-24 13:12:34 +00002615 LocDeclsTy::iterator BeginIt =
2616 std::lower_bound(LocDecls.begin(), LocDecls.end(),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002617 std::make_pair(Offset, (Decl *)nullptr),
2618 llvm::less_first());
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +00002619 if (BeginIt != LocDecls.begin())
2620 --BeginIt;
2621
Argyrios Kyrtzidisc14a03d2011-11-23 20:27:36 +00002622 // If we are pointing at a top-level decl inside an objc container, we need
2623 // to backtrack until we find it otherwise we will fail to report that the
2624 // region overlaps with an objc container.
2625 while (BeginIt != LocDecls.begin() &&
2626 BeginIt->second->isTopLevelDeclInObjCContainer())
2627 --BeginIt;
2628
Benjamin Kramera9bdbce2013-08-24 13:12:34 +00002629 LocDeclsTy::iterator EndIt = std::upper_bound(
2630 LocDecls.begin(), LocDecls.end(),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002631 std::make_pair(Offset + Length, (Decl *)nullptr), llvm::less_first());
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +00002632 if (EndIt != LocDecls.end())
2633 ++EndIt;
2634
2635 for (LocDeclsTy::iterator DIt = BeginIt; DIt != EndIt; ++DIt)
2636 Decls.push_back(DIt->second);
2637}
2638
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002639SourceLocation ASTUnit::getLocation(const FileEntry *File,
2640 unsigned Line, unsigned Col) const {
2641 const SourceManager &SM = getSourceManager();
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00002642 SourceLocation Loc = SM.translateFileLineCol(File, Line, Col);
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002643 return SM.getMacroArgExpandedLocation(Loc);
2644}
2645
2646SourceLocation ASTUnit::getLocation(const FileEntry *File,
2647 unsigned Offset) const {
2648 const SourceManager &SM = getSourceManager();
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00002649 SourceLocation FileLoc = SM.translateFileLineCol(File, 1, 1);
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002650 return SM.getMacroArgExpandedLocation(FileLoc.getLocWithOffset(Offset));
2651}
2652
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00002653/// \brief If \arg Loc is a loaded location from the preamble, returns
2654/// the corresponding local location of the main file, otherwise it returns
2655/// \arg Loc.
2656SourceLocation ASTUnit::mapLocationFromPreamble(SourceLocation Loc) {
2657 FileID PreambleID;
2658 if (SourceMgr)
2659 PreambleID = SourceMgr->getPreambleFileID();
2660
2661 if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2662 return Loc;
2663
2664 unsigned Offs;
2665 if (SourceMgr->isInFileID(Loc, PreambleID, &Offs) && Offs < Preamble.size()) {
2666 SourceLocation FileLoc
2667 = SourceMgr->getLocForStartOfFile(SourceMgr->getMainFileID());
2668 return FileLoc.getLocWithOffset(Offs);
2669 }
2670
2671 return Loc;
2672}
2673
2674/// \brief If \arg Loc is a local location of the main file but inside the
2675/// preamble chunk, returns the corresponding loaded location from the
2676/// preamble, otherwise it returns \arg Loc.
2677SourceLocation ASTUnit::mapLocationToPreamble(SourceLocation Loc) {
2678 FileID PreambleID;
2679 if (SourceMgr)
2680 PreambleID = SourceMgr->getPreambleFileID();
2681
2682 if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2683 return Loc;
2684
2685 unsigned Offs;
2686 if (SourceMgr->isInFileID(Loc, SourceMgr->getMainFileID(), &Offs) &&
2687 Offs < Preamble.size()) {
2688 SourceLocation FileLoc = SourceMgr->getLocForStartOfFile(PreambleID);
2689 return FileLoc.getLocWithOffset(Offs);
2690 }
2691
2692 return Loc;
2693}
2694
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00002695bool ASTUnit::isInPreambleFileID(SourceLocation Loc) {
2696 FileID FID;
2697 if (SourceMgr)
2698 FID = SourceMgr->getPreambleFileID();
2699
2700 if (Loc.isInvalid() || FID.isInvalid())
2701 return false;
2702
2703 return SourceMgr->isInFileID(Loc, FID);
2704}
2705
2706bool ASTUnit::isInMainFileID(SourceLocation Loc) {
2707 FileID FID;
2708 if (SourceMgr)
2709 FID = SourceMgr->getMainFileID();
2710
2711 if (Loc.isInvalid() || FID.isInvalid())
2712 return false;
2713
2714 return SourceMgr->isInFileID(Loc, FID);
2715}
2716
2717SourceLocation ASTUnit::getEndOfPreambleFileID() {
2718 FileID FID;
2719 if (SourceMgr)
2720 FID = SourceMgr->getPreambleFileID();
2721
2722 if (FID.isInvalid())
2723 return SourceLocation();
2724
2725 return SourceMgr->getLocForEndOfFile(FID);
2726}
2727
2728SourceLocation ASTUnit::getStartOfMainFileID() {
2729 FileID FID;
2730 if (SourceMgr)
2731 FID = SourceMgr->getMainFileID();
2732
2733 if (FID.isInvalid())
2734 return SourceLocation();
2735
2736 return SourceMgr->getLocForStartOfFile(FID);
2737}
2738
Argyrios Kyrtzidis632dcc92012-10-02 16:10:51 +00002739std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
2740ASTUnit::getLocalPreprocessingEntities() const {
2741 if (isMainFileAST()) {
2742 serialization::ModuleFile &
2743 Mod = Reader->getModuleManager().getPrimaryModule();
2744 return Reader->getModulePreprocessedEntities(Mod);
2745 }
2746
2747 if (PreprocessingRecord *PPRec = PP->getPreprocessingRecord())
2748 return std::make_pair(PPRec->local_begin(), PPRec->local_end());
2749
2750 return std::make_pair(PreprocessingRecord::iterator(),
2751 PreprocessingRecord::iterator());
2752}
2753
Argyrios Kyrtzidis95c579c2012-10-03 01:58:28 +00002754bool ASTUnit::visitLocalTopLevelDecls(void *context, DeclVisitorFn Fn) {
Argyrios Kyrtzidis2093e0b2012-10-02 21:09:13 +00002755 if (isMainFileAST()) {
2756 serialization::ModuleFile &
2757 Mod = Reader->getModuleManager().getPrimaryModule();
2758 ASTReader::ModuleDeclIterator MDI, MDE;
Stephen Hines651f13c2014-04-23 16:59:28 -07002759 std::tie(MDI, MDE) = Reader->getModuleFileLevelDecls(Mod);
Argyrios Kyrtzidis2093e0b2012-10-02 21:09:13 +00002760 for (; MDI != MDE; ++MDI) {
2761 if (!Fn(context, *MDI))
2762 return false;
2763 }
2764
2765 return true;
2766 }
2767
2768 for (ASTUnit::top_level_iterator TL = top_level_begin(),
2769 TLEnd = top_level_end();
2770 TL != TLEnd; ++TL) {
2771 if (!Fn(context, *TL))
2772 return false;
2773 }
2774
2775 return true;
2776}
2777
Argyrios Kyrtzidis3da76bf2012-10-03 21:05:51 +00002778namespace {
2779struct PCHLocatorInfo {
2780 serialization::ModuleFile *Mod;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002781 PCHLocatorInfo() : Mod(nullptr) {}
Argyrios Kyrtzidis3da76bf2012-10-03 21:05:51 +00002782};
2783}
2784
2785static bool PCHLocator(serialization::ModuleFile &M, void *UserData) {
2786 PCHLocatorInfo &Info = *static_cast<PCHLocatorInfo*>(UserData);
2787 switch (M.Kind) {
Stephen Hines176edba2014-12-01 14:53:08 -08002788 case serialization::MK_ImplicitModule:
2789 case serialization::MK_ExplicitModule:
Argyrios Kyrtzidis3da76bf2012-10-03 21:05:51 +00002790 return true; // skip dependencies.
2791 case serialization::MK_PCH:
2792 Info.Mod = &M;
2793 return true; // found it.
2794 case serialization::MK_Preamble:
2795 return false; // look in dependencies.
2796 case serialization::MK_MainFile:
2797 return false; // look in dependencies.
2798 }
2799
2800 return true;
2801}
2802
2803const FileEntry *ASTUnit::getPCHFile() {
2804 if (!Reader)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002805 return nullptr;
Argyrios Kyrtzidis3da76bf2012-10-03 21:05:51 +00002806
2807 PCHLocatorInfo Info;
2808 Reader->getModuleManager().visit(PCHLocator, &Info);
2809 if (Info.Mod)
2810 return Info.Mod->File;
2811
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002812 return nullptr;
Argyrios Kyrtzidis3da76bf2012-10-03 21:05:51 +00002813}
2814
Argyrios Kyrtzidis62288ed2012-10-10 02:12:47 +00002815bool ASTUnit::isModuleFile() {
2816 return isMainFileAST() && !ASTFileLangOpts.CurrentModule.empty();
2817}
2818
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002819void ASTUnit::PreambleData::countLines() const {
2820 NumLines = 0;
2821 if (empty())
2822 return;
2823
2824 for (std::vector<char>::const_iterator
2825 I = Buffer.begin(), E = Buffer.end(); I != E; ++I) {
2826 if (*I == '\n')
2827 ++NumLines;
2828 }
2829 if (Buffer.back() != '\n')
2830 ++NumLines;
2831}
Argyrios Kyrtzidisa696ece2011-10-10 21:57:12 +00002832
2833#ifndef NDEBUG
2834ASTUnit::ConcurrencyState::ConcurrencyState() {
2835 Mutex = new llvm::sys::MutexImpl(/*recursive=*/true);
2836}
2837
2838ASTUnit::ConcurrencyState::~ConcurrencyState() {
2839 delete static_cast<llvm::sys::MutexImpl *>(Mutex);
2840}
2841
2842void ASTUnit::ConcurrencyState::start() {
2843 bool acquired = static_cast<llvm::sys::MutexImpl *>(Mutex)->tryacquire();
2844 assert(acquired && "Concurrent access to ASTUnit!");
2845}
2846
2847void ASTUnit::ConcurrencyState::finish() {
2848 static_cast<llvm::sys::MutexImpl *>(Mutex)->release();
2849}
2850
2851#else // NDEBUG
2852
Stephen Hines651f13c2014-04-23 16:59:28 -07002853ASTUnit::ConcurrencyState::ConcurrencyState() { Mutex = 0; }
Argyrios Kyrtzidisa696ece2011-10-10 21:57:12 +00002854ASTUnit::ConcurrencyState::~ConcurrencyState() {}
2855void ASTUnit::ConcurrencyState::start() {}
2856void ASTUnit::ConcurrencyState::finish() {}
2857
2858#endif