xref: /openbsd-src/gnu/llvm/clang/lib/CrossTU/CrossTranslationUnit.cpp (revision 12c855180aad702bbcca06e0398d774beeafb155)
1e5dd7070Spatrick //===--- CrossTranslationUnit.cpp - -----------------------------*- C++ -*-===//
2e5dd7070Spatrick //
3e5dd7070Spatrick // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4e5dd7070Spatrick // See https://llvm.org/LICENSE.txt for license information.
5e5dd7070Spatrick // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6e5dd7070Spatrick //
7e5dd7070Spatrick //===----------------------------------------------------------------------===//
8e5dd7070Spatrick //
9e5dd7070Spatrick //  This file implements the CrossTranslationUnit interface.
10e5dd7070Spatrick //
11e5dd7070Spatrick //===----------------------------------------------------------------------===//
12e5dd7070Spatrick #include "clang/CrossTU/CrossTranslationUnit.h"
13e5dd7070Spatrick #include "clang/AST/ASTImporter.h"
14e5dd7070Spatrick #include "clang/AST/Decl.h"
15ec727ea7Spatrick #include "clang/AST/ParentMapContext.h"
16e5dd7070Spatrick #include "clang/Basic/TargetInfo.h"
17e5dd7070Spatrick #include "clang/CrossTU/CrossTUDiagnostic.h"
18e5dd7070Spatrick #include "clang/Frontend/ASTUnit.h"
19e5dd7070Spatrick #include "clang/Frontend/CompilerInstance.h"
20e5dd7070Spatrick #include "clang/Frontend/TextDiagnosticPrinter.h"
21e5dd7070Spatrick #include "clang/Index/USRGeneration.h"
22e5dd7070Spatrick #include "llvm/ADT/Statistic.h"
23ec727ea7Spatrick #include "llvm/ADT/Triple.h"
24ec727ea7Spatrick #include "llvm/Option/ArgList.h"
25e5dd7070Spatrick #include "llvm/Support/ErrorHandling.h"
26e5dd7070Spatrick #include "llvm/Support/ManagedStatic.h"
27e5dd7070Spatrick #include "llvm/Support/Path.h"
28ec727ea7Spatrick #include "llvm/Support/YAMLParser.h"
29e5dd7070Spatrick #include "llvm/Support/raw_ostream.h"
30ec727ea7Spatrick #include <algorithm>
31e5dd7070Spatrick #include <fstream>
32*12c85518Srobert #include <optional>
33e5dd7070Spatrick #include <sstream>
34ec727ea7Spatrick #include <tuple>
35e5dd7070Spatrick 
36e5dd7070Spatrick namespace clang {
37e5dd7070Spatrick namespace cross_tu {
38e5dd7070Spatrick 
39e5dd7070Spatrick namespace {
40e5dd7070Spatrick 
41e5dd7070Spatrick #define DEBUG_TYPE "CrossTranslationUnit"
42e5dd7070Spatrick STATISTIC(NumGetCTUCalled, "The # of getCTUDefinition function called");
43e5dd7070Spatrick STATISTIC(
44e5dd7070Spatrick     NumNotInOtherTU,
45e5dd7070Spatrick     "The # of getCTUDefinition called but the function is not in any other TU");
46e5dd7070Spatrick STATISTIC(NumGetCTUSuccess,
47e5dd7070Spatrick           "The # of getCTUDefinition successfully returned the "
48e5dd7070Spatrick           "requested function's body");
49e5dd7070Spatrick STATISTIC(NumUnsupportedNodeFound, "The # of imports when the ASTImporter "
50e5dd7070Spatrick                                    "encountered an unsupported AST Node");
51e5dd7070Spatrick STATISTIC(NumNameConflicts, "The # of imports when the ASTImporter "
52e5dd7070Spatrick                             "encountered an ODR error");
53e5dd7070Spatrick STATISTIC(NumTripleMismatch, "The # of triple mismatches");
54e5dd7070Spatrick STATISTIC(NumLangMismatch, "The # of language mismatches");
55e5dd7070Spatrick STATISTIC(NumLangDialectMismatch, "The # of language dialect mismatches");
56e5dd7070Spatrick STATISTIC(NumASTLoadThresholdReached,
57e5dd7070Spatrick           "The # of ASTs not loaded because of threshold");
58e5dd7070Spatrick 
59e5dd7070Spatrick // Same as Triple's equality operator, but we check a field only if that is
60e5dd7070Spatrick // known in both instances.
hasEqualKnownFields(const llvm::Triple & Lhs,const llvm::Triple & Rhs)61e5dd7070Spatrick bool hasEqualKnownFields(const llvm::Triple &Lhs, const llvm::Triple &Rhs) {
62e5dd7070Spatrick   using llvm::Triple;
63e5dd7070Spatrick   if (Lhs.getArch() != Triple::UnknownArch &&
64e5dd7070Spatrick       Rhs.getArch() != Triple::UnknownArch && Lhs.getArch() != Rhs.getArch())
65e5dd7070Spatrick     return false;
66e5dd7070Spatrick   if (Lhs.getSubArch() != Triple::NoSubArch &&
67e5dd7070Spatrick       Rhs.getSubArch() != Triple::NoSubArch &&
68e5dd7070Spatrick       Lhs.getSubArch() != Rhs.getSubArch())
69e5dd7070Spatrick     return false;
70e5dd7070Spatrick   if (Lhs.getVendor() != Triple::UnknownVendor &&
71e5dd7070Spatrick       Rhs.getVendor() != Triple::UnknownVendor &&
72e5dd7070Spatrick       Lhs.getVendor() != Rhs.getVendor())
73e5dd7070Spatrick     return false;
74e5dd7070Spatrick   if (!Lhs.isOSUnknown() && !Rhs.isOSUnknown() &&
75e5dd7070Spatrick       Lhs.getOS() != Rhs.getOS())
76e5dd7070Spatrick     return false;
77e5dd7070Spatrick   if (Lhs.getEnvironment() != Triple::UnknownEnvironment &&
78e5dd7070Spatrick       Rhs.getEnvironment() != Triple::UnknownEnvironment &&
79e5dd7070Spatrick       Lhs.getEnvironment() != Rhs.getEnvironment())
80e5dd7070Spatrick     return false;
81e5dd7070Spatrick   if (Lhs.getObjectFormat() != Triple::UnknownObjectFormat &&
82e5dd7070Spatrick       Rhs.getObjectFormat() != Triple::UnknownObjectFormat &&
83e5dd7070Spatrick       Lhs.getObjectFormat() != Rhs.getObjectFormat())
84e5dd7070Spatrick     return false;
85e5dd7070Spatrick   return true;
86e5dd7070Spatrick }
87e5dd7070Spatrick 
88e5dd7070Spatrick // FIXME: This class is will be removed after the transition to llvm::Error.
89e5dd7070Spatrick class IndexErrorCategory : public std::error_category {
90e5dd7070Spatrick public:
name() const91e5dd7070Spatrick   const char *name() const noexcept override { return "clang.index"; }
92e5dd7070Spatrick 
message(int Condition) const93e5dd7070Spatrick   std::string message(int Condition) const override {
94e5dd7070Spatrick     switch (static_cast<index_error_code>(Condition)) {
95a9ac8606Spatrick     case index_error_code::success:
96a9ac8606Spatrick       // There should not be a success error. Jump to unreachable directly.
97a9ac8606Spatrick       // Add this case to make the compiler stop complaining.
98a9ac8606Spatrick       break;
99e5dd7070Spatrick     case index_error_code::unspecified:
100e5dd7070Spatrick       return "An unknown error has occurred.";
101e5dd7070Spatrick     case index_error_code::missing_index_file:
102e5dd7070Spatrick       return "The index file is missing.";
103e5dd7070Spatrick     case index_error_code::invalid_index_format:
104e5dd7070Spatrick       return "Invalid index file format.";
105e5dd7070Spatrick     case index_error_code::multiple_definitions:
106e5dd7070Spatrick       return "Multiple definitions in the index file.";
107e5dd7070Spatrick     case index_error_code::missing_definition:
108e5dd7070Spatrick       return "Missing definition from the index file.";
109e5dd7070Spatrick     case index_error_code::failed_import:
110e5dd7070Spatrick       return "Failed to import the definition.";
111e5dd7070Spatrick     case index_error_code::failed_to_get_external_ast:
112e5dd7070Spatrick       return "Failed to load external AST source.";
113e5dd7070Spatrick     case index_error_code::failed_to_generate_usr:
114e5dd7070Spatrick       return "Failed to generate USR.";
115e5dd7070Spatrick     case index_error_code::triple_mismatch:
116e5dd7070Spatrick       return "Triple mismatch";
117e5dd7070Spatrick     case index_error_code::lang_mismatch:
118e5dd7070Spatrick       return "Language mismatch";
119e5dd7070Spatrick     case index_error_code::lang_dialect_mismatch:
120e5dd7070Spatrick       return "Language dialect mismatch";
121e5dd7070Spatrick     case index_error_code::load_threshold_reached:
122e5dd7070Spatrick       return "Load threshold reached";
123ec727ea7Spatrick     case index_error_code::invocation_list_ambiguous:
124ec727ea7Spatrick       return "Invocation list file contains multiple references to the same "
125ec727ea7Spatrick              "source file.";
126ec727ea7Spatrick     case index_error_code::invocation_list_file_not_found:
127ec727ea7Spatrick       return "Invocation list file is not found.";
128ec727ea7Spatrick     case index_error_code::invocation_list_empty:
129ec727ea7Spatrick       return "Invocation list file is empty.";
130ec727ea7Spatrick     case index_error_code::invocation_list_wrong_format:
131ec727ea7Spatrick       return "Invocation list file is in wrong format.";
132ec727ea7Spatrick     case index_error_code::invocation_list_lookup_unsuccessful:
133ec727ea7Spatrick       return "Invocation list file does not contain the requested source file.";
134e5dd7070Spatrick     }
135e5dd7070Spatrick     llvm_unreachable("Unrecognized index_error_code.");
136e5dd7070Spatrick   }
137e5dd7070Spatrick };
138e5dd7070Spatrick 
139e5dd7070Spatrick static llvm::ManagedStatic<IndexErrorCategory> Category;
140e5dd7070Spatrick } // end anonymous namespace
141e5dd7070Spatrick 
142e5dd7070Spatrick char IndexError::ID;
143e5dd7070Spatrick 
log(raw_ostream & OS) const144e5dd7070Spatrick void IndexError::log(raw_ostream &OS) const {
145e5dd7070Spatrick   OS << Category->message(static_cast<int>(Code)) << '\n';
146e5dd7070Spatrick }
147e5dd7070Spatrick 
convertToErrorCode() const148e5dd7070Spatrick std::error_code IndexError::convertToErrorCode() const {
149e5dd7070Spatrick   return std::error_code(static_cast<int>(Code), *Category);
150e5dd7070Spatrick }
151e5dd7070Spatrick 
152*12c85518Srobert /// Parse one line of the input CTU index file.
153*12c85518Srobert ///
154*12c85518Srobert /// @param[in]  LineRef     The input CTU index item in format
155*12c85518Srobert ///                         "<USR-Length>:<USR> <File-Path>".
156*12c85518Srobert /// @param[out] LookupName  The lookup name in format "<USR-Length>:<USR>".
157*12c85518Srobert /// @param[out] FilePath    The file path "<File-Path>".
parseCrossTUIndexItem(StringRef LineRef,StringRef & LookupName,StringRef & FilePath)158*12c85518Srobert static bool parseCrossTUIndexItem(StringRef LineRef, StringRef &LookupName,
159*12c85518Srobert                                   StringRef &FilePath) {
160*12c85518Srobert   // `LineRef` is "<USR-Length>:<USR> <File-Path>" now.
161*12c85518Srobert 
162*12c85518Srobert   size_t USRLength = 0;
163*12c85518Srobert   if (LineRef.consumeInteger(10, USRLength))
164*12c85518Srobert     return false;
165*12c85518Srobert   assert(USRLength && "USRLength should be greater than zero.");
166*12c85518Srobert 
167*12c85518Srobert   if (!LineRef.consume_front(":"))
168*12c85518Srobert     return false;
169*12c85518Srobert 
170*12c85518Srobert   // `LineRef` is now just "<USR> <File-Path>".
171*12c85518Srobert 
172*12c85518Srobert   // Check LookupName length out of bound and incorrect delimiter.
173*12c85518Srobert   if (USRLength >= LineRef.size() || ' ' != LineRef[USRLength])
174*12c85518Srobert     return false;
175*12c85518Srobert 
176*12c85518Srobert   LookupName = LineRef.substr(0, USRLength);
177*12c85518Srobert   FilePath = LineRef.substr(USRLength + 1);
178*12c85518Srobert   return true;
179*12c85518Srobert }
180*12c85518Srobert 
181e5dd7070Spatrick llvm::Expected<llvm::StringMap<std::string>>
parseCrossTUIndex(StringRef IndexPath)182ec727ea7Spatrick parseCrossTUIndex(StringRef IndexPath) {
183ec727ea7Spatrick   std::ifstream ExternalMapFile{std::string(IndexPath)};
184e5dd7070Spatrick   if (!ExternalMapFile)
185e5dd7070Spatrick     return llvm::make_error<IndexError>(index_error_code::missing_index_file,
186e5dd7070Spatrick                                         IndexPath.str());
187e5dd7070Spatrick 
188e5dd7070Spatrick   llvm::StringMap<std::string> Result;
189e5dd7070Spatrick   std::string Line;
190e5dd7070Spatrick   unsigned LineNo = 1;
191e5dd7070Spatrick   while (std::getline(ExternalMapFile, Line)) {
192*12c85518Srobert     // Split lookup name and file path
193*12c85518Srobert     StringRef LookupName, FilePathInIndex;
194*12c85518Srobert     if (!parseCrossTUIndexItem(Line, LookupName, FilePathInIndex))
195*12c85518Srobert       return llvm::make_error<IndexError>(
196*12c85518Srobert           index_error_code::invalid_index_format, IndexPath.str(), LineNo);
197ec727ea7Spatrick 
198ec727ea7Spatrick     // Store paths with posix-style directory separator.
199*12c85518Srobert     SmallString<32> FilePath(FilePathInIndex);
200ec727ea7Spatrick     llvm::sys::path::native(FilePath, llvm::sys::path::Style::posix);
201ec727ea7Spatrick 
202ec727ea7Spatrick     bool InsertionOccured;
203ec727ea7Spatrick     std::tie(std::ignore, InsertionOccured) =
204ec727ea7Spatrick         Result.try_emplace(LookupName, FilePath.begin(), FilePath.end());
205ec727ea7Spatrick     if (!InsertionOccured)
206e5dd7070Spatrick       return llvm::make_error<IndexError>(
207e5dd7070Spatrick           index_error_code::multiple_definitions, IndexPath.str(), LineNo);
208*12c85518Srobert 
209ec727ea7Spatrick     ++LineNo;
210e5dd7070Spatrick   }
211e5dd7070Spatrick   return Result;
212e5dd7070Spatrick }
213e5dd7070Spatrick 
214e5dd7070Spatrick std::string
createCrossTUIndexString(const llvm::StringMap<std::string> & Index)215e5dd7070Spatrick createCrossTUIndexString(const llvm::StringMap<std::string> &Index) {
216e5dd7070Spatrick   std::ostringstream Result;
217e5dd7070Spatrick   for (const auto &E : Index)
218*12c85518Srobert     Result << E.getKey().size() << ':' << E.getKey().str() << ' '
219*12c85518Srobert            << E.getValue() << '\n';
220e5dd7070Spatrick   return Result.str();
221e5dd7070Spatrick }
222e5dd7070Spatrick 
shouldImport(const VarDecl * VD,const ASTContext & ACtx)223*12c85518Srobert bool shouldImport(const VarDecl *VD, const ASTContext &ACtx) {
224e5dd7070Spatrick   CanQualType CT = ACtx.getCanonicalType(VD->getType());
225*12c85518Srobert   return CT.isConstQualified() && VD->getType().isTrivialType(ACtx);
226e5dd7070Spatrick }
227e5dd7070Spatrick 
hasBodyOrInit(const FunctionDecl * D,const FunctionDecl * & DefD)228e5dd7070Spatrick static bool hasBodyOrInit(const FunctionDecl *D, const FunctionDecl *&DefD) {
229e5dd7070Spatrick   return D->hasBody(DefD);
230e5dd7070Spatrick }
hasBodyOrInit(const VarDecl * D,const VarDecl * & DefD)231e5dd7070Spatrick static bool hasBodyOrInit(const VarDecl *D, const VarDecl *&DefD) {
232e5dd7070Spatrick   return D->getAnyInitializer(DefD);
233e5dd7070Spatrick }
hasBodyOrInit(const T * D)234e5dd7070Spatrick template <typename T> static bool hasBodyOrInit(const T *D) {
235e5dd7070Spatrick   const T *Unused;
236e5dd7070Spatrick   return hasBodyOrInit(D, Unused);
237e5dd7070Spatrick }
238e5dd7070Spatrick 
CrossTranslationUnitContext(CompilerInstance & CI)239e5dd7070Spatrick CrossTranslationUnitContext::CrossTranslationUnitContext(CompilerInstance &CI)
240e5dd7070Spatrick     : Context(CI.getASTContext()), ASTStorage(CI) {}
241e5dd7070Spatrick 
~CrossTranslationUnitContext()242e5dd7070Spatrick CrossTranslationUnitContext::~CrossTranslationUnitContext() {}
243e5dd7070Spatrick 
244*12c85518Srobert std::optional<std::string>
getLookupName(const NamedDecl * ND)245e5dd7070Spatrick CrossTranslationUnitContext::getLookupName(const NamedDecl *ND) {
246e5dd7070Spatrick   SmallString<128> DeclUSR;
247e5dd7070Spatrick   bool Ret = index::generateUSRForDecl(ND, DeclUSR);
248e5dd7070Spatrick   if (Ret)
249e5dd7070Spatrick     return {};
250e5dd7070Spatrick   return std::string(DeclUSR.str());
251e5dd7070Spatrick }
252e5dd7070Spatrick 
253e5dd7070Spatrick /// Recursively visits the decls of a DeclContext, and returns one with the
254e5dd7070Spatrick /// given USR.
255e5dd7070Spatrick template <typename T>
256e5dd7070Spatrick const T *
findDefInDeclContext(const DeclContext * DC,StringRef LookupName)257e5dd7070Spatrick CrossTranslationUnitContext::findDefInDeclContext(const DeclContext *DC,
258e5dd7070Spatrick                                                   StringRef LookupName) {
259e5dd7070Spatrick   assert(DC && "Declaration Context must not be null");
260e5dd7070Spatrick   for (const Decl *D : DC->decls()) {
261e5dd7070Spatrick     const auto *SubDC = dyn_cast<DeclContext>(D);
262e5dd7070Spatrick     if (SubDC)
263e5dd7070Spatrick       if (const auto *ND = findDefInDeclContext<T>(SubDC, LookupName))
264e5dd7070Spatrick         return ND;
265e5dd7070Spatrick 
266e5dd7070Spatrick     const auto *ND = dyn_cast<T>(D);
267e5dd7070Spatrick     const T *ResultDecl;
268e5dd7070Spatrick     if (!ND || !hasBodyOrInit(ND, ResultDecl))
269e5dd7070Spatrick       continue;
270*12c85518Srobert     std::optional<std::string> ResultLookupName = getLookupName(ResultDecl);
271e5dd7070Spatrick     if (!ResultLookupName || *ResultLookupName != LookupName)
272e5dd7070Spatrick       continue;
273e5dd7070Spatrick     return ResultDecl;
274e5dd7070Spatrick   }
275e5dd7070Spatrick   return nullptr;
276e5dd7070Spatrick }
277e5dd7070Spatrick 
278e5dd7070Spatrick template <typename T>
getCrossTUDefinitionImpl(const T * D,StringRef CrossTUDir,StringRef IndexName,bool DisplayCTUProgress)279e5dd7070Spatrick llvm::Expected<const T *> CrossTranslationUnitContext::getCrossTUDefinitionImpl(
280e5dd7070Spatrick     const T *D, StringRef CrossTUDir, StringRef IndexName,
281e5dd7070Spatrick     bool DisplayCTUProgress) {
282e5dd7070Spatrick   assert(D && "D is missing, bad call to this function!");
283e5dd7070Spatrick   assert(!hasBodyOrInit(D) &&
284e5dd7070Spatrick          "D has a body or init in current translation unit!");
285e5dd7070Spatrick   ++NumGetCTUCalled;
286*12c85518Srobert   const std::optional<std::string> LookupName = getLookupName(D);
287e5dd7070Spatrick   if (!LookupName)
288e5dd7070Spatrick     return llvm::make_error<IndexError>(
289e5dd7070Spatrick         index_error_code::failed_to_generate_usr);
290e5dd7070Spatrick   llvm::Expected<ASTUnit *> ASTUnitOrError =
291e5dd7070Spatrick       loadExternalAST(*LookupName, CrossTUDir, IndexName, DisplayCTUProgress);
292e5dd7070Spatrick   if (!ASTUnitOrError)
293e5dd7070Spatrick     return ASTUnitOrError.takeError();
294e5dd7070Spatrick   ASTUnit *Unit = *ASTUnitOrError;
295e5dd7070Spatrick   assert(&Unit->getFileManager() ==
296e5dd7070Spatrick          &Unit->getASTContext().getSourceManager().getFileManager());
297e5dd7070Spatrick 
298e5dd7070Spatrick   const llvm::Triple &TripleTo = Context.getTargetInfo().getTriple();
299e5dd7070Spatrick   const llvm::Triple &TripleFrom =
300e5dd7070Spatrick       Unit->getASTContext().getTargetInfo().getTriple();
301e5dd7070Spatrick   // The imported AST had been generated for a different target.
302e5dd7070Spatrick   // Some parts of the triple in the loaded ASTContext can be unknown while the
303e5dd7070Spatrick   // very same parts in the target ASTContext are known. Thus we check for the
304e5dd7070Spatrick   // known parts only.
305e5dd7070Spatrick   if (!hasEqualKnownFields(TripleTo, TripleFrom)) {
306e5dd7070Spatrick     // TODO: Pass the SourceLocation of the CallExpression for more precise
307e5dd7070Spatrick     // diagnostics.
308e5dd7070Spatrick     ++NumTripleMismatch;
309e5dd7070Spatrick     return llvm::make_error<IndexError>(index_error_code::triple_mismatch,
310ec727ea7Spatrick                                         std::string(Unit->getMainFileName()),
311ec727ea7Spatrick                                         TripleTo.str(), TripleFrom.str());
312e5dd7070Spatrick   }
313e5dd7070Spatrick 
314e5dd7070Spatrick   const auto &LangTo = Context.getLangOpts();
315e5dd7070Spatrick   const auto &LangFrom = Unit->getASTContext().getLangOpts();
316e5dd7070Spatrick 
317e5dd7070Spatrick   // FIXME: Currenty we do not support CTU across C++ and C and across
318e5dd7070Spatrick   // different dialects of C++.
319e5dd7070Spatrick   if (LangTo.CPlusPlus != LangFrom.CPlusPlus) {
320e5dd7070Spatrick     ++NumLangMismatch;
321e5dd7070Spatrick     return llvm::make_error<IndexError>(index_error_code::lang_mismatch);
322e5dd7070Spatrick   }
323e5dd7070Spatrick 
324e5dd7070Spatrick   // If CPP dialects are different then return with error.
325e5dd7070Spatrick   //
326e5dd7070Spatrick   // Consider this STL code:
327e5dd7070Spatrick   //   template<typename _Alloc>
328e5dd7070Spatrick   //     struct __alloc_traits
329e5dd7070Spatrick   //   #if __cplusplus >= 201103L
330e5dd7070Spatrick   //     : std::allocator_traits<_Alloc>
331e5dd7070Spatrick   //   #endif
332e5dd7070Spatrick   //     { // ...
333e5dd7070Spatrick   //     };
334e5dd7070Spatrick   // This class template would create ODR errors during merging the two units,
335e5dd7070Spatrick   // since in one translation unit the class template has a base class, however
336e5dd7070Spatrick   // in the other unit it has none.
337e5dd7070Spatrick   if (LangTo.CPlusPlus11 != LangFrom.CPlusPlus11 ||
338e5dd7070Spatrick       LangTo.CPlusPlus14 != LangFrom.CPlusPlus14 ||
339e5dd7070Spatrick       LangTo.CPlusPlus17 != LangFrom.CPlusPlus17 ||
340ec727ea7Spatrick       LangTo.CPlusPlus20 != LangFrom.CPlusPlus20) {
341e5dd7070Spatrick     ++NumLangDialectMismatch;
342e5dd7070Spatrick     return llvm::make_error<IndexError>(
343e5dd7070Spatrick         index_error_code::lang_dialect_mismatch);
344e5dd7070Spatrick   }
345e5dd7070Spatrick 
346e5dd7070Spatrick   TranslationUnitDecl *TU = Unit->getASTContext().getTranslationUnitDecl();
347e5dd7070Spatrick   if (const T *ResultDecl = findDefInDeclContext<T>(TU, *LookupName))
348e5dd7070Spatrick     return importDefinition(ResultDecl, Unit);
349e5dd7070Spatrick   return llvm::make_error<IndexError>(index_error_code::failed_import);
350e5dd7070Spatrick }
351e5dd7070Spatrick 
352e5dd7070Spatrick llvm::Expected<const FunctionDecl *>
getCrossTUDefinition(const FunctionDecl * FD,StringRef CrossTUDir,StringRef IndexName,bool DisplayCTUProgress)353e5dd7070Spatrick CrossTranslationUnitContext::getCrossTUDefinition(const FunctionDecl *FD,
354e5dd7070Spatrick                                                   StringRef CrossTUDir,
355e5dd7070Spatrick                                                   StringRef IndexName,
356e5dd7070Spatrick                                                   bool DisplayCTUProgress) {
357e5dd7070Spatrick   return getCrossTUDefinitionImpl(FD, CrossTUDir, IndexName,
358e5dd7070Spatrick                                   DisplayCTUProgress);
359e5dd7070Spatrick }
360e5dd7070Spatrick 
361e5dd7070Spatrick llvm::Expected<const VarDecl *>
getCrossTUDefinition(const VarDecl * VD,StringRef CrossTUDir,StringRef IndexName,bool DisplayCTUProgress)362e5dd7070Spatrick CrossTranslationUnitContext::getCrossTUDefinition(const VarDecl *VD,
363e5dd7070Spatrick                                                   StringRef CrossTUDir,
364e5dd7070Spatrick                                                   StringRef IndexName,
365e5dd7070Spatrick                                                   bool DisplayCTUProgress) {
366e5dd7070Spatrick   return getCrossTUDefinitionImpl(VD, CrossTUDir, IndexName,
367e5dd7070Spatrick                                   DisplayCTUProgress);
368e5dd7070Spatrick }
369e5dd7070Spatrick 
emitCrossTUDiagnostics(const IndexError & IE)370e5dd7070Spatrick void CrossTranslationUnitContext::emitCrossTUDiagnostics(const IndexError &IE) {
371e5dd7070Spatrick   switch (IE.getCode()) {
372e5dd7070Spatrick   case index_error_code::missing_index_file:
373e5dd7070Spatrick     Context.getDiagnostics().Report(diag::err_ctu_error_opening)
374e5dd7070Spatrick         << IE.getFileName();
375e5dd7070Spatrick     break;
376e5dd7070Spatrick   case index_error_code::invalid_index_format:
377e5dd7070Spatrick     Context.getDiagnostics().Report(diag::err_extdefmap_parsing)
378e5dd7070Spatrick         << IE.getFileName() << IE.getLineNum();
379e5dd7070Spatrick     break;
380e5dd7070Spatrick   case index_error_code::multiple_definitions:
381e5dd7070Spatrick     Context.getDiagnostics().Report(diag::err_multiple_def_index)
382e5dd7070Spatrick         << IE.getLineNum();
383e5dd7070Spatrick     break;
384e5dd7070Spatrick   case index_error_code::triple_mismatch:
385e5dd7070Spatrick     Context.getDiagnostics().Report(diag::warn_ctu_incompat_triple)
386e5dd7070Spatrick         << IE.getFileName() << IE.getTripleToName() << IE.getTripleFromName();
387e5dd7070Spatrick     break;
388e5dd7070Spatrick   default:
389e5dd7070Spatrick     break;
390e5dd7070Spatrick   }
391e5dd7070Spatrick }
392e5dd7070Spatrick 
ASTUnitStorage(CompilerInstance & CI)393e5dd7070Spatrick CrossTranslationUnitContext::ASTUnitStorage::ASTUnitStorage(
394ec727ea7Spatrick     CompilerInstance &CI)
395ec727ea7Spatrick     : Loader(CI, CI.getAnalyzerOpts()->CTUDir,
396ec727ea7Spatrick              CI.getAnalyzerOpts()->CTUInvocationList),
397ec727ea7Spatrick       LoadGuard(CI.getASTContext().getLangOpts().CPlusPlus
398ec727ea7Spatrick                     ? CI.getAnalyzerOpts()->CTUImportCppThreshold
399ec727ea7Spatrick                     : CI.getAnalyzerOpts()->CTUImportThreshold) {}
400e5dd7070Spatrick 
401e5dd7070Spatrick llvm::Expected<ASTUnit *>
getASTUnitForFile(StringRef FileName,bool DisplayCTUProgress)402e5dd7070Spatrick CrossTranslationUnitContext::ASTUnitStorage::getASTUnitForFile(
403e5dd7070Spatrick     StringRef FileName, bool DisplayCTUProgress) {
404e5dd7070Spatrick   // Try the cache first.
405e5dd7070Spatrick   auto ASTCacheEntry = FileASTUnitMap.find(FileName);
406e5dd7070Spatrick   if (ASTCacheEntry == FileASTUnitMap.end()) {
407e5dd7070Spatrick 
408e5dd7070Spatrick     // Do not load if the limit is reached.
409e5dd7070Spatrick     if (!LoadGuard) {
410e5dd7070Spatrick       ++NumASTLoadThresholdReached;
411e5dd7070Spatrick       return llvm::make_error<IndexError>(
412e5dd7070Spatrick           index_error_code::load_threshold_reached);
413e5dd7070Spatrick     }
414e5dd7070Spatrick 
415ec727ea7Spatrick     auto LoadAttempt = Loader.load(FileName);
416ec727ea7Spatrick 
417ec727ea7Spatrick     if (!LoadAttempt)
418ec727ea7Spatrick       return LoadAttempt.takeError();
419ec727ea7Spatrick 
420ec727ea7Spatrick     std::unique_ptr<ASTUnit> LoadedUnit = std::move(LoadAttempt.get());
421e5dd7070Spatrick 
422e5dd7070Spatrick     // Need the raw pointer and the unique_ptr as well.
423e5dd7070Spatrick     ASTUnit *Unit = LoadedUnit.get();
424e5dd7070Spatrick 
425e5dd7070Spatrick     // Update the cache.
426e5dd7070Spatrick     FileASTUnitMap[FileName] = std::move(LoadedUnit);
427e5dd7070Spatrick 
428e5dd7070Spatrick     LoadGuard.indicateLoadSuccess();
429e5dd7070Spatrick 
430e5dd7070Spatrick     if (DisplayCTUProgress)
431e5dd7070Spatrick       llvm::errs() << "CTU loaded AST file: " << FileName << "\n";
432e5dd7070Spatrick 
433e5dd7070Spatrick     return Unit;
434e5dd7070Spatrick 
435e5dd7070Spatrick   } else {
436e5dd7070Spatrick     // Found in the cache.
437e5dd7070Spatrick     return ASTCacheEntry->second.get();
438e5dd7070Spatrick   }
439e5dd7070Spatrick }
440e5dd7070Spatrick 
441e5dd7070Spatrick llvm::Expected<ASTUnit *>
getASTUnitForFunction(StringRef FunctionName,StringRef CrossTUDir,StringRef IndexName,bool DisplayCTUProgress)442e5dd7070Spatrick CrossTranslationUnitContext::ASTUnitStorage::getASTUnitForFunction(
443e5dd7070Spatrick     StringRef FunctionName, StringRef CrossTUDir, StringRef IndexName,
444e5dd7070Spatrick     bool DisplayCTUProgress) {
445e5dd7070Spatrick   // Try the cache first.
446e5dd7070Spatrick   auto ASTCacheEntry = NameASTUnitMap.find(FunctionName);
447e5dd7070Spatrick   if (ASTCacheEntry == NameASTUnitMap.end()) {
448e5dd7070Spatrick     // Load the ASTUnit from the pre-dumped AST file specified by ASTFileName.
449e5dd7070Spatrick 
450e5dd7070Spatrick     // Ensure that the Index is loaded, as we need to search in it.
451e5dd7070Spatrick     if (llvm::Error IndexLoadError =
452e5dd7070Spatrick             ensureCTUIndexLoaded(CrossTUDir, IndexName))
453e5dd7070Spatrick       return std::move(IndexLoadError);
454e5dd7070Spatrick 
455*12c85518Srobert     // Check if there is an entry in the index for the function.
456e5dd7070Spatrick     if (!NameFileMap.count(FunctionName)) {
457e5dd7070Spatrick       ++NumNotInOtherTU;
458e5dd7070Spatrick       return llvm::make_error<IndexError>(index_error_code::missing_definition);
459e5dd7070Spatrick     }
460e5dd7070Spatrick 
461*12c85518Srobert     // Search in the index for the filename where the definition of FunctionName
462e5dd7070Spatrick     // resides.
463e5dd7070Spatrick     if (llvm::Expected<ASTUnit *> FoundForFile =
464e5dd7070Spatrick             getASTUnitForFile(NameFileMap[FunctionName], DisplayCTUProgress)) {
465e5dd7070Spatrick 
466e5dd7070Spatrick       // Update the cache.
467e5dd7070Spatrick       NameASTUnitMap[FunctionName] = *FoundForFile;
468e5dd7070Spatrick       return *FoundForFile;
469e5dd7070Spatrick 
470e5dd7070Spatrick     } else {
471e5dd7070Spatrick       return FoundForFile.takeError();
472e5dd7070Spatrick     }
473e5dd7070Spatrick   } else {
474e5dd7070Spatrick     // Found in the cache.
475e5dd7070Spatrick     return ASTCacheEntry->second;
476e5dd7070Spatrick   }
477e5dd7070Spatrick }
478e5dd7070Spatrick 
479e5dd7070Spatrick llvm::Expected<std::string>
getFileForFunction(StringRef FunctionName,StringRef CrossTUDir,StringRef IndexName)480e5dd7070Spatrick CrossTranslationUnitContext::ASTUnitStorage::getFileForFunction(
481e5dd7070Spatrick     StringRef FunctionName, StringRef CrossTUDir, StringRef IndexName) {
482e5dd7070Spatrick   if (llvm::Error IndexLoadError = ensureCTUIndexLoaded(CrossTUDir, IndexName))
483e5dd7070Spatrick     return std::move(IndexLoadError);
484e5dd7070Spatrick   return NameFileMap[FunctionName];
485e5dd7070Spatrick }
486e5dd7070Spatrick 
ensureCTUIndexLoaded(StringRef CrossTUDir,StringRef IndexName)487e5dd7070Spatrick llvm::Error CrossTranslationUnitContext::ASTUnitStorage::ensureCTUIndexLoaded(
488e5dd7070Spatrick     StringRef CrossTUDir, StringRef IndexName) {
489e5dd7070Spatrick   // Dont initialize if the map is filled.
490e5dd7070Spatrick   if (!NameFileMap.empty())
491e5dd7070Spatrick     return llvm::Error::success();
492e5dd7070Spatrick 
493e5dd7070Spatrick   // Get the absolute path to the index file.
494e5dd7070Spatrick   SmallString<256> IndexFile = CrossTUDir;
495e5dd7070Spatrick   if (llvm::sys::path::is_absolute(IndexName))
496e5dd7070Spatrick     IndexFile = IndexName;
497e5dd7070Spatrick   else
498e5dd7070Spatrick     llvm::sys::path::append(IndexFile, IndexName);
499e5dd7070Spatrick 
500ec727ea7Spatrick   if (auto IndexMapping = parseCrossTUIndex(IndexFile)) {
501e5dd7070Spatrick     // Initialize member map.
502e5dd7070Spatrick     NameFileMap = *IndexMapping;
503e5dd7070Spatrick     return llvm::Error::success();
504e5dd7070Spatrick   } else {
505e5dd7070Spatrick     // Error while parsing CrossTU index file.
506e5dd7070Spatrick     return IndexMapping.takeError();
507e5dd7070Spatrick   };
508e5dd7070Spatrick }
509e5dd7070Spatrick 
loadExternalAST(StringRef LookupName,StringRef CrossTUDir,StringRef IndexName,bool DisplayCTUProgress)510e5dd7070Spatrick llvm::Expected<ASTUnit *> CrossTranslationUnitContext::loadExternalAST(
511e5dd7070Spatrick     StringRef LookupName, StringRef CrossTUDir, StringRef IndexName,
512e5dd7070Spatrick     bool DisplayCTUProgress) {
513e5dd7070Spatrick   // FIXME: The current implementation only supports loading decls with
514e5dd7070Spatrick   //        a lookup name from a single translation unit. If multiple
515e5dd7070Spatrick   //        translation units contains decls with the same lookup name an
516e5dd7070Spatrick   //        error will be returned.
517e5dd7070Spatrick 
518e5dd7070Spatrick   // Try to get the value from the heavily cached storage.
519e5dd7070Spatrick   llvm::Expected<ASTUnit *> Unit = ASTStorage.getASTUnitForFunction(
520e5dd7070Spatrick       LookupName, CrossTUDir, IndexName, DisplayCTUProgress);
521e5dd7070Spatrick 
522e5dd7070Spatrick   if (!Unit)
523e5dd7070Spatrick     return Unit.takeError();
524e5dd7070Spatrick 
525e5dd7070Spatrick   // Check whether the backing pointer of the Expected is a nullptr.
526e5dd7070Spatrick   if (!*Unit)
527e5dd7070Spatrick     return llvm::make_error<IndexError>(
528e5dd7070Spatrick         index_error_code::failed_to_get_external_ast);
529e5dd7070Spatrick 
530e5dd7070Spatrick   return Unit;
531e5dd7070Spatrick }
532e5dd7070Spatrick 
ASTLoader(CompilerInstance & CI,StringRef CTUDir,StringRef InvocationListFilePath)533ec727ea7Spatrick CrossTranslationUnitContext::ASTLoader::ASTLoader(
534ec727ea7Spatrick     CompilerInstance &CI, StringRef CTUDir, StringRef InvocationListFilePath)
535ec727ea7Spatrick     : CI(CI), CTUDir(CTUDir), InvocationListFilePath(InvocationListFilePath) {}
536ec727ea7Spatrick 
537ec727ea7Spatrick CrossTranslationUnitContext::LoadResultTy
load(StringRef Identifier)538ec727ea7Spatrick CrossTranslationUnitContext::ASTLoader::load(StringRef Identifier) {
539ec727ea7Spatrick   llvm::SmallString<256> Path;
540ec727ea7Spatrick   if (llvm::sys::path::is_absolute(Identifier, PathStyle)) {
541ec727ea7Spatrick     Path = Identifier;
542ec727ea7Spatrick   } else {
543ec727ea7Spatrick     Path = CTUDir;
544ec727ea7Spatrick     llvm::sys::path::append(Path, PathStyle, Identifier);
545ec727ea7Spatrick   }
546ec727ea7Spatrick 
547ec727ea7Spatrick   // The path is stored in the InvocationList member in posix style. To
548ec727ea7Spatrick   // successfully lookup an entry based on filepath, it must be converted.
549ec727ea7Spatrick   llvm::sys::path::native(Path, PathStyle);
550ec727ea7Spatrick 
551ec727ea7Spatrick   // Normalize by removing relative path components.
552ec727ea7Spatrick   llvm::sys::path::remove_dots(Path, /*remove_dot_dot*/ true, PathStyle);
553ec727ea7Spatrick 
554ec727ea7Spatrick   if (Path.endswith(".ast"))
555ec727ea7Spatrick     return loadFromDump(Path);
556ec727ea7Spatrick   else
557ec727ea7Spatrick     return loadFromSource(Path);
558ec727ea7Spatrick }
559ec727ea7Spatrick 
560ec727ea7Spatrick CrossTranslationUnitContext::LoadResultTy
loadFromDump(StringRef ASTDumpPath)561ec727ea7Spatrick CrossTranslationUnitContext::ASTLoader::loadFromDump(StringRef ASTDumpPath) {
562ec727ea7Spatrick   IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
563ec727ea7Spatrick   TextDiagnosticPrinter *DiagClient =
564ec727ea7Spatrick       new TextDiagnosticPrinter(llvm::errs(), &*DiagOpts);
565ec727ea7Spatrick   IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
566ec727ea7Spatrick   IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
567ec727ea7Spatrick       new DiagnosticsEngine(DiagID, &*DiagOpts, DiagClient));
568ec727ea7Spatrick   return ASTUnit::LoadFromASTFile(
569ec727ea7Spatrick       std::string(ASTDumpPath.str()),
570ec727ea7Spatrick       CI.getPCHContainerOperations()->getRawReader(), ASTUnit::LoadEverything,
571ec727ea7Spatrick       Diags, CI.getFileSystemOpts());
572ec727ea7Spatrick }
573ec727ea7Spatrick 
574ec727ea7Spatrick /// Load the AST from a source-file, which is supposed to be located inside the
575ec727ea7Spatrick /// YAML formatted invocation list file under the filesystem path specified by
576ec727ea7Spatrick /// \p InvocationList. The invocation list should contain absolute paths.
577ec727ea7Spatrick /// \p SourceFilePath is the absolute path of the source file that contains the
578ec727ea7Spatrick /// function definition the analysis is looking for. The Index is built by the
579ec727ea7Spatrick /// \p clang-extdef-mapping tool, which is also supposed to be generating
580ec727ea7Spatrick /// absolute paths.
581ec727ea7Spatrick ///
582ec727ea7Spatrick /// Proper diagnostic emission requires absolute paths, so even if a future
583ec727ea7Spatrick /// change introduces the handling of relative paths, this must be taken into
584ec727ea7Spatrick /// consideration.
585ec727ea7Spatrick CrossTranslationUnitContext::LoadResultTy
loadFromSource(StringRef SourceFilePath)586ec727ea7Spatrick CrossTranslationUnitContext::ASTLoader::loadFromSource(
587ec727ea7Spatrick     StringRef SourceFilePath) {
588ec727ea7Spatrick 
589ec727ea7Spatrick   if (llvm::Error InitError = lazyInitInvocationList())
590ec727ea7Spatrick     return std::move(InitError);
591ec727ea7Spatrick   assert(InvocationList);
592ec727ea7Spatrick 
593ec727ea7Spatrick   auto Invocation = InvocationList->find(SourceFilePath);
594ec727ea7Spatrick   if (Invocation == InvocationList->end())
595ec727ea7Spatrick     return llvm::make_error<IndexError>(
596ec727ea7Spatrick         index_error_code::invocation_list_lookup_unsuccessful);
597ec727ea7Spatrick 
598ec727ea7Spatrick   const InvocationListTy::mapped_type &InvocationCommand = Invocation->second;
599ec727ea7Spatrick 
600ec727ea7Spatrick   SmallVector<const char *, 32> CommandLineArgs(InvocationCommand.size());
601ec727ea7Spatrick   std::transform(InvocationCommand.begin(), InvocationCommand.end(),
602ec727ea7Spatrick                  CommandLineArgs.begin(),
603ec727ea7Spatrick                  [](auto &&CmdPart) { return CmdPart.c_str(); });
604ec727ea7Spatrick 
605ec727ea7Spatrick   IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts{&CI.getDiagnosticOpts()};
606ec727ea7Spatrick   auto *DiagClient = new ForwardingDiagnosticConsumer{CI.getDiagnosticClient()};
607ec727ea7Spatrick   IntrusiveRefCntPtr<DiagnosticIDs> DiagID{
608ec727ea7Spatrick       CI.getDiagnostics().getDiagnosticIDs()};
609ec727ea7Spatrick   IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
610ec727ea7Spatrick       new DiagnosticsEngine{DiagID, &*DiagOpts, DiagClient});
611ec727ea7Spatrick 
612ec727ea7Spatrick   return std::unique_ptr<ASTUnit>(ASTUnit::LoadFromCommandLine(
613ec727ea7Spatrick       CommandLineArgs.begin(), (CommandLineArgs.end()),
614ec727ea7Spatrick       CI.getPCHContainerOperations(), Diags,
615ec727ea7Spatrick       CI.getHeaderSearchOpts().ResourceDir));
616ec727ea7Spatrick }
617ec727ea7Spatrick 
618ec727ea7Spatrick llvm::Expected<InvocationListTy>
parseInvocationList(StringRef FileContent,llvm::sys::path::Style PathStyle)619ec727ea7Spatrick parseInvocationList(StringRef FileContent, llvm::sys::path::Style PathStyle) {
620ec727ea7Spatrick   InvocationListTy InvocationList;
621ec727ea7Spatrick 
622ec727ea7Spatrick   /// LLVM YAML parser is used to extract information from invocation list file.
623ec727ea7Spatrick   llvm::SourceMgr SM;
624ec727ea7Spatrick   llvm::yaml::Stream InvocationFile(FileContent, SM);
625ec727ea7Spatrick 
626ec727ea7Spatrick   /// Only the first document is processed.
627ec727ea7Spatrick   llvm::yaml::document_iterator FirstInvocationFile = InvocationFile.begin();
628ec727ea7Spatrick 
629ec727ea7Spatrick   /// There has to be at least one document available.
630ec727ea7Spatrick   if (FirstInvocationFile == InvocationFile.end())
631ec727ea7Spatrick     return llvm::make_error<IndexError>(
632ec727ea7Spatrick         index_error_code::invocation_list_empty);
633ec727ea7Spatrick 
634ec727ea7Spatrick   llvm::yaml::Node *DocumentRoot = FirstInvocationFile->getRoot();
635ec727ea7Spatrick   if (!DocumentRoot)
636ec727ea7Spatrick     return llvm::make_error<IndexError>(
637ec727ea7Spatrick         index_error_code::invocation_list_wrong_format);
638ec727ea7Spatrick 
639ec727ea7Spatrick   /// According to the format specified the document must be a mapping, where
640ec727ea7Spatrick   /// the keys are paths to source files, and values are sequences of invocation
641ec727ea7Spatrick   /// parts.
642ec727ea7Spatrick   auto *Mappings = dyn_cast<llvm::yaml::MappingNode>(DocumentRoot);
643ec727ea7Spatrick   if (!Mappings)
644ec727ea7Spatrick     return llvm::make_error<IndexError>(
645ec727ea7Spatrick         index_error_code::invocation_list_wrong_format);
646ec727ea7Spatrick 
647ec727ea7Spatrick   for (auto &NextMapping : *Mappings) {
648ec727ea7Spatrick     /// The keys should be strings, which represent a source-file path.
649ec727ea7Spatrick     auto *Key = dyn_cast<llvm::yaml::ScalarNode>(NextMapping.getKey());
650ec727ea7Spatrick     if (!Key)
651ec727ea7Spatrick       return llvm::make_error<IndexError>(
652ec727ea7Spatrick           index_error_code::invocation_list_wrong_format);
653ec727ea7Spatrick 
654a9ac8606Spatrick     SmallString<32> ValueStorage;
655ec727ea7Spatrick     StringRef SourcePath = Key->getValue(ValueStorage);
656ec727ea7Spatrick 
657ec727ea7Spatrick     // Store paths with PathStyle directory separator.
658a9ac8606Spatrick     SmallString<32> NativeSourcePath(SourcePath);
659ec727ea7Spatrick     llvm::sys::path::native(NativeSourcePath, PathStyle);
660ec727ea7Spatrick 
661a9ac8606Spatrick     StringRef InvocationKey = NativeSourcePath;
662ec727ea7Spatrick 
663ec727ea7Spatrick     if (InvocationList.find(InvocationKey) != InvocationList.end())
664ec727ea7Spatrick       return llvm::make_error<IndexError>(
665ec727ea7Spatrick           index_error_code::invocation_list_ambiguous);
666ec727ea7Spatrick 
667ec727ea7Spatrick     /// The values should be sequences of strings, each representing a part of
668ec727ea7Spatrick     /// the invocation.
669ec727ea7Spatrick     auto *Args = dyn_cast<llvm::yaml::SequenceNode>(NextMapping.getValue());
670ec727ea7Spatrick     if (!Args)
671ec727ea7Spatrick       return llvm::make_error<IndexError>(
672ec727ea7Spatrick           index_error_code::invocation_list_wrong_format);
673ec727ea7Spatrick 
674ec727ea7Spatrick     for (auto &Arg : *Args) {
675ec727ea7Spatrick       auto *CmdString = dyn_cast<llvm::yaml::ScalarNode>(&Arg);
676ec727ea7Spatrick       if (!CmdString)
677ec727ea7Spatrick         return llvm::make_error<IndexError>(
678ec727ea7Spatrick             index_error_code::invocation_list_wrong_format);
679ec727ea7Spatrick       /// Every conversion starts with an empty working storage, as it is not
680ec727ea7Spatrick       /// clear if this is a requirement of the YAML parser.
681ec727ea7Spatrick       ValueStorage.clear();
682ec727ea7Spatrick       InvocationList[InvocationKey].emplace_back(
683ec727ea7Spatrick           CmdString->getValue(ValueStorage));
684ec727ea7Spatrick     }
685ec727ea7Spatrick 
686ec727ea7Spatrick     if (InvocationList[InvocationKey].empty())
687ec727ea7Spatrick       return llvm::make_error<IndexError>(
688ec727ea7Spatrick           index_error_code::invocation_list_wrong_format);
689ec727ea7Spatrick   }
690ec727ea7Spatrick 
691ec727ea7Spatrick   return InvocationList;
692ec727ea7Spatrick }
693ec727ea7Spatrick 
lazyInitInvocationList()694ec727ea7Spatrick llvm::Error CrossTranslationUnitContext::ASTLoader::lazyInitInvocationList() {
695ec727ea7Spatrick   /// Lazily initialize the invocation list member used for on-demand parsing.
696ec727ea7Spatrick   if (InvocationList)
697ec727ea7Spatrick     return llvm::Error::success();
698a9ac8606Spatrick   if (index_error_code::success != PreviousParsingResult)
699a9ac8606Spatrick     return llvm::make_error<IndexError>(PreviousParsingResult);
700ec727ea7Spatrick 
701ec727ea7Spatrick   llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> FileContent =
702ec727ea7Spatrick       llvm::MemoryBuffer::getFile(InvocationListFilePath);
703a9ac8606Spatrick   if (!FileContent) {
704a9ac8606Spatrick     PreviousParsingResult = index_error_code::invocation_list_file_not_found;
705a9ac8606Spatrick     return llvm::make_error<IndexError>(PreviousParsingResult);
706a9ac8606Spatrick   }
707ec727ea7Spatrick   std::unique_ptr<llvm::MemoryBuffer> ContentBuffer = std::move(*FileContent);
708ec727ea7Spatrick   assert(ContentBuffer && "If no error was produced after loading, the pointer "
709ec727ea7Spatrick                           "should not be nullptr.");
710ec727ea7Spatrick 
711ec727ea7Spatrick   llvm::Expected<InvocationListTy> ExpectedInvocationList =
712ec727ea7Spatrick       parseInvocationList(ContentBuffer->getBuffer(), PathStyle);
713ec727ea7Spatrick 
714a9ac8606Spatrick   // Handle the error to store the code for next call to this function.
715a9ac8606Spatrick   if (!ExpectedInvocationList) {
716a9ac8606Spatrick     llvm::handleAllErrors(
717a9ac8606Spatrick         ExpectedInvocationList.takeError(),
718a9ac8606Spatrick         [&](const IndexError &E) { PreviousParsingResult = E.getCode(); });
719a9ac8606Spatrick     return llvm::make_error<IndexError>(PreviousParsingResult);
720a9ac8606Spatrick   }
721ec727ea7Spatrick 
722ec727ea7Spatrick   InvocationList = *ExpectedInvocationList;
723ec727ea7Spatrick 
724ec727ea7Spatrick   return llvm::Error::success();
725ec727ea7Spatrick }
726ec727ea7Spatrick 
727e5dd7070Spatrick template <typename T>
728e5dd7070Spatrick llvm::Expected<const T *>
importDefinitionImpl(const T * D,ASTUnit * Unit)729e5dd7070Spatrick CrossTranslationUnitContext::importDefinitionImpl(const T *D, ASTUnit *Unit) {
730e5dd7070Spatrick   assert(hasBodyOrInit(D) && "Decls to be imported should have body or init.");
731e5dd7070Spatrick 
732e5dd7070Spatrick   assert(&D->getASTContext() == &Unit->getASTContext() &&
733e5dd7070Spatrick          "ASTContext of Decl and the unit should match.");
734e5dd7070Spatrick   ASTImporter &Importer = getOrCreateASTImporter(Unit);
735e5dd7070Spatrick 
736e5dd7070Spatrick   auto ToDeclOrError = Importer.Import(D);
737e5dd7070Spatrick   if (!ToDeclOrError) {
738*12c85518Srobert     handleAllErrors(ToDeclOrError.takeError(), [&](const ASTImportError &IE) {
739e5dd7070Spatrick       switch (IE.Error) {
740*12c85518Srobert       case ASTImportError::NameConflict:
741e5dd7070Spatrick         ++NumNameConflicts;
742e5dd7070Spatrick         break;
743*12c85518Srobert       case ASTImportError::UnsupportedConstruct:
744e5dd7070Spatrick         ++NumUnsupportedNodeFound;
745e5dd7070Spatrick         break;
746*12c85518Srobert       case ASTImportError::Unknown:
747e5dd7070Spatrick         llvm_unreachable("Unknown import error happened.");
748e5dd7070Spatrick         break;
749e5dd7070Spatrick       }
750e5dd7070Spatrick     });
751e5dd7070Spatrick     return llvm::make_error<IndexError>(index_error_code::failed_import);
752e5dd7070Spatrick   }
753e5dd7070Spatrick   auto *ToDecl = cast<T>(*ToDeclOrError);
754e5dd7070Spatrick   assert(hasBodyOrInit(ToDecl) && "Imported Decl should have body or init.");
755e5dd7070Spatrick   ++NumGetCTUSuccess;
756e5dd7070Spatrick 
757ec727ea7Spatrick   // Parent map is invalidated after changing the AST.
758ec727ea7Spatrick   ToDecl->getASTContext().getParentMapContext().clear();
759ec727ea7Spatrick 
760e5dd7070Spatrick   return ToDecl;
761e5dd7070Spatrick }
762e5dd7070Spatrick 
763e5dd7070Spatrick llvm::Expected<const FunctionDecl *>
importDefinition(const FunctionDecl * FD,ASTUnit * Unit)764e5dd7070Spatrick CrossTranslationUnitContext::importDefinition(const FunctionDecl *FD,
765e5dd7070Spatrick                                               ASTUnit *Unit) {
766e5dd7070Spatrick   return importDefinitionImpl(FD, Unit);
767e5dd7070Spatrick }
768e5dd7070Spatrick 
769e5dd7070Spatrick llvm::Expected<const VarDecl *>
importDefinition(const VarDecl * VD,ASTUnit * Unit)770e5dd7070Spatrick CrossTranslationUnitContext::importDefinition(const VarDecl *VD,
771e5dd7070Spatrick                                               ASTUnit *Unit) {
772e5dd7070Spatrick   return importDefinitionImpl(VD, Unit);
773e5dd7070Spatrick }
774e5dd7070Spatrick 
lazyInitImporterSharedSt(TranslationUnitDecl * ToTU)775e5dd7070Spatrick void CrossTranslationUnitContext::lazyInitImporterSharedSt(
776e5dd7070Spatrick     TranslationUnitDecl *ToTU) {
777e5dd7070Spatrick   if (!ImporterSharedSt)
778e5dd7070Spatrick     ImporterSharedSt = std::make_shared<ASTImporterSharedState>(*ToTU);
779e5dd7070Spatrick }
780e5dd7070Spatrick 
781e5dd7070Spatrick ASTImporter &
getOrCreateASTImporter(ASTUnit * Unit)782e5dd7070Spatrick CrossTranslationUnitContext::getOrCreateASTImporter(ASTUnit *Unit) {
783e5dd7070Spatrick   ASTContext &From = Unit->getASTContext();
784e5dd7070Spatrick 
785e5dd7070Spatrick   auto I = ASTUnitImporterMap.find(From.getTranslationUnitDecl());
786e5dd7070Spatrick   if (I != ASTUnitImporterMap.end())
787e5dd7070Spatrick     return *I->second;
788e5dd7070Spatrick   lazyInitImporterSharedSt(Context.getTranslationUnitDecl());
789e5dd7070Spatrick   ASTImporter *NewImporter = new ASTImporter(
790e5dd7070Spatrick       Context, Context.getSourceManager().getFileManager(), From,
791e5dd7070Spatrick       From.getSourceManager().getFileManager(), false, ImporterSharedSt);
792e5dd7070Spatrick   ASTUnitImporterMap[From.getTranslationUnitDecl()].reset(NewImporter);
793e5dd7070Spatrick   return *NewImporter;
794e5dd7070Spatrick }
795e5dd7070Spatrick 
796*12c85518Srobert std::optional<clang::MacroExpansionContext>
getMacroExpansionContextForSourceLocation(const clang::SourceLocation & ToLoc) const797a9ac8606Spatrick CrossTranslationUnitContext::getMacroExpansionContextForSourceLocation(
798e5dd7070Spatrick     const clang::SourceLocation &ToLoc) const {
799a9ac8606Spatrick   // FIXME: Implement: Record such a context for every imported ASTUnit; lookup.
800*12c85518Srobert   return std::nullopt;
801*12c85518Srobert }
802*12c85518Srobert 
isImportedAsNew(const Decl * ToDecl) const803*12c85518Srobert bool CrossTranslationUnitContext::isImportedAsNew(const Decl *ToDecl) const {
804*12c85518Srobert   if (!ImporterSharedSt)
805*12c85518Srobert     return false;
806*12c85518Srobert   return ImporterSharedSt->isNewDecl(const_cast<Decl *>(ToDecl));
807*12c85518Srobert }
808*12c85518Srobert 
hasError(const Decl * ToDecl) const809*12c85518Srobert bool CrossTranslationUnitContext::hasError(const Decl *ToDecl) const {
810*12c85518Srobert   if (!ImporterSharedSt)
811*12c85518Srobert     return false;
812*12c85518Srobert   return static_cast<bool>(
813*12c85518Srobert       ImporterSharedSt->getImportDeclErrorIfAny(const_cast<Decl *>(ToDecl)));
814e5dd7070Spatrick }
815e5dd7070Spatrick 
816e5dd7070Spatrick } // namespace cross_tu
817e5dd7070Spatrick } // namespace clang
818