blob: fc44d9f1b4c08863ea2160b9c5fe960192ee7d3e [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
108typedef llvm::DenseMap<const ASTUnit *, OnDiskData *> OnDiskDataMap;
109static OnDiskDataMap &getOnDiskDataMap() {
110 static OnDiskDataMap M;
111 static bool hasRegisteredAtExit = false;
112 if (!hasRegisteredAtExit) {
113 hasRegisteredAtExit = true;
114 atexit(cleanupOnDiskMapAtExit);
115 }
116 return M;
117}
118
Dmitri Gribenkoc4a77902012-11-15 14:28:07 +0000119static void cleanupOnDiskMapAtExit() {
Argyrios Kyrtzidis81788132012-07-03 16:30:52 +0000120 // Use the mutex because there can be an alive thread destroying an ASTUnit.
121 llvm::MutexGuard Guard(getOnDiskMutex());
Ted Kremenek1872b312011-10-27 17:55:18 +0000122 OnDiskDataMap &M = getOnDiskDataMap();
123 for (OnDiskDataMap::iterator I = M.begin(), E = M.end(); I != E; ++I) {
124 // We don't worry about freeing the memory associated with OnDiskDataMap.
125 // All we care about is erasing stale files.
126 I->second->Cleanup();
127 }
128}
129
130static OnDiskData &getOnDiskData(const ASTUnit *AU) {
Ted Kremeneke055f8a2011-10-27 19:44:25 +0000131 // We require the mutex since we are modifying the structure of the
132 // DenseMap.
133 llvm::MutexGuard Guard(getOnDiskMutex());
Ted Kremenek1872b312011-10-27 17:55:18 +0000134 OnDiskDataMap &M = getOnDiskDataMap();
135 OnDiskData *&D = M[AU];
136 if (!D)
137 D = new OnDiskData();
138 return *D;
139}
140
141static void erasePreambleFile(const ASTUnit *AU) {
142 getOnDiskData(AU).CleanPreambleFile();
143}
144
145static void removeOnDiskEntry(const ASTUnit *AU) {
Ted Kremeneke055f8a2011-10-27 19:44:25 +0000146 // We require the mutex since we are modifying the structure of the
147 // DenseMap.
148 llvm::MutexGuard Guard(getOnDiskMutex());
Ted Kremenek1872b312011-10-27 17:55:18 +0000149 OnDiskDataMap &M = getOnDiskDataMap();
150 OnDiskDataMap::iterator I = M.find(AU);
151 if (I != M.end()) {
152 I->second->Cleanup();
153 delete I->second;
154 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 Hines6bcf27b2014-05-29 04:14:42 -0700222 PreambleRebuildCounter(0), SavedMainFileBuffer(nullptr),
223 PreambleBuffer(nullptr), 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 Gregor28233422010-07-27 14:52:07 +0000254
255 delete SavedMainFileBuffer;
Douglas Gregor671947b2010-08-19 01:33:06 +0000256 delete PreambleBuffer;
257
Douglas Gregor213f18b2010-10-28 15:44:59 +0000258 ClearCachedCompletionResults();
Douglas Gregore3c60a72010-11-17 00:13:31 +0000259
Stephen Hines651f13c2014-04-23 16:59:28 -0700260 if (getenv("LIBCLANG_OBJTRACKING"))
261 fprintf(stderr, "--- %u translation units\n", --ActiveASTUnitObjects);
Douglas Gregorabc563f2010-07-19 21:46:24 +0000262}
263
Argyrios Kyrtzidis7fe90f32012-01-17 18:48:07 +0000264void ASTUnit::setPreprocessor(Preprocessor *pp) { PP = pp; }
265
Douglas Gregor8071e422010-08-15 06:18:01 +0000266/// \brief Determine the set of code-completion contexts in which this
267/// declaration should be shown.
Dmitri Gribenko89cf4252013-01-23 17:21:11 +0000268static unsigned getDeclShowContexts(const NamedDecl *ND,
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000269 const LangOptions &LangOpts,
270 bool &IsNestedNameSpecifier) {
271 IsNestedNameSpecifier = false;
272
Douglas Gregor8071e422010-08-15 06:18:01 +0000273 if (isa<UsingShadowDecl>(ND))
274 ND = dyn_cast<NamedDecl>(ND->getUnderlyingDecl());
275 if (!ND)
276 return 0;
277
Richard Smith026b3582012-08-14 03:13:00 +0000278 uint64_t Contexts = 0;
Douglas Gregor8071e422010-08-15 06:18:01 +0000279 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND) ||
280 isa<ClassTemplateDecl>(ND) || isa<TemplateTemplateParmDecl>(ND)) {
281 // Types can appear in these contexts.
282 if (LangOpts.CPlusPlus || !isa<TagDecl>(ND))
Richard Smith026b3582012-08-14 03:13:00 +0000283 Contexts |= (1LL << CodeCompletionContext::CCC_TopLevel)
284 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
285 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
286 | (1LL << CodeCompletionContext::CCC_Statement)
287 | (1LL << CodeCompletionContext::CCC_Type)
288 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression);
Douglas Gregor8071e422010-08-15 06:18:01 +0000289
290 // In C++, types can appear in expressions contexts (for functional casts).
291 if (LangOpts.CPlusPlus)
Richard Smith026b3582012-08-14 03:13:00 +0000292 Contexts |= (1LL << CodeCompletionContext::CCC_Expression);
Douglas Gregor8071e422010-08-15 06:18:01 +0000293
294 // In Objective-C, message sends can send interfaces. In Objective-C++,
295 // all types are available due to functional casts.
296 if (LangOpts.CPlusPlus || isa<ObjCInterfaceDecl>(ND))
Richard Smith026b3582012-08-14 03:13:00 +0000297 Contexts |= (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver);
Douglas Gregor3da626b2011-07-07 16:03:39 +0000298
299 // In Objective-C, you can only be a subclass of another Objective-C class
300 if (isa<ObjCInterfaceDecl>(ND))
Richard Smith026b3582012-08-14 03:13:00 +0000301 Contexts |= (1LL << CodeCompletionContext::CCC_ObjCInterfaceName);
Douglas Gregor8071e422010-08-15 06:18:01 +0000302
303 // Deal with tag names.
304 if (isa<EnumDecl>(ND)) {
Richard Smith026b3582012-08-14 03:13:00 +0000305 Contexts |= (1LL << CodeCompletionContext::CCC_EnumTag);
Douglas Gregor8071e422010-08-15 06:18:01 +0000306
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000307 // Part of the nested-name-specifier in C++0x.
Richard Smith80ad52f2013-01-02 11:42:31 +0000308 if (LangOpts.CPlusPlus11)
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000309 IsNestedNameSpecifier = true;
Dmitri Gribenko89cf4252013-01-23 17:21:11 +0000310 } else if (const RecordDecl *Record = dyn_cast<RecordDecl>(ND)) {
Douglas Gregor8071e422010-08-15 06:18:01 +0000311 if (Record->isUnion())
Richard Smith026b3582012-08-14 03:13:00 +0000312 Contexts |= (1LL << CodeCompletionContext::CCC_UnionTag);
Douglas Gregor8071e422010-08-15 06:18:01 +0000313 else
Richard Smith026b3582012-08-14 03:13:00 +0000314 Contexts |= (1LL << CodeCompletionContext::CCC_ClassOrStructTag);
Douglas Gregor8071e422010-08-15 06:18:01 +0000315
Douglas Gregor8071e422010-08-15 06:18:01 +0000316 if (LangOpts.CPlusPlus)
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000317 IsNestedNameSpecifier = true;
Douglas Gregor52779fb2010-09-23 23:01:17 +0000318 } else if (isa<ClassTemplateDecl>(ND))
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000319 IsNestedNameSpecifier = true;
Douglas Gregor8071e422010-08-15 06:18:01 +0000320 } else if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
321 // Values can appear in these contexts.
Richard Smith026b3582012-08-14 03:13:00 +0000322 Contexts = (1LL << CodeCompletionContext::CCC_Statement)
323 | (1LL << CodeCompletionContext::CCC_Expression)
324 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
325 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver);
Douglas Gregor8071e422010-08-15 06:18:01 +0000326 } else if (isa<ObjCProtocolDecl>(ND)) {
Richard Smith026b3582012-08-14 03:13:00 +0000327 Contexts = (1LL << CodeCompletionContext::CCC_ObjCProtocolName);
Douglas Gregor3da626b2011-07-07 16:03:39 +0000328 } else if (isa<ObjCCategoryDecl>(ND)) {
Richard Smith026b3582012-08-14 03:13:00 +0000329 Contexts = (1LL << CodeCompletionContext::CCC_ObjCCategoryName);
Douglas Gregor8071e422010-08-15 06:18:01 +0000330 } else if (isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) {
Richard Smith026b3582012-08-14 03:13:00 +0000331 Contexts = (1LL << CodeCompletionContext::CCC_Namespace);
Douglas Gregor8071e422010-08-15 06:18:01 +0000332
333 // Part of the nested-name-specifier.
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000334 IsNestedNameSpecifier = true;
Douglas Gregor8071e422010-08-15 06:18:01 +0000335 }
336
337 return Contexts;
338}
339
Douglas Gregor87c08a52010-08-13 22:48:40 +0000340void ASTUnit::CacheCodeCompletionResults() {
341 if (!TheSema)
342 return;
343
Douglas Gregor213f18b2010-10-28 15:44:59 +0000344 SimpleTimer Timer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +0000345 Timer.setOutput("Cache global code completions for " + getMainFileName());
Douglas Gregor87c08a52010-08-13 22:48:40 +0000346
347 // Clear out the previous results.
348 ClearCachedCompletionResults();
349
350 // Gather the set of global code completions.
John McCall0a2c5e22010-08-25 06:19:51 +0000351 typedef CodeCompletionResult Result;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000352 SmallVector<Result, 8> Results;
Douglas Gregor48601b32011-02-16 19:08:06 +0000353 CachedCompletionAllocator = new GlobalCodeCompletionAllocator;
Argyrios Kyrtzidis7fdc8fd2012-11-16 03:34:57 +0000354 CodeCompletionTUInfo CCTUInfo(CachedCompletionAllocator);
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +0000355 TheSema->GatherGlobalCodeCompletions(*CachedCompletionAllocator,
Argyrios Kyrtzidis7fdc8fd2012-11-16 03:34:57 +0000356 CCTUInfo, Results);
Douglas Gregor87c08a52010-08-13 22:48:40 +0000357
358 // Translate global code completions into cached completions.
Douglas Gregorf5586f62010-08-16 18:08:11 +0000359 llvm::DenseMap<CanQualType, unsigned> CompletionTypes;
360
Douglas Gregor87c08a52010-08-13 22:48:40 +0000361 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
362 switch (Results[I].Kind) {
Douglas Gregor8071e422010-08-15 06:18:01 +0000363 case Result::RK_Declaration: {
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000364 bool IsNestedNameSpecifier = false;
Douglas Gregor8071e422010-08-15 06:18:01 +0000365 CachedCodeCompletionResult CachedResult;
Douglas Gregor218937c2011-02-01 19:23:04 +0000366 CachedResult.Completion = Results[I].CreateCodeCompletionString(*TheSema,
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +0000367 *CachedCompletionAllocator,
Argyrios Kyrtzidis7fdc8fd2012-11-16 03:34:57 +0000368 CCTUInfo,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +0000369 IncludeBriefCommentsInCodeCompletion);
Douglas Gregor8071e422010-08-15 06:18:01 +0000370 CachedResult.ShowInContexts = getDeclShowContexts(Results[I].Declaration,
David Blaikie4e4d0842012-03-11 07:00:24 +0000371 Ctx->getLangOpts(),
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000372 IsNestedNameSpecifier);
Douglas Gregor8071e422010-08-15 06:18:01 +0000373 CachedResult.Priority = Results[I].Priority;
374 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregor58ddb602010-08-23 23:00:57 +0000375 CachedResult.Availability = Results[I].Availability;
Douglas Gregorc4421e92010-08-16 16:46:30 +0000376
Douglas Gregorf5586f62010-08-16 18:08:11 +0000377 // Keep track of the type of this completion in an ASTContext-agnostic
378 // way.
Douglas Gregorc4421e92010-08-16 16:46:30 +0000379 QualType UsageType = getDeclUsageType(*Ctx, Results[I].Declaration);
Douglas Gregorf5586f62010-08-16 18:08:11 +0000380 if (UsageType.isNull()) {
Douglas Gregorc4421e92010-08-16 16:46:30 +0000381 CachedResult.TypeClass = STC_Void;
Douglas Gregorf5586f62010-08-16 18:08:11 +0000382 CachedResult.Type = 0;
383 } else {
384 CanQualType CanUsageType
385 = Ctx->getCanonicalType(UsageType.getUnqualifiedType());
386 CachedResult.TypeClass = getSimplifiedTypeClass(CanUsageType);
387
388 // Determine whether we have already seen this type. If so, we save
389 // ourselves the work of formatting the type string by using the
390 // temporary, CanQualType-based hash table to find the associated value.
391 unsigned &TypeValue = CompletionTypes[CanUsageType];
392 if (TypeValue == 0) {
393 TypeValue = CompletionTypes.size();
394 CachedCompletionTypes[QualType(CanUsageType).getAsString()]
395 = TypeValue;
396 }
397
398 CachedResult.Type = TypeValue;
Douglas Gregorc4421e92010-08-16 16:46:30 +0000399 }
Douglas Gregorf5586f62010-08-16 18:08:11 +0000400
Douglas Gregor8071e422010-08-15 06:18:01 +0000401 CachedCompletionResults.push_back(CachedResult);
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000402
403 /// Handle nested-name-specifiers in C++.
David Blaikie4e4d0842012-03-11 07:00:24 +0000404 if (TheSema->Context.getLangOpts().CPlusPlus &&
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000405 IsNestedNameSpecifier && !Results[I].StartsNestedNameSpecifier) {
406 // The contexts in which a nested-name-specifier can appear in C++.
Richard Smith026b3582012-08-14 03:13:00 +0000407 uint64_t NNSContexts
408 = (1LL << CodeCompletionContext::CCC_TopLevel)
409 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
410 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
411 | (1LL << CodeCompletionContext::CCC_Statement)
412 | (1LL << CodeCompletionContext::CCC_Expression)
413 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
414 | (1LL << CodeCompletionContext::CCC_EnumTag)
415 | (1LL << CodeCompletionContext::CCC_UnionTag)
416 | (1LL << CodeCompletionContext::CCC_ClassOrStructTag)
417 | (1LL << CodeCompletionContext::CCC_Type)
418 | (1LL << CodeCompletionContext::CCC_PotentiallyQualifiedName)
419 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression);
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000420
421 if (isa<NamespaceDecl>(Results[I].Declaration) ||
422 isa<NamespaceAliasDecl>(Results[I].Declaration))
Richard Smith026b3582012-08-14 03:13:00 +0000423 NNSContexts |= (1LL << CodeCompletionContext::CCC_Namespace);
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000424
425 if (unsigned RemainingContexts
426 = NNSContexts & ~CachedResult.ShowInContexts) {
427 // If there any contexts where this completion can be a
428 // nested-name-specifier but isn't already an option, create a
429 // nested-name-specifier completion.
430 Results[I].StartsNestedNameSpecifier = true;
Douglas Gregor218937c2011-02-01 19:23:04 +0000431 CachedResult.Completion
432 = Results[I].CreateCodeCompletionString(*TheSema,
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +0000433 *CachedCompletionAllocator,
Argyrios Kyrtzidis7fdc8fd2012-11-16 03:34:57 +0000434 CCTUInfo,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +0000435 IncludeBriefCommentsInCodeCompletion);
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000436 CachedResult.ShowInContexts = RemainingContexts;
437 CachedResult.Priority = CCP_NestedNameSpecifier;
438 CachedResult.TypeClass = STC_Void;
439 CachedResult.Type = 0;
440 CachedCompletionResults.push_back(CachedResult);
441 }
442 }
Douglas Gregor87c08a52010-08-13 22:48:40 +0000443 break;
Douglas Gregor8071e422010-08-15 06:18:01 +0000444 }
445
Douglas Gregor87c08a52010-08-13 22:48:40 +0000446 case Result::RK_Keyword:
447 case Result::RK_Pattern:
448 // Ignore keywords and patterns; we don't care, since they are so
449 // easily regenerated.
450 break;
451
452 case Result::RK_Macro: {
453 CachedCodeCompletionResult CachedResult;
Douglas Gregor218937c2011-02-01 19:23:04 +0000454 CachedResult.Completion
455 = Results[I].CreateCodeCompletionString(*TheSema,
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +0000456 *CachedCompletionAllocator,
Argyrios Kyrtzidis7fdc8fd2012-11-16 03:34:57 +0000457 CCTUInfo,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +0000458 IncludeBriefCommentsInCodeCompletion);
Douglas Gregor87c08a52010-08-13 22:48:40 +0000459 CachedResult.ShowInContexts
Richard Smith026b3582012-08-14 03:13:00 +0000460 = (1LL << CodeCompletionContext::CCC_TopLevel)
461 | (1LL << CodeCompletionContext::CCC_ObjCInterface)
462 | (1LL << CodeCompletionContext::CCC_ObjCImplementation)
463 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
464 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
465 | (1LL << CodeCompletionContext::CCC_Statement)
466 | (1LL << CodeCompletionContext::CCC_Expression)
467 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
468 | (1LL << CodeCompletionContext::CCC_MacroNameUse)
469 | (1LL << CodeCompletionContext::CCC_PreprocessorExpression)
470 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
471 | (1LL << CodeCompletionContext::CCC_OtherWithMacros);
Douglas Gregor2ccccb32010-08-23 18:23:48 +0000472
Douglas Gregor87c08a52010-08-13 22:48:40 +0000473 CachedResult.Priority = Results[I].Priority;
474 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregor58ddb602010-08-23 23:00:57 +0000475 CachedResult.Availability = Results[I].Availability;
Douglas Gregor1827e102010-08-16 16:18:59 +0000476 CachedResult.TypeClass = STC_Void;
Douglas Gregorf5586f62010-08-16 18:08:11 +0000477 CachedResult.Type = 0;
Douglas Gregor87c08a52010-08-13 22:48:40 +0000478 CachedCompletionResults.push_back(CachedResult);
479 break;
480 }
481 }
Douglas Gregor87c08a52010-08-13 22:48:40 +0000482 }
Douglas Gregor9b7db622011-02-16 18:16:54 +0000483
484 // Save the current top-level hash value.
485 CompletionCacheTopLevelHashValue = CurrentTopLevelHashValue;
Douglas Gregor87c08a52010-08-13 22:48:40 +0000486}
487
488void ASTUnit::ClearCachedCompletionResults() {
Douglas Gregor87c08a52010-08-13 22:48:40 +0000489 CachedCompletionResults.clear();
Douglas Gregorf5586f62010-08-16 18:08:11 +0000490 CachedCompletionTypes.clear();
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700491 CachedCompletionAllocator = nullptr;
Douglas Gregor87c08a52010-08-13 22:48:40 +0000492}
493
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000494namespace {
495
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000496/// \brief Gathers information from ASTReader that will be used to initialize
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000497/// a Preprocessor.
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000498class ASTInfoCollector : public ASTReaderListener {
Douglas Gregor998b3d32011-09-01 23:39:15 +0000499 Preprocessor &PP;
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000500 ASTContext &Context;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000501 LangOptions &LangOpt;
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700502 std::shared_ptr<TargetOptions> &TargetOpts;
Dylan Noblesmithc93dc782012-02-20 14:00:23 +0000503 IntrusiveRefCntPtr<TargetInfo> &Target;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000504 unsigned &Counter;
Mike Stump1eb44332009-09-09 15:08:12 +0000505
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000506 bool InitializedLanguage;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000507public:
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700508 ASTInfoCollector(Preprocessor &PP, ASTContext &Context, LangOptions &LangOpt,
509 std::shared_ptr<TargetOptions> &TargetOpts,
510 IntrusiveRefCntPtr<TargetInfo> &Target, unsigned &Counter)
511 : PP(PP), Context(Context), LangOpt(LangOpt), TargetOpts(TargetOpts),
512 Target(Target), Counter(Counter), InitializedLanguage(false) {}
Mike Stump1eb44332009-09-09 15:08:12 +0000513
Stephen Hines651f13c2014-04-23 16:59:28 -0700514 bool ReadLanguageOptions(const LangOptions &LangOpts,
515 bool Complain) override {
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000516 if (InitializedLanguage)
Douglas Gregor998b3d32011-09-01 23:39:15 +0000517 return false;
518
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000519 LangOpt = LangOpts;
520 InitializedLanguage = true;
521
522 updated();
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000523 return false;
524 }
Mike Stump1eb44332009-09-09 15:08:12 +0000525
Stephen Hines651f13c2014-04-23 16:59:28 -0700526 bool ReadTargetOptions(const TargetOptions &TargetOpts,
527 bool Complain) override {
Douglas Gregor998b3d32011-09-01 23:39:15 +0000528 // If we've already initialized the target, don't do it again.
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000529 if (Target)
Douglas Gregor998b3d32011-09-01 23:39:15 +0000530 return false;
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700531
532 this->TargetOpts = std::make_shared<TargetOptions>(TargetOpts);
533 Target =
534 TargetInfo::CreateTargetInfo(PP.getDiagnostics(), this->TargetOpts);
Argyrios Kyrtzidis7f186332012-09-14 20:24:53 +0000535
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000536 updated();
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000537 return false;
538 }
Mike Stump1eb44332009-09-09 15:08:12 +0000539
Stephen Hines651f13c2014-04-23 16:59:28 -0700540 void ReadCounter(const serialization::ModuleFile &M,
541 unsigned Value) override {
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000542 Counter = Value;
543 }
Argyrios Kyrtzidis7f186332012-09-14 20:24:53 +0000544
545private:
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000546 void updated() {
547 if (!Target || !InitializedLanguage)
548 return;
549
550 // Inform the target of the language options.
551 //
552 // FIXME: We shouldn't need to do this, the target should be immutable once
553 // created. This complexity should be lifted elsewhere.
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700554 Target->adjust(LangOpt);
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000555
556 // Initialize the preprocessor.
557 PP.Initialize(*Target);
558
559 // Initialize the ASTContext
560 Context.InitBuiltinTypes(*Target);
Dmitri Gribenko6ebf0912013-02-22 14:21:27 +0000561
562 // We didn't have access to the comment options when the ASTContext was
563 // constructed, so register them now.
564 Context.getCommentCommandTraits().registerCommentOptions(
565 LangOpt.CommentOpts);
Argyrios Kyrtzidis7f186332012-09-14 20:24:53 +0000566 }
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000567};
568
Douglas Gregora4a90ca2013-05-03 22:58:43 +0000569 /// \brief Diagnostic consumer that saves each diagnostic it is given.
David Blaikie26e7a902011-09-26 00:01:39 +0000570class StoredDiagnosticConsumer : public DiagnosticConsumer {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000571 SmallVectorImpl<StoredDiagnostic> &StoredDiags;
Douglas Gregora4a90ca2013-05-03 22:58:43 +0000572 SourceManager *SourceMgr;
573
Douglas Gregora88084b2010-02-18 18:08:43 +0000574public:
David Blaikie26e7a902011-09-26 00:01:39 +0000575 explicit StoredDiagnosticConsumer(
Chris Lattner5f9e2722011-07-23 10:55:15 +0000576 SmallVectorImpl<StoredDiagnostic> &StoredDiags)
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700577 : StoredDiags(StoredDiags), SourceMgr(nullptr) {}
Douglas Gregora4a90ca2013-05-03 22:58:43 +0000578
Stephen Hines651f13c2014-04-23 16:59:28 -0700579 void BeginSourceFile(const LangOptions &LangOpts,
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700580 const Preprocessor *PP = nullptr) override {
Douglas Gregora4a90ca2013-05-03 22:58:43 +0000581 if (PP)
582 SourceMgr = &PP->getSourceManager();
583 }
584
Stephen Hines651f13c2014-04-23 16:59:28 -0700585 void HandleDiagnostic(DiagnosticsEngine::Level Level,
586 const Diagnostic &Info) override;
Douglas Gregora88084b2010-02-18 18:08:43 +0000587};
588
589/// \brief RAII object that optionally captures diagnostics, if
590/// there is no diagnostic client to capture them already.
591class CaptureDroppedDiagnostics {
David Blaikied6471f72011-09-25 23:23:43 +0000592 DiagnosticsEngine &Diags;
David Blaikie26e7a902011-09-26 00:01:39 +0000593 StoredDiagnosticConsumer Client;
David Blaikie78ad0b92011-09-25 23:39:51 +0000594 DiagnosticConsumer *PreviousClient;
Douglas Gregora88084b2010-02-18 18:08:43 +0000595
596public:
David Blaikied6471f72011-09-25 23:23:43 +0000597 CaptureDroppedDiagnostics(bool RequestCapture, DiagnosticsEngine &Diags,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000598 SmallVectorImpl<StoredDiagnostic> &StoredDiags)
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700599 : Diags(Diags), Client(StoredDiags), PreviousClient(nullptr)
Douglas Gregora88084b2010-02-18 18:08:43 +0000600 {
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700601 if (RequestCapture || Diags.getClient() == nullptr) {
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000602 PreviousClient = Diags.takeClient();
Douglas Gregora88084b2010-02-18 18:08:43 +0000603 Diags.setClient(&Client);
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000604 }
Douglas Gregora88084b2010-02-18 18:08:43 +0000605 }
606
607 ~CaptureDroppedDiagnostics() {
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000608 if (Diags.getClient() == &Client) {
609 Diags.takeClient();
610 Diags.setClient(PreviousClient);
611 }
Douglas Gregora88084b2010-02-18 18:08:43 +0000612 }
613};
614
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000615} // anonymous namespace
616
David Blaikie26e7a902011-09-26 00:01:39 +0000617void StoredDiagnosticConsumer::HandleDiagnostic(DiagnosticsEngine::Level Level,
David Blaikie40847cf2011-09-26 01:18:08 +0000618 const Diagnostic &Info) {
Argyrios Kyrtzidisf2224d82010-11-18 20:06:46 +0000619 // Default implementation (Warnings/errors count).
David Blaikie78ad0b92011-09-25 23:39:51 +0000620 DiagnosticConsumer::HandleDiagnostic(Level, Info);
Argyrios Kyrtzidisf2224d82010-11-18 20:06:46 +0000621
Douglas Gregora4a90ca2013-05-03 22:58:43 +0000622 // Only record the diagnostic if it's part of the source manager we know
623 // about. This effectively drops diagnostics from modules we're building.
624 // FIXME: In the long run, ee don't want to drop source managers from modules.
625 if (!Info.hasSourceManager() || &Info.getSourceManager() == SourceMgr)
626 StoredDiags.push_back(StoredDiagnostic(Level, Info));
Douglas Gregora88084b2010-02-18 18:08:43 +0000627}
628
Argyrios Kyrtzidis7eca8d22013-05-10 01:28:51 +0000629ASTMutationListener *ASTUnit::getASTMutationListener() {
630 if (WriterData)
631 return &WriterData->Writer;
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700632 return nullptr;
Argyrios Kyrtzidis7eca8d22013-05-10 01:28:51 +0000633}
634
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000635ASTDeserializationListener *ASTUnit::getDeserializationListener() {
636 if (WriterData)
637 return &WriterData->Writer;
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700638 return nullptr;
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000639}
640
Chris Lattner5f9e2722011-07-23 10:55:15 +0000641llvm::MemoryBuffer *ASTUnit::getBufferForFile(StringRef Filename,
Chris Lattner75dfb652010-11-23 09:19:42 +0000642 std::string *ErrorStr) {
Chris Lattner39b49bc2010-11-23 08:35:12 +0000643 assert(FileMgr);
Chris Lattner75dfb652010-11-23 09:19:42 +0000644 return FileMgr->getBufferForFile(Filename, ErrorStr);
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +0000645}
646
Douglas Gregore47be3e2010-11-11 00:39:14 +0000647/// \brief Configure the diagnostics object for use with ASTUnit.
Dylan Noblesmithc93dc782012-02-20 14:00:23 +0000648void ASTUnit::ConfigureDiags(IntrusiveRefCntPtr<DiagnosticsEngine> &Diags,
Douglas Gregor0b53cf82011-01-19 01:02:47 +0000649 const char **ArgBegin, const char **ArgEnd,
Douglas Gregore47be3e2010-11-11 00:39:14 +0000650 ASTUnit &AST, bool CaptureDiagnostics) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700651 if (!Diags.get()) {
Douglas Gregore47be3e2010-11-11 00:39:14 +0000652 // No diagnostics engine was provided, so create our own diagnostics object
653 // with the default options.
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700654 DiagnosticConsumer *Client = nullptr;
Douglas Gregore47be3e2010-11-11 00:39:14 +0000655 if (CaptureDiagnostics)
David Blaikie26e7a902011-09-26 00:01:39 +0000656 Client = new StoredDiagnosticConsumer(AST.StoredDiagnostics);
Douglas Gregor02c23eb2012-10-23 22:26:28 +0000657 Diags = CompilerInstance::createDiagnostics(new DiagnosticOptions(),
Sean Silvad47afb92013-01-20 01:58:28 +0000658 Client,
Douglas Gregorcc2b6532013-05-03 23:07:45 +0000659 /*ShouldOwnClient=*/true);
Douglas Gregore47be3e2010-11-11 00:39:14 +0000660 } else if (CaptureDiagnostics) {
David Blaikie26e7a902011-09-26 00:01:39 +0000661 Diags->setClient(new StoredDiagnosticConsumer(AST.StoredDiagnostics));
Douglas Gregore47be3e2010-11-11 00:39:14 +0000662 }
663}
664
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000665ASTUnit *ASTUnit::LoadFromASTFile(const std::string &Filename,
Dylan Noblesmithc93dc782012-02-20 14:00:23 +0000666 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +0000667 const FileSystemOptions &FileSystemOpts,
Ted Kremenek5cf48762009-10-17 00:34:24 +0000668 bool OnlyLocalDecls,
Stephen Hines651f13c2014-04-23 16:59:28 -0700669 ArrayRef<RemappedFile> RemappedFiles,
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +0000670 bool CaptureDiagnostics,
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +0000671 bool AllowPCHWithCompilerErrors,
672 bool UserFilesAreVolatile) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700673 std::unique_ptr<ASTUnit> AST(new ASTUnit(true));
Ted Kremenekb547eeb2011-03-18 02:06:56 +0000674
675 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +0000676 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
677 ASTUnitCleanup(AST.get());
David Blaikied6471f72011-09-25 23:23:43 +0000678 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
679 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700680 DiagCleanup(Diags.get());
Ted Kremenekb547eeb2011-03-18 02:06:56 +0000681
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700682 ConfigureDiags(Diags, nullptr, nullptr, *AST, CaptureDiagnostics);
Douglas Gregorabc563f2010-07-19 21:46:24 +0000683
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000684 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregore47be3e2010-11-11 00:39:14 +0000685 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor28019772010-04-05 23:52:57 +0000686 AST->Diagnostics = Diags;
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700687 IntrusiveRefCntPtr<vfs::FileSystem> VFS = vfs::getRealFileSystem();
688 AST->FileMgr = new FileManager(FileSystemOpts, VFS);
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +0000689 AST->UserFilesAreVolatile = UserFilesAreVolatile;
Ted Kremenek4f327862011-03-21 18:40:17 +0000690 AST->SourceMgr = new SourceManager(AST->getDiagnostics(),
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +0000691 AST->getFileManager(),
692 UserFilesAreVolatile);
Douglas Gregorc042edd2012-10-24 16:19:39 +0000693 AST->HSOpts = new HeaderSearchOptions();
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700694
Douglas Gregorc042edd2012-10-24 16:19:39 +0000695 AST->HeaderInfo.reset(new HeaderSearch(AST->HSOpts,
Manuel Klimekee0cd372013-10-24 07:51:24 +0000696 AST->getSourceManager(),
Douglas Gregor51f564f2011-12-31 04:05:44 +0000697 AST->getDiagnostics(),
Douglas Gregordc58aa72012-01-30 06:01:29 +0000698 AST->ASTFileLangOpts,
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700699 /*Target=*/nullptr));
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000700
Stephen Hines651f13c2014-04-23 16:59:28 -0700701 PreprocessorOptions *PPOpts = new PreprocessorOptions();
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000702
Stephen Hines651f13c2014-04-23 16:59:28 -0700703 for (unsigned I = 0, N = RemappedFiles.size(); I != N; ++I)
704 PPOpts->addRemappedFile(RemappedFiles[I].first, RemappedFiles[I].second);
705
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000706 // Gather Info for preprocessor construction later on.
Mike Stump1eb44332009-09-09 15:08:12 +0000707
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000708 HeaderSearch &HeaderInfo = *AST->HeaderInfo.get();
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000709 unsigned Counter;
710
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700711 AST->PP =
712 new Preprocessor(PPOpts, AST->getDiagnostics(), AST->ASTFileLangOpts,
713 AST->getSourceManager(), HeaderInfo, *AST,
714 /*IILookup=*/nullptr,
715 /*OwnsHeaderSearch=*/false);
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000716 Preprocessor &PP = *AST->PP;
717
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700718 AST->Ctx = new ASTContext(AST->ASTFileLangOpts, AST->getSourceManager(),
719 PP.getIdentifierTable(), PP.getSelectorTable(),
720 PP.getBuiltinInfo());
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000721 ASTContext &Context = *AST->Ctx;
Douglas Gregor998b3d32011-09-01 23:39:15 +0000722
Argyrios Kyrtzidis98e95bf2012-09-15 01:10:20 +0000723 bool disableValid = false;
724 if (::getenv("LIBCLANG_DISABLE_PCH_VALIDATION"))
725 disableValid = true;
Stephen Hines651f13c2014-04-23 16:59:28 -0700726 AST->Reader = new ASTReader(PP, Context,
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +0000727 /*isysroot=*/"",
Argyrios Kyrtzidis98e95bf2012-09-15 01:10:20 +0000728 /*DisableValidation=*/disableValid,
Stephen Hines651f13c2014-04-23 16:59:28 -0700729 AllowPCHWithCompilerErrors);
Ted Kremenek8c647de2011-05-04 23:27:12 +0000730
Stephen Hines651f13c2014-04-23 16:59:28 -0700731 AST->Reader->setListener(new ASTInfoCollector(*AST->PP, Context,
Argyrios Kyrtzidisf9ba8512013-05-08 23:46:55 +0000732 AST->ASTFileLangOpts,
Douglas Gregor9a022bb2012-10-15 16:45:32 +0000733 AST->TargetOpts, AST->Target,
Douglas Gregor43998902012-10-25 00:09:28 +0000734 Counter));
Daniel Dunbarcc318932009-09-03 05:59:35 +0000735
Stephen Hines651f13c2014-04-23 16:59:28 -0700736 switch (AST->Reader->ReadAST(Filename, serialization::MK_MainFile,
Argyrios Kyrtzidis958bcaf2012-11-15 18:57:22 +0000737 SourceLocation(), ASTReader::ARR_None)) {
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000738 case ASTReader::Success:
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000739 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000740
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000741 case ASTReader::Failure:
Douglas Gregor677e15f2013-03-19 00:28:20 +0000742 case ASTReader::Missing:
Douglas Gregor4825fd72012-10-22 22:50:17 +0000743 case ASTReader::OutOfDate:
744 case ASTReader::VersionMismatch:
745 case ASTReader::ConfigurationMismatch:
746 case ASTReader::HadErrors:
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000747 AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700748 return nullptr;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000749 }
Mike Stump1eb44332009-09-09 15:08:12 +0000750
Stephen Hines651f13c2014-04-23 16:59:28 -0700751 AST->OriginalSourceFile = AST->Reader->getOriginalSourceFile();
Daniel Dunbar68d40e22009-12-02 08:44:16 +0000752
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000753 PP.setCounterValue(Counter);
Mike Stump1eb44332009-09-09 15:08:12 +0000754
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000755 // Attach the AST reader to the AST context as an external AST
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000756 // source, so that declarations will be deserialized from the
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000757 // AST file as needed.
Stephen Hines651f13c2014-04-23 16:59:28 -0700758 Context.setExternalSource(AST->Reader);
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000759
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000760 // Create an AST consumer, even though it isn't used.
761 AST->Consumer.reset(new ASTConsumer);
762
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000763 // Create a semantic analysis object and tell the AST reader about it.
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000764 AST->TheSema.reset(new Sema(PP, Context, *AST->Consumer));
765 AST->TheSema->Initialize();
Stephen Hines651f13c2014-04-23 16:59:28 -0700766 AST->Reader->InitializeSema(*AST->TheSema);
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000767
Douglas Gregora4a90ca2013-05-03 22:58:43 +0000768 // Tell the diagnostic client that we have started a source file.
769 AST->getDiagnostics().getClient()->BeginSourceFile(Context.getLangOpts(),&PP);
770
Stephen Hines651f13c2014-04-23 16:59:28 -0700771 return AST.release();
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000772}
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000773
774namespace {
775
Douglas Gregor9b7db622011-02-16 18:16:54 +0000776/// \brief Preprocessor callback class that updates a hash value with the names
777/// of all macros that have been defined by the translation unit.
778class MacroDefinitionTrackerPPCallbacks : public PPCallbacks {
779 unsigned &Hash;
780
781public:
782 explicit MacroDefinitionTrackerPPCallbacks(unsigned &Hash) : Hash(Hash) { }
Stephen Hines651f13c2014-04-23 16:59:28 -0700783
784 void MacroDefined(const Token &MacroNameTok,
785 const MacroDirective *MD) override {
Douglas Gregor9b7db622011-02-16 18:16:54 +0000786 Hash = llvm::HashString(MacroNameTok.getIdentifierInfo()->getName(), Hash);
787 }
788};
789
790/// \brief Add the given declaration to the hash of all top-level entities.
791void AddTopLevelDeclarationToHash(Decl *D, unsigned &Hash) {
792 if (!D)
793 return;
794
795 DeclContext *DC = D->getDeclContext();
796 if (!DC)
797 return;
798
799 if (!(DC->isTranslationUnit() || DC->getLookupParent()->isTranslationUnit()))
800 return;
801
802 if (NamedDecl *ND = dyn_cast<NamedDecl>(D)) {
Argyrios Kyrtzidise96a7b42013-10-15 17:37:55 +0000803 if (EnumDecl *EnumD = dyn_cast<EnumDecl>(D)) {
804 // For an unscoped enum include the enumerators in the hash since they
805 // enter the top-level namespace.
806 if (!EnumD->isScoped()) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700807 for (const auto *EI : EnumD->enumerators()) {
808 if (EI->getIdentifier())
809 Hash = llvm::HashString(EI->getIdentifier()->getName(), Hash);
Argyrios Kyrtzidise96a7b42013-10-15 17:37:55 +0000810 }
811 }
812 }
813
Douglas Gregor9b7db622011-02-16 18:16:54 +0000814 if (ND->getIdentifier())
815 Hash = llvm::HashString(ND->getIdentifier()->getName(), Hash);
816 else if (DeclarationName Name = ND->getDeclName()) {
817 std::string NameStr = Name.getAsString();
818 Hash = llvm::HashString(NameStr, Hash);
819 }
820 return;
Argyrios Kyrtzidis1f3ff6a2013-06-24 21:19:12 +0000821 }
822
823 if (ImportDecl *ImportD = dyn_cast<ImportDecl>(D)) {
824 if (Module *Mod = ImportD->getImportedModule()) {
825 std::string ModName = Mod->getFullModuleName();
826 Hash = llvm::HashString(ModName, Hash);
827 }
828 return;
829 }
Douglas Gregor9b7db622011-02-16 18:16:54 +0000830}
831
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000832class TopLevelDeclTrackerConsumer : public ASTConsumer {
833 ASTUnit &Unit;
Douglas Gregor9b7db622011-02-16 18:16:54 +0000834 unsigned &Hash;
835
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000836public:
Douglas Gregor9b7db622011-02-16 18:16:54 +0000837 TopLevelDeclTrackerConsumer(ASTUnit &_Unit, unsigned &Hash)
838 : Unit(_Unit), Hash(Hash) {
839 Hash = 0;
840 }
Douglas Gregor9b7db622011-02-16 18:16:54 +0000841
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000842 void handleTopLevelDecl(Decl *D) {
Argyrios Kyrtzidis35593a92011-11-16 02:35:10 +0000843 if (!D)
844 return;
845
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000846 // FIXME: Currently ObjC method declarations are incorrectly being
847 // reported as top-level declarations, even though their DeclContext
848 // is the containing ObjC @interface/@implementation. This is a
849 // fundamental problem in the parser right now.
850 if (isa<ObjCMethodDecl>(D))
851 return;
852
853 AddTopLevelDeclarationToHash(D, Hash);
854 Unit.addTopLevelDecl(D);
855
856 handleFileLevelDecl(D);
857 }
858
859 void handleFileLevelDecl(Decl *D) {
860 Unit.addFileLevelDecl(D);
861 if (NamespaceDecl *NSD = dyn_cast<NamespaceDecl>(D)) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700862 for (auto *I : NSD->decls())
863 handleFileLevelDecl(I);
Ted Kremenekda5a4282010-05-03 20:16:35 +0000864 }
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000865 }
Sebastian Redl27372b42010-08-11 18:52:41 +0000866
Stephen Hines651f13c2014-04-23 16:59:28 -0700867 bool HandleTopLevelDecl(DeclGroupRef D) override {
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000868 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it)
869 handleTopLevelDecl(*it);
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000870 return true;
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000871 }
872
Sebastian Redl27372b42010-08-11 18:52:41 +0000873 // We're not interested in "interesting" decls.
Stephen Hines651f13c2014-04-23 16:59:28 -0700874 void HandleInterestingDecl(DeclGroupRef) override {}
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000875
Stephen Hines651f13c2014-04-23 16:59:28 -0700876 void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) override {
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000877 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it)
878 handleTopLevelDecl(*it);
879 }
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000880
Stephen Hines651f13c2014-04-23 16:59:28 -0700881 ASTMutationListener *GetASTMutationListener() override {
Argyrios Kyrtzidis7eca8d22013-05-10 01:28:51 +0000882 return Unit.getASTMutationListener();
883 }
884
Stephen Hines651f13c2014-04-23 16:59:28 -0700885 ASTDeserializationListener *GetASTDeserializationListener() override {
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000886 return Unit.getDeserializationListener();
887 }
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000888};
889
890class TopLevelDeclTrackerAction : public ASTFrontendAction {
891public:
892 ASTUnit &Unit;
893
Stephen Hines651f13c2014-04-23 16:59:28 -0700894 ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
895 StringRef InFile) override {
Douglas Gregor9b7db622011-02-16 18:16:54 +0000896 CI.getPreprocessor().addPPCallbacks(
897 new MacroDefinitionTrackerPPCallbacks(Unit.getCurrentTopLevelHashValue()));
898 return new TopLevelDeclTrackerConsumer(Unit,
899 Unit.getCurrentTopLevelHashValue());
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000900 }
901
902public:
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000903 TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {}
904
Stephen Hines651f13c2014-04-23 16:59:28 -0700905 bool hasCodeCompletionSupport() const override { return false; }
906 TranslationUnitKind getTranslationUnitKind() override {
Douglas Gregor467dc882011-08-25 22:30:56 +0000907 return Unit.getTranslationUnitKind();
Douglas Gregordf95a132010-08-09 20:45:32 +0000908 }
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000909};
910
Benjamin Kramerb62b8b92013-06-11 13:07:19 +0000911class PrecompilePreambleAction : public ASTFrontendAction {
912 ASTUnit &Unit;
913 bool HasEmittedPreamblePCH;
914
915public:
916 explicit PrecompilePreambleAction(ASTUnit &Unit)
917 : Unit(Unit), HasEmittedPreamblePCH(false) {}
918
Stephen Hines651f13c2014-04-23 16:59:28 -0700919 ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
920 StringRef InFile) override;
Benjamin Kramerb62b8b92013-06-11 13:07:19 +0000921 bool hasEmittedPreamblePCH() const { return HasEmittedPreamblePCH; }
922 void setHasEmittedPreamblePCH() { HasEmittedPreamblePCH = true; }
Stephen Hines651f13c2014-04-23 16:59:28 -0700923 bool shouldEraseOutputFiles() override { return !hasEmittedPreamblePCH(); }
Benjamin Kramerb62b8b92013-06-11 13:07:19 +0000924
Stephen Hines651f13c2014-04-23 16:59:28 -0700925 bool hasCodeCompletionSupport() const override { return false; }
926 bool hasASTFileSupport() const override { return false; }
927 TranslationUnitKind getTranslationUnitKind() override { return TU_Prefix; }
Benjamin Kramerb62b8b92013-06-11 13:07:19 +0000928};
929
Argyrios Kyrtzidis92ddef12011-09-19 20:40:48 +0000930class PrecompilePreambleConsumer : public PCHGenerator {
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000931 ASTUnit &Unit;
Benjamin Kramerb62b8b92013-06-11 13:07:19 +0000932 unsigned &Hash;
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000933 std::vector<Decl *> TopLevelDecls;
Benjamin Kramerb62b8b92013-06-11 13:07:19 +0000934 PrecompilePreambleAction *Action;
935
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000936public:
Benjamin Kramerb62b8b92013-06-11 13:07:19 +0000937 PrecompilePreambleConsumer(ASTUnit &Unit, PrecompilePreambleAction *Action,
938 const Preprocessor &PP, StringRef isysroot,
939 raw_ostream *Out)
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700940 : PCHGenerator(PP, "", nullptr, isysroot, Out, /*AllowASTWithErrors=*/true),
Benjamin Kramerb62b8b92013-06-11 13:07:19 +0000941 Unit(Unit), Hash(Unit.getCurrentTopLevelHashValue()), Action(Action) {
Douglas Gregor9b7db622011-02-16 18:16:54 +0000942 Hash = 0;
943 }
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000944
Stephen Hines651f13c2014-04-23 16:59:28 -0700945 bool HandleTopLevelDecl(DeclGroupRef D) override {
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000946 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
947 Decl *D = *it;
948 // FIXME: Currently ObjC method declarations are incorrectly being
949 // reported as top-level declarations, even though their DeclContext
950 // is the containing ObjC @interface/@implementation. This is a
951 // fundamental problem in the parser right now.
952 if (isa<ObjCMethodDecl>(D))
953 continue;
Douglas Gregor9b7db622011-02-16 18:16:54 +0000954 AddTopLevelDeclarationToHash(D, Hash);
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000955 TopLevelDecls.push_back(D);
956 }
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000957 return true;
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000958 }
959
Stephen Hines651f13c2014-04-23 16:59:28 -0700960 void HandleTranslationUnit(ASTContext &Ctx) override {
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000961 PCHGenerator::HandleTranslationUnit(Ctx);
Argyrios Kyrtzidis1f01f7c2013-06-11 00:36:55 +0000962 if (hasEmittedPCH()) {
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000963 // Translate the top-level declarations we captured during
964 // parsing into declaration IDs in the precompiled
965 // preamble. This will allow us to deserialize those top-level
966 // declarations when requested.
Argyrios Kyrtzidis51e75ae2013-08-07 21:17:33 +0000967 for (unsigned I = 0, N = TopLevelDecls.size(); I != N; ++I) {
968 Decl *D = TopLevelDecls[I];
969 // Invalid top-level decls may not have been serialized.
970 if (D->isInvalidDecl())
971 continue;
972 Unit.addTopLevelDeclFromPreamble(getWriter().getDeclID(D));
973 }
Benjamin Kramerb62b8b92013-06-11 13:07:19 +0000974
975 Action->setHasEmittedPreamblePCH();
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000976 }
977 }
978};
979
Benjamin Kramerb62b8b92013-06-11 13:07:19 +0000980}
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000981
Benjamin Kramerb62b8b92013-06-11 13:07:19 +0000982ASTConsumer *PrecompilePreambleAction::CreateASTConsumer(CompilerInstance &CI,
983 StringRef InFile) {
984 std::string Sysroot;
985 std::string OutputFile;
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700986 raw_ostream *OS = nullptr;
Benjamin Kramerb62b8b92013-06-11 13:07:19 +0000987 if (GeneratePCHAction::ComputeASTConsumerArguments(CI, InFile, Sysroot,
988 OutputFile, OS))
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700989 return nullptr;
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000990
Benjamin Kramerb62b8b92013-06-11 13:07:19 +0000991 if (!CI.getFrontendOpts().RelocatablePCH)
992 Sysroot.clear();
Douglas Gregor832d6202011-07-22 16:35:34 +0000993
Benjamin Kramerb62b8b92013-06-11 13:07:19 +0000994 CI.getPreprocessor().addPPCallbacks(new MacroDefinitionTrackerPPCallbacks(
995 Unit.getCurrentTopLevelHashValue()));
996 return new PrecompilePreambleConsumer(Unit, this, CI.getPreprocessor(),
997 Sysroot, OS);
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000998}
999
Benjamin Kramerfe57db22013-05-05 12:39:28 +00001000static bool isNonDriverDiag(const StoredDiagnostic &StoredDiag) {
1001 return StoredDiag.getLocation().isValid();
1002}
1003
1004static void
1005checkAndRemoveNonDriverDiags(SmallVectorImpl<StoredDiagnostic> &StoredDiags) {
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00001006 // Get rid of stored diagnostics except the ones from the driver which do not
1007 // have a source location.
Benjamin Kramerfe57db22013-05-05 12:39:28 +00001008 StoredDiags.erase(
1009 std::remove_if(StoredDiags.begin(), StoredDiags.end(), isNonDriverDiag),
1010 StoredDiags.end());
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00001011}
1012
1013static void checkAndSanitizeDiags(SmallVectorImpl<StoredDiagnostic> &
1014 StoredDiagnostics,
1015 SourceManager &SM) {
1016 // The stored diagnostic has the old source manager in it; update
1017 // the locations to refer into the new source manager. Since we've
1018 // been careful to make sure that the source manager's state
1019 // before and after are identical, so that we can reuse the source
1020 // location itself.
1021 for (unsigned I = 0, N = StoredDiagnostics.size(); I < N; ++I) {
1022 if (StoredDiagnostics[I].getLocation().isValid()) {
1023 FullSourceLoc Loc(StoredDiagnostics[I].getLocation(), SM);
1024 StoredDiagnostics[I].setLocation(Loc);
1025 }
1026 }
1027}
1028
Douglas Gregorabc563f2010-07-19 21:46:24 +00001029/// Parse the source file into a translation unit using the given compiler
1030/// invocation, replacing the current translation unit.
1031///
1032/// \returns True if a failure occurred that causes the ASTUnit not to
1033/// contain any translation-unit information, false otherwise.
Douglas Gregor754f3492010-07-24 00:38:13 +00001034bool ASTUnit::Parse(llvm::MemoryBuffer *OverrideMainBuffer) {
Douglas Gregor28233422010-07-27 14:52:07 +00001035 delete SavedMainFileBuffer;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001036 SavedMainFileBuffer = nullptr;
1037
Ted Kremenek4f327862011-03-21 18:40:17 +00001038 if (!Invocation) {
Douglas Gregor671947b2010-08-19 01:33:06 +00001039 delete OverrideMainBuffer;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001040 return true;
Douglas Gregor671947b2010-08-19 01:33:06 +00001041 }
Douglas Gregorabc563f2010-07-19 21:46:24 +00001042
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001043 // Create the compiler instance to use for building the AST.
Stephen Hines651f13c2014-04-23 16:59:28 -07001044 std::unique_ptr<CompilerInstance> Clang(new CompilerInstance());
Ted Kremenek03201fb2011-03-21 18:40:07 +00001045
1046 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00001047 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1048 CICleanup(Clang.get());
Ted Kremenek03201fb2011-03-21 18:40:07 +00001049
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001050 IntrusiveRefCntPtr<CompilerInvocation>
Argyrios Kyrtzidis26d43cd2011-09-12 18:09:38 +00001051 CCInvocation(new CompilerInvocation(*Invocation));
1052
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001053 Clang->setInvocation(CCInvocation.get());
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001054 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
Douglas Gregorabc563f2010-07-19 21:46:24 +00001055
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001056 // Set up diagnostics, capturing any diagnostics that would
1057 // otherwise be dropped.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001058 Clang->setDiagnostics(&getDiagnostics());
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001059
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001060 // Create the target instance.
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001061 Clang->setTarget(TargetInfo::CreateTargetInfo(
1062 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
Ted Kremenek03201fb2011-03-21 18:40:07 +00001063 if (!Clang->hasTarget()) {
Douglas Gregor671947b2010-08-19 01:33:06 +00001064 delete OverrideMainBuffer;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001065 return true;
Douglas Gregor671947b2010-08-19 01:33:06 +00001066 }
1067
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001068 // Inform the target of the language options.
1069 //
1070 // FIXME: We shouldn't need to do this, the target should be immutable once
1071 // created. This complexity should be lifted elsewhere.
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001072 Clang->getTarget().adjust(Clang->getLangOpts());
Douglas Gregorabc563f2010-07-19 21:46:24 +00001073
Ted Kremenek03201fb2011-03-21 18:40:07 +00001074 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001075 "Invocation must have exactly one source file!");
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001076 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001077 "FIXME: AST inputs not yet supported here!");
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001078 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
Daniel Dunbarfaddc3e2010-06-07 23:26:47 +00001079 "IR inputs not support here!");
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001080
Douglas Gregorabc563f2010-07-19 21:46:24 +00001081 // Configure the various subsystems.
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001082 LangOpts = Clang->getInvocation().LangOpts;
Ted Kremenek03201fb2011-03-21 18:40:07 +00001083 FileSystemOpts = Clang->getFileSystemOpts();
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001084 IntrusiveRefCntPtr<vfs::FileSystem> VFS =
1085 createVFSFromCompilerInvocation(Clang->getInvocation(), getDiagnostics());
1086 if (!VFS) {
1087 delete OverrideMainBuffer;
1088 return true;
1089 }
1090 FileMgr = new FileManager(FileSystemOpts, VFS);
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001091 SourceMgr = new SourceManager(getDiagnostics(), *FileMgr,
1092 UserFilesAreVolatile);
Douglas Gregor914ed9d2010-08-13 03:15:25 +00001093 TheSema.reset();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001094 Ctx = nullptr;
1095 PP = nullptr;
1096 Reader = nullptr;
1097
Douglas Gregorabc563f2010-07-19 21:46:24 +00001098 // Clear out old caches and data.
1099 TopLevelDecls.clear();
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +00001100 clearFileLevelDecls();
Douglas Gregorabc563f2010-07-19 21:46:24 +00001101 CleanTemporaryFiles();
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001102
Douglas Gregorf128fed2010-08-20 00:02:33 +00001103 if (!OverrideMainBuffer) {
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00001104 checkAndRemoveNonDriverDiags(StoredDiagnostics);
Douglas Gregorf128fed2010-08-20 00:02:33 +00001105 TopLevelDeclsInPreamble.clear();
1106 }
1107
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001108 // Create a file manager object to provide access to and cache the filesystem.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001109 Clang->setFileManager(&getFileManager());
Douglas Gregorabc563f2010-07-19 21:46:24 +00001110
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001111 // Create the source manager.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001112 Clang->setSourceManager(&getSourceManager());
Douglas Gregorabc563f2010-07-19 21:46:24 +00001113
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001114 // If the main file has been overridden due to the use of a preamble,
1115 // make that override happen and introduce the preamble.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001116 PreprocessorOptions &PreprocessorOpts = Clang->getPreprocessorOpts();
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001117 if (OverrideMainBuffer) {
1118 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
1119 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
1120 PreprocessorOpts.PrecompiledPreambleBytes.second
1121 = PreambleEndsAtStartOfLine;
Ted Kremenek1872b312011-10-27 17:55:18 +00001122 PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001123 PreprocessorOpts.DisablePCHValidation = true;
Douglas Gregor28233422010-07-27 14:52:07 +00001124
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001125 // The stored diagnostic has the old source manager in it; update
1126 // the locations to refer into the new source manager. Since we've
1127 // been careful to make sure that the source manager's state
1128 // before and after are identical, so that we can reuse the source
1129 // location itself.
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00001130 checkAndSanitizeDiags(StoredDiagnostics, getSourceManager());
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001131
1132 // Keep track of the override buffer;
1133 SavedMainFileBuffer = OverrideMainBuffer;
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001134 }
Stephen Hines651f13c2014-04-23 16:59:28 -07001135
1136 std::unique_ptr<TopLevelDeclTrackerAction> Act(
1137 new TopLevelDeclTrackerAction(*this));
1138
Ted Kremenek25a11e12011-03-22 01:15:24 +00001139 // Recover resources if we crash before exiting this method.
1140 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1141 ActCleanup(Act.get());
1142
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001143 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0]))
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001144 goto error;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001145
1146 if (OverrideMainBuffer) {
Ted Kremenek1872b312011-10-27 17:55:18 +00001147 std::string ModName = getPreambleFile(this);
Stephen Hines651f13c2014-04-23 16:59:28 -07001148 TranslateStoredDiagnostics(getFileManager(), getSourceManager(),
1149 PreambleDiagnostics, StoredDiagnostics);
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001150 }
1151
Argyrios Kyrtzidis374a00b2012-06-08 05:48:06 +00001152 if (!Act->Execute())
1153 goto error;
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001154
1155 transferASTDataFromCompilerInstance(*Clang);
Douglas Gregorabc563f2010-07-19 21:46:24 +00001156
Daniel Dunbarf772d1e2009-12-04 08:17:33 +00001157 Act->EndSourceFile();
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001158
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001159 FailedParseDiagnostics.clear();
1160
Douglas Gregorabc563f2010-07-19 21:46:24 +00001161 return false;
Ted Kremenek4f327862011-03-21 18:40:17 +00001162
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001163error:
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001164 // Remove the overridden buffer we used for the preamble.
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001165 if (OverrideMainBuffer) {
Douglas Gregor671947b2010-08-19 01:33:06 +00001166 delete OverrideMainBuffer;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001167 SavedMainFileBuffer = nullptr;
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001168 }
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001169
1170 // Keep the ownership of the data in the ASTUnit because the client may
1171 // want to see the diagnostics.
1172 transferASTDataFromCompilerInstance(*Clang);
1173 FailedParseDiagnostics.swap(StoredDiagnostics);
Douglas Gregord54eb442010-10-12 16:25:54 +00001174 StoredDiagnostics.clear();
Argyrios Kyrtzidis3e9d3262011-10-24 17:25:20 +00001175 NumStoredDiagnosticsFromDriver = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001176 return true;
1177}
1178
Douglas Gregor44c181a2010-07-23 00:33:23 +00001179/// \brief Simple function to retrieve a path for a preamble precompiled header.
1180static std::string GetPreamblePCHPath() {
Douglas Gregor424668c2010-09-11 18:05:19 +00001181 // FIXME: This is a hack so that we can override the preamble file during
1182 // crash-recovery testing, which is the only case where the preamble files
Rafael Espindola85d28482013-06-26 04:02:37 +00001183 // are not necessarily cleaned up.
Douglas Gregor424668c2010-09-11 18:05:19 +00001184 const char *TmpFile = ::getenv("CINDEXTEST_PREAMBLE_FILE");
1185 if (TmpFile)
1186 return TmpFile;
Rafael Espindola85d28482013-06-26 04:02:37 +00001187
1188 SmallString<128> Path;
Rafael Espindola1ec4a862013-07-05 20:00:06 +00001189 llvm::sys::fs::createTemporaryFile("preamble", "pch", Path);
Rafael Espindola85d28482013-06-26 04:02:37 +00001190
1191 return Path.str();
Douglas Gregor44c181a2010-07-23 00:33:23 +00001192}
1193
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001194/// \brief Compute the preamble for the main file, providing the source buffer
1195/// that corresponds to the main file along with a pair (bytes, start-of-line)
1196/// that describes the preamble.
1197std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> >
Douglas Gregordf95a132010-08-09 20:45:32 +00001198ASTUnit::ComputePreamble(CompilerInvocation &Invocation,
1199 unsigned MaxLines, bool &CreatedBuffer) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001200 FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
Chris Lattner39b49bc2010-11-23 08:35:12 +00001201 PreprocessorOptions &PreprocessorOpts = Invocation.getPreprocessorOpts();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001202 CreatedBuffer = false;
1203
Douglas Gregor44c181a2010-07-23 00:33:23 +00001204 // Try to determine if the main file has been remapped, either from the
1205 // command line (to another file) or directly through the compiler invocation
1206 // (to a memory buffer).
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001207 llvm::MemoryBuffer *Buffer = nullptr;
Rafael Espindola105b2072013-06-18 19:40:07 +00001208 std::string MainFilePath(FrontendOpts.Inputs[0].getFile());
Rafael Espindola44888352013-07-29 21:26:52 +00001209 llvm::sys::fs::UniqueID MainFileID;
Rafael Espindolada4cb0c2013-06-20 15:12:38 +00001210 if (!llvm::sys::fs::getUniqueID(MainFilePath, MainFileID)) {
Douglas Gregor44c181a2010-07-23 00:33:23 +00001211 // Check whether there is a file-file remapping of the main file
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001212 for (const auto &RF : PreprocessorOpts.RemappedFiles) {
1213 std::string MPath(RF.first);
Rafael Espindola44888352013-07-29 21:26:52 +00001214 llvm::sys::fs::UniqueID MID;
Rafael Espindolada4cb0c2013-06-20 15:12:38 +00001215 if (!llvm::sys::fs::getUniqueID(MPath, MID)) {
Rafael Espindola105b2072013-06-18 19:40:07 +00001216 if (MainFileID == MID) {
Douglas Gregor44c181a2010-07-23 00:33:23 +00001217 // We found a remapping. Try to load the resulting, remapped source.
Douglas Gregor175c4a92010-07-23 23:58:40 +00001218 if (CreatedBuffer) {
Douglas Gregor44c181a2010-07-23 00:33:23 +00001219 delete Buffer;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001220 CreatedBuffer = false;
1221 }
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001222
1223 Buffer = getBufferForFile(RF.second);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001224 if (!Buffer)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001225 return std::make_pair(nullptr, std::make_pair(0, true));
Douglas Gregor175c4a92010-07-23 23:58:40 +00001226 CreatedBuffer = true;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001227 }
1228 }
1229 }
1230
1231 // Check whether there is a file-buffer remapping. It supercedes the
1232 // file-file remapping.
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001233 for (const auto &RB : PreprocessorOpts.RemappedFileBuffers) {
1234 std::string MPath(RB.first);
Rafael Espindola44888352013-07-29 21:26:52 +00001235 llvm::sys::fs::UniqueID MID;
Rafael Espindolada4cb0c2013-06-20 15:12:38 +00001236 if (!llvm::sys::fs::getUniqueID(MPath, MID)) {
Rafael Espindola105b2072013-06-18 19:40:07 +00001237 if (MainFileID == MID) {
1238 // We found a remapping.
Douglas Gregor175c4a92010-07-23 23:58:40 +00001239 if (CreatedBuffer) {
Douglas Gregor44c181a2010-07-23 00:33:23 +00001240 delete Buffer;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001241 CreatedBuffer = false;
1242 }
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001243
1244 Buffer = const_cast<llvm::MemoryBuffer *>(RB.second);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001245 }
1246 }
Douglas Gregor175c4a92010-07-23 23:58:40 +00001247 }
Douglas Gregor44c181a2010-07-23 00:33:23 +00001248 }
1249
1250 // If the main source file was not remapped, load it now.
1251 if (!Buffer) {
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001252 Buffer = getBufferForFile(FrontendOpts.Inputs[0].getFile());
Douglas Gregor44c181a2010-07-23 00:33:23 +00001253 if (!Buffer)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001254 return std::make_pair(nullptr, std::make_pair(0, true));
1255
Douglas Gregor175c4a92010-07-23 23:58:40 +00001256 CreatedBuffer = true;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001257 }
1258
Argyrios Kyrtzidis03c107a2011-08-25 20:39:19 +00001259 return std::make_pair(Buffer, Lexer::ComputePreamble(Buffer,
Ted Kremenekd3b74d92011-11-17 23:01:24 +00001260 *Invocation.getLangOpts(),
Argyrios Kyrtzidis03c107a2011-08-25 20:39:19 +00001261 MaxLines));
Douglas Gregor175c4a92010-07-23 23:58:40 +00001262}
1263
Stephen Hines651f13c2014-04-23 16:59:28 -07001264ASTUnit::PreambleFileHash
1265ASTUnit::PreambleFileHash::createForFile(off_t Size, time_t ModTime) {
1266 PreambleFileHash Result;
1267 Result.Size = Size;
1268 Result.ModTime = ModTime;
1269 memset(Result.MD5, 0, sizeof(Result.MD5));
Douglas Gregor754f3492010-07-24 00:38:13 +00001270 return Result;
1271}
1272
Stephen Hines651f13c2014-04-23 16:59:28 -07001273ASTUnit::PreambleFileHash ASTUnit::PreambleFileHash::createForMemoryBuffer(
1274 const llvm::MemoryBuffer *Buffer) {
1275 PreambleFileHash Result;
1276 Result.Size = Buffer->getBufferSize();
1277 Result.ModTime = 0;
1278
1279 llvm::MD5 MD5Ctx;
1280 MD5Ctx.update(Buffer->getBuffer().data());
1281 MD5Ctx.final(Result.MD5);
1282
1283 return Result;
1284}
1285
1286namespace clang {
1287bool operator==(const ASTUnit::PreambleFileHash &LHS,
1288 const ASTUnit::PreambleFileHash &RHS) {
1289 return LHS.Size == RHS.Size && LHS.ModTime == RHS.ModTime &&
1290 memcmp(LHS.MD5, RHS.MD5, sizeof(LHS.MD5)) == 0;
1291}
1292} // namespace clang
1293
1294static std::pair<unsigned, unsigned>
1295makeStandaloneRange(CharSourceRange Range, const SourceManager &SM,
1296 const LangOptions &LangOpts) {
1297 CharSourceRange FileRange = Lexer::makeFileCharRange(Range, SM, LangOpts);
1298 unsigned Offset = SM.getFileOffset(FileRange.getBegin());
1299 unsigned EndOffset = SM.getFileOffset(FileRange.getEnd());
1300 return std::make_pair(Offset, EndOffset);
1301}
1302
1303static void makeStandaloneFixIt(const SourceManager &SM,
1304 const LangOptions &LangOpts,
1305 const FixItHint &InFix,
1306 ASTUnit::StandaloneFixIt &OutFix) {
1307 OutFix.RemoveRange = makeStandaloneRange(InFix.RemoveRange, SM, LangOpts);
1308 OutFix.InsertFromRange = makeStandaloneRange(InFix.InsertFromRange, SM,
1309 LangOpts);
1310 OutFix.CodeToInsert = InFix.CodeToInsert;
1311 OutFix.BeforePreviousInsertions = InFix.BeforePreviousInsertions;
1312}
1313
1314static void makeStandaloneDiagnostic(const LangOptions &LangOpts,
1315 const StoredDiagnostic &InDiag,
1316 ASTUnit::StandaloneDiagnostic &OutDiag) {
1317 OutDiag.ID = InDiag.getID();
1318 OutDiag.Level = InDiag.getLevel();
1319 OutDiag.Message = InDiag.getMessage();
1320 OutDiag.LocOffset = 0;
1321 if (InDiag.getLocation().isInvalid())
1322 return;
1323 const SourceManager &SM = InDiag.getLocation().getManager();
1324 SourceLocation FileLoc = SM.getFileLoc(InDiag.getLocation());
1325 OutDiag.Filename = SM.getFilename(FileLoc);
1326 if (OutDiag.Filename.empty())
1327 return;
1328 OutDiag.LocOffset = SM.getFileOffset(FileLoc);
1329 for (StoredDiagnostic::range_iterator
1330 I = InDiag.range_begin(), E = InDiag.range_end(); I != E; ++I) {
1331 OutDiag.Ranges.push_back(makeStandaloneRange(*I, SM, LangOpts));
1332 }
1333 for (StoredDiagnostic::fixit_iterator
1334 I = InDiag.fixit_begin(), E = InDiag.fixit_end(); I != E; ++I) {
1335 ASTUnit::StandaloneFixIt Fix;
1336 makeStandaloneFixIt(SM, LangOpts, *I, Fix);
1337 OutDiag.FixIts.push_back(Fix);
1338 }
1339}
1340
Douglas Gregor175c4a92010-07-23 23:58:40 +00001341/// \brief Attempt to build or re-use a precompiled preamble when (re-)parsing
1342/// the source file.
1343///
1344/// This routine will compute the preamble of the main source file. If a
1345/// non-trivial preamble is found, it will precompile that preamble into a
1346/// precompiled header so that the precompiled preamble can be used to reduce
1347/// reparsing time. If a precompiled preamble has already been constructed,
1348/// this routine will determine if it is still valid and, if so, avoid
1349/// rebuilding the precompiled preamble.
1350///
Douglas Gregordf95a132010-08-09 20:45:32 +00001351/// \param AllowRebuild When true (the default), this routine is
1352/// allowed to rebuild the precompiled preamble if it is found to be
1353/// out-of-date.
1354///
1355/// \param MaxLines When non-zero, the maximum number of lines that
1356/// can occur within the preamble.
1357///
Douglas Gregor754f3492010-07-24 00:38:13 +00001358/// \returns If the precompiled preamble can be used, returns a newly-allocated
1359/// buffer that should be used in place of the main file when doing so.
1360/// Otherwise, returns a NULL pointer.
Douglas Gregordf95a132010-08-09 20:45:32 +00001361llvm::MemoryBuffer *ASTUnit::getMainBufferWithPrecompiledPreamble(
Douglas Gregor01b6e312011-07-01 18:22:13 +00001362 const CompilerInvocation &PreambleInvocationIn,
Douglas Gregordf95a132010-08-09 20:45:32 +00001363 bool AllowRebuild,
1364 unsigned MaxLines) {
Douglas Gregor01b6e312011-07-01 18:22:13 +00001365
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001366 IntrusiveRefCntPtr<CompilerInvocation>
Douglas Gregor01b6e312011-07-01 18:22:13 +00001367 PreambleInvocation(new CompilerInvocation(PreambleInvocationIn));
1368 FrontendOptions &FrontendOpts = PreambleInvocation->getFrontendOpts();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001369 PreprocessorOptions &PreprocessorOpts
Douglas Gregor01b6e312011-07-01 18:22:13 +00001370 = PreambleInvocation->getPreprocessorOpts();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001371
1372 bool CreatedPreambleBuffer = false;
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001373 std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> > NewPreamble
Douglas Gregor01b6e312011-07-01 18:22:13 +00001374 = ComputePreamble(*PreambleInvocation, MaxLines, CreatedPreambleBuffer);
Douglas Gregor175c4a92010-07-23 23:58:40 +00001375
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001376 // If ComputePreamble() Take ownership of the preamble buffer.
Stephen Hines651f13c2014-04-23 16:59:28 -07001377 std::unique_ptr<llvm::MemoryBuffer> OwnedPreambleBuffer;
Douglas Gregor73fc9122010-11-16 20:45:51 +00001378 if (CreatedPreambleBuffer)
1379 OwnedPreambleBuffer.reset(NewPreamble.first);
1380
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001381 if (!NewPreamble.second.first) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001382 // We couldn't find a preamble in the main source. Clear out the current
1383 // preamble, if we have one. It's obviously no good any more.
1384 Preamble.clear();
Ted Kremenek1872b312011-10-27 17:55:18 +00001385 erasePreambleFile(this);
Douglas Gregoreababfb2010-08-04 05:53:38 +00001386
1387 // The next time we actually see a preamble, precompile it.
1388 PreambleRebuildCounter = 1;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001389 return nullptr;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001390 }
1391
1392 if (!Preamble.empty()) {
1393 // We've previously computed a preamble. Check whether we have the same
1394 // preamble now that we did before, and that there's enough space in
1395 // the main-file buffer within the precompiled preamble to fit the
1396 // new main file.
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001397 if (Preamble.size() == NewPreamble.second.first &&
1398 PreambleEndsAtStartOfLine == NewPreamble.second.second &&
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00001399 memcmp(Preamble.getBufferStart(), NewPreamble.first->getBufferStart(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001400 NewPreamble.second.first) == 0) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001401 // The preamble has not changed. We may be able to re-use the precompiled
1402 // preamble.
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001403
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001404 // Check that none of the files used by the preamble have changed.
1405 bool AnyFileChanged = false;
1406
1407 // First, make a record of those files that have been overridden via
1408 // remapping or unsaved_files.
Stephen Hines651f13c2014-04-23 16:59:28 -07001409 llvm::StringMap<PreambleFileHash> OverriddenFiles;
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001410 for (const auto &R : PreprocessorOpts.RemappedFiles) {
1411 if (AnyFileChanged)
1412 break;
1413
Stephen Hines651f13c2014-04-23 16:59:28 -07001414 vfs::Status Status;
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001415 if (FileMgr->getNoncachedStatValue(R.second, Status)) {
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001416 // If we can't stat the file we're remapping to, assume that something
1417 // horrible happened.
1418 AnyFileChanged = true;
1419 break;
1420 }
Rafael Espindolaaefb1d32013-07-29 18:22:23 +00001421
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001422 OverriddenFiles[R.first] = PreambleFileHash::createForFile(
Rafael Espindolaaefb1d32013-07-29 18:22:23 +00001423 Status.getSize(), Status.getLastModificationTime().toEpochTime());
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001424 }
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001425
1426 for (const auto &RB : PreprocessorOpts.RemappedFileBuffers) {
1427 if (AnyFileChanged)
1428 break;
1429 OverriddenFiles[RB.first] =
1430 PreambleFileHash::createForMemoryBuffer(RB.second);
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001431 }
1432
1433 // Check whether anything has changed.
Stephen Hines651f13c2014-04-23 16:59:28 -07001434 for (llvm::StringMap<PreambleFileHash>::iterator
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001435 F = FilesInPreamble.begin(), FEnd = FilesInPreamble.end();
1436 !AnyFileChanged && F != FEnd;
1437 ++F) {
Stephen Hines651f13c2014-04-23 16:59:28 -07001438 llvm::StringMap<PreambleFileHash>::iterator Overridden
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001439 = OverriddenFiles.find(F->first());
1440 if (Overridden != OverriddenFiles.end()) {
1441 // This file was remapped; check whether the newly-mapped file
1442 // matches up with the previous mapping.
1443 if (Overridden->second != F->second)
1444 AnyFileChanged = true;
1445 continue;
1446 }
1447
1448 // The file was not remapped; check whether it has changed on disk.
Stephen Hines651f13c2014-04-23 16:59:28 -07001449 vfs::Status Status;
Rafael Espindolaaefb1d32013-07-29 18:22:23 +00001450 if (FileMgr->getNoncachedStatValue(F->first(), Status)) {
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001451 // If we can't stat the file, assume that something horrible happened.
1452 AnyFileChanged = true;
Stephen Hines651f13c2014-04-23 16:59:28 -07001453 } else if (Status.getSize() != uint64_t(F->second.Size) ||
Rafael Espindolaaefb1d32013-07-29 18:22:23 +00001454 Status.getLastModificationTime().toEpochTime() !=
Stephen Hines651f13c2014-04-23 16:59:28 -07001455 uint64_t(F->second.ModTime))
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001456 AnyFileChanged = true;
1457 }
1458
1459 if (!AnyFileChanged) {
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001460 // Okay! We can re-use the precompiled preamble.
1461
1462 // Set the state of the diagnostic object to mimic its state
1463 // after parsing the preamble.
1464 getDiagnostics().Reset();
Douglas Gregor32be4a52010-10-11 21:37:58 +00001465 ProcessWarningOptions(getDiagnostics(),
Douglas Gregor01b6e312011-07-01 18:22:13 +00001466 PreambleInvocation->getDiagnosticOpts());
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001467 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001468
Stephen Hines651f13c2014-04-23 16:59:28 -07001469 return llvm::MemoryBuffer::getMemBufferCopy(
1470 NewPreamble.first->getBuffer(), FrontendOpts.Inputs[0].getFile());
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001471 }
Douglas Gregor175c4a92010-07-23 23:58:40 +00001472 }
Douglas Gregordf95a132010-08-09 20:45:32 +00001473
1474 // If we aren't allowed to rebuild the precompiled preamble, just
1475 // return now.
1476 if (!AllowRebuild)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001477 return nullptr;
Douglas Gregoraa3e6ba2010-10-08 04:03:57 +00001478
Douglas Gregor175c4a92010-07-23 23:58:40 +00001479 // We can't reuse the previously-computed preamble. Build a new one.
1480 Preamble.clear();
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001481 PreambleDiagnostics.clear();
Ted Kremenek1872b312011-10-27 17:55:18 +00001482 erasePreambleFile(this);
Douglas Gregoreababfb2010-08-04 05:53:38 +00001483 PreambleRebuildCounter = 1;
Douglas Gregordf95a132010-08-09 20:45:32 +00001484 } else if (!AllowRebuild) {
1485 // We aren't allowed to rebuild the precompiled preamble; just
1486 // return now.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001487 return nullptr;
Douglas Gregordf95a132010-08-09 20:45:32 +00001488 }
Douglas Gregoreababfb2010-08-04 05:53:38 +00001489
1490 // If the preamble rebuild counter > 1, it's because we previously
1491 // failed to build a preamble and we're not yet ready to try
1492 // again. Decrement the counter and return a failure.
1493 if (PreambleRebuildCounter > 1) {
1494 --PreambleRebuildCounter;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001495 return nullptr;
Douglas Gregoreababfb2010-08-04 05:53:38 +00001496 }
1497
Douglas Gregor2cd4fd42010-09-11 17:56:52 +00001498 // Create a temporary file for the precompiled preamble. In rare
1499 // circumstances, this can fail.
1500 std::string PreamblePCHPath = GetPreamblePCHPath();
1501 if (PreamblePCHPath.empty()) {
1502 // Try again next time.
1503 PreambleRebuildCounter = 1;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001504 return nullptr;
Douglas Gregor2cd4fd42010-09-11 17:56:52 +00001505 }
1506
Douglas Gregor175c4a92010-07-23 23:58:40 +00001507 // We did not previously compute a preamble, or it can't be reused anyway.
Douglas Gregor213f18b2010-10-28 15:44:59 +00001508 SimpleTimer PreambleTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00001509 PreambleTimer.setOutput("Precompiling preamble");
Douglas Gregor175c4a92010-07-23 23:58:40 +00001510
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001511 // Save the preamble text for later; we'll need to compare against it for
1512 // subsequent reparses.
Stephen Hines651f13c2014-04-23 16:59:28 -07001513 StringRef MainFilename = FrontendOpts.Inputs[0].getFile();
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00001514 Preamble.assign(FileMgr->getFile(MainFilename),
1515 NewPreamble.first->getBufferStart(),
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001516 NewPreamble.first->getBufferStart()
1517 + NewPreamble.second.first);
1518 PreambleEndsAtStartOfLine = NewPreamble.second.second;
1519
Douglas Gregor671947b2010-08-19 01:33:06 +00001520 delete PreambleBuffer;
1521 PreambleBuffer
Stephen Hines651f13c2014-04-23 16:59:28 -07001522 = llvm::MemoryBuffer::getMemBufferCopy(
1523 NewPreamble.first->getBuffer().slice(0, Preamble.size()), MainFilename);
Rafael Espindola1cd7df42013-06-26 04:12:57 +00001524
Douglas Gregor44c181a2010-07-23 00:33:23 +00001525 // Remap the main source file to the preamble buffer.
Rafael Espindola1cd7df42013-06-26 04:12:57 +00001526 StringRef MainFilePath = FrontendOpts.Inputs[0].getFile();
1527 PreprocessorOpts.addRemappedFile(MainFilePath, PreambleBuffer);
1528
Douglas Gregor44c181a2010-07-23 00:33:23 +00001529 // Tell the compiler invocation to generate a temporary precompiled header.
1530 FrontendOpts.ProgramAction = frontend::GeneratePCH;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001531 // FIXME: Generate the precompiled header into memory?
Douglas Gregor2cd4fd42010-09-11 17:56:52 +00001532 FrontendOpts.OutputFile = PreamblePCHPath;
Douglas Gregoraa3e6ba2010-10-08 04:03:57 +00001533 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
1534 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001535
1536 // Create the compiler instance to use for building the precompiled preamble.
Stephen Hines651f13c2014-04-23 16:59:28 -07001537 std::unique_ptr<CompilerInstance> Clang(new CompilerInstance());
Ted Kremenek03201fb2011-03-21 18:40:07 +00001538
1539 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00001540 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1541 CICleanup(Clang.get());
Ted Kremenek03201fb2011-03-21 18:40:07 +00001542
Douglas Gregor01b6e312011-07-01 18:22:13 +00001543 Clang->setInvocation(&*PreambleInvocation);
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001544 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
Douglas Gregor44c181a2010-07-23 00:33:23 +00001545
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001546 // Set up diagnostics, capturing all of the diagnostics produced.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001547 Clang->setDiagnostics(&getDiagnostics());
Douglas Gregor44c181a2010-07-23 00:33:23 +00001548
1549 // Create the target instance.
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001550 Clang->setTarget(TargetInfo::CreateTargetInfo(
1551 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
Ted Kremenek03201fb2011-03-21 18:40:07 +00001552 if (!Clang->hasTarget()) {
Rafael Espindola21b18242013-06-26 04:26:38 +00001553 llvm::sys::fs::remove(FrontendOpts.OutputFile);
Douglas Gregor175c4a92010-07-23 23:58:40 +00001554 Preamble.clear();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001555 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001556 PreprocessorOpts.RemappedFileBuffers.pop_back();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001557 return nullptr;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001558 }
1559
1560 // Inform the target of the language options.
1561 //
1562 // FIXME: We shouldn't need to do this, the target should be immutable once
1563 // created. This complexity should be lifted elsewhere.
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001564 Clang->getTarget().adjust(Clang->getLangOpts());
Douglas Gregor44c181a2010-07-23 00:33:23 +00001565
Ted Kremenek03201fb2011-03-21 18:40:07 +00001566 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Douglas Gregor44c181a2010-07-23 00:33:23 +00001567 "Invocation must have exactly one source file!");
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001568 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
Douglas Gregor44c181a2010-07-23 00:33:23 +00001569 "FIXME: AST inputs not yet supported here!");
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001570 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
Douglas Gregor44c181a2010-07-23 00:33:23 +00001571 "IR inputs not support here!");
1572
1573 // Clear out old caches and data.
Douglas Gregoraa3e6ba2010-10-08 04:03:57 +00001574 getDiagnostics().Reset();
Ted Kremenek03201fb2011-03-21 18:40:07 +00001575 ProcessWarningOptions(getDiagnostics(), Clang->getDiagnosticOpts());
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00001576 checkAndRemoveNonDriverDiags(StoredDiagnostics);
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001577 TopLevelDecls.clear();
1578 TopLevelDeclsInPreamble.clear();
Stephen Hines651f13c2014-04-23 16:59:28 -07001579 PreambleDiagnostics.clear();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001580
1581 IntrusiveRefCntPtr<vfs::FileSystem> VFS =
1582 createVFSFromCompilerInvocation(Clang->getInvocation(), getDiagnostics());
1583 if (!VFS)
1584 return nullptr;
1585
Douglas Gregor44c181a2010-07-23 00:33:23 +00001586 // Create a file manager object to provide access to and cache the filesystem.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001587 Clang->setFileManager(new FileManager(Clang->getFileSystemOpts(), VFS));
Douglas Gregor44c181a2010-07-23 00:33:23 +00001588
1589 // Create the source manager.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001590 Clang->setSourceManager(new SourceManager(getDiagnostics(),
Ted Kremenek4f327862011-03-21 18:40:17 +00001591 Clang->getFileManager()));
Stephen Hines651f13c2014-04-23 16:59:28 -07001592
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001593 auto PreambleDepCollector = std::make_shared<DependencyCollector>();
1594 Clang->addDependencyCollector(PreambleDepCollector);
1595
Stephen Hines651f13c2014-04-23 16:59:28 -07001596 std::unique_ptr<PrecompilePreambleAction> Act;
Douglas Gregor1d715ac2010-08-03 08:14:03 +00001597 Act.reset(new PrecompilePreambleAction(*this));
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001598 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
Rafael Espindola21b18242013-06-26 04:26:38 +00001599 llvm::sys::fs::remove(FrontendOpts.OutputFile);
Douglas Gregor175c4a92010-07-23 23:58:40 +00001600 Preamble.clear();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001601 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001602 PreprocessorOpts.RemappedFileBuffers.pop_back();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001603 return nullptr;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001604 }
1605
1606 Act->Execute();
Stephen Hines651f13c2014-04-23 16:59:28 -07001607
1608 // Transfer any diagnostics generated when parsing the preamble into the set
1609 // of preamble diagnostics.
1610 for (stored_diag_iterator
1611 I = stored_diag_afterDriver_begin(),
1612 E = stored_diag_end(); I != E; ++I) {
1613 StandaloneDiagnostic Diag;
1614 makeStandaloneDiagnostic(Clang->getLangOpts(), *I, Diag);
1615 PreambleDiagnostics.push_back(Diag);
1616 }
1617
Douglas Gregor44c181a2010-07-23 00:33:23 +00001618 Act->EndSourceFile();
Ted Kremenek4f327862011-03-21 18:40:17 +00001619
Stephen Hines651f13c2014-04-23 16:59:28 -07001620 checkAndRemoveNonDriverDiags(StoredDiagnostics);
1621
Argyrios Kyrtzidis1f01f7c2013-06-11 00:36:55 +00001622 if (!Act->hasEmittedPreamblePCH()) {
Argyrios Kyrtzidis739f9e52013-06-11 16:42:34 +00001623 // The preamble PCH failed (e.g. there was a module loading fatal error),
1624 // so no precompiled header was generated. Forget that we even tried.
Douglas Gregor06e50442010-09-27 16:43:25 +00001625 // FIXME: Should we leave a note for ourselves to try again?
Rafael Espindola21b18242013-06-26 04:26:38 +00001626 llvm::sys::fs::remove(FrontendOpts.OutputFile);
Douglas Gregor175c4a92010-07-23 23:58:40 +00001627 Preamble.clear();
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001628 TopLevelDeclsInPreamble.clear();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001629 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001630 PreprocessorOpts.RemappedFileBuffers.pop_back();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001631 return nullptr;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001632 }
1633
1634 // Keep track of the preamble we precompiled.
Ted Kremenek1872b312011-10-27 17:55:18 +00001635 setPreambleFile(this, FrontendOpts.OutputFile);
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001636 NumWarningsInPreamble = getDiagnostics().getNumWarnings();
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001637
1638 // Keep track of all of the files that the source manager knows about,
1639 // so we can verify whether they have changed or not.
1640 FilesInPreamble.clear();
Ted Kremenek03201fb2011-03-21 18:40:07 +00001641 SourceManager &SourceMgr = Clang->getSourceManager();
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001642 for (auto &Filename : PreambleDepCollector->getDependencies()) {
1643 const FileEntry *File = Clang->getFileManager().getFile(Filename);
1644 if (!File || File == SourceMgr.getFileEntryForID(SourceMgr.getMainFileID()))
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001645 continue;
Stephen Hines651f13c2014-04-23 16:59:28 -07001646 if (time_t ModTime = File->getModificationTime()) {
1647 FilesInPreamble[File->getName()] = PreambleFileHash::createForFile(
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001648 File->getSize(), ModTime);
Stephen Hines651f13c2014-04-23 16:59:28 -07001649 } else {
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001650 llvm::MemoryBuffer *Buffer = SourceMgr.getMemoryBufferForFile(File);
Stephen Hines651f13c2014-04-23 16:59:28 -07001651 FilesInPreamble[File->getName()] =
1652 PreambleFileHash::createForMemoryBuffer(Buffer);
1653 }
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001654 }
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001655
Douglas Gregoreababfb2010-08-04 05:53:38 +00001656 PreambleRebuildCounter = 1;
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001657 PreprocessorOpts.RemappedFileBuffers.pop_back();
1658
Douglas Gregor9b7db622011-02-16 18:16:54 +00001659 // If the hash of top-level entities differs from the hash of the top-level
1660 // entities the last time we rebuilt the preamble, clear out the completion
1661 // cache.
1662 if (CurrentTopLevelHashValue != PreambleTopLevelHashValue) {
1663 CompletionCacheTopLevelHashValue = 0;
1664 PreambleTopLevelHashValue = CurrentTopLevelHashValue;
1665 }
1666
Stephen Hines651f13c2014-04-23 16:59:28 -07001667 return llvm::MemoryBuffer::getMemBufferCopy(NewPreamble.first->getBuffer(),
1668 MainFilename);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001669}
Douglas Gregorabc563f2010-07-19 21:46:24 +00001670
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001671void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
1672 std::vector<Decl *> Resolved;
1673 Resolved.reserve(TopLevelDeclsInPreamble.size());
1674 ExternalASTSource &Source = *getASTContext().getExternalSource();
1675 for (unsigned I = 0, N = TopLevelDeclsInPreamble.size(); I != N; ++I) {
1676 // Resolve the declaration ID to an actual declaration, possibly
1677 // deserializing the declaration in the process.
1678 Decl *D = Source.GetExternalDecl(TopLevelDeclsInPreamble[I]);
1679 if (D)
1680 Resolved.push_back(D);
1681 }
1682 TopLevelDeclsInPreamble.clear();
1683 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1684}
1685
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001686void ASTUnit::transferASTDataFromCompilerInstance(CompilerInstance &CI) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001687 // Steal the created target, context, and preprocessor if they have been
1688 // created.
1689 assert(CI.hasInvocation() && "missing invocation");
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001690 LangOpts = CI.getInvocation().LangOpts;
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001691 TheSema.reset(CI.takeSema());
1692 Consumer.reset(CI.takeASTConsumer());
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001693 if (CI.hasASTContext())
1694 Ctx = &CI.getASTContext();
1695 if (CI.hasPreprocessor())
1696 PP = &CI.getPreprocessor();
1697 CI.setSourceManager(nullptr);
1698 CI.setFileManager(nullptr);
1699 if (CI.hasTarget())
1700 Target = &CI.getTarget();
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001701 Reader = CI.getModuleManager();
Argyrios Kyrtzidis3b7deda2013-05-24 05:44:08 +00001702 HadModuleLoaderFatalFailure = CI.hadModuleLoaderFatalFailure();
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001703}
1704
Chris Lattner5f9e2722011-07-23 10:55:15 +00001705StringRef ASTUnit::getMainFileName() const {
Argyrios Kyrtzidis814b51a2013-01-11 22:11:14 +00001706 if (Invocation && !Invocation->getFrontendOpts().Inputs.empty()) {
1707 const FrontendInputFile &Input = Invocation->getFrontendOpts().Inputs[0];
1708 if (Input.isFile())
1709 return Input.getFile();
1710 else
1711 return Input.getBuffer()->getBufferIdentifier();
1712 }
1713
1714 if (SourceMgr) {
1715 if (const FileEntry *
1716 FE = SourceMgr->getFileEntryForID(SourceMgr->getMainFileID()))
1717 return FE->getName();
1718 }
1719
1720 return StringRef();
Douglas Gregor213f18b2010-10-28 15:44:59 +00001721}
1722
Argyrios Kyrtzidis44f65a52013-03-05 20:21:14 +00001723StringRef ASTUnit::getASTFileName() const {
1724 if (!isMainFileAST())
1725 return StringRef();
1726
1727 serialization::ModuleFile &
1728 Mod = Reader->getModuleManager().getPrimaryModule();
1729 return Mod.FileName;
1730}
1731
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001732ASTUnit *ASTUnit::create(CompilerInvocation *CI,
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001733 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001734 bool CaptureDiagnostics,
1735 bool UserFilesAreVolatile) {
Stephen Hines651f13c2014-04-23 16:59:28 -07001736 std::unique_ptr<ASTUnit> AST;
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001737 AST.reset(new ASTUnit(false));
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001738 ConfigureDiags(Diags, nullptr, nullptr, *AST, CaptureDiagnostics);
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001739 AST->Diagnostics = Diags;
Ted Kremenek4f327862011-03-21 18:40:17 +00001740 AST->Invocation = CI;
Anders Carlsson0d8d7e62011-03-18 18:22:40 +00001741 AST->FileSystemOpts = CI->getFileSystemOpts();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001742 IntrusiveRefCntPtr<vfs::FileSystem> VFS =
1743 createVFSFromCompilerInvocation(*CI, *Diags);
1744 if (!VFS)
1745 return nullptr;
1746 AST->FileMgr = new FileManager(AST->FileSystemOpts, VFS);
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001747 AST->UserFilesAreVolatile = UserFilesAreVolatile;
1748 AST->SourceMgr = new SourceManager(AST->getDiagnostics(), *AST->FileMgr,
1749 UserFilesAreVolatile);
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001750
Stephen Hines651f13c2014-04-23 16:59:28 -07001751 return AST.release();
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001752}
1753
Stephen Hines651f13c2014-04-23 16:59:28 -07001754ASTUnit *ASTUnit::LoadFromCompilerInvocationAction(
1755 CompilerInvocation *CI, IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
1756 ASTFrontendAction *Action, ASTUnit *Unit, bool Persistent,
1757 StringRef ResourceFilesPath, bool OnlyLocalDecls, bool CaptureDiagnostics,
1758 bool PrecompilePreamble, bool CacheCodeCompletionResults,
1759 bool IncludeBriefCommentsInCodeCompletion, bool UserFilesAreVolatile,
1760 std::unique_ptr<ASTUnit> *ErrAST) {
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001761 assert(CI && "A CompilerInvocation is required");
1762
Stephen Hines651f13c2014-04-23 16:59:28 -07001763 std::unique_ptr<ASTUnit> OwnAST;
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001764 ASTUnit *AST = Unit;
1765 if (!AST) {
1766 // Create the AST unit.
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001767 OwnAST.reset(create(CI, Diags, CaptureDiagnostics, UserFilesAreVolatile));
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001768 AST = OwnAST.get();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001769 if (!AST)
1770 return nullptr;
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001771 }
1772
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00001773 if (!ResourceFilesPath.empty()) {
1774 // Override the resources path.
1775 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
1776 }
1777 AST->OnlyLocalDecls = OnlyLocalDecls;
1778 AST->CaptureDiagnostics = CaptureDiagnostics;
1779 if (PrecompilePreamble)
1780 AST->PreambleRebuildCounter = 2;
Douglas Gregor467dc882011-08-25 22:30:56 +00001781 AST->TUKind = Action ? Action->getTranslationUnitKind() : TU_Complete;
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00001782 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00001783 AST->IncludeBriefCommentsInCodeCompletion
1784 = IncludeBriefCommentsInCodeCompletion;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001785
1786 // Recover resources if we crash before exiting this method.
1787 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001788 ASTUnitCleanup(OwnAST.get());
David Blaikied6471f72011-09-25 23:23:43 +00001789 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1790 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001791 DiagCleanup(Diags.get());
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001792
1793 // We'll manage file buffers ourselves.
1794 CI->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1795 CI->getFrontendOpts().DisableFree = false;
1796 ProcessWarningOptions(AST->getDiagnostics(), CI->getDiagnosticOpts());
1797
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001798 // Create the compiler instance to use for building the AST.
Stephen Hines651f13c2014-04-23 16:59:28 -07001799 std::unique_ptr<CompilerInstance> Clang(new CompilerInstance());
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001800
1801 // Recover resources if we crash before exiting this method.
1802 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1803 CICleanup(Clang.get());
1804
1805 Clang->setInvocation(CI);
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001806 AST->OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001807
1808 // Set up diagnostics, capturing any diagnostics that would
1809 // otherwise be dropped.
1810 Clang->setDiagnostics(&AST->getDiagnostics());
1811
1812 // Create the target instance.
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001813 Clang->setTarget(TargetInfo::CreateTargetInfo(
1814 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001815 if (!Clang->hasTarget())
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001816 return nullptr;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001817
1818 // Inform the target of the language options.
1819 //
1820 // FIXME: We shouldn't need to do this, the target should be immutable once
1821 // created. This complexity should be lifted elsewhere.
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001822 Clang->getTarget().adjust(Clang->getLangOpts());
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001823
1824 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1825 "Invocation must have exactly one source file!");
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001826 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001827 "FIXME: AST inputs not yet supported here!");
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001828 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001829 "IR inputs not supported here!");
1830
1831 // Configure the various subsystems.
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001832 AST->TheSema.reset();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001833 AST->Ctx = nullptr;
1834 AST->PP = nullptr;
1835 AST->Reader = nullptr;
1836
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001837 // Create a file manager object to provide access to and cache the filesystem.
1838 Clang->setFileManager(&AST->getFileManager());
1839
1840 // Create the source manager.
1841 Clang->setSourceManager(&AST->getSourceManager());
1842
1843 ASTFrontendAction *Act = Action;
1844
Stephen Hines651f13c2014-04-23 16:59:28 -07001845 std::unique_ptr<TopLevelDeclTrackerAction> TrackerAct;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001846 if (!Act) {
1847 TrackerAct.reset(new TopLevelDeclTrackerAction(*AST));
1848 Act = TrackerAct.get();
1849 }
1850
1851 // Recover resources if we crash before exiting this method.
1852 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1853 ActCleanup(TrackerAct.get());
1854
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001855 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
1856 AST->transferASTDataFromCompilerInstance(*Clang);
1857 if (OwnAST && ErrAST)
1858 ErrAST->swap(OwnAST);
1859
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001860 return nullptr;
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001861 }
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00001862
1863 if (Persistent && !TrackerAct) {
1864 Clang->getPreprocessor().addPPCallbacks(
1865 new MacroDefinitionTrackerPPCallbacks(AST->getCurrentTopLevelHashValue()));
1866 std::vector<ASTConsumer*> Consumers;
1867 if (Clang->hasASTConsumer())
1868 Consumers.push_back(Clang->takeASTConsumer());
1869 Consumers.push_back(new TopLevelDeclTrackerConsumer(*AST,
1870 AST->getCurrentTopLevelHashValue()));
1871 Clang->setASTConsumer(new MultiplexConsumer(Consumers));
1872 }
Argyrios Kyrtzidis374a00b2012-06-08 05:48:06 +00001873 if (!Act->Execute()) {
1874 AST->transferASTDataFromCompilerInstance(*Clang);
1875 if (OwnAST && ErrAST)
1876 ErrAST->swap(OwnAST);
1877
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001878 return nullptr;
Argyrios Kyrtzidis374a00b2012-06-08 05:48:06 +00001879 }
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001880
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001881 // Steal the created target, context, and preprocessor.
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001882 AST->transferASTDataFromCompilerInstance(*Clang);
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001883
1884 Act->EndSourceFile();
1885
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001886 if (OwnAST)
Stephen Hines651f13c2014-04-23 16:59:28 -07001887 return OwnAST.release();
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001888 else
1889 return AST;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001890}
1891
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001892bool ASTUnit::LoadFromCompilerInvocation(bool PrecompilePreamble) {
1893 if (!Invocation)
1894 return true;
1895
1896 // We'll manage file buffers ourselves.
1897 Invocation->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1898 Invocation->getFrontendOpts().DisableFree = false;
Douglas Gregor0b53cf82011-01-19 01:02:47 +00001899 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001900
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001901 llvm::MemoryBuffer *OverrideMainBuffer = nullptr;
Douglas Gregor99ba2022010-10-27 17:24:53 +00001902 if (PrecompilePreamble) {
Douglas Gregor08bb4c62010-11-15 23:00:34 +00001903 PreambleRebuildCounter = 2;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001904 OverrideMainBuffer
1905 = getMainBufferWithPrecompiledPreamble(*Invocation);
1906 }
1907
Douglas Gregor213f18b2010-10-28 15:44:59 +00001908 SimpleTimer ParsingTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00001909 ParsingTimer.setOutput("Parsing " + getMainFileName());
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001910
Ted Kremenek25a11e12011-03-22 01:15:24 +00001911 // Recover resources if we crash before exiting this method.
1912 llvm::CrashRecoveryContextCleanupRegistrar<llvm::MemoryBuffer>
1913 MemBufferCleanup(OverrideMainBuffer);
1914
Douglas Gregor213f18b2010-10-28 15:44:59 +00001915 return Parse(OverrideMainBuffer);
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001916}
1917
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001918std::unique_ptr<ASTUnit> ASTUnit::LoadFromCompilerInvocation(
1919 CompilerInvocation *CI, IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
1920 bool OnlyLocalDecls, bool CaptureDiagnostics, bool PrecompilePreamble,
1921 TranslationUnitKind TUKind, bool CacheCodeCompletionResults,
1922 bool IncludeBriefCommentsInCodeCompletion, bool UserFilesAreVolatile) {
Douglas Gregorabc563f2010-07-19 21:46:24 +00001923 // Create the AST unit.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001924 std::unique_ptr<ASTUnit> AST(new ASTUnit(false));
1925 ConfigureDiags(Diags, nullptr, nullptr, *AST, CaptureDiagnostics);
Douglas Gregorabc563f2010-07-19 21:46:24 +00001926 AST->Diagnostics = Diags;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001927 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregore47be3e2010-11-11 00:39:14 +00001928 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor467dc882011-08-25 22:30:56 +00001929 AST->TUKind = TUKind;
Douglas Gregor87c08a52010-08-13 22:48:40 +00001930 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00001931 AST->IncludeBriefCommentsInCodeCompletion
1932 = IncludeBriefCommentsInCodeCompletion;
Ted Kremenek4f327862011-03-21 18:40:17 +00001933 AST->Invocation = CI;
Argyrios Kyrtzidiseb8fc582013-01-21 18:45:42 +00001934 AST->FileSystemOpts = CI->getFileSystemOpts();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001935 IntrusiveRefCntPtr<vfs::FileSystem> VFS =
1936 createVFSFromCompilerInvocation(*CI, *Diags);
1937 if (!VFS)
1938 return nullptr;
1939 AST->FileMgr = new FileManager(AST->FileSystemOpts, VFS);
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001940 AST->UserFilesAreVolatile = UserFilesAreVolatile;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001941
Ted Kremenekb547eeb2011-03-18 02:06:56 +00001942 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00001943 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1944 ASTUnitCleanup(AST.get());
David Blaikied6471f72011-09-25 23:23:43 +00001945 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1946 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001947 DiagCleanup(Diags.get());
Ted Kremenekb547eeb2011-03-18 02:06:56 +00001948
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001949 if (AST->LoadFromCompilerInvocation(PrecompilePreamble))
1950 return nullptr;
1951 return AST;
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001952}
Daniel Dunbar7b556682009-12-02 03:23:45 +00001953
Stephen Hines651f13c2014-04-23 16:59:28 -07001954ASTUnit *ASTUnit::LoadFromCommandLine(
1955 const char **ArgBegin, const char **ArgEnd,
1956 IntrusiveRefCntPtr<DiagnosticsEngine> Diags, StringRef ResourceFilesPath,
1957 bool OnlyLocalDecls, bool CaptureDiagnostics,
1958 ArrayRef<RemappedFile> RemappedFiles, bool RemappedFilesKeepOriginalName,
1959 bool PrecompilePreamble, TranslationUnitKind TUKind,
1960 bool CacheCodeCompletionResults, bool IncludeBriefCommentsInCodeCompletion,
1961 bool AllowPCHWithCompilerErrors, bool SkipFunctionBodies,
1962 bool UserFilesAreVolatile, bool ForSerialization,
1963 std::unique_ptr<ASTUnit> *ErrAST) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001964 if (!Diags.get()) {
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001965 // No diagnostics engine was provided, so create our own diagnostics object
1966 // with the default options.
Sean Silvad47afb92013-01-20 01:58:28 +00001967 Diags = CompilerInstance::createDiagnostics(new DiagnosticOptions());
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001968 }
Daniel Dunbar7b556682009-12-02 03:23:45 +00001969
Chris Lattner5f9e2722011-07-23 10:55:15 +00001970 SmallVector<StoredDiagnostic, 4> StoredDiagnostics;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001971
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001972 IntrusiveRefCntPtr<CompilerInvocation> CI;
Douglas Gregore47be3e2010-11-11 00:39:14 +00001973
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001974 {
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001975
Douglas Gregore47be3e2010-11-11 00:39:14 +00001976 CaptureDroppedDiagnostics Capture(CaptureDiagnostics, *Diags,
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001977 StoredDiagnostics);
Daniel Dunbar3bd54cc2010-01-25 00:44:02 +00001978
Argyrios Kyrtzidis832316e2011-04-04 23:11:45 +00001979 CI = clang::createInvocationFromCommandLine(
Frits van Bommele9c02652011-07-18 12:00:32 +00001980 llvm::makeArrayRef(ArgBegin, ArgEnd),
1981 Diags);
Argyrios Kyrtzidis054e4f52011-04-04 21:38:51 +00001982 if (!CI)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001983 return nullptr;
Daniel Dunbar7b556682009-12-02 03:23:45 +00001984 }
Douglas Gregore47be3e2010-11-11 00:39:14 +00001985
Douglas Gregor4db64a42010-01-23 00:14:00 +00001986 // Override any files that need remapping
Stephen Hines651f13c2014-04-23 16:59:28 -07001987 for (unsigned I = 0, N = RemappedFiles.size(); I != N; ++I) {
1988 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
1989 RemappedFiles[I].second);
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001990 }
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +00001991 PreprocessorOptions &PPOpts = CI->getPreprocessorOpts();
1992 PPOpts.RemappedFilesKeepOriginalName = RemappedFilesKeepOriginalName;
1993 PPOpts.AllowPCHWithCompilerErrors = AllowPCHWithCompilerErrors;
Douglas Gregor4db64a42010-01-23 00:14:00 +00001994
Daniel Dunbar8b9adfe2009-12-15 00:06:45 +00001995 // Override the resources path.
Daniel Dunbar807b0612010-01-30 21:47:16 +00001996 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
Daniel Dunbar7b556682009-12-02 03:23:45 +00001997
Erik Verbruggen6a91d382012-04-12 10:11:59 +00001998 CI->getFrontendOpts().SkipFunctionBodies = SkipFunctionBodies;
1999
Douglas Gregor4cd912a2010-10-12 00:50:20 +00002000 // Create the AST unit.
Stephen Hines651f13c2014-04-23 16:59:28 -07002001 std::unique_ptr<ASTUnit> AST;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00002002 AST.reset(new ASTUnit(false));
Douglas Gregor0b53cf82011-01-19 01:02:47 +00002003 ConfigureDiags(Diags, ArgBegin, ArgEnd, *AST, CaptureDiagnostics);
Douglas Gregor4cd912a2010-10-12 00:50:20 +00002004 AST->Diagnostics = Diags;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002005 Diags = nullptr; // Zero out now to ease cleanup during crash recovery.
Anders Carlsson0d8d7e62011-03-18 18:22:40 +00002006 AST->FileSystemOpts = CI->getFileSystemOpts();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002007 IntrusiveRefCntPtr<vfs::FileSystem> VFS =
2008 createVFSFromCompilerInvocation(*CI, *Diags);
2009 if (!VFS)
2010 return nullptr;
2011 AST->FileMgr = new FileManager(AST->FileSystemOpts, VFS);
Douglas Gregor4cd912a2010-10-12 00:50:20 +00002012 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregore47be3e2010-11-11 00:39:14 +00002013 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor467dc882011-08-25 22:30:56 +00002014 AST->TUKind = TUKind;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00002015 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002016 AST->IncludeBriefCommentsInCodeCompletion
2017 = IncludeBriefCommentsInCodeCompletion;
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00002018 AST->UserFilesAreVolatile = UserFilesAreVolatile;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00002019 AST->NumStoredDiagnosticsFromDriver = StoredDiagnostics.size();
Douglas Gregor4cd912a2010-10-12 00:50:20 +00002020 AST->StoredDiagnostics.swap(StoredDiagnostics);
Ted Kremenek4f327862011-03-21 18:40:17 +00002021 AST->Invocation = CI;
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +00002022 if (ForSerialization)
2023 AST->WriterData.reset(new ASTWriterData());
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002024 CI = nullptr; // Zero out now to ease cleanup during crash recovery.
2025
Ted Kremenekb547eeb2011-03-18 02:06:56 +00002026 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00002027 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
2028 ASTUnitCleanup(AST.get());
Ted Kremenekb547eeb2011-03-18 02:06:56 +00002029
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00002030 if (AST->LoadFromCompilerInvocation(PrecompilePreamble)) {
2031 // Some error occurred, if caller wants to examine diagnostics, pass it the
2032 // ASTUnit.
2033 if (ErrAST) {
2034 AST->StoredDiagnostics.swap(AST->FailedParseDiagnostics);
2035 ErrAST->swap(AST);
2036 }
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002037 return nullptr;
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00002038 }
2039
Stephen Hines651f13c2014-04-23 16:59:28 -07002040 return AST.release();
Daniel Dunbar7b556682009-12-02 03:23:45 +00002041}
Douglas Gregorabc563f2010-07-19 21:46:24 +00002042
Stephen Hines651f13c2014-04-23 16:59:28 -07002043bool ASTUnit::Reparse(ArrayRef<RemappedFile> RemappedFiles) {
Ted Kremenek4f327862011-03-21 18:40:17 +00002044 if (!Invocation)
Douglas Gregorabc563f2010-07-19 21:46:24 +00002045 return true;
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +00002046
2047 clearFileLevelDecls();
Douglas Gregorabc563f2010-07-19 21:46:24 +00002048
Douglas Gregor213f18b2010-10-28 15:44:59 +00002049 SimpleTimer ParsingTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00002050 ParsingTimer.setOutput("Reparsing " + getMainFileName());
Douglas Gregor213f18b2010-10-28 15:44:59 +00002051
Douglas Gregorcc5888d2010-07-31 00:40:00 +00002052 // Remap files.
Douglas Gregorf128fed2010-08-20 00:02:33 +00002053 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002054 for (const auto &RB : PPOpts.RemappedFileBuffers)
2055 delete RB.second;
2056
Douglas Gregorcc5888d2010-07-31 00:40:00 +00002057 Invocation->getPreprocessorOpts().clearRemappedFiles();
Stephen Hines651f13c2014-04-23 16:59:28 -07002058 for (unsigned I = 0, N = RemappedFiles.size(); I != N; ++I) {
2059 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
2060 RemappedFiles[I].second);
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00002061 }
Stephen Hines651f13c2014-04-23 16:59:28 -07002062
Douglas Gregoreababfb2010-08-04 05:53:38 +00002063 // If we have a preamble file lying around, or if we might try to
2064 // build a precompiled preamble, do so now.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002065 llvm::MemoryBuffer *OverrideMainBuffer = nullptr;
Ted Kremenek1872b312011-10-27 17:55:18 +00002066 if (!getPreambleFile(this).empty() || PreambleRebuildCounter > 0)
Douglas Gregor2283d792010-08-20 00:59:43 +00002067 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(*Invocation);
Douglas Gregor175c4a92010-07-23 23:58:40 +00002068
Douglas Gregorabc563f2010-07-19 21:46:24 +00002069 // Clear out the diagnostics state.
Argyrios Kyrtzidise6825d32011-11-03 20:28:19 +00002070 getDiagnostics().Reset();
2071 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Argyrios Kyrtzidis27368f92011-11-03 20:57:33 +00002072 if (OverrideMainBuffer)
2073 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
Argyrios Kyrtzidise6825d32011-11-03 20:28:19 +00002074
Douglas Gregor175c4a92010-07-23 23:58:40 +00002075 // Parse the sources
Douglas Gregor9b7db622011-02-16 18:16:54 +00002076 bool Result = Parse(OverrideMainBuffer);
Argyrios Kyrtzidis2fe17fc2011-10-31 21:25:31 +00002077
2078 // If we're caching global code-completion results, and the top-level
2079 // declarations have changed, clear out the code-completion cache.
2080 if (!Result && ShouldCacheCodeCompletionResults &&
2081 CurrentTopLevelHashValue != CompletionCacheTopLevelHashValue)
2082 CacheCodeCompletionResults();
Douglas Gregor9b7db622011-02-16 18:16:54 +00002083
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00002084 // We now need to clear out the completion info related to this translation
2085 // unit; it'll be recreated if necessary.
2086 CCTUInfo.reset();
Douglas Gregor8fa0a802011-08-04 20:04:59 +00002087
Douglas Gregor175c4a92010-07-23 23:58:40 +00002088 return Result;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002089}
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002090
Douglas Gregor87c08a52010-08-13 22:48:40 +00002091//----------------------------------------------------------------------------//
2092// Code completion
2093//----------------------------------------------------------------------------//
2094
2095namespace {
2096 /// \brief Code completion consumer that combines the cached code-completion
2097 /// results from an ASTUnit with the code-completion results provided to it,
2098 /// then passes the result on to
2099 class AugmentedCodeCompleteConsumer : public CodeCompleteConsumer {
Richard Smith026b3582012-08-14 03:13:00 +00002100 uint64_t NormalContexts;
Douglas Gregor87c08a52010-08-13 22:48:40 +00002101 ASTUnit &AST;
2102 CodeCompleteConsumer &Next;
2103
2104 public:
2105 AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002106 const CodeCompleteOptions &CodeCompleteOpts)
2107 : CodeCompleteConsumer(CodeCompleteOpts, Next.isOutputBinary()),
2108 AST(AST), Next(Next)
Douglas Gregor87c08a52010-08-13 22:48:40 +00002109 {
2110 // Compute the set of contexts in which we will look when we don't have
2111 // any information about the specific context.
2112 NormalContexts
Richard Smith026b3582012-08-14 03:13:00 +00002113 = (1LL << CodeCompletionContext::CCC_TopLevel)
2114 | (1LL << CodeCompletionContext::CCC_ObjCInterface)
2115 | (1LL << CodeCompletionContext::CCC_ObjCImplementation)
2116 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
2117 | (1LL << CodeCompletionContext::CCC_Statement)
2118 | (1LL << CodeCompletionContext::CCC_Expression)
2119 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
2120 | (1LL << CodeCompletionContext::CCC_DotMemberAccess)
2121 | (1LL << CodeCompletionContext::CCC_ArrowMemberAccess)
2122 | (1LL << CodeCompletionContext::CCC_ObjCPropertyAccess)
2123 | (1LL << CodeCompletionContext::CCC_ObjCProtocolName)
2124 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
2125 | (1LL << CodeCompletionContext::CCC_Recovery);
Douglas Gregor02688102010-09-14 23:59:36 +00002126
David Blaikie4e4d0842012-03-11 07:00:24 +00002127 if (AST.getASTContext().getLangOpts().CPlusPlus)
Richard Smith026b3582012-08-14 03:13:00 +00002128 NormalContexts |= (1LL << CodeCompletionContext::CCC_EnumTag)
2129 | (1LL << CodeCompletionContext::CCC_UnionTag)
2130 | (1LL << CodeCompletionContext::CCC_ClassOrStructTag);
Douglas Gregor87c08a52010-08-13 22:48:40 +00002131 }
Stephen Hines651f13c2014-04-23 16:59:28 -07002132
2133 void ProcessCodeCompleteResults(Sema &S, CodeCompletionContext Context,
2134 CodeCompletionResult *Results,
2135 unsigned NumResults) override;
2136
2137 void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
2138 OverloadCandidate *Candidates,
2139 unsigned NumCandidates) override {
Douglas Gregor87c08a52010-08-13 22:48:40 +00002140 Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates);
2141 }
Stephen Hines651f13c2014-04-23 16:59:28 -07002142
2143 CodeCompletionAllocator &getAllocator() override {
Douglas Gregor218937c2011-02-01 19:23:04 +00002144 return Next.getAllocator();
2145 }
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00002146
Stephen Hines651f13c2014-04-23 16:59:28 -07002147 CodeCompletionTUInfo &getCodeCompletionTUInfo() override {
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00002148 return Next.getCodeCompletionTUInfo();
2149 }
Douglas Gregor87c08a52010-08-13 22:48:40 +00002150 };
2151}
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002152
Douglas Gregor5f808c22010-08-16 21:18:39 +00002153/// \brief Helper function that computes which global names are hidden by the
2154/// local code-completion results.
Ted Kremenekc198f612010-11-07 06:11:36 +00002155static void CalculateHiddenNames(const CodeCompletionContext &Context,
2156 CodeCompletionResult *Results,
2157 unsigned NumResults,
2158 ASTContext &Ctx,
2159 llvm::StringSet<llvm::BumpPtrAllocator> &HiddenNames){
Douglas Gregor5f808c22010-08-16 21:18:39 +00002160 bool OnlyTagNames = false;
2161 switch (Context.getKind()) {
Douglas Gregor52779fb2010-09-23 23:01:17 +00002162 case CodeCompletionContext::CCC_Recovery:
Douglas Gregor5f808c22010-08-16 21:18:39 +00002163 case CodeCompletionContext::CCC_TopLevel:
2164 case CodeCompletionContext::CCC_ObjCInterface:
2165 case CodeCompletionContext::CCC_ObjCImplementation:
2166 case CodeCompletionContext::CCC_ObjCIvarList:
2167 case CodeCompletionContext::CCC_ClassStructUnion:
2168 case CodeCompletionContext::CCC_Statement:
2169 case CodeCompletionContext::CCC_Expression:
2170 case CodeCompletionContext::CCC_ObjCMessageReceiver:
Douglas Gregor3da626b2011-07-07 16:03:39 +00002171 case CodeCompletionContext::CCC_DotMemberAccess:
2172 case CodeCompletionContext::CCC_ArrowMemberAccess:
2173 case CodeCompletionContext::CCC_ObjCPropertyAccess:
Douglas Gregor5f808c22010-08-16 21:18:39 +00002174 case CodeCompletionContext::CCC_Namespace:
2175 case CodeCompletionContext::CCC_Type:
Douglas Gregor2ccccb32010-08-23 18:23:48 +00002176 case CodeCompletionContext::CCC_Name:
2177 case CodeCompletionContext::CCC_PotentiallyQualifiedName:
Douglas Gregor02688102010-09-14 23:59:36 +00002178 case CodeCompletionContext::CCC_ParenthesizedExpression:
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00002179 case CodeCompletionContext::CCC_ObjCInterfaceName:
Douglas Gregor5f808c22010-08-16 21:18:39 +00002180 break;
2181
2182 case CodeCompletionContext::CCC_EnumTag:
2183 case CodeCompletionContext::CCC_UnionTag:
2184 case CodeCompletionContext::CCC_ClassOrStructTag:
2185 OnlyTagNames = true;
2186 break;
2187
2188 case CodeCompletionContext::CCC_ObjCProtocolName:
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002189 case CodeCompletionContext::CCC_MacroName:
2190 case CodeCompletionContext::CCC_MacroNameUse:
Douglas Gregorf29c5232010-08-24 22:20:20 +00002191 case CodeCompletionContext::CCC_PreprocessorExpression:
Douglas Gregor721f3592010-08-25 18:41:16 +00002192 case CodeCompletionContext::CCC_PreprocessorDirective:
Douglas Gregor59a66942010-08-25 18:04:30 +00002193 case CodeCompletionContext::CCC_NaturalLanguage:
Douglas Gregor458433d2010-08-26 15:07:07 +00002194 case CodeCompletionContext::CCC_SelectorName:
Douglas Gregor1a480c42010-08-27 17:35:51 +00002195 case CodeCompletionContext::CCC_TypeQualifiers:
Douglas Gregor52779fb2010-09-23 23:01:17 +00002196 case CodeCompletionContext::CCC_Other:
Douglas Gregor5c722c702011-02-18 23:30:37 +00002197 case CodeCompletionContext::CCC_OtherWithMacros:
Douglas Gregor3da626b2011-07-07 16:03:39 +00002198 case CodeCompletionContext::CCC_ObjCInstanceMessage:
2199 case CodeCompletionContext::CCC_ObjCClassMessage:
2200 case CodeCompletionContext::CCC_ObjCCategoryName:
Douglas Gregor721f3592010-08-25 18:41:16 +00002201 // We're looking for nothing, or we're looking for names that cannot
2202 // be hidden.
Douglas Gregor5f808c22010-08-16 21:18:39 +00002203 return;
2204 }
2205
John McCall0a2c5e22010-08-25 06:19:51 +00002206 typedef CodeCompletionResult Result;
Douglas Gregor5f808c22010-08-16 21:18:39 +00002207 for (unsigned I = 0; I != NumResults; ++I) {
2208 if (Results[I].Kind != Result::RK_Declaration)
2209 continue;
2210
2211 unsigned IDNS
2212 = Results[I].Declaration->getUnderlyingDecl()->getIdentifierNamespace();
2213
2214 bool Hiding = false;
2215 if (OnlyTagNames)
2216 Hiding = (IDNS & Decl::IDNS_Tag);
2217 else {
2218 unsigned HiddenIDNS = (Decl::IDNS_Type | Decl::IDNS_Member |
Douglas Gregora5fb7c32010-08-16 23:05:20 +00002219 Decl::IDNS_Namespace | Decl::IDNS_Ordinary |
2220 Decl::IDNS_NonMemberOperator);
David Blaikie4e4d0842012-03-11 07:00:24 +00002221 if (Ctx.getLangOpts().CPlusPlus)
Douglas Gregor5f808c22010-08-16 21:18:39 +00002222 HiddenIDNS |= Decl::IDNS_Tag;
2223 Hiding = (IDNS & HiddenIDNS);
2224 }
2225
2226 if (!Hiding)
2227 continue;
2228
2229 DeclarationName Name = Results[I].Declaration->getDeclName();
2230 if (IdentifierInfo *Identifier = Name.getAsIdentifierInfo())
2231 HiddenNames.insert(Identifier->getName());
2232 else
2233 HiddenNames.insert(Name.getAsString());
2234 }
2235}
2236
2237
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002238void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &S,
2239 CodeCompletionContext Context,
John McCall0a2c5e22010-08-25 06:19:51 +00002240 CodeCompletionResult *Results,
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002241 unsigned NumResults) {
2242 // Merge the results we were given with the results we cached.
2243 bool AddedResult = false;
Richard Smith026b3582012-08-14 03:13:00 +00002244 uint64_t InContexts =
2245 Context.getKind() == CodeCompletionContext::CCC_Recovery
2246 ? NormalContexts : (1LL << Context.getKind());
Douglas Gregor5f808c22010-08-16 21:18:39 +00002247 // Contains the set of names that are hidden by "local" completion results.
Ted Kremenekc198f612010-11-07 06:11:36 +00002248 llvm::StringSet<llvm::BumpPtrAllocator> HiddenNames;
John McCall0a2c5e22010-08-25 06:19:51 +00002249 typedef CodeCompletionResult Result;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002250 SmallVector<Result, 8> AllResults;
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002251 for (ASTUnit::cached_completion_iterator
Douglas Gregor5535d572010-08-16 21:23:13 +00002252 C = AST.cached_completion_begin(),
2253 CEnd = AST.cached_completion_end();
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002254 C != CEnd; ++C) {
2255 // If the context we are in matches any of the contexts we are
2256 // interested in, we'll add this result.
2257 if ((C->ShowInContexts & InContexts) == 0)
2258 continue;
2259
2260 // If we haven't added any results previously, do so now.
2261 if (!AddedResult) {
Douglas Gregor5f808c22010-08-16 21:18:39 +00002262 CalculateHiddenNames(Context, Results, NumResults, S.Context,
2263 HiddenNames);
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002264 AllResults.insert(AllResults.end(), Results, Results + NumResults);
2265 AddedResult = true;
2266 }
2267
Douglas Gregor5f808c22010-08-16 21:18:39 +00002268 // Determine whether this global completion result is hidden by a local
2269 // completion result. If so, skip it.
2270 if (C->Kind != CXCursor_MacroDefinition &&
2271 HiddenNames.count(C->Completion->getTypedText()))
2272 continue;
2273
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002274 // Adjust priority based on similar type classes.
2275 unsigned Priority = C->Priority;
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002276 CodeCompletionString *Completion = C->Completion;
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002277 if (!Context.getPreferredType().isNull()) {
2278 if (C->Kind == CXCursor_MacroDefinition) {
2279 Priority = getMacroUsagePriority(C->Completion->getTypedText(),
David Blaikie4e4d0842012-03-11 07:00:24 +00002280 S.getLangOpts(),
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002281 Context.getPreferredType()->isAnyPointerType());
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002282 } else if (C->Type) {
2283 CanQualType Expected
Douglas Gregor5535d572010-08-16 21:23:13 +00002284 = S.Context.getCanonicalType(
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002285 Context.getPreferredType().getUnqualifiedType());
2286 SimplifiedTypeClass ExpectedSTC = getSimplifiedTypeClass(Expected);
2287 if (ExpectedSTC == C->TypeClass) {
2288 // We know this type is similar; check for an exact match.
2289 llvm::StringMap<unsigned> &CachedCompletionTypes
Douglas Gregor5535d572010-08-16 21:23:13 +00002290 = AST.getCachedCompletionTypes();
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002291 llvm::StringMap<unsigned>::iterator Pos
Douglas Gregor5535d572010-08-16 21:23:13 +00002292 = CachedCompletionTypes.find(QualType(Expected).getAsString());
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002293 if (Pos != CachedCompletionTypes.end() && Pos->second == C->Type)
2294 Priority /= CCF_ExactTypeMatch;
2295 else
2296 Priority /= CCF_SimilarTypeMatch;
2297 }
2298 }
2299 }
2300
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002301 // Adjust the completion string, if required.
2302 if (C->Kind == CXCursor_MacroDefinition &&
2303 Context.getKind() == CodeCompletionContext::CCC_MacroNameUse) {
2304 // Create a new code-completion string that just contains the
2305 // macro name, without its arguments.
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00002306 CodeCompletionBuilder Builder(getAllocator(), getCodeCompletionTUInfo(),
2307 CCP_CodePattern, C->Availability);
Douglas Gregor218937c2011-02-01 19:23:04 +00002308 Builder.AddTypedTextChunk(C->Completion->getTypedText());
Douglas Gregor4125c372010-08-25 18:03:13 +00002309 Priority = CCP_CodePattern;
Douglas Gregor218937c2011-02-01 19:23:04 +00002310 Completion = Builder.TakeString();
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002311 }
2312
Argyrios Kyrtzidisc04bb922012-09-27 00:24:09 +00002313 AllResults.push_back(Result(Completion, Priority, C->Kind,
Douglas Gregor58ddb602010-08-23 23:00:57 +00002314 C->Availability));
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002315 }
2316
2317 // If we did not add any cached completion results, just forward the
2318 // results we were given to the next consumer.
2319 if (!AddedResult) {
2320 Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
2321 return;
2322 }
Douglas Gregor1e5e6682010-08-26 13:48:20 +00002323
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002324 Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
2325 AllResults.size());
2326}
2327
2328
2329
Chris Lattner5f9e2722011-07-23 10:55:15 +00002330void ASTUnit::CodeComplete(StringRef File, unsigned Line, unsigned Column,
Stephen Hines651f13c2014-04-23 16:59:28 -07002331 ArrayRef<RemappedFile> RemappedFiles,
Douglas Gregorcee235c2010-08-05 09:09:23 +00002332 bool IncludeMacros,
2333 bool IncludeCodePatterns,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002334 bool IncludeBriefComments,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002335 CodeCompleteConsumer &Consumer,
David Blaikied6471f72011-09-25 23:23:43 +00002336 DiagnosticsEngine &Diag, LangOptions &LangOpts,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002337 SourceManager &SourceMgr, FileManager &FileMgr,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002338 SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
2339 SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers) {
Ted Kremenek4f327862011-03-21 18:40:17 +00002340 if (!Invocation)
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002341 return;
2342
Douglas Gregor213f18b2010-10-28 15:44:59 +00002343 SimpleTimer CompletionTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00002344 CompletionTimer.setOutput("Code completion @ " + File + ":" +
Chris Lattner5f9e2722011-07-23 10:55:15 +00002345 Twine(Line) + ":" + Twine(Column));
Douglas Gregordf95a132010-08-09 20:45:32 +00002346
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00002347 IntrusiveRefCntPtr<CompilerInvocation>
Ted Kremenek4f327862011-03-21 18:40:17 +00002348 CCInvocation(new CompilerInvocation(*Invocation));
2349
2350 FrontendOptions &FrontendOpts = CCInvocation->getFrontendOpts();
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002351 CodeCompleteOptions &CodeCompleteOpts = FrontendOpts.CodeCompleteOpts;
Ted Kremenek4f327862011-03-21 18:40:17 +00002352 PreprocessorOptions &PreprocessorOpts = CCInvocation->getPreprocessorOpts();
Douglas Gregorcee235c2010-08-05 09:09:23 +00002353
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002354 CodeCompleteOpts.IncludeMacros = IncludeMacros &&
2355 CachedCompletionResults.empty();
2356 CodeCompleteOpts.IncludeCodePatterns = IncludeCodePatterns;
2357 CodeCompleteOpts.IncludeGlobals = CachedCompletionResults.empty();
2358 CodeCompleteOpts.IncludeBriefComments = IncludeBriefComments;
2359
2360 assert(IncludeBriefComments == this->IncludeBriefCommentsInCodeCompletion);
2361
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002362 FrontendOpts.CodeCompletionAt.FileName = File;
2363 FrontendOpts.CodeCompletionAt.Line = Line;
2364 FrontendOpts.CodeCompletionAt.Column = Column;
2365
2366 // Set the language options appropriately.
Ted Kremenekd3b74d92011-11-17 23:01:24 +00002367 LangOpts = *CCInvocation->getLangOpts();
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002368
Stephen Hines651f13c2014-04-23 16:59:28 -07002369 std::unique_ptr<CompilerInstance> Clang(new CompilerInstance());
Ted Kremenek03201fb2011-03-21 18:40:07 +00002370
2371 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00002372 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
2373 CICleanup(Clang.get());
Ted Kremenek03201fb2011-03-21 18:40:07 +00002374
Ted Kremenek4f327862011-03-21 18:40:17 +00002375 Clang->setInvocation(&*CCInvocation);
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00002376 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002377
2378 // Set up diagnostics, capturing any diagnostics produced.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002379 Clang->setDiagnostics(&Diag);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002380 CaptureDroppedDiagnostics Capture(true,
Ted Kremenek03201fb2011-03-21 18:40:07 +00002381 Clang->getDiagnostics(),
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002382 StoredDiagnostics);
Manuel Klimekf0c06a32013-07-18 14:23:12 +00002383 ProcessWarningOptions(Diag, CCInvocation->getDiagnosticOpts());
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002384
2385 // Create the target instance.
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002386 Clang->setTarget(TargetInfo::CreateTargetInfo(
2387 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
Ted Kremenek03201fb2011-03-21 18:40:07 +00002388 if (!Clang->hasTarget()) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002389 Clang->setInvocation(nullptr);
Douglas Gregorbdbb0042010-08-18 22:29:43 +00002390 return;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002391 }
2392
2393 // Inform the target of the language options.
2394 //
2395 // FIXME: We shouldn't need to do this, the target should be immutable once
2396 // created. This complexity should be lifted elsewhere.
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002397 Clang->getTarget().adjust(Clang->getLangOpts());
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002398
Ted Kremenek03201fb2011-03-21 18:40:07 +00002399 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002400 "Invocation must have exactly one source file!");
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00002401 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002402 "FIXME: AST inputs not yet supported here!");
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00002403 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002404 "IR inputs not support here!");
2405
2406
2407 // Use the source and file managers that we were given.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002408 Clang->setFileManager(&FileMgr);
2409 Clang->setSourceManager(&SourceMgr);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002410
2411 // Remap files.
2412 PreprocessorOpts.clearRemappedFiles();
Douglas Gregorb75d3df2010-08-04 17:07:00 +00002413 PreprocessorOpts.RetainRemappedFileBuffers = true;
Stephen Hines651f13c2014-04-23 16:59:28 -07002414 for (unsigned I = 0, N = RemappedFiles.size(); I != N; ++I) {
2415 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first,
2416 RemappedFiles[I].second);
2417 OwnedBuffers.push_back(RemappedFiles[I].second);
Douglas Gregor2283d792010-08-20 00:59:43 +00002418 }
Stephen Hines651f13c2014-04-23 16:59:28 -07002419
Douglas Gregor87c08a52010-08-13 22:48:40 +00002420 // Use the code completion consumer we were given, but adding any cached
2421 // code-completion results.
Douglas Gregor7f946ad2010-11-29 16:13:56 +00002422 AugmentedCodeCompleteConsumer *AugmentedConsumer
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002423 = new AugmentedCodeCompleteConsumer(*this, Consumer, CodeCompleteOpts);
Ted Kremenek03201fb2011-03-21 18:40:07 +00002424 Clang->setCodeCompletionConsumer(AugmentedConsumer);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002425
Douglas Gregordf95a132010-08-09 20:45:32 +00002426 // If we have a precompiled preamble, try to use it. We only allow
2427 // the use of the precompiled preamble if we're if the completion
2428 // point is within the main file, after the end of the precompiled
2429 // preamble.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002430 llvm::MemoryBuffer *OverrideMainBuffer = nullptr;
Ted Kremenek1872b312011-10-27 17:55:18 +00002431 if (!getPreambleFile(this).empty()) {
Rafael Espindola105b2072013-06-18 19:40:07 +00002432 std::string CompleteFilePath(File);
Rafael Espindola44888352013-07-29 21:26:52 +00002433 llvm::sys::fs::UniqueID CompleteFileID;
Rafael Espindola105b2072013-06-18 19:40:07 +00002434
Rafael Espindolada4cb0c2013-06-20 15:12:38 +00002435 if (!llvm::sys::fs::getUniqueID(CompleteFilePath, CompleteFileID)) {
Rafael Espindola105b2072013-06-18 19:40:07 +00002436 std::string MainPath(OriginalSourceFile);
Rafael Espindola44888352013-07-29 21:26:52 +00002437 llvm::sys::fs::UniqueID MainID;
Rafael Espindolada4cb0c2013-06-20 15:12:38 +00002438 if (!llvm::sys::fs::getUniqueID(MainPath, MainID)) {
Rafael Espindola105b2072013-06-18 19:40:07 +00002439 if (CompleteFileID == MainID && Line > 1)
Douglas Gregor2283d792010-08-20 00:59:43 +00002440 OverrideMainBuffer
Ted Kremenek4f327862011-03-21 18:40:17 +00002441 = getMainBufferWithPrecompiledPreamble(*CCInvocation, false,
Douglas Gregorc9c29a82010-08-25 18:04:15 +00002442 Line - 1);
Rafael Espindola105b2072013-06-18 19:40:07 +00002443 }
2444 }
Douglas Gregordf95a132010-08-09 20:45:32 +00002445 }
2446
2447 // If the main file has been overridden due to the use of a preamble,
2448 // make that override happen and introduce the preamble.
2449 if (OverrideMainBuffer) {
2450 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
2451 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
2452 PreprocessorOpts.PrecompiledPreambleBytes.second
2453 = PreambleEndsAtStartOfLine;
Ted Kremenek1872b312011-10-27 17:55:18 +00002454 PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
Douglas Gregordf95a132010-08-09 20:45:32 +00002455 PreprocessorOpts.DisablePCHValidation = true;
2456
Douglas Gregor2283d792010-08-20 00:59:43 +00002457 OwnedBuffers.push_back(OverrideMainBuffer);
Douglas Gregorf128fed2010-08-20 00:02:33 +00002458 } else {
2459 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
2460 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregordf95a132010-08-09 20:45:32 +00002461 }
2462
Argyrios Kyrtzidise50904f2012-11-02 22:18:44 +00002463 // Disable the preprocessing record if modules are not enabled.
2464 if (!Clang->getLangOpts().Modules)
2465 PreprocessorOpts.DetailedRecord = false;
Stephen Hines651f13c2014-04-23 16:59:28 -07002466
2467 std::unique_ptr<SyntaxOnlyAction> Act;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002468 Act.reset(new SyntaxOnlyAction);
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00002469 if (Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002470 Act->Execute();
2471 Act->EndSourceFile();
2472 }
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002473}
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002474
Argyrios Kyrtzidise6d22022012-09-26 16:39:46 +00002475bool ASTUnit::Save(StringRef File) {
Argyrios Kyrtzidis3b7deda2013-05-24 05:44:08 +00002476 if (HadModuleLoaderFatalFailure)
2477 return true;
2478
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002479 // Write to a temporary file and later rename it to the actual file, to avoid
2480 // possible race conditions.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002481 SmallString<128> TempPath;
Argyrios Kyrtzidis7e909852011-07-28 00:45:10 +00002482 TempPath = File;
2483 TempPath += "-%%%%%%%%";
2484 int fd;
Rafael Espindola70e7aec2013-07-05 21:13:58 +00002485 if (llvm::sys::fs::createUniqueFile(TempPath.str(), fd, TempPath))
Argyrios Kyrtzidise6d22022012-09-26 16:39:46 +00002486 return true;
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002487
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002488 // FIXME: Can we somehow regenerate the stat cache here, or do we need to
2489 // unconditionally create a stat cache when we parse the file?
Argyrios Kyrtzidis7e909852011-07-28 00:45:10 +00002490 llvm::raw_fd_ostream Out(fd, /*shouldClose=*/true);
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00002491
2492 serialize(Out);
2493 Out.close();
Argyrios Kyrtzidis4bd26542012-03-13 02:17:06 +00002494 if (Out.has_error()) {
2495 Out.clear_error();
Argyrios Kyrtzidise6d22022012-09-26 16:39:46 +00002496 return true;
Argyrios Kyrtzidis4bd26542012-03-13 02:17:06 +00002497 }
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002498
Rafael Espindola8d2a7012011-12-25 01:18:52 +00002499 if (llvm::sys::fs::rename(TempPath.str(), File)) {
Stephen Hines651f13c2014-04-23 16:59:28 -07002500 llvm::sys::fs::remove(TempPath.str());
Argyrios Kyrtzidise6d22022012-09-26 16:39:46 +00002501 return true;
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002502 }
2503
Argyrios Kyrtzidise6d22022012-09-26 16:39:46 +00002504 return false;
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00002505}
2506
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +00002507static bool serializeUnit(ASTWriter &Writer,
2508 SmallVectorImpl<char> &Buffer,
2509 Sema &S,
2510 bool hasErrors,
2511 raw_ostream &OS) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002512 Writer.WriteAST(S, std::string(), nullptr, "", hasErrors);
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +00002513
2514 // Write the generated bitstream to "Out".
2515 if (!Buffer.empty())
2516 OS.write(Buffer.data(), Buffer.size());
2517
2518 return false;
2519}
2520
Chris Lattner5f9e2722011-07-23 10:55:15 +00002521bool ASTUnit::serialize(raw_ostream &OS) {
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +00002522 bool hasErrors = getDiagnostics().hasErrorOccurred();
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00002523
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +00002524 if (WriterData)
2525 return serializeUnit(WriterData->Writer, WriterData->Buffer,
2526 getSema(), hasErrors, OS);
2527
Daniel Dunbar8d6ff022012-02-29 20:31:23 +00002528 SmallString<128> Buffer;
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002529 llvm::BitstreamWriter Stream(Buffer);
Sebastian Redla4232eb2010-08-18 23:56:21 +00002530 ASTWriter Writer(Stream);
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +00002531 return serializeUnit(Writer, Buffer, getSema(), hasErrors, OS);
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002532}
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002533
2534typedef ContinuousRangeMap<unsigned, int, 2> SLocRemap;
2535
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002536void ASTUnit::TranslateStoredDiagnostics(
Stephen Hines651f13c2014-04-23 16:59:28 -07002537 FileManager &FileMgr,
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002538 SourceManager &SrcMgr,
Stephen Hines651f13c2014-04-23 16:59:28 -07002539 const SmallVectorImpl<StandaloneDiagnostic> &Diags,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002540 SmallVectorImpl<StoredDiagnostic> &Out) {
Stephen Hines651f13c2014-04-23 16:59:28 -07002541 // Map the standalone diagnostic into the new source manager. We also need to
2542 // remap all the locations to the new view. This includes the diag location,
2543 // any associated source ranges, and the source ranges of associated fix-its.
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002544 // FIXME: There should be a cleaner way to do this.
2545
Chris Lattner5f9e2722011-07-23 10:55:15 +00002546 SmallVector<StoredDiagnostic, 4> Result;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002547 Result.reserve(Diags.size());
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002548 for (unsigned I = 0, N = Diags.size(); I != N; ++I) {
2549 // Rebuild the StoredDiagnostic.
Stephen Hines651f13c2014-04-23 16:59:28 -07002550 const StandaloneDiagnostic &SD = Diags[I];
2551 if (SD.Filename.empty())
2552 continue;
2553 const FileEntry *FE = FileMgr.getFile(SD.Filename);
2554 if (!FE)
2555 continue;
2556 FileID FID = SrcMgr.translateFile(FE);
2557 SourceLocation FileLoc = SrcMgr.getLocForStartOfFile(FID);
2558 if (FileLoc.isInvalid())
2559 continue;
2560 SourceLocation L = FileLoc.getLocWithOffset(SD.LocOffset);
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002561 FullSourceLoc Loc(L, SrcMgr);
2562
Chris Lattner5f9e2722011-07-23 10:55:15 +00002563 SmallVector<CharSourceRange, 4> Ranges;
Stephen Hines651f13c2014-04-23 16:59:28 -07002564 Ranges.reserve(SD.Ranges.size());
2565 for (std::vector<std::pair<unsigned, unsigned> >::const_iterator
2566 I = SD.Ranges.begin(), E = SD.Ranges.end(); I != E; ++I) {
2567 SourceLocation BL = FileLoc.getLocWithOffset((*I).first);
2568 SourceLocation EL = FileLoc.getLocWithOffset((*I).second);
2569 Ranges.push_back(CharSourceRange::getCharRange(BL, EL));
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002570 }
2571
Chris Lattner5f9e2722011-07-23 10:55:15 +00002572 SmallVector<FixItHint, 2> FixIts;
Stephen Hines651f13c2014-04-23 16:59:28 -07002573 FixIts.reserve(SD.FixIts.size());
2574 for (std::vector<StandaloneFixIt>::const_iterator
2575 I = SD.FixIts.begin(), E = SD.FixIts.end();
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002576 I != E; ++I) {
2577 FixIts.push_back(FixItHint());
2578 FixItHint &FH = FixIts.back();
2579 FH.CodeToInsert = I->CodeToInsert;
Stephen Hines651f13c2014-04-23 16:59:28 -07002580 SourceLocation BL = FileLoc.getLocWithOffset(I->RemoveRange.first);
2581 SourceLocation EL = FileLoc.getLocWithOffset(I->RemoveRange.second);
2582 FH.RemoveRange = CharSourceRange::getCharRange(BL, EL);
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002583 }
2584
Stephen Hines651f13c2014-04-23 16:59:28 -07002585 Result.push_back(StoredDiagnostic(SD.Level, SD.ID,
2586 SD.Message, Loc, Ranges, FixIts));
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002587 }
2588 Result.swap(Out);
2589}
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002590
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +00002591void ASTUnit::addFileLevelDecl(Decl *D) {
2592 assert(D);
Douglas Gregor66e87002011-11-07 18:53:57 +00002593
2594 // We only care about local declarations.
2595 if (D->isFromASTFile())
2596 return;
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +00002597
2598 SourceManager &SM = *SourceMgr;
2599 SourceLocation Loc = D->getLocation();
2600 if (Loc.isInvalid() || !SM.isLocalSourceLocation(Loc))
2601 return;
2602
2603 // We only keep track of the file-level declarations of each file.
2604 if (!D->getLexicalDeclContext()->isFileContext())
2605 return;
2606
2607 SourceLocation FileLoc = SM.getFileLoc(Loc);
2608 assert(SM.isLocalSourceLocation(FileLoc));
2609 FileID FID;
2610 unsigned Offset;
Stephen Hines651f13c2014-04-23 16:59:28 -07002611 std::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc);
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +00002612 if (FID.isInvalid())
2613 return;
2614
2615 LocDeclsTy *&Decls = FileDecls[FID];
2616 if (!Decls)
2617 Decls = new LocDeclsTy();
2618
2619 std::pair<unsigned, Decl *> LocDecl(Offset, D);
2620
2621 if (Decls->empty() || Decls->back().first <= Offset) {
2622 Decls->push_back(LocDecl);
2623 return;
2624 }
2625
Benjamin Kramer809d2542013-08-24 13:22:59 +00002626 LocDeclsTy::iterator I = std::upper_bound(Decls->begin(), Decls->end(),
2627 LocDecl, llvm::less_first());
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +00002628
2629 Decls->insert(I, LocDecl);
2630}
2631
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +00002632void ASTUnit::findFileRegionDecls(FileID File, unsigned Offset, unsigned Length,
2633 SmallVectorImpl<Decl *> &Decls) {
2634 if (File.isInvalid())
2635 return;
2636
2637 if (SourceMgr->isLoadedFileID(File)) {
2638 assert(Ctx->getExternalSource() && "No external source!");
2639 return Ctx->getExternalSource()->FindFileRegionDecls(File, Offset, Length,
2640 Decls);
2641 }
2642
2643 FileDeclsTy::iterator I = FileDecls.find(File);
2644 if (I == FileDecls.end())
2645 return;
2646
2647 LocDeclsTy &LocDecls = *I->second;
2648 if (LocDecls.empty())
2649 return;
2650
Benjamin Kramera9bdbce2013-08-24 13:12:34 +00002651 LocDeclsTy::iterator BeginIt =
2652 std::lower_bound(LocDecls.begin(), LocDecls.end(),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002653 std::make_pair(Offset, (Decl *)nullptr),
2654 llvm::less_first());
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +00002655 if (BeginIt != LocDecls.begin())
2656 --BeginIt;
2657
Argyrios Kyrtzidisc14a03d2011-11-23 20:27:36 +00002658 // If we are pointing at a top-level decl inside an objc container, we need
2659 // to backtrack until we find it otherwise we will fail to report that the
2660 // region overlaps with an objc container.
2661 while (BeginIt != LocDecls.begin() &&
2662 BeginIt->second->isTopLevelDeclInObjCContainer())
2663 --BeginIt;
2664
Benjamin Kramera9bdbce2013-08-24 13:12:34 +00002665 LocDeclsTy::iterator EndIt = std::upper_bound(
2666 LocDecls.begin(), LocDecls.end(),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002667 std::make_pair(Offset + Length, (Decl *)nullptr), llvm::less_first());
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +00002668 if (EndIt != LocDecls.end())
2669 ++EndIt;
2670
2671 for (LocDeclsTy::iterator DIt = BeginIt; DIt != EndIt; ++DIt)
2672 Decls.push_back(DIt->second);
2673}
2674
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002675SourceLocation ASTUnit::getLocation(const FileEntry *File,
2676 unsigned Line, unsigned Col) const {
2677 const SourceManager &SM = getSourceManager();
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00002678 SourceLocation Loc = SM.translateFileLineCol(File, Line, Col);
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002679 return SM.getMacroArgExpandedLocation(Loc);
2680}
2681
2682SourceLocation ASTUnit::getLocation(const FileEntry *File,
2683 unsigned Offset) const {
2684 const SourceManager &SM = getSourceManager();
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00002685 SourceLocation FileLoc = SM.translateFileLineCol(File, 1, 1);
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002686 return SM.getMacroArgExpandedLocation(FileLoc.getLocWithOffset(Offset));
2687}
2688
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00002689/// \brief If \arg Loc is a loaded location from the preamble, returns
2690/// the corresponding local location of the main file, otherwise it returns
2691/// \arg Loc.
2692SourceLocation ASTUnit::mapLocationFromPreamble(SourceLocation Loc) {
2693 FileID PreambleID;
2694 if (SourceMgr)
2695 PreambleID = SourceMgr->getPreambleFileID();
2696
2697 if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2698 return Loc;
2699
2700 unsigned Offs;
2701 if (SourceMgr->isInFileID(Loc, PreambleID, &Offs) && Offs < Preamble.size()) {
2702 SourceLocation FileLoc
2703 = SourceMgr->getLocForStartOfFile(SourceMgr->getMainFileID());
2704 return FileLoc.getLocWithOffset(Offs);
2705 }
2706
2707 return Loc;
2708}
2709
2710/// \brief If \arg Loc is a local location of the main file but inside the
2711/// preamble chunk, returns the corresponding loaded location from the
2712/// preamble, otherwise it returns \arg Loc.
2713SourceLocation ASTUnit::mapLocationToPreamble(SourceLocation Loc) {
2714 FileID PreambleID;
2715 if (SourceMgr)
2716 PreambleID = SourceMgr->getPreambleFileID();
2717
2718 if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2719 return Loc;
2720
2721 unsigned Offs;
2722 if (SourceMgr->isInFileID(Loc, SourceMgr->getMainFileID(), &Offs) &&
2723 Offs < Preamble.size()) {
2724 SourceLocation FileLoc = SourceMgr->getLocForStartOfFile(PreambleID);
2725 return FileLoc.getLocWithOffset(Offs);
2726 }
2727
2728 return Loc;
2729}
2730
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00002731bool ASTUnit::isInPreambleFileID(SourceLocation Loc) {
2732 FileID FID;
2733 if (SourceMgr)
2734 FID = SourceMgr->getPreambleFileID();
2735
2736 if (Loc.isInvalid() || FID.isInvalid())
2737 return false;
2738
2739 return SourceMgr->isInFileID(Loc, FID);
2740}
2741
2742bool ASTUnit::isInMainFileID(SourceLocation Loc) {
2743 FileID FID;
2744 if (SourceMgr)
2745 FID = SourceMgr->getMainFileID();
2746
2747 if (Loc.isInvalid() || FID.isInvalid())
2748 return false;
2749
2750 return SourceMgr->isInFileID(Loc, FID);
2751}
2752
2753SourceLocation ASTUnit::getEndOfPreambleFileID() {
2754 FileID FID;
2755 if (SourceMgr)
2756 FID = SourceMgr->getPreambleFileID();
2757
2758 if (FID.isInvalid())
2759 return SourceLocation();
2760
2761 return SourceMgr->getLocForEndOfFile(FID);
2762}
2763
2764SourceLocation ASTUnit::getStartOfMainFileID() {
2765 FileID FID;
2766 if (SourceMgr)
2767 FID = SourceMgr->getMainFileID();
2768
2769 if (FID.isInvalid())
2770 return SourceLocation();
2771
2772 return SourceMgr->getLocForStartOfFile(FID);
2773}
2774
Argyrios Kyrtzidis632dcc92012-10-02 16:10:51 +00002775std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
2776ASTUnit::getLocalPreprocessingEntities() const {
2777 if (isMainFileAST()) {
2778 serialization::ModuleFile &
2779 Mod = Reader->getModuleManager().getPrimaryModule();
2780 return Reader->getModulePreprocessedEntities(Mod);
2781 }
2782
2783 if (PreprocessingRecord *PPRec = PP->getPreprocessingRecord())
2784 return std::make_pair(PPRec->local_begin(), PPRec->local_end());
2785
2786 return std::make_pair(PreprocessingRecord::iterator(),
2787 PreprocessingRecord::iterator());
2788}
2789
Argyrios Kyrtzidis95c579c2012-10-03 01:58:28 +00002790bool ASTUnit::visitLocalTopLevelDecls(void *context, DeclVisitorFn Fn) {
Argyrios Kyrtzidis2093e0b2012-10-02 21:09:13 +00002791 if (isMainFileAST()) {
2792 serialization::ModuleFile &
2793 Mod = Reader->getModuleManager().getPrimaryModule();
2794 ASTReader::ModuleDeclIterator MDI, MDE;
Stephen Hines651f13c2014-04-23 16:59:28 -07002795 std::tie(MDI, MDE) = Reader->getModuleFileLevelDecls(Mod);
Argyrios Kyrtzidis2093e0b2012-10-02 21:09:13 +00002796 for (; MDI != MDE; ++MDI) {
2797 if (!Fn(context, *MDI))
2798 return false;
2799 }
2800
2801 return true;
2802 }
2803
2804 for (ASTUnit::top_level_iterator TL = top_level_begin(),
2805 TLEnd = top_level_end();
2806 TL != TLEnd; ++TL) {
2807 if (!Fn(context, *TL))
2808 return false;
2809 }
2810
2811 return true;
2812}
2813
Argyrios Kyrtzidis3da76bf2012-10-03 21:05:51 +00002814namespace {
2815struct PCHLocatorInfo {
2816 serialization::ModuleFile *Mod;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002817 PCHLocatorInfo() : Mod(nullptr) {}
Argyrios Kyrtzidis3da76bf2012-10-03 21:05:51 +00002818};
2819}
2820
2821static bool PCHLocator(serialization::ModuleFile &M, void *UserData) {
2822 PCHLocatorInfo &Info = *static_cast<PCHLocatorInfo*>(UserData);
2823 switch (M.Kind) {
2824 case serialization::MK_Module:
2825 return true; // skip dependencies.
2826 case serialization::MK_PCH:
2827 Info.Mod = &M;
2828 return true; // found it.
2829 case serialization::MK_Preamble:
2830 return false; // look in dependencies.
2831 case serialization::MK_MainFile:
2832 return false; // look in dependencies.
2833 }
2834
2835 return true;
2836}
2837
2838const FileEntry *ASTUnit::getPCHFile() {
2839 if (!Reader)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002840 return nullptr;
Argyrios Kyrtzidis3da76bf2012-10-03 21:05:51 +00002841
2842 PCHLocatorInfo Info;
2843 Reader->getModuleManager().visit(PCHLocator, &Info);
2844 if (Info.Mod)
2845 return Info.Mod->File;
2846
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002847 return nullptr;
Argyrios Kyrtzidis3da76bf2012-10-03 21:05:51 +00002848}
2849
Argyrios Kyrtzidis62288ed2012-10-10 02:12:47 +00002850bool ASTUnit::isModuleFile() {
2851 return isMainFileAST() && !ASTFileLangOpts.CurrentModule.empty();
2852}
2853
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002854void ASTUnit::PreambleData::countLines() const {
2855 NumLines = 0;
2856 if (empty())
2857 return;
2858
2859 for (std::vector<char>::const_iterator
2860 I = Buffer.begin(), E = Buffer.end(); I != E; ++I) {
2861 if (*I == '\n')
2862 ++NumLines;
2863 }
2864 if (Buffer.back() != '\n')
2865 ++NumLines;
2866}
Argyrios Kyrtzidisa696ece2011-10-10 21:57:12 +00002867
2868#ifndef NDEBUG
2869ASTUnit::ConcurrencyState::ConcurrencyState() {
2870 Mutex = new llvm::sys::MutexImpl(/*recursive=*/true);
2871}
2872
2873ASTUnit::ConcurrencyState::~ConcurrencyState() {
2874 delete static_cast<llvm::sys::MutexImpl *>(Mutex);
2875}
2876
2877void ASTUnit::ConcurrencyState::start() {
2878 bool acquired = static_cast<llvm::sys::MutexImpl *>(Mutex)->tryacquire();
2879 assert(acquired && "Concurrent access to ASTUnit!");
2880}
2881
2882void ASTUnit::ConcurrencyState::finish() {
2883 static_cast<llvm::sys::MutexImpl *>(Mutex)->release();
2884}
2885
2886#else // NDEBUG
2887
Stephen Hines651f13c2014-04-23 16:59:28 -07002888ASTUnit::ConcurrencyState::ConcurrencyState() { Mutex = 0; }
Argyrios Kyrtzidisa696ece2011-10-10 21:57:12 +00002889ASTUnit::ConcurrencyState::~ConcurrencyState() {}
2890void ASTUnit::ConcurrencyState::start() {}
2891void ASTUnit::ConcurrencyState::finish() {}
2892
2893#endif