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