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