CrossTranslationUnit.cpp revision 1.1 1 1.1 joerg //===--- CrossTranslationUnit.cpp - -----------------------------*- C++ -*-===//
2 1.1 joerg //
3 1.1 joerg // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 1.1 joerg // See https://llvm.org/LICENSE.txt for license information.
5 1.1 joerg // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 1.1 joerg //
7 1.1 joerg //===----------------------------------------------------------------------===//
8 1.1 joerg //
9 1.1 joerg // This file implements the CrossTranslationUnit interface.
10 1.1 joerg //
11 1.1 joerg //===----------------------------------------------------------------------===//
12 1.1 joerg #include "clang/CrossTU/CrossTranslationUnit.h"
13 1.1 joerg #include "clang/AST/ASTImporter.h"
14 1.1 joerg #include "clang/AST/Decl.h"
15 1.1 joerg #include "clang/Basic/TargetInfo.h"
16 1.1 joerg #include "clang/CrossTU/CrossTUDiagnostic.h"
17 1.1 joerg #include "clang/Frontend/ASTUnit.h"
18 1.1 joerg #include "clang/Frontend/CompilerInstance.h"
19 1.1 joerg #include "clang/Frontend/TextDiagnosticPrinter.h"
20 1.1 joerg #include "clang/Index/USRGeneration.h"
21 1.1 joerg #include "llvm/ADT/Triple.h"
22 1.1 joerg #include "llvm/ADT/Statistic.h"
23 1.1 joerg #include "llvm/Support/ErrorHandling.h"
24 1.1 joerg #include "llvm/Support/ManagedStatic.h"
25 1.1 joerg #include "llvm/Support/Path.h"
26 1.1 joerg #include "llvm/Support/raw_ostream.h"
27 1.1 joerg #include <fstream>
28 1.1 joerg #include <sstream>
29 1.1 joerg
30 1.1 joerg namespace clang {
31 1.1 joerg namespace cross_tu {
32 1.1 joerg
33 1.1 joerg namespace {
34 1.1 joerg
35 1.1 joerg #define DEBUG_TYPE "CrossTranslationUnit"
36 1.1 joerg STATISTIC(NumGetCTUCalled, "The # of getCTUDefinition function called");
37 1.1 joerg STATISTIC(
38 1.1 joerg NumNotInOtherTU,
39 1.1 joerg "The # of getCTUDefinition called but the function is not in any other TU");
40 1.1 joerg STATISTIC(NumGetCTUSuccess,
41 1.1 joerg "The # of getCTUDefinition successfully returned the "
42 1.1 joerg "requested function's body");
43 1.1 joerg STATISTIC(NumUnsupportedNodeFound, "The # of imports when the ASTImporter "
44 1.1 joerg "encountered an unsupported AST Node");
45 1.1 joerg STATISTIC(NumNameConflicts, "The # of imports when the ASTImporter "
46 1.1 joerg "encountered an ODR error");
47 1.1 joerg STATISTIC(NumTripleMismatch, "The # of triple mismatches");
48 1.1 joerg STATISTIC(NumLangMismatch, "The # of language mismatches");
49 1.1 joerg STATISTIC(NumLangDialectMismatch, "The # of language dialect mismatches");
50 1.1 joerg STATISTIC(NumASTLoadThresholdReached,
51 1.1 joerg "The # of ASTs not loaded because of threshold");
52 1.1 joerg
53 1.1 joerg // Same as Triple's equality operator, but we check a field only if that is
54 1.1 joerg // known in both instances.
55 1.1 joerg bool hasEqualKnownFields(const llvm::Triple &Lhs, const llvm::Triple &Rhs) {
56 1.1 joerg using llvm::Triple;
57 1.1 joerg if (Lhs.getArch() != Triple::UnknownArch &&
58 1.1 joerg Rhs.getArch() != Triple::UnknownArch && Lhs.getArch() != Rhs.getArch())
59 1.1 joerg return false;
60 1.1 joerg if (Lhs.getSubArch() != Triple::NoSubArch &&
61 1.1 joerg Rhs.getSubArch() != Triple::NoSubArch &&
62 1.1 joerg Lhs.getSubArch() != Rhs.getSubArch())
63 1.1 joerg return false;
64 1.1 joerg if (Lhs.getVendor() != Triple::UnknownVendor &&
65 1.1 joerg Rhs.getVendor() != Triple::UnknownVendor &&
66 1.1 joerg Lhs.getVendor() != Rhs.getVendor())
67 1.1 joerg return false;
68 1.1 joerg if (!Lhs.isOSUnknown() && !Rhs.isOSUnknown() &&
69 1.1 joerg Lhs.getOS() != Rhs.getOS())
70 1.1 joerg return false;
71 1.1 joerg if (Lhs.getEnvironment() != Triple::UnknownEnvironment &&
72 1.1 joerg Rhs.getEnvironment() != Triple::UnknownEnvironment &&
73 1.1 joerg Lhs.getEnvironment() != Rhs.getEnvironment())
74 1.1 joerg return false;
75 1.1 joerg if (Lhs.getObjectFormat() != Triple::UnknownObjectFormat &&
76 1.1 joerg Rhs.getObjectFormat() != Triple::UnknownObjectFormat &&
77 1.1 joerg Lhs.getObjectFormat() != Rhs.getObjectFormat())
78 1.1 joerg return false;
79 1.1 joerg return true;
80 1.1 joerg }
81 1.1 joerg
82 1.1 joerg // FIXME: This class is will be removed after the transition to llvm::Error.
83 1.1 joerg class IndexErrorCategory : public std::error_category {
84 1.1 joerg public:
85 1.1 joerg const char *name() const noexcept override { return "clang.index"; }
86 1.1 joerg
87 1.1 joerg std::string message(int Condition) const override {
88 1.1 joerg switch (static_cast<index_error_code>(Condition)) {
89 1.1 joerg case index_error_code::unspecified:
90 1.1 joerg return "An unknown error has occurred.";
91 1.1 joerg case index_error_code::missing_index_file:
92 1.1 joerg return "The index file is missing.";
93 1.1 joerg case index_error_code::invalid_index_format:
94 1.1 joerg return "Invalid index file format.";
95 1.1 joerg case index_error_code::multiple_definitions:
96 1.1 joerg return "Multiple definitions in the index file.";
97 1.1 joerg case index_error_code::missing_definition:
98 1.1 joerg return "Missing definition from the index file.";
99 1.1 joerg case index_error_code::failed_import:
100 1.1 joerg return "Failed to import the definition.";
101 1.1 joerg case index_error_code::failed_to_get_external_ast:
102 1.1 joerg return "Failed to load external AST source.";
103 1.1 joerg case index_error_code::failed_to_generate_usr:
104 1.1 joerg return "Failed to generate USR.";
105 1.1 joerg case index_error_code::triple_mismatch:
106 1.1 joerg return "Triple mismatch";
107 1.1 joerg case index_error_code::lang_mismatch:
108 1.1 joerg return "Language mismatch";
109 1.1 joerg case index_error_code::lang_dialect_mismatch:
110 1.1 joerg return "Language dialect mismatch";
111 1.1 joerg case index_error_code::load_threshold_reached:
112 1.1 joerg return "Load threshold reached";
113 1.1 joerg }
114 1.1 joerg llvm_unreachable("Unrecognized index_error_code.");
115 1.1 joerg }
116 1.1 joerg };
117 1.1 joerg
118 1.1 joerg static llvm::ManagedStatic<IndexErrorCategory> Category;
119 1.1 joerg } // end anonymous namespace
120 1.1 joerg
121 1.1 joerg char IndexError::ID;
122 1.1 joerg
123 1.1 joerg void IndexError::log(raw_ostream &OS) const {
124 1.1 joerg OS << Category->message(static_cast<int>(Code)) << '\n';
125 1.1 joerg }
126 1.1 joerg
127 1.1 joerg std::error_code IndexError::convertToErrorCode() const {
128 1.1 joerg return std::error_code(static_cast<int>(Code), *Category);
129 1.1 joerg }
130 1.1 joerg
131 1.1 joerg llvm::Expected<llvm::StringMap<std::string>>
132 1.1 joerg parseCrossTUIndex(StringRef IndexPath, StringRef CrossTUDir) {
133 1.1 joerg std::ifstream ExternalMapFile(IndexPath);
134 1.1 joerg if (!ExternalMapFile)
135 1.1 joerg return llvm::make_error<IndexError>(index_error_code::missing_index_file,
136 1.1 joerg IndexPath.str());
137 1.1 joerg
138 1.1 joerg llvm::StringMap<std::string> Result;
139 1.1 joerg std::string Line;
140 1.1 joerg unsigned LineNo = 1;
141 1.1 joerg while (std::getline(ExternalMapFile, Line)) {
142 1.1 joerg const size_t Pos = Line.find(" ");
143 1.1 joerg if (Pos > 0 && Pos != std::string::npos) {
144 1.1 joerg StringRef LineRef{Line};
145 1.1 joerg StringRef LookupName = LineRef.substr(0, Pos);
146 1.1 joerg if (Result.count(LookupName))
147 1.1 joerg return llvm::make_error<IndexError>(
148 1.1 joerg index_error_code::multiple_definitions, IndexPath.str(), LineNo);
149 1.1 joerg StringRef FileName = LineRef.substr(Pos + 1);
150 1.1 joerg SmallString<256> FilePath = CrossTUDir;
151 1.1 joerg llvm::sys::path::append(FilePath, FileName);
152 1.1 joerg Result[LookupName] = FilePath.str().str();
153 1.1 joerg } else
154 1.1 joerg return llvm::make_error<IndexError>(
155 1.1 joerg index_error_code::invalid_index_format, IndexPath.str(), LineNo);
156 1.1 joerg LineNo++;
157 1.1 joerg }
158 1.1 joerg return Result;
159 1.1 joerg }
160 1.1 joerg
161 1.1 joerg std::string
162 1.1 joerg createCrossTUIndexString(const llvm::StringMap<std::string> &Index) {
163 1.1 joerg std::ostringstream Result;
164 1.1 joerg for (const auto &E : Index)
165 1.1 joerg Result << E.getKey().str() << " " << E.getValue() << '\n';
166 1.1 joerg return Result.str();
167 1.1 joerg }
168 1.1 joerg
169 1.1 joerg bool containsConst(const VarDecl *VD, const ASTContext &ACtx) {
170 1.1 joerg CanQualType CT = ACtx.getCanonicalType(VD->getType());
171 1.1 joerg if (!CT.isConstQualified()) {
172 1.1 joerg const RecordType *RTy = CT->getAs<RecordType>();
173 1.1 joerg if (!RTy || !RTy->hasConstFields())
174 1.1 joerg return false;
175 1.1 joerg }
176 1.1 joerg return true;
177 1.1 joerg }
178 1.1 joerg
179 1.1 joerg static bool hasBodyOrInit(const FunctionDecl *D, const FunctionDecl *&DefD) {
180 1.1 joerg return D->hasBody(DefD);
181 1.1 joerg }
182 1.1 joerg static bool hasBodyOrInit(const VarDecl *D, const VarDecl *&DefD) {
183 1.1 joerg return D->getAnyInitializer(DefD);
184 1.1 joerg }
185 1.1 joerg template <typename T> static bool hasBodyOrInit(const T *D) {
186 1.1 joerg const T *Unused;
187 1.1 joerg return hasBodyOrInit(D, Unused);
188 1.1 joerg }
189 1.1 joerg
190 1.1 joerg CrossTranslationUnitContext::CrossTranslationUnitContext(CompilerInstance &CI)
191 1.1 joerg : Context(CI.getASTContext()), ASTStorage(CI) {}
192 1.1 joerg
193 1.1 joerg CrossTranslationUnitContext::~CrossTranslationUnitContext() {}
194 1.1 joerg
195 1.1 joerg llvm::Optional<std::string>
196 1.1 joerg CrossTranslationUnitContext::getLookupName(const NamedDecl *ND) {
197 1.1 joerg SmallString<128> DeclUSR;
198 1.1 joerg bool Ret = index::generateUSRForDecl(ND, DeclUSR);
199 1.1 joerg if (Ret)
200 1.1 joerg return {};
201 1.1 joerg return std::string(DeclUSR.str());
202 1.1 joerg }
203 1.1 joerg
204 1.1 joerg /// Recursively visits the decls of a DeclContext, and returns one with the
205 1.1 joerg /// given USR.
206 1.1 joerg template <typename T>
207 1.1 joerg const T *
208 1.1 joerg CrossTranslationUnitContext::findDefInDeclContext(const DeclContext *DC,
209 1.1 joerg StringRef LookupName) {
210 1.1 joerg assert(DC && "Declaration Context must not be null");
211 1.1 joerg for (const Decl *D : DC->decls()) {
212 1.1 joerg const auto *SubDC = dyn_cast<DeclContext>(D);
213 1.1 joerg if (SubDC)
214 1.1 joerg if (const auto *ND = findDefInDeclContext<T>(SubDC, LookupName))
215 1.1 joerg return ND;
216 1.1 joerg
217 1.1 joerg const auto *ND = dyn_cast<T>(D);
218 1.1 joerg const T *ResultDecl;
219 1.1 joerg if (!ND || !hasBodyOrInit(ND, ResultDecl))
220 1.1 joerg continue;
221 1.1 joerg llvm::Optional<std::string> ResultLookupName = getLookupName(ResultDecl);
222 1.1 joerg if (!ResultLookupName || *ResultLookupName != LookupName)
223 1.1 joerg continue;
224 1.1 joerg return ResultDecl;
225 1.1 joerg }
226 1.1 joerg return nullptr;
227 1.1 joerg }
228 1.1 joerg
229 1.1 joerg template <typename T>
230 1.1 joerg llvm::Expected<const T *> CrossTranslationUnitContext::getCrossTUDefinitionImpl(
231 1.1 joerg const T *D, StringRef CrossTUDir, StringRef IndexName,
232 1.1 joerg bool DisplayCTUProgress) {
233 1.1 joerg assert(D && "D is missing, bad call to this function!");
234 1.1 joerg assert(!hasBodyOrInit(D) &&
235 1.1 joerg "D has a body or init in current translation unit!");
236 1.1 joerg ++NumGetCTUCalled;
237 1.1 joerg const llvm::Optional<std::string> LookupName = getLookupName(D);
238 1.1 joerg if (!LookupName)
239 1.1 joerg return llvm::make_error<IndexError>(
240 1.1 joerg index_error_code::failed_to_generate_usr);
241 1.1 joerg llvm::Expected<ASTUnit *> ASTUnitOrError =
242 1.1 joerg loadExternalAST(*LookupName, CrossTUDir, IndexName, DisplayCTUProgress);
243 1.1 joerg if (!ASTUnitOrError)
244 1.1 joerg return ASTUnitOrError.takeError();
245 1.1 joerg ASTUnit *Unit = *ASTUnitOrError;
246 1.1 joerg assert(&Unit->getFileManager() ==
247 1.1 joerg &Unit->getASTContext().getSourceManager().getFileManager());
248 1.1 joerg
249 1.1 joerg const llvm::Triple &TripleTo = Context.getTargetInfo().getTriple();
250 1.1 joerg const llvm::Triple &TripleFrom =
251 1.1 joerg Unit->getASTContext().getTargetInfo().getTriple();
252 1.1 joerg // The imported AST had been generated for a different target.
253 1.1 joerg // Some parts of the triple in the loaded ASTContext can be unknown while the
254 1.1 joerg // very same parts in the target ASTContext are known. Thus we check for the
255 1.1 joerg // known parts only.
256 1.1 joerg if (!hasEqualKnownFields(TripleTo, TripleFrom)) {
257 1.1 joerg // TODO: Pass the SourceLocation of the CallExpression for more precise
258 1.1 joerg // diagnostics.
259 1.1 joerg ++NumTripleMismatch;
260 1.1 joerg return llvm::make_error<IndexError>(index_error_code::triple_mismatch,
261 1.1 joerg Unit->getMainFileName(), TripleTo.str(),
262 1.1 joerg TripleFrom.str());
263 1.1 joerg }
264 1.1 joerg
265 1.1 joerg const auto &LangTo = Context.getLangOpts();
266 1.1 joerg const auto &LangFrom = Unit->getASTContext().getLangOpts();
267 1.1 joerg
268 1.1 joerg // FIXME: Currenty we do not support CTU across C++ and C and across
269 1.1 joerg // different dialects of C++.
270 1.1 joerg if (LangTo.CPlusPlus != LangFrom.CPlusPlus) {
271 1.1 joerg ++NumLangMismatch;
272 1.1 joerg return llvm::make_error<IndexError>(index_error_code::lang_mismatch);
273 1.1 joerg }
274 1.1 joerg
275 1.1 joerg // If CPP dialects are different then return with error.
276 1.1 joerg //
277 1.1 joerg // Consider this STL code:
278 1.1 joerg // template<typename _Alloc>
279 1.1 joerg // struct __alloc_traits
280 1.1 joerg // #if __cplusplus >= 201103L
281 1.1 joerg // : std::allocator_traits<_Alloc>
282 1.1 joerg // #endif
283 1.1 joerg // { // ...
284 1.1 joerg // };
285 1.1 joerg // This class template would create ODR errors during merging the two units,
286 1.1 joerg // since in one translation unit the class template has a base class, however
287 1.1 joerg // in the other unit it has none.
288 1.1 joerg if (LangTo.CPlusPlus11 != LangFrom.CPlusPlus11 ||
289 1.1 joerg LangTo.CPlusPlus14 != LangFrom.CPlusPlus14 ||
290 1.1 joerg LangTo.CPlusPlus17 != LangFrom.CPlusPlus17 ||
291 1.1 joerg LangTo.CPlusPlus2a != LangFrom.CPlusPlus2a) {
292 1.1 joerg ++NumLangDialectMismatch;
293 1.1 joerg return llvm::make_error<IndexError>(
294 1.1 joerg index_error_code::lang_dialect_mismatch);
295 1.1 joerg }
296 1.1 joerg
297 1.1 joerg TranslationUnitDecl *TU = Unit->getASTContext().getTranslationUnitDecl();
298 1.1 joerg if (const T *ResultDecl = findDefInDeclContext<T>(TU, *LookupName))
299 1.1 joerg return importDefinition(ResultDecl, Unit);
300 1.1 joerg return llvm::make_error<IndexError>(index_error_code::failed_import);
301 1.1 joerg }
302 1.1 joerg
303 1.1 joerg llvm::Expected<const FunctionDecl *>
304 1.1 joerg CrossTranslationUnitContext::getCrossTUDefinition(const FunctionDecl *FD,
305 1.1 joerg StringRef CrossTUDir,
306 1.1 joerg StringRef IndexName,
307 1.1 joerg bool DisplayCTUProgress) {
308 1.1 joerg return getCrossTUDefinitionImpl(FD, CrossTUDir, IndexName,
309 1.1 joerg DisplayCTUProgress);
310 1.1 joerg }
311 1.1 joerg
312 1.1 joerg llvm::Expected<const VarDecl *>
313 1.1 joerg CrossTranslationUnitContext::getCrossTUDefinition(const VarDecl *VD,
314 1.1 joerg StringRef CrossTUDir,
315 1.1 joerg StringRef IndexName,
316 1.1 joerg bool DisplayCTUProgress) {
317 1.1 joerg return getCrossTUDefinitionImpl(VD, CrossTUDir, IndexName,
318 1.1 joerg DisplayCTUProgress);
319 1.1 joerg }
320 1.1 joerg
321 1.1 joerg void CrossTranslationUnitContext::emitCrossTUDiagnostics(const IndexError &IE) {
322 1.1 joerg switch (IE.getCode()) {
323 1.1 joerg case index_error_code::missing_index_file:
324 1.1 joerg Context.getDiagnostics().Report(diag::err_ctu_error_opening)
325 1.1 joerg << IE.getFileName();
326 1.1 joerg break;
327 1.1 joerg case index_error_code::invalid_index_format:
328 1.1 joerg Context.getDiagnostics().Report(diag::err_extdefmap_parsing)
329 1.1 joerg << IE.getFileName() << IE.getLineNum();
330 1.1 joerg break;
331 1.1 joerg case index_error_code::multiple_definitions:
332 1.1 joerg Context.getDiagnostics().Report(diag::err_multiple_def_index)
333 1.1 joerg << IE.getLineNum();
334 1.1 joerg break;
335 1.1 joerg case index_error_code::triple_mismatch:
336 1.1 joerg Context.getDiagnostics().Report(diag::warn_ctu_incompat_triple)
337 1.1 joerg << IE.getFileName() << IE.getTripleToName() << IE.getTripleFromName();
338 1.1 joerg break;
339 1.1 joerg default:
340 1.1 joerg break;
341 1.1 joerg }
342 1.1 joerg }
343 1.1 joerg
344 1.1 joerg CrossTranslationUnitContext::ASTFileLoader::ASTFileLoader(
345 1.1 joerg const CompilerInstance &CI)
346 1.1 joerg : CI(CI) {}
347 1.1 joerg
348 1.1 joerg std::unique_ptr<ASTUnit>
349 1.1 joerg CrossTranslationUnitContext::ASTFileLoader::operator()(StringRef ASTFilePath) {
350 1.1 joerg // Load AST from ast-dump.
351 1.1 joerg IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
352 1.1 joerg TextDiagnosticPrinter *DiagClient =
353 1.1 joerg new TextDiagnosticPrinter(llvm::errs(), &*DiagOpts);
354 1.1 joerg IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
355 1.1 joerg IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
356 1.1 joerg new DiagnosticsEngine(DiagID, &*DiagOpts, DiagClient));
357 1.1 joerg
358 1.1 joerg return ASTUnit::LoadFromASTFile(
359 1.1 joerg ASTFilePath, CI.getPCHContainerOperations()->getRawReader(),
360 1.1 joerg ASTUnit::LoadEverything, Diags, CI.getFileSystemOpts());
361 1.1 joerg }
362 1.1 joerg
363 1.1 joerg CrossTranslationUnitContext::ASTUnitStorage::ASTUnitStorage(
364 1.1 joerg const CompilerInstance &CI)
365 1.1 joerg : FileAccessor(CI), LoadGuard(const_cast<CompilerInstance &>(CI)
366 1.1 joerg .getAnalyzerOpts()
367 1.1 joerg ->CTUImportThreshold) {}
368 1.1 joerg
369 1.1 joerg llvm::Expected<ASTUnit *>
370 1.1 joerg CrossTranslationUnitContext::ASTUnitStorage::getASTUnitForFile(
371 1.1 joerg StringRef FileName, bool DisplayCTUProgress) {
372 1.1 joerg // Try the cache first.
373 1.1 joerg auto ASTCacheEntry = FileASTUnitMap.find(FileName);
374 1.1 joerg if (ASTCacheEntry == FileASTUnitMap.end()) {
375 1.1 joerg
376 1.1 joerg // Do not load if the limit is reached.
377 1.1 joerg if (!LoadGuard) {
378 1.1 joerg ++NumASTLoadThresholdReached;
379 1.1 joerg return llvm::make_error<IndexError>(
380 1.1 joerg index_error_code::load_threshold_reached);
381 1.1 joerg }
382 1.1 joerg
383 1.1 joerg // Load the ASTUnit from the pre-dumped AST file specified by ASTFileName.
384 1.1 joerg std::unique_ptr<ASTUnit> LoadedUnit = FileAccessor(FileName);
385 1.1 joerg
386 1.1 joerg // Need the raw pointer and the unique_ptr as well.
387 1.1 joerg ASTUnit *Unit = LoadedUnit.get();
388 1.1 joerg
389 1.1 joerg // Update the cache.
390 1.1 joerg FileASTUnitMap[FileName] = std::move(LoadedUnit);
391 1.1 joerg
392 1.1 joerg LoadGuard.indicateLoadSuccess();
393 1.1 joerg
394 1.1 joerg if (DisplayCTUProgress)
395 1.1 joerg llvm::errs() << "CTU loaded AST file: " << FileName << "\n";
396 1.1 joerg
397 1.1 joerg return Unit;
398 1.1 joerg
399 1.1 joerg } else {
400 1.1 joerg // Found in the cache.
401 1.1 joerg return ASTCacheEntry->second.get();
402 1.1 joerg }
403 1.1 joerg }
404 1.1 joerg
405 1.1 joerg llvm::Expected<ASTUnit *>
406 1.1 joerg CrossTranslationUnitContext::ASTUnitStorage::getASTUnitForFunction(
407 1.1 joerg StringRef FunctionName, StringRef CrossTUDir, StringRef IndexName,
408 1.1 joerg bool DisplayCTUProgress) {
409 1.1 joerg // Try the cache first.
410 1.1 joerg auto ASTCacheEntry = NameASTUnitMap.find(FunctionName);
411 1.1 joerg if (ASTCacheEntry == NameASTUnitMap.end()) {
412 1.1 joerg // Load the ASTUnit from the pre-dumped AST file specified by ASTFileName.
413 1.1 joerg
414 1.1 joerg // Ensure that the Index is loaded, as we need to search in it.
415 1.1 joerg if (llvm::Error IndexLoadError =
416 1.1 joerg ensureCTUIndexLoaded(CrossTUDir, IndexName))
417 1.1 joerg return std::move(IndexLoadError);
418 1.1 joerg
419 1.1 joerg // Check if there is and entry in the index for the function.
420 1.1 joerg if (!NameFileMap.count(FunctionName)) {
421 1.1 joerg ++NumNotInOtherTU;
422 1.1 joerg return llvm::make_error<IndexError>(index_error_code::missing_definition);
423 1.1 joerg }
424 1.1 joerg
425 1.1 joerg // Search in the index for the filename where the definition of FuncitonName
426 1.1 joerg // resides.
427 1.1 joerg if (llvm::Expected<ASTUnit *> FoundForFile =
428 1.1 joerg getASTUnitForFile(NameFileMap[FunctionName], DisplayCTUProgress)) {
429 1.1 joerg
430 1.1 joerg // Update the cache.
431 1.1 joerg NameASTUnitMap[FunctionName] = *FoundForFile;
432 1.1 joerg return *FoundForFile;
433 1.1 joerg
434 1.1 joerg } else {
435 1.1 joerg return FoundForFile.takeError();
436 1.1 joerg }
437 1.1 joerg } else {
438 1.1 joerg // Found in the cache.
439 1.1 joerg return ASTCacheEntry->second;
440 1.1 joerg }
441 1.1 joerg }
442 1.1 joerg
443 1.1 joerg llvm::Expected<std::string>
444 1.1 joerg CrossTranslationUnitContext::ASTUnitStorage::getFileForFunction(
445 1.1 joerg StringRef FunctionName, StringRef CrossTUDir, StringRef IndexName) {
446 1.1 joerg if (llvm::Error IndexLoadError = ensureCTUIndexLoaded(CrossTUDir, IndexName))
447 1.1 joerg return std::move(IndexLoadError);
448 1.1 joerg return NameFileMap[FunctionName];
449 1.1 joerg }
450 1.1 joerg
451 1.1 joerg llvm::Error CrossTranslationUnitContext::ASTUnitStorage::ensureCTUIndexLoaded(
452 1.1 joerg StringRef CrossTUDir, StringRef IndexName) {
453 1.1 joerg // Dont initialize if the map is filled.
454 1.1 joerg if (!NameFileMap.empty())
455 1.1 joerg return llvm::Error::success();
456 1.1 joerg
457 1.1 joerg // Get the absolute path to the index file.
458 1.1 joerg SmallString<256> IndexFile = CrossTUDir;
459 1.1 joerg if (llvm::sys::path::is_absolute(IndexName))
460 1.1 joerg IndexFile = IndexName;
461 1.1 joerg else
462 1.1 joerg llvm::sys::path::append(IndexFile, IndexName);
463 1.1 joerg
464 1.1 joerg if (auto IndexMapping = parseCrossTUIndex(IndexFile, CrossTUDir)) {
465 1.1 joerg // Initialize member map.
466 1.1 joerg NameFileMap = *IndexMapping;
467 1.1 joerg return llvm::Error::success();
468 1.1 joerg } else {
469 1.1 joerg // Error while parsing CrossTU index file.
470 1.1 joerg return IndexMapping.takeError();
471 1.1 joerg };
472 1.1 joerg }
473 1.1 joerg
474 1.1 joerg llvm::Expected<ASTUnit *> CrossTranslationUnitContext::loadExternalAST(
475 1.1 joerg StringRef LookupName, StringRef CrossTUDir, StringRef IndexName,
476 1.1 joerg bool DisplayCTUProgress) {
477 1.1 joerg // FIXME: The current implementation only supports loading decls with
478 1.1 joerg // a lookup name from a single translation unit. If multiple
479 1.1 joerg // translation units contains decls with the same lookup name an
480 1.1 joerg // error will be returned.
481 1.1 joerg
482 1.1 joerg // Try to get the value from the heavily cached storage.
483 1.1 joerg llvm::Expected<ASTUnit *> Unit = ASTStorage.getASTUnitForFunction(
484 1.1 joerg LookupName, CrossTUDir, IndexName, DisplayCTUProgress);
485 1.1 joerg
486 1.1 joerg if (!Unit)
487 1.1 joerg return Unit.takeError();
488 1.1 joerg
489 1.1 joerg // Check whether the backing pointer of the Expected is a nullptr.
490 1.1 joerg if (!*Unit)
491 1.1 joerg return llvm::make_error<IndexError>(
492 1.1 joerg index_error_code::failed_to_get_external_ast);
493 1.1 joerg
494 1.1 joerg return Unit;
495 1.1 joerg }
496 1.1 joerg
497 1.1 joerg template <typename T>
498 1.1 joerg llvm::Expected<const T *>
499 1.1 joerg CrossTranslationUnitContext::importDefinitionImpl(const T *D, ASTUnit *Unit) {
500 1.1 joerg assert(hasBodyOrInit(D) && "Decls to be imported should have body or init.");
501 1.1 joerg
502 1.1 joerg assert(&D->getASTContext() == &Unit->getASTContext() &&
503 1.1 joerg "ASTContext of Decl and the unit should match.");
504 1.1 joerg ASTImporter &Importer = getOrCreateASTImporter(Unit);
505 1.1 joerg
506 1.1 joerg auto ToDeclOrError = Importer.Import(D);
507 1.1 joerg if (!ToDeclOrError) {
508 1.1 joerg handleAllErrors(ToDeclOrError.takeError(),
509 1.1 joerg [&](const ImportError &IE) {
510 1.1 joerg switch (IE.Error) {
511 1.1 joerg case ImportError::NameConflict:
512 1.1 joerg ++NumNameConflicts;
513 1.1 joerg break;
514 1.1 joerg case ImportError::UnsupportedConstruct:
515 1.1 joerg ++NumUnsupportedNodeFound;
516 1.1 joerg break;
517 1.1 joerg case ImportError::Unknown:
518 1.1 joerg llvm_unreachable("Unknown import error happened.");
519 1.1 joerg break;
520 1.1 joerg }
521 1.1 joerg });
522 1.1 joerg return llvm::make_error<IndexError>(index_error_code::failed_import);
523 1.1 joerg }
524 1.1 joerg auto *ToDecl = cast<T>(*ToDeclOrError);
525 1.1 joerg assert(hasBodyOrInit(ToDecl) && "Imported Decl should have body or init.");
526 1.1 joerg ++NumGetCTUSuccess;
527 1.1 joerg
528 1.1 joerg return ToDecl;
529 1.1 joerg }
530 1.1 joerg
531 1.1 joerg llvm::Expected<const FunctionDecl *>
532 1.1 joerg CrossTranslationUnitContext::importDefinition(const FunctionDecl *FD,
533 1.1 joerg ASTUnit *Unit) {
534 1.1 joerg return importDefinitionImpl(FD, Unit);
535 1.1 joerg }
536 1.1 joerg
537 1.1 joerg llvm::Expected<const VarDecl *>
538 1.1 joerg CrossTranslationUnitContext::importDefinition(const VarDecl *VD,
539 1.1 joerg ASTUnit *Unit) {
540 1.1 joerg return importDefinitionImpl(VD, Unit);
541 1.1 joerg }
542 1.1 joerg
543 1.1 joerg void CrossTranslationUnitContext::lazyInitImporterSharedSt(
544 1.1 joerg TranslationUnitDecl *ToTU) {
545 1.1 joerg if (!ImporterSharedSt)
546 1.1 joerg ImporterSharedSt = std::make_shared<ASTImporterSharedState>(*ToTU);
547 1.1 joerg }
548 1.1 joerg
549 1.1 joerg ASTImporter &
550 1.1 joerg CrossTranslationUnitContext::getOrCreateASTImporter(ASTUnit *Unit) {
551 1.1 joerg ASTContext &From = Unit->getASTContext();
552 1.1 joerg
553 1.1 joerg auto I = ASTUnitImporterMap.find(From.getTranslationUnitDecl());
554 1.1 joerg if (I != ASTUnitImporterMap.end())
555 1.1 joerg return *I->second;
556 1.1 joerg lazyInitImporterSharedSt(Context.getTranslationUnitDecl());
557 1.1 joerg ASTImporter *NewImporter = new ASTImporter(
558 1.1 joerg Context, Context.getSourceManager().getFileManager(), From,
559 1.1 joerg From.getSourceManager().getFileManager(), false, ImporterSharedSt);
560 1.1 joerg NewImporter->setFileIDImportHandler([this, Unit](FileID ToID, FileID FromID) {
561 1.1 joerg assert(ImportedFileIDs.find(ToID) == ImportedFileIDs.end() &&
562 1.1 joerg "FileID already imported, should not happen.");
563 1.1 joerg ImportedFileIDs[ToID] = std::make_pair(FromID, Unit);
564 1.1 joerg });
565 1.1 joerg ASTUnitImporterMap[From.getTranslationUnitDecl()].reset(NewImporter);
566 1.1 joerg return *NewImporter;
567 1.1 joerg }
568 1.1 joerg
569 1.1 joerg llvm::Optional<std::pair<SourceLocation, ASTUnit *>>
570 1.1 joerg CrossTranslationUnitContext::getImportedFromSourceLocation(
571 1.1 joerg const clang::SourceLocation &ToLoc) const {
572 1.1 joerg const SourceManager &SM = Context.getSourceManager();
573 1.1 joerg auto DecToLoc = SM.getDecomposedLoc(ToLoc);
574 1.1 joerg
575 1.1 joerg auto I = ImportedFileIDs.find(DecToLoc.first);
576 1.1 joerg if (I == ImportedFileIDs.end())
577 1.1 joerg return {};
578 1.1 joerg
579 1.1 joerg FileID FromID = I->second.first;
580 1.1 joerg clang::ASTUnit *Unit = I->second.second;
581 1.1 joerg SourceLocation FromLoc =
582 1.1 joerg Unit->getSourceManager().getComposedLoc(FromID, DecToLoc.second);
583 1.1 joerg
584 1.1 joerg return std::make_pair(FromLoc, Unit);
585 1.1 joerg }
586 1.1 joerg
587 1.1 joerg } // namespace cross_tu
588 1.1 joerg } // namespace clang
589