ExternalASTMerger.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548
  1. //===- ExternalASTMerger.cpp - Merging External AST Interface ---*- 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 ExternalASTMerger, which vends a combination of
  10. // ASTs from several different ASTContext/FileManager pairs
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "clang/AST/ASTContext.h"
  14. #include "clang/AST/Decl.h"
  15. #include "clang/AST/DeclCXX.h"
  16. #include "clang/AST/DeclObjC.h"
  17. #include "clang/AST/DeclTemplate.h"
  18. #include "clang/AST/ExternalASTMerger.h"
  19. using namespace clang;
  20. namespace {
  21. template <typename T> struct Source {
  22. T t;
  23. Source(T t) : t(t) {}
  24. operator T() { return t; }
  25. template <typename U = T> U &get() { return t; }
  26. template <typename U = T> const U &get() const { return t; }
  27. template <typename U> operator Source<U>() { return Source<U>(t); }
  28. };
  29. typedef std::pair<Source<NamedDecl *>, ASTImporter *> Candidate;
  30. /// For the given DC, return the DC that is safe to perform lookups on. This is
  31. /// the DC we actually want to work with most of the time.
  32. const DeclContext *CanonicalizeDC(const DeclContext *DC) {
  33. if (isa<LinkageSpecDecl>(DC))
  34. return DC->getRedeclContext();
  35. return DC;
  36. }
  37. Source<const DeclContext *>
  38. LookupSameContext(Source<TranslationUnitDecl *> SourceTU, const DeclContext *DC,
  39. ASTImporter &ReverseImporter) {
  40. DC = CanonicalizeDC(DC);
  41. if (DC->isTranslationUnit()) {
  42. return SourceTU;
  43. }
  44. Source<const DeclContext *> SourceParentDC =
  45. LookupSameContext(SourceTU, DC->getParent(), ReverseImporter);
  46. if (!SourceParentDC) {
  47. // If we couldn't find the parent DC in this TranslationUnit, give up.
  48. return nullptr;
  49. }
  50. auto *ND = cast<NamedDecl>(DC);
  51. DeclarationName Name = ND->getDeclName();
  52. auto SourceNameOrErr = ReverseImporter.Import(Name);
  53. if (!SourceNameOrErr) {
  54. llvm::consumeError(SourceNameOrErr.takeError());
  55. return nullptr;
  56. }
  57. Source<DeclarationName> SourceName = *SourceNameOrErr;
  58. DeclContext::lookup_result SearchResult =
  59. SourceParentDC.get()->lookup(SourceName.get());
  60. size_t SearchResultSize = SearchResult.size();
  61. if (SearchResultSize == 0 || SearchResultSize > 1) {
  62. // There are two cases here. First, we might not find the name.
  63. // We might also find multiple copies, in which case we have no
  64. // guarantee that the one we wanted is the one we pick. (E.g.,
  65. // if we have two specializations of the same template it is
  66. // very hard to determine which is the one you want.)
  67. //
  68. // The Origins map fixes this problem by allowing the origin to be
  69. // explicitly recorded, so we trigger that recording by returning
  70. // nothing (rather than a possibly-inaccurate guess) here.
  71. return nullptr;
  72. } else {
  73. NamedDecl *SearchResultDecl = SearchResult[0];
  74. if (isa<DeclContext>(SearchResultDecl) &&
  75. SearchResultDecl->getKind() == DC->getDeclKind())
  76. return cast<DeclContext>(SearchResultDecl)->getPrimaryContext();
  77. return nullptr; // This type of lookup is unsupported
  78. }
  79. }
  80. /// A custom implementation of ASTImporter, for ExternalASTMerger's purposes.
  81. ///
  82. /// There are several modifications:
  83. ///
  84. /// - It enables lazy lookup (via the HasExternalLexicalStorage flag and a few
  85. /// others), which instructs Clang to refer to ExternalASTMerger. Also, it
  86. /// forces MinimalImport to true, which is necessary to make this work.
  87. /// - It maintains a reverse importer for use with names. This allows lookup of
  88. /// arbitrary names in the source context.
  89. /// - It updates the ExternalASTMerger's origin map as needed whenever a
  90. /// it sees a DeclContext.
  91. class LazyASTImporter : public ASTImporter {
  92. private:
  93. ExternalASTMerger &Parent;
  94. ASTImporter Reverse;
  95. const ExternalASTMerger::OriginMap &FromOrigins;
  96. /// @see ExternalASTMerger::ImporterSource::Temporary
  97. bool TemporarySource;
  98. /// Map of imported declarations back to the declarations they originated
  99. /// from.
  100. llvm::DenseMap<Decl *, Decl *> ToOrigin;
  101. /// @see ExternalASTMerger::ImporterSource::Merger
  102. ExternalASTMerger *SourceMerger;
  103. llvm::raw_ostream &logs() { return Parent.logs(); }
  104. public:
  105. LazyASTImporter(ExternalASTMerger &_Parent, ASTContext &ToContext,
  106. FileManager &ToFileManager,
  107. const ExternalASTMerger::ImporterSource &S,
  108. std::shared_ptr<ASTImporterSharedState> SharedState)
  109. : ASTImporter(ToContext, ToFileManager, S.getASTContext(),
  110. S.getFileManager(),
  111. /*MinimalImport=*/true, SharedState),
  112. Parent(_Parent),
  113. Reverse(S.getASTContext(), S.getFileManager(), ToContext, ToFileManager,
  114. /*MinimalImport=*/true),
  115. FromOrigins(S.getOriginMap()), TemporarySource(S.isTemporary()),
  116. SourceMerger(S.getMerger()) {}
  117. llvm::Expected<Decl *> ImportImpl(Decl *FromD) override {
  118. if (!TemporarySource || !SourceMerger)
  119. return ASTImporter::ImportImpl(FromD);
  120. // If we get here, then this source is importing from a temporary ASTContext
  121. // that also has another ExternalASTMerger attached. It could be
  122. // possible that the current ExternalASTMerger and the temporary ASTContext
  123. // share a common ImporterSource, which means that the temporary
  124. // AST could contain declarations that were imported from a source
  125. // that this ExternalASTMerger can access directly. Instead of importing
  126. // such declarations from the temporary ASTContext, they should instead
  127. // be directly imported by this ExternalASTMerger from the original
  128. // source. This way the ExternalASTMerger can safely do a minimal import
  129. // without creating incomplete declarations originated from a temporary
  130. // ASTContext. If we would try to complete such declarations later on, we
  131. // would fail to do so as their temporary AST could be deleted (which means
  132. // that the missing parts of the minimally imported declaration in that
  133. // ASTContext were also deleted).
  134. //
  135. // The following code tracks back any declaration that needs to be
  136. // imported from the temporary ASTContext to a persistent ASTContext.
  137. // Then the ExternalASTMerger tries to import from the persistent
  138. // ASTContext directly by using the associated ASTImporter. If that
  139. // succeeds, this ASTImporter just maps the declarations imported by
  140. // the other (persistent) ASTImporter to this (temporary) ASTImporter.
  141. // The steps can be visualized like this:
  142. //
  143. // Target AST <--- 3. Indirect import --- Persistent AST
  144. // ^ of persistent decl ^
  145. // | |
  146. // 1. Current import 2. Tracking back to persistent decl
  147. // 4. Map persistent decl |
  148. // & pretend we imported. |
  149. // | |
  150. // Temporary AST -------------------------------'
  151. // First, ask the ExternalASTMerger of the source where the temporary
  152. // declaration originated from.
  153. Decl *Persistent = SourceMerger->FindOriginalDecl(FromD);
  154. // FromD isn't from a persistent AST, so just do a normal import.
  155. if (!Persistent)
  156. return ASTImporter::ImportImpl(FromD);
  157. // Now ask the current ExternalASTMerger to try import the persistent
  158. // declaration into the target.
  159. ASTContext &PersistentCtx = Persistent->getASTContext();
  160. ASTImporter &OtherImporter = Parent.ImporterForOrigin(PersistentCtx);
  161. // Check that we never end up in the current Importer again.
  162. assert((&PersistentCtx != &getFromContext()) && (&OtherImporter != this) &&
  163. "Delegated to same Importer?");
  164. auto DeclOrErr = OtherImporter.Import(Persistent);
  165. // Errors when importing the persistent decl are treated as if we
  166. // had errors with importing the temporary decl.
  167. if (!DeclOrErr)
  168. return DeclOrErr.takeError();
  169. Decl *D = *DeclOrErr;
  170. // Tell the current ASTImporter that this has already been imported
  171. // to prevent any further queries for the temporary decl.
  172. MapImported(FromD, D);
  173. return D;
  174. }
  175. /// Implements the ASTImporter interface for tracking back a declaration
  176. /// to its original declaration it came from.
  177. Decl *GetOriginalDecl(Decl *To) override {
  178. auto It = ToOrigin.find(To);
  179. if (It != ToOrigin.end())
  180. return It->second;
  181. return nullptr;
  182. }
  183. /// Whenever a DeclContext is imported, ensure that ExternalASTSource's origin
  184. /// map is kept up to date. Also set the appropriate flags.
  185. void Imported(Decl *From, Decl *To) override {
  186. ToOrigin[To] = From;
  187. if (auto *ToDC = dyn_cast<DeclContext>(To)) {
  188. const bool LoggingEnabled = Parent.LoggingEnabled();
  189. if (LoggingEnabled)
  190. logs() << "(ExternalASTMerger*)" << (void*)&Parent
  191. << " imported (DeclContext*)" << (void*)ToDC
  192. << ", (ASTContext*)" << (void*)&getToContext()
  193. << " from (DeclContext*)" << (void*)llvm::cast<DeclContext>(From)
  194. << ", (ASTContext*)" << (void*)&getFromContext()
  195. << "\n";
  196. Source<DeclContext *> FromDC(
  197. cast<DeclContext>(From)->getPrimaryContext());
  198. if (FromOrigins.count(FromDC) &&
  199. Parent.HasImporterForOrigin(*FromOrigins.at(FromDC).AST)) {
  200. if (LoggingEnabled)
  201. logs() << "(ExternalASTMerger*)" << (void*)&Parent
  202. << " forced origin (DeclContext*)"
  203. << (void*)FromOrigins.at(FromDC).DC
  204. << ", (ASTContext*)"
  205. << (void*)FromOrigins.at(FromDC).AST
  206. << "\n";
  207. Parent.ForceRecordOrigin(ToDC, FromOrigins.at(FromDC));
  208. } else {
  209. if (LoggingEnabled)
  210. logs() << "(ExternalASTMerger*)" << (void*)&Parent
  211. << " maybe recording origin (DeclContext*)" << (void*)FromDC
  212. << ", (ASTContext*)" << (void*)&getFromContext()
  213. << "\n";
  214. Parent.MaybeRecordOrigin(ToDC, {FromDC, &getFromContext()});
  215. }
  216. }
  217. if (auto *ToTag = dyn_cast<TagDecl>(To)) {
  218. ToTag->setHasExternalLexicalStorage();
  219. ToTag->getPrimaryContext()->setMustBuildLookupTable();
  220. assert(Parent.CanComplete(ToTag));
  221. } else if (auto *ToNamespace = dyn_cast<NamespaceDecl>(To)) {
  222. ToNamespace->setHasExternalVisibleStorage();
  223. assert(Parent.CanComplete(ToNamespace));
  224. } else if (auto *ToContainer = dyn_cast<ObjCContainerDecl>(To)) {
  225. ToContainer->setHasExternalLexicalStorage();
  226. ToContainer->getPrimaryContext()->setMustBuildLookupTable();
  227. assert(Parent.CanComplete(ToContainer));
  228. }
  229. }
  230. ASTImporter &GetReverse() { return Reverse; }
  231. };
  232. bool HasDeclOfSameType(llvm::ArrayRef<Candidate> Decls, const Candidate &C) {
  233. if (isa<FunctionDecl>(C.first.get()))
  234. return false;
  235. return llvm::any_of(Decls, [&](const Candidate &D) {
  236. return C.first.get()->getKind() == D.first.get()->getKind();
  237. });
  238. }
  239. } // end namespace
  240. ASTImporter &ExternalASTMerger::ImporterForOrigin(ASTContext &OriginContext) {
  241. for (const std::unique_ptr<ASTImporter> &I : Importers)
  242. if (&I->getFromContext() == &OriginContext)
  243. return *I;
  244. llvm_unreachable("We should have an importer for this origin!");
  245. }
  246. namespace {
  247. LazyASTImporter &LazyImporterForOrigin(ExternalASTMerger &Merger,
  248. ASTContext &OriginContext) {
  249. return static_cast<LazyASTImporter &>(
  250. Merger.ImporterForOrigin(OriginContext));
  251. }
  252. }
  253. bool ExternalASTMerger::HasImporterForOrigin(ASTContext &OriginContext) {
  254. for (const std::unique_ptr<ASTImporter> &I : Importers)
  255. if (&I->getFromContext() == &OriginContext)
  256. return true;
  257. return false;
  258. }
  259. template <typename CallbackType>
  260. void ExternalASTMerger::ForEachMatchingDC(const DeclContext *DC,
  261. CallbackType Callback) {
  262. if (Origins.count(DC)) {
  263. ExternalASTMerger::DCOrigin Origin = Origins[DC];
  264. LazyASTImporter &Importer = LazyImporterForOrigin(*this, *Origin.AST);
  265. Callback(Importer, Importer.GetReverse(), Origin.DC);
  266. } else {
  267. bool DidCallback = false;
  268. for (const std::unique_ptr<ASTImporter> &Importer : Importers) {
  269. Source<TranslationUnitDecl *> SourceTU =
  270. Importer->getFromContext().getTranslationUnitDecl();
  271. ASTImporter &Reverse =
  272. static_cast<LazyASTImporter *>(Importer.get())->GetReverse();
  273. if (auto SourceDC = LookupSameContext(SourceTU, DC, Reverse)) {
  274. DidCallback = true;
  275. if (Callback(*Importer, Reverse, SourceDC))
  276. break;
  277. }
  278. }
  279. if (!DidCallback && LoggingEnabled())
  280. logs() << "(ExternalASTMerger*)" << (void*)this
  281. << " asserting for (DeclContext*)" << (const void*)DC
  282. << ", (ASTContext*)" << (void*)&Target.AST
  283. << "\n";
  284. assert(DidCallback && "Couldn't find a source context matching our DC");
  285. }
  286. }
  287. void ExternalASTMerger::CompleteType(TagDecl *Tag) {
  288. assert(Tag->hasExternalLexicalStorage());
  289. ForEachMatchingDC(Tag, [&](ASTImporter &Forward, ASTImporter &Reverse,
  290. Source<const DeclContext *> SourceDC) -> bool {
  291. auto *SourceTag = const_cast<TagDecl *>(cast<TagDecl>(SourceDC.get()));
  292. if (SourceTag->hasExternalLexicalStorage())
  293. SourceTag->getASTContext().getExternalSource()->CompleteType(SourceTag);
  294. if (!SourceTag->getDefinition())
  295. return false;
  296. Forward.MapImported(SourceTag, Tag);
  297. if (llvm::Error Err = Forward.ImportDefinition(SourceTag))
  298. llvm::consumeError(std::move(Err));
  299. Tag->setCompleteDefinition(SourceTag->isCompleteDefinition());
  300. return true;
  301. });
  302. }
  303. void ExternalASTMerger::CompleteType(ObjCInterfaceDecl *Interface) {
  304. assert(Interface->hasExternalLexicalStorage());
  305. ForEachMatchingDC(
  306. Interface, [&](ASTImporter &Forward, ASTImporter &Reverse,
  307. Source<const DeclContext *> SourceDC) -> bool {
  308. auto *SourceInterface = const_cast<ObjCInterfaceDecl *>(
  309. cast<ObjCInterfaceDecl>(SourceDC.get()));
  310. if (SourceInterface->hasExternalLexicalStorage())
  311. SourceInterface->getASTContext().getExternalSource()->CompleteType(
  312. SourceInterface);
  313. if (!SourceInterface->getDefinition())
  314. return false;
  315. Forward.MapImported(SourceInterface, Interface);
  316. if (llvm::Error Err = Forward.ImportDefinition(SourceInterface))
  317. llvm::consumeError(std::move(Err));
  318. return true;
  319. });
  320. }
  321. bool ExternalASTMerger::CanComplete(DeclContext *Interface) {
  322. assert(Interface->hasExternalLexicalStorage() ||
  323. Interface->hasExternalVisibleStorage());
  324. bool FoundMatchingDC = false;
  325. ForEachMatchingDC(Interface,
  326. [&](ASTImporter &Forward, ASTImporter &Reverse,
  327. Source<const DeclContext *> SourceDC) -> bool {
  328. FoundMatchingDC = true;
  329. return true;
  330. });
  331. return FoundMatchingDC;
  332. }
  333. namespace {
  334. bool IsSameDC(const DeclContext *D1, const DeclContext *D2) {
  335. if (isa<ObjCContainerDecl>(D1) && isa<ObjCContainerDecl>(D2))
  336. return true; // There are many cases where Objective-C is ambiguous.
  337. if (auto *T1 = dyn_cast<TagDecl>(D1))
  338. if (auto *T2 = dyn_cast<TagDecl>(D2))
  339. if (T1->getFirstDecl() == T2->getFirstDecl())
  340. return true;
  341. return D1 == D2 || D1 == CanonicalizeDC(D2);
  342. }
  343. }
  344. void ExternalASTMerger::MaybeRecordOrigin(const DeclContext *ToDC,
  345. DCOrigin Origin) {
  346. LazyASTImporter &Importer = LazyImporterForOrigin(*this, *Origin.AST);
  347. ASTImporter &Reverse = Importer.GetReverse();
  348. Source<const DeclContext *> FoundFromDC =
  349. LookupSameContext(Origin.AST->getTranslationUnitDecl(), ToDC, Reverse);
  350. const bool DoRecord = !FoundFromDC || !IsSameDC(FoundFromDC.get(), Origin.DC);
  351. if (DoRecord)
  352. RecordOriginImpl(ToDC, Origin, Importer);
  353. if (LoggingEnabled())
  354. logs() << "(ExternalASTMerger*)" << (void*)this
  355. << (DoRecord ? " decided " : " decided NOT")
  356. << " to record origin (DeclContext*)" << (void*)Origin.DC
  357. << ", (ASTContext*)" << (void*)&Origin.AST
  358. << "\n";
  359. }
  360. void ExternalASTMerger::ForceRecordOrigin(const DeclContext *ToDC,
  361. DCOrigin Origin) {
  362. RecordOriginImpl(ToDC, Origin, ImporterForOrigin(*Origin.AST));
  363. }
  364. void ExternalASTMerger::RecordOriginImpl(const DeclContext *ToDC, DCOrigin Origin,
  365. ASTImporter &Importer) {
  366. Origins[ToDC] = Origin;
  367. Importer.ASTImporter::MapImported(cast<Decl>(Origin.DC), const_cast<Decl*>(cast<Decl>(ToDC)));
  368. }
  369. ExternalASTMerger::ExternalASTMerger(const ImporterTarget &Target,
  370. llvm::ArrayRef<ImporterSource> Sources) : LogStream(&llvm::nulls()), Target(Target) {
  371. SharedState = std::make_shared<ASTImporterSharedState>(
  372. *Target.AST.getTranslationUnitDecl());
  373. AddSources(Sources);
  374. }
  375. Decl *ExternalASTMerger::FindOriginalDecl(Decl *D) {
  376. assert(&D->getASTContext() == &Target.AST);
  377. for (const auto &I : Importers)
  378. if (auto Result = I->GetOriginalDecl(D))
  379. return Result;
  380. return nullptr;
  381. }
  382. void ExternalASTMerger::AddSources(llvm::ArrayRef<ImporterSource> Sources) {
  383. for (const ImporterSource &S : Sources) {
  384. assert(&S.getASTContext() != &Target.AST);
  385. // Check that the associated merger actually imports into the source AST.
  386. assert(!S.getMerger() || &S.getMerger()->Target.AST == &S.getASTContext());
  387. Importers.push_back(std::make_unique<LazyASTImporter>(
  388. *this, Target.AST, Target.FM, S, SharedState));
  389. }
  390. }
  391. void ExternalASTMerger::RemoveSources(llvm::ArrayRef<ImporterSource> Sources) {
  392. if (LoggingEnabled())
  393. for (const ImporterSource &S : Sources)
  394. logs() << "(ExternalASTMerger*)" << (void *)this
  395. << " removing source (ASTContext*)" << (void *)&S.getASTContext()
  396. << "\n";
  397. Importers.erase(
  398. std::remove_if(Importers.begin(), Importers.end(),
  399. [&Sources](std::unique_ptr<ASTImporter> &Importer) -> bool {
  400. for (const ImporterSource &S : Sources) {
  401. if (&Importer->getFromContext() == &S.getASTContext())
  402. return true;
  403. }
  404. return false;
  405. }),
  406. Importers.end());
  407. for (OriginMap::iterator OI = Origins.begin(), OE = Origins.end(); OI != OE; ) {
  408. std::pair<const DeclContext *, DCOrigin> Origin = *OI;
  409. bool Erase = false;
  410. for (const ImporterSource &S : Sources) {
  411. if (&S.getASTContext() == Origin.second.AST) {
  412. Erase = true;
  413. break;
  414. }
  415. }
  416. if (Erase)
  417. OI = Origins.erase(OI);
  418. else
  419. ++OI;
  420. }
  421. }
  422. template <typename DeclTy>
  423. static bool importSpecializations(DeclTy *D, ASTImporter *Importer) {
  424. for (auto *Spec : D->specializations()) {
  425. auto ImportedSpecOrError = Importer->Import(Spec);
  426. if (!ImportedSpecOrError) {
  427. llvm::consumeError(ImportedSpecOrError.takeError());
  428. return true;
  429. }
  430. }
  431. return false;
  432. }
  433. /// Imports specializations from template declarations that can be specialized.
  434. static bool importSpecializationsIfNeeded(Decl *D, ASTImporter *Importer) {
  435. if (!isa<TemplateDecl>(D))
  436. return false;
  437. if (auto *FunctionTD = dyn_cast<FunctionTemplateDecl>(D))
  438. return importSpecializations(FunctionTD, Importer);
  439. else if (auto *ClassTD = dyn_cast<ClassTemplateDecl>(D))
  440. return importSpecializations(ClassTD, Importer);
  441. else if (auto *VarTD = dyn_cast<VarTemplateDecl>(D))
  442. return importSpecializations(VarTD, Importer);
  443. return false;
  444. }
  445. bool ExternalASTMerger::FindExternalVisibleDeclsByName(const DeclContext *DC,
  446. DeclarationName Name) {
  447. llvm::SmallVector<NamedDecl *, 1> Decls;
  448. llvm::SmallVector<Candidate, 4> Candidates;
  449. auto FilterFoundDecl = [&Candidates](const Candidate &C) {
  450. if (!HasDeclOfSameType(Candidates, C))
  451. Candidates.push_back(C);
  452. };
  453. ForEachMatchingDC(DC,
  454. [&](ASTImporter &Forward, ASTImporter &Reverse,
  455. Source<const DeclContext *> SourceDC) -> bool {
  456. auto FromNameOrErr = Reverse.Import(Name);
  457. if (!FromNameOrErr) {
  458. llvm::consumeError(FromNameOrErr.takeError());
  459. return false;
  460. }
  461. DeclContextLookupResult Result =
  462. SourceDC.get()->lookup(*FromNameOrErr);
  463. for (NamedDecl *FromD : Result) {
  464. FilterFoundDecl(std::make_pair(FromD, &Forward));
  465. }
  466. return false;
  467. });
  468. if (Candidates.empty())
  469. return false;
  470. Decls.reserve(Candidates.size());
  471. for (const Candidate &C : Candidates) {
  472. Decl *LookupRes = C.first.get();
  473. ASTImporter *Importer = C.second;
  474. auto NDOrErr = Importer->Import(LookupRes);
  475. assert(NDOrErr);
  476. (void)static_cast<bool>(NDOrErr);
  477. NamedDecl *ND = cast_or_null<NamedDecl>(*NDOrErr);
  478. assert(ND);
  479. // If we don't import specialization, they are not available via lookup
  480. // because the lookup result is imported TemplateDecl and it does not
  481. // reference its specializations until they are imported explicitly.
  482. bool IsSpecImportFailed =
  483. importSpecializationsIfNeeded(LookupRes, Importer);
  484. assert(!IsSpecImportFailed);
  485. (void)IsSpecImportFailed;
  486. Decls.push_back(ND);
  487. }
  488. SetExternalVisibleDeclsForName(DC, Name, Decls);
  489. return true;
  490. }
  491. void ExternalASTMerger::FindExternalLexicalDecls(
  492. const DeclContext *DC, llvm::function_ref<bool(Decl::Kind)> IsKindWeWant,
  493. SmallVectorImpl<Decl *> &Result) {
  494. ForEachMatchingDC(DC, [&](ASTImporter &Forward, ASTImporter &Reverse,
  495. Source<const DeclContext *> SourceDC) -> bool {
  496. for (const Decl *SourceDecl : SourceDC.get()->decls()) {
  497. if (IsKindWeWant(SourceDecl->getKind())) {
  498. auto ImportedDeclOrErr = Forward.Import(SourceDecl);
  499. if (ImportedDeclOrErr)
  500. assert(!(*ImportedDeclOrErr) ||
  501. IsSameDC((*ImportedDeclOrErr)->getDeclContext(), DC));
  502. else
  503. llvm::consumeError(ImportedDeclOrErr.takeError());
  504. }
  505. }
  506. return false;
  507. });
  508. }